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
refactor: move lib to shared package
Brad Barbinfd73db5e53c8
diff --git a/README.md b/README.mdindex 2495a895db..bf71211cef 100644--- a/README.md+++ b/README.md@@ -73,6 +73,7 @@ The monorepo follows the Turborepo convention of grouping packages into one of t| `@carbon/logger` | Shared logger used across apps || `@carbon/react` | Shared web-based UI components || `@carbon/kv` | Redis cache client |+| `@carbon/lib` | Third-party client libraries (slack, resend, stripe) || `@carbon/tsconfig` | Shared, extendable tsconfig configuration used across apps and packages || `@carbon/utils` | Shared utility functions used across apps and packages |diff --git a/apps/erp/app/routes/api+/webhook.stripe.ts b/apps/erp/app/routes/api+/webhook.stripe.tsindex 3c72e82ae0..d4bec4104b 100644--- a/apps/erp/app/routes/api+/webhook.stripe.ts+++ b/apps/erp/app/routes/api+/webhook.stripe.ts@@ -1,11 +1,11 @@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";+} from "@carbon/lib/stripe.server";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";+import { json, redirect } from "@vercel/remix";import { path } from "~/utils/path";export async function loader({ request }: LoaderFunctionArgs) {diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsxindex 4dbe188798..fd56471df4 100644--- a/apps/erp/app/routes/onboarding+/_layout.tsx+++ b/apps/erp/app/routes/onboarding+/_layout.tsx@@ -5,9 +5,9 @@ import { getLocationsList } from "~/modules/resources";import { getCompany } from "~/modules/settings";import { onboardingSequence, path } from "~/utils/path";+import { getStripeCustomerByCompanyId } from "@carbon/lib/stripe.server";import { VStack } from "@carbon/react";import type { ShouldRevalidateFunction } from "@remix-run/react";-import { getStripeCustomerByCompanyId } from "~/lib/stripe.server";export const shouldRevalidate: ShouldRevalidateFunction = () => true;diff --git a/apps/erp/app/routes/onboarding+/plan.tsx b/apps/erp/app/routes/onboarding+/plan.tsxindex d54aedeb40..194768933c 100644--- a/apps/erp/app/routes/onboarding+/plan.tsx+++ b/apps/erp/app/routes/onboarding+/plan.tsx@@ -1,5 +1,6 @@import { getCarbonServiceRole, getUser } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { getCheckoutUrl } from "@carbon/lib/stripe.server";import {Badge,Button,@@ -16,7 +17,6 @@ import { Form, useFetcher, useLoaderData } from "@remix-run/react";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, getPlans, insertCompanyPlan } from "~/modules/settings";import { path } from "~/utils/path";diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 2fd2fa81e5..45b9484853 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 { getStripeCustomerByCompanyId } from "@carbon/lib/stripe.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 = ({diff --git a/apps/erp/app/routes/x+/feedback.tsx b/apps/erp/app/routes/x+/feedback.tsxindex 6b47523a07..41a3a51420 100644--- a/apps/erp/app/routes/x+/feedback.tsx+++ b/apps/erp/app/routes/x+/feedback.tsx@@ -1,8 +1,8 @@import { getCarbonServiceRole, SUPABASE_URL } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { validator } from "@carbon/form";+import { getSlackClient } from "@carbon/lib/slack.server";import { json, type ActionFunctionArgs } from "@vercel/remix";-import { getSlackClient } from "~/lib/slack.server";import { feedbackValidator } from "~/modules/shared";export const config = {diff --git a/apps/erp/app/routes/x+/users+/customers.new.tsx b/apps/erp/app/routes/x+/users+/customers.new.tsxindex 30952755bd..f7b9f21771 100644--- a/apps/erp/app/routes/x+/users+/customers.new.tsx+++ b/apps/erp/app/routes/x+/users+/customers.new.tsx@@ -3,11 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";+import { resend } from "@carbon/lib/resend.server";import { render } from "@react-email/components";import type { ActionFunctionArgs } from "@vercel/remix";import { redirect } from "@vercel/remix";import { nanoid } from "nanoid";-import { resend } from "~/lib/resend.server";import {CreateCustomerModal,createCustomerAccountValidator,diff --git a/apps/erp/app/routes/x+/users+/employees.new.tsx b/apps/erp/app/routes/x+/users+/employees.new.tsxindex 73c54a8ad7..6d49f17f86 100644--- a/apps/erp/app/routes/x+/users+/employees.new.tsx+++ b/apps/erp/app/routes/x+/users+/employees.new.tsx@@ -3,12 +3,12 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";+import { resend } from "@carbon/lib/resend.server";import { render } from "@react-email/components";import { useLoaderData } from "@remix-run/react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";import { json, redirect } from "@vercel/remix";import { nanoid } from "nanoid";-import { resend } from "~/lib/resend.server";import {CreateEmployeeModal,createEmployeeValidator,diff --git a/apps/erp/app/routes/x+/users+/resend-invite.tsx b/apps/erp/app/routes/x+/users+/resend-invite.tsxindex 4c8d7602c1..172ff53e2f 100644--- a/apps/erp/app/routes/x+/users+/resend-invite.tsx+++ b/apps/erp/app/routes/x+/users+/resend-invite.tsx@@ -3,12 +3,12 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";+import { resend } from "@carbon/lib/resend.server";import { render } from "@react-email/components";import { tasks } from "@trigger.dev/sdk/v3";import type { ActionFunctionArgs } from "@vercel/remix";import { json } from "@vercel/remix";import { nanoid } from "nanoid";-import { resend } from "~/lib/resend.server";import { resendInviteValidator } from "~/modules/users";export const config = { runtime: "nodejs" };diff --git a/apps/erp/app/routes/x+/users+/suppliers.new.tsx b/apps/erp/app/routes/x+/users+/suppliers.new.tsxindex 5ed896a101..9bd2912f93 100644--- a/apps/erp/app/routes/x+/users+/suppliers.new.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.new.tsx@@ -3,11 +3,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";+import { resend } from "@carbon/lib/resend.server";import { render } from "@react-email/components";import type { ActionFunctionArgs } from "@vercel/remix";import { redirect } from "@vercel/remix";import { nanoid } from "nanoid";-import { resend } from "~/lib/resend.server";import {CreateSupplierModal,createSupplierAccountValidator,diff --git a/apps/erp/app/trigger/user-admin.ts b/apps/erp/app/trigger/user-admin.tsindex 88926815ea..16e06fe874 100644--- a/apps/erp/app/trigger/user-admin.ts+++ b/apps/erp/app/trigger/user-admin.ts@@ -3,9 +3,9 @@ import { z } from "zod";import { getAppUrl, getCarbonServiceRole } from "@carbon/auth";import { InviteEmail } from "@carbon/documents/email";+import { resend } from "@carbon/lib/resend.server";import { render } from "@react-email/components";import { nanoid } from "nanoid";-import { resend } from "~/lib/resend.server";import { deactivateUser } from "~/modules/users/users.server";import type { Result } from "~/types";diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex ab90761dcb..bbf0c0b0c6 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -8,6 +8,7 @@"@carbon/documents": "*","@carbon/form": "*","@carbon/kv": "*",+ "@carbon/lib": "*","@carbon/notifications": "*","@carbon/react": "*","@carbon/remix": "*",@@ -28,7 +29,6 @@"@remix-run/eslint-config": "~2.11.2","@remix-run/react": "~2.11.2","@remix-run/serve": "~2.11.2",- "@slack/web-api": "~7.6.0","@supabase/functions-js": "2.1.5","@supabase/supabase-js": "^2.40.0","@tailwindcss/container-queries": "^0.1.1",@@ -75,9 +75,7 @@"react-use-measure": "^2.1.1","recharts": "^2.15.0","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",diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex e5623d5665..5cd87ff5ef 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -3,6 +3,7 @@ import {destroyAuthSession,requireAuthSession,} from "@carbon/auth/session.server";+import { getStripeCustomerByCompanyId } from "@carbon/lib/stripe.server";import { SidebarProvider, TooltipProvider, useMount } from "@carbon/react";import type { ShouldRevalidateFunction } from "@remix-run/react";import { Outlet, useLoaderData, useNavigation } from "@remix-run/react";@@ -63,7 +64,7 @@ export async function loader({ request }: LoaderFunctionArgs) {companyId,userId,}),- getCompanyPlan(client, companyId),+ getStripeCustomerByCompanyId(companyId),getLocationsByCompany(client, companyId),getActiveJobCount(client, {employeeId: userId,@@ -71,7 +72,7 @@ export async function loader({ request }: LoaderFunctionArgs) {}),]);- if (!companyPlan.data?.id) {+ if (!companyPlan) {throw redirect(path.to.onboarding);}diff --git a/apps/mes/app/routes/x+/feedback.tsx b/apps/mes/app/routes/x+/feedback.tsxindex bc1593a3fa..6643920f38 100644--- a/apps/mes/app/routes/x+/feedback.tsx+++ b/apps/mes/app/routes/x+/feedback.tsx@@ -1,8 +1,8 @@import { getCarbonServiceRole, SUPABASE_URL } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { validator } from "@carbon/form";+import { getSlackClient } from "@carbon/lib/slack.server";import { json, type ActionFunctionArgs } from "@vercel/remix";-import { getSlackClient } from "~/lib/slack.server";import { feedbackValidator } from "~/services/models";export const config = {diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex e73cea1826..4870bba8f4 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -7,6 +7,7 @@"@carbon/documents": "*","@carbon/form": "*","@carbon/kv": "*",+ "@carbon/lib": "*","@carbon/logger": "*","@carbon/react": "*","@carbon/remix": "*",diff --git a/apps/starter/app/routes/x+/_layout.tsx b/apps/starter/app/routes/x+/_layout.tsxindex 57e886a3bb..f6d52a55e7 100644--- a/apps/starter/app/routes/x+/_layout.tsx+++ b/apps/starter/app/routes/x+/_layout.tsx@@ -12,12 +12,10 @@ import {getCompanies,getUser,} from "@carbon/auth";-import { getCompanyPlan } from "@carbon/auth/auth.server";import {destroyAuthSession,requireAuthSession,} from "@carbon/auth/session.server";-import { path } from "~/utils/path";export async function loader({ request }: LoaderFunctionArgs) {const { accessToken, companyId, expiresAt, expiresIn, userId } =@@ -41,11 +39,6 @@ export async function loader({ request }: LoaderFunctionArgs) {throw redirect(getAppUrl());}- const companyPlan = await getCompanyPlan(client, companyId);- if (!companyPlan.data?.id) {- throw redirect(path.to.onboarding);- }-return json({session: {accessToken,diff --git a/package-lock.json b/package-lock.jsonindex bab3a4dc88..c62c063160 100644--- a/package-lock.json+++ b/package-lock.json@@ -38,6 +38,7 @@"@carbon/documents": "*","@carbon/form": "*","@carbon/kv": "*",+ "@carbon/lib": "*","@carbon/notifications": "*","@carbon/react": "*","@carbon/remix": "*",@@ -58,7 +59,6 @@"@remix-run/eslint-config": "~2.11.2","@remix-run/react": "~2.11.2","@remix-run/serve": "~2.11.2",- "@slack/web-api": "~7.6.0","@supabase/functions-js": "2.1.5","@supabase/supabase-js": "^2.40.0","@tailwindcss/container-queries": "^0.1.1",@@ -105,9 +105,7 @@"react-use-measure": "^2.1.1","recharts": "^2.15.0","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",@@ -185,6 +183,7 @@"@carbon/documents": "*","@carbon/form": "*","@carbon/kv": "*",+ "@carbon/lib": "*","@carbon/logger": "*","@carbon/react": "*","@carbon/remix": "*",@@ -1735,6 +1734,10 @@"resolved": "packages/kv","link": true},+ "node_modules/@carbon/lib": {+ "resolved": "packages/lib",+ "link": true+ },"node_modules/@carbon/logger": {"resolved": "packages/logger","link": true@@ -35830,6 +35833,31 @@"typescript": "^5.2.2"}},+ "packages/lib": {+ "name": "@carbon/lib",+ "version": "*",+ "dependencies": {+ "@carbon/auth": "*",+ "@carbon/database": "*",+ "@carbon/kv": "*",+ "@slack/web-api": "~7.6.0",+ "@supabase/supabase-js": "^2.40.0",+ "resend": "^3.1.0",+ "stripe": "^18.3.0"+ },+ "devDependencies": {+ "@carbon/logger": "*",+ "@carbon/tsconfig": "*",+ "@types/node": "^20.12.5",+ "dotenv": "16.3.1",+ "eslint": "^8.23.1",+ "eslint-config-carbon": "*",+ "rimraf": "^5.0.5",+ "tsup": "^6.5.0",+ "tsx": "^4.13.2",+ "typescript": "^5.2.2"+ }+ },"packages/logger": {"name": "@carbon/logger","version": "*",diff --git a/packages/lib/.eslintrc.js b/packages/lib/.eslintrc.jsnew file mode 100644index 0000000000..1308cba140--- /dev/null+++ b/packages/lib/.eslintrc.js@@ -0,0 +1,4 @@+module.exports = {+ root: true,+ extends: ["carbon"],+};diff --git a/packages/lib/package.json b/packages/lib/package.jsonnew file mode 100644index 0000000000..e440c76772--- /dev/null+++ b/packages/lib/package.json@@ -0,0 +1,37 @@+{+ "name": "@carbon/lib",+ "dependencies": {+ "@carbon/auth": "*",+ "@carbon/database": "*",+ "@carbon/kv": "*",+ "@slack/web-api": "~7.6.0",+ "@supabase/supabase-js": "^2.40.0",+ "resend": "^3.1.0",+ "stripe": "^18.3.0"+ },+ "devDependencies": {+ "@carbon/logger": "*",+ "@carbon/tsconfig": "*",+ "@types/node": "^20.12.5",+ "dotenv": "16.3.1",+ "eslint": "^8.23.1",+ "eslint-config-carbon": "*",+ "rimraf": "^5.0.5",+ "tsup": "^6.5.0",+ "tsx": "^4.13.2",+ "typescript": "^5.2.2"+ },+ "exports": {+ "./resend.server": "./src/resend.server.ts",+ "./slack.server": "./src/slack.server.ts",+ "./stripe.server": "./src/stripe.server.ts"+ },+ "private": true,+ "scripts": {+ "clean": "rimraf .turbo node_modules dist",+ "dev": "tsup --watch",+ "lint": "TIMING=1 eslint \"src/**/*.ts*\""+ },+ "sideEffects": false,+ "version": "*"+}diff --git a/apps/erp/app/lib/resend.server.ts b/packages/lib/src/resend.server.tssimilarity index 100%rename from apps/erp/app/lib/resend.server.tsrename to packages/lib/src/resend.server.tsdiff --git a/apps/erp/app/lib/slack.server.ts b/packages/lib/src/slack.server.tssimilarity index 100%rename from apps/erp/app/lib/slack.server.tsrename to packages/lib/src/slack.server.tsdiff --git a/apps/erp/app/lib/stripe.server.ts b/packages/lib/src/stripe.server.tssimilarity index 89%rename from apps/erp/app/lib/stripe.server.tsrename to packages/lib/src/stripe.server.tsindex 4adf9f2e39..84796473a0 100644--- a/apps/erp/app/lib/stripe.server.ts+++ b/packages/lib/src/stripe.server.ts@@ -1,13 +1,9 @@-import { getCarbonServiceRole } from "@carbon/auth";+import { getAppUrl, getCarbonServiceRole } from "@carbon/auth";+import type { Database } from "@carbon/database";import { redis } from "@carbon/kv";-import { redirect } from "@vercel/remix";+import type { SupabaseClient } from "@supabase/supabase-js";import { Stripe } from "stripe";import { z } from "zod";-import {- getPlanById,- updateCompanyPlan,-} from "~/modules/settings/settings.service";-import { path } from "~/utils/path";if (!process.env.STRIPE_SECRET_KEY) {throw new Error("process.env.STRIPE_SECRET_KEY not defined");@@ -42,26 +38,28 @@ 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);-}--const KvStripeUserSchema = z.string().nullish();--export async function getStripeCustomerId(companyId: string) {- return KvStripeUserSchema.parse(- await redis.get(`stripe:company:${companyId}`)- );-}+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];export async function createStripeCustomer({userId,@@ -102,134 +100,29 @@ export async function createStripeCustomer({}}-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");- }-- console.log({ customer });-- try {- await syncStripeDataToKV(customer);- } catch (error) {- console.error("Error processing webhook:", error);- throw new Error("Stripe webhook handler failed");- }+function getPlanById(client: SupabaseClient<Database>, planId: string) {+ return client.from("plan").select("*").eq("id", planId).single();}-export async function syncStripeDataToKV(customerId: string) {- const key = `stripe:customer:${customerId}`;- console.log({ key });-- 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);+export async function getStripeCustomerByCompanyId(companyId: string) {+ const customerId = await getStripeCustomerId(companyId);+ if (!customerId) {return null;}+ return getStripeCustomer(customerId);+}- 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,- });-- 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;+export async function getStripeCustomer(customerId: string) {+ const customer = await redis.get(`stripe:customer:${customerId}`);+ return KvStripeCustomerSchema.nullish().parse(customer);}-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];+const KvStripeUserSchema = z.string().nullish();-function isAllowedEventType<TEvent extends Stripe.Event>(- event: TEvent-): event is TEvent & { type: AllowedEventType } {- return allowedEventTypes.includes(event.type as AllowedEventType);+export async function getStripeCustomerId(companyId: string) {+ return KvStripeUserSchema.parse(+ await redis.get(`stripe:company:${companyId}`)+ );}function getStripeWebhookEvent({@@ -289,8 +182,8 @@ export async function getCheckoutUrl({},],mode: "subscription",- success_url: `${process.env.VERCEL_URL}${path.to.api.webhookStripe}`,- cancel_url: `${process.env.VERCEL_URL}${path.to.api.webhookStripe}`,+ success_url: `${getAppUrl()}/api/webhook/stripe`,+ cancel_url: `${getAppUrl()}/api/webhook/stripe`,payment_method_types: ["card", "us_bank_account", "cashapp"],metadata: {companyId,@@ -304,7 +197,7 @@ export async function getCheckoutUrl({return checkoutSession.url;}-export async function redirectToBillingPortal({+export async function getBillingPortalRedirectUrl({companyId,}: {companyId: string;@@ -316,14 +209,119 @@ export async function redirectToBillingPortal({const portalSession = await stripe.billingPortal.sessions.create({customer: customerId,- return_url: `${process.env.VERCEL_URL}${path.to.settings}`,+ return_url: `${getAppUrl()}/settings`,});if (!portalSession.url) {throw new Error("Failed to create portal session");}- redirect(portalSession.url);+ return portalSession.url;+}++function isAllowedEventType<TEvent extends Stripe.Event>(+ event: TEvent+): event is TEvent & { type: AllowedEventType } {+ return allowedEventTypes.includes(event.type as AllowedEventType);+}++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");+ }++ console.log({ customer });++ 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}`;+ console.log({ key });++ 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,+ });++ 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(),+ }),+ ]);++ if (companyPlan.error) {+ throw new Error("Failed to update company plan");+ }+ }++ return subData;}export async function updateActiveUsers({@@ -337,3 +335,19 @@ export async function updateActiveUsers({quantity: activeUsers,});}++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);+}diff --git a/packages/lib/tsconfig.json b/packages/lib/tsconfig.jsonnew file mode 100644index 0000000000..fc3043b055--- /dev/null+++ b/packages/lib/tsconfig.json@@ -0,0 +1,10 @@+{+ "compilerOptions": {+ "lib": ["ES2015"],+ "outDir": "./dist",+ "rootDir": "./src"+ },+ "exclude": ["node_modules"],+ "extends": "@carbon/tsconfig/base.json",+ "include": ["src"]+}diff --git a/packages/lib/tsup.config.ts b/packages/lib/tsup.config.tsnew file mode 100644index 0000000000..971be238af--- /dev/null+++ b/packages/lib/tsup.config.ts@@ -0,0 +1,12 @@+import { defineConfig } from "tsup";++const isProduction = process.env.VERCEL_ENV === "production";++export default defineConfig({+ clean: true,+ dts: true,+ entry: ["src/index.ts"],+ format: ["cjs", "esm"],+ minify: isProduction,+ sourcemap: true,+});