Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: update quantity in plan when invite is accepted
Brad Barbin859683af01e8
diff --git a/.env.example b/.env.exampleindex 1aafbd6ad6..f742fc553c 100644--- a/.env.example+++ b/.env.example@@ -13,12 +13,16 @@ SLACK_BOT_TOKEN="***********************"SESSION_SECRET="************************"STRIPE_SECRET_KEY="sk_test_*************"-STRIP_WEBHOOK_SECRET="whsec_************"+STRIPE_WEBHOOK_SECRET="whsec_************"SUPABASE_ANON_KEY="******************"SUPABASE_SERVICE_ROLE_KEY="*****************"SUPABASE_URL="http://localhost:54321"+SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID="************.apps.googleusercontent.com"+SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_SECRET="GOCSPX-****************************"+SUPABASE_AUTH_EXTERNAL_GOOGLE_REDIRECT_URI="http://127.0.0.1:54321/auth/v1/callback"+TRIGGER_ID="****************************"TRIGGER_API_KEY="***********************"TRIGGER_API_URL="https://api.trigger.dev"diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.tsindex eafe912db8..0150d9a37e 100644--- a/apps/erp/app/modules/users/users.server.ts+++ b/apps/erp/app/modules/users/users.server.ts@@ -9,6 +9,7 @@ import {import type { Database, Json } from "@carbon/database";import { redis } from "@carbon/kv";+import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";import type { SupabaseClient } from "@supabase/supabase-js";import { redirect } from "@vercel/remix";import { getSupplierContact } from "~/modules/purchasing";@@ -112,6 +113,8 @@ export async function acceptInvite(return setPermissions;}+ await updateSubscriptionQuantityForCompany(invite.data.companyId);+return serviceRole.from("invite").update({ acceptedAt: new Date().toISOString() })diff --git a/apps/erp/app/routes/onboarding+/plan.tsx b/apps/erp/app/routes/onboarding+/plan.tsxindex f46ca9b596..f33eeb2d36 100644--- a/apps/erp/app/routes/onboarding+/plan.tsx+++ b/apps/erp/app/routes/onboarding+/plan.tsx@@ -75,7 +75,7 @@ export async function action({ request }: ActionFunctionArgs) {throw new Error("Plan ID is required");}- if (!(planId in PLANS) || planId === "PARTNER") {+ if (!(planId in PLANS) || planId.startsWith("PARTNER")) {throw new Error("Invalid plan ID");}diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex a02dea14e4..ff324a75a8 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -100,8 +100,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const company = companies.data?.find((c) => c.companyId === companyId);const requiresOnboarding =- !companies.data?.[0]?.name ||- (CarbonEdition === Edition.Cloud && !stripeCustomer);+ !company?.name || (CarbonEdition === Edition.Cloud && !stripeCustomer);if (requiresOnboarding) {throw redirect(path.to.onboarding.root);}@@ -157,7 +156,7 @@ export default function AuthenticatedRoute() {<RealtimeDataProvider><TooltipProvider><div className="flex flex-col h-screen">- {user?.acknowledgedUniversity ? null : <UniversityBanner />}+ {/* {user?.acknowledgedUniversity ? null : <UniversityBanner />} */}<Topbar /><div className="flex flex-1 h-[calc(100vh-49px)] relative"><PrimaryNavigation />diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.tsindex 066c6a557e..538e3dd9aa 100644--- a/packages/auth/src/config/env.ts+++ b/packages/auth/src/config/env.ts@@ -27,6 +27,7 @@ declare global {SESSION_ERROR_KEY: string;STRIPE_SECRET_KEY: string;STRIPE_WEBHOOK_SECRET: string;+ STRIPE_BYPASS_COMPANY_IDS: string;SUPABASE_ANON_KEY: string;SUPABASE_URL: string;SUPABASE_SERVICE_ROLE_KEY: string;@@ -114,6 +115,9 @@ export const STRIPE_SECRET_KEY = getEnv("STRIPE_SECRET_KEY", {export const STRIPE_WEBHOOK_SECRET = getEnv("STRIPE_WEBHOOK_SECRET", {isRequired: false,});+export const STRIPE_BYPASS_COMPANY_IDS = getEnv("STRIPE_BYPASS_COMPANY_IDS", {+ isRequired: false,+});export const UPSTASH_REDIS_REST_URL = getEnv("UPSTASH_REDIS_REST_URL", {isRequired: false,});diff --git a/packages/database/src/seed/stripe.ts b/packages/database/src/seed/stripe.tsindex 2d77e54f0e..d21dc07d93 100644--- a/packages/database/src/seed/stripe.ts+++ b/packages/database/src/seed/stripe.ts@@ -7,7 +7,7 @@ export const devPrices = {stripePriceId: "price_1RgZtlFV6ecOa0Xv30ClxYOe",name: "Business - Test Mode",},- PARTNER: {+ "PARTNER-400": {stripePriceId: "price_1RgZuKFV6ecOa0Xvv0RpaJUr",name: "Design Partner - Test Mode",},diff --git a/packages/database/supabase/migrations/20250619100940_billing.sql b/packages/database/supabase/migrations/20250619100940_billing.sqlindex bfb6eb99f7..4a126a4c66 100644--- a/packages/database/supabase/migrations/20250619100940_billing.sql+++ b/packages/database/supabase/migrations/20250619100940_billing.sql@@ -96,9 +96,11 @@ CREATE POLICY "SELECT" ON "plan"INSERT INTO "plan" ("id", "name", "userBasedPricing", "stripePriceId", "tasksLimit", "aiTokensLimit", "stripeTrialPeriodDays", "public") VALUES- ('STARTER', 'Cloud Starter', TRUE, 'price_1RgUYhFV6ecOa0XvD37hQOhK', 10000, 1000000, 14, TRUE),- ('BUSINESS', 'Cloud Business', TRUE, 'price_1RgUZ3FV6ecOa0XvQFLFQsX4', 10000, 1000000, 14, TRUE),- ('PARTNER', 'Design Partner', FALSE, 'price_1RgXMSFV6ecOa0XvLQtlhQr0', 10000, 1000000, 14, FALSE);+ ('STARTER', 'Cloud Starter', TRUE, 'price_1RgUYhFV6ecOa0XvD37hQOhK', 10000, 1000000, 30, TRUE),+ ('BUSINESS', 'Cloud Business', TRUE, 'price_1RgUZ3FV6ecOa0XvQFLFQsX4', 10000, 1000000, 30, TRUE),+ ('PARTNER-400', 'Design Partner', FALSE, 'price_1RgXMSFV6ecOa0XvLQtlhQr0', 10000, 1000000, 30, FALSE),+ ('PARTNER-300', 'Design Partner', FALSE, 'price_1Rj20jFV6ecOa0Xvk4WV6b7l', 10000, 1000000, 30, FALSE),+ ('PARTNER-500', 'Design Partner', FALSE, 'price_1Rj21OFV6ecOa0XvCTdELYdv', 10000, 1000000, 30, FALSE);CREATE TABLE "companyPlan" ("id" TEXT NOT NULL DEFAULT xid(),diff --git a/packages/documents/src/email/components/Logo.tsx b/packages/documents/src/email/components/Logo.tsxindex 5d7d4fc17a..eb84d13bc1 100644--- a/packages/documents/src/email/components/Logo.tsx+++ b/packages/documents/src/email/components/Logo.tsx@@ -4,7 +4,7 @@ export function Logo() {return (<Section className="mt-[32px]"><Img- src="https://app.carbonos.dev/carbon-word-light.svg"+ src="https://app.carbonos.dev/carbon-word-light.png"width="auto"height="45"alt="Carbon"diff --git a/packages/stripe/src/stripe.server.ts b/packages/stripe/src/stripe.server.tsindex 06019ce9e0..8533b3036d 100644--- a/packages/stripe/src/stripe.server.ts+++ b/packages/stripe/src/stripe.server.ts@@ -1,4 +1,9 @@-import { CarbonEdition, getAppUrl, getCarbonServiceRole } from "@carbon/auth";+import {+ CarbonEdition,+ getAppUrl,+ getCarbonServiceRole,+ STRIPE_BYPASS_COMPANY_IDS,+} from "@carbon/auth";import type { Database } from "@carbon/database";import { redis } from "@carbon/kv";import { Edition } from "@carbon/utils";@@ -115,6 +120,25 @@ export async function getStripeCustomerByCompanyId(companyId: string) {return null;}+ // Check if this company is in the bypass list+ if (STRIPE_BYPASS_COMPANY_IDS) {+ const bypassList = STRIPE_BYPASS_COMPANY_IDS.split(",").map((id: string) =>+ id.trim()+ );+ if (bypassList.includes(companyId)) {+ // Return a mock customer object that satisfies the expected interface+ return {+ subscriptionId: "bypass-subscription",+ status: "active" as const,+ priceId: "bypass-price",+ currentPeriodStart: Math.floor(Date.now() / 1000),+ currentPeriodEnd: Math.floor(Date.now() / 1000) + 365 * 24 * 60 * 60, // 1 year from now+ cancelAtPeriodEnd: false,+ paymentMethod: null,+ };+ }+ }+const customerId = await getStripeCustomerId(companyId);if (!customerId) {return null;@@ -185,7 +209,7 @@ export async function getCheckoutUrl({stripeCustomerId = customer.id;}- const serviceRole = await getCarbonServiceRole();+ const serviceRole = getCarbonServiceRole();const plan = await getPlanById(serviceRole, planId);const checkoutSession = await stripe.checkout.sessions.create({customer: stripeCustomerId,@@ -339,8 +363,6 @@ export async function processStripeEvent({throw new Error("Stripe webhook handler failed");}- console.log("customer.subscription.updated", customer);-try {await syncStripeDataToKV(customer);} catch (error) {@@ -356,7 +378,7 @@ export async function processStripeEvent({}try {- const serviceRole = await getCarbonServiceRole();+ const serviceRole = getCarbonServiceRole();const key = `stripe:customer:${customer}`;await Promise.all([@@ -379,7 +401,7 @@ export async function syncStripeDataToKV() {const key = `stripe:customer:${customerId}`;let companyId = companyIdFromMetadata;- const serviceRole = await getCarbonServiceRole();+ const serviceRole = getCarbonServiceRole();const subscriptions = await stripe.subscriptions.list({customer: customerId,@@ -448,7 +470,7 @@ export async function syncStripeDataToKV(const [, companyPlan] = await Promise.all([redis.set(key, subData),- upsertCompanyPlan(await getCarbonServiceRole(), companyPlanData),+ upsertCompanyPlan(getCarbonServiceRole(), companyPlanData),]);if (companyPlan.error) {@@ -506,7 +528,7 @@ export async function updateSubscriptionQuantityForCompany(companyId: string) {// Count active usersconst activeUsersResult = await serviceRole.from("userToCompany")- .select("userId", { count: "exact", head: true })+ .select("userId, ...user(email)").eq("companyId", companyId);if (activeUsersResult.error) {@@ -517,7 +539,10 @@ export async function updateSubscriptionQuantityForCompany(companyId: string) {return;}- const activeUserCount = activeUsersResult.count || 0;+ const activeUserCount =+ activeUsersResult.data?.filter(+ (user) => !(user?.email).includes("@carbonos.dev")+ ).length || 1;// Get the subscription from Stripe to find the subscription itemconst subscription = await stripe.subscriptions.retrieve(diff --git a/scripts/migrations/stripe-customer-migrations.ts b/scripts/migrations/stripe-customer-migrations.tsindex c4adfe83ba..143a1916df 100644--- a/scripts/migrations/stripe-customer-migrations.ts+++ b/scripts/migrations/stripe-customer-migrations.ts@@ -5,10 +5,12 @@ import { Redis } from "@upstash/redis";import { config } from "dotenv";import { Stripe } from "stripe";import { z } from "zod";-import { companies } from "./data/stripe-customers";+import { localCompanies, productionCompanies } from "./data/stripe-customers";config();-const PROD = true;+const PROD = false;++const companies = PROD ? productionCompanies : localCompanies;const upstashRedisRestUrl = PROD? process.env.PROD_UPSTASH_REDIS_REST_URL@@ -18,11 +20,19 @@ const upstashRedisRestToken = PROD: process.env.UPSTASH_REDIS_REST_TOKEN;if (!upstashRedisRestUrl) {- throw new Error("UPSTASH_REDIS_REST_URL is not defined");+ throw new Error(+ PROD+ ? "PROD_UPSTASH_REDIS_REST_URL is not defined"+ : "UPSTASH_REDIS_REST_URL is not defined"+ );}if (!upstashRedisRestToken) {- throw new Error("UPSTASH_REDIS_REST_TOKEN is not defined");+ throw new Error(+ PROD+ ? "PROD_UPSTASH_REDIS_REST_TOKEN is not defined"+ : "UPSTASH_REDIS_REST_TOKEN is not defined"+ );}const redis = new Redis({@@ -38,11 +48,17 @@ const supabaseServiceRoleKey = PROD: process.env.SUPABASE_SERVICE_ROLE_KEY;if (!supabaseUrl) {- throw new Error("SUPABASE_URL is not defined");+ throw new Error(+ PROD ? "PROD_SUPABASE_URL is not defined" : "SUPABASE_URL is not defined"+ );}if (!supabaseServiceRoleKey) {- throw new Error("SUPABASE_SERVICE_ROLE_KEY is not defined");+ throw new Error(+ PROD+ ? "PROD_SUPABASE_SERVICE_ROLE_KEY is not defined"+ : "SUPABASE_SERVICE_ROLE_KEY is not defined"+ );}const stripeSecretKey = PROD@@ -50,7 +66,11 @@ const stripeSecretKey = PROD: process.env.STRIPE_SECRET_KEY!;if (!stripeSecretKey) {- throw new Error("STRIPE_SECRET_KEY is not defined");+ throw new Error(+ PROD+ ? "PROD_STRIPE_SECRET_KEY is not defined"+ : "STRIPE_SECRET_KEY is not defined"+ );}const client = createClient(supabaseUrl, supabaseServiceRoleKey);@@ -86,19 +106,80 @@ const KvStripeCustomerSchema = z.object({(async () => {for await (const company of companies) {+ const companyId = company.id;+ const customerId = company.customerId;console.log(company.name);- const customerKey = `stripe:customer:${company.customerId}`;+ if (!companyId) {+ throw new Error("Company ID is required");+ }++ if (!customerId) {+ throw new Error("Customer ID is required");+ }++ const customerKey = `stripe:customer:${customerId}`;const companyKey = `stripe:company:${company.id}`;- await redis.set(companyKey, company.customerId);+ await redis.set(companyKey, customerId);- const subscription = await getSubscription(company.customerId);+ const subscription = await getSubscription(customerId);if (!subscription) {await redis.del(customerKey);return null;}- console.log(subscription.id);+ const subDataResult = KvStripeCustomerSchema.safeParse({+ subscriptionId: subscription.id,+ status: subscription.status,+ priceId: subscription.items.data[0].price.id,+ currentPeriodStart: subscription.items.data[0].current_period_start,+ currentPeriodEnd: subscription.items.data[0].current_period_end,+ cancelAtPeriodEnd: subscription.cancel_at_period_end,+ paymentMethod:+ subscription.default_payment_method &&+ typeof subscription.default_payment_method !== "string"+ ? {+ brand: subscription.default_payment_method.card?.brand ?? null,+ last4: subscription.default_payment_method.card?.last4 ?? null,+ }+ : null,+ });++ if (!subDataResult.success) {+ console.error("Failed to parse subscription data:", subDataResult.error);+ throw new Error("Failed to parse subscription data");+ }++ const subData = subDataResult.data;++ if (companyId) {+ const companyPlanData = {+ companyId,+ priceId: subData.priceId,+ status: (subData.cancelAtPeriodEnd+ ? "Canceled"+ : ["active", "trialing"].includes(subData.status)+ ? "Active"+ : "Inactive") as "Active" | "Inactive" | "Canceled",+ stripeCustomerId: customerId,+ stripeSubscriptionId: subData.subscriptionId,+ stripeSubscriptionStatus: subData.status,+ subscriptionStartDate: new Date(+ subData.currentPeriodStart * 1000+ ).toISOString(),+ };++ const [, companyPlan] = await Promise.all([+ redis.set(customerKey, subData),+ upsertCompanyPlan(client, companyPlanData),+ ]);++ if (companyPlan.error) {+ console.error("Failed to upsert company plan:", companyPlan.error);+ }+ } else {+ console.error("no company id, skipping company plan upsert");+ }}})();@@ -137,7 +218,7 @@ async function upsertCompanyPlan() {const plan = await getPlanByPriceId(client, companyPlan.priceId);if (plan.error) {- console.error("upsertCompanyPlan - plan error:", plan.error);+ console.error("failed to get plan by ", plan.error);return plan;}