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 stripe webhook
Brad Barbina8ff68552f38
diff --git a/README.md b/README.mdindex 146ee349f9..2495a895db 100644--- a/README.md+++ b/README.md@@ -17,7 +17,7 @@ Features:- [x] MCP Client/Server- [x] API- [x] Webhooks-- [ ] Purchase Planning+- [x] Purchase Planning- [ ] AccountingTechnical highlights:diff --git a/apps/erp/app/components/AvatarMenu.tsx b/apps/erp/app/components/AvatarMenu.tsxindex fbd164c040..9b5faa4821 100644--- a/apps/erp/app/components/AvatarMenu.tsx+++ b/apps/erp/app/components/AvatarMenu.tsx@@ -179,7 +179,7 @@ const AvatarMenu = () => {<DropdownMenuSeparator /><DropdownMenuItem asChild><Form method="post" action={path.to.logout}>- <button type="submit" className="w-full flex items-center">+ <button type="submit" className="w-full h-full flex items-center"><DropdownMenuIcon icon={<LuLogOut />} /><span>Sign Out</span></button>diff --git a/apps/erp/app/lib/stripe.server.ts b/apps/erp/app/lib/stripe.server.tsindex 5c092456be..769c733e57 100644--- a/apps/erp/app/lib/stripe.server.ts+++ b/apps/erp/app/lib/stripe.server.ts@@ -1,10 +1,13 @@-import { getPlanById } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth";import { redis } from "@carbon/kv";import { redirect } from "@vercel/remix";import { Stripe } from "stripe";import { z } from "zod";+import {+ getPlanById,+ updateCompanyPlan,+} from "~/modules/settings/settings.service";import { path } from "~/utils/path";-import { getCarbonServiceRole } from "../../../../packages/auth/src/lib/supabase/client";if (!process.env.STRIPE_SECRET_KEY) {throw new Error("process.env.STRIPE_SECRET_KEY not defined");@@ -39,6 +42,14 @@ const KvStripeCustomerSchema = z.object({.nullable(),});+export async function getStripeCustomerByCompanyId(companyId: string) {+ const customerId = await getStripeCustomerId(companyId);+ if (!customerId) {+ return null;+ }+ return getStripeCustomer(customerId);+}+export async function getStripeCustomer(customerId: string) {const customer = await redis.get(`stripe:customer:${customerId}`);return KvStripeCustomerSchema.nullish().parse(customer);@@ -46,15 +57,19 @@ export async function getStripeCustomer(customerId: string) {const KvStripeUserSchema = z.string().nullish();-export async function getStripeCustomerId(userId: string) {- return KvStripeUserSchema.parse(await redis.get(`stripe:user:${userId}`));+export async function getStripeCustomerId(companyId: string) {+ return KvStripeUserSchema.parse(+ await redis.get(`stripe:company:${companyId}`)+ );}export async function createStripeCustomer({+ userId,companyId,email,name,}: {+ userId: string;companyId: string;email: string;name?: string | null;@@ -65,17 +80,18 @@ export async function createStripeCustomer({email,name: name ?? undefined,metadata: {+ owner: userId,companyId,},},{- idempotencyKey: companyId,+ idempotencyKey: `${companyId}-${userId}`,});- // Store the relation between userId and stripeCustomerId in KV+ // Store the relation between companyId and stripeCustomerId in KVawait redis.set(- `stripe:user:${companyId}`,+ `stripe:company:${companyId}`,KvStripeUserSchema.parse(customer.id));@@ -115,6 +131,8 @@ export async function processStripeEvent({throw new Error("Stripe webhook handler failed");}+ console.log({ customer });+try {await syncStripeDataToKV(customer);} catch (error) {@@ -125,6 +143,7 @@ export async function processStripeEvent({export async function syncStripeDataToKV(customerId: string) {const key = `stripe:customer:${customerId}`;+ console.log({ key });const subscriptions = await stripe.subscriptions.list({customer: customerId,@@ -157,7 +176,30 @@ export async function syncStripeDataToKV(customerId: string) {: null,});- await redis.set(key, subData);+ const customer = await stripe.customers.retrieve(customerId);+ const companyId = (customer as any).metadata?.companyId;++ if (companyId) {+ const [, companyPlan] = await Promise.all([+ redis.set(key, subData),+ updateCompanyPlan(getCarbonServiceRole(), {+ companyId,+ stripeCustomerId: customerId,+ stripeSubscriptionId: subscription.id,+ stripeSubscriptionStatus: subscription.status,+ subscriptionStartDate: new Date(+ subscription.items.data[0].current_period_start * 1000+ ).toISOString(),+ }),+ ]);++ console.log({ companyPlan });++ if (companyPlan.error) {+ throw new Error("Failed to update company plan");+ }+ }+return subData;}@@ -211,11 +253,13 @@ function getStripeWebhookEvent({export async function getCheckoutUrl({planId,+ userId,companyId,email,name,}: {planId: string;+ userId: string;companyId: string;email: string;name?: string | null;@@ -226,6 +270,7 @@ export async function getCheckoutUrl({if (!stripeCustomerId) {// Create a new customer if one doesn't existconst customer = await createStripeCustomer({+ userId,companyId,email,name,@@ -244,8 +289,8 @@ export async function getCheckoutUrl({},],mode: "subscription",- success_url: `${process.env.VERCEL_URL}/api/webhook/stripe`,- cancel_url: `${process.env.VERCEL_URL}/api/webhook/stripe`,+ success_url: `${process.env.VERCEL_URL}${path.to.api.webhookStripe}`,+ cancel_url: `${process.env.VERCEL_URL}${path.to.api.webhookStripe}`,metadata: {companyId,},@@ -279,3 +324,15 @@ export async function redirectToBillingPortal({redirect(portalSession.url);}++export async function updateActiveUsers({+ subscriptionId,+ activeUsers,+}: {+ subscriptionId: string;+ activeUsers: number;+}) {+ await stripe.subscriptionItems.update(subscriptionId, {+ quantity: activeUsers,+ });+}diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 3872f9e0d8..ae518713af 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -1,4 +1,5 @@import { SUPABASE_URL } from "@carbon/auth";+import type { Database, Json } from "@carbon/database";import type { SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";@@ -151,6 +152,13 @@ export async function getCompany(};}+export async function getCompanyPlan(+ client: SupabaseClient,+ companyId: string+) {+ return client.from("companyPlan").select("*").eq("id", companyId).single();+}+export async function getCompanySettings(client: SupabaseClient<Database>,companyId: string@@ -262,6 +270,14 @@ export async function getIntegrations(return client.from("integrations").select("*").eq("companyId", companyId);}+export async function getPlanById(client: SupabaseClient, planId: string) {+ return client.from("plan").select("*").eq("id", planId).single();+}++export async function getPlans(client: SupabaseClient) {+ return client.from("plan").select("*");+}+export async function getNextSequence(client: SupabaseClient<Database>,table: string,@@ -378,6 +394,58 @@ export async function insertCompany(return client.from("company").insert(company).select("id").single();}+export async function insertCompanyPlan(+ client: SupabaseClient<Database>,+ companyPlan: {+ companyId: string;+ planId: string;+ status: "active" | "inactive";+ }+) {+ const plan = await getPlanById(client, companyPlan.planId);+ if (plan.error) {+ return plan;+ }++ const companyPlanData: Database["public"]["Tables"]["companyPlan"]["Insert"] =+ {+ id: companyPlan.companyId,+ planId: companyPlan.planId,+ tasksLimit: plan.data.tasksLimit,+ aiTokensLimit: plan.data.aiTokensLimit,+ usersLimit: 10, // Default value as defined in the migration+ subscriptionStartDate: new Date().toISOString(),+ stripeSubscriptionStatus: companyPlan.status,+ trialPeriodEndsAt: plan.data.stripeTrialPeriodDays+ ? new Date(+ Date.now() + plan.data.stripeTrialPeriodDays * 24 * 60 * 60 * 1000+ ).toISOString()+ : null,+ };++ return client+ .from("companyPlan")+ .upsert(companyPlanData)+ .select("id")+ .single();+}++export async function updateCompanyPlan(+ client: SupabaseClient<Database>,+ data: {+ companyId: string;+ stripeCustomerId: string;+ stripeSubscriptionId: string;+ stripeSubscriptionStatus: string;+ subscriptionStartDate: string;+ }+) {+ // Extract companyId and build the update data without it+ const { companyId, ...updateData } = data;++ return client.from("companyPlan").update(updateData).eq("id", companyId);+}+export async function seedCompany(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/routes/api+/webhook.stripe.ts b/apps/erp/app/routes/api+/webhook.stripe.tsnew file mode 100644index 0000000000..3c72e82ae0--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.stripe.ts@@ -0,0 +1,38 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";+import {+ getStripeCustomerId,+ processStripeEvent,+ syncStripeDataToKV,+} from "~/lib/stripe.server";+import { path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ const { companyId } = await requirePermissions(request, {});++ const customerId = await getStripeCustomerId(companyId);+ if (customerId) {+ await syncStripeDataToKV(customerId);+ }++ throw redirect(path.to.authenticatedRoot);+}++export async function action({ request }: ActionFunctionArgs) {+ const body = await request.text();+ const signature = request.headers.get("stripe-signature");++ if (!signature) {+ console.error("No signature");+ return json({ error: "No signature" }, { status: 400 });+ }++ try {+ await processStripeEvent({ body, signature });+ return json({ success: true });+ } catch (error) {+ console.error("Stripe webhook error:", error);+ return json({ error: "Webhook processing failed" }, { status: 400 });+ }+}diff --git a/apps/erp/app/routes/onboarding+/_index.tsx b/apps/erp/app/routes/onboarding+/_index.tsxindex dba39849ae..1536c01306 100644--- a/apps/erp/app/routes/onboarding+/_index.tsx+++ b/apps/erp/app/routes/onboarding+/_index.tsx@@ -6,9 +6,9 @@ import { onboardingSequence } from "~/utils/path";const Heading = motion(_Heading);const Button = motion(_Button);-const fade = {- initial: { opacity: 0 },- animate: { opacity: 1 },+const slideUp = {+ initial: { opacity: 0, y: 20 },+ animate: { opacity: 1, y: 0 },};export default function GetStarted() {@@ -18,17 +18,17 @@ export default function GetStarted() {<AnimatePresence><VStack spacing={4} className="max-w-lg p-4 items-center text-center"><motion.img- initial={{ opacity: 0, scale: 0.4 }}+ initial={{ opacity: 0, scale: 0.6 }}animate={{ opacity: 1, scale: 1 }}- transition={{ duration: 1, ease: "easeInOut" }}+ transition={{ duration: 2.4, ease: "easeInOut" }}src="/carbon-logo-mark.svg"alt="Carbon Logo"className="w-24 mb-3"/><Heading- {...fade}- transition={{ duration: 0.8, ease: "easeInOut", delay: 0.5 }}+ {...slideUp}+ transition={{ duration: 0.8, ease: "easeInOut", delay: 1.7 }}size="h1"className="m-0">@@ -36,16 +36,16 @@ export default function GetStarted() {</Heading><motion.p- {...fade}- transition={{ duration: 0.8, ease: "easeInOut", delay: 0.7 }}+ {...slideUp}+ transition={{ duration: 0.8, ease: "easeInOut", delay: 1.7 }}className="text-muted-foreground text-balance text-sm pb-4">- Carbon is the new standard for tech-enabled manufacturing+ The new standard for tech-enabled manufacturing</motion.p><Button- {...fade}- transition={{ duration: 0.8, ease: "easeInOut", delay: 0.7 }}+ {...slideUp}+ transition={{ duration: 0.8, ease: "easeInOut", delay: 2.7 }}size="lg"onClick={() => navigate(onboardingSequence[0])}>diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsxindex 4baedf7359..4dbe188798 100644--- a/apps/erp/app/routes/onboarding+/_layout.tsx+++ b/apps/erp/app/routes/onboarding+/_layout.tsx@@ -1,4 +1,4 @@-import { getCompanyPlan, requirePermissions } from "@carbon/auth/auth.server";+import { requirePermissions } from "@carbon/auth/auth.server";import { Outlet } from "@remix-run/react";import { redirect, type LoaderFunctionArgs } from "@vercel/remix";import { getLocationsList } from "~/modules/resources";@@ -7,6 +7,7 @@ import { onboardingSequence, path } from "~/utils/path";import { VStack } from "@carbon/react";import type { ShouldRevalidateFunction } from "@remix-run/react";+import { getStripeCustomerByCompanyId } from "~/lib/stripe.server";export const shouldRevalidate: ShouldRevalidateFunction = () => true;@@ -17,20 +18,19 @@ export const config = {export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});- const [company, plan, locations] = await Promise.all([+ const [company, stripeCustomer, locations] = await Promise.all([getCompany(client, companyId),- getCompanyPlan(client, companyId),+ getStripeCustomerByCompanyId(companyId),getLocationsList(client, companyId),]);const pathname = new URL(request.url).pathname;- const isOnPlanRoute = pathname === path.to.onboarding.plan;- // Only redirect to plan page if we're not already on it+ // Only redirect to stripeCustomer page if we're not already on itif (company.data?.name && locations.data?.length) {- if (!plan.data?.id && !isOnPlanRoute) {+ if (!stripeCustomer && pathname !== path.to.onboarding.plan) {throw redirect(path.to.onboarding.plan);- } else if (plan.data?.id) {+ } else if (stripeCustomer) {throw redirect(path.to.authenticatedRoot);}}diff --git a/apps/erp/app/routes/onboarding+/plan.tsx b/apps/erp/app/routes/onboarding+/plan.tsxindex b313e03988..d54aedeb40 100644--- a/apps/erp/app/routes/onboarding+/plan.tsx+++ b/apps/erp/app/routes/onboarding+/plan.tsx@@ -1,5 +1,5 @@-import { getUser } from "@carbon/auth";-import { getPlans, requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole, getUser } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";import {Badge,Button,@@ -17,7 +17,7 @@ import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";import { useMemo } from "react";import { LuMoveLeft } from "react-icons/lu";import { getCheckoutUrl } from "~/lib/stripe.server";-import { getCompany } from "~/modules/settings";+import { getCompany, getPlans, insertCompanyPlan } from "~/modules/settings";import { path } from "~/utils/path";const FEATURED_PLAN = "BUSINESS";@@ -87,8 +87,20 @@ export async function action({ request }: ActionFunctionArgs) {throw new Error("Company not found");}+ const companyPlan = await insertCompanyPlan(getCarbonServiceRole(), {+ companyId,+ planId,+ status: "active",+ });++ if (companyPlan.error) {+ console.error(companyPlan.error);+ throw new Error("Failed to insert company plan");+ }+const url = await getCheckoutUrl({planId,+ userId,companyId,name: company.data?.name,email: user.data?.email,diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex e7b32e9cd4..2fd2fa81e5 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -22,10 +22,10 @@ import {} from "~/modules/users/users.server";import { path } from "~/utils/path";-import { getCompanyPlan } from "@carbon/auth/auth.server";import type { ShouldRevalidateFunction } from "@remix-run/react";import posthog from "posthog-js";import { useUser } from "~/hooks";+import { getStripeCustomerByCompanyId } from "~/lib/stripe.server";import { getSavedViews } from "~/modules/shared/shared.service";export const shouldRevalidate: ShouldRevalidateFunction = ({@@ -62,7 +62,7 @@ export async function loader({ request }: LoaderFunctionArgs) {// parallelize the requestsconst [companies,- companyPlan,+ stripeCustomer,customFields,integrations,savedViews,@@ -72,7 +72,7 @@ export async function loader({ request }: LoaderFunctionArgs) {defaults,] = await Promise.all([getCompanies(client, userId),- getCompanyPlan(client, companyId),+ getStripeCustomerByCompanyId(companyId),getCustomFieldsSchemas(client, { companyId }),getCompanyIntegrations(client, companyId),getSavedViews(client, userId, companyId),@@ -88,8 +88,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const company = companies.data?.find((c) => c.companyId === companyId);- const requiresOnboarding =- !companies.data?.[0]?.name || !companyPlan.data?.id;+ const requiresOnboarding = !companies.data?.[0]?.name || !stripeCustomer;if (requiresOnboarding) {throw redirect(path.to.onboarding.root);}diff --git a/apps/erp/app/styles/tailwind.css b/apps/erp/app/styles/tailwind.cssindex 4c315b6eab..4983e745cb 100644--- a/apps/erp/app/styles/tailwind.css+++ b/apps/erp/app/styles/tailwind.css@@ -169,6 +169,7 @@ p.is-editor-empty:first-child:before {width: 100%;height: 40px;}+/* Three dot loading animation */.circle {display: inline-block;@@ -176,18 +177,18 @@ p.is-editor-empty:first-child:before {width: 16px;height: 16px;background-color: #5fe4d3;- border-radius: 50%;+ transform: rotate(45deg);animation: dotloader 1.4s infinite ease-in-out;}.circle + .circle {- margin-left: 12px;+ margin-left: 16px;animation: dotloader 1.4s 0.2s infinite ease-in-out;background-color: #4faade;}.circle + .circle + .circle {- margin-left: 12px;+ margin-left: 16px;animation: dotloader 1.4s 0.4s infinite ease-in-out;background-color: #6041d0;}@@ -196,11 +197,11 @@ p.is-editor-empty:first-child:before {0%,80%,100% {- transform: scale(0.5);+ transform: scale(0.5) rotate(45deg);opacity: 0;}40% {- transform: scale(1.2);+ transform: scale(1) rotate(45deg);opacity: 1;}}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex bf80e9551c..21271307ae 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -139,6 +139,7 @@ export const path = {generatePath(`${api}/shared/tags?table=${table}`),unitOfMeasures: `${api}/items/uoms`,webhookTables: `${api}/webhook/tables`,+ webhookStripe: `${api}/webhook/stripe`,workCentersByLocation: (id: string) =>generatePath(`${api}/resources/work-centers?location=${id}`),workCenters: `${api}/resources/work-centers`,diff --git a/apps/erp/stripe.dev.ts b/apps/erp/stripe.dev.tsindex 56e18cb121..bf1b087689 100644--- a/apps/erp/stripe.dev.ts+++ b/apps/erp/stripe.dev.ts@@ -31,7 +31,9 @@ const events: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [];console.log("🔄 Setting up Stripe webhook endpoint...");-const url = `https://${process.env.VERCEL_URL}/api/stripe`;++const url = `${process.env.VERCEL_URL}/api/webhook/stripe`;+console.log("🔄 Webhook URL:", url);if (!url.includes("localhost:")) {throw new Error("Running in production mode");diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex c235e73a24..e5623d5665 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -1,5 +1,4 @@import { CarbonProvider, getCarbon, getCompanies, getUser } from "@carbon/auth";-import { getCompanyPlan } from "@carbon/auth/auth.server";import {destroyAuthSession,requireAuthSession,diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.tsindex d40a3f7512..2d5095b2f2 100644--- a/packages/auth/src/services/auth.server.ts+++ b/packages/auth/src/services/auth.server.ts@@ -38,21 +38,6 @@ export async function createEmailAuthAccount(return data.user;}-export async function getCompanyPlan(- client: SupabaseClient,- companyId: string-) {- return client.from("companyPlan").select("*").eq("id", companyId).single();-}--export async function getPlanById(client: SupabaseClient, planId: string) {- return client.from("plan").select("*").eq("id", planId).single();-}--export async function getPlans(client: SupabaseClient) {- return client.from("plan").select("*");-}-export async function deleteAuthAccount(client: SupabaseClient<Database>,userId: stringdiff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 36a959775b..7418948010 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -41307,9 +41307,6 @@ export default {{$ref: "#/parameters/rowFilter.company.slackChannel",},- {- $ref: "#/parameters/rowFilter.company.ownerId",- },{$ref: "#/parameters/select",},@@ -41429,9 +41426,6 @@ export default {{$ref: "#/parameters/rowFilter.company.slackChannel",},- {- $ref: "#/parameters/rowFilter.company.ownerId",- },{$ref: "#/parameters/preferReturn",},@@ -41505,9 +41499,6 @@ export default {{$ref: "#/parameters/rowFilter.company.slackChannel",},- {- $ref: "#/parameters/rowFilter.company.ownerId",- },{$ref: "#/parameters/body.company",},@@ -72795,7 +72786,6 @@ export default {"aiTokensLimit","usersLimit","subscriptionStartDate",- "stripeSubscriptionId","stripeSubscriptionStatus","createdAt","updatedAt",@@ -72842,7 +72832,7 @@ export default {type: "string",},stripeSubscriptionStatus: {- default: "ACTIVE",+ default: "active",format: "text",type: "string",},@@ -76909,12 +76899,6 @@ export default {format: "text",type: "string",},- ownerId: {- description:- "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",- format: "text",- type: "string",- },},type: "object",},@@ -104223,12 +104207,6 @@ export default {in: "query",type: "string",},- "rowFilter.company.ownerId": {- name: "ownerId",- required: false,- in: "query",- type: "string",- },"body.salesOrderLocations": {name: "salesOrderLocations",description: "salesOrderLocations",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 01b24f9038..5028740fb7 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1982,7 +1982,6 @@ export type Database = {logoLight: string | nulllogoLightIcon: string | nullname: string- ownerId: string | nullphone: string | nullpostalCode: string | nullslackChannel: string | null@@ -2005,7 +2004,6 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname: string- ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2028,7 +2026,6 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname?: string- ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2080,41 +2077,6 @@ export type Database = {referencedRelation: "currencyCode"referencedColumns: ["code"]},- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },]}companyIntegration: {@@ -2194,7 +2156,7 @@ export type Database = {id: stringplanId: stringstripeCustomerId: string | null- stripeSubscriptionId: string+ stripeSubscriptionId: string | nullstripeSubscriptionStatus: stringsubscriptionStartDate: stringtasksLimit: number@@ -2208,7 +2170,7 @@ export type Database = {id?: stringplanId: stringstripeCustomerId?: string | null- stripeSubscriptionId: string+ stripeSubscriptionId?: string | nullstripeSubscriptionStatus?: stringsubscriptionStartDate: stringtasksLimit?: number@@ -2222,7 +2184,7 @@ export type Database = {id?: stringplanId?: stringstripeCustomerId?: string | null- stripeSubscriptionId?: string+ stripeSubscriptionId?: string | nullstripeSubscriptionStatus?: stringsubscriptionStartDate?: stringtasksLimit?: numberdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 01b24f9038..5028740fb7 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1982,7 +1982,6 @@ export type Database = {logoLight: string | nulllogoLightIcon: string | nullname: string- ownerId: string | nullphone: string | nullpostalCode: string | nullslackChannel: string | null@@ -2005,7 +2004,6 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname: string- ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2028,7 +2026,6 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname?: string- ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2080,41 +2077,6 @@ export type Database = {referencedRelation: "currencyCode"referencedColumns: ["code"]},- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "company_ownerId_fkey"- columns: ["ownerId"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },]}companyIntegration: {@@ -2194,7 +2156,7 @@ export type Database = {id: stringplanId: stringstripeCustomerId: string | null- stripeSubscriptionId: string+ stripeSubscriptionId: string | nullstripeSubscriptionStatus: stringsubscriptionStartDate: stringtasksLimit: number@@ -2208,7 +2170,7 @@ export type Database = {id?: stringplanId: stringstripeCustomerId?: string | null- stripeSubscriptionId: string+ stripeSubscriptionId?: string | nullstripeSubscriptionStatus?: stringsubscriptionStartDate: stringtasksLimit?: number@@ -2222,7 +2184,7 @@ export type Database = {id?: stringplanId?: stringstripeCustomerId?: string | null- stripeSubscriptionId?: string+ stripeSubscriptionId?: string | nullstripeSubscriptionStatus?: stringsubscriptionStartDate?: stringtasksLimit?: numberdiff --git a/packages/database/supabase/migrations/20250619100940_billing.sql b/packages/database/supabase/migrations/20250619100940_billing.sqlindex 7756b3bcf1..9cb9f950c0 100644--- a/packages/database/supabase/migrations/20250619100940_billing.sql+++ b/packages/database/supabase/migrations/20250619100940_billing.sql@@ -1,5 +1,3 @@-ALTER TABLE "company" ADD COLUMN "ownerId" TEXT REFERENCES "user"("id") ON DELETE SET NULL;-CREATE TABLE "plan" ("id" TEXT NOT NULL DEFAULT xid(),"name" TEXT NOT NULL,@@ -25,8 +23,8 @@ CREATE POLICY "SELECT" ON "plan"INSERT INTO "plan" ("id", "name", "userBasedPricing", "stripePriceId", "tasksLimit", "aiTokensLimit", "stripeTrialPeriodDays", "public") VALUES- ('STARTER', 'Starter', TRUE, 'price_1RgUYhFV6ecOa0XvD37hQOhK', 10000, 1000000, 14, TRUE),- ('BUSINESS', 'Business', TRUE, 'price_1RgUZ3FV6ecOa0XvQFLFQsX4', 10000, 1000000, 14, TRUE),+ ('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);CREATE TABLE "companyPlan" (@@ -37,8 +35,8 @@ CREATE TABLE "companyPlan" ("usersLimit" INTEGER NOT NULL DEFAULT 10,"subscriptionStartDate" TIMESTAMP WITH TIME ZONE NOT NULL,"stripeCustomerId" TEXT,- "stripeSubscriptionId" TEXT NOT NULL,- "stripeSubscriptionStatus" TEXT NOT NULL DEFAULT 'ACTIVE',+ "stripeSubscriptionId" TEXT,+ "stripeSubscriptionStatus" TEXT NOT NULL DEFAULT 'active',"trialPeriodEndsAt" TIMESTAMP WITH TIME ZONE,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),diff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sqlindex 883f233ad0..98bedff39a 100644--- a/packages/database/supabase/seed.sql+++ b/packages/database/supabase/seed.sql@@ -1,101 +1,100 @@---- Insert admin user into auth.users table-INSERT INTO auth.users (- instance_id, id, aud, role, email, encrypted_password,- email_confirmed_at, invited_at, confirmation_token, confirmation_sent_at,- recovery_token, recovery_sent_at, email_change_token_new, email_change,- email_change_sent_at, last_sign_in_at, raw_app_meta_data, raw_user_meta_data,- is_super_admin, created_at, updated_at, phone, phone_confirmed_at,- phone_change, phone_change_token, phone_change_sent_at,- email_change_token_current, email_change_confirm_status, banned_until,- reauthentication_token, reauthentication_sent_at, is_sso_user, deleted_at, is_anonymous-) VALUES (- '00000000-0000-0000-0000-000000000000',- '82fd05db-270d-46af-b29e-082e9f709b1f',- 'authenticated',- 'authenticated',- '[email protected]',- crypt(md5(random()::text), gen_salt('bf')),- CURRENT_TIMESTAMP,- NULL,- '',- NULL,- '',- NULL,- '',- '',- NULL,- NULL,- '{"role": "employee", "provider": "email", "providers": ["email"]}',- '{}',- NULL,- CURRENT_TIMESTAMP,- CURRENT_TIMESTAMP,- NULL,- NULL,- '',- '',- NULL,- '',- 0,- NULL,- '',- NULL,- false,- NULL,- false-);--INSERT INTO- auth.identities (- user_id,- provider_id,- identity_data,- provider,- last_sign_in_at,- created_at,- updated_at+-- Insert admin user into auth.users table and public.user table+WITH new_auth_user AS (+ INSERT INTO auth.users (+ instance_id, id, aud, role, email, encrypted_password,+ email_confirmed_at, invited_at, confirmation_token, confirmation_sent_at,+ recovery_token, recovery_sent_at, email_change_token_new, email_change,+ email_change_sent_at, last_sign_in_at, raw_app_meta_data, raw_user_meta_data,+ is_super_admin, created_at, updated_at, phone, phone_confirmed_at,+ phone_change, phone_change_token, phone_change_sent_at,+ email_change_token_current, email_change_confirm_status, banned_until,+ reauthentication_token, reauthentication_sent_at, is_sso_user, deleted_at, is_anonymous+ ) VALUES (+ '00000000-0000-0000-0000-000000000000',+ uuid_generate_v4(),+ 'authenticated',+ 'authenticated',+ '[email protected]',+ crypt(md5(random()::text), gen_salt('bf')),+ CURRENT_TIMESTAMP,+ NULL,+ '',+ NULL,+ '',+ NULL,+ '',+ '',+ NULL,+ NULL,+ '{"role": "employee", "provider": "email", "providers": ["email"]}',+ '{}',+ NULL,+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP,+ NULL,+ NULL,+ '',+ '',+ NULL,+ '',+ 0,+ NULL,+ '',+ NULL,+ false,+ NULL,+ false+ ) RETURNING id+),+auth_identities AS (+ INSERT INTO auth.identities (+ user_id,+ provider_id,+ identity_data,+ provider,+ last_sign_in_at,+ created_at,+ updated_at)-VALUES (- '82fd05db-270d-46af-b29e-082e9f709b1f',- '82fd05db-270d-46af-b29e-082e9f709b1f',- format('{"sub":"%s","email":"%s"}', '82fd05db-270d-46af-b29e-082e9f709b1f', '[email protected]')::jsonb,- 'email',- CURRENT_TIMESTAMP,- CURRENT_TIMESTAMP,- CURRENT_TIMESTAMP+ SELECT+ id,+ id,+ format('{"sub":"%s","email":"%s"}', id, '[email protected]')::jsonb,+ 'email',+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP,+ CURRENT_TIMESTAMP+ FROM new_auth_user+ ON CONFLICT (provider_id, provider) DO NOTHING+),+new_user AS (+ INSERT INTO public."user" (+ id, email, "firstName", "lastName", about, "avatarUrl",+ active, "createdAt", "updatedAt", developer, admin+ )+ SELECT+ id,+ '[email protected]',+ 'Brad',+ 'Barbin',+ '',+ NULL,+ true,+ '2025-03-14 19:25:59.271544+00',+ NULL,+ false,+ false+ FROM new_auth_user+ RETURNING id)-ON CONFLICT (provider_id, provider) DO NOTHING;---- Insert admin user into public.user table-INSERT INTO public."user" (- id, email, "firstName", "lastName", about, "avatarUrl",- active, "createdAt", "updatedAt", developer, admin-) VALUES (- '82fd05db-270d-46af-b29e-082e9f709b1f',- '[email protected]',- 'Brad',- 'Barbin',- '',- NULL,- true,- '2025-03-14 19:25:59.271544+00',- NULL,- false,- false-);--- Insert admin user permissionsINSERT INTO public."userPermission" (id, permissions-) VALUES (- '82fd05db-270d-46af-b29e-082e9f709b1f',+)+SELECT+ id,'{- "users_update": [- "0"- ],- "settings_update": [- "0"- ]+ "users_update": [],+ "settings_update": []}'-);\ No newline at end of file+FROM new_user;\ No newline at end of file