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
@carbon/stripe
Stripe billing integration — checkout, subscriptions, webhooks, and customer sync. Cloud edition only.
Always
- Route all subscription state writes through
syncStripeDataToKV()— it's the single writer ofcompanyPlanfrom Stripe; both webhook and GET re-sync funnel through it - Use
normalizePlanId()before comparing plans — DB stores partner tiers asPARTNER-300/400/500; normalize collapses ontoPlan.Partner - Query
companyPlanby.eq("id", companyId)— theidcolumn IS the company id (not a generatedid('cplan')) - Guard for null
stripeclient —stripeisnullwhenSTRIPE_SECRET_KEYis unset (non-Cloud); all functions must handle this
Ask First
- Adding new Stripe webhook event handlers (coordinate with
processStripeEventflow) - Changing plan catalog (
plantable seeds) or price IDs - Modifying the bypass mechanism (
STRIPE_BYPASS_COMPANY_IDS/USER_IDS)
Never
- Add subscription-status logic outside
syncStripeDataToKV— it's the one source of truth - Commit real Stripe price IDs or secrets — use test-mode overrides from
database/src/seed/stripe.ts - Skip signature verification in the webhook handler
Validation Commands
pnpm --filter @carbon/stripe typecheck # tsc --noEmit
pnpm --filter @carbon/stripe dev:stripe # local Stripe listener (dev)
Key Patterns
- Exports:
@carbon/stripe/stripe.server(platform billing),@carbon/stripe/connect.server(Connect accounts, invoicing, Connect webhooks),@carbon/stripe/connect.constants,@carbon/stripe/send-sales-invoice.server(the send of a posted sales invoice, below) — all server-only — plus@carbon/stripe/connect-invoice, the pure line mapping (toStripeInvoiceLines,expectedConnectInvoiceTotal, no client or env), tested inpackages/jobs/src/invoicing/stripe-invoice-lines.test.ts - Send a posted sales invoice:
sendPostedSalesInvoiceViaStripe(send-sales-invoice.server.ts) is the ONE send, shared by the ERP post operation (postSalesInvoice,invoicing.server.ts) and invoice automation (sendPostedInvoiceViaStripein@carbon/jobssrc/invoicing/automate-invoice.ts, thePost and Send via Stripemode). The caller resolves and links the Stripe customer first. The mapping write is injected aslinkStripeInvoice, so this package never depends on@carbon/ee. It throws when the invoice cannot be read, created, sent or linked; after the send, storing the PDF and writing the payment link to the notes are best-effort (a retry would create a SECOND Stripe invoice). Same file:getStripeConnectAccountId(null until onboarding can accept charges —activealone is not enough),getLinkedStripeCustomerId,toStripeInvoiceLines(re-exported fromconnect-invoice),STRIPE_CONNECT_INTEGRATION - Redis cache: subscription state cached by customer ID;
companyPlanis the durable mirror - GTM forwarding:
gtm-events.server.tsforwards invoice events to Google Tag Manager - User-based pricing:
updateSubscriptionQuantityForCompany()syncs active user count (excludes@carbon.ms) - Stripe API version:
2025-06-30.basilon the shared v1stripeclient (2026-07-29.dahliaon the v2stripeConnectclient used for account management). On basil,invoice.charge/invoice.payment_intentno longer exist — payments hang offinvoice.payments(seegetConnectInvoicePaymentDetails) - Two webhook endpoints, two secrets: the platform endpoint
(
/api/webhook/stripe,STRIPE_WEBHOOK_SECRET, verified insideprocessStripeEvent) and the Connect endpoint (/api/webhook/stripe-connect,STRIPE_CONNECT_WEBHOOK_SECRET, verified byconstructConnectWebhookEvent). Connected-account events carryevent.account; verifying one against the wrong secret always fails - Money conversion:
toStripeAmount/fromStripeAmounthandle zero- and three-decimal currencies — never hand-roll* 100. Per-unit prices go through the SDK's brandedStripe.Decimal(unit_amount_decimal/quantity_decimalareDecimal, notstring), never a rounded minor-unit integer - Sales invoice → Stripe invoice:
createAndSendConnectInvoicemirrors thesalesInvoicesview's arithmetic, which is the only definition of what a Carbon invoice is worth, in the INVOICE currency:toStripeInvoiceLinesreads the line'sconverted*columns (the unprefixed ones are base currency), and the headersalesInvoiceShipment.shippingCostis converted withtoDocumentAmountat the currency'sdecimalPlaces. One Carbon line becomes up to four Stripe items (unitPrice × quantity,addOnCost,shippingCost— all taxable — plus an untaxednonTaxableAddOnCost). The line discount (discountPercent, a fraction) is applied to the merchandise item only:toStripeInvoiceLinessends the NET unit priceconvertedNetUnitPriceunrounded and says "(20% off)" in the description; add-ons and shipping go at full price, and Stripe coupons are not used (a coupon discounts the whole invoice), andsalesInvoiceShipment.shippingCostis a fifth, untaxed, invoice-level item.setupPriceis in neither the view's subtotal nor its tax base, so it is not billed.salesInvoiceLine.taxPercentis a FRACTION in [0,1] (a column CHECK) and must be ×100 for Stripe'spercentage; rates are looked-up-or-created per connected account byresolveConnectTaxRateId. Before finalizing, the draft's Stripe-computed total is reconciled againstexpectedConnectInvoiceTotaland the draft is deleted rather than sent on a mismatch beyond per-item rounding. Every Stripe write of the send carries an idempotency key derived fromConnectInvoiceInput.idempotencyKey(carbon-invoice-<account>-<invoiceId>;-item-<n>,-finalize,-send), so a retry after Stripe succeeded replays the same invoice instead of creating a second one. Stripe keeps a key for 24 hours and refuses a reused key whose parameters changed, so the send's parameters must not move with the clock: the due and issue dates are decided on whole company calendar days (stripeDueDate/stripeEffectiveDateinconnect-invoice.ts— a due date on or before today, and an issue date of today or later, are left unset, never replaced with "now"). A retry that straddles the company's midnight can still change them; Stripe then refuses it (a safe failure, never a duplicate) until the key expires - Connect customers:
upsertConnectCustomer(create/update),retrieveConnectCustomer(null on missing ORdeleted, so a stale mapping degrades instead of throwing),findConnectCustomersByEmail(customers.list, NOTcustomers.search— search lags indexing and would duplicate a just-created customer;limit: 2so callers can detect ambiguity). Every call passes{ stripeAccount }; a platform-scoped call lands on the wrong account.invoice_prefixandtax_id_dataare create-only (tax_id_datais absent fromCustomerUpdateParamsentirely — changing tax ids meanscreateTaxId/deleteTaxId).ConnectCustomerInput.taxExemptis already in Stripe's vocabulary (none/exempt/reverse); interpreting Carbon'scustomerTaxpair is the ERP's job, inapps/erp/app/modules/invoicing/stripe-customer.mapper.ts
Cross-References
.claude/rules/billing-system.md— full billing architecturepackages/ee/src/plan.ts+plan.server.ts— feature/plan gating (FEATURE_PLANS)apps/erp/app/routes/api+/webhook.stripe.ts— platform webhook routeapps/erp/app/routes/api+/webhook.stripe-connect.ts— Connect webhook routepackages/ee/src/stripe-connect/payment.server.ts(exported as@carbon/ee/stripe-connect.server) —recordStripeConnectPayment, the Connect payment → Carbonpaymentrecorderpackages/database/supabase/migrations/*billing*.sql— schema