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
feat: add hook for plan
Brad Barbinf1fa6cd9c11e
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex ff324a75a8..5cdd5c4996 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -118,6 +118,7 @@ export async function loader({ request }: LoaderFunctionArgs) {integrations: integrations.data ?? [],groups: groups.data,permissions: claims?.permissions,+ plan: stripeCustomer?.planId,role: claims?.role,user: user.data,savedViews: savedViews.data ?? [],diff --git a/apps/erp/app/routes/x+/settings+/company.tsx b/apps/erp/app/routes/x+/settings+/company.tsxindex 3be21e3ed5..3f02ccf692 100644--- a/apps/erp/app/routes/x+/settings+/company.tsx+++ b/apps/erp/app/routes/x+/settings+/company.tsx@@ -330,7 +330,7 @@ export default function Company() {</VStack></CardContent><CardFooter>- <Submit isDisabled={ownerId === userId}>+ <Submit withBlocker={false} isDisabled={ownerId === userId}>Transfer Ownership</Submit></CardFooter>diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 5b195ad90e..cbb693f04b 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -103,6 +103,7 @@ export async function loader({ request }: LoaderFunctionArgs) {companies: companies.data ?? [],location: storedLocations.location,locations: locations.data ?? [],+ plan: companyPlan?.planId,user: user.data,},storedLocations.updateddiff --git a/packages/remix/src/hooks/index.ts b/packages/remix/src/hooks/index.tsindex aba23a9bae..de8246b174 100644--- a/packages/remix/src/hooks/index.ts+++ b/packages/remix/src/hooks/index.ts@@ -2,6 +2,7 @@ import { useEdition } from "./useEdition";import { useMode } from "./useMode";import { useNanoStore } from "./useNanoStore";import { useOptimisticLocation } from "./useOptimisticLocation";+import { usePlan } from "./usePlan";import { useRouteData } from "./useRouteData";import { useUrlParams } from "./useUrlParams";@@ -10,6 +11,7 @@ export {useMode,useNanoStore,useOptimisticLocation,+ usePlan,useRouteData,useUrlParams,};diff --git a/packages/remix/src/hooks/usePlan.tsx b/packages/remix/src/hooks/usePlan.tsxnew file mode 100644index 0000000000..2120f8f12e--- /dev/null+++ b/packages/remix/src/hooks/usePlan.tsx@@ -0,0 +1,7 @@+import { useRouteData } from "@carbon/remix";+import { Plan } from "@carbon/utils";++export function usePlan() {+ const routeData = useRouteData<{ plan?: Plan }>("/x");+ return routeData?.plan ?? Plan.Unknown;+}diff --git a/packages/stripe/src/stripe.server.ts b/packages/stripe/src/stripe.server.tsindex 8533b3036d..cd7d1a28b4 100644--- a/packages/stripe/src/stripe.server.ts+++ b/packages/stripe/src/stripe.server.ts@@ -6,7 +6,7 @@ import {} from "@carbon/auth";import type { Database } from "@carbon/database";import { redis } from "@carbon/kv";-import { Edition } from "@carbon/utils";+import { Edition, Plan } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { tasks } from "@trigger.dev/sdk/v3";import { Stripe } from "stripe";@@ -33,6 +33,7 @@ const KvStripeCustomerSchema = z.object({z.literal("trialing"),z.literal("unpaid"),]),+ planId: z.string().nullable(),priceId: z.string(),currentPeriodStart: z.number(),currentPeriodEnd: z.number(),@@ -131,6 +132,7 @@ export async function getStripeCustomerByCompanyId(companyId: string) {subscriptionId: "bypass-subscription",status: "active" as const,priceId: "bypass-price",+ planId: Plan.Partner,currentPeriodStart: Math.floor(Date.now() / 1000),currentPeriodEnd: Math.floor(Date.now() / 1000) + 365 * 24 * 60 * 60, // 1 year from nowcancelAtPeriodEnd: false,@@ -260,36 +262,9 @@ export async function getBillingPortalRedirectUrl({async function upsertCompanyPlan(client: SupabaseClient<Database>,- companyPlan: {- companyId: string;- priceId: string;- status?: "Active" | "Inactive" | "Canceled";- stripeCustomerId?: string;- stripeSubscriptionId?: string;- subscriptionStartDate?: string;- }+ companyPlan: Database["public"]["Tables"]["companyPlan"]["Insert"]) {- const plan = await getPlanByPriceId(client, companyPlan.priceId);- if (plan.error) {- console.error("upsertCompanyPlan - plan error:", plan.error);- return plan;- }-- const companyPlanData: Database["public"]["Tables"]["companyPlan"]["Insert"] =- {- id: companyPlan.companyId,- planId: plan.data.id,- tasksLimit: plan.data.tasksLimit,- aiTokensLimit: plan.data.aiTokensLimit,- usersLimit: 10, // Default value as defined in the migration- subscriptionStartDate:- companyPlan.subscriptionStartDate || new Date().toISOString(),- stripeSubscriptionStatus: companyPlan.status,- stripeCustomerId: companyPlan.stripeCustomerId,- stripeSubscriptionId: companyPlan.stripeSubscriptionId,- };-- return client.from("companyPlan").upsert(companyPlanData);+ return client.from("companyPlan").upsert(companyPlan);}function isAllowedEventType<TEvent extends Stripe.Event>(@@ -426,10 +401,22 @@ export async function syncStripeDataToKV(}const subscription = subscriptions.data[0];+ const plan = await getPlanByPriceId(+ serviceRole,+ subscription.items.data[0].price.id+ );++ if (!plan.data) {+ console.error("Failed to get plan by price id:", plan.error);+ throw new Error(+ `Failed to get plan for price_id: ${subscription.items.data[0].price.id}`+ );+ }const subDataResult = KvStripeCustomerSchema.safeParse({subscriptionId: subscription.id,status: subscription.status,+ planId: plan.data?.id ?? null,priceId: subscription.items.data[0].price.id,currentPeriodStart: subscription.items.data[0].current_period_start,currentPeriodEnd: subscription.items.data[0].current_period_end,@@ -452,25 +439,28 @@ export async function syncStripeDataToKV(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 companyPlanData: Database["public"]["Tables"]["companyPlan"]["Insert"] =+ {+ id: companyId,+ planId: plan.data?.id ?? null,+ tasksLimit: plan.data.tasksLimit,+ aiTokensLimit: plan.data.aiTokensLimit,+ usersLimit: 10, // Default value as defined in the migration+ stripeSubscriptionStatus: (subData.cancelAtPeriodEnd+ ? "Canceled"+ : ["active", "trialing"].includes(subData.status)+ ? "Active"+ : "Inactive") as "Active" | "Inactive" | "Canceled",+ stripeCustomerId: customerId,+ stripeSubscriptionId: subData.subscriptionId,+ subscriptionStartDate: new Date(+ subData.currentPeriodStart * 1000+ ).toISOString(),+ };const [, companyPlan] = await Promise.all([redis.set(key, subData),- upsertCompanyPlan(getCarbonServiceRole(), companyPlanData),+ upsertCompanyPlan(serviceRole, companyPlanData),]);if (companyPlan.error) {diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.tsindex ab549df6f0..6d582bb773 100644--- a/packages/utils/src/types.ts+++ b/packages/utils/src/types.ts@@ -12,6 +12,13 @@ export const modeValidator = z.object({mode: z.enum(["light", "dark", "system"]),});+export enum Plan {+ Starter = "STARTER",+ Business = "BUSINESS",+ Partner = "PARTNER",+ Unknown = "UNKNOWN",+}+export type PickPartial<T, K extends keyof T> = Omit<T, K> &Partial<Pick<T, K>>;diff --git a/scripts/migrations/stripe-customer-migrations.ts b/scripts/migrations/stripe-customer-migrations.tsindex 143a1916df..2914dc2105 100644--- a/scripts/migrations/stripe-customer-migrations.ts+++ b/scripts/migrations/stripe-customer-migrations.ts@@ -93,6 +93,7 @@ const KvStripeCustomerSchema = z.object({z.literal("unpaid"),]),priceId: z.string(),+ planId: z.string().nullable(),currentPeriodStart: z.number(),currentPeriodEnd: z.number(),cancelAtPeriodEnd: z.boolean(),@@ -128,10 +129,21 @@ const KvStripeCustomerSchema = z.object({return null;}+ const plan = await getPlanByPriceId(+ client,+ subscription.items.data[0].price.id+ );++ if (plan.error) {+ console.error("Failed to get plan by price id:", plan.error);+ continue;+ }+const subDataResult = KvStripeCustomerSchema.safeParse({subscriptionId: subscription.id,status: subscription.status,priceId: subscription.items.data[0].price.id,+ planId: plan.data?.id ?? null,currentPeriodStart: subscription.items.data[0].current_period_start,currentPeriodEnd: subscription.items.data[0].current_period_end,cancelAtPeriodEnd: subscription.cancel_at_period_end,@@ -153,21 +165,24 @@ const KvStripeCustomerSchema = z.object({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 companyPlanData: Database["public"]["Tables"]["companyPlan"]["Insert"] =+ {+ id: companyId,+ planId: plan.data?.id ?? null,+ tasksLimit: plan.data.tasksLimit,+ aiTokensLimit: plan.data.aiTokensLimit,+ usersLimit: 10, // Default value as defined in the migration+ stripeSubscriptionStatus: (subData.cancelAtPeriodEnd+ ? "Canceled"+ : ["active", "trialing"].includes(subData.status)+ ? "Active"+ : "Inactive") as "Active" | "Inactive" | "Canceled",+ stripeCustomerId: customerId,+ stripeSubscriptionId: subData.subscriptionId,+ subscriptionStartDate: new Date(+ subData.currentPeriodStart * 1000+ ).toISOString(),+ };const [, companyPlan] = await Promise.all([redis.set(customerKey, subData),@@ -207,34 +222,7 @@ async function getPlanByPriceId(async function upsertCompanyPlan(client: SupabaseClient<Database>,- companyPlan: {- companyId: string;- priceId: string;- status?: "Active" | "Inactive" | "Canceled";- stripeCustomerId?: string;- stripeSubscriptionId?: string;- subscriptionStartDate?: string;- }+ companyPlan: Database["public"]["Tables"]["companyPlan"]["Insert"]) {- const plan = await getPlanByPriceId(client, companyPlan.priceId);- if (plan.error) {- console.error("failed to get plan by ", plan.error);- return plan;- }-- const companyPlanData: Database["public"]["Tables"]["companyPlan"]["Insert"] =- {- id: companyPlan.companyId,- planId: plan.data.id,- tasksLimit: plan.data.tasksLimit,- aiTokensLimit: plan.data.aiTokensLimit,- usersLimit: 10, // Default value as defined in the migration- subscriptionStartDate:- companyPlan.subscriptionStartDate || new Date().toISOString(),- stripeSubscriptionStatus: companyPlan.status,- stripeCustomerId: companyPlan.stripeCustomerId,- stripeSubscriptionId: companyPlan.stripeSubscriptionId,- };-- return client.from("companyPlan").upsert(companyPlanData);+ return client.from("companyPlan").upsert(companyPlan);}