Skip to content

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.

feat: create script for migrating stripe customers

Brad Barbin06abbde0796f
diff --git a/.gitignore b/.gitignore
index db6bbe7891..420b5e02e2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,8 @@ server/dist
public/dist
vite.config.ts.timestamp*
+scripts/migrations/data
+
# local env files
.env
.env.local
diff --git a/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx b/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx
index 17f2ebcdb5..993dc5757e 100644
--- a/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx
+++ b/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx
@@ -38,7 +38,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
try {
const { object } = await generateObject<Record<string, string>>({
- model: openai("gpt-4o-mini"),
+ model: openai("gpt-4o"),
schema,
prompt: `
The following columns are the headings from a CSV import file for importing a ${table}.
diff --git a/packages/database/supabase/migrations/20250708192443_inventory-by-location.sql b/packages/database/supabase/migrations/20250708192443_inventory-by-location.sql
new file mode 100644
index 0000000000..dc3b458c60
--- /dev/null
+++ b/packages/database/supabase/migrations/20250708192443_inventory-by-location.sql
@@ -0,0 +1,138 @@
+
+DROP FUNCTION IF EXISTS get_inventory_quantities;
+CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT)
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "quantityOnHand" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityOnProductionDemand" NUMERIC
+ ) AS $$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId",
+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ GROUP BY pol."itemId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ GROUP BY sol."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY jm."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY j."itemId"
+ ),
+ item_ledgers AS (
+ SELECT "itemId", SUM("quantity") AS "quantityOnHand"
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ GROUP BY "itemId"
+ )
+
+SELECT
+ i."id",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ m."materialSubstanceId",
+ m."materialFormId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"
+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"
+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"
+ LEFT JOIN material m ON i."readableId" = m."id"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id;
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/scripts/migrations/part-revision-merges.ts b/scripts/migrations/part-revision-merges.ts
index 27dee5a964..d8abb2a300 100644
--- a/scripts/migrations/part-revision-merges.ts
+++ b/scripts/migrations/part-revision-merges.ts
@@ -6,11 +6,11 @@ import { homedir } from "os";
import { resolve } from "path";
dotenv.config();
-const COMPANY_ID = "cs868u84gfk07v78v9e0";
+const COMPANY_ID = "*****************";
const PROD: boolean = true;
const READ_ONLY: boolean = false;
-const sourceFile = resolve(homedir(), "Downloads/black-cat-july-3.csv");
+const sourceFile = resolve(homedir(), "Downloads/******.csv");
const columns = ["ID", "OLD", "NEW", "REVISION"];
const parser = parse({
diff --git a/scripts/migrations/stripe-customer-migrations.ts b/scripts/migrations/stripe-customer-migrations.ts
new file mode 100644
index 0000000000..c4adfe83ba
--- /dev/null
+++ b/scripts/migrations/stripe-customer-migrations.ts
@@ -0,0 +1,159 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { createClient } from "@supabase/supabase-js";
+import { Redis } from "@upstash/redis";
+import { config } from "dotenv";
+import { Stripe } from "stripe";
+import { z } from "zod";
+import { companies } from "./data/stripe-customers";
+config();
+
+const PROD = true;
+
+const upstashRedisRestUrl = PROD
+ ? process.env.PROD_UPSTASH_REDIS_REST_URL
+ : process.env.UPSTASH_REDIS_REST_URL;
+const upstashRedisRestToken = PROD
+ ? process.env.PROD_UPSTASH_REDIS_REST_TOKEN
+ : process.env.UPSTASH_REDIS_REST_TOKEN;
+
+if (!upstashRedisRestUrl) {
+ throw new Error("UPSTASH_REDIS_REST_URL is not defined");
+}
+
+if (!upstashRedisRestToken) {
+ throw new Error("UPSTASH_REDIS_REST_TOKEN is not defined");
+}
+
+const redis = new Redis({
+ url: upstashRedisRestUrl,
+ token: upstashRedisRestToken,
+});
+
+const supabaseUrl = PROD
+ ? process.env.PROD_SUPABASE_URL
+ : process.env.SUPABASE_URL;
+const supabaseServiceRoleKey = PROD
+ ? process.env.PROD_SUPABASE_SERVICE_ROLE_KEY
+ : process.env.SUPABASE_SERVICE_ROLE_KEY;
+
+if (!supabaseUrl) {
+ throw new Error("SUPABASE_URL is not defined");
+}
+
+if (!supabaseServiceRoleKey) {
+ throw new Error("SUPABASE_SERVICE_ROLE_KEY is not defined");
+}
+
+const stripeSecretKey = PROD
+ ? process.env.PROD_STRIPE_SECRET_KEY!
+ : process.env.STRIPE_SECRET_KEY!;
+
+if (!stripeSecretKey) {
+ throw new Error("STRIPE_SECRET_KEY is not defined");
+}
+
+const client = createClient(supabaseUrl, supabaseServiceRoleKey);
+
+const stripe = new Stripe(stripeSecretKey, {
+ 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(),
+});
+
+(async () => {
+ for await (const company of companies) {
+ console.log(company.name);
+ const customerKey = `stripe:customer:${company.customerId}`;
+ const companyKey = `stripe:company:${company.id}`;
+
+ await redis.set(companyKey, company.customerId);
+
+ const subscription = await getSubscription(company.customerId);
+ if (!subscription) {
+ await redis.del(customerKey);
+ return null;
+ }
+
+ console.log(subscription.id);
+ }
+})();
+
+async function getSubscription(customerId: string) {
+ const subscriptions = await stripe.subscriptions.list({
+ customer: customerId,
+ limit: 1,
+ status: "all",
+ expand: ["data.default_payment_method"],
+ });
+
+ return subscriptions.data[0];
+}
+
+async function getPlanByPriceId(
+ client: SupabaseClient<Database>,
+ priceId: string
+) {
+ return await client
+ .from("plan")
+ .select("*")
+ .eq("stripePriceId", priceId)
+ .single();
+}
+
+async function upsertCompanyPlan(
+ client: SupabaseClient<Database>,
+ companyPlan: {
+ companyId: string;
+ priceId: string;
+ status?: "Active" | "Inactive" | "Canceled";
+ stripeCustomerId?: string;
+ stripeSubscriptionId?: string;
+ subscriptionStartDate?: string;
+ }
+) {
+ 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);
+}