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 service
Brad Barbin7b52df1c1cf0
diff --git a/.env.example b/.env.exampleindex 48c01a5ce5..c64b82f009 100644--- a/.env.example+++ b/.env.example@@ -14,6 +14,9 @@ SLACK_BOT_TOKEN="***********************"SESSION_SECRET="************************"+STRIPE_SECRET_KEY="sk_test_*************"+STRIP_WEBHOOK_SECRET="whsec_************"+SUPABASE_ANON_KEY="******************"SUPABASE_SERVICE_ROLE_KEY="*****************"SUPABASE_URL="http://localhost:54321"diff --git a/README.md b/README.mdindex 387424db4b..f7bea18515 100644--- a/README.md+++ b/README.md@@ -226,6 +226,13 @@ For example, to run test command in the `@carbon/react` package you can run:$ npm run test -w @carbon/react```+To run Stripe locally, run:++```+$ npm run -w erp register:stripe+$ npm run -w erp dev:stripe+```+### Restoring a Production Database Locally1. Download the production database backup from Supabasediff --git a/apps/erp/app/lib/stripe/plans.ts b/apps/erp/app/lib/stripe/plans.tsnew file mode 100644index 0000000000..8f38b3c668--- /dev/null+++ b/apps/erp/app/lib/stripe/plans.ts@@ -0,0 +1,37 @@+import { getStripeCustomer, getStripeCustomerId } from "./stripe.server";++// Add new plans here+const defaultPlans = [+ {+ id: "FREE",+ priceId: undefined,+ messageLimit: 10,+ },+ {+ id: "PRO",+ priceId: "price_1R3aDvLxBMFKq9DZn1vkvwwW",+ messageLimit: 100,+ },+];++export async function getPlans() {+ return defaultPlans;+}++export async function getStripePlan(companyId: string) {+ const plans = await getPlans();+ const freePlan = plans.find((plan) => plan.priceId === undefined) ?? plans[0];++ const customerId = await getStripeCustomerId(companyId);+ if (!customerId) {+ return freePlan;+ }++ const subData = await getStripeCustomer(customerId);+ if (!subData || subData.status !== "active") {+ // Inactive subscriptions happen after canceling, once the billing period ends+ return freePlan;+ }++ return plans.find((plan) => plan.priceId === subData.priceId) ?? freePlan;+}diff --git a/apps/erp/app/lib/stripe/stripe.server.ts b/apps/erp/app/lib/stripe/stripe.server.tsnew file mode 100644index 0000000000..f2ad5ba8b5--- /dev/null+++ b/apps/erp/app/lib/stripe/stripe.server.ts@@ -0,0 +1,280 @@+/**+ * Integrate Stripe with a KV store.+ */+import { redis } from "@carbon/kv";+import { redirect } from "@vercel/remix";+import { Stripe } from "stripe";+import { z } from "zod";+import { path } from "~/utils/path";+import { getPlans } from "./plans";++if (!process.env.STRIPE_SECRET_KEY) {+ throw new Error("process.env.STRIPE_SECRET_KEY not defined");+}++export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {+ apiVersion: "2025-06-30.basil",+ typescript: true,+});++const KvStripeCustomerSchema = z.object({+ subscriptionId: z.string(),+ status: z.union([+ z.literal("active"),+ z.literal("canceled"),+ z.literal("incomplete"),+ z.literal("incomplete_expired"),+ z.literal("past_due"),+ z.literal("paused"),+ z.literal("trialing"),+ z.literal("unpaid"),+ ]),+ priceId: z.string(),+ currentPeriodStart: z.number(),+ currentPeriodEnd: z.number(),+ cancelAtPeriodEnd: z.boolean(),+ paymentMethod: z+ .object({+ brand: z.string().nullable(),+ last4: z.string().nullable(),+ })+ .nullable(),+});++export async function getStripeCustomer(customerId: string) {+ const customer = await redis.get(`stripe:customer:${customerId}`);+ return KvStripeCustomerSchema.nullish().parse(customer);+}++const KvStripeUserSchema = z.string().nullish();++export async function getStripeCustomerId(userId: string) {+ return KvStripeUserSchema.parse(await redis.get(`stripe:user:${userId}`));+}++export async function createStripeCustomer({+ companyId,+ email,+ name,+}: {+ companyId: string;+ email: string;+ name?: string | null;+}) {+ try {+ const customer = await stripe.customers.create(+ {+ email,+ name: name ?? undefined,+ metadata: {+ companyId,+ },+ },+ {+ idempotencyKey: companyId,+ }+ );++ // Store the relation between userId and stripeCustomerId in KV+ await redis.set(+ `stripe:user:${companyId}`,+ KvStripeUserSchema.parse(customer.id)+ );++ return customer;+ } catch (error) {+ console.error("Error creating Stripe customer:", error);+ throw error;+ }+}++export async function processStripeEvent({+ body,+ signature,+}: {+ body: string;+ signature: string;+}) {+ const {+ event,+ success: eventSuccess,+ error: eventError,+ } = getStripeWebhookEvent({ body, signature });++ if (!eventSuccess) {+ throw new Error(`Stripe webhook event error: ${eventError.message}`);+ }++ if (!isAllowedEventType(event)) {+ console.warn(+ `[STRIPE HOOK] Received untracked event: ${event.type}. Configure webhook event types in your Stripe dashboard.`+ );+ return;+ }++ const { customer } = event.data.object;+ if (typeof customer !== "string") {+ throw new Error("Stripe webhook handler failed");+ }++ try {+ await syncStripeDataToKV(customer);+ } catch (error) {+ console.error("Error processing webhook:", error);+ throw new Error("Stripe webhook handler failed");+ }+}++export async function syncStripeDataToKV(customerId: string) {+ const key = `stripe:customer:${customerId}`;++ const subscriptions = await stripe.subscriptions.list({+ customer: customerId,+ limit: 1,+ status: "all",+ expand: ["data.default_payment_method"],+ });++ if (subscriptions.data.length === 0) {+ await redis.del(key);+ return null;+ }++ const subscription = subscriptions.data[0];++ const subData = KvStripeCustomerSchema.parse({+ 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,+ });++ await redis.set(key, subData);+ return subData;+}++const allowedEventTypes = [+ "checkout.session.completed",+ "checkout.session.async_payment_succeeded",+ "customer.subscription.created",+ "customer.subscription.updated",+ "customer.subscription.deleted",+ "customer.subscription.paused",+ "customer.subscription.resumed",+ "customer.subscription.pending_update_applied",+ "customer.subscription.pending_update_expired",+ "customer.subscription.trial_will_end",+ "invoice.paid",+ "invoice.payment_failed",+ "invoice.payment_action_required",+ "invoice.upcoming",+ "invoice.marked_uncollectible",+ "invoice.payment_succeeded",+ "payment_intent.succeeded",+ "payment_intent.payment_failed",+ "payment_intent.canceled",+] as const;+type AllowedEventType = (typeof allowedEventTypes)[number];++function isAllowedEventType<TEvent extends Stripe.Event>(+ event: TEvent+): event is TEvent & { type: AllowedEventType } {+ return allowedEventTypes.includes(event.type as AllowedEventType);+}++function getStripeWebhookEvent({+ body,+ signature,+}: {+ body: string;+ signature: string;+}) {+ try {+ const event = stripe.webhooks.constructEvent(+ body,+ signature,+ process.env.STRIPE_WEBHOOK_SECRET!+ );+ return { success: true as const, event: event, error: null };+ } catch (error) {+ return { success: false as const, error: error as Error, event: null };+ }+}++export async function redirectToCheckout({+ companyId,+ email,+ name,+}: {+ companyId: string;+ email: string;+ name?: string | null;+}) {+ const customerId = await getStripeCustomerId(companyId);+ let stripeCustomerId = customerId;++ if (!stripeCustomerId) {+ // Create a new customer if one doesn't exist+ const customer = await createStripeCustomer({+ companyId,+ email,+ name,+ });+ stripeCustomerId = customer.id;+ }++ const plans = await getPlans();+ const checkoutSession = await stripe.checkout.sessions.create({+ customer: stripeCustomerId,+ line_items: [+ {+ price: plans.find((plan) => plan.id === "PRO")?.priceId,+ quantity: 1,+ },+ ],+ mode: "subscription",+ success_url: `${process.env.VERCEL_URL}/api/webhook/stripe`,+ cancel_url: `${process.env.VERCEL_URL}/api/webhook/stripe`,+ metadata: {+ companyId,+ },+ });++ if (!checkoutSession.url) {+ throw new Error("Failed to create checkout session");+ }++ return checkoutSession.url;+}++export async function redirectToBillingPortal({+ companyId,+}: {+ companyId: string;+}) {+ const customerId = await getStripeCustomerId(companyId);+ if (!customerId) {+ throw new Error("Customer not found");+ }++ const portalSession = await stripe.billingPortal.sessions.create({+ customer: customerId,+ return_url: `${process.env.VERCEL_URL}${path.to.settings}`,+ });++ if (!portalSession.url) {+ throw new Error("Failed to create portal session");+ }++ redirect(portalSession.url);+}diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsxindex b6d38c8cff..847173cd69 100644--- a/apps/erp/app/routes/onboarding+/_layout.tsx+++ b/apps/erp/app/routes/onboarding+/_layout.tsx@@ -1,5 +1,5 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { Outlet } from "@remix-run/react";+import { Outlet, useLoaderData } from "@remix-run/react";import { redirect, type LoaderFunctionArgs } from "@vercel/remix";import { getLocationsList } from "~/modules/resources";import { getCompany } from "~/modules/settings";@@ -19,12 +19,17 @@ export async function loader({ request }: LoaderFunctionArgs) {update: "settings",});- const [company, locations] = await Promise.all([+ const [company, plan, locations] = await Promise.all([getCompany(client, companyId),+ getCompanyPlan(client, companyId),getLocationsList(client, companyId),]);+// we don't need to do onboarding if we have a company name or locationsif (company.data?.name && locations.data?.length) {+ if (!plan.data?.planId) {+ throw redirect(path.to.onboarding.plan);+ }throw redirect(path.to.authenticatedRoot);}@@ -48,6 +53,8 @@ export async function loader({ request }: LoaderFunctionArgs) {}export default function OnboardingLayout() {+ const loaderData = useLoaderData<typeof loader>();+ console.log(loaderData);return (<VStackspacing={4}diff --git a/apps/erp/app/routes/onboarding+/plan.tsx b/apps/erp/app/routes/onboarding+/plan.tsxnew file mode 100644index 0000000000..e69de29bb2diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 62b086010c..bf80e9551c 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -270,6 +270,7 @@ export const path = {onboarding: {company: `${onboarding}/company`,location: `${onboarding}/location`,+ plan: `${onboarding}/plan`,root: `${onboarding}`,theme: `${onboarding}/theme`,user: `${onboarding}/user`,@@ -1282,6 +1283,7 @@ export const onboardingSequence = [path.to.onboarding.theme,path.to.onboarding.user,path.to.onboarding.company,+ path.to.onboarding.plan,] as const;export const getStoragePath = (bucket: string, path: string) => {diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex c4ff79dcab..ab90761dcb 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -77,6 +77,7 @@"remix-flat-routes": "^0.6.5","resend": "^3.1.0","spin-delay": "2.0.1",+ "stripe": "^18.3.0","tailwind-merge": "^2.2.1","tailwindcss-animate": "^1.0.7","zod": "^3.24.1",@@ -109,9 +110,11 @@"build": "remix vite:build","clean": "rimraf .cache .turbo node_modules dist build","dev": "run-p dev:remix dev:trigger",+ "dev:novu": "npx novu@latest dev --port 3000","dev:remix": "remix vite:dev","dev:trigger": "npx --yes [email protected] dev",- "dev:novu": "npx novu@latest dev --port 3000",+ "dev:stripe": "tsx ./stripe.dev.ts",+ "register:stripe": "tsx ./stripe.register.ts","sync:novu": "npx novu@latest sync ","lint": "TIMING=1 eslint \"app/**/*.ts*\"","start": "remix-serve ./build/server/index.js",diff --git a/apps/erp/stripe.dev.ts b/apps/erp/stripe.dev.tsnew file mode 100644index 0000000000..56e18cb121--- /dev/null+++ b/apps/erp/stripe.dev.ts@@ -0,0 +1,72 @@+import { spawn } from "child_process";+import { config } from "dotenv";+import type Stripe from "stripe";++config();++const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;+if (!STRIPE_SECRET_KEY) {+ throw new Error("STRIPE_SECRET_KEY is required");+}++const events: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [+ "checkout.session.completed",+ "customer.subscription.created",+ "customer.subscription.updated",+ "customer.subscription.deleted",+ "customer.subscription.paused",+ "customer.subscription.resumed",+ "customer.subscription.pending_update_applied",+ "customer.subscription.pending_update_expired",+ "customer.subscription.trial_will_end",+ "invoice.paid",+ "invoice.payment_failed",+ "invoice.payment_action_required",+ "invoice.upcoming",+ "invoice.marked_uncollectible",+ "invoice.payment_succeeded",+ "payment_intent.succeeded",+ "payment_intent.payment_failed",+ "payment_intent.canceled",+];++console.log("🔄 Setting up Stripe webhook endpoint...");+const url = `https://${process.env.VERCEL_URL}/api/stripe`;++if (!url.includes("localhost:")) {+ throw new Error("Running in production mode");+}+console.log("🔄 Running in local development mode");+console.log("🔄 Starting Stripe CLI webhook forwarder...");++const stripeProcess = spawn("stripe", [+ "listen",+ "--events",+ events.join(","),+ "--forward-to",+ url,+]);++stripeProcess.stdout.on("data", (data) => {+ console.log(`${data}`);+ if (data.toString().includes("Ready!")) {+ console.log("✅ Stripe CLI webhook forwarder is ready");+ }+});++stripeProcess.stderr.on("data", (data) => {+ console.error(`${data}`);+});++stripeProcess.on("close", (code) => {+ if (code !== 0) {+ console.error(`❌ Stripe CLI webhook forwarder exited with code ${code}`);+ process.exit(1);+ }+});++// Keep the process running+process.on("SIGINT", () => {+ stripeProcess.kill();+ process.exit(0);+});diff --git a/apps/erp/stripe.register.ts b/apps/erp/stripe.register.tsnew file mode 100644index 0000000000..f58398c667--- /dev/null+++ b/apps/erp/stripe.register.ts@@ -0,0 +1,115 @@+import Stripe from "stripe";++import { config } from "dotenv";+config();++const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;+const VERCEL_URL = process.env.VERCEL_URL;++if (!STRIPE_SECRET_KEY) {+ console.error("❌ STRIPE_SECRET_KEY is required");+ process.exit(1);+}++if (!VERCEL_URL) {+ console.error("❌ VERCEL_URL is required");+ process.exit(1);+}++// Initialize Stripe+const stripe = new Stripe(STRIPE_SECRET_KEY, {+ apiVersion: "2025-06-30.basil",+});++// Define the events to listen for (same as in stripe.dev.ts)+const events: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [+ "checkout.session.completed",+ "customer.subscription.created",+ "customer.subscription.updated",+ "customer.subscription.deleted",+ "customer.subscription.paused",+ "customer.subscription.resumed",+ "customer.subscription.pending_update_applied",+ "customer.subscription.pending_update_expired",+ "customer.subscription.trial_will_end",+ "invoice.paid",+ "invoice.payment_failed",+ "invoice.payment_action_required",+ "invoice.upcoming",+ "invoice.marked_uncollectible",+ "invoice.payment_succeeded",+ "payment_intent.succeeded",+ "payment_intent.payment_failed",+ "payment_intent.canceled",+];++// const webhookUrl = `https://${VERCEL_URL}/api/webhook/stripe`;+const webhookUrl = `https://app.carbonos.dev/api/webhook/stripe`;+if (webhookUrl.includes("localhost")) {+ throw new Error("Cannot register webhook in local development mode");+}++async function registerWebhook() {+ console.log(`🔄 Registering Stripe webhook for ${webhookUrl}...`);++ try {+ // First, list existing webhooks to avoid duplicates+ const existingEndpoints = await stripe.webhookEndpoints.list();++ // Check if we already have a webhook for this URL+ const existingEndpoint = existingEndpoints.data.find(+ (endpoint) => endpoint.url === webhookUrl+ );++ if (existingEndpoint) {+ console.log(`ℹ️ Webhook already exists for ${webhookUrl}`);+ console.log(`ℹ️ Webhook ID: ${existingEndpoint.id}`);+ console.log(+ `ℹ️ Updating webhook to ensure it has the correct event types...`+ );++ // Update the existing webhook with the current event types+ const updatedEndpoint = await stripe.webhookEndpoints.update(+ existingEndpoint.id,+ {+ enabled_events: events,+ }+ );++ console.log(`✅ Webhook updated successfully!`);+ return updatedEndpoint;+ }++ // Create a new webhook endpoint+ const endpoint = await stripe.webhookEndpoints.create({+ url: webhookUrl,+ enabled_events: events,+ description: `Webhook for ${VERCEL_URL}`,+ });++ console.log(`✅ Webhook registered successfully!`);+ console.log(`ℹ️ Webhook ID: ${endpoint.id}`);+ console.log(`ℹ️ Webhook Secret: ${endpoint.secret}`);+ console.log(`+⚠️ IMPORTANT: Add this webhook secret to your environment variables:+STRIPE_WEBHOOK_SECRET=${endpoint.secret}+`);++ return endpoint;+ } catch (error) {+ console.error(`❌ Error registering webhook:`, error);+ throw error;+ }+}++registerWebhook()+ .then(() => {+ console.log(`+🎉 All done! Your Stripe webhook is now registered.+📝 Remember to add the webhook secret to your Vercel environment variables.+`);+ })+ .catch((error) => {+ console.error(`❌ Failed to register webhook:`, error);+ process.exit(1);+ });diff --git a/package-lock.json b/package-lock.jsonindex 728d08d688..bab3a4dc88 100644--- a/package-lock.json+++ b/package-lock.json@@ -107,6 +107,7 @@"remix-flat-routes": "^0.6.5","resend": "^3.1.0","spin-delay": "2.0.1",+ "stripe": "^18.3.0","tailwind-merge": "^2.2.1","tailwindcss-animate": "^1.0.7","zod": "^3.24.1",@@ -31977,6 +31978,25 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/stripe": {+ "version": "18.3.0",+ "resolved": "https://registry.npmjs.org/stripe/-/stripe-18.3.0.tgz",+ "integrity": "sha512-FkxrTUUcWB4CVN2yzgsfF/YHD6WgYHduaa7VmokCy5TLCgl5UNJkwortxcedrxSavQ8Qfa4Ir4JxcbIYiBsyLg==",+ "dependencies": {+ "qs": "^6.11.0"+ },+ "engines": {+ "node": ">=12.*"+ },+ "peerDependencies": {+ "@types/node": ">=12.x.x"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ }+ }+ },"node_modules/style-to-object": {"version": "0.4.4","resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-0.4.4.tgz",diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.tsindex 9ac212fbf4..323c08804c 100644--- a/packages/auth/src/config/env.ts+++ b/packages/auth/src/config/env.ts@@ -24,6 +24,8 @@ declare global {SESSION_SECRET: string;SESSION_KEY: string;SESSION_ERROR_KEY: string;+ STRIPE_SECRET_KEY: string;+ STRIPE_WEBHOOK_SECRET: string;SUPABASE_ANON_KEY: string;SUPABASE_URL: string;SUPABASE_SERVICE_ROLE_KEY: string;@@ -84,6 +86,8 @@ export const SUPABASE_SERVICE_ROLE_KEY = getEnv("SUPABASE_SERVICE_ROLE_KEY");export const SESSION_SECRET = getEnv("SESSION_SECRET");export const SESSION_KEY = "auth";export const SESSION_ERROR_KEY = "error";+export const STRIPE_SECRET_KEY = getEnv("STRIPE_SECRET_KEY");+export const STRIPE_WEBHOOK_SECRET = getEnv("STRIPE_WEBHOOK_SECRET");export const SESSION_MAX_AGE = 60 * 60 * 24 * 7; // 7 days;export const REFRESH_ACCESS_TOKEN_THRESHOLD = 60 * 10; // 10 minutes left before token expiresexport const VERCEL_URL = getEnv("VERCEL_URL", { isSecret: false });diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 946a0a9118..4322c3a930 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -40767,6 +40767,9 @@ export default {{$ref: "#/parameters/rowFilter.company.slackChannel",},+ {+ $ref: "#/parameters/rowFilter.company.ownerId",+ },{$ref: "#/parameters/select",},@@ -40886,6 +40889,9 @@ export default {{$ref: "#/parameters/rowFilter.company.slackChannel",},+ {+ $ref: "#/parameters/rowFilter.company.ownerId",+ },{$ref: "#/parameters/preferReturn",},@@ -40959,6 +40965,9 @@ export default {{$ref: "#/parameters/rowFilter.company.slackChannel",},+ {+ $ref: "#/parameters/rowFilter.company.ownerId",+ },{$ref: "#/parameters/body.company",},@@ -76162,6 +76171,12 @@ 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",},@@ -103263,6 +103278,12 @@ 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 d4a91baa2a..491337b943 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -1982,6 +1982,7 @@ export type Database = {logoLight: string | nulllogoLightIcon: string | nullname: string+ ownerId: string | nullphone: string | nullpostalCode: string | nullslackChannel: string | null@@ -2004,6 +2005,7 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname: string+ ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2026,6 +2028,7 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname?: string+ ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2077,6 +2080,41 @@ 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: {diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d4a91baa2a..491337b943 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -1982,6 +1982,7 @@ export type Database = {logoLight: string | nulllogoLightIcon: string | nullname: string+ ownerId: string | nullphone: string | nullpostalCode: string | nullslackChannel: string | null@@ -2004,6 +2005,7 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname: string+ ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2026,6 +2028,7 @@ export type Database = {logoLight?: string | nulllogoLightIcon?: string | nullname?: string+ ownerId?: string | nullphone?: string | nullpostalCode?: string | nullslackChannel?: string | null@@ -2077,6 +2080,41 @@ 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: {diff --git a/packages/database/supabase/migrations/20250702170717_self-signup.sql b/packages/database/supabase/migrations/20250702170717_self-signup.sqlnew file mode 100644index 0000000000..ed4d0c07e7--- /dev/null+++ b/packages/database/supabase/migrations/20250702170717_self-signup.sql@@ -0,0 +1 @@+ALTER TABLE "company" ADD COLUMN "ownerId" TEXT REFERENCES "user"("id") ON DELETE SET NULL;\ No newline at end of file