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
Stripe Connect (#1444)
Samay Gandhiad3aea85299c
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex ded866c8d9..46339e8655 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1112,6 +1112,16 @@ canvas hosting Radix popovers/selects.**Applies to:** `packages/database/supabase/functions/get-method/index.ts` (`quoteToQuote`), `apps/erp/app/modules/sales/sales.service.ts` (`deleteQuote`), any insert into `externalLink`.+## An incremental pull-sweep cursor must advance on the SAME field the query filters on++**Context:** The Stripe Connect payment pull sweep (`stripe-connect-pull-sweep.ts`) queried Stripe with `invoices.list({ status: "paid", created: { gte: since } })` but advanced the cursor to `latest status_transitions.paid_at + 1`. An invoice created before the cursor but paid after it (a normal case — invoices are created, then paid later) would never be returned by a future `created`-filtered query once the cursor passed its `paid_at`, so it was permanently skipped with no error, no log, and no retry.++**Problem:** The query filters on one field (`created`) while the cursor tracks a different field (`paid_at`) that moves independently of it. Any record whose "when it changed" timestamp and "when it was created" timestamp can diverge — which is true of nearly all incremental-sync designs (a row's `updated_at` also isn't its `created_at`) — silently falls outside the next window once the cursor advances past its create time but the record itself hasn't changed since.++**Rule:** An incremental cursor MUST advance on the exact field the list query filters on, never a related-but-different timestamp. When the two are genuinely different concerns (created vs. paid, created vs. updated), either filter on the field you actually care about, or carry a trailing lookback window (`pullWindowStart` re-scans `since - CURSOR_LOOKBACK_SECONDS`) so a bounded re-scan catches what a pure cursor would miss — cheap when the record-processing step is idempotent (here, `recordStripeConnectPayment` is idempotent on the Stripe invoice id via a partial unique index, so re-scanning already-recorded invoices is a free no-op). Extract cursor arithmetic into an import-light pure module (`stripe-connect-pull-sweep-cursor.ts`) so the regression is unit-testable without booting Stripe/Inngest/DB.++**Applies to:** `packages/jobs/src/inngest/functions/integrations/*-pull-sweep.ts`, any incremental sync reading `since`/cursor state against an external API's list filter.+## Card lists never get their own scroll region — the page is the only scroll surface**Context:** The Bill of Material / Bill of Process cards were capped at `max-h-[60dvh]` with an internal ScrollArea (PR #1230) so long lists wouldn't grow the page unbounded. Brad asked for the scrollbars to be removed; hiding the bar but keeping the capped region was the wrong reading.diff --git a/.claude/rules/billing-system.md b/.claude/rules/billing-system.mdindex b0c682c0cd..63688df307 100644--- a/.claude/rules/billing-system.md+++ b/.claude/rules/billing-system.md@@ -115,6 +115,9 @@ Env: `STRIPE_BYPASS_COMPANY_IDS`, `STRIPE_BYPASS_USER_IDS` (comma-separated, ser`STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` (both optional — Cloud only),`STRIPE_BYPASS_COMPANY_IDS`, `STRIPE_BYPASS_USER_IDS`. Re-exported from `@carbon/auth`.+`STRIPE_CONNECT_WEBHOOK_SECRET` also lives here but belongs to Stripe **Connect**+(customer payments on connected accounts), not to Carbon's own billing — see+`packages/stripe/src/connect.server.ts` and `webhook.stripe-connect.ts`.## Gotchasdiff --git a/.claude/rules/environment-configuration.md b/.claude/rules/environment-configuration.mdindex c5f90c8d9d..efd240f3c6 100644--- a/.claude/rules/environment-configuration.md+++ b/.claude/rules/environment-configuration.md@@ -71,8 +71,11 @@ secret), `SUPABASE_JWT_SECRET` (optional), plus(`email,google,azure,passkey`; gate via `isAuthProviderEnabled`),`CLOUDFLARE_TURNSTILE_SITE_KEY` / `_SECRET_KEY`, `RATE_LIMIT`.-**Stripe** — `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` (both optional),-`STRIPE_BYPASS_COMPANY_IDS`, `STRIPE_BYPASS_USER_IDS`.+**Stripe** — `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`,+`STRIPE_CONNECT_WEBHOOK_SECRET` (all optional), `STRIPE_BYPASS_COMPANY_IDS`,+`STRIPE_BYPASS_USER_IDS`. The two webhook secrets are distinct: the platform+endpoint (`/api/webhook/stripe`, billing) and the Connect endpoint+(`/api/webhook/stripe-connect`, connected-account events) are signed separately.**Email** — `RESEND_API_KEY`, `RESEND_DOMAIN` (default `carbon.ms`),`DISABLE_RESEND` (short-circuits sends), optional `RESEND_AUDIENCE_ID`.diff --git a/.env.example b/.env.exampleindex 9fae3f9f89..44c7bf001c 100644--- a/.env.example+++ b/.env.example@@ -26,6 +26,7 @@ POSTHOG_PROJECT_PUBLIC_KEY="********************"# StripeSTRIPE_SECRET_KEY="sk_test_*************"STRIPE_WEBHOOK_SECRET="whsec_************"+STRIPE_CONNECT_WEBHOOK_SECRET="whsec_************"# GTM (notifications fan-out)GTM_EVENTS_API_SECRET_KEY=""diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.tsindex 6a6f1c321a..b8dac4fc73 100644--- a/apps/erp/app/modules/invoicing/invoicing.models.ts+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts@@ -200,18 +200,59 @@ export const salesInvoiceValidator = z.object({exchangeRateUpdatedAt: zfd.text(z.string().optional())});+export const stripeCustomerActions = [+ "use-linked",+ "link-existing",+ "create"+] as const;+export const salesInvoicePostValidator = z.object({- notification: z.enum(["Email", "None"]).optional(),+ notification: z.enum(["Email", "Stripe", "None"]).optional(),customerContact: zfd.text(z.string().optional()),- cc: z.array(z.string()).optional()+ cc: z.array(z.string()).optional(),+ // What the user agreed to do with the connected account's customer list.+ stripeCustomerAction: z.enum(stripeCustomerActions).optional(),+ // The customer to link to, when the user picked one Stripe already had.+ stripeCustomerId: zfd.text(z.string().optional()),+ // Supplied only when the selected contact had no email on file.+ stripeContactEmail: zfd.text(+ z.string().email({ message: "Email is invalid" }).optional()+ ),+ // Supplied only when the invoice's own dateDue wouldn't survive+ // clampDueDate (missing, past, or too far out) — see the post modal.+ stripeDueDate: zfd.text(z.string().optional())}).refine(- (data) => (data.notification === "Email" ? data.customerContact : true),+ (data) =>+ data.notification === "Email" || data.notification === "Stripe"+ ? data.customerContact+ : true,{- message: "Customer contact is required for email",+ message: "Customer contact is required",path: ["customerContact"] // path of error}+ )+ // The guard that makes the confirmation step structurally mandatory: with no+ // action there is no code path left that creates a customer on a merchant's+ // account, so a stale or hand-rolled form body cannot skip the dialog.+ .refine(+ (data) =>+ data.notification === "Stripe" ? data.stripeCustomerAction : true,+ {+ message: "Confirm the Stripe customer before posting",+ path: ["stripeCustomerAction"]+ }+ )+ .refine(+ (data) =>+ data.stripeCustomerAction === "link-existing"+ ? data.stripeCustomerId+ : true,+ {+ message: "Select the Stripe customer to link",+ path: ["stripeCustomerId"]+ });export const salesInvoiceShipmentValidator = z.object({diff --git a/apps/erp/app/modules/invoicing/stripe-customer.mapper.ts b/apps/erp/app/modules/invoicing/stripe-customer.mapper.tsnew file mode 100644index 0000000000..66ba1b1c40--- /dev/null+++ b/apps/erp/app/modules/invoicing/stripe-customer.mapper.ts@@ -0,0 +1,116 @@+import type { ConnectCustomerInput } from "@carbon/stripe/connect.server";+// Type-only imports on purpose: they are erased at build, so this module stays+// free of the `~/modules/sales` barrel. Importing it for real would transitively+// pull `@carbon/glossary`'s Lingui macros, which throw outside a configured i18n+// runtime and take plain unit tests of this mapper down with them.+import type {+ getCustomer,+ getCustomerContact,+ getCustomerLocation,+ getCustomerTax+} from "~/modules/sales";++/**+ * Stripe caps a metadata value at 500 characters and rejects the whole request+ * over it — a long tag list would otherwise fail the customer create rather+ * than being quietly trimmed.+ */+const METADATA_VALUE_LIMIT = 500;++export type StripeCustomerSources = {+ customer: NonNullable<Awaited<ReturnType<typeof getCustomer>>["data"]>;+ contact: Awaited<ReturnType<typeof getCustomerContact>>["data"];+ billingLocation: Awaited<ReturnType<typeof getCustomerLocation>>["data"];+ customerTax: Awaited<ReturnType<typeof getCustomerTax>>["data"];+};++function clampMetadata(value: string | null | undefined): string {+ if (!value) return "";+ return value.slice(0, METADATA_VALUE_LIMIT);+}++/**+ * Carbon's `taxExempt` + `taxExemptionReason` → Stripe's single `tax_exempt`.+ *+ * An export sale is zero-rated with the liability shifted to the buyer, which+ * is Stripe's `"reverse"` — not a blanket exemption. Every other Carbon reason+ * (Resale, Government, Nonprofit, Agriculture, Industrial, Medical,+ * Educational, Religious, Other) is an ordinary `"exempt"`.+ */+export function toStripeTaxExempt(+ taxExempt: boolean | null | undefined,+ reason: string | null | undefined+): "none" | "exempt" | "reverse" {+ if (!taxExempt) return "none";+ return reason === "Export" ? "reverse" : "exempt";+}++/**+ * Flatten Carbon's customer graph into Stripe's single-object shape.+ *+ * Pure so the mapping can be tested without a database or a Stripe account.+ * `emailOverride` carries an address the user typed into the post modal for a+ * contact that had none — it has already been written back to `contact.email`+ * by then, but the row in hand is the pre-update read.+ *+ * Returns null when the customer cannot be billed at all (no name, or no email+ * for Stripe to send the invoice to), so the caller has one thing to check.+ */+export function buildStripeCustomerInput(+ sources: StripeCustomerSources,+ emailOverride?: string+): ConnectCustomerInput | null {+ const { customer, contact, billingLocation, customerTax } = sources;++ if (!customer.name) return null;++ const email = emailOverride ?? contact?.contact?.email ?? undefined;+ if (!email) return null;++ // `customerContact` is the join row — the person's details hang off the+ // embedded `contact`, never off the join row itself.+ const person = contact?.contact;+ // The `customers` view derives `phone` from the primary contact already; the+ // selected contact's own numbers are the better answer when it does not.+ const phone =+ customer.phone ?? person?.workPhone ?? person?.mobilePhone ?? undefined;++ // Address fields likewise hang off the embedded `address`, not the+ // `customerLocation` join row. `countryCode` is ISO 3166-1 alpha-2 by+ // construction — it is a foreign key to `country("alpha2")` — so it needs no+ // normalization before Stripe sees it.+ const address = billingLocation?.address+ ? {+ line1: billingLocation.address.addressLine1 ?? undefined,+ line2: billingLocation.address.addressLine2 ?? undefined,+ city: billingLocation.address.city ?? undefined,+ state: billingLocation.address.stateProvince ?? undefined,+ postal_code: billingLocation.address.postalCode ?? undefined,+ country: billingLocation.address.countryCode ?? undefined+ }+ : undefined;++ return {+ name: customer.name,+ email,+ phone,+ website: customer.website,+ readableId: customer.readableId,+ address,+ taxExempt: toStripeTaxExempt(+ customerTax?.taxExempt,+ customerTax?.taxExemptionReason+ ),+ metadata: {+ carbon_customer_id: clampMetadata(customer.id),+ carbon_company_id: clampMetadata(customer.companyId),+ carbon_readable_id: clampMetadata(customer.readableId),+ carbon_status: clampMetadata(customer.status) || "unknown",+ carbon_type: clampMetadata(customer.type) || "unknown",+ // A fraction in [0, 1], not a percent. Carried for traceability only —+ // Stripe computes tax per line item from the invoice's own rates.+ carbon_tax_percent: (customer.taxPercent ?? 0).toString(),+ carbon_tags: clampMetadata(customer.tags?.join(",") ?? "")+ }+ };+}diff --git a/apps/erp/app/modules/invoicing/stripe-customer.server.ts b/apps/erp/app/modules/invoicing/stripe-customer.server.tsnew file mode 100644index 0000000000..d3b5547d40--- /dev/null+++ b/apps/erp/app/modules/invoicing/stripe-customer.server.ts@@ -0,0 +1,330 @@+import type { getCarbonServiceRole } from "@carbon/auth/client.server";+import { createMappingService } from "@carbon/ee/accounting";+import type { ConnectCustomerInput } from "@carbon/stripe/connect.server";+import {+ findConnectCustomersByEmail,+ retrieveConnectCustomer+} from "@carbon/stripe/connect.server";+import {+ getCustomer,+ getCustomerLocation,+ getCustomerPayment,+ getCustomerTax+} from "~/modules/sales";+import { getDatabaseClient } from "~/services/database.server";+import type { StripeCustomerSources } from "./stripe-customer.mapper";+import { buildStripeCustomerInput } from "./stripe-customer.mapper";++type ServiceRole = ReturnType<typeof getCarbonServiceRole>;++export const STRIPE_CONNECT_INTEGRATION = "stripe-connect";++// The pure Carbon → Stripe field mapping lives in its own module so it can be+// unit tested without this file's database and Stripe imports.+export { buildStripeCustomerInput };+export type { StripeCustomerSources };++/**+ * Gather every table a Stripe customer is assembled from.+ *+ * The billing address is NOT "the customer's first location" — Carbon points at+ * it explicitly through `customerPayment.invoiceCustomerLocationId`, which can+ * differ from the shipping location and can even belong to a different customer+ * (bill-to ≠ sold-to). Resolving it any other way bills the wrong address.+ *+ * `customerContactId` is scoped to `customerId = billingCustomerId` (not just+ * `companyId`) — `customerContact` carries no `companyId` column of its own, and+ * `billingCustomerId` is already validated against the invoice's `companyId` by+ * `getBillingCustomerId`. Without this, a caller who knows a contact UUID from+ * another tenant's customer could resolve that contact's email into this Stripe+ * lookup.+ */+export async function resolveStripeCustomerSources(+ serviceRole: ServiceRole,+ companyId: string,+ billingCustomerId: string,+ customerContactId: string+): Promise<StripeCustomerSources | null> {+ const [customer, contact, payment, customerTax] = await Promise.all([+ getCustomer(serviceRole, billingCustomerId, companyId),+ serviceRole+ .from("customerContact")+ .select(+ "*, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, notes)"+ )+ .eq("id", customerContactId)+ .eq("customerId", billingCustomerId)+ .eq("companyId", companyId)+ .single(),+ getCustomerPayment(serviceRole, billingCustomerId, companyId),+ getCustomerTax(serviceRole, billingCustomerId, companyId)+ ]);++ if (!customer.data) return null;++ // `getCustomerLocation` (singular) is the only reader that selects+ // `address.countryCode`; the plural `getCustomerLocations` embeds+ // `country(alpha2, name)` instead and cannot supply Stripe's `address.country`.+ const billingLocationId = payment.data?.invoiceCustomerLocationId;+ const billingLocation = billingLocationId+ ? (await getCustomerLocation(serviceRole, billingLocationId, companyId))+ .data+ : null;++ return {+ customer: customer.data,+ contact: contact.data,+ billingLocation,+ customerTax: customerTax.data+ };+}++/** A Stripe customer, reduced to what the confirmation panel shows. */+export type StripeCustomerSummary = {+ id: string;+ name: string | null;+ email: string | null;+};++/**+ * What posting this invoice through Stripe would do to the connected account.+ *+ * Deliberately a closed union rather than a bag of optional fields: every state+ * demands a different question of the user, and the caller must handle all of+ * them before anything is created on a merchant's live account.+ */+export type StripeCustomerResolution =+ | { state: "unavailable"; message: string }+ | { state: "missing-email"; customerName: string }+ | { state: "linked"; customer: StripeCustomerSummary }+ | { state: "match-found"; matches: StripeCustomerSummary[] }+ | {+ state: "new";+ preview: {+ name: string;+ email: string;+ phone?: string;+ addressLines: string[];+ taxExempt: "none" | "exempt" | "reverse";+ };+ };++function toSummary(customer: {+ id: string;+ name?: string | null;+ email?: string | null;+}): StripeCustomerSummary {+ return {+ id: customer.id,+ name: customer.name ?? null,+ email: customer.email ?? null+ };+}++/**+ * The connected account this company bills through, or null if the+ * integration is not set up or onboarding is not far enough along to accept+ * charges yet.+ *+ * `active` alone is not enough to gate on: the connect callback sets it+ * `true` as soon as a Stripe account exists, before onboarding (and+ * `chargesEnabled`) is complete. Gating only on `active` let mid-onboarding+ * companies see the Stripe send option, get their invoice Posted, and then+ * fail the actual Stripe send.+ */+export async function getStripeConnectAccountId(+ serviceRole: ServiceRole,+ companyId: string+): Promise<string | null> {+ const integration = await serviceRole+ .from("companyIntegration")+ .select("active, metadata")+ .eq("id", STRIPE_CONNECT_INTEGRATION)+ .eq("companyId", companyId)+ .maybeSingle();++ if (!integration.data?.active) return null;++ const metadata = integration.data.metadata as+ | Record<string, unknown>+ | undefined;+ if (metadata?.chargesEnabled !== true) return null;++ return (metadata?.stripeAccountId as string | undefined) ?? null;+}++/**+ * Who gets billed for this invoice.+ *+ * `invoiceCustomerId` is the bill-to and takes precedence — it is set when the+ * customer receiving the goods is not the one paying for them.+ */+export async function getBillingCustomerId(+ serviceRole: ServiceRole,+ invoiceId: string,+ companyId: string+): Promise<string | null> {+ const invoice = await serviceRole+ .from("salesInvoice")+ .select("customerId, invoiceCustomerId")+ .eq("id", invoiceId)+ .eq("companyId", companyId)+ .maybeSingle();++ if (!invoice.data) return null;+ return invoice.data.invoiceCustomerId ?? invoice.data.customerId ?? null;+}++/**+ * Decide what would happen to the connected account, without changing anything.+ *+ * Read-only by design: both the modal (to ask the user) and the post action (to+ * check the answer it got back) call this. Running the same resolution on both+ * sides is what stops a client from claiming "just link me to cus_X" for a+ * customer that does not exist, belongs to another account, or was never offered.+ */+export async function resolveStripeCustomer({+ serviceRole,+ companyId,+ invoiceId,+ customerContactId,+ emailOverride+}: {+ serviceRole: ServiceRole;+ companyId: string;+ invoiceId: string;+ customerContactId: string;+ emailOverride?: string;+}): Promise<+ | { resolution: StripeCustomerResolution; sources: null }+ | {+ resolution: StripeCustomerResolution;+ sources: StripeCustomerSources;+ stripeAccountId: string;+ billingCustomerId: string;+ input: ConnectCustomerInput | null;+ }+> {+ const stripeAccountId = await getStripeConnectAccountId(+ serviceRole,+ companyId+ );+ if (!stripeAccountId) {+ return {+ resolution: {+ state: "unavailable",+ message: "Stripe Connect is not connected for this company"+ },+ sources: null+ };+ }++ const billingCustomerId = await getBillingCustomerId(+ serviceRole,+ invoiceId,+ companyId+ );+ if (!billingCustomerId) {+ return {+ resolution: {+ state: "unavailable",+ message: "this invoice has no customer to bill"+ },+ sources: null+ };+ }++ const sources = await resolveStripeCustomerSources(+ serviceRole,+ companyId,+ billingCustomerId,+ customerContactId+ );+ if (!sources) {+ return {+ resolution: {+ state: "unavailable",+ message: "the customer could not be loaded"+ },+ sources: null+ };+ }++ const found = { stripeAccountId, billingCustomerId, sources };+ const input = buildStripeCustomerInput(sources, emailOverride);++ // No email means no invoice can be sent, so ask for one before looking+ // anything up — an email is also the only key we can match Stripe on.+ if (!input) {+ return {+ ...found,+ input: null,+ resolution: {+ state: "missing-email",+ customerName: sources.customer.name ?? ""+ }+ };+ }++ const mappingService = createMappingService(getDatabaseClient(), companyId);+ const mapping = await mappingService.getByEntity(+ "customer",+ billingCustomerId,+ STRIPE_CONNECT_INTEGRATION+ );++ if (mapping?.externalId) {+ const existing = await retrieveConnectCustomer(+ stripeAccountId,+ mapping.externalId+ );+ // A mapping whose customer was deleted in the Stripe dashboard falls+ // through to the search below rather than failing the post.+ if (existing) {+ return {+ ...found,+ input,+ resolution: { state: "linked", customer: toSummary(existing) }+ };+ }+ }++ const matches = await findConnectCustomersByEmail(+ stripeAccountId,+ input.email+ );++ if (matches.length) {+ return {+ ...found,+ input,+ resolution: { state: "match-found", matches: matches.map(toSummary) }+ };+ }++ return {+ ...found,+ input,+ resolution: {+ state: "new",+ preview: {+ name: input.name,+ email: input.email,+ phone: input.phone,+ addressLines: [+ input.address?.line1,+ input.address?.line2,+ [+ input.address?.city,+ input.address?.state,+ input.address?.postal_code+ ]+ .filter(Boolean)+ .join(", "),+ input.address?.country+ ].filter((line): line is string => Boolean(line)),+ taxExempt: input.taxExempt ?? "none"+ }+ }+ };+}diff --git a/apps/erp/app/modules/invoicing/stripe-customer.test.ts b/apps/erp/app/modules/invoicing/stripe-customer.test.tsnew file mode 100644index 0000000000..bbdd6c8f9a--- /dev/null+++ b/apps/erp/app/modules/invoicing/stripe-customer.test.ts@@ -0,0 +1,233 @@+import { describe, expect, it } from "vitest";+// Import the mapper directly, never `./stripe-customer.server` — that module+// pulls the `~/modules/sales` barrel and, through it, `@carbon/glossary`'s+// Lingui macros, which throw outside a configured i18n runtime.+import type { StripeCustomerSources } from "./stripe-customer.mapper";+import {+ buildStripeCustomerInput,+ toStripeTaxExempt+} from "./stripe-customer.mapper";++/**+ * The real `StripeCustomerSources` is derived from Supabase query-builder+ * return types, which are far wider than the mapper reads. These fixtures carry+ * only the fields under test and are cast in — a full literal would be noise+ * that obscures which field each case is actually about.+ */+function sources(+ overrides: {+ customer?: Record<string, unknown>;+ contact?: Record<string, unknown> | null;+ billingLocation?: Record<string, unknown> | null;+ customerTax?: Record<string, unknown> | null;+ } = {}+): StripeCustomerSources {+ return {+ customer: {+ id: "cust_1",+ companyId: "co_1",+ name: "Acme Manufacturing",+ readableId: "CUS000123",+ website: "https://acme.test",+ phone: null,+ status: "Active",+ type: "Direct",+ taxPercent: 0.0825,+ tags: ["oem"],+ ...overrides.customer+ },+ contact:+ overrides.contact === null+ ? null+ : {+ id: "ccontact_1",+ contactId: "contact_1",+ contact: {+ email: "[email protected]",+ firstName: "Dana",+ lastName: "Reed",+ workPhone: "+1-555-0100",+ mobilePhone: null+ },+ ...overrides.contact+ },+ billingLocation:+ overrides.billingLocation === null+ ? null+ : {+ id: "cloc_1",+ address: {+ addressLine1: "1 Foundry Way",+ addressLine2: "Suite 4",+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US"+ },+ ...overrides.billingLocation+ },+ customerTax:+ overrides.customerTax === null+ ? null+ : {+ customerId: "cust_1",+ taxExempt: false,+ taxExemptionReason: null,+ ...overrides.customerTax+ }+ } as unknown as StripeCustomerSources;+}++describe("buildStripeCustomerInput", () => {+ it("reads email and phone from the embedded contact, not the join row", () => {+ const input = buildStripeCustomerInput(sources());++ expect(input?.email).toBe("[email protected]");+ expect(input?.phone).toBe("+1-555-0100");+ });++ it("reads address from the embedded address, not the location join row", () => {+ const input = buildStripeCustomerInput(sources());++ expect(input?.address).toEqual({+ line1: "1 Foundry Way",+ line2: "Suite 4",+ city: "Detroit",+ state: "MI",+ postal_code: "48201",+ country: "US"+ });+ });++ it("prefers the customer's own phone over the contact's", () => {+ const input = buildStripeCustomerInput(+ sources({ customer: { phone: "+1-555-9999" } })+ );++ expect(input?.phone).toBe("+1-555-9999");+ });++ it("falls back to the contact's mobile when there is no work phone", () => {+ const input = buildStripeCustomerInput(+ sources({+ contact: {+ contact: {+ email: "[email protected]",+ workPhone: null,+ mobilePhone: "+1-555-0177"+ }+ }+ })+ );++ expect(input?.phone).toBe("+1-555-0177");+ });++ it("returns null when there is no email to invoice", () => {+ const input = buildStripeCustomerInput(+ sources({ contact: { contact: { email: null } } })+ );++ expect(input).toBeNull();+ });++ it("uses the override email when the contact has none", () => {+ const input = buildStripeCustomerInput(+ sources({ contact: { contact: { email: null } } }),+ );++ expect(input?.email).toBe("[email protected]");+ });++ it("omits the address entirely when no billing location is set", () => {+ const input = buildStripeCustomerInput(sources({ billingLocation: null }));++ expect(input?.address).toBeUndefined();+ // A customer with no billing address is still billable.+ expect(input?.email).toBe("[email protected]");+ });++ it("maps an export exemption to Stripe's reverse charge", () => {+ const input = buildStripeCustomerInput(+ sources({+ customerTax: { taxExempt: true, taxExemptionReason: "Export" }+ })+ );++ expect(input?.taxExempt).toBe("reverse");+ });++ it("defaults to not exempt when the customer has no tax row", () => {+ const input = buildStripeCustomerInput(sources({ customerTax: null }));++ expect(input?.taxExempt).toBe("none");+ });++ it("stores taxPercent as the stored fraction, not a percentage", () => {+ const input = buildStripeCustomerInput(sources());++ expect(input?.metadata.carbon_tax_percent).toBe("0.0825");+ });++ it("clamps metadata values to Stripe's 500-character limit", () => {+ const input = buildStripeCustomerInput(+ sources({ customer: { tags: [`${"a".repeat(400)},${"b".repeat(400)}`] } })+ );++ expect(input?.metadata.carbon_tags).toHaveLength(500);+ });++ it("labels a missing status and type rather than emitting empty strings", () => {+ const input = buildStripeCustomerInput(+ sources({ customer: { status: null, type: null } })+ );++ // Stripe accepts empty values, but "unknown" reads correctly in the+ // dashboard where these are the only Carbon context a support rep has.+ expect(input?.metadata.carbon_status).toBe("unknown");+ expect(input?.metadata.carbon_type).toBe("unknown");+ });++ it("keeps the Carbon ids that tie the Stripe record back to the ERP", () => {+ const input = buildStripeCustomerInput(sources());++ expect(input?.metadata.carbon_customer_id).toBe("cust_1");+ expect(input?.metadata.carbon_company_id).toBe("co_1");+ expect(input?.metadata.carbon_readable_id).toBe("CUS000123");+ });+});++describe("toStripeTaxExempt", () => {+ it("is 'none' when the customer is not exempt, whatever the reason says", () => {+ expect(toStripeTaxExempt(false, "Export")).toBe("none");+ expect(toStripeTaxExempt(null, null)).toBe("none");+ expect(toStripeTaxExempt(undefined, undefined)).toBe("none");+ });++ it("treats an export sale as a reverse charge, not an exemption", () => {+ // Zero-rated with the tax liability shifted to the buyer — billing it as+ // "exempt" would misstate the transaction on the Stripe invoice.+ expect(toStripeTaxExempt(true, "Export")).toBe("reverse");+ });++ it("treats every other Carbon reason as an ordinary exemption", () => {+ for (const reason of [+ "Resale",+ "Government",+ "Nonprofit",+ "Agriculture",+ "Industrial",+ "Medical",+ "Educational",+ "Religious",+ "Other"+ ]) {+ expect(toStripeTaxExempt(true, reason)).toBe("exempt");+ }+ });++ it("is 'exempt' when exempt with no reason recorded", () => {+ expect(toStripeTaxExempt(true, null)).toBe("exempt");+ });+});diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsxindex f50c766a2d..882f8145af 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx@@ -11,6 +11,7 @@ import {Heading,HStack,IconButton,+ Status,useDisclosure} from "@carbon/react";import { getItemReadableId } from "@carbon/utils";@@ -85,6 +86,7 @@ const SalesInvoiceHeader = () => {salesInvoiceLines: SalesInvoiceLine[];defaultCc: string[];orgHasCredits: boolean;+ stripeInvoiceUrl: string | null;}>(path.to.salesInvoice(invoiceId));if (!routeData?.salesInvoice) throw new Error("salesInvoice not found");@@ -301,6 +303,18 @@ const SalesInvoiceHeader = () => {</DropdownMenuContent></DropdownMenu><SalesInvoiceStatus status={salesInvoice.status} />+ {routeData?.stripeInvoiceUrl && isPosted && (+ <a+ href={routeData.stripeInvoiceUrl}+ target="_blank"+ rel="noreferrer"+ className="no-underline"+ >+ <Status color="purple">+ <Trans>Stripe</Trans>+ </Status>+ </a>+ )}</HStack><HStack>{relatedDocs.salesOrders.length === 1 && (@@ -435,6 +449,7 @@ const SalesInvoiceHeader = () => {invoiceId={invoiceId}customerId={salesInvoice.invoiceCustomerId}customerContactId={salesInvoice.invoiceCustomerContactId}+ dateDue={salesInvoice.dateDue}isOpen={postingModal.isOpen}onClose={postingModal.onClose}linesToShip={linesNotAssociatedWithSO}diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsxindex c29579d506..cc142e0452 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicePostModal.tsx@@ -18,17 +18,24 @@ import {toast,VStack} from "@carbon/react";+import { parseDate } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import type { FetcherWithComponents } from "react-router";+import { useFetcher } from "react-router";import {CustomerContact,+ DatePicker,EmailRecipients,+ Hidden,SelectControlled} from "~/components/Form";+import { useCompanyToday } from "~/hooks";import { useIntegrations } from "~/hooks/useIntegrations";+import type { StripeCustomerResolution } from "~/modules/invoicing/stripe-customer.server";import { path } from "~/utils/path";import { salesInvoicePostValidator } from "../../invoicing.models";+import StripeCustomerPanel from "./StripeCustomerPanel";type SalesInvoicePostModalProps = {fetcher: FetcherWithComponents<{ success: boolean; message: string }>;@@ -43,6 +50,7 @@ type SalesInvoicePostModalProps = {}[];customerId: string | null;customerContactId: string | null;+ dateDue: string | null;defaultCc?: string[];};@@ -54,26 +62,83 @@ const SalesInvoicePostModal = ({linesToShip,customerId,customerContactId,+ dateDue,defaultCc = []}: SalesInvoicePostModalProps) => {const { t } = useLingui();const hasLinesToShip = linesToShip.length > 0;const integrations = useIntegrations();const canEmail = integrations.has("email");+ const canStripe = integrations.has("stripe-connect");- const [notificationType, setNotificationType] = useState(- canEmail ? "Email" : "None"- );+ // The invoice's own dateDue is a business date, so the "would this survive+ // clampDueDate" check anchors on the company's calendar, not the browser's.+ const companyToday = parseDate(useCompanyToday());+ const minStripeDueDate = companyToday.add({ days: 1 });+ const maxStripeDueDate = companyToday.add({ years: 5 });+ const parsedDateDue = (() => {+ if (!dateDue) return null;+ try {+ return parseDate(dateDue.slice(0, 10));+ } catch {+ return null;+ }+ })();+ // Mirrors clampDueDate's server-side rule (missing, on/before today, or+ // more than 5 years out) — if the invoice's own date wouldn't survive that+ // clamp, ask the user for one instead of silently sending with none.+ const needsStripeDueDate =+ !parsedDateDue ||+ parsedDateDue.compare(companyToday) <= 0 ||+ parsedDateDue.compare(maxStripeDueDate) > 0;++ const [notificationType, setNotificationType] = useState<+ "Email" | "Stripe" | "None"+ >(canStripe ? "Stripe" : canEmail ? "Email" : "None");++ const [contactId, setContactId] = useState<string | null>(customerContactId);+ const [stripeEmail, setStripeEmail] = useState("");+ const [committedEmail, setCommittedEmail] = useState<string | undefined>();+ const stripeCustomer = useFetcher<StripeCustomerResolution>();+ const isStripe = notificationType === "Stripe";+ // The identity the current panel state must correspond to. Anything the+ // fetcher still holds for a different key is stale.+ const requestKey = `${contactId ?? ""}|${committedEmail ?? ""}`;+ const loadedKeyRef = useRef<string | null>(null);++ // biome-ignore lint/correctness/useExhaustiveDependencies: `stripeCustomer` is a fresh object each render, so depending on it would re-run this effect forever.+ useEffect(() => {+ if (!isStripe || !contactId) return;+ loadedKeyRef.current = requestKey;+ stripeCustomer.load(+ path.to.api.stripeConnectCustomer(invoiceId, contactId, committedEmail)+ );+ }, [isStripe, contactId, invoiceId, committedEmail]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (fetcher.data?.success) {+ if (fetcher.data?.message) toast.success(fetcher.data.message);onClose();} else if (fetcher.data?.success === false && fetcher.data?.message) {toast.error(fetcher.data.message);}}, [fetcher.data?.success]);+ const resolution = stripeCustomer.data ?? null;+ const isStale = loadedKeyRef.current !== requestKey;+ const isResolving = stripeCustomer.state !== "idle" || isStale;++ // Nothing may be created on a merchant's Stripe account without a decision,+ // so the submit stays shut until the panel has produced one.+ const isStripeBlocked =+ isStripe &&+ (!contactId ||+ isResolving ||+ !resolution ||+ resolution.state === "unavailable" ||+ resolution.state === "missing-email");+return (<Modalopen={isOpen}@@ -87,9 +152,13 @@ const SalesInvoicePostModal = ({validator={salesInvoicePostValidator}action={path.to.salesInvoicePost(invoiceId)}defaultValues={{- notification: notificationType as "Email" | "None",+ notification: notificationType,customerContact: customerContactId ?? undefined,- cc: defaultCc+ cc: defaultCc,+ stripeDueDate:+ isStripe && needsStripeDueDate+ ? companyToday.add({ days: 30 }).toString()+ : undefined}}fetcher={fetcher}>@@ -142,7 +211,7 @@ const SalesInvoicePostModal = ({</div>)}- {canEmail && (+ {(canEmail || canStripe) && (<SelectControlledlabel={t`Send Via`}name="notification"@@ -151,26 +220,75 @@ const SalesInvoicePostModal = ({label: "None",value: "None"},- {- label: "Email",- value: "Email"- }+ ...(canEmail+ ? [+ {+ label: "Email",+ value: "Email"+ }+ ]+ : []),+ ...(canStripe+ ? [+ {+ label: "Stripe",+ value: "Stripe"+ }+ ]+ : [])]}value={notificationType}onChange={(t) => {- if (t) setNotificationType(t.value);+ if (t)+ setNotificationType(+ t.value as "Email" | "Stripe" | "None"+ );}}/>)}+ {(notificationType === "Email" ||+ notificationType === "Stripe") && (+ <CustomerContact+ name="customerContact"+ customer={customerId ?? undefined}+ onChange={(contact) => {+ setContactId(contact?.id ?? null);+ // A different contact may have an email of its own, so+ // drop anything typed for the previous one.+ setStripeEmail("");+ setCommittedEmail(undefined);+ }}+ />+ )}+ {isStripe && contactId && (+ <StripeCustomerPanel+ resolution={resolution}+ isLoading={isResolving}+ email={stripeEmail}+ onEmailChange={setStripeEmail}+ onEmailCommit={(email) => {+ // Re-resolve once an address exists: Stripe may already+ // have a customer under it, and linking beats duplicating.+ if (email.includes("@")) setCommittedEmail(email);+ }}+ />+ )}+ {isStripe && committedEmail && (+ <Hidden name="stripeContactEmail" value={committedEmail} />+ )}+ {isStripe && needsStripeDueDate && (+ <DatePicker+ name="stripeDueDate"+ label={t`Stripe Due Date`}+ helperText={t`This invoice has no usable due date — choose one for Stripe.`}+ minValue={minStripeDueDate}+ maxValue={maxStripeDueDate}+ isRequired+ />+ )}{notificationType === "Email" && (- <>- <CustomerContact- name="customerContact"- customer={customerId ?? undefined}- />- <EmailRecipients name="cc" label={t`CC`} type="employee" />- </>+ <EmailRecipients name="cc" label={t`CC`} type="employee" />)}</VStack></ModalBody>@@ -180,7 +298,7 @@ const SalesInvoicePostModal = ({<Trans>Cancel</Trans></Button><Button- isDisabled={fetcher.state !== "idle"}+ isDisabled={fetcher.state !== "idle" || isStripeBlocked}isLoading={fetcher.state !== "idle"}type="submit">diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/StripeCustomerPanel.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/StripeCustomerPanel.tsxnew file mode 100644index 0000000000..164d1a52af--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/StripeCustomerPanel.tsx@@ -0,0 +1,252 @@+import {+ Alert,+ AlertDescription,+ AlertTitle,+ Label,+ RadioGroup,+ RadioGroupItem,+ Spinner,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useEffect, useState } from "react";+import { LuCircleAlert, LuCreditCard } from "react-icons/lu";+import { Hidden, InputControlled } from "~/components/Form";+import type { StripeCustomerResolution } from "~/modules/invoicing/stripe-customer.server";++const CREATE_NEW = "__create_new__";++type StripeCustomerPanelProps = {+ resolution: StripeCustomerResolution | null;+ isLoading: boolean;+ /** Email the user typed for a contact that had none; lifted so the parent can re-resolve. */+ email: string;+ onEmailChange: (email: string) => void;+ onEmailCommit: (email: string) => void;+};++function CustomerLine({+ name,+ email,+ id+}: {+ name: string | null;+ email: string | null;+ id?: string;+}) {+ return (+ <VStack spacing={0}>+ <span className="text-sm font-medium">{name ?? email ?? id}</span>+ {email && <span className="text-xs text-muted-foreground">{email}</span>}+ {id && <span className="text-xs text-muted-foreground">{id}</span>}+ </VStack>+ );+}++/**+ * What posting through Stripe will do to the connected account, and the+ * decision the user has to make about it.+ *+ * The `stripeCustomerAction` hidden field is the whole point: the post action+ * refuses to run without one, so every path through this panel either emits an+ * action the user chose or emits nothing and leaves the submit disabled.+ */+const StripeCustomerPanel = ({+ resolution,+ isLoading,+ email,+ onEmailChange,+ onEmailCommit+}: StripeCustomerPanelProps) => {+ const { t } = useLingui();+ const [selection, setSelection] = useState<string>(CREATE_NEW);++ // A fresh resolution invalidates whatever the user had picked — the match+ // list it referred to no longer exists.+ useEffect(() => {+ if (resolution?.state === "match-found") {+ setSelection(resolution.matches[0]?.id ?? CREATE_NEW);+ } else {+ setSelection(CREATE_NEW);+ }+ }, [resolution]);++ if (isLoading || !resolution) {+ return (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Spinner className="size-4" />+ <Trans>Checking Stripe for this customer…</Trans>+ </div>+ );+ }++ switch (resolution.state) {+ case "unavailable":+ return (+ <Alert variant="destructive">+ <LuCircleAlert />+ <AlertTitle>+ <Trans>Cannot send through Stripe</Trans>+ </AlertTitle>+ <AlertDescription>{resolution.message}</AlertDescription>+ </Alert>+ );++ case "missing-email":+ return (+ <VStack spacing={2}>+ <Alert variant="warning">+ <LuCircleAlert />+ <AlertTitle>+ <Trans>This contact has no email address</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ Stripe emails the invoice to the customer, so an address is+ required. This will also be saved to the contact in Carbon.+ </Trans>+ </AlertDescription>+ </Alert>+ <InputControlled+ name="stripeCustomerEmail"+ label={t`Email`}+ value={email}+ onChange={onEmailChange}+ onBlur={() => onEmailCommit(email)}+ />+ </VStack>+ );++ case "linked":+ return (+ <VStack spacing={2}>+ <Alert variant="info">+ <LuCreditCard />+ <AlertTitle>+ <Trans>Existing Stripe customer</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ This invoice will be billed to the Stripe customer already+ linked to this Carbon customer. To change its details, edit it+ in the Stripe dashboard.+ </Trans>+ </AlertDescription>+ </Alert>+ <div className="w-full rounded-lg border p-3">+ <CustomerLine+ name={resolution.customer.name}+ email={resolution.customer.email}+ id={resolution.customer.id}+ />+ </div>+ <Hidden name="stripeCustomerAction" value="use-linked" />+ </VStack>+ );++ case "match-found":+ return (+ <VStack spacing={2}>+ <Alert variant="warning">+ <LuCircleAlert />+ <AlertTitle>+ <Trans>Stripe already has a customer with this email</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ Link this Carbon customer to one of them, or create a separate+ Stripe customer.+ </Trans>+ </AlertDescription>+ </Alert>+ <RadioGroup+ value={selection}+ onValueChange={setSelection}+ className="w-full"+ >+ {resolution.matches.map((match) => (+ <label+ key={match.id}+ htmlFor={match.id}+ className="flex w-full cursor-pointer items-center gap-3 rounded-lg border p-3"+ >+ <RadioGroupItem value={match.id} id={match.id} />+ <CustomerLine+ name={match.name}+ email={match.email}+ id={match.id}+ />+ </label>+ ))}+ <label+ htmlFor={CREATE_NEW}+ className="flex w-full cursor-pointer items-center gap-3 rounded-lg border p-3"+ >+ <RadioGroupItem value={CREATE_NEW} id={CREATE_NEW} />+ <Label className="cursor-pointer text-sm font-medium">+ <Trans>Create a new Stripe customer instead</Trans>+ </Label>+ </label>+ </RadioGroup>+ <Hidden+ name="stripeCustomerAction"+ value={selection === CREATE_NEW ? "create" : "link-existing"}+ />+ {selection !== CREATE_NEW && (+ <Hidden name="stripeCustomerId" value={selection} />+ )}+ </VStack>+ );++ case "new":+ return (+ <VStack spacing={2}>+ <Alert variant="info">+ <LuCreditCard />+ <AlertTitle>+ <Trans>A new Stripe customer will be created</Trans>+ </AlertTitle>+ <AlertDescription>+ <Trans>+ Stripe has no customer for this Carbon customer yet. Posting+ will create one on your connected account.+ </Trans>+ </AlertDescription>+ </Alert>+ <div className="w-full rounded-lg border p-3">+ <VStack spacing={0}>+ <span className="text-sm font-medium">+ {resolution.preview.name}+ </span>+ <span className="text-xs text-muted-foreground">+ {resolution.preview.email}+ </span>+ {resolution.preview.phone && (+ <span className="text-xs text-muted-foreground">+ {resolution.preview.phone}+ </span>+ )}+ {resolution.preview.addressLines.map((line) => (+ <span key={line} className="text-xs text-muted-foreground">+ {line}+ </span>+ ))}+ {resolution.preview.taxExempt === "exempt" && (+ <span className="text-xs text-muted-foreground">+ <Trans>Tax exempt</Trans>+ </span>+ )}+ {resolution.preview.taxExempt === "reverse" && (+ <span className="text-xs text-muted-foreground">+ <Trans>Reverse charge</Trans>+ </span>+ )}+ </VStack>+ </div>+ <Hidden name="stripeCustomerAction" value="create" />+ </VStack>+ );+ }+};++export default StripeCustomerPanel;diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 8225b6ff4c..2925dd32c6 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -571,34 +571,42 @@ export async function getConfigurationParametersByQuoteLineId(export async function getCustomer(client: SupabaseClient<Database>,- customerId: string+ customerId: string,+ companyId?: string) {- return client.from("customers").select("*").eq("id", customerId).single();+ let query = client.from("customers").select("*").eq("id", customerId);+ if (companyId) query = query.eq("companyId", companyId);+ return query.single();}export async function getCustomerContact(client: SupabaseClient<Database>,- customerContactId: string+ customerContactId: string,+ companyId?: string) {- return client+ let query = client.from("customerContact").select("*, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, notes)")- .eq("id", customerContactId)- .single();+ .eq("id", customerContactId);+ if (companyId) query = query.eq("companyId", companyId);+ return query.single();}export async function getCustomerContacts(client: SupabaseClient<Database>,- customerId: string+ customerId: string,+ companyId?: string) {- return client+ let query = client.from("customerContact").select("*, contact(id, fullName, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, notes), user(id, active)").eq("customerId", customerId);+ if (companyId) query = query.eq("companyId", companyId);+ return query;}export async function getCustomerItemPriceOverride(@@ -626,60 +634,71 @@ export async function getCustomerItemPriceOverride(export async function getCustomerLocation(client: SupabaseClient<Database>,- customerLocationId: string+ customerLocationId: string,+ companyId?: string) {- return client+ let query = client.from("customerLocation").select("*, address(id, addressLine1, addressLine2, city, stateProvince, countryCode, country(alpha2, name), postalCode)")- .eq("id", customerLocationId)- .single();+ .eq("id", customerLocationId);+ if (companyId) query = query.eq("companyId", companyId);+ return query.single();}export async function getCustomerLocations(client: SupabaseClient<Database>,- customerId: string+ customerId: string,+ companyId?: string) {- return client+ let query = client.from("customerLocation").select("*, address(id, addressLine1, addressLine2, city, stateProvince, country(alpha2, name), postalCode)").eq("customerId", customerId);+ if (companyId) query = query.eq("companyId", companyId);+ return query;}export async function getCustomerPayment(client: SupabaseClient<Database>,- customerId: string+ customerId: string,+ companyId?: string) {- return client+ let query = client.from("customerPayment").select("*")- .eq("customerId", customerId)- .single();+ .eq("customerId", customerId);+ if (companyId) query = query.eq("companyId", companyId);+ return query.single();}export async function getCustomerShipping(client: SupabaseClient<Database>,- customerId: string+ customerId: string,+ companyId?: string) {- return client+ let query = client.from("customerShipping").select("*")- .eq("customerId", customerId)- .single();+ .eq("customerId", customerId);+ if (companyId) query = query.eq("companyId", companyId);+ return query.single();}export async function getCustomerTax(client: SupabaseClient<Database>,- customerId: string+ customerId: string,+ companyId?: string) {- return client+ let query = client.from("customerTax").select("*")- .eq("customerId", customerId)- .single();+ .eq("customerId", customerId);+ if (companyId) query = query.eq("companyId", companyId);+ return query.single();}export async function getCustomerTypeItemPriceOverride(diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex 9ba42df7cc..77f3301421 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -63,15 +63,23 @@ function IntegrationActionButton({setStatus("running");try {- const response = await fetch(action.endpoint, { method: "POST" });+ const response = await fetch(action.endpoint, {+ method: "POST"+ });+const data = await response.json();- if (data.success) {+ if (data?.redirectUrl) {+ window.location.href = data.redirectUrl;+ return;+ }++ if (data?.success) {toast.success(`${action.label} started`);setStatus("completed");} else {setStatus("idle");- toast.error(data.error || `Failed to start ${action.label}`);+ toast.error(data?.error || `Failed to start ${action.label}`);}} catch {setStatus("idle");@@ -766,7 +774,11 @@ export function IntegrationForm({<Trans>Setup instructions</Trans></div>{/* @ts-expect-error TS2339 */}- <integration.setupInstructions companyId={companyId} />+ <integration.setupInstructions+ companyId={companyId}+ metadata={metadata}+ installed={installed}+ /></div>)}diff --git a/apps/erp/app/routes/api+/integrations.stripe-connect.callback.ts b/apps/erp/app/routes/api+/integrations.stripe-connect.callback.tsnew file mode 100644index 0000000000..82d2f54a48--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.stripe-connect.callback.ts@@ -0,0 +1,90 @@+import { error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getConnectAccountStatus } from "@carbon/stripe/connect.server";+import type { LoaderFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { upsertCompanyIntegration } from "~/modules/settings/settings.server";+import { path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "settings"+ });++ const url = new URL(request.url);+ const statusParam = url.searchParams.get("status");++ // Get current integration metadata+ const existing = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "stripe-connect")+ .eq("companyId", companyId)+ .maybeSingle();++ const existingMeta = existing.data?.metadata as+ | Record<string, unknown>+ | undefined;+ const stripeAccountId = existingMeta?.stripeAccountId as string | undefined;++ if (!stripeAccountId) {+ throw redirect(+ path.to.integration("stripe-connect"),+ await flash(request, error(null, "No Stripe Connect account found"))+ );+ }++ const accountStatus = await getConnectAccountStatus(stripeAccountId);++ if (accountStatus) {+ const onboardingComplete =+ !!accountStatus.detailsSubmitted && !!accountStatus.chargesEnabled;++ await upsertCompanyIntegration(client, {+ id: "stripe-connect",+ companyId,+ active: true,+ metadata: {+ ...existingMeta,+ ...accountStatus+ },+ updatedBy: userId+ });++ if (statusParam === "refresh") {+ throw redirect(+ path.to.api.stripeConnectOnboard,+ await flash(+ request,+ error(+ null,+ "Stripe Connect onboarding link expired. Please try again."+ )+ )+ );+ }++ if (onboardingComplete) {+ throw redirect(+ path.to.integration("stripe-connect"),+ await flash(+ request,+ success("Stripe Connect account successfully connected and enabled!")+ )+ );+ } else {+ throw redirect(+ path.to.integration("stripe-connect"),+ await flash(+ request,+ success(+ "Stripe Connect details saved. Onboarding is pending completion."+ )+ )+ );+ }+ }++ throw redirect(path.to.integration("stripe-connect"));+}diff --git a/apps/erp/app/routes/api+/integrations.stripe-connect.connect.ts b/apps/erp/app/routes/api+/integrations.stripe-connect.connect.tsnew file mode 100644index 0000000000..db58ea7594--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.stripe-connect.connect.ts@@ -0,0 +1,141 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";+import {+ createConnectAccountLink,+ getOrCreateConnectAccount,+ isStaleConnectAccountError+} from "@carbon/stripe/connect.server";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++const logger = getLogger("stripe-connect");++async function handle({ request }: { request: Request }) {+ const { client, companyId, email } = await requirePermissions(request, {+ update: "settings"+ });++ const url = new URL(request.url);+ const returnUrl = `${url.origin}/api/integrations/stripe-connect/callback?status=success`;+ const refreshUrl = `${url.origin}/api/integrations/stripe-connect/callback?status=refresh`;++ try {+ let stripeAccountId = await getOrCreateConnectAccount(+ client,+ companyId,+ );++ let onboardingUrl: string;+ try {+ onboardingUrl = await createConnectAccountLink(+ stripeAccountId,+ returnUrl,+ refreshUrl+ );+ } catch (linkErr) {+ if (!isStaleConnectAccountError(linkErr)) {+ throw linkErr;+ }++ logger.warn(+ "Stripe Connect account link failed against the stored account; creating a new account",+ { companyId, stripeAccountId, error: linkErr }+ );++ stripeAccountId = await getOrCreateConnectAccount(+ client,+ companyId,+ email,+ { forceNew: true }+ );++ onboardingUrl = await createConnectAccountLink(+ stripeAccountId,+ returnUrl,+ refreshUrl+ );+ }++ const existing = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "stripe-connect")+ .eq("companyId", companyId)+ .maybeSingle();+ const upsert = await client.from("companyIntegration").upsert({+ id: "stripe-connect",+ companyId,+ active: true,+ metadata: {+ ...(existing.data?.metadata as Record<string, unknown> | undefined),+ stripeAccountId,+ onboardingStarted: true // mark started on try+ }+ });++ if (upsert.error) {+ // Silent failure here leaves no `stripeAccountId` on the integration+ // row — the callback would then throw "No Stripe Connect account+ // found." Throw so this hits the catch below and surfaces to the user+ // instead of onboarding silently against an unrecorded account.+ throw new Error(+ `Failed to save Stripe Connect account id: ${upsert.error.message}`+ );+ }++ if (+ request.headers.get("Accept")?.includes("application/json") ||+ request.method === "POST"+ ) {+ return Response.json({ redirectUrl: onboardingUrl });+ }++ return redirect(onboardingUrl);+ } catch (err: any) {+ logger.error("Failed to initiate Stripe Connect onboarding", {+ error: err+ });++ // "platform_account_required" is Stripe's code for "your own Stripe+ // account isn't set up as a Connect platform" — a genuine admin-fixable+ // platform misconfiguration, distinct from an ordinary per-request+ // failure. Surface it distinctly so the drawer can show a persistent+ // "ask your administrator" state instead of a one-off retryable toast.+ const code = err.code ?? err.raw?.code;+ const isPlatformConfigError = code === "platform_account_required";++ if (+ request.headers.get("Accept")?.includes("application/json") ||+ request.method === "POST"+ ) {+ return Response.json(+ {+ error: err.message || "Failed to initiate Stripe Connect onboarding",+ code,+ isPlatformConfigError+ },+ { status: 400 }+ );+ }++ throw redirect(+ path.to.integrations,+ await flash(+ request,+ error(err, "Failed to initiate Stripe Connect onboarding")+ )+ );+ }+}++export async function loader({ request }: LoaderFunctionArgs) {+ return handle({ request });+}++export async function action({ request }: ActionFunctionArgs) {+ return handle({ request });+}diff --git a/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.ts b/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.tsnew file mode 100644index 0000000000..d933af8dba--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.stripe-connect.dashboard.ts@@ -0,0 +1,85 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";+import { createExpressDashboardLoginLink } from "@carbon/stripe/connect.server";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++const logger = getLogger("stripe-connect");++async function handle({ request }: { request: Request }) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const existing = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "stripe-connect")+ .eq("companyId", companyId)+ .maybeSingle();++ const existingMeta = existing.data?.metadata as+ | Record<string, unknown>+ | undefined;+ const stripeAccountId = existingMeta?.stripeAccountId as string | undefined;++ if (!stripeAccountId) {+ if (+ request.headers.get("Accept")?.includes("application/json") ||+ request.method === "POST"+ ) {+ return Response.json(+ { error: "No Stripe Connect account found" },+ { status: 400 }+ );+ }+ throw redirect(+ path.to.integrations,+ await flash(request, error(null, "No Stripe Connect account found"))+ );+ }++ try {+ const loginLinkUrl = await createExpressDashboardLoginLink(stripeAccountId);++ if (+ request.headers.get("Accept")?.includes("application/json") ||+ request.method === "POST"+ ) {+ return Response.json({ redirectUrl: loginLinkUrl });+ }++ return redirect(loginLinkUrl);+ } catch (err: any) {+ logger.error("Failed to open Stripe Express Dashboard", { error: err });++ if (+ request.headers.get("Accept")?.includes("application/json") ||+ request.method === "POST"+ ) {+ return Response.json(+ { error: err.message || "Failed to open Stripe Express Dashboard" },+ { status: 400 }+ );+ }++ throw redirect(+ path.to.integrations,+ await flash(+ request,+ error(err, "Failed to open Stripe Express Dashboard")+ )+ );+ }+}++export async function loader({ request }: LoaderFunctionArgs) {+ return handle({ request });+}++export async function action({ request }: ActionFunctionArgs) {+ return handle({ request });+}diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 79653b99e8..83807a262e 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-08-21T16:20:10.204Z",+ "generated": "2026-08-22T01:32:58.017Z","totalTools": 1443,"modules": 15,"tools": [@@ -35302,7 +35302,8 @@"paramCount": 1,"serviceParams": ["client",- "customerId"+ "customerId",+ "companyId"],"injectAuth": ["companyId"@@ -35327,7 +35328,8 @@"paramCount": 1,"serviceParams": ["client",- "customerContactId"+ "customerContactId",+ "companyId"],"injectAuth": ["companyId"@@ -35352,7 +35354,8 @@"paramCount": 1,"serviceParams": ["client",- "customerId"+ "customerId",+ "companyId"],"injectAuth": ["companyId"@@ -35415,7 +35418,8 @@"paramCount": 1,"serviceParams": ["client",- "customerLocationId"+ "customerLocationId",+ "companyId"],"injectAuth": ["companyId"@@ -35440,7 +35444,8 @@"paramCount": 1,"serviceParams": ["client",- "customerId"+ "customerId",+ "companyId"],"injectAuth": ["companyId"@@ -35465,7 +35470,8 @@"paramCount": 1,"serviceParams": ["client",- "customerId"+ "customerId",+ "companyId"],"injectAuth": ["companyId"@@ -35490,7 +35496,8 @@"paramCount": 1,"serviceParams": ["client",- "customerId"+ "customerId",+ "companyId"],"injectAuth": ["companyId"@@ -35515,7 +35522,8 @@"paramCount": 1,"serviceParams": ["client",- "customerId"+ "customerId",+ "companyId"],"injectAuth": ["companyId"diff --git a/apps/erp/app/routes/api+/stripe-connect.customer.$invoiceId.ts b/apps/erp/app/routes/api+/stripe-connect.customer.$invoiceId.tsnew file mode 100644index 0000000000..e383ef4bc0--- /dev/null+++ b/apps/erp/app/routes/api+/stripe-connect.customer.$invoiceId.ts@@ -0,0 +1,63 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { getLogger } from "@carbon/logger";+import type { LoaderFunctionArgs } from "react-router";+import type { StripeCustomerResolution } from "~/modules/invoicing/stripe-customer.server";+import { resolveStripeCustomer } from "~/modules/invoicing/stripe-customer.server";++const logger = getLogger("stripe-connect");++export type { StripeCustomerResolution };++/**+ * What posting this invoice through Stripe would do to the connected account.+ *+ * Read-only — the post action re-runs the same resolution before it acts, so+ * nothing here is load-bearing for correctness; it exists so the user can see+ * the decision before making it.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { companyId } = await requirePermissions(request, {+ create: "invoicing"+ });++ const { invoiceId } = params;+ if (!invoiceId) {+ return Response.json({+ state: "unavailable",+ message: "Could not find invoiceId"+ } satisfies StripeCustomerResolution);+ }++ const url = new URL(request.url);+ const customerContactId = url.searchParams.get("contact");+ if (!customerContactId) {+ return Response.json({+ state: "unavailable",+ message: "a customer contact is required"+ } satisfies StripeCustomerResolution);+ }++ try {+ const { resolution } = await resolveStripeCustomer({+ serviceRole: getCarbonServiceRole(),+ companyId,+ invoiceId,+ customerContactId,+ // Set once the user supplies an address for a contact that had none, so+ // the match search runs against it too — otherwise a customer Stripe+ // already has under that email would be duplicated.+ emailOverride: url.searchParams.get("email") ?? undefined+ });++ return Response.json(resolution);+ } catch (err) {+ logger.error("Failed to resolve Stripe customer", { error: err });+ // A Stripe outage must not present as "ready to create" — the modal keeps+ // the submit disabled on `unavailable`.+ return Response.json({+ state: "unavailable",+ message: "could not reach Stripe to check for an existing customer"+ } satisfies StripeCustomerResolution);+ }+}diff --git a/apps/erp/app/routes/api+/webhook.stripe-connect.ts b/apps/erp/app/routes/api+/webhook.stripe-connect.tsnew file mode 100644index 0000000000..f3255eaec8--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.stripe-connect.ts@@ -0,0 +1,350 @@+/**+ * Stripe Connect Webhook Handler+ *+ * Receives events raised on CONNECTED accounts (Stripe delivers these to an+ * endpoint registered with `connect: true`, signed with its own secret and+ * carrying `event.account`). Separate from `/api/webhook/stripe`, which handles+ * Carbon's own billing subscription on the platform account.+ *+ * Handled today:+ * - `invoice.paid` / `invoice.payment_succeeded` — record and post a Carbon+ * payment against the originating sales invoice, and book Stripe's fee.+ * - `invoice.payment_failed` / `invoice.marked_uncollectible` — logged only; no+ * ledger change, since nothing was collected.+ * - `charge.refunded` (full only), `charge.dispute.closed` (status "lost"),+ * `invoice.voided` — void the Carbon payment via `voidStripeConnectPayment`,+ * a full reversal. A PARTIAL refund has no safe automated GL treatment (no+ * partial-reversal journal capability exists) and is logged, not acted on.+ * - `account.updated` — refresh `chargesEnabled`/`payoutsEnabled`/requirement+ * errors on the integration, the same way `callback.ts` does after+ * onboarding. NOTE: Carbon creates Connect accounts via Stripe's v2 Core+ * Accounts API, while this endpoint is a classic v1 webhook — whether+ * Stripe delivers a v1 `account.updated` for a v2-created account has not+ * been verified against a live test event; treat this case as best-effort+ * until confirmed.+ *+ * Anything else is acknowledged with 200 so Stripe stops retrying it. Non-2xx is+ * reserved for a failed signature check and for genuinely retryable failures.+ */++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getStripeInvoiceIdForCharge,+ recordStripeConnectPayment,+ voidStripeConnectPayment+} from "@carbon/ee/stripe-connect.server";+import { getLogger } from "@carbon/logger";+import type {+ ConnectCharge,+ ConnectDispute,+ ConnectInvoice+} from "@carbon/stripe/connect.server";+import {+ constructConnectWebhookEvent,+ getConnectAccountStatus+} from "@carbon/stripe/connect.server";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { upsertCompanyIntegration } from "~/modules/settings/settings.server";++export const config = {+ runtime: "nodejs"+};++const logger = getLogger("erp", "webhook", "stripe-connect");+// Matches the SYSTEM_USER convention in payment.server.ts — this handler has+// no real user, but upsertCompanyIntegration requires an updatedBy audit value.+const SYSTEM_UPDATED_BY = "system";++async function getCompanyForConnectAccount(stripeAccountId: string) {+ const serviceRole = getCarbonServiceRole();++ const integration = await serviceRole+ .from("companyIntegration")+ .select("companyId, active, metadata")+ .eq("id", "stripe-connect")+ .eq("metadata->>stripeAccountId", stripeAccountId)+ .maybeSingle();++ if (integration.error) {+ // Includes the ambiguous case where more than one company claims this+ // account, which maybeSingle() also reports as an error.+ return { error: integration.error };+ }+ if (!integration.data) return { error: null, company: null };++ return {+ error: null,+ company: {+ companyId: integration.data.companyId,+ active: integration.data.active,+ metadata: (integration.data.metadata ?? {}) as Record<string, unknown>+ }+ };+}++export async function action({ request }: ActionFunctionArgs) {+ const body = await request.text();+ const signature = request.headers.get("stripe-signature");++ if (!signature) {+ logger.error("No signature");+ return data({ error: "No signature" }, { status: 400 });+ }++ const verified = constructConnectWebhookEvent({ body, signature });+ if (!verified.success) {+ logger.error("Stripe Connect webhook signature verification failed", {+ error: verified.error+ });+ return data({ error: "Invalid signature" }, { status: 400 });+ }++ const event = verified.event;++ // Platform-account events belong on /api/webhook/stripe. Acknowledge rather+ // than error so a misrouted event doesn't retry forever.+ if (!event.account) {+ logger.warn("Ignoring Stripe Connect event with no connected account", {+ type: event.type,+ eventId: event.id+ });+ return { success: true };+ }++ const lookup = await getCompanyForConnectAccount(event.account);+ if (lookup.error) {+ logger.error("Failed to resolve the company for this Stripe account", {+ error: lookup.error,+ eventId: event.id,+ stripeAccountId: event.account+ });+ return data({ error: "Company lookup failed" }, { status: 500 });+ }++ const company = lookup.company;+ if (!company) {+ logger.warn("No company is connected to this Stripe account", {+ type: event.type,+ eventId: event.id,+ stripeAccountId: event.account+ });+ return { success: true };+ }++ if (!company.active) {+ logger.warn("Stripe Connect integration is inactive for this company", {+ type: event.type,+ companyId: company.companyId+ });+ return { success: true };+ }++ try {+ switch (event.type) {+ case "invoice.paid":+ case "invoice.payment_succeeded": {+ const invoice = event.data.object as ConnectInvoice;++ // The send path stamps the company on the Stripe invoice. When it's+ // there it must agree with the account→company lookup; a mismatch is a+ // cross-tenant write we refuse outright.+ const invoiceCompanyId = invoice.metadata?.companyId;+ if (invoiceCompanyId && invoiceCompanyId !== company.companyId) {+ logger.error("Stripe invoice company does not match its account", {+ eventId: event.id,+ stripeAccountId: event.account,+ invoiceCompanyId,+ companyId: company.companyId+ });+ return data({ error: "Company mismatch" }, { status: 400 });+ }++ const result = await recordStripeConnectPayment({+ companyId: company.companyId,+ stripeAccountId: event.account,+ integrationMetadata: company.metadata,+ stripeInvoice: invoice+ });++ if (result.status === "skipped") {+ logger.info("Stripe Connect payment not recorded", {+ eventId: event.id,+ companyId: company.companyId,+ reason: result.reason+ });+ } else {+ logger.info("Recorded Stripe Connect payment", {+ eventId: event.id,+ companyId: company.companyId,+ paymentId: result.paymentId+ });+ }+ break;+ }++ case "invoice.payment_failed":+ case "invoice.marked_uncollectible": {+ const invoice = event.data.object as ConnectInvoice;+ logger.warn("Stripe Connect invoice was not collected", {+ type: event.type,+ companyId: company.companyId,+ stripeInvoiceId: invoice.id,+ carbonInvoiceId: invoice.metadata?.carbonInvoiceId+ });+ break;+ }++ case "invoice.voided": {+ const invoice = event.data.object as ConnectInvoice;+ const result = await voidStripeConnectPayment({+ companyId: company.companyId,+ stripeInvoiceId: invoice.id+ });+ logger.info("Stripe Connect invoice voided", {+ eventId: event.id,+ companyId: company.companyId,+ stripeInvoiceId: invoice.id,+ result+ });+ break;+ }++ case "charge.refunded": {+ const charge = event.data.object as ConnectCharge;+ // Stripe's pinned API version dropped Charge.invoice — resolve via+ // Carbon's own mapping metadata instead (see+ // getStripeInvoiceIdForCharge).+ const stripeInvoiceId = await getStripeInvoiceIdForCharge(+ company.companyId,+ charge.id+ );++ if (!stripeInvoiceId) {+ logger.warn("Refunded charge has no invoice to trace", {+ eventId: event.id,+ companyId: company.companyId,+ chargeId: charge.id+ });+ break;+ }++ if (!charge.refunded) {+ // Partial refund — Stripe only sets `refunded: true` once the FULL+ // charge amount has been returned. There is no partial-reversal+ // journal capability, so this is surfaced for manual handling+ // rather than voiding the whole payment.+ logger.warn(+ "Partial Stripe Connect refund — no automated GL reversal, needs manual handling",+ {+ eventId: event.id,+ companyId: company.companyId,+ chargeId: charge.id,+ stripeInvoiceId,+ amountRefunded: charge.amount_refunded,+ amountCaptured: charge.amount_captured+ }+ );+ break;+ }++ const result = await voidStripeConnectPayment({+ companyId: company.companyId,+ stripeInvoiceId+ });+ logger.info("Stripe Connect payment voided for a full refund", {+ eventId: event.id,+ companyId: company.companyId,+ stripeInvoiceId,+ result+ });+ break;+ }++ case "charge.dispute.closed": {+ const dispute = event.data.object as ConnectDispute;+ if (dispute.status !== "lost") {+ // won / warning_* / needs_response — no funds actually changed+ // hands yet, nothing to reverse.+ logger.info("Stripe Connect dispute closed without a loss", {+ eventId: event.id,+ companyId: company.companyId,+ disputeId: dispute.id,+ status: dispute.status+ });+ break;+ }++ const chargeId =+ typeof dispute.charge === "string"+ ? dispute.charge+ : dispute.charge.id;+ const stripeInvoiceId = await getStripeInvoiceIdForCharge(+ company.companyId,+ chargeId+ );++ if (!stripeInvoiceId) {+ logger.warn("Lost dispute has no traceable invoice", {+ eventId: event.id,+ companyId: company.companyId,+ disputeId: dispute.id,+ chargeId+ });+ break;+ }++ const result = await voidStripeConnectPayment({+ companyId: company.companyId,+ stripeInvoiceId+ });+ logger.info("Stripe Connect payment voided for a lost dispute", {+ eventId: event.id,+ companyId: company.companyId,+ stripeInvoiceId,+ result+ });+ break;+ }++ case "account.updated": {+ const accountStatus = await getConnectAccountStatus(event.account);+ if (accountStatus) {+ await upsertCompanyIntegration(getCarbonServiceRole(), {+ id: "stripe-connect",+ companyId: company.companyId,+ active: true,+ metadata: { ...company.metadata, ...accountStatus },+ updatedBy: SYSTEM_UPDATED_BY+ });+ logger.info("Refreshed Stripe Connect account status", {+ eventId: event.id,+ companyId: company.companyId,+ chargesEnabled: accountStatus.chargesEnabled,+ payoutsEnabled: accountStatus.payoutsEnabled+ });+ }+ break;+ }++ default:+ logger.info("Unhandled Stripe Connect event", {+ type: event.type,+ eventId: event.id,+ companyId: company.companyId+ });+ }++ return { success: true };+ } catch (error) {+ // 500 so Stripe retries — the failures that reach here are the fixable+ // configuration ones (missing bank account, missing sequence).+ logger.error("Stripe Connect webhook error", {+ error,+ type: event.type,+ eventId: event.id,+ companyId: company.companyId+ });+ return data({ error: "Webhook processing failed" }, { status: 500 });+ }+}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsxindex 99ae14254d..6794db89d5 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx@@ -1,11 +1,23 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import type { Json } from "@carbon/database";import { SalesInvoiceEmail } from "@carbon/documents/email";+import { createMappingService } from "@carbon/ee/accounting";import { validator } from "@carbon/form";import { trigger } from "@carbon/jobs";import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";+import { getLogger } from "@carbon/logger";+import type { ConnectInvoiceLineInput } from "@carbon/stripe/connect.server";+import {+ createAndSendConnectInvoice,+ expectedConnectInvoiceTotal,+ retrieveConnectCustomer,+ upsertConnectCustomer+} from "@carbon/stripe/connect.server";+import { datetime } from "@carbon/utils";+import { parseDate, Time, toCalendarDateTime } from "@internationalized/date";import { renderAsync } from "@react-email/components";import { parseAcceptLanguage } from "intl-parse-accept-language";import type { ActionFunctionArgs } from "react-router";@@ -15,14 +27,458 @@ import {getSalesInvoice,getSalesInvoiceCustomerDetails,getSalesInvoiceLines,- getSalesInvoiceShipment+ getSalesInvoiceShipment,+ salesInvoicePostValidator,+ type stripeCustomerActions} from "~/modules/invoicing";-import { getCustomerContact, salesConfirmValidator } from "~/modules/sales";+import {+ resolveStripeCustomer,+ STRIPE_CONNECT_INTEGRATION+} from "~/modules/invoicing/stripe-customer.server";+import { getCustomerContact, updateCustomerContact } from "~/modules/sales";import { getCompany } from "~/modules/settings";+import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { getUser } from "~/modules/users/users.server";import { loader as pdfLoader } from "~/routes/file+/sales-invoice+/$id[.]pdf";+import { getDatabaseClient } from "~/services/database.server";import { stripSpecialCharacters } from "~/utils/string";+const logger = getLogger("stripe-connect");++type ServiceRole = ReturnType<typeof getCarbonServiceRole>;++async function storeStripeInvoicePdf({+ serviceRole,+ invoicePdf,+ invoiceId,+ readableInvoiceId,+ opportunityId,+ companyId,+ userId+}: {+ serviceRole: ServiceRole;+ invoicePdf: string | null;+ invoiceId: string;+ readableInvoiceId: string | null;+ opportunityId: string | null;+ companyId: string;+ userId: string;+}) {+ if (!invoicePdf) return;++ // Storage layout is opportunity-scoped; without one this would write into a+ // literal "opportunity/null/" folder. The PDF is still reachable via the+ // Stripe hosted invoice URL, so skip the store rather than corrupt the path.+ if (!opportunityId) return;++ const response = await fetch(invoicePdf, {+ signal: AbortSignal.timeout(15_000)+ });+ if (!response.ok) {+ throw new Error(+ `Failed to download Stripe invoice PDF (${response.status})`+ );+ }+ const file = await response.arrayBuffer();++ const fileName = stripSpecialCharacters(+ `${readableInvoiceId ?? invoiceId} - Stripe.pdf`+ );+ const filePath = `${companyId}/opportunity/${opportunityId}/${fileName}`;++ const upload = await serviceRole.storage+ .from("private")+ .upload(filePath, file, {+ cacheControl: `${12 * 60 * 60}`,+ contentType: "application/pdf",+ upsert: true+ });++ if (upload.error) {+ throw new Error("Failed to upload Stripe invoice PDF");+ }++ const document = await upsertDocument(serviceRole, {+ path: filePath,+ name: fileName,+ size: Math.round(file.byteLength / 1024),+ sourceDocument: "Sales Invoice",+ sourceDocumentId: invoiceId,+ readGroups: [userId],+ writeGroups: [userId],+ createdBy: userId,+ companyId+ });++ if (document.error) {+ throw new Error("Failed to create document for the Stripe invoice PDF");+ }+}++async function appendStripeLinkToNotes({+ serviceRole,+ invoiceId,+ companyId,+ hostedInvoiceUrl,+ userId+}: {+ serviceRole: ServiceRole;+ invoiceId: string;+ companyId: string;+ hostedInvoiceUrl: string | null;+ userId: string;+}) {+ if (!hostedInvoiceUrl) return;++ const existing = await serviceRole+ .from("salesInvoice")+ .select("internalNotes")+ .eq("id", invoiceId)+ .eq("companyId", companyId)+ .single();++ if (existing.error) {+ throw new Error("Failed to read invoice notes");+ }++ const current = (existing.data?.internalNotes ?? {}) as {+ type?: string;+ content?: Json[];+ };+ const content = Array.isArray(current.content) ? current.content : [];++ const notes: Json = {+ type: "doc",+ content: [+ ...content,+ {+ type: "paragraph",+ content: [+ { type: "text", text: "Stripe payment link: " },+ {+ type: "text",+ text: hostedInvoiceUrl,+ marks: [{ type: "link", attrs: { href: hostedInvoiceUrl } }]+ }+ ]+ }+ ]+ };++ const update = await serviceRole+ .from("salesInvoice")+ .update({+ internalNotes: notes,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .eq("id", invoiceId)+ .eq("companyId", companyId);++ if (update.error) {+ throw new Error("Failed to write the Stripe payment link to invoice notes");+ }+}++type StripeSendContext = {+ stripeAccountId: string;+ /**+ * Already resolved and linked by the preflight — by the time the send runs,+ * the customer exists on the connected account and+ * `externalIntegrationMapping` points at it.+ */+ stripeCustomerId: string;+ customerName: string;+};++type SalesInvoiceLineRow = NonNullable<+ Awaited<ReturnType<typeof getSalesInvoiceLines>>["data"]+>[number];++/**+ * Carbon invoice lines → the Stripe mapping's line input.+ *+ * Comment lines carry no money and exist only to annotate the printed invoice,+ * so they are dropped rather than sent as zero-amount items. Every other field+ * is passed through untouched — in particular `taxPercent` stays the fraction+ * the column stores, and the `converted*` mirrors are ignored because Stripe+ * bills in the invoice's own currency, not the company's base currency.+ */+function toStripeInvoiceLines(+ lines: SalesInvoiceLineRow[]+): ConnectInvoiceLineInput[] {+ return lines+ .filter((line) => line.invoiceLineType !== "Comment")+ .map((line) => ({+ description: line.description ?? line.itemReadableId ?? "Item",+ quantity: line.quantity ?? 0,+ unitPrice: line.unitPrice ?? 0,+ addOnCost: line.addOnCost ?? 0,+ shippingCost: line.shippingCost ?? 0,+ nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,+ taxPercent: line.taxPercent ?? 0,+ unitOfMeasureCode: line.unitOfMeasureCode,+ metadata: {+ carbonLineId: line.id ?? "",+ carbonItemId: line.itemId ?? "",+ carbonLineType: line.invoiceLineType ?? "",+ carbonSalesOrderId: line.salesOrderId ?? "",+ carbonSalesOrderLineId: line.salesOrderLineId ?? ""+ }+ }));+}++/**+ * A Carbon calendar date → the Unix seconds Stripe wants.+ *+ * Anchored at midday on the company's business calendar rather than midnight:+ * Stripe renders the date in the connected account's own timezone, and a+ * midnight instant lands on the previous day for any account behind it.+ */+function toStripeEpochSeconds(+ date: string | null | undefined,+ timeZone: string+): number | undefined {+ if (!date) return undefined;+ return Math.trunc(+ toCalendarDateTime(parseDate(date), new Time(12))+ .toDate(timeZone)+ .getTime() / 1000+ );+}++const FIVE_YEARS_SECONDS = 5 * 365.25 * 24 * 60 * 60;++function clampDueDate(epoch: number | undefined): number | undefined {+ if (epoch === undefined) return undefined;+ // Native .toDate().getTime() is required to get Unix epoch seconds for Stripe.+ const now = Math.trunc(datetime.now("UTC").toDate().getTime() / 1000);+ if (epoch < now || epoch > now + FIVE_YEARS_SECONDS) return undefined;+ return epoch;+}++function clampEffectiveAt(epoch: number | undefined): number | undefined {+ if (epoch === undefined) return undefined;+ // Native .toDate().getTime() is required to get Unix epoch seconds for Stripe.+ const now = Math.trunc(datetime.now("UTC").toDate().getTime() / 1000);+ if (epoch > now) return now;+ if (epoch < now - FIVE_YEARS_SECONDS) return undefined;+ return epoch;+}++/**+ * Resolve the Stripe customer this invoice will be billed to, and link it.+ *+ * Runs BEFORE the invoice is posted, so a customer that cannot be resolved+ * aborts the whole operation rather than leaving a posted invoice that was+ * never sent.+ *+ * The user's choice arrives from the post modal, but is never taken at face+ * value: `resolveStripeCustomer` is re-run here — the same function the modal+ * called — and the action is checked against what the connected account+ * actually looks like now. That closes the gap between the dialog being shown+ * and the form being submitted (a customer deleted in the Stripe dashboard, a+ * mapping written by a concurrent post, a hand-rolled form body naming someone+ * else's customer id).+ */+async function preflightStripeSend({+ serviceRole,+ companyId,+ userId,+ invoiceId,+ customerContact,+ stripeCustomerAction,+ stripeCustomerId,+ stripeContactEmail+}: {+ serviceRole: ServiceRole;+ companyId: string;+ userId: string;+ invoiceId: string;+ customerContact?: string;+ stripeCustomerAction?: (typeof stripeCustomerActions)[number];+ stripeCustomerId?: string;+ stripeContactEmail?: string;+}): Promise<+ { ok: true; context: StripeSendContext } | { ok: false; message: string }+> {+ if (!customerContact) {+ return { ok: false, message: "a customer contact is required" };+ }+ if (!stripeCustomerAction) {+ return { ok: false, message: "the Stripe customer was not confirmed" };+ }++ if (stripeContactEmail) {+ const contact = await getCustomerContact(serviceRole, customerContact);+ if (contact.data && !contact.data.contact?.email) {+ const update = await updateCustomerContact(serviceRole, {+ contactId: contact.data.contactId,+ contact: {+ firstName: contact.data.contact?.firstName ?? "",+ lastName: contact.data.contact?.lastName ?? "",+ email: stripeContactEmail+ }+ });+ if (update.error) {+ return { ok: false, message: "the contact email could not be saved" };+ }+ }+ }++ const resolved = await resolveStripeCustomer({+ serviceRole,+ companyId,+ invoiceId,+ customerContactId: customerContact,+ emailOverride: stripeContactEmail+ });++ if (!resolved.sources) {+ return {+ ok: false,+ message:+ resolved.resolution.state === "unavailable"+ ? resolved.resolution.message+ : "the Stripe customer could not be resolved"+ };+ }++ const { stripeAccountId, billingCustomerId, sources, input } = resolved;++ if (!input) {+ return { ok: false, message: "the selected contact has no email address" };+ }++ const customerName = sources.customer.name;+ if (!customerName) {+ return { ok: false, message: "the customer could not be loaded" };+ }++ const [lines, shipment] = await Promise.all([+ getSalesInvoiceLines(serviceRole, invoiceId),+ getSalesInvoiceShipment(serviceRole, invoiceId)+ ]);++ // The same arithmetic the send itself reconciles against, so an invoice that+ // is billable only through its surcharges isn't rejected here as empty.+ const { total } = expectedConnectInvoiceTotal({+ lines: toStripeInvoiceLines(lines.data ?? []),+ shippingCost: shipment.data?.shippingCost ?? undefined+ });+ if (total <= 0) {+ return {+ ok: false,+ message: "Stripe cannot send a zero-amount invoice"+ };+ }++ const mappingService = createMappingService(getDatabaseClient(), companyId);++ let resolvedCustomerId: string;++ switch (stripeCustomerAction) {+ case "use-linked": {+ // The dialog showed a linked customer; it must still be linked and live.+ // Falling through to a create here would put a customer on the merchant's+ // account that the user never agreed to.+ if (resolved.resolution.state !== "linked") {+ return {+ ok: false,+ message:+ "the linked Stripe customer is no longer available — reopen the dialog"+ };+ }+ resolvedCustomerId = resolved.resolution.customer.id;+ break;+ }+ case "link-existing": {+ if (!stripeCustomerId) {+ return {+ ok: false,+ message: "no Stripe customer was selected to link"+ };+ }+ // Confirm the id exists on THIS connected account before writing it into+ // the mapping — an id from another account (or an invented one) would+ // otherwise be linked and every future invoice would fail at send.+ const existing = await retrieveConnectCustomer(+ stripeAccountId,+ stripeCustomerId+ );+ if (!existing) {+ return {+ ok: false,+ message: "that Stripe customer no longer exists on this account"+ };+ }+ resolvedCustomerId = existing.id;+ break;+ }+ case "create": {+ // A concurrent post (or a link made since the dialog opened) means this+ // Carbon customer now HAS a Stripe customer. Creating a second one is+ // exactly what this flow exists to prevent, so stop and let the user+ // confirm the one that now exists.+ if (resolved.resolution.state === "linked") {+ return {+ ok: false,+ message:+ "this customer was just linked to a Stripe customer — reopen the dialog to confirm it"+ };+ }+ try {+ resolvedCustomerId = await upsertConnectCustomer(+ stripeAccountId,+ null,+ input+ );+ } catch (err) {+ // A genuinely concurrent post for the same unlinked customer reuses+ // the same idempotency key (upsertConnectCustomer scopes it by+ // companyId+carbonCustomerId) — Stripe rejects the SECOND request+ // in-flight with an idempotency_error rather than returning the+ // first request's result. The winning request finishes and links+ // its mapping shortly after, so re-resolve once instead of failing+ // the whole send outright.+ if ((err as { type?: string }).type !== "idempotency_error") {+ throw err;+ }+ await new Promise((resolve) => setTimeout(resolve, 500));+ const retried = await resolveStripeCustomer({+ serviceRole,+ companyId,+ invoiceId,+ customerContactId: customerContact,+ emailOverride: stripeContactEmail+ });+ if (retried.resolution.state !== "linked") {+ throw err;+ }+ resolvedCustomerId = retried.resolution.customer.id;+ }+ break;+ }+ }++ await mappingService.link(+ "customer",+ billingCustomerId,+ STRIPE_CONNECT_INTEGRATION,+ resolvedCustomerId,+ { createdBy: userId }+ );++ return {+ ok: true,+ context: {+ stripeAccountId,+ stripeCustomerId: resolvedCustomerId,+ customerName+ }+ };+}+export async function action(args: ActionFunctionArgs) {const { request, params } = args;assertIsPost(request);@@ -45,6 +501,66 @@ export async function action(args: ActionFunctionArgs) {let fileName: string;let documentFilePath: string;+ const serviceRole = getCarbonServiceRole();++ const validation = await validator(salesInvoicePostValidator).validate(+ await request.formData()+ );++ if (validation.error) {+ return {+ success: false,+ message: "Invalid notification type"+ };+ }++ const {+ notification,+ customerContact,+ cc: ccSelections,+ stripeCustomerAction,+ stripeCustomerId,+ stripeContactEmail,+ stripeDueDate+ } = validation.data;++ let stripeSendContext: StripeSendContext | null = null;+ if (notification === "Stripe") {+ // The invoice has not been posted yet at this point, so an uncaught+ // Stripe API error here must not become a raw 500 — surface it the same+ // way an ordinary preflight failure is surfaced.+ let preflight: Awaited<ReturnType<typeof preflightStripeSend>>;+ try {+ preflight = await preflightStripeSend({+ serviceRole,+ companyId,+ userId,+ invoiceId,+ customerContact,+ stripeCustomerAction,+ stripeCustomerId,+ stripeContactEmail+ });+ } catch (err) {+ logger.error("Stripe preflight failed", { error: err, invoiceId });+ return {+ success: false,+ message: `Invoice not posted — ${+ err instanceof Error ? err.message : "the Stripe preflight failed"+ }`+ };+ }++ if (!preflight.ok) {+ return {+ success: false,+ message: `Invoice not posted — ${preflight.message}`+ };+ }++ stripeSendContext = preflight.context;+ }+const setPendingState = await client.from("salesInvoice").update({@@ -59,8 +575,6 @@ export async function action(args: ActionFunctionArgs) {};}- const serviceRole = getCarbonServiceRole();-try {const postSalesInvoice = await serviceRole.functions.invoke("post-sales-invoice",@@ -198,19 +712,6 @@ export async function action(args: ActionFunctionArgs) {};}- const validation = await validator(salesConfirmValidator).validate(- await request.formData()- );-- if (validation.error) {- return {- success: false,- message: "Invalid notification type"- };- }-- const { notification, customerContact, cc: ccSelections } = validation.data;-switch (notification) {case "Email":try {@@ -347,6 +848,160 @@ export async function action(args: ActionFunctionArgs) {};}break;+ case "Stripe": {+ let stripeInvoice: Awaited<+ ReturnType<typeof createAndSendConnectInvoice>+ >;+ try {+ if (!stripeSendContext) {+ return {+ success: false,+ message: "Invoice posted, but the Stripe send was not prepared"+ };+ }++ // Resolved, confirmed by the user, and linked in the preflight — by+ // here the customer is known to exist on the connected account.+ const { stripeAccountId, stripeCustomerId, customerName } =+ stripeSendContext;++ const [invoiceLines, shipment, addresses, timeZone] = await Promise.all(+ [+ getSalesInvoiceLines(serviceRole, invoiceId),+ getSalesInvoiceShipment(serviceRole, invoiceId),+ getSalesInvoiceCustomerDetails(serviceRole, invoiceId),+ getCompanyTimeZone(serviceRole, companyId)+ ]+ );++ const shippingAddress = addresses.data?.shipmentAddressLine1+ ? {+ name:+ addresses.data.shipmentCustomerName ??+ addresses.data.customerName ??+ customerName,+ address: {+ line1: addresses.data.shipmentAddressLine1 ?? undefined,+ line2: addresses.data.shipmentAddressLine2 ?? undefined,+ city: addresses.data.shipmentCity ?? undefined,+ state: addresses.data.shipmentStateProvince ?? undefined,+ postal_code: addresses.data.shipmentPostalCode ?? undefined,+ country: addresses.data.shipmentCountryCode ?? undefined+ }+ }+ : undefined;++ stripeInvoice = await createAndSendConnectInvoice(+ stripeAccountId,+ stripeCustomerId,+ {+ lines: toStripeInvoiceLines(invoiceLines.data ?? []),+ currencyCode: salesInvoice.data.currencyCode ?? "USD",+ // Invoice-level freight, which the salesInvoices view adds after+ // tax — it is not one of the taxable per-line components.+ shippingCost: shipment.data?.shippingCost ?? 0,+ invoiceNumber: salesInvoice.data.invoiceId ?? undefined,+ // stripeDueDate is the user-chosen override from the post modal,+ // submitted only when the invoice's own dateDue wouldn't survive+ // clampDueDate (missing, past, or too far out). Re-clamped here+ // regardless of source — never trust client input for what+ // reaches a merchant's live Stripe account.+ dueDate: clampDueDate(+ toStripeEpochSeconds(+ stripeDueDate || salesInvoice.data.dateDue,+ timeZone+ )+ ),+ effectiveAt: clampEffectiveAt(+ toStripeEpochSeconds(+ salesInvoice.data.dateIssued ?? salesInvoice.data.postingDate,+ timeZone+ )+ ),+ customFields: salesInvoice.data.customerReference+ ? [+ {+ name: "Reference",+ value: salesInvoice.data.customerReference+ }+ ]+ : undefined,+ shippingDetails: shippingAddress,+ metadata: {+ carbonInvoiceId: invoiceId,+ carbonInvoiceNumber: salesInvoice.data.invoiceId ?? "",+ companyId,+ carbonOpportunityId: salesInvoice.data.opportunityId ?? "",+ carbonShipmentId: salesInvoice.data.shipmentId ?? ""+ }+ }+ );++ const mappingService = createMappingService(+ getDatabaseClient(),+ companyId+ );++ await mappingService.link(+ "salesInvoice",+ invoiceId,+ STRIPE_CONNECT_INTEGRATION,+ stripeInvoice.id,+ {+ metadata: {+ hostedInvoiceUrl: stripeInvoice.hostedInvoiceUrl,+ invoicePdf: stripeInvoice.invoicePdf+ }+ }+ );+ } catch (err) {+ logger.error("Failed to send sales invoice via Stripe", {+ error: err,+ invoiceId+ });+ return {+ success: false,+ message: `Invoice posted, but failed to send via Stripe: ${+ err instanceof Error ? err.message : "unknown error"+ }`+ };+ }++ // Best-effort cleanup — the Stripe invoice has already been created and+ // sent to the customer at this point, so a failure here must not read+ // as a failed send: that would prompt a retry and create a SECOND+ // Stripe invoice. Log and move on; the hosted invoice URL and PDF are+ // still reachable directly on Stripe if this drops.+ try {+ await Promise.all([+ storeStripeInvoicePdf({+ serviceRole,+ invoicePdf: stripeInvoice.invoicePdf,+ invoiceId,+ readableInvoiceId: salesInvoice.data.invoiceId,+ opportunityId: salesInvoice.data.opportunityId,+ companyId,+ userId+ }),+ appendStripeLinkToNotes({+ serviceRole,+ invoiceId,+ companyId,+ hostedInvoiceUrl: stripeInvoice.hostedInvoiceUrl,+ userId+ })+ ]);+ } catch (err) {+ logger.error("Stripe invoice sent, but post-send cleanup failed", {+ error: err,+ invoiceId+ });+ }+ return {+ success: true,+ message: "Invoice posted and sent via Stripe"+ };+ }case undefined:case "None":break;diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsxindex a660310508..19b9ff8199 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx@@ -2,6 +2,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";+import { createMappingService } from "@carbon/ee/accounting";import { VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";@@ -14,6 +15,7 @@ import {getSalesInvoiceLines,getSalesInvoiceShipment} from "~/modules/invoicing";+import { STRIPE_CONNECT_INTEGRATION } from "~/modules/invoicing/stripe-customer.server";import SalesInvoiceExplorer from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer";import SalesInvoiceHeader from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader";import SalesInvoiceProperties from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties";@@ -23,6 +25,7 @@ import {getOpportunityDocuments} from "~/modules/sales/sales.service";import { getCompanySettings } from "~/modules/settings";+import { getDatabaseClient } from "~/services/database.server";import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -85,6 +88,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {? customer.data.defaultCc: (companySettings.data?.defaultCustomerCc ?? []);+ // Fetch Stripe invoice URL if this invoice was posted via Stripe+ let stripeInvoiceUrl: string | null = null;+ if (salesInvoice.data?.postingDate) {+ const mappingService = createMappingService(getDatabaseClient(), companyId);+ const mapping = await mappingService.getByEntity(+ "salesInvoice",+ invoiceId,+ STRIPE_CONNECT_INTEGRATION+ );+ if (mapping?.metadata) {+ const metadata = mapping.metadata as Record<string, unknown> | undefined;+ stripeInvoiceUrl =+ (metadata?.hostedInvoiceUrl as string | undefined) ?? null;+ }+ }+return {salesInvoice: salesInvoice.data,currency: currency?.data ?? null,@@ -98,7 +117,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {opportunity: opportunity?.data ?? null,customer: customer?.data ?? null,defaultCc,- orgHasCredits+ orgHasCredits,+ stripeInvoiceUrl};}diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 671f160ecf..d0830f1183 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -47,9 +47,14 @@ import {import { getPath, SECRET_KEYS } from "@carbon/ee/integrations/secrets";import { isIntegrationWhitelisted } from "@carbon/ee/plan";import { requirePlan } from "@carbon/ee/plan.server";+import { STRIPE_SECRET_KEY } from "@carbon/env";import { validationError, validator } from "@carbon/form";import { getLogger } from "@carbon/logger";import { Badge } from "@carbon/react";+import {+ getConnectAccountStatus,+ isConnectAccountStillLinked+} from "@carbon/stripe/connect.server";import { Trans } from "@lingui/react/macro";import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";@@ -704,8 +709,93 @@ export async function loader({ request, params }: LoaderFunctionArgs) {logger.error("Failed to fetch Xero accounts for settings", {error: error});- // Continue without chart accounts — the Account Mapping tab renders- // with Carbon accounts only+ // Continue without dynamic options - form will show empty selects+ }+ } else if (integrationId === "stripe-connect") {+ // Whether the platform even has a Stripe secret key configured — cheap,+ // synchronous, known without ever calling Stripe. Display-only: never+ // part of the submitted form/schema, so merging it into metadata here+ // doesn't risk it being written back to the DB on save.+ flattenedMetadata.platformConfigured = !!STRIPE_SECRET_KEY;++ // Refresh Stripe Connect's status from Stripe so the drawer shows live+ // onboarding progress rather than a possibly-stale stored snapshot.+ if (flattenedMetadata.stripeAccountId) {+ const stripeAccountId = flattenedMetadata.stripeAccountId as string;+ try {+ if (await isConnectAccountStillLinked(stripeAccountId)) {+ const freshStatus = await getConnectAccountStatus(stripeAccountId);+ if (freshStatus) {+ Object.assign(flattenedMetadata, freshStatus);+ }+ } else {+ logger.warn(+ "Stripe Connect account is no longer linked; hiding stale connection state",+ { companyId, stripeAccountId }+ );+ delete flattenedMetadata.stripeAccountId;+ delete flattenedMetadata.chargesEnabled;+ delete flattenedMetadata.payoutsEnabled;+ delete flattenedMetadata.detailsSubmitted;+ delete flattenedMetadata.requirementErrors;+ delete flattenedMetadata.email;+ delete flattenedMetadata.displayName;+ delete flattenedMetadata.onboardingStarted;+ }+ } catch (err) {+ logger.error("Failed to fetch Stripe Connect status for settings", {+ error: err+ });+ }+ }++ const accountDefaults = await client+ .from("accountDefault")+ .select(+ `bankCashAccount, receivablesAccount, customerPaymentDiscountAccount, customerWriteOffAccount, realizedExchangeGainAccount, realizedExchangeLossAccount, serviceChargeAccount, roundingAccount`+ )+ .eq("companyId", companyId)+ .single();++ if (accountDefaults.data) {+ const accountIds = [+ accountDefaults.data.bankCashAccount,+ accountDefaults.data.receivablesAccount,+ accountDefaults.data.customerPaymentDiscountAccount,+ accountDefaults.data.customerWriteOffAccount,+ accountDefaults.data.realizedExchangeGainAccount,+ accountDefaults.data.realizedExchangeLossAccount,+ accountDefaults.data.serviceChargeAccount,+ accountDefaults.data.roundingAccount+ ].filter(Boolean);++ if (accountIds.length > 0) {+ const { data: accounts } = await client+ .from("account")+ .select("id, number, name")+ .in("id", accountIds);++ const byId = new Map((accounts ?? []).map((a) => [a.id, a]));++ const fmt = (id: string | null) => {+ if (!id) return null;+ const a = byId.get(id);+ return a ? (a.number ? `${a.number} — ${a.name}` : a.name) : null;+ };++ flattenedMetadata.accountingAccounts = {+ bankCash: fmt(accountDefaults.data.bankCashAccount),+ receivables: fmt(accountDefaults.data.receivablesAccount),+ customerPaymentDiscount: fmt(+ accountDefaults.data.customerPaymentDiscountAccount+ ),+ customerWriteOff: fmt(accountDefaults.data.customerWriteOffAccount),+ fxGain: fmt(accountDefaults.data.realizedExchangeGainAccount),+ fxLoss: fmt(accountDefaults.data.realizedExchangeLossAccount),+ serviceCharge: fmt(accountDefaults.data.serviceChargeAccount),+ rounding: fmt(accountDefaults.data.roundingAccount)+ };+ }}}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 6df0fe94f9..321fdf1d92 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -260,6 +260,18 @@ export const path = {itemId ? `&itemId=${itemId}` : ""}`),+ stripeConnectCustomer: (+ invoiceId: string,+ customerContactId: string,+ email?: string+ ) => {+ const params = new URLSearchParams({ contact: customerContactId });+ if (email) params.set("email", email);+ return generatePath(+ `${api}/stripe-connect/customer/${invoiceId}?${params.toString()}`+ );+ },+ stripeConnectOnboard: `${api}/integrations/stripe-connect/connect`,supplierContacts: (id: string) =>generatePath(`${api}/purchasing/supplier-contacts/${id}`),supplierLocations: (id: string) =>diff --git a/ci/src/deploy.ts b/ci/src/deploy.tsindex f324ffd767..546ca32491 100644--- a/ci/src/deploy.ts+++ b/ci/src/deploy.ts@@ -71,6 +71,7 @@ export type Workspace = {stripe_bypass_company_ids: string | null;stripe_secret_key: string | null;stripe_webhook_secret: string | null;+ stripe_connect_webhook_secret: string | null;url_erp: string | null;url_mes: string | null;xero_client_id: string | null;@@ -154,6 +155,7 @@ async function deploy(): Promise<void> {stripe_bypass_company_ids,stripe_secret_key,stripe_webhook_secret,+ stripe_connect_webhook_secret,url_erp,url_mes,xero_client_id,@@ -310,6 +312,8 @@ async function deploy(): Promise<void> {STRIPE_BYPASS_COMPANY_IDS: stripe_bypass_company_ids ?? undefined,STRIPE_SECRET_KEY: stripe_secret_key ?? undefined,STRIPE_WEBHOOK_SECRET: stripe_webhook_secret ?? undefined,+ STRIPE_CONNECT_WEBHOOK_SECRET:+ stripe_connect_webhook_secret ?? undefined,SUPABASE_ANON_KEY: anon_key,SUPABASE_DB_URL: database_connection_pooler_url,SUPABASE_JWT_SECRET: jwt_secret ?? undefined,diff --git a/docs/content/docs/platform/self-hosting/environment-variables.mdx b/docs/content/docs/platform/self-hosting/environment-variables.mdxindex 4a12a151c5..94cb902796 100644--- a/docs/content/docs/platform/self-hosting/environment-variables.mdx+++ b/docs/content/docs/platform/self-hosting/environment-variables.mdx@@ -69,6 +69,7 @@ Sign-in bot protection uses Cloudflare Turnstile: `CLOUDFLARE_TURNSTILE_SITE_KEY<EnvVar name="RESEND_DOMAIN" type="string">Verified sending domain.</EnvVar><EnvVar name="STRIPE_SECRET_KEY" type="string">Stripe secret key, Cloud / Enterprise billing.</EnvVar><EnvVar name="STRIPE_WEBHOOK_SECRET" type="string">Verifies inbound Stripe webhooks.</EnvVar>+<EnvVar name="STRIPE_CONNECT_WEBHOOK_SECRET" type="string">Verifies inbound Stripe Connect webhooks (connected-account events, signed with a separate secret).</EnvVar></EnvVars>## AI & analyticsdiff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex a0b4159d2b..b7f11b76ae 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -428,6 +428,8 @@"no-raw-rounding::apps/erp/app/routes/x+/resources+/_index.tsx::{percentageChange.toFixed(0)}%","no-raw-rounding::apps/erp/app/routes/x+/sales+/_index.tsx::<Badge variant=\"green\">+{percentageChange.toFixed(0)}%</Badge>","no-raw-rounding::apps/erp/app/routes/x+/sales+/_index.tsx::<Badge variant=\"red\">{percentageChange.toFixed(0)}%</Badge>",+ "no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::const now = Math.floor(Date.now() / 1000);",+ "no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::return Math.floor(","no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::size: Math.round(file.byteLength / 1024),","no-raw-rounding::apps/erp/app/routes/x+/settings+/backups.tsx::{convertKbToString(Math.round(file.sizeBytes / 1024))}","no-raw-rounding::apps/erp/app/routes/x+/settings+/printing.tsx::const heightDots = Math.round(height * dpi);",@@ -505,6 +507,8 @@"no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-reconciliation.ts::const cents = Math.round(","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(amount * 100);","no-raw-rounding::packages/jobs/src/inngest/functions/integrations/accounting-sync-operations.ts::const cents = Math.round(line.amount * 100);",+ "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts::: Math.floor(Date.now() / 1000) - 60 * 60 * 24 * 7; // 7 days max",+ "no-raw-rounding::packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts::? Math.floor(new Date(target.updatedAt).getTime() / 1000)","no-raw-rounding::packages/jobs/src/inngest/functions/scheduled/cleanup.ts::await step.sleep(\"jitter\", `${Math.floor(Math.random() * 3600)}s`);","no-raw-rounding::packages/react/src/BarProgress.tsx::<span className=\"sr-only\">{Math.round(percentage)}%</span>","no-raw-rounding::packages/react/src/BarProgress.tsx::const activeBars = Math.round((clampedProgress / max) * barCount);",diff --git a/packages/database/supabase/functions/post-payment/build-payment-journal.ts b/packages/database/supabase/functions/post-payment/build-payment-journal.tsindex 2ef9028f31..92915d8868 100644--- a/packages/database/supabase/functions/post-payment/build-payment-journal.ts+++ b/packages/database/supabase/functions/post-payment/build-payment-journal.ts@@ -19,7 +19,13 @@// AP refund (cash in from a supplier against a debit memo): !isAR && cashIn.//// Posting model (all amounts converted to base currency):-// 1) Cash — DR Bank (cashIn) / CR Bank (!cashIn) for the full cash.+// 1) Cash — DR Bank (cashIn) / CR Bank (!cashIn). When a processor fee is+// deducted AT SOURCE (e.g. Stripe never deposits the gross —+// the fee is withheld before the payout lands), the bank line+// carries only the NET amount and a same-side fee expense line+// makes up the difference, so the entry reflects what actually+// moved through the bank rather than a gross deposit that never+// happened.// 2) Per app — control account (AR/AP) at the TARGET rate so it reverses the// original booking exactly; discount and write-off (also// invoice-currency reliefs) at the target rate; realized FX on@@ -72,6 +78,17 @@ export interface PaymentJournalAccounts {fxLossAccountId: string | null;}+// A fee withheld by a payment processor BEFORE the cash reaches the bank (e.g.+// Stripe Connect's per-charge commission) — never a fee billed separately. The+// caller resolves the account (a per-integration override or the company's+// service-charge default) and converts nothing; `amount` is in the payment's+// own currency, same as `totalAmount`, and gets the same exchangeRate applied.+export interface PaymentJournalFeeInput {+ amount: number;+ accountId: string;+ description?: string;+}+export interface BuildPaymentJournalInput {// Internal payment record id — becomes `documentId` on every line.paymentId: string;@@ -86,6 +103,7 @@ export interface BuildPaymentJournalInput {journalLineReference: string;applications: PaymentJournalApplicationInput[];accounts: PaymentJournalAccounts;+ fee?: PaymentJournalFeeInput;}export interface BuildPaymentJournalResult {@@ -115,6 +133,7 @@ export function buildPaymentJournal(journalLineReference,applications,accounts,+ fee,} = input;const {@@ -164,12 +183,25 @@ export function buildPaymentJournal(});};- // 1) Cash: DR Bank (cash in) / CR Bank (cash out), full cash in base.- const cashBase = round(totalAmount * exchangeRate);- pushLine(cashIn ? "debit" : "credit", "asset", cashBase, {+ // 1) Cash: DR Bank (cash in) / CR Bank (cash out). A processor fee withheld+ // at source never reaches the bank, so it comes OUT of the cash line+ // (not booked against a gross deposit that never happened) and gets its+ // own expense line on the SAME side — the control account below is still+ // relieved at the full (gross) applied amount, since the fee is between+ // us and the processor, not something the customer/supplier owes less of.+ const grossBase = round(totalAmount * exchangeRate);+ const feeBase = fee && fee.amount > 0 ? round(fee.amount * exchangeRate) : 0;+ const netBase = round(grossBase - feeBase);+ pushLine(cashIn ? "debit" : "credit", "asset", netBase, {accountId: bankAccount,description: "Bank / Cash",});+ if (feeBase > 0) {+ pushLine(cashIn ? "debit" : "credit", "expense", feeBase, {+ accountId: fee!.accountId,+ description: fee!.description ?? "Payment Processing Fee",+ });+ }// 2) Per application: control at TARGET rate; discount / write-off at target// rate. FX is accumulated and plugged once below.diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.tsindex 901eee73c0..8c49036dd7 100644--- a/packages/database/supabase/functions/post-payment/index.ts+++ b/packages/database/supabase/functions/post-payment/index.ts@@ -23,6 +23,17 @@ const payloadValidator = z.object({paymentId: z.string(),userId: z.string(),companyId: z.string(),+ // A fee withheld by a payment processor before the cash reached the bank+ // (e.g. Stripe Connect's per-charge commission). The caller resolves the+ // account (an integration override or the company's service-charge+ // default) — this function stays payment-processor-agnostic.+ fee: z+ .object({+ amount: z.number().positive(),+ accountId: z.string(),+ description: z.string().optional(),+ })+ .optional(),});serve(async (req: Request) => {@@ -32,7 +43,7 @@ serve(async (req: Request) => {const payload = await req.json();try {- const { type, paymentId, userId, companyId } =+ const { type, paymentId, userId, companyId, fee } =payloadValidator.parse(payload);console.log({ function: "post-payment", type, paymentId, userId, companyId });@@ -416,6 +427,7 @@ serve(async (req: Request) => {fxGainAccountId: ad.realizedExchangeGainAccount,fxLossAccountId: ad.realizedExchangeLossAccount,},+ fee,});journalLineInserts.push(...lines);}diff --git a/packages/database/supabase/functions/post-payment/post-payment.test.ts b/packages/database/supabase/functions/post-payment/post-payment.test.tsindex aa4572e351..540e1bb1ce 100644--- a/packages/database/supabase/functions/post-payment/post-payment.test.ts+++ b/packages/database/supabase/functions/post-payment/post-payment.test.ts@@ -207,6 +207,63 @@ Deno.test("AP write-off: vendor write-off income credited (revenue)", () => {assert(balanced(signedDebitTotal));});+// ---------------------------------------------------------------------------+// Processor fee — withheld at source (Stripe Connect), so it never touches the+// bank line. One journal entry, not a payment entry plus a follow-up fee entry.+// ---------------------------------------------------------------------------++Deno.test("AR with processor fee: net bank + fee expense / gross receivables, balanced", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ fee: { amount: 3, accountId: "servicecharge" },+ })+ );++ assertEquals(lines.length, 3);+ assertEquals(line(lines, "Bank / Cash")!.amount, 97); // (100 − 3) debit asset+ const feeLine = line(lines, "Payment Processing Fee")!;+ assertEquals(feeLine.accountId, "servicecharge");+ assertEquals(feeLine.amount, 3); // debit expense+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // gross, unaffected by the fee+ assert(balanced(signedDebitTotal));+});++Deno.test("AR with processor fee and custom description", () => {+ const { lines } = buildPaymentJournal(+ arBase({+ fee: { amount: 3, accountId: "servicecharge", description: "Stripe processing fee — INV-1" },+ })+ );++ assert(line(lines, "Stripe processing fee — INV-1") !== undefined);+ assert(line(lines, "Payment Processing Fee") === undefined);+});++Deno.test("AR with processor fee and FX: fee stays gross-of-FX, entry still balances", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ exchangeRate: 1.2,+ fee: { amount: 3, accountId: "servicecharge" },+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.2,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 116.4); // (100 × 1.2) − (3 × 1.2)+ assertEquals(line(lines, "Payment Processing Fee")!.amount, 3.6); // 3 × 1.2+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // 100 × 1.0+ assert(line(lines, "Realized FX Gain") !== undefined); // unaffected by the fee+ assert(balanced(signedDebitTotal));+});+// ---------------------------------------------------------------------------// Realized FX — the sign convention. These pin that AR collected high = gain,// AP paid high = LOSS (the case a reviewer mis-called as inverted).diff --git a/packages/database/supabase/migrations/20260805105526_add-stripe-connect-integration.sql b/packages/database/supabase/migrations/20260805105526_add-stripe-connect-integration.sqlnew file mode 100644index 0000000000..7a69467555--- /dev/null+++ b/packages/database/supabase/migrations/20260805105526_add-stripe-connect-integration.sql@@ -0,0 +1,4 @@+INSERT INTO "integration" ("id", "jsonschema")+VALUES+ ('stripe-connect', '{"type": "object", "properties": {}}'::json)+ON CONFLICT ("id") DO NOTHING;diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 9eb57a7028..3d4aa53bec 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -24,7 +24,8 @@"./hooks.server": "./src/hooks.server.ts","./quickbooks/hooks.server": "./src/quickbooks/hooks.server.ts","./rillet/hooks.server": "./src/rillet/hooks.server.ts",- "./xero/hooks.server": "./src/xero/hooks.server.ts"+ "./xero/hooks.server": "./src/xero/hooks.server.ts",+ "./stripe-connect.server": "./src/stripe-connect/payment.server.ts"},"private": true,"scripts": {@@ -43,6 +44,7 @@"@carbon/lib": "workspace:*","@carbon/logger": "workspace:*","@carbon/react": "workspace:*",+ "@carbon/stripe": "workspace:*","@carbon/utils": "workspace:*","@internationalized/date": "catalog:","@slack/bolt": "4.4.0",diff --git a/packages/ee/src/accounting/core/external-mapping.ts b/packages/ee/src/accounting/core/external-mapping.tsindex d1590bfc3a..075c8e50d6 100644--- a/packages/ee/src/accounting/core/external-mapping.ts+++ b/packages/ee/src/accounting/core/external-mapping.ts@@ -192,6 +192,31 @@ export class ExternalIntegrationMappingService {return (mapping as ExternalIntegrationMapping) ?? null;}+ /**+ * Get every mapping for an external ID — for the many-to-one relationships+ * `link()`'s `allowDuplicateExternalId` option enables. `getByExternalId`+ * (singular) uses `executeTakeFirst()` and can only ever surface one of them.+ */+ async getAllByExternalId(+ integration: string,+ externalId: string,+ entityType?: string+ ): Promise<ExternalIntegrationMapping[]> {+ let query = this.db+ .selectFrom("externalIntegrationMapping")+ .selectAll()+ .where("integration", "=", integration)+ .where("externalId", "=", externalId)+ .where("companyId", "=", this.companyId);++ if (entityType) {+ query = query.where("entityType", "=", entityType);+ }++ const mappings = await query.execute();+ return mappings as ExternalIntegrationMapping[];+ }+/*** Get all mappings for a Carbon entity (across all integrations).*/diff --git a/packages/ee/src/hooks.server.ts b/packages/ee/src/hooks.server.tsindex 0db1b9d135..3b1c657ffb 100644--- a/packages/ee/src/hooks.server.ts+++ b/packages/ee/src/hooks.server.ts@@ -11,6 +11,11 @@ import {rilletOnInstall,rilletOnUninstall} from "./rillet/hooks.server";+import {+ stripeConnectHealthcheck,+ stripeConnectOnInstall,+ stripeConnectOnUninstall+} from "./stripe-connect/hooks.server";import type { IntegrationServerHooks } from "./types";// Onshape keeps its release webhook subscription in lockstep with the asset-sync@@ -68,6 +73,11 @@ const serverHooks: Record<string, IntegrationServerHooks> = {onInstall: xeroOnInstall,onUpdate: xeroOnInstall,onUninstall: xeroOnUninstall+ },+ "stripe-connect": {+ onHealthcheck: stripeConnectHealthcheck,+ onInstall: stripeConnectOnInstall,+ onUninstall: stripeConnectOnUninstall}};diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.tsindex dc8370c237..b584ebc46d 100644--- a/packages/ee/src/index.ts+++ b/packages/ee/src/index.ts@@ -9,6 +9,7 @@ import { QuickBooks } from "./quickbooks/config";import { Rillet } from "./rillet/config";import { Sage } from "./sage/config";import { Slack } from "./slack/config";+import { StripeConnect } from "./stripe-connect/config";import type { QuickInstallConnector } from "./types";import { Xero } from "./xero/config";@@ -40,7 +41,8 @@ export const integrations = [Rillet,Sage,Slack,- Xero+ Xero,+ StripeConnect];export type IntegrationID = (typeof integrations)[number]["id"];@@ -53,6 +55,7 @@ export { QuickBooks } from "./quickbooks/config";export { Rillet } from "./rillet/config";export { Slack } from "./slack/config";export * from "./slack/lib/messages";+export { StripeConnect } from "./stripe-connect/config";export { Xero } from "./xero/config";/**diff --git a/packages/ee/src/stripe-connect/AGENTS.md b/packages/ee/src/stripe-connect/AGENTS.mdnew file mode 100644index 0000000000..fa88f2274e--- /dev/null+++ b/packages/ee/src/stripe-connect/AGENTS.md@@ -0,0 +1,137 @@+# @carbon/ee/stripe-connect++Stripe Connect integration for Carbon: onboarding connected accounts, resolving+Stripe customers for sales invoices, recording payments into the Carbon GL, and+syncing missed payments via a background sweep.++## Always++- **Import `recordStripeConnectPayment` only from `@carbon/ee/stripe-connect.server`** —+ it is the single authority for writing Stripe payments into Carbon. Both the+ webhook handler and the pull sweep call it; adding a third call site MUST go+ through the same function.+- **`recordStripeConnectPayment` is idempotent on Stripe invoice id, but NOT+ limited to one payment per invoice** — a duplicate delivery of the SAME+ `amount_paid` loses the race at the DB via the partial unique index on+ `externalIntegrationMapping` (`INTEGRATION="stripe-connect"`,+ `entityType="payment"`, `allowDuplicateExternalId=false`). A delivery with a+ HIGHER cumulative `amount_paid` than what's already recorded (installment /+ partial-payment invoices) instead records a new payment for just the delta,+ linked with `allowDuplicateExternalId: true` — so one Stripe invoice can map+ to several Carbon payments. Never guard with an ad-hoc SELECT before calling+ it, and never assume `getByExternalId` (singular) sees every payment for an+ invoice — use `mappingService.getAllByExternalId` for that.+- **`voidStripeConnectPayment` reverses every non-Voided payment mapped to an+ invoice** — it's a FULL reversal only (via `post-payment`'s `void` op,+ which mirrors every journal line including the fee). There is no partial+ reversal capability; a partial refund is logged, not acted on.+- **All external-ID links go through `createMappingService` from `@carbon/ee/accounting`** —+ `mappingService.getByExternalId`, `mappingService.getEntityId`, `mappingService.link`.+ Do not add per-entity `externalId` columns.+- **Hooks must stay in `hooks.server.ts`** — registered under `"stripe-connect"`+ in `packages/ee/src/hooks.server.ts`. Server-only imports (e.g. `@carbon/stripe/connect.server`)+ must not appear in `config.tsx` (bundled for client).+- **`StripeConnect` config and `StripeConnectSettingsSchema` are exported from `@carbon/ee`**+ (the root barrel) — the integration framework reads them there. Do not re-export+ from a separate subpath.++## Ask First++- Changing the accounting accounts that are used for FX gain/loss or service-charge+ fees — these are read from `accountDefault` at record time and affect live GL entries.+- Adding or removing Stripe capabilities on the account-creation constants in+ `@carbon/stripe/connect.constants.ts`.+- Making `stripeConnectOnInstall` or `stripeConnectOnUninstall` non-stubs — currently+ no-ops; any side effects must be reviewed against the install lifecycle.++## Never++- **Do not call `serviceRole.from("payment").delete(...)` outside of `recordStripeConnectPayment`** —+ the rollback path inside that function is the only place that deletes a payment+ row; orphaning `invoiceSettlement` rows by deleting their payment elsewhere will+ corrupt the AR ledger.+- **Do not advance a pull-sweep cursor on `paid_at` when the Stripe query filters on `created`** —+ invoices created before the cursor window but paid after it are permanently missed.+ Advance the cursor on the same field used in the list filter (`invoice.created`).+- **Do not surface post-send cleanup failures (PDF storage, notes append) as Stripe+ send failures** — the invoice is already sent to the customer. Log and continue;+ returning `success: false` after a sent invoice causes the caller to retry and+ create a duplicate Stripe invoice.++## Validation Commands++```bash+pnpm --filter @carbon/ee typecheck+pnpm --filter @carbon/ee test+```++## Key Exports++| Subpath | Provides |+|---|---|+| `@carbon/ee` (root) | `StripeConnect` integration definition, `StripeConnectSettingsSchema` |+| `@carbon/ee/stripe-connect.server` | `recordStripeConnectPayment`, `StripeConnectPaymentResult`, `voidStripeConnectPayment`, `StripeConnectVoidResult` |++## Key Functions++- **`recordStripeConnectPayment`** (`payment.server.ts`) — records a paid Stripe+ invoice as a Carbon `payment` row, settles it against the `salesInvoice`,+ posts the journal entry (bank debit, AR credit, service-charge expense via the+ `fee` field on `post-payment`), and writes to `externalIntegrationMapping`.+ Returns `{ status: "recorded" | "skipped" }`. Throws on fixable config errors+ (missing bank account, missing fee account, missing sequence) so Stripe retries.+ Reconciles against every prior mapping for the invoice before doing anything:+ a mapped payment still `Draft` (a prior delivery that inserted the payment ++ mapping but crashed before settlement/posting) is RESUMED at its own already-+ recorded amount; otherwise the delta between the invoice's current+ `amount_paid` and the sum already recorded is what gets recorded (0 or+ negative → skipped), with the processing fee prorated to that delta's share.+ The realized settlement-date exchange rate (`getConnectInvoicePaymentDetails().exchangeRate`,+ from Stripe's `balance_transaction.exchange_rate`) drives `invoiceSettlement.sourceExchangeRate`+ and `payment.exchangeRate`; the invoice's own booked rate stays on+ `targetExchangeRate` — this is what makes `totalFxImpact` in `post-payment`+ non-zero for a real FX payment instead of structurally suppressed.+- **`voidStripeConnectPayment`** (`payment.server.ts`) — reverses every+ non-Voided payment mapped to a Stripe invoice via `post-payment`'s `void` op+ (a full reversal that mirrors every journal line, fee included). Called on+ `charge.refunded` (full only), `charge.dispute.closed` (status `lost`), and+ `invoice.voided`. Returns `{ status: "voided", paymentIds } | { status: "skipped", reason }`;+ throws on a `post-payment` failure so the webhook returns 500 and Stripe retries.+- **`stripeConnectHealthcheck`** (`hooks.server.ts`) — called by the integration+ health system; returns `true` only when `chargesEnabled && payoutsEnabled` on+ the connected account. Returns `false` for missing accounts, Stripe errors,+ requirement errors, AND the normal mid-onboarding case (account exists, no+ errors yet, just not fully enabled) — the return type is a plain `boolean`,+ so a mid-onboarding account reads as unhealthy (red badge) until onboarding+ completes. `companyIntegration.active` goes `true` as soon as the Stripe+ account is created (see `getOrCreateConnectAccount`), before onboarding+ finishes, so it does NOT gate this neutral state — `getStripeConnectAccountId`+ (`apps/erp/app/modules/invoicing/stripe-customer.server.ts`) additionally+ checks `metadata.chargesEnabled` for exactly this reason.+- **`stripeConnectOnInstall` / `stripeConnectOnUninstall`** (`hooks.server.ts`) —+ currently no-ops; registered because the `IntegrationServerHooks` contract+ requires them.++## Tables Touched by `recordStripeConnectPayment`++| Table | Operation |+|---|---|+| `salesInvoices` | SELECT — look up the Carbon invoice by id |+| `accountDefault` | SELECT — resolve GL accounts for bank, AR, service charge |+| `companySettings` | SELECT — currency and payment sequence settings |+| `payment` | INSERT (and DELETE on rollback within the same function), plus a SELECT across all mapped payments for the invoice to compute the resume/delta decision |+| `invoiceSettlement` | DELETE + INSERT (Kysely transaction) — replace settlements |+| `externalIntegrationMapping` | SELECT (all mappings for the invoice) + INSERT — links a Stripe invoice to one or more payments |++## Cross-References++- `.claude/rules/billing-system.md` — plan/edition gating (`INTEGRATION_WHITELIST`, `FEATURE_PLANS`)+- `packages/stripe/AGENTS.md` — `@carbon/stripe/connect.server` API (`getConnectAccountStatus`,+ `getConnectInvoicePaymentDetails`, `fromStripeAmount`)+- `packages/ee/AGENTS.md` — `createMappingService` pattern, `externalIntegrationMapping` table+- `packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts` — background+ sweep that calls `recordStripeConnectPayment` for invoices missed by webhooks+- `apps/erp/app/routes/api+/webhook.stripe-connect.ts` — real-time webhook caller;+ also handles `charge.refunded`, `charge.dispute.closed`, `invoice.voided`+ (→ `voidStripeConnectPayment`) and `account.updated` (→ refreshes+ `chargesEnabled`/`payoutsEnabled`/requirement errors via `getConnectAccountStatus`)diff --git a/packages/ee/src/stripe-connect/config.tsx b/packages/ee/src/stripe-connect/config.tsxnew file mode 100644index 0000000000..b1eee2c668--- /dev/null+++ b/packages/ee/src/stripe-connect/config.tsx@@ -0,0 +1,325 @@+import { STRIPE_CONNECT_ENABLED } from "@carbon/env";+import { Badge, Button, toast } from "@carbon/react";+import type { ComponentProps } from "react";+import { useCallback, useState } from "react";+import { z } from "zod";+import { defineIntegration } from "../fns";++export const StripeConnectSettingsSchema = z.object({+ stripeAccountId: z.string().optional(),+ chargesEnabled: z.boolean().optional(),+ payoutsEnabled: z.boolean().optional(),+ autoEnableInvoicing: z.boolean().optional().default(true)+});++export const StripeConnect = defineIntegration({+ name: "Stripe Connect",+ id: "stripe-connect",+ // Only offered when the platform has a Stripe secret key configured — without+ // it every Connect call throws and the pull-sweep backstop no-ops, so the+ // whole feature is inert. Gated on the browser-safe STRIPE_CONNECT_ENABLED+ // flag (never the secret itself), mirroring how OAuth integrations gate on+ // their public clientId.+ active: STRIPE_CONNECT_ENABLED,+ category: "Payments",+ logo: StripeLogo,+ description:+ "Connect your Stripe account to send invoices with direct online payment options to your customers, automatically updating payment statuses and AR ledger entries.",+ shortDescription: "Accept card and ACH payments directly on sales invoices.",+ images: [],+ setupInstructions: StripeConnectStatus,+ schema: StripeConnectSettingsSchema,+ settingGroups: [+ {+ name: "Invoicing Settings",+ description: "Configure payment options for sales invoices"+ }+ ],+ settings: [+ {+ name: "autoEnableInvoicing",+ label: "Default to Online Payments",+ description:+ "Automatically include Stripe online payment links on newly created sales invoices",+ group: "Invoicing Settings",+ type: "switch" as const,+ required: false,+ value: true+ }+ ],+ actions: [+ {+ id: "dashboard",+ label: "Open Express Dashboard",+ description: "View payouts, transactions, and account details in Stripe",+ endpoint: "/api/integrations/stripe-connect/dashboard"+ }+ ]+});++function ConnectStripeAccountButton({+ label,+ onPlatformError+}: {+ label: string;+ onPlatformError: (message: string) => void;+}) {+ const [isLoading, setIsLoading] = useState(false);++ const handleClick = useCallback(async () => {+ setIsLoading(true);+ try {+ const response = await fetch("/api/integrations/stripe-connect/connect", {+ method: "POST"+ });+ const data = await response.json();++ if (data?.redirectUrl) {+ window.open(data.redirectUrl, "_blank", "noopener,noreferrer");+ return;+ }++ // A platform-level misconfiguration (e.g. this Stripe account was+ // never set up as a Connect platform) isn't something retrying fixes —+ // switch the panel to a persistent "ask your administrator" state+ // instead of just a one-off toast the user could miss.+ if (data?.isPlatformConfigError) {+ onPlatformError(+ data.error || "Stripe Connect isn't set up on this platform yet."+ );+ return;+ }++ toast.error(data?.error || "Failed to start Stripe Connect onboarding");+ } catch {+ toast.error("Failed to start Stripe Connect onboarding");+ } finally {+ setIsLoading(false);+ }+ }, [onPlatformError]);++ return (+ <Button+ variant="secondary"+ size="sm"+ onClick={handleClick}+ isLoading={isLoading}+ isDisabled={isLoading}+ >+ {label}+ </Button>+ );+}++function AccountingAccountRow({+ label,+ value+}: {+ label: string;+ value: string | null;+}) {+ return (+ <div className="flex items-center justify-between gap-2 py-1.5">+ <span className="text-xs text-muted-foreground">{label}</span>+ <span className="text-xs font-medium text-foreground truncate max-w-[60%] text-right">+ {value ?? "Not configured"}+ </span>+ </div>+ );+}++function StripeConnectStatus({+ metadata+}: {+ companyId: string;+ metadata?: Record<string, unknown>;+ installed?: boolean;+}) {+ const [platformError, setPlatformError] = useState<string | null>(null);++ // The loader always sets this for stripe-connect (even before any row+ // exists — see integrations.$id.tsx), so treat a missing value as+ // configured rather than silently showing State A on a loader hiccup.+ const platformConfigured = metadata?.platformConfigured !== false;+ const stripeAccountId = metadata?.stripeAccountId as string | undefined;+ const chargesEnabled = metadata?.chargesEnabled === true;+ const payoutsEnabled = metadata?.payoutsEnabled === true;+ const onboardingComplete = chargesEnabled && payoutsEnabled;+ const requirementErrors =+ (metadata?.requirementErrors as string[] | undefined) ?? [];+ const hasIssue = requirementErrors.length > 0;+ const email = metadata?.email as string | undefined;+ const displayName = metadata?.displayName as string | undefined;+ // A linked account already existing counts as "started" even if the flag+ // predates this field being introduced.+ const onboardingStarted =+ metadata?.onboardingStarted === true || !!stripeAccountId;++ const showPlatformIssue = !platformConfigured || !!platformError;++ const status = showPlatformIssue+ ? { label: "Not available", variant: "gray" as const }+ : !stripeAccountId+ ? { label: "Not connected", variant: "gray" as const }+ : onboardingComplete+ ? { label: "Active", variant: "green" as const }+ : hasIssue+ ? { label: "Needs attention", variant: "red" as const }+ : { label: "Pending onboarding", variant: "yellow" as const };++ const accountingAccounts = metadata?.accountingAccounts as+ | {+ bankCash: string | null;+ receivables: string | null;+ customerPaymentDiscount: string | null;+ customerWriteOff: string | null;+ fxGain: string | null;+ fxLoss: string | null;+ serviceCharge: string | null;+ rounding: string | null;+ }+ | undefined;++ return (+ <div className="flex flex-col gap-4">+ <input+ type="hidden"+ name="onboardingStarted"+ value={onboardingStarted ? "true" : "false"}+ />+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">Connection status</span>+ <Badge variant={status.variant}>{status.label}</Badge>+ </div>++ {showPlatformIssue ? (+ // State A: nothing the installing user can do here — retrying won't+ // help until an administrator fixes the platform-level Stripe setup.+ <p className="text-xs text-muted-foreground">+ {platformError ??+ "Stripe isn't configured on this platform yet. Ask your administrator to add a Stripe secret key with Connect enabled."}+ </p>+ ) : !stripeAccountId ? (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-muted-foreground">+ Connecting creates a Stripe Express account for this company from+ your Company Settings details — no extra info needed here — then+ sends you to Stripe to finish onboarding.+ </p>+ <div>+ <ConnectStripeAccountButton+ label="Connect Stripe Account"+ onPlatformError={setPlatformError}+ />+ </div>+ </div>+ ) : !onboardingComplete ? (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-muted-foreground">+ {hasIssue+ ? "Stripe flagged an issue with this account:"+ : "Your Stripe account has been created, but onboarding isn't complete — card payments and payouts won't work until it is."}+ </p>+ {hasIssue && (+ <ul className="list-disc pl-4 text-xs text-muted-foreground">+ {requirementErrors.map((message) => (+ <li key={message}>{message}</li>+ ))}+ </ul>+ )}+ <div>+ <ConnectStripeAccountButton+ label={hasIssue ? "Fix on Stripe" : "Finish Onboarding"}+ onPlatformError={setPlatformError}+ />+ </div>+ </div>+ ) : (+ <div className="flex flex-col gap-1">+ <p className="text-xs text-muted-foreground">+ Onboarding is complete. Use "Open Express Dashboard" below to view+ payouts and transactions on Stripe.+ </p>+ {(displayName || email) && (+ <p className="text-xs text-muted-foreground">+ Connected as {displayName || email}+ {displayName && email ? ` (${email})` : ""}.+ </p>+ )}+ </div>+ )}++ {accountingAccounts && (+ <div className="border-t border-border pt-4 flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ Accounting+ </span>+ <a+ href="/x/accounting/defaults"+ className="text-[0.6875rem] text-primary hover:underline"+ >+ Change in Account Defaults+ </a>+ </div>+ <p className="text-xs text-muted-foreground">+ GL accounts used when recording Stripe payments and fees.+ </p>+ <div className="flex flex-col divide-y divide-border/50">+ <AccountingAccountRow+ label="Bank / Cash"+ value={accountingAccounts.bankCash}+ />+ <AccountingAccountRow+ label="Accounts Receivable"+ value={accountingAccounts.receivables}+ />+ <AccountingAccountRow+ label="Customer Payment Discount"+ value={accountingAccounts.customerPaymentDiscount}+ />+ <AccountingAccountRow+ label="Customer Write-Off (Bad Debt)"+ value={accountingAccounts.customerWriteOff}+ />+ <AccountingAccountRow+ label="Realized FX Gain"+ value={accountingAccounts.fxGain}+ />+ <AccountingAccountRow+ label="Realized FX Loss"+ value={accountingAccounts.fxLoss}+ />+ <AccountingAccountRow+ label="Processing Fees"+ value={accountingAccounts.serviceCharge}+ />+ <AccountingAccountRow+ label="Rounding"+ value={accountingAccounts.rounding}+ />+ </div>+ </div>+ )}+ </div>+ );+}++function StripeLogo(props: ComponentProps<"svg">) {+ return (+ <svg+ {...props}+ width="40"+ height="40"+ viewBox="0 0 40 40"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <rect width="40" height="40" rx="8" fill="#000000" />+ <path+ d="M18.8 15.3C18.8 14.5 19.5 14.1 20.7 14.1C22.3 14.1 24.3 14.6 25.8 15.4V11.2C24.1 10.5 22.4 10.2 20.6 10.2C16 10.2 13 12.6 13 16.3C13 22.4 21.3 21.4 21.3 24.2C21.3 25.2 20.3 25.6 19 25.6C17.2 25.6 14.9 24.8 13.2 23.9V28.3C15.1 29.2 17.2 29.7 19.2 29.7C24 29.7 27.1 27.4 27.1 23.4C27.1 16.9 18.8 18 18.8 15.3Z"+ fill="white"+ />+ </svg>+ );+}diff --git a/packages/ee/src/stripe-connect/hooks.server.ts b/packages/ee/src/stripe-connect/hooks.server.tsnew file mode 100644index 0000000000..1e4cf70038--- /dev/null+++ b/packages/ee/src/stripe-connect/hooks.server.ts@@ -0,0 +1,43 @@+import { getConnectAccountStatus } from "@carbon/stripe/connect.server";++// Only runs once `companyIntegration.active` is already true, which now only+// happens once a real Stripe account exists (see getOrCreateConnectAccount) —+// the "no account at all" case is already "inactive" for free via the+// generic `!integration.active` check upstream in getIntegrationHealth.+//+// Returns true only when the account is fully onboarded (charges + payouts+// both live). Everything else — no account, Stripe API unreachable, real+// requirement errors, or just a normal mid-onboarding account with no+// requirement errors yet — returns false. Mid-onboarding isn't distinguished+// from a real problem here; it reads as unhealthy (red badge) until+// onboarding completes.+export async function stripeConnectHealthcheck(+ companyId: string,+ metadata: Record<string, unknown>+): Promise<boolean> {+ const stripeAccountId = metadata?.stripeAccountId as string | undefined;+ if (!stripeAccountId) {+ return false;+ }++ const status = await getConnectAccountStatus(stripeAccountId);+ if (!status || status.requirementErrors.length) {+ return false;+ }++ if (status.chargesEnabled && status.payoutsEnabled) {+ return true;+ }++ return false;+}++export async function stripeConnectOnInstall(companyId: string): Promise<void> {+ return;+}++export async function stripeConnectOnUninstall(+ companyId: string+): Promise<void> {+ return;+}diff --git a/packages/ee/src/stripe-connect/payment.server.ts b/packages/ee/src/stripe-connect/payment.server.tsnew file mode 100644index 0000000000..e666a8f410--- /dev/null+++ b/packages/ee/src/stripe-connect/payment.server.ts@@ -0,0 +1,682 @@+/**+ * Stripe Connect payment recording — shared between the webhook handler in the+ * ERP app and the pull sweep in the jobs package. Kept in @carbon/ee so both+ * callers can import it without crossing the app→package dependency boundary.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { getCompanyTimeZone } from "@carbon/database";+import type { KyselyDatabase } from "@carbon/database/client";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import { getLogger } from "@carbon/logger";+import type { ConnectInvoice } from "@carbon/stripe/connect.server";+import {+ fromStripeAmount,+ getConnectInvoicePaymentDetails,+ toStripeAmount+} from "@carbon/stripe/connect.server";+import { datetime } from "@carbon/utils";+import { fromAbsolute, toCalendarDate } from "@internationalized/date";+import { PostgresDriver, sql } from "kysely";+import { createMappingService } from "../accounting/index";++const logger = getLogger("ee", "stripe-connect", "payments");++const INTEGRATION = "stripe-connect";+const SYSTEM_USER = "system";++// Module-level Kysely pool — one connection is enough; we only use it for the+// replaceInvoiceSettlements transaction path.+const _pool = getPostgresConnectionPool(1);+const _db = getPostgresClient<KyselyDatabase>(_pool, PostgresDriver);++export type StripeConnectPaymentResult =+ | { status: "recorded"; paymentId: string }+ | { status: "skipped"; reason: string };++export type StripeConnectVoidResult =+ | { status: "voided"; paymentIds: string[] }+ | { status: "skipped"; reason: string };++/**+ * Record a Stripe Connect invoice payment against its originating Carbon sales+ * invoice: create a Receipt payment for the amount collected, settle it+ * against the invoice, and post it. Stripe's processing fee — withheld before+ * the payout ever reaches the bank — rides along in the SAME journal entry+ * `post-payment` builds: the bank line carries the net deposit and a fee+ * expense line makes up the difference, so there is one entry per payment+ * instead of a payment entry plus a follow-up fee entry.+ *+ * Idempotent on the Stripe invoice id, but NOT limited to one payment per+ * invoice: `amount_paid` on a Stripe invoice is cumulative, and Stripe can+ * report it growing across multiple webhook deliveries for the same invoice+ * (installment / partial-payment invoices). Each delivery reconciles against+ * every payment already mapped to this invoice+ * (`externalIntegrationMapping`, `allowDuplicateExternalId: true` for the+ * second and later payments) and:+ * - resumes a stranded `Draft` payment (a prior delivery that inserted the+ * payment + mapping but crashed before settlement/posting completed) at+ * its ALREADY-RECORDED amount, rather than re-deriving anything from+ * Stripe — a resume completes an interrupted write, it is not a new delta;+ * - otherwise records a NEW payment for just the delta between the+ * invoice's current `amount_paid` and what's already been recorded, with+ * the processing fee prorated to that delta's share of the total.+ *+ * Throws on *fixable* configuration problems (missing bank account, missing+ * service-charge account, missing sequence) so the caller returns non-2xx and+ * Stripe retries once the admin has corrected it. Returns `skipped` for+ * anything a retry could never fix, and for "nothing new to record".+ */+export async function recordStripeConnectPayment({+ companyId,+ stripeAccountId,+ integrationMetadata,+ stripeInvoice+}: {+ companyId: string;+ stripeAccountId: string;+ integrationMetadata: Record<string, unknown>;+ stripeInvoice: ConnectInvoice;+}): Promise<StripeConnectPaymentResult> {+ const serviceRole = getCarbonServiceRole();+ const mappingService = createMappingService(_db, companyId);++ const stripeInvoiceId = stripeInvoice.id;+ if (!stripeInvoiceId) {+ return { status: "skipped", reason: "Stripe invoice has no id" };+ }++ // Every payment ever recorded against this Stripe invoice — normally zero+ // (first delivery) or one (fully paid), but installment/partial-payment+ // invoices can have several once a later delivery reports a higher+ // amount_paid than what's already been recorded.+ const existingMappings = await mappingService.getAllByExternalId(+ INTEGRATION,+ stripeInvoiceId,+ "payment"+ );++ // The send path stamps `carbonInvoiceId` on the Stripe invoice; the mapping+ // table is the fallback for invoices sent before that, or if metadata is lost.+ const carbonInvoiceId =+ (stripeInvoice.metadata?.carbonInvoiceId as string | undefined) ??+ (await mappingService.getEntityId(+ INTEGRATION,+ stripeInvoiceId,+ "salesInvoice"+ ));++ if (!carbonInvoiceId) {+ return {+ status: "skipped",+ reason: `No Carbon sales invoice is linked to Stripe invoice ${stripeInvoiceId}`+ };+ }++ const salesInvoice = await serviceRole+ .from("salesInvoices")+ .select("*")+ .eq("id", carbonInvoiceId)+ .single();++ if (salesInvoice.error || !salesInvoice.data) {+ return {+ status: "skipped",+ reason: `Carbon sales invoice ${carbonInvoiceId} could not be loaded`+ };+ }++ // The mapping and the metadata are both company-scoped already, but the+ // invoice is fetched by id alone — re-assert the tenant before writing cash.+ if (salesInvoice.data.companyId !== companyId) {+ throw new Error(+ `Sales invoice ${carbonInvoiceId} belongs to a different company than the Stripe account that reported the payment`+ );+ }++ const currencyCode = (+ salesInvoice.data.currencyCode ??+ stripeInvoice.currency ??+ "USD"+ ).toUpperCase();++ const amountPaid = fromStripeAmount(stripeInvoice.amount_paid, currencyCode);+ if (amountPaid <= 0) {+ return {+ status: "skipped",+ reason: `Stripe invoice ${stripeInvoiceId} reported no amount paid`+ };+ }++ const customerId =+ salesInvoice.data.invoiceCustomerId ?? salesInvoice.data.customerId;+ if (!customerId) {+ return {+ status: "skipped",+ reason: `Sales invoice ${carbonInvoiceId} has no customer to credit`+ };+ }++ // Reconcile this delivery against every payment already recorded for this+ // invoice: resume a stranded Draft, or compute the unrecorded delta.+ type ExistingMapping = (typeof existingMappings)[number];+ let resume: {+ paymentId: string;+ mapping: ExistingMapping;+ totalAmount: number;+ } | null = null;+ let recordedTotal = 0;++ if (existingMappings.length > 0) {+ const paymentIds = existingMappings.map((m) => m.entityId);+ const existingPayments = await serviceRole+ .from("payment")+ .select("id, status, totalAmount")+ .in("id", paymentIds)+ .eq("companyId", companyId);++ if (existingPayments.error) {+ return {+ status: "skipped",+ reason: `Could not verify prior Stripe Connect payments recorded for invoice ${stripeInvoiceId}`+ };+ }++ const paymentById = new Map(+ (existingPayments.data ?? []).map((p) => [p.id, p])+ );++ for (const mapping of existingMappings) {+ const payment = paymentById.get(mapping.entityId);+ if (!payment) continue; // orphaned mapping — ignore, don't block++ if (payment.status === "Draft") {+ // A prior delivery inserted the payment + mapping but crashed before+ // settlement/posting completed. Resume THAT attempt at its own+ // recorded amount — read off the payment row itself (not the mapping+ // metadata's amountRecorded, which didn't exist before this fix and+ // would read as 0 for a Draft stranded prior to it) — rather than+ // treating this as a fresh delta.+ resume = {+ paymentId: mapping.entityId,+ mapping,+ totalAmount: Number(payment.totalAmount ?? 0)+ };+ break;+ }++ if (payment.status !== "Voided") {+ recordedTotal += Number(payment.totalAmount ?? 0);+ }+ }+ }++ const accountDefaults = await serviceRole+ .from("accountDefault")+ .select("bankCashAccount, serviceChargeAccount")+ .eq("companyId", companyId)+ .single();++ const timezone = await getCompanyTimeZone(serviceRole, companyId);+ const paidAt = stripeInvoice.status_transitions?.paid_at;+ const paymentDate = (+ paidAt+ ? toCalendarDate(fromAbsolute(paidAt * 1000, timezone))+ : datetime.today(timezone)+ ).toString();++ let paymentId: string;+ let amountToRecord: number;+ // The realized rate the cash actually moved at, when Stripe converted it —+ // falls back to the invoice's own booked rate below (item 5/FX).+ let realizedExchangeRate: number | null = null;+ let journalFee:+ | { amount: number; accountId: string; description: string }+ | undefined;++ if (resume) {+ // Resume: reuse exactly what the interrupted attempt already captured —+ // do not re-derive anything from Stripe, this completes a write, it does+ // not start a new one.+ paymentId = resume.paymentId;+ amountToRecord = resume.totalAmount;+ const meta = (resume.mapping.metadata ?? {}) as Record<string, unknown>;+ realizedExchangeRate = (meta.exchangeRate as number | null) ?? null;++ const feeAmount = Number(meta.feeAmount ?? 0);+ const feeCurrency = (meta.feeCurrency as string | null) ?? null;+ if (feeAmount > 0 && feeCurrency === currencyCode) {+ const companySettings = await serviceRole+ .from("companySettings")+ .select("accountingEnabled")+ .eq("id", companyId)+ .single();++ if (companySettings.data?.accountingEnabled) {+ const feeAccount =+ (integrationMetadata.paymentFeeAccount as string | undefined) ||+ accountDefaults.data?.serviceChargeAccount;+ if (!feeAccount) {+ throw new Error(+ "No service charge account is configured for Stripe processing fees (set accountDefault.serviceChargeAccount or the integration's paymentFeeAccount)"+ );+ }+ journalFee = {+ amount: feeAmount,+ accountId: feeAccount,+ description: `Stripe processing fee — ${stripeInvoice.number ?? stripeInvoiceId}`+ };+ }+ }+ } else {+ // Round through Stripe's own minor-unit conversion (the same one+ // `amountPaid`/`recordedTotal` already went through) rather than the+ // internal SCALE=5 default — this is a settlement value, and it must+ // land on the currency's own decimal places, not a finer one.+ const delta = fromStripeAmount(+ toStripeAmount(amountPaid - recordedTotal, currencyCode),+ currencyCode+ );+ if (delta <= 0) {+ return {+ status: "skipped",+ reason: `Stripe invoice ${stripeInvoiceId} has no new amount to record (already recorded ${recordedTotal} of ${amountPaid})`+ };+ }+ amountToRecord = delta;+ const isTopUp = recordedTotal > 0;++ const bankAccount =+ (integrationMetadata.paymentBankAccount as string | undefined) ||+ accountDefaults.data?.bankCashAccount;+ if (!bankAccount) {+ throw new Error(+ "No bank account is configured for Stripe Connect receipts (set accountDefault.bankCashAccount or the integration's paymentBankAccount)"+ );+ }++ // Resolved BEFORE the payment is created (like bankAccount above) so a+ // missing service-charge account throws before any row is written — a+ // retry after the admin fixes it starts clean instead of leaving behind an+ // orphaned Draft payment. Gated on accountingEnabled: `post-payment` only+ // ever builds a GL journal (fee included) when accounting is on, so a+ // company that hasn't configured a service-charge account because they+ // don't use Carbon's accounting at all must not have Stripe payments+ // start failing over it.+ const feeDetails = await getConnectInvoicePaymentDetails(+ stripeAccountId,+ stripeInvoiceId+ );+ realizedExchangeRate = feeDetails.exchangeRate;++ // Prorate the fee to this delta's share of the invoice's total collected+ // — feeDetails.feeAmount is the CUMULATIVE fee across every charge behind+ // the invoice, and on a top-up delivery only a slice of it is new.+ const feeAmount = isTopUp+ ? fromStripeAmount(+ toStripeAmount(+ (feeDetails.feeAmount * delta) / amountPaid,+ currencyCode+ ),+ currencyCode+ )+ : feeDetails.feeAmount;++ if (feeAmount > 0) {+ // Fees are assessed in the account's settlement currency, which needn't be+ // the invoice currency. getConnectInvoicePaymentDetails already converts+ // the fee back into the charge's own currency using Stripe's own+ // balance-transaction exchange rate whenever one was available, so+ // feeCurrency matches the invoice currency in the normal case. The only+ // residual mismatch is the rare case where Stripe settled into a+ // different currency with no rate to convert by — that's not a+ // fixable-by-retry problem, so it warns and leaves it to manual+ // reconciliation rather than throwing.+ if (feeDetails.feeCurrency && feeDetails.feeCurrency !== currencyCode) {+ logger.warn(+ "Skipping Stripe fee journal line — no exchange rate was available to convert the fee into the invoice currency",+ {+ companyId,+ stripeInvoiceId,+ feeCurrency: feeDetails.feeCurrency,+ settlementCurrency: feeDetails.settlementCurrency,+ currencyCode+ }+ );+ } else {+ const companySettings = await serviceRole+ .from("companySettings")+ .select("accountingEnabled")+ .eq("id", companyId)+ .single();++ if (companySettings.data?.accountingEnabled) {+ const feeAccount =+ (integrationMetadata.paymentFeeAccount as string | undefined) ||+ accountDefaults.data?.serviceChargeAccount;+ if (!feeAccount) {+ throw new Error(+ "No service charge account is configured for Stripe processing fees (set accountDefault.serviceChargeAccount or the integration's paymentFeeAccount)"+ );+ }+ journalFee = {+ amount: feeAmount,+ accountId: feeAccount,+ description: `Stripe processing fee — ${stripeInvoice.number ?? stripeInvoiceId}`+ };+ }+ }+ }++ const nextSeq = await serviceRole.rpc("get_next_sequence", {+ sequence_name: "payment",+ company_id: companyId+ });+ if (nextSeq.error || !nextSeq.data) {+ throw new Error("Failed to allocate a payment id for the Stripe payment");+ }++ const insert = await serviceRole+ .from("payment")+ .insert([+ {+ paymentId: nextSeq.data,+ paymentType: "Receipt" as const,+ customerId,+ paymentDate,+ currencyCode,+ exchangeRate:+ realizedExchangeRate ??+ (Number(salesInvoice.data.exchangeRate ?? 1) || 1),+ totalAmount: amountToRecord,+ bankAccount,+ reference: stripeInvoice.number ?? stripeInvoiceId,+ memo: `Stripe payment for ${salesInvoice.data.invoiceId ?? carbonInvoiceId}`,+ companyId,+ createdBy: SYSTEM_USER+ }+ ])+ .select("id, paymentId")+ .single();++ if (insert.error || !insert.data) {+ throw new Error(+ `Failed to create the Carbon payment for Stripe invoice ${stripeInvoiceId}`+ );+ }++ paymentId = insert.data.id;+ const mappingMetadata: Record<string, unknown> = {+ stripeInvoiceId,+ stripeAccountId,+ chargeIds: feeDetails.chargeIds,+ feeAmount,+ feeCurrency: feeDetails.feeCurrency,+ settlementCurrency: feeDetails.settlementCurrency,+ exchangeRate: realizedExchangeRate,+ amountRecorded: amountToRecord,+ // The invoice's cumulative amount_paid at the moment THIS row was+ // linked — the running total the next delivery's delta is computed+ // against (recordedTotal above sums payment.totalAmount, which is+ // independent of this and would work alone, but the snapshot makes the+ // reconciliation auditable from the mapping row itself).+ amountPaidAtRecording: amountPaid+ };++ // Claim the Stripe invoice for this payment BEFORE settling or posting.+ // A duplicate delivery racing us fails the unique index here (when this+ // is the first payment for the invoice), while the payment it created is+ // still an unsettled Draft that can be rolled back. Later top-up+ // payments deliberately allow duplicates — that's the whole point.+ try {+ await mappingService.link(+ "payment",+ paymentId,+ INTEGRATION,+ stripeInvoiceId,+ {+ metadata: mappingMetadata,+ createdBy: SYSTEM_USER,+ allowDuplicateExternalId: isTopUp+ }+ );+ } catch (err) {+ await serviceRole.from("payment").delete().eq("id", paymentId);+ if ((err as { code?: string }).code === "23505") {+ return {+ status: "skipped",+ reason: `Stripe invoice ${stripeInvoiceId} was recorded concurrently by another delivery`+ };+ }+ throw err;+ }+ }++ // Settle against the invoice's open balance. Cash beyond it stays unapplied+ // and becomes on-account credit — `post-payment` already handles that.+ const openBalance = Number(salesInvoice.data.balance ?? 0);+ const appliedAmount = Math.min(amountToRecord, openBalance);+ const targetExchangeRate = Number(salesInvoice.data.exchangeRate ?? 1) || 1;+ // The rate the cash actually moved at — falls back to the invoice's own+ // booked rate when Stripe didn't need to convert (same-currency+ // settlement), which keeps totalFxImpact correctly at 0 in that case.+ const sourceExchangeRate = realizedExchangeRate ?? targetExchangeRate;++ if (appliedAmount > 0) {+ try {+ await _db.transaction().execute(async (trx) => {+ const payment = await trx+ .selectFrom("payment")+ .select(["id", "status", "paymentType", "customerId", "supplierId"])+ .where("id", "=", paymentId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ if (!payment) throw new Error("Payment not found");+ if (payment.status !== "Draft") {+ throw new Error(+ "Applications can only be edited while the payment is Draft"+ );+ }++ await trx+ .deleteFrom("invoiceSettlement")+ .where("paymentId", "=", paymentId)+ .execute();++ // Verify the invoice belongs to the same customer as the payment —+ // Kysely bypasses RLS so this is the only enforcement boundary.+ const invoice = await trx+ .selectFrom("salesInvoice")+ .select(["id", "customerId"])+ .where("id", "=", carbonInvoiceId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();++ if (!invoice) throw new Error("Sales invoice not found for settlement");+ if (invoice.customerId !== payment.customerId) {+ throw new Error(+ "Settlement target customer does not match payment customer"+ );+ }++ await trx+ .insertInto("invoiceSettlement")+ .values({+ paymentId,+ targetSalesInvoiceId: carbonInvoiceId,+ targetPurchaseInvoiceId: null,+ appliedAmount,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate,+ sourceExchangeRate,+ appliedDate: paymentDate,+ companyId,+ createdBy: SYSTEM_USER+ })+ .execute();+ });+ } catch (err) {+ // The payment (and, for a fresh record, its mapping) already exist —+ // only the settlement failed. Leave the Draft in place: it's resumable+ // by the next delivery (webhook retry, or the pull sweep) via the+ // `resume` path above, instead of being stranded forever behind the+ // "already recorded" mapping check.+ logger.error("Failed to settle the Stripe Connect payment", {+ error: err,+ companyId,+ paymentId,+ stripeInvoiceId+ });+ return { status: "recorded", paymentId };+ }+ } else {+ logger.warn(+ "Stripe payment has no open invoice balance to settle; recording it as on-account credit",+ { companyId, carbonInvoiceId, paymentId }+ );+ }++ const posted = await serviceRole.functions.invoke("post-payment", {+ body: {+ type: "post",+ paymentId,+ userId: SYSTEM_USER,+ companyId,+ fee: journalFee+ }+ });++ if (posted.error) {+ // The payment and its settlement are correct — only the posting failed, so+ // leave the Draft in place for a human (or the next delivery's resume+ // path) to post rather than losing the record.+ logger.error("Failed to post the Stripe Connect payment", {+ error: posted.error,+ companyId,+ paymentId,+ stripeInvoiceId+ });+ return { status: "recorded", paymentId };+ }++ return { status: "recorded", paymentId };+}++/**+ * Resolve the Stripe invoice id behind a charge, from Carbon's OWN recorded+ * data — used to trace a `charge.dispute.*` / `charge.refunded` event (which+ * only carries a charge id) back to the invoice a payment was recorded+ * against. Stripe's pinned API version (`2025-06-30.basil`) removed the+ * `invoice` back-reference from `Charge` itself, so this can't be resolved+ * via a Stripe API call — `recordStripeConnectPayment` already stores every+ * charge id behind a payment in its mapping's `metadata.chargeIds`, which is+ * a reverse index of exactly this. Never throws; returns `null` when no+ * mapping references the charge (e.g. a charge on an invoice Carbon never+ * recorded), so the caller can log and skip.+ */+export async function getStripeInvoiceIdForCharge(+ companyId: string,+ chargeId: string+): Promise<string | null> {+ const row = await _db+ .selectFrom("externalIntegrationMapping")+ .select(["externalId"])+ .where("integration", "=", INTEGRATION)+ .where("entityType", "=", "payment")+ .where("companyId", "=", companyId)+ .where(sql<boolean>`"metadata"->'chargeIds' ? ${chargeId}`)+ .executeTakeFirst();++ return row?.externalId ?? null;+}++/**+ * Reverse a Stripe Connect payment via `post-payment`'s existing `void` op —+ * a FULL reversal that mirrors every journal line (including the fee line)+ * with a negated amount. Called for a full refund, a lost dispute, or an+ * invoice being voided on Stripe's side. Voids every non-Voided payment+ * mapped to the invoice (installment/partial-payment invoices can have more+ * than one — see `recordStripeConnectPayment`).+ *+ * There is no partial-reversal capability — a partial refund has no safe+ * automated GL treatment here and must be handled manually; callers should+ * not invoke this for one.+ */+export async function voidStripeConnectPayment({+ companyId,+ stripeInvoiceId+}: {+ companyId: string;+ stripeInvoiceId: string;+}): Promise<StripeConnectVoidResult> {+ const serviceRole = getCarbonServiceRole();+ const mappingService = createMappingService(_db, companyId);++ const mappings = await mappingService.getAllByExternalId(+ INTEGRATION,+ stripeInvoiceId,+ "payment"+ );+ if (mappings.length === 0) {+ return {+ status: "skipped",+ reason: `No Stripe Connect payment is recorded for Stripe invoice ${stripeInvoiceId}`+ };+ }++ const paymentIds = mappings.map((m) => m.entityId);+ const existingPayments = await serviceRole+ .from("payment")+ .select("id, status")+ .in("id", paymentIds)+ .eq("companyId", companyId);++ if (existingPayments.error) {+ throw new Error(+ `Failed to load Stripe Connect payments recorded for invoice ${stripeInvoiceId}`+ );+ }++ const voidable = (existingPayments.data ?? []).filter(+ (p) => p.status === "Posted"+ );+ if (voidable.length === 0) {+ return {+ status: "skipped",+ reason: `No Posted Stripe Connect payment to void for invoice ${stripeInvoiceId}`+ };+ }++ const voidedIds: string[] = [];+ for (const payment of voidable) {+ const voided = await serviceRole.functions.invoke("post-payment", {+ body: {+ type: "void",+ paymentId: payment.id,+ userId: SYSTEM_USER,+ companyId+ }+ });++ if (voided.error) {+ logger.error("Failed to void a Stripe Connect payment", {+ error: voided.error,+ companyId,+ paymentId: payment.id,+ stripeInvoiceId+ });+ throw new Error(+ `Failed to void payment ${payment.id} for Stripe invoice ${stripeInvoiceId}: ${voided.error.message}`+ );+ }++ voidedIds.push(payment.id);+ }++ return { status: "voided", paymentIds: voidedIds };+}diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 07a9c9c7a9..74478797fb 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -8,6 +8,7 @@ declare global {CARBON_EDITION: string;CARBON_API_URL: string;CARBON_SLACK_ENABLED: string;+ STRIPE_CONNECT_ENABLED: string;CLOUDFLARE_TURNSTILE_SITE_KEY: string;CONTROLLED_ENVIRONMENT: string;ERP_URL: string;@@ -64,6 +65,7 @@ declare global {SLACK_STATE_SECRET: string;STRIPE_SECRET_KEY: string;STRIPE_WEBHOOK_SECRET: string;+ STRIPE_CONNECT_WEBHOOK_SECRET: string;STRIPE_BYPASS_COMPANY_IDS: string;STRIPE_BYPASS_USER_IDS: string;GTM_URL: string;@@ -348,9 +350,26 @@ export const SESSION_ERROR_KEY = "error";export const STRIPE_SECRET_KEY = getEnv("STRIPE_SECRET_KEY", {isRequired: false});+// Browser-safe boolean signal for whether Stripe (and therefore the Stripe+// Connect integration) is configured. STRIPE_SECRET_KEY is a secret, so it is+// `""` in the browser — the integration's `active` gate must read this derived+// flag instead, which crosses to the client via getBrowserEnv() the same way+// CARBON_SLACK_ENABLED does. Only the boolean is exposed, never the key.+export const STRIPE_CONNECT_ENABLED = isBrowser+ ? window.env?.STRIPE_CONNECT_ENABLED === "true"+ : Boolean(STRIPE_SECRET_KEY);export const STRIPE_WEBHOOK_SECRET = getEnv("STRIPE_WEBHOOK_SECRET", {isRequired: false});+// Connect webhook endpoints (`connect: true`) are signed with their OWN secret,+// distinct from the platform-account endpoint above — a Connect event verified+// against STRIPE_WEBHOOK_SECRET fails signature validation.+export const STRIPE_CONNECT_WEBHOOK_SECRET = getEnv(+ "STRIPE_CONNECT_WEBHOOK_SECRET",+ {+ isRequired: false+ }+);export const STRIPE_BYPASS_COMPANY_IDS = getEnv("STRIPE_BYPASS_COMPANY_IDS", {isRequired: false});@@ -506,6 +525,7 @@ export function getBrowserEnv() {CARBON_API_URL,CARBON_EDITION,CARBON_SLACK_ENABLED: CARBON_SLACK_ENABLED ? "true" : "",+ STRIPE_CONNECT_ENABLED: STRIPE_CONNECT_ENABLED ? "true" : "",CLOUDFLARE_TURNSTILE_SITE_KEY,CONTROLLED_ENVIRONMENT,DEFAULT_LANGUAGE,diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.tsindex 0725465cb2..f08e3ac5f1 100644--- a/packages/jobs/src/inngest/functions/integrations/index.ts+++ b/packages/jobs/src/inngest/functions/integrations/index.ts@@ -14,5 +14,6 @@ export {slackDocumentStatusUpdateFunction,slackDocumentTaskUpdateFunction} from "./slack-document-sync";+export { stripeConnectPullSweepFunction } from "./stripe-connect-pull-sweep";export { syncExternalAccountingFunction } from "./sync-external-accounting";export { timeCardAutoCloseFunction } from "./timecard-auto-close";diff --git a/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep-cursor.ts b/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep-cursor.tsnew file mode 100644index 0000000000..024fca31c1--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep-cursor.ts@@ -0,0 +1,38 @@+/**+ * Pure cursor arithmetic for the Stripe Connect pull sweep, split out of+ * `stripe-connect-pull-sweep.ts` so it stays import-light (no `@carbon/auth`,+ * no Stripe client, no Inngest) and directly unit-testable — same pattern as+ * `accounting-sync-operations.ts` for the accounting sweeps.+ */++// How far behind the stored cursor each sweep re-scans. An invoice created+// before the cursor but paid after it would otherwise never be listed again,+// since the query filters on `created`, not `paid_at`. 30 days comfortably+// covers realistic invoice payment terms; the re-scan is free because+// `recordStripeConnectPayment` is idempotent on the Stripe invoice id.+export const CURSOR_LOOKBACK_SECONDS = 60 * 60 * 24 * 30;++/**+ * The Stripe `created` timestamp to query from for a given stored cursor —+ * `since - CURSOR_LOOKBACK_SECONDS`, floored at 0.+ */+export function pullWindowStart(since: number): number {+ return Math.max(0, since - CURSOR_LOOKBACK_SECONDS);+}++/**+ * The next cursor value given the latest `created` timestamp seen this run,+ * the current cursor, and whether any invoice in the batch errored. Returns+ * `null` when the cursor should not advance (nothing newer seen, or a+ * partial failure held it back for retry).+ */+export function nextPullCursor(+ latestCreated: number | null,+ since: number,+ anyError: boolean+): number | null {+ if (anyError || latestCreated === null || latestCreated <= since) {+ return null;+ }+ return latestCreated + 1;+}diff --git a/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.test.ts b/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.test.tsnew file mode 100644index 0000000000..b0bb0ebdc5--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.test.ts@@ -0,0 +1,72 @@+// Unit tests for the pull sweep's cursor arithmetic. These two functions are+// pure and import-light on purpose so the regression this plan fixes — the+// cursor advancing on `paid_at` while the Stripe query filters on `created` —+// is directly testable without booting Inngest, Stripe, or a database.+import { describe, expect, it } from "vitest";+import {+ nextPullCursor,+ pullWindowStart+} from "./stripe-connect-pull-sweep-cursor";++const DAY = 60 * 60 * 24;+const LOOKBACK = 30 * DAY;++describe("pullWindowStart", () => {+ it("subtracts the lookback window from the stored cursor", () => {+ // A realistic Unix-seconds cursor, well past the 30-day lookback, so the+ // floor-at-0 case (tested separately below) doesn't mask the arithmetic.+ const since = 1_700_000_000;+ expect(pullWindowStart(since)).toBe(since - LOOKBACK);+ });++ it("floors at 0 instead of going negative for an early cursor", () => {+ expect(pullWindowStart(100)).toBe(0);+ });+});++describe("nextPullCursor", () => {+ it("advances to the latest created timestamp + 1 seen this run", () => {+ const since = 1_000_000;+ const latestCreated = since + 5 * DAY;+ expect(nextPullCursor(latestCreated, since, false)).toBe(latestCreated + 1);+ });++ it(+ "picks up an invoice created BEFORE the cursor but paid AFTER it — " ++ "the regression this plan fixes. The list query re-scans from " ++ "pullWindowStart(since), so an invoice with created < since can still " ++ "appear in this run's batch and drive the next cursor forward",+ () => {+ const since = 1_000_000;+ // An invoice created 10 days before the cursor, paid after it, shows+ // up in this run because the query window looks back 30 days.+ const createdBeforeCursor = since - 10 * DAY;+ expect(pullWindowStart(since)).toBeLessThanOrEqual(createdBeforeCursor);++ // Advancing on `created` (not `paid_at`) means this invoice's OWN+ // `created` timestamp does not push the cursor forward past invoices+ // created after it but not yet paid — it only advances as far as the+ // latest `created` actually seen and successfully processed.+ const latestCreatedThisRun = since + 2 * DAY;+ expect(nextPullCursor(latestCreatedThisRun, since, false)).toBe(+ latestCreatedThisRun + 1+ );+ }+ );++ it("does not advance when nothing newer than the cursor was seen", () => {+ const since = 1_000_000;+ expect(nextPullCursor(since, since, false)).toBeNull();+ expect(nextPullCursor(since - 1, since, false)).toBeNull();+ });++ it("does not advance when no invoices were found at all", () => {+ expect(nextPullCursor(null, 1_000_000, false)).toBeNull();+ });++ it("holds the cursor when any invoice in the batch errored, even if others succeeded", () => {+ const since = 1_000_000;+ const latestCreated = since + 5 * DAY;+ expect(nextPullCursor(latestCreated, since, true)).toBeNull();+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts b/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.tsnew file mode 100644index 0000000000..80e96bffa7--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/stripe-connect-pull-sweep.ts@@ -0,0 +1,307 @@+/**+ * Stripe Connect payment pull sweep — the correctness guarantee behind the+ * webhook handler. Webhooks are a latency optimization; deliveries can be+ * missed, disabled after repeated failures, or unreachable for firewalled+ * self-hosted instances. This cron runs every 30 minutes and catches anything+ * the webhook missed.+ *+ * Per active Stripe Connect company:+ * 1. Read the sweep cursor from `metadata.settings.pullCursor`; default = the+ * integration row's `updatedAt` (ensures we don't pull pre-install history).+ * 2. List paid invoices from Stripe `created` at or after+ * `cursor - CURSOR_LOOKBACK_SECONDS`. The lookback re-scans a trailing+ * window on every run so an invoice CREATED before the cursor but PAID+ * after it is not permanently missed — `recordStripeConnectPayment` is+ * idempotent on the Stripe invoice id, so re-scanning is a no-op for+ * invoices already recorded.+ * 3. For each, call `recordStripeConnectPayment` — idempotent on the Stripe+ * invoice id via the `externalIntegrationMapping` unique index.+ * 4. Advance the cursor to the latest `invoice.created` seen — the SAME field+ * the list query filters on — only when all processing succeeded (Celigo+ * cursor rule). Advancing on `status_transitions.paid_at` instead (a+ * different field than the query filter) is what caused the original miss.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { recordStripeConnectPayment } from "@carbon/ee/stripe-connect.server";+import type { ConnectInvoice } from "@carbon/stripe/connect.server";+import { stripe } from "@carbon/stripe/stripe.server";+import { datetime } from "@carbon/utils";+import { parseAbsolute } from "@internationalized/date";+import { inngest } from "../../client";+import {+ nextPullCursor,+ pullWindowStart+} from "./stripe-connect-pull-sweep-cursor";++const INTEGRATION_ID = "stripe-connect";++export const stripeConnectPullSweepFunction = inngest.createFunction(+ { id: "stripe-connect-pull-sweep", retries: 2 },+ { cron: "15,45 * * * *" }, // offset from the accounting pull sweep (*/30)+ async ({ step, logger }) => {+ const client = getCarbonServiceRole();++ const targets = await step.run("find-stripe-connect-targets", async () => {+ const integrations = await client+ .from("companyIntegration")+ .select("id, companyId, metadata, updatedAt")+ .eq("id", INTEGRATION_ID)+ .eq("active", true);++ if (integrations.error) {+ throw new Error(+ `Failed to list Stripe Connect integrations: ${integrations.error.message}`+ );+ }++ return (integrations.data ?? []).map((row) => ({+ companyId: row.companyId,+ metadata: (row.metadata ?? {}) as Record<string, unknown>,+ updatedAt: row.updatedAt+ }));+ });++ if (targets.length === 0) {+ return { targets: 0, results: [] };+ }++ const results: Array<{+ companyId: string;+ invoicesFound: number;+ recorded: number;+ skipped: number;+ errors: number;+ cursorAdvancedTo: number | null;+ skippedReason?: string;+ }> = [];++ for (const target of targets) {+ let result: (typeof results)[number];+ try {+ result = await step.run(+ `stripe-connect-sweep-${target.companyId}`,+ async () => {+ const { companyId, metadata } = target;++ // stripeAccountId is written top-level on companyIntegration.metadata+ // by getOrCreateConnectAccount/callback.ts — NOT nested under+ // `settings`. Reading it nested here silently short-circuited every+ // company forever; keep this read in sync with those writers.+ const stripeAccountId = metadata.stripeAccountId as+ | string+ | undefined;++ if (!stripeAccountId) {+ return {+ companyId,+ invoicesFound: 0,+ recorded: 0,+ skipped: 0,+ errors: 0,+ cursorAdvancedTo: null,+ skippedReason: "no stripeAccountId in metadata"+ };+ }++ // Cursor is a Unix timestamp (seconds). Default = integration+ // updatedAt so we don't reach back before install.+ const settings = (metadata.settings ?? {}) as Record<+ string,+ unknown+ >;+ const storedCursor = settings.pullCursor as number | undefined;+ const fallbackCursor = target.updatedAt+ ? Math.trunc(+ parseAbsolute(target.updatedAt, "UTC").toDate().getTime() /+ 1000+ )+ : Math.trunc(datetime.now("UTC").toDate().getTime() / 1000) -+ 60 * 60 * 24 * 7; // 7 days max++ const since = storedCursor ?? fallbackCursor;++ if (!stripe) {+ return {+ companyId,+ invoicesFound: 0,+ recorded: 0,+ skipped: 0,+ errors: 0,+ cursorAdvancedTo: null,+ skippedReason:+ "Stripe client not initialized (STRIPE_SECRET_KEY not set)"+ };+ }++ // Page through all paid invoices created since the lookback window,+ // not just since the raw cursor — see CURSOR_LOOKBACK_SECONDS above.+ const queryFrom = pullWindowStart(since);++ type StripeInvoice = Awaited<+ ReturnType<typeof stripe.invoices.list>+ >["data"][number];+ const invoices: StripeInvoice[] = [];+ let hasMore = true;+ let startingAfter: string | undefined;++ while (hasMore) {+ const page = await stripe.invoices.list(+ {+ status: "paid",+ created: { gte: queryFrom },+ limit: 100,+ ...(startingAfter ? { starting_after: startingAfter } : {})+ },+ { stripeAccount: stripeAccountId }+ );++ invoices.push(...page.data);+ hasMore = page.has_more;+ const last = page.data.at(-1);+ if (last) {+ startingAfter = last.id;+ } else {+ hasMore = false;+ }+ }++ const summary = {+ companyId,+ invoicesFound: invoices.length,+ recorded: 0,+ skipped: 0,+ errors: 0,+ cursorAdvancedTo: null as number | null+ };++ if (invoices.length === 0) {+ return summary;+ }++ let latestCreated: number | null = null;+ let anyError = false;++ for (const invoice of invoices) {+ try {+ const result = await recordStripeConnectPayment({+ companyId,+ stripeAccountId,+ integrationMetadata: metadata,+ stripeInvoice: invoice as ConnectInvoice+ });++ if (result.status === "recorded") {+ summary.recorded++;+ } else {+ if (+ result.reason.includes("could not be loaded") ||+ result.reason.includes("Could not verify prior") ||+ result.reason.includes("concurrently")+ ) {+ throw new Error(`Retryable skip: ${result.reason}`);+ }++ summary.skipped++;+ logger.info(+ `[stripe-connect-pull-sweep] ${companyId}: skipped ${invoice.id}: ${result.reason}`+ );+ }++ // Advance on `created`, the same field the list query filters+ // on — not `paid_at`, which is what let invoices slip through.+ if (latestCreated === null || invoice.created > latestCreated) {+ latestCreated = invoice.created;+ }+ } catch (err) {+ summary.errors++;+ anyError = true;+ logger.error(+ `[stripe-connect-pull-sweep] ${companyId}: error processing ${invoice.id}`,+ { error: err }+ );+ }+ }++ // Celigo cursor rule: only advance when all processing succeeded.+ // A partial error holds the cursor so the next run re-fetches the+ // same window, naturally retrying any failed invoice.+ const newCursor = nextPullCursor(latestCreated, since, anyError);+ if (newCursor !== null) {+ await storePullCursor(client, companyId, newCursor);+ summary.cursorAdvancedTo = newCursor;+ } else if (anyError) {+ logger.warn(+ `[stripe-connect-pull-sweep] ${companyId}: ${summary.errors} error(s); holding cursor at ${since} for retry`+ );+ }++ return summary;+ }+ );+ } catch (err) {+ logger.error(+ `[stripe-connect-pull-sweep] ${target.companyId}: sweep failed`,+ { error: err }+ );+ result = {+ companyId: target.companyId,+ invoicesFound: 0,+ recorded: 0,+ skipped: 0,+ errors: 1,+ cursorAdvancedTo: null,+ skippedReason: err instanceof Error ? err.message : String(err)+ };+ }++ results.push(result);+ }++ return { targets: targets.length, results };+ }+);++/**+ * Read-modify-write on the raw metadata so no sibling key is clobbered —+ * same contract as `storePullCursor` in accounting-pull-sweep.ts.+ */+async function storePullCursor(+ client: ReturnType<typeof getCarbonServiceRole>,+ companyId: string,+ cursor: number+): Promise<void> {+ const current = await client+ .from("companyIntegration")+ .select("metadata")+ .eq("id", INTEGRATION_ID)+ .eq("companyId", companyId)+ .single();++ if (current.error) {+ throw new Error(+ `Failed to read integration metadata for cursor store: ${current.error.message}`+ );+ }++ const existing = (current.data?.metadata ?? {}) as Record<string, unknown>;+ const settings = (existing.settings ?? {}) as Record<string, unknown>;+ const merged = {+ ...existing,+ settings: {+ ...settings,+ pullCursor: cursor+ }+ };++ const updated = await client+ .from("companyIntegration")+ .update({ metadata: merged as any })+ .eq("id", INTEGRATION_ID)+ .eq("companyId", companyId);++ if (updated.error) {+ throw new Error(+ `Failed to store Stripe Connect pull cursor: ${updated.error.message}`+ );+ }+}diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex a645a713bd..e39842b5d3 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -43,6 +43,7 @@ import {slackDocumentCreatedFunction,slackDocumentStatusUpdateFunction,slackDocumentTaskUpdateFunction,+ stripeConnectPullSweepFunction,syncExternalAccountingFunction,timeCardAutoCloseFunction} from "./functions/integrations";@@ -162,6 +163,7 @@ export const functions = [slackDocumentStatusUpdateFunction,slackDocumentTaskUpdateFunction,slackDocumentAssignmentUpdateFunction,+ stripeConnectPullSweepFunction,timeCardAutoCloseFunction,// Document extractionextractDocumentFunctiondiff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex ab9a0e7c0e..e7a9a42e41 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -487,6 +487,9 @@ msgstr "Eine neue Revision wird erstellt, indem eine Kopie der aktuellen Revisiomsgid "A new size will be created using a copy of the current size"msgstr "Eine neue Größe wird erstellt, indem eine Kopie der aktuellen Größe verwendet wird"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Ein nicht-liquiditätswirksames Dokument, das eine Rechnung gegen ein Begründungskonto abrechnet: eine Gutschrift reduziert die Schuld, eine Belastung erhöht sie."@@ -2793,6 +2796,9 @@ msgstr "Kann nicht gebucht werden – Sendung enthält abgelaufene nachverfölgtmsgid "Cannot send RFQ"msgstr "RFQ kann nicht gesendet werden"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Hochladen nicht möglich — Lieferanteninteraktion noch nicht erstellt"@@ -2998,6 +3004,9 @@ msgstr "Überprüfen Sie das Artikelhauptbuch auf Artikel mit negativem Bestandmsgid "Check your email"msgstr "Überprüfen Sie Ihre E-Mail"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Checkpoint ·"@@ -3896,6 +3905,9 @@ msgstr "Erstellen Sie eine neue Wartungsmitteilung, um Gerätereparaturen und Wamsgid "Create a new production job to fulfill the sales order"msgstr "Erstellen Sie einen neuen Produktionsauftrag, um die Bestellung zu erfüllen"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Neue Version erstellen"@@ -6210,6 +6222,9 @@ msgstr "Existierende Zuordnungen. Wählen Sie ein anderes Provider-Konto zum Neumsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Vorhandene Zuordnungen. Wählen Sie eine andere Provider-Option zum Neu-Zuordnen."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Erweitern"@@ -8521,6 +8536,9 @@ msgstr "Jira-Problem verknüpfen"msgid "Link Linear Issue"msgstr "Linear-Problem verknüpfen"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Mit Verkaufsauftragszeile verknüpfen"@@ -12591,6 +12609,9 @@ msgstr "Alle Journal- und Kostenkontoeinträge rückgängig machen"msgid "Reverse any item ledger entries from this invoice"msgstr "Alle Artikelledgereinträge aus dieser Rechnung stornieren"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Umkehrbuchung Umsatzsteuer"@@ -14238,6 +14259,21 @@ msgstr "Speichern Sie eine feste Anzahl von Tagen für diesen Artikel. Das Ablaumsgid "Straight line"msgstr "Linear"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Stil der Kanban-Ausgabe, die in der Kanban-Tabelle angezeigt werden soll"@@ -14650,6 +14686,9 @@ msgstr "Steuerabschreibung"msgid "Tax Depreciation Method"msgstr "Steuerabschreibungsmethode"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Steuerbefreit"@@ -15507,6 +15546,9 @@ msgstr "Diese Änderungsmitteilung ist geschlossen, daher sind ihre Änderungenmsgid "This completes the Discovery step."msgstr "Dies schließt den Discovery-Schritt ab."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Dieser Geschäftspartner hat keine ausstehenden Forderungen — die Zahlung wird auf Kontokorrent verbucht."@@ -15532,6 +15574,12 @@ msgstr "dieser Inspektionsplan"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "Diese Einladung zum Beitritt zu {0} ist abgelaufen. Sie können eine neue Einladung anfordern, die an Ihre E-Mail gesendet wird."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "Dies ist eine kontrollierte Umgebung, daher ist eine Authentifizierungs-App erforderlich."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 8cd9df088a..2d72c6cc5f 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -487,6 +487,9 @@ msgstr "A new revision will be created using a copy of the current revision"msgid "A new size will be created using a copy of the current size"msgstr "A new size will be created using a copy of the current size"+msgid "A new Stripe customer will be created"+msgstr "A new Stripe customer will be created"+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."@@ -2793,6 +2796,9 @@ msgstr "Cannot post — shipment contains expired tracked entities."msgid "Cannot send RFQ"msgstr "Cannot send RFQ"+msgid "Cannot send through Stripe"+msgstr "Cannot send through Stripe"+msgid "Cannot upload — supplier interaction not yet created"msgstr "Cannot upload — supplier interaction not yet created"@@ -2998,6 +3004,9 @@ msgstr "Check the item ledger for any items with a negative on-hand quantity asmsgid "Check your email"msgstr "Check your email"+msgid "Checking Stripe for this customer…"+msgstr "Checking Stripe for this customer…"+msgid "Checkpoint ·"msgstr "Checkpoint ·"@@ -3896,6 +3905,9 @@ msgstr "Create a new maintenance dispatch to track equipment repairs and maintenmsgid "Create a new production job to fulfill the sales order"msgstr "Create a new production job to fulfill the sales order"+msgid "Create a new Stripe customer instead"+msgstr "Create a new Stripe customer instead"+msgid "Create a new version"msgstr "Create a new version"@@ -6210,6 +6222,9 @@ msgstr "Existing mappings. Pick a different provider account to re-map."msgid "Existing mappings. Pick a different provider option to re-map."msgstr "Existing mappings. Pick a different provider option to re-map."+msgid "Existing Stripe customer"+msgstr "Existing Stripe customer"+msgid "Expand"msgstr "Expand"@@ -8521,6 +8536,9 @@ msgstr "Link Jira Issue"msgid "Link Linear Issue"msgstr "Link Linear Issue"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgid "Link to sales order line"msgstr "Link to sales order line"@@ -12591,6 +12609,9 @@ msgstr "Reverse all journal and cost ledger entries"msgid "Reverse any item ledger entries from this invoice"msgstr "Reverse any item ledger entries from this invoice"+msgid "Reverse charge"+msgstr "Reverse charge"+msgid "Reverse Charge Sales Tax"msgstr "Reverse Charge Sales Tax"@@ -14238,6 +14259,21 @@ msgstr "Store a fixed number of days on this item. Expiry start date is set on emsgid "Straight line"msgstr "Straight line"+msgid "Stripe"+msgstr "Stripe"++msgid "Stripe already has a customer with this email"+msgstr "Stripe already has a customer with this email"++msgid "Stripe Due Date"+msgstr "Stripe Due Date"++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgid "Style of kanban output to show in the Kanban table"msgstr "Style of kanban output to show in the Kanban table"@@ -14650,6 +14686,9 @@ msgstr "Tax Depreciation"msgid "Tax Depreciation Method"msgstr "Tax Depreciation Method"+msgid "Tax exempt"+msgstr "Tax exempt"+msgid "Tax Exempt"msgstr "Tax Exempt"@@ -15507,6 +15546,9 @@ msgstr "This change notice is closed, so its changes are read-only."msgid "This completes the Discovery step."msgstr "This completes the Discovery step."+msgid "This contact has no email address"+msgstr "This contact has no email address"+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "This counterparty has nothing outstanding — the payment will be recorded on-account."@@ -15532,6 +15574,12 @@ msgstr "this inspection plan"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "This invitation to join {0} has expired. You can request a new invite to be sent to your email."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr "This invoice has no usable due date — choose one for Stripe."++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgid "This is a controlled environment, so an authenticator app is required."msgstr "This is a controlled environment, so an authenticator app is required."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 42be392137..e3c688b466 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -487,6 +487,9 @@ msgstr "Se creará una nueva revisión utilizando una copia de la revisión actumsgid "A new size will be created using a copy of the current size"msgstr "Se creará un nuevo tamaño utilizando una copia del tamaño actual"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Un documento sin efectivo que liquida una factura contra una cuenta de razón: un crédito reduce lo adeudado, un débito lo aumenta."@@ -2793,6 +2796,9 @@ msgstr "No se puede publicar — el envío contiene entidades rastreadas vencidamsgid "Cannot send RFQ"msgstr "No se puede enviar RFQ"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "No se puede cargar — la interacción con el proveedor aún no se ha creado"@@ -2998,6 +3004,9 @@ msgstr "Revise el libro mayor de artículos para buscar artículos con cantidadmsgid "Check your email"msgstr "Revisa tu correo electrónico"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Punto de control ·"@@ -3896,6 +3905,9 @@ msgstr "Crear un nuevo despacho de mantenimiento para rastrear reparaciones de emsgid "Create a new production job to fulfill the sales order"msgstr "Crear un nuevo trabajo de producción para cumplir con el pedido de venta"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Crear una nueva versión"@@ -6210,6 +6222,9 @@ msgstr "Asignaciones existentes. Selecciona una cuenta de proveedor diferente pamsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Mapeos existentes. Elige una opción de proveedor diferente para remapear."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Expandir"@@ -8521,6 +8536,9 @@ msgstr "Vincular problema de Jira"msgid "Link Linear Issue"msgstr "Vincular problema de Linear"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Vincular a una línea de orden de venta"@@ -12591,6 +12609,9 @@ msgstr "Revertir todos los asientos del diario y del libro mayor de costos"msgid "Reverse any item ledger entries from this invoice"msgstr "Revertir cualquier entrada del libro mayor de artículos de esta factura"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Impuesto a las ventas de cargo inverso"@@ -14238,6 +14259,21 @@ msgstr "Almacena un número fijo de días en este artículo. La fecha de iniciomsgid "Straight line"msgstr "Línea recta"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Estilo de salida de kanban para mostrar en la tabla Kanban"@@ -14650,6 +14686,9 @@ msgstr "Depreciación Fiscal"msgid "Tax Depreciation Method"msgstr "Método de Depreciación Fiscal"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Exento de Impuestos"@@ -15507,6 +15546,9 @@ msgstr "Esta notificación de cambio está cerrada, por lo que sus cambios son dmsgid "This completes the Discovery step."msgstr "Esto completa el paso de Descubrimiento."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Este tercero no tiene nada pendiente — el pago se registrará en cuenta."@@ -15532,6 +15574,12 @@ msgstr "este plan de inspección"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "Esta invitación para unirse a {0} ha expirado. Puedes solicitar que se envíe una nueva invitación a tu correo electrónico."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "Este es un entorno controlado, por lo que se requiere una aplicación autenticadora."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 61f19c20dd..3327c543c7 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -487,6 +487,9 @@ msgstr "Une nouvelle révision sera créée en utilisant une copie de la révisimsgid "A new size will be created using a copy of the current size"msgstr "Une nouvelle taille sera créée en utilisant une copie de la taille actuelle"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Un document sans trésorerie qui règle une facture sur un compte de raison : un crédit réduit ce qui est dû, un débit l'augmente."@@ -2793,6 +2796,9 @@ msgstr "Impossible de publier — l'expédition contient des entités suivies exmsgid "Cannot send RFQ"msgstr "Impossible d'envoyer la demande de devis"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Impossible de télécharger — l'interaction fournisseur n'a pas encore été créée"@@ -2998,6 +3004,9 @@ msgstr "Vérifiez le registre des articles pour tous les articles ayant une quanmsgid "Check your email"msgstr "Vérifiez votre email"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Point de contrôle ·"@@ -3896,6 +3905,9 @@ msgstr "Créer une nouvelle demande de maintenance pour suivre les réparationsmsgid "Create a new production job to fulfill the sales order"msgstr "Créer une nouvelle tâche de production pour honorer la commande client"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Créer une nouvelle version"@@ -6210,6 +6222,9 @@ msgstr "Mappages existants. Choisissez un compte fournisseur différent pour remmsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Mappages existants. Choisissez une option de fournisseur différente pour remapper."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Développer"@@ -8521,6 +8536,9 @@ msgstr "Lier un problème Jira"msgid "Link Linear Issue"msgstr "Lier un problème Linear"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Lier à la ligne de commande client"@@ -12591,6 +12609,9 @@ msgstr "Inverser tous les écritures de journal et de grand livre des coûts"msgid "Reverse any item ledger entries from this invoice"msgstr "Inverser les écritures de registre d'articles de cette facture"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Taxe de vente d'autoliquidation"@@ -14238,6 +14259,21 @@ msgstr "Stockez un nombre fixe de jours sur cet article. La date de début d'expmsgid "Straight line"msgstr "Linéaire"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Style de sortie kanban à afficher dans le tableau Kanban"@@ -14650,6 +14686,9 @@ msgstr "Dépréciation Fiscale"msgid "Tax Depreciation Method"msgstr "Méthode de Dépréciation Fiscale"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Exonéré de Taxe"@@ -15507,6 +15546,9 @@ msgstr "Cette notice de modification est fermée, donc ses modifications sont enmsgid "This completes the Discovery step."msgstr "Cela complète l'étape de découverte."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Ce tiers n'a rien en suspens — le paiement sera enregistré en compte courant."@@ -15532,6 +15574,12 @@ msgstr "ce plan d'inspection"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "Cette invitation pour rejoindre {0} a expiré. Vous pouvez demander une nouvelle invitation à envoyer à votre e-mail."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "C'est un environnement contrôlé, donc une application d'authentification est requise."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex d89cb7fab9..46ee8c79fa 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -487,6 +487,9 @@ msgstr "एक नया संशोधन वर्तमान संशोmsgid "A new size will be created using a copy of the current size"msgstr "एक नया आकार वर्तमान आकार की प्रतिलिपि का उपयोग करके बनाया जाएगा"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "एक गैर-नकद दस्तावेज जो एक कारण खाते के विरुद्ध एक चालान को निपटाता है: एक क्रेडिट बकाया राशि को कम करता है, एक डेबिट इसे बढ़ाता है।"@@ -2793,6 +2796,9 @@ msgstr "पोस्ट नहीं कर सकते — शिपमेंmsgid "Cannot send RFQ"msgstr "RFQ नहीं भेज सकते"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "अपलोड नहीं कर सकते — आपूर्तिकर्ता इंटरैक्शन अभी तक बनाया नहीं गया"@@ -2998,6 +3004,9 @@ msgstr "अवधि के अंत तक नकारात्मक मौmsgid "Check your email"msgstr "अपना ईमेल जांचें"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "चेकपॉइंट ·"@@ -3896,6 +3905,9 @@ msgstr "उपकरण मरम्मत और रखरखाव गतिmsgid "Create a new production job to fulfill the sales order"msgstr "बिक्रय आदेश को पूरा करने के लिए एक नई उत्पादन नौकरी बनाएं"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "एक नया संस्करण बनाएं"@@ -6210,6 +6222,9 @@ msgstr "मौजूदा मानचित्रण। पुनः मानmsgid "Existing mappings. Pick a different provider option to re-map."msgstr "मौजूदा मैपिंग। पुनः-मैप करने के लिए एक अलग प्रदाता विकल्प चुनें।"+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "विस्तार करें"@@ -8521,6 +8536,9 @@ msgstr "Jira समस्या को लिंक करें"msgid "Link Linear Issue"msgstr "Linear समस्या को लिंक करें"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "बिक्रय आदेश पंक्ति से लिंक करें"@@ -12591,6 +12609,9 @@ msgstr "सभी जर्नल और लागत लेजर प्रवmsgid "Reverse any item ledger entries from this invoice"msgstr "इस चालान से किसी भी आइटम लेजर प्रविष्टियों को उलट दें"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "रिवर्स चार्ज बिक्रय कर"@@ -14238,6 +14259,21 @@ msgstr "इस आइटम पर दिनों की एक निश्चmsgid "Straight line"msgstr "सीधी रेखा"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Kanban तालिका में दिखाने के लिए kanban आउटपुट की शैली"@@ -14650,6 +14686,9 @@ msgstr "कर मूल्यह्रास"msgid "Tax Depreciation Method"msgstr "कर मूल्यह्रास पद्धति"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "कर छूट"@@ -15507,6 +15546,9 @@ msgstr "यह परिवर्तन सूचना बंद है, इसmsgid "This completes the Discovery step."msgstr "यह Discovery चरण को पूरा करता है।"+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "यह प्रतिपक्ष के पास कुछ भी बकाया नहीं है — भुगतान खाते पर दर्ज किया जाएगा।"@@ -15532,6 +15574,12 @@ msgstr "इस निरीक्षण योजना"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "यह आमंत्रण {0} में शामिल होने के लिए समाप्त हो गया है। आप अपने ईमेल पर भेजने के लिए नया आमंत्रण का अनुरोध कर सकते हैं।"+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "यह एक नियंत्रित वातावरण है, इसलिए एक प्रमाणकर्ता ऐप की आवश्यकता है।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex b928bebdc9..a7c1d07751 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -487,6 +487,9 @@ msgstr "Una nuova revisione verrà creata utilizzando una copia della revisionemsgid "A new size will be created using a copy of the current size"msgstr "Una nuova dimensione verrà creata utilizzando una copia della dimensione attuale"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Un documento non in contanti che regola una fattura rispetto a un conto motivo: un credito abbassa ciò che è dovuto, un debito lo aumenta."@@ -2793,6 +2796,9 @@ msgstr "Impossibile registrare — la spedizione contiene entità tracciate scadmsgid "Cannot send RFQ"msgstr "Impossibile inviare RFQ"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Impossibile caricare — interazione fornitore non ancora creata"@@ -2998,6 +3004,9 @@ msgstr "Controlla il registro degli articoli per eventuali articoli con una quanmsgid "Check your email"msgstr "Controlla la tua email"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Checkpoint ·"@@ -3896,6 +3905,9 @@ msgstr "Crea un nuovo ordine di manutenzione per tracciare le riparazioni dellemsgid "Create a new production job to fulfill the sales order"msgstr "Crea un nuovo ordine di produzione per evadere l'ordine di vendita"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Crea una nuova versione"@@ -6210,6 +6222,9 @@ msgstr "Mappature esistenti. Seleziona un conto provider diverso per rimappare."msgid "Existing mappings. Pick a different provider option to re-map."msgstr "Mapping esistenti. Scegli un'opzione provider diversa per rimappare."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Espandi"@@ -8521,6 +8536,9 @@ msgstr "Collega Problema Jira"msgid "Link Linear Issue"msgstr "Collega problema Linear"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Collega alla riga dell'ordine di vendita"@@ -12591,6 +12609,9 @@ msgstr "Storna tutti i movimenti di giornale e di contabilità analitica"msgid "Reverse any item ledger entries from this invoice"msgstr "Storna qualsiasi voce di ledger articoli da questa fattura"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Imposta di vendita con inversione contabile"@@ -14238,6 +14259,21 @@ msgstr "Memorizza un numero fisso di giorni su questo articolo. La data di inizimsgid "Straight line"msgstr "Lineare"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Stile dell'output kanban da mostrare nella tabella Kanban"@@ -14650,6 +14686,9 @@ msgstr "Ammortamento Fiscale"msgid "Tax Depreciation Method"msgstr "Metodo di Ammortamento Fiscale"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Esente da Imposte"@@ -15507,6 +15546,9 @@ msgstr "Questo avviso di modifica è chiuso, quindi le sue modifiche sono di solmsgid "This completes the Discovery step."msgstr "Questo completa il passaggio Discovery."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Questa controparte non ha nulla in sospeso — il pagamento verrà registrato come credito in conto."@@ -15532,6 +15574,12 @@ msgstr "questo piano di ispezione"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "Questo invito per unirti a {0} è scaduto. Puoi richiedere un nuovo invito da inviare alla tua email."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "Questo è un ambiente controllato, quindi è necessaria un'app autenticatore."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex d461b5d2db..11905bbcfb 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -487,6 +487,9 @@ msgstr "現在のリビジョンのコピーを使用して、新しいリビジmsgid "A new size will be created using a copy of the current size"msgstr "新しいサイズが現在のサイズのコピーを使用して作成されます"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "請求書を理由勘定に対して決済する非現金ドキュメント。クレジットは債務額を低下させ、デビットは債務額を増加させます。"@@ -2793,6 +2796,9 @@ msgstr "投稿できません — 出荷に期限切れの追跡対象エンテmsgid "Cannot send RFQ"msgstr "RFQを送信できません"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "アップロードできません — サプライヤーインタラクションがまだ作成されていません"@@ -2998,6 +3004,9 @@ msgstr "期末時点で保有数量がマイナスの品目がないか品目台msgid "Check your email"msgstr "メールを確認してください"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "チェックポイント ·"@@ -3896,6 +3905,9 @@ msgstr "新しい保守ディスパッチを作成して、機器の修理と保msgid "Create a new production job to fulfill the sales order"msgstr "販売注文を履行するための新しい生産ジョブを作成します"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "新しいバージョンを作成"@@ -6210,6 +6222,9 @@ msgstr "既存のマッピング。再マップするには別のプロバイダmsgid "Existing mappings. Pick a different provider option to re-map."msgstr "既存のマッピング。異なるプロバイダーオプションを選択して再マップしてください。"+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "展開"@@ -8521,6 +8536,9 @@ msgstr "Jira イシューをリンク"msgid "Link Linear Issue"msgstr "Linear イシューをリンク"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "販売注文行へのリンク"@@ -12591,6 +12609,9 @@ msgstr "すべての仕訳帳とコスト台帳エントリを取り消す"msgid "Reverse any item ledger entries from this invoice"msgstr "このインボイスからのアイテム台帳エントリをすべて取り消す"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "逆請求売上税"@@ -14238,6 +14259,21 @@ msgstr "このアイテムの固定日数を保存します。有効期限の開msgid "Straight line"msgstr "定額法"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Kanbanテーブルに表示するカンバン出力のスタイル"@@ -14650,6 +14686,9 @@ msgstr "税務償却"msgid "Tax Depreciation Method"msgstr "税務償却方法"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "税務上免除"@@ -15507,6 +15546,9 @@ msgstr "この変更通知は閉じられているため、変更は読み取りmsgid "This completes the Discovery step."msgstr "これはDiscoveryステップを完了します。"+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "この取引先には未払い金がありません。支払いは掛け金として記録されます。"@@ -15532,6 +15574,12 @@ msgstr "この検査計画"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "この{0}への参加への招待は期限切れです。新しい招待をメールで送信されるようにリクエストできます。"+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "これは管理環境のため、認証アプリが必須です。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex bb8a06121b..c36e5a11d3 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -487,6 +487,9 @@ msgstr "현재 리비전을 복사하여 새 리비전이 생성됩니다"msgid "A new size will be created using a copy of the current size"msgstr "현재 사이즈를 복사하여 새 사이즈가 생성됩니다"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "인보이스를 이유 계정에 대해 정산하는 비현금 문서로서, 신용은 지불액을 낮추고 차변은 올립니다."@@ -2793,6 +2796,9 @@ msgstr "전기할 수 없습니다 — 출하에 유효기한이 만료된 추msgid "Cannot send RFQ"msgstr "RFQ를 보낼 수 없습니다"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "업로드할 수 없습니다 — 공급업체 상호작용이 아직 생성되지 않았습니다"@@ -2998,6 +3004,9 @@ msgstr "기간 종료 시점의 음수 수량 보유 항목에 대해 항목 원msgid "Check your email"msgstr "이메일을 확인하세요"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "체크포인트 ·"@@ -3896,6 +3905,9 @@ msgstr "장비 수리 및 유지보수 활동을 추적할 새 유지보수 작msgid "Create a new production job to fulfill the sales order"msgstr "판매주문을 이행할 새 생산 작업을 생성합니다"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "새 버전 만들기"@@ -6210,6 +6222,9 @@ msgstr "기존 매핑입니다. 다시 매핑하려면 다른 공급자 계정msgid "Existing mappings. Pick a different provider option to re-map."msgstr "기존 매핑입니다. 다시 매핑하려면 다른 제공자 옵션을 선택하세요."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "펼치기"@@ -8521,6 +8536,9 @@ msgstr "Jira 이슈 연결"msgid "Link Linear Issue"msgstr "Linear 이슈 연결"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "판매주문 라인에 연결"@@ -12591,6 +12609,9 @@ msgstr "모든 분개 및 원가 원장 항목 취소"msgid "Reverse any item ledger entries from this invoice"msgstr "이 인보이스의 모든 품목 원장 항목 취소"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "매입자 납부 판매세(Reverse Charge)"@@ -14238,6 +14259,21 @@ msgstr "이 품목에 고정된 일수를 저장합니다. 유효기한 시작msgid "Straight line"msgstr "정액법"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "칸반 테이블에 표시할 칸반 출력 스타일"@@ -14650,6 +14686,9 @@ msgstr "세무 감가상각"msgid "Tax Depreciation Method"msgstr "세무 감가상각 방법"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "세금 면제"@@ -15507,6 +15546,9 @@ msgstr "이 변경 사항은 닫혀 있으므로 변경 사항이 읽기 전용msgid "This completes the Discovery step."msgstr "이것으로 발견(Discovery) 단계가 완료됩니다."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "이 거래처에는 미결제 항목이 없습니다 — 결제는 선수금으로 기록됩니다."@@ -15532,6 +15574,12 @@ msgstr "이 검사 계획"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "{0}에 참여하기 위한 이 초대권은 만료되었습니다. 이메일로 새 초대권을 보내달라고 요청할 수 있습니다."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "이것은 제어되는 환경이므로 인증자 앱이 필수입니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 0337ad4e0d..ca327b8f8e 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -487,6 +487,9 @@ msgstr "Nowa wersja zostanie utworzona przy użyciu kopii bieżącej wersji"msgid "A new size will be created using a copy of the current size"msgstr "Nowy rozmiar zostanie utworzony przy użyciu kopii bieżącego rozmiaru"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Dokument bezgotówkowy, który rozlicza fakturę względem konta przyczyny: kredyt obniża to, co się należy, debet to podwyższa."@@ -2793,6 +2796,9 @@ msgstr "Nie można wysłać — przesyłka zawiera wygasłe jednostki śledzeniamsgid "Cannot send RFQ"msgstr "Nie można wysłać ZZO"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Nie można przesłać — interakcja z dostawcą nie została jeszcze utworzona"@@ -2998,6 +3004,9 @@ msgstr "Sprawdź księgę pozycji w poszukiwaniu pozycji z ujemną ilością dosmsgid "Check your email"msgstr "Sprawdź swoją pocztę"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Punkt kontrolny ·"@@ -3896,6 +3905,9 @@ msgstr "Utwórz nową dyspozycję konserwacji, aby śledzić naprawy sprzętu imsgid "Create a new production job to fulfill the sales order"msgstr "Utwórz nowe zadanie produkcyjne, aby zrealizować zamówienie sprzedaży"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Utwórz nową wersję"@@ -6210,6 +6222,9 @@ msgstr "Istniejące mapowania. Wybierz inne konto dostawcy, aby ponownie zmapowamsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Istniejące mapowania. Wybierz inną opcję dostawcy, aby przezmapować."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Rozwiń"@@ -8521,6 +8536,9 @@ msgstr "Połącz problem Jiry"msgid "Link Linear Issue"msgstr "Połącz problem Linear"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Połącz z linią zamówienia sprzedaży"@@ -12591,6 +12609,9 @@ msgstr "Odwróć wszystkie wpisy dziennika i księgi kosztów"msgid "Reverse any item ledger entries from this invoice"msgstr "Odwróć wszystkie wpisy rejestru pozycji z tej faktury"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Odwrotne obciążenie podatkiem od sprzedaży"@@ -14238,6 +14259,21 @@ msgstr "Przechowuj stałą liczbę dni dla tego artykułu. Data rozpoczęcia wygmsgid "Straight line"msgstr "Liniowa"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Styl wyjścia kanban do wyświetlenia w tabeli Kanban"@@ -14650,6 +14686,9 @@ msgstr "Amortyzacja Podatkowa"msgid "Tax Depreciation Method"msgstr "Metoda Amortyzacji Podatkowej"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Zwolniony z Podatku"@@ -15507,6 +15546,9 @@ msgstr "Ta notacja zmiany jest zamknięta, więc jej zmiany są tylko do odczytumsgid "This completes the Discovery step."msgstr "To uzupełnia krok Discovery."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Ta strona nie ma żadnych zaległości — płatność zostanie zarejestrowana na koncie."@@ -15532,6 +15574,12 @@ msgstr "ten plan inspekcji"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "To zaproszenie do dołączenia do {0} wygasło. Możesz poprosić o wysłanie nowego zaproszenia na Twoją wiadomość e-mail."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "To jest kontrolowane środowisko, dlatego wymagana jest aplikacja authenticator."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 10385459c2..0103031be3 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -487,6 +487,9 @@ msgstr "Uma nova revisão será criada usando uma cópia da revisão atual"msgid "A new size will be created using a copy of the current size"msgstr "Um novo tamanho será criado usando uma cópia do tamanho atual"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Um documento sem dinheiro que liquida uma fatura em relação a uma conta de motivo: um crédito reduz o que é devido, um débito aumenta."@@ -2793,6 +2796,9 @@ msgstr "Não é possível postar — o envio contém entidades rastreadas expiramsgid "Cannot send RFQ"msgstr "Não é possível enviar RFQ"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Não é possível fazer upload — interação com fornecedor ainda não foi criada"@@ -2998,6 +3004,9 @@ msgstr "Verifique o razão de itens para qualquer item com quantidade em mão nemsgid "Check your email"msgstr "Verifique seu email"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Checkpoint ·"@@ -3896,6 +3905,9 @@ msgstr "Crie uma nova ordem de manutenção para rastrear reparos de equipamentomsgid "Create a new production job to fulfill the sales order"msgstr "Criar um novo trabalho de produção para atender ao pedido de venda"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Criar uma nova versão"@@ -6210,6 +6222,9 @@ msgstr "Mapeamentos existentes. Escolha uma conta de provedor diferente para remmsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Mapeamentos existentes. Escolha uma opção de provedor diferente para remapear."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Expandir"@@ -8521,6 +8536,9 @@ msgstr "Vincular Problema do Jira"msgid "Link Linear Issue"msgstr "Vincular Problema Linear"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Vincular à linha do pedido de venda"@@ -12591,6 +12609,9 @@ msgstr "Reverter todos os lançamentos de diário e razão de custos"msgid "Reverse any item ledger entries from this invoice"msgstr "Reverter quaisquer entradas do razão de itens desta fatura"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Imposto de vendas de cobrança reversa"@@ -14238,6 +14259,21 @@ msgstr "Armazene um número fixo de dias neste item. A data de início da validamsgid "Straight line"msgstr "Linear"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Estilo de saída do kanban para mostrar na tabela Kanban"@@ -14650,6 +14686,9 @@ msgstr "Depreciação Fiscal"msgid "Tax Depreciation Method"msgstr "Método de Depreciação Fiscal"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Isento de Impostos"@@ -15507,6 +15546,9 @@ msgstr "Este aviso de mudança está fechado, portanto suas alterações são somsgid "This completes the Discovery step."msgstr "Isto completa a etapa de Descoberta."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Este terceiro não tem nada pendente — o pagamento será registrado em conta."@@ -15532,6 +15574,12 @@ msgstr "este plano de inspeção"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "Este convite para ingressar em {0} expirou. Você pode solicitar um novo convite a ser enviado para seu e-mail."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "Este é um ambiente controlado, portanto um aplicativo autenticador é obrigatório."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 50f52ad7cd..99ff2152fc 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -487,6 +487,9 @@ msgstr "Новая редакция будет создана с использmsgid "A new size will be created using a copy of the current size"msgstr "Новый размер будет создан с использованием копии текущего размера"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Неденежный документ, погашающий счёт-фактуру по счёту причин: кредит уменьшает сумму задолженности, дебет её увеличивает."@@ -2793,6 +2796,9 @@ msgstr "Невозможно отправить — отправка содерmsgid "Cannot send RFQ"msgstr "Невозможно отправить РФП"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Невозможно загрузить — взаимодействие с поставщиком еще не создано"@@ -2998,6 +3004,9 @@ msgstr "Проверьте реестр товаров на наличие тоmsgid "Check your email"msgstr "Проверьте вашу почту"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Контрольная точка ·"@@ -3896,6 +3905,9 @@ msgstr "Создайте новую заявку на техническое оmsgid "Create a new production job to fulfill the sales order"msgstr "Создайте новое производственное задание для выполнения заказа"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Создать новую версию"@@ -6210,6 +6222,9 @@ msgstr "Существующие сопоставления. Выберите дmsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Существующие отображения. Выберите другой вариант провайдера для переотображения."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Развернуть"@@ -8521,6 +8536,9 @@ msgstr "Связать проблему Jira"msgid "Link Linear Issue"msgstr "Связать проблему Linear"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Связать со строкой заказа на продажу"@@ -12591,6 +12609,9 @@ msgstr "Обратить все записи журнала и реестра зmsgid "Reverse any item ledger entries from this invoice"msgstr "Отменить все записи реестра товаров из этого счета"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Налог на продажи с обратным взиманием"@@ -14238,6 +14259,21 @@ msgstr "Сохраняйте фиксированное количество дmsgid "Straight line"msgstr "Линейный"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Стиль вывода канбана для отображения в таблице Канбана"@@ -14650,6 +14686,9 @@ msgstr "Налоговая амортизация"msgid "Tax Depreciation Method"msgstr "Метод налоговой амортизации"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Налоговое освобождение"@@ -15507,6 +15546,9 @@ msgstr "Это уведомление об изменении закрыто, пmsgid "This completes the Discovery step."msgstr "Это завершает этап Discovery."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Эта контрагент не имеет задолженности — платеж будет записан на счет."@@ -15532,6 +15574,12 @@ msgstr "этот план проверки"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "Это приглашение присоединиться к {0} истекло. Вы можете запросить новое приглашение, которое будет отправлено на вашу электронную почту."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "Это контролируемая среда, поэтому требуется приложение аутентификации."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 8e9e45c575..0c428d89c1 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -487,6 +487,9 @@ msgstr "Yeni bir revizyon, mevcut revizyonun bir kopyası kullanılarak oluşturmsgid "A new size will be created using a copy of the current size"msgstr "Yeni bir boyut, mevcut boyutun bir kopyası kullanılarak oluşturulacaktır"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "Bir faturayı bir sebep hesabına karşı ödeyen nakitsiz bir belge: alacak, borçlu olunan tutarı azaltır, borç artırır."@@ -2793,6 +2796,9 @@ msgstr "Gönderilemiyor — gönderi süresi dolmuş takip edilen varlıklar içmsgid "Cannot send RFQ"msgstr "RFQ gönderilemiyor"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "Yüklenemiyor — tedarikçi etkileşimi henüz oluşturulmadı"@@ -2998,6 +3004,9 @@ msgstr "Dönem sonunda negatif el altında miktarı olan herhangi bir madde içimsgid "Check your email"msgstr "E-postanızı kontrol edin"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "Kontrol Noktası ·"@@ -3896,6 +3905,9 @@ msgstr "Ekipman onarımlarını ve bakım faaliyetlerini izlemek için yeni birmsgid "Create a new production job to fulfill the sales order"msgstr "Satış siparişini yerine getirmek için yeni bir üretim işi oluşturun"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "Yeni bir sürüm oluşturun"@@ -6210,6 +6222,9 @@ msgstr "Mevcut haritalamalar. Yeniden haritalamak için farklı bir sağlayıcımsgid "Existing mappings. Pick a different provider option to re-map."msgstr "Mevcut eşlemeler. Yeniden eşlemek için farklı bir sağlayıcı seçeneği seçin."+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "Genişlet"@@ -8521,6 +8536,9 @@ msgstr "Jira Sorununu Bağla"msgid "Link Linear Issue"msgstr "Linear sorununu bağla"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "Satış siparişi satırına bağla"@@ -12591,6 +12609,9 @@ msgstr "Tüm günlük ve mali defter kayıtlarını tersine çevirir"msgid "Reverse any item ledger entries from this invoice"msgstr "Bu faturadaki herhangi bir kalem defteri girişini tersine çevirir"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "Ters yükleme satış vergisi"@@ -14238,6 +14259,21 @@ msgstr "Bu öğeye sabit sayıda gün saklayın. Son kullanma tarihi, her partimsgid "Straight line"msgstr "Doğrusal"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "Kanban tablosunda gösterilecek kanban çıktısı stili"@@ -14650,6 +14686,9 @@ msgstr "Vergi Amortisman"msgid "Tax Depreciation Method"msgstr "Vergi Amortisman Yöntemi"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "Vergi Muaf"@@ -15507,6 +15546,9 @@ msgstr "Bu değişiklik bildirimi kapalı olduğundan, değişiklikleri salt okumsgid "This completes the Discovery step."msgstr "Bu, Keşif adımını tamamlar."+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "Bu muhasebe ortağının ödenmemiş bir borcu yok — ödeme hesap üzerinde kaydedilecektir."@@ -15532,6 +15574,12 @@ msgstr "bu muayene planı"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "{0} kuruluşuna katılmak için gönderilen bu davet süresi dolmuştur. E-postanıza yeni bir davet gönderilmesini isteyebilirsiniz."+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "Bu kontrollü bir ortamdır, bu nedenle doğrulayıcı uygulaması gereklidir."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 15bae7d360..9ec300d667 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -487,6 +487,9 @@ msgstr "将使用当前版本的副本创建新版本"msgid "A new size will be created using a copy of the current size"msgstr "将使用当前尺寸的副本创建新尺寸"+msgid "A new Stripe customer will be created"+msgstr ""+msgid "A non-cash document that settles an invoice against a reason account: a credit lowers what's owed, a debit raises it."msgstr "一份非现金单据,根据原因账户结算发票:贷方降低应付金额,借方提高它。"@@ -2793,6 +2796,9 @@ msgstr "无法发布 — 货运单包含已过期的追踪实体。"msgid "Cannot send RFQ"msgstr "无法发送询价单"+msgid "Cannot send through Stripe"+msgstr ""+msgid "Cannot upload — supplier interaction not yet created"msgstr "无法上传 — 供应商互动尚未创建"@@ -2998,6 +3004,9 @@ msgstr "检查物料分类账中期末库存数量为负的任何物料——通msgid "Check your email"msgstr "检查您的电子邮件"+msgid "Checking Stripe for this customer…"+msgstr ""+msgid "Checkpoint ·"msgstr "检查点 ·"@@ -3896,6 +3905,9 @@ msgstr "创建新的维护派工单以跟踪设备维修和维护活动"msgid "Create a new production job to fulfill the sales order"msgstr "创建新的生产工作以完成销售订单"+msgid "Create a new Stripe customer instead"+msgstr ""+msgid "Create a new version"msgstr "创建新版本"@@ -6210,6 +6222,9 @@ msgstr "现有映射。选择不同的提供商账户以重新映射。"msgid "Existing mappings. Pick a different provider option to re-map."msgstr "现有映射。选择不同的提供商选项以重新映射。"+msgid "Existing Stripe customer"+msgstr ""+msgid "Expand"msgstr "展开"@@ -8521,6 +8536,9 @@ msgstr "关联 Jira 问题"msgid "Link Linear Issue"msgstr "关联 Linear 问题"+msgid "Link this Carbon customer to one of them, or create a separate Stripe customer."+msgstr ""+msgid "Link to sales order line"msgstr "关联销售订单行"@@ -12591,6 +12609,9 @@ msgstr "反转所有日记账和成本分类账条目"msgid "Reverse any item ledger entries from this invoice"msgstr "反转此发票中的任何项目分类账条目"+msgid "Reverse charge"+msgstr ""+msgid "Reverse Charge Sales Tax"msgstr "反向收费销售税"@@ -14238,6 +14259,21 @@ msgstr "在此项目上存储固定天数。每个批次或序列号在收到时msgid "Straight line"msgstr "直线法"+msgid "Stripe"+msgstr ""++msgid "Stripe already has a customer with this email"+msgstr ""++msgid "Stripe Due Date"+msgstr ""++msgid "Stripe emails the invoice to the customer, so an address is required. This will also be saved to the contact in Carbon."+msgstr ""++msgid "Stripe has no customer for this Carbon customer yet. Posting will create one on your connected account."+msgstr ""+msgid "Style of kanban output to show in the Kanban table"msgstr "看板输出在看板表中显示的样式"@@ -14650,6 +14686,9 @@ msgstr "税务折旧"msgid "Tax Depreciation Method"msgstr "税务折旧方法"+msgid "Tax exempt"+msgstr ""+msgid "Tax Exempt"msgstr "免税"@@ -15507,6 +15546,9 @@ msgstr "此变更通知已关闭,因此其更改为只读。"msgid "This completes the Discovery step."msgstr "这完成了发现步骤。"+msgid "This contact has no email address"+msgstr ""+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."msgstr "该交易对手没有未结余额——该付款将记录为应收账款。"@@ -15532,6 +15574,12 @@ msgstr "这个检验计划"msgid "This invitation to join {0} has expired. You can request a new invite to be sent to your email."msgstr "加入 {0} 的邀请已过期。您可以请求将新邀请发送到您的电子邮件。"+msgid "This invoice has no usable due date — choose one for Stripe."+msgstr ""++msgid "This invoice will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."+msgstr ""+msgid "This is a controlled environment, so an authenticator app is required."msgstr "这是受控环境,因此需要身份验证器应用。"diff --git a/packages/stripe/AGENTS.md b/packages/stripe/AGENTS.mdindex 34747e22ce..cbe382cc09 100644--- a/packages/stripe/AGENTS.md+++ b/packages/stripe/AGENTS.md@@ -30,15 +30,58 @@ pnpm --filter @carbon/stripe dev:stripe # local Stripe listener (dev)## Key Patterns-- **Single export**: `@carbon/stripe/stripe.server` — all functions server-only+- **Exports**: `@carbon/stripe/stripe.server` (platform billing),+ `@carbon/stripe/connect.server` (Connect accounts, invoicing, Connect webhooks),+ `@carbon/stripe/connect.constants` — all server-only- **Redis cache**: subscription state cached by customer ID; `companyPlan` is the durable mirror- **GTM forwarding**: `gtm-events.server.ts` forwards invoice events to Google Tag Manager- **User-based pricing**: `updateSubscriptionQuantityForCompany()` syncs active user count (excludes `@carbon.ms`)-- **Stripe API version**: `2025-06-30.basil`+- **Stripe API version**: `2025-06-30.basil` on the shared v1 `stripe` client+ (`2026-07-29.dahlia` on the v2 `stripeConnect` client used for account management).+ On basil, `invoice.charge` / `invoice.payment_intent` no longer exist — payments+ hang off `invoice.payments` (see `getConnectInvoicePaymentDetails`)+- **Two webhook endpoints, two secrets**: the platform endpoint+ (`/api/webhook/stripe`, `STRIPE_WEBHOOK_SECRET`, verified inside+ `processStripeEvent`) and the Connect endpoint (`/api/webhook/stripe-connect`,+ `STRIPE_CONNECT_WEBHOOK_SECRET`, verified by `constructConnectWebhookEvent`).+ Connected-account events carry `event.account`; verifying one against the wrong+ secret always fails+- **Money conversion**: `toStripeAmount` / `fromStripeAmount` handle zero- and+ three-decimal currencies — never hand-roll `* 100`. Per-unit prices go through+ the SDK's branded `Stripe.Decimal` (`unit_amount_decimal` / `quantity_decimal`+ are `Decimal`, not `string`), never a rounded minor-unit integer+- **Sales invoice → Stripe invoice**: `createAndSendConnectInvoice` mirrors the+ `salesInvoices` view's arithmetic, which is the only definition of what a+ Carbon invoice is worth. One Carbon line becomes up to four Stripe items+ (`unitPrice × quantity`, `addOnCost`, `shippingCost` — all taxable — plus an+ untaxed `nonTaxableAddOnCost`), and `salesInvoiceShipment.shippingCost` is a+ fifth, untaxed, invoice-level item. `setupPrice` is in neither the view's+ subtotal nor its tax base, so it is **not billed**. `salesInvoiceLine.taxPercent`+ is a FRACTION in [0,1] (a column CHECK) and must be ×100 for Stripe's+ `percentage`; rates are looked-up-or-created per connected account by+ `resolveConnectTaxRateId`. Before finalizing, the draft's Stripe-computed+ total is reconciled against `expectedConnectInvoiceTotal` and the draft is+ deleted rather than sent on a mismatch beyond per-item rounding+- **Connect customers**: `upsertConnectCustomer` (create/update),+ `retrieveConnectCustomer` (null on missing OR `deleted`, so a stale mapping+ degrades instead of throwing), `findConnectCustomersByEmail` (`customers.list`,+ NOT `customers.search` — search lags indexing and would duplicate a+ just-created customer; `limit: 2` so callers can detect ambiguity). Every call+ passes `{ stripeAccount }`; a platform-scoped call lands on the wrong account.+ `invoice_prefix` and `tax_id_data` are create-only (`tax_id_data` is absent+ from `CustomerUpdateParams` entirely — changing tax ids means+ `createTaxId`/`deleteTaxId`). `ConnectCustomerInput.taxExempt` is already in+ Stripe's vocabulary (`none`/`exempt`/`reverse`); interpreting Carbon's+ `customerTax` pair is the ERP's job, in+ `apps/erp/app/modules/invoicing/stripe-customer.mapper.ts`## Cross-References- `.claude/rules/billing-system.md` — full billing architecture- `packages/ee/src/plan.ts` + `plan.server.ts` — feature/plan gating (`FEATURE_PLANS`)-- `apps/erp/app/routes/api+/webhook.stripe.ts` — webhook route+- `apps/erp/app/routes/api+/webhook.stripe.ts` — platform webhook route+- `apps/erp/app/routes/api+/webhook.stripe-connect.ts` — Connect webhook route+- `packages/ee/src/stripe-connect/payment.server.ts` (exported as+ `@carbon/ee/stripe-connect.server`) — `recordStripeConnectPayment`, the+ Connect payment → Carbon `payment` recorder- `packages/database/supabase/migrations/*billing*.sql` — schemadiff --git a/packages/stripe/package.json b/packages/stripe/package.jsonindex e4b277c4ca..7f2708a581 100644--- a/packages/stripe/package.json+++ b/packages/stripe/package.json@@ -9,7 +9,7 @@"@carbon/logger": "workspace:*","@carbon/utils": "workspace:*","@supabase/supabase-js": "catalog:",- "stripe": "18.5.0"+ "stripe": "22.4.0"},"type": "module","devDependencies": {@@ -24,7 +24,9 @@"zod": "catalog:"},"exports": {- "./stripe.server": "./src/stripe.server.ts"+ "./stripe.server": "./src/stripe.server.ts",+ "./connect.server": "./src/connect.server.ts",+ "./connect.constants": "./src/connect.constants.ts"},"private": true,"scripts": {diff --git a/packages/stripe/src/connect.constants.ts b/packages/stripe/src/connect.constants.tsnew file mode 100644index 0000000000..f1d71b40d0--- /dev/null+++ b/packages/stripe/src/connect.constants.ts@@ -0,0 +1,9 @@+export const STRIPE_CONNECT_ACCOUNT_CONFIG = {+ dashboard: "express",+ entityType: "company",+ capabilities: { ach_debit_payments: true, card_payments: true },+ responsibilities: {+ feesCollector: "application_express",+ lossesCollector: "application"+ }+} as const;diff --git a/packages/stripe/src/connect.server.ts b/packages/stripe/src/connect.server.tsnew file mode 100644index 0000000000..775f6d722e--- /dev/null+++ b/packages/stripe/src/connect.server.ts@@ -0,0 +1,1104 @@+import type { Database } from "@carbon/database";+import { STRIPE_CONNECT_WEBHOOK_SECRET, STRIPE_SECRET_KEY } from "@carbon/env";+import { getLogger } from "@carbon/logger";+import type { SupabaseClient } from "@supabase/supabase-js";+import { Stripe } from "stripe";+import { STRIPE_CONNECT_ACCOUNT_CONFIG } from "./connect.constants";+import { stripe } from "./stripe.server";++const log = getLogger("stripe-connect");++const stripeConnect = STRIPE_SECRET_KEY+ ? new Stripe(STRIPE_SECRET_KEY, {+ apiVersion: "2026-07-29.dahlia",+ typescript: true+ })+ : null;++function deriveConnectAccountMetadata(account: Stripe.V2.Core.Account) {+ const capabilities = account.configuration?.merchant?.capabilities;+ const entries = account.requirements?.entries ?? [];+ const requirementErrors = [+ ...new Set(+ entries+ .flatMap((entry) => entry.errors ?? [])+ .map((requirementError) => requirementError.description)+ )+ ];++ return {+ chargesEnabled: capabilities?.card_payments?.status === "active",+ payoutsEnabled: capabilities?.stripe_balance?.payouts?.status === "active",+ detailsSubmitted: !entries.length,+ requirementErrors+ };+}++/**+ * Whether an error means a previously-created Connect account is no longer+ * usable from the platform's side (disconnected or deleted directly in+ * Stripe), as opposed to a transient failure (network, rate limit, outage).+ *+ * `resource_missing`/403/404 cover the account being gone outright. But an+ * Express account the merchant disconnected via their Stripe dashboard keeps+ * answering a bare `retrieve` — the "does not have access to account …+ * (Application access may have been revoked)" error only surfaces on calls+ * that need the deeper platform grant Stripe just pulled (an `include`d+ * retrieve, `accountLinks.create`, …). Stripe doesn't give that case a+ * distinct `code`, so match the message too. Re-creating on a transient+ * error would leave the company with two live Connect accounts, so this+ * stays narrow rather than treating every `invalid_request_error` as stale.+ */+export function isStaleConnectAccountError(err: unknown): boolean {+ if (!(err instanceof Stripe.errors.StripeError)) return false;+ if (err.code === "resource_missing") return true;+ if (err.statusCode === 403 || err.statusCode === 404) return true;+ return /does not have access to account|application access may have been revoked/i.test(+ err.message ?? ""+ );+}++/**+ * Whether a previously-created Connect account is still usable from the+ * platform's side. Mirrors `getConnectAccountStatus`'s `include`d retrieve+ * (not a bare one) — that's the call shape that actually surfaces a revoked+ * connection; see `isStaleConnectAccountError`.+ */+export async function isConnectAccountStillLinked(+ stripeAccountId: string+): Promise<boolean> {+ if (!stripeConnect) return false;++ try {+ await stripeConnect.v2.core.accounts.retrieve(stripeAccountId, {+ include: ["configuration.merchant", "requirements"]+ });+ return true;+ } catch (err) {+ if (isStaleConnectAccountError(err)) return false;+ throw err;+ }+}++export async function getOrCreateConnectAccount(+ client: SupabaseClient<Database>,+ companyId: string,+ userEmail: string,+ options?: { forceNew?: boolean }+): Promise<string> {+ if (!stripeConnect) {+ throw new Error("Stripe secret key is not configured.");+ }+ // 1. Check if company already has a companyIntegration row for stripe-connect+ const existingIntegration = await client+ .from("companyIntegration")+ .select("metadata, active")+ .eq("id", "stripe-connect")+ .eq("companyId", companyId)+ .maybeSingle();++ if (existingIntegration.error) {+ throw new Error(+ `Failed to read the stripe-connect integration row: ${existingIntegration.error.message}`+ );+ }++ const existingMeta = existingIntegration.data?.metadata as+ | Record<string, unknown>+ | undefined;+ // `forceNew` skips reuse entirely — used when a caller already proved the+ // stored account is stale (e.g. `createConnectAccountLink` just failed+ // with `isStaleConnectAccountError`) and a liveness re-check would be+ // redundant.+ let stripeAccountId = options?.forceNew+ ? undefined+ : (existingMeta?.stripeAccountId as string | undefined);++ if (stripeAccountId) {+ if (await isConnectAccountStillLinked(stripeAccountId)) {+ return stripeAccountId;+ }++ log.warn(+ "Stripe Connect account is no longer linked (disconnected or deleted directly in Stripe); creating a new account",+ { companyId, stripeAccountId }+ );+ stripeAccountId = undefined;+ }++ // 2. Fetch company details to pre-populate Stripe Connect onboarding form+ const company = await client+ .from("company")+ .select("*")+ .eq("id", companyId)+ .single();++ if (company.error || !company.data) {+ throw new Error("Failed to load company details for Stripe Connect.");+ }++ const comp = company.data;++ const account = await stripeConnect.v2.core.accounts.create({+ contact_email: comp.email || undefined,+ display_name: comp.name,+ dashboard: STRIPE_CONNECT_ACCOUNT_CONFIG.dashboard,+ identity: {+ country: comp.countryCode || "US",+ entity_type: STRIPE_CONNECT_ACCOUNT_CONFIG.entityType,+ business_details: {+ registered_name: comp.name,+ phone: comp.phone || undefined,+ address: comp.countryCode+ ? {+ line1: comp.addressLine1 || undefined,+ line2: comp.addressLine2 || undefined,+ city: comp.city || undefined,+ state: comp.stateProvince || undefined,+ postal_code: comp.postalCode || undefined,+ country: comp.countryCode+ }+ : undefined+ }+ },+ configuration: {+ merchant: {+ capabilities: {+ ach_debit_payments: {+ requested:+ STRIPE_CONNECT_ACCOUNT_CONFIG.capabilities.ach_debit_payments+ },+ card_payments: {+ requested: STRIPE_CONNECT_ACCOUNT_CONFIG.capabilities.card_payments+ }+ },+ support: {+ email: comp.email || undefined,+ phone: comp.phone || undefined+ }+ }+ },+ defaults: {+ responsibilities: {+ fees_collector:+ STRIPE_CONNECT_ACCOUNT_CONFIG.responsibilities.feesCollector,+ losses_collector:+ STRIPE_CONNECT_ACCOUNT_CONFIG.responsibilities.lossesCollector+ }+ },+ metadata: {+ companyId+ },+ include: ["configuration.merchant", "requirements"]+ });++ stripeAccountId = account.id;++ const upsert = await client.from("companyIntegration").upsert({+ id: "stripe-connect",+ companyId,+ active: true,+ metadata: {+ ...existingMeta,+ stripeAccountId,+ ...deriveConnectAccountMetadata(account)+ }+ });++ if (upsert.error) {+ // The Stripe account already exists at this point — a swallowed error+ // here would leave no `stripeAccountId` in `companyIntegration`, and the+ // next call would find no existing row and create ANOTHER Stripe account+ // for the same company. Throw so the caller (and its logs) can recover+ // the orphaned account id rather than silently losing it.+ throw new Error(+ `Stripe Connect account ${stripeAccountId} was created but failed to save to companyIntegration: ${upsert.error.message}`+ );+ }++ return stripeAccountId;+}++export async function createConnectAccountLink(+ stripeAccountId: string,+ returnUrl: string,+ refreshUrl: string+): Promise<string> {+ if (!stripeConnect) {+ throw new Error("Stripe secret key is not configured.");+ }++ const accountLink = await stripeConnect.v2.core.accountLinks.create({+ account: stripeAccountId,+ use_case: {+ type: "account_onboarding",+ account_onboarding: {+ configurations: ["merchant"],+ return_url: returnUrl,+ refresh_url: refreshUrl+ }+ }+ });++ return accountLink.url;+}++export async function getConnectAccountStatus(stripeAccountId: string) {+ if (!stripeConnect) {+ return null;+ }++ try {+ const account = await stripeConnect.v2.core.accounts.retrieve(+ stripeAccountId,+ {+ include: ["configuration.merchant", "requirements"]+ }+ );++ return {+ stripeAccountId: account.id,+ ...deriveConnectAccountMetadata(account),+ email: account.contact_email,+ displayName: account.display_name+ };+ } catch (err) {+ log.error("Failed to retrieve Stripe Connect account status", {+ error: err+ });+ return null;+ }+}++export async function createExpressDashboardLoginLink(+ stripeAccountId: string+): Promise<string> {+ if (!stripe) {+ throw new Error("Stripe secret key is not configured.");+ }+ const loginLink = await stripe.accounts.createLoginLink(stripeAccountId);+ return loginLink.url;+}++// --- Invoicing against a connected account ---+// Everything below operates on an existing Connect account (see above) to+// create and send a Stripe invoice on its behalf. Same v1/v2 interop rule as+// createExpressDashboardLoginLink: Invoicing is a v1-only API surface, so it+// stays on the shared v1-pinned `stripe` client with `{ stripeAccount }`+// rather than the v2 `stripeConnect` client used for account management.++// Stripe expresses amounts in a currency's smallest unit, and the number of+// decimal places is currency-dependent — ¥1000 is `1000`, not `100000`. Anything+// not listed here is the ordinary 2-decimal case.+const ZERO_DECIMAL_CURRENCIES = new Set([+ "BIF",+ "CLP",+ "DJF",+ "GNF",+ "JPY",+ "KMF",+ "KRW",+ "MGA",+ "PYG",+ "RWF",+ "UGX",+ "VND",+ "VUV",+ "XAF",+ "XOF",+ "XPF"+]);++const THREE_DECIMAL_CURRENCIES = new Set(["BHD", "JOD", "KWD", "OMR", "TND"]);++function currencyExponent(currencyCode: string): number {+ const code = currencyCode.toUpperCase();+ if (ZERO_DECIMAL_CURRENCIES.has(code)) return 0;+ if (THREE_DECIMAL_CURRENCIES.has(code)) return 3;+ return 2;+}++/** Carbon's decimal amount → Stripe's smallest-unit integer. */+export function toStripeAmount(value: number, currencyCode: string): number {+ const factor = 10 ** currencyExponent(currencyCode);+ const minor = Math.round(value * factor);+ // Stripe rejects three-decimal amounts that aren't a multiple of 10 (the+ // smallest unit is charged in hundredths for these currencies).+ return currencyExponent(currencyCode) === 3+ ? Math.round(minor / 10) * 10+ : minor;+}++/** Stripe's smallest-unit integer → Carbon's decimal amount. */+export function fromStripeAmount(minor: number, currencyCode: string): number {+ return minor / 10 ** currencyExponent(currencyCode);+}++/**+ * Carbon's decimal amount → Stripe's `unit_amount_decimal`, a value in the+ * currency's smallest unit that Stripe multiplies by the quantity itself.+ *+ * Unlike `toStripeAmount` this must NOT round to a whole minor unit: rounding+ * the per-unit price first and then multiplying by, say, 250 turns a half-cent+ * into $1.25 of drift. Goes through the SDK's `Decimal` rather than+ * `value * 100` because binary floating point makes 19.99 into+ * 1998.9999999999998, and that error is about to be multiplied.+ */+function toStripeMinorDecimal(+ value: number,+ currencyCode: string+): Stripe.Decimal {+ const minor = Stripe.Decimal.from(String(value)).mul(+ Stripe.Decimal.from(10 ** currencyExponent(currencyCode))+ );+ // Stripe accepts at most twelve decimal places; six is already far more+ // precision than any ERP unit price carries.+ return Stripe.Decimal.from(minor.toFixed(6, "half-even"));+}++/**+ * One Carbon customer, flattened into the shape Stripe's customer endpoint wants.+ *+ * Carbon spreads a customer across `customer`, `customerTax`, `customerContact`+ * → `contact`, and `customerPayment` → `customerLocation` → `address`. Folding+ * those together is the ERP's job, not this package's — building the payload+ * here would drag the generated DB types into `@carbon/stripe`. The caller+ * (`apps/erp/app/modules/invoicing/stripe-customer.server.ts`) owns the mapping+ * and hands over plain values.+ */+export type ConnectCustomerInput = {+ name: string;+ /**+ * Stripe accepts a customer with no email, but `collection_method:+ * "send_invoice"` — which `createAndSendConnectInvoice` always uses — has+ * nowhere to send the invoice without one. Required here so the failure+ * lands before an invoice is posted rather than at the send.+ */+ email: string;+ phone?: string;+ website?: string | null;+ /** `customer.readableId`; only ever applied on create. */+ readableId?: string | null;+ address?: Stripe.AddressParam;+ shipping?: Stripe.CustomerCreateParams.Shipping;+ /**+ * Already in Stripe's vocabulary. Interpreting Carbon's `taxExempt` /+ * `taxExemptionReason` pair is the ERP's job — this package does not know+ * that an `"Export"` sale is a reverse charge rather than an exemption.+ */+ taxExempt?: Stripe.CustomerCreateParams.TaxExempt;+ metadata: Record<string, string>;+};++/**+ * Stripe's `invoice_prefix` accepts 3–12 uppercase alphanumerics. Carbon's+ * `readableId` ("CUS000123") already fits once punctuation is stripped, but a+ * customer imported with a short or symbol-heavy id may not — return undefined+ * and let Stripe assign its own rather than send something it will reject.+ */+function toInvoicePrefix(readableId?: string | null): string | undefined {+ if (!readableId) return undefined;+ const cleaned = readableId.replace(/[^A-Z0-9]/gi, "").toUpperCase();+ return cleaned.length >= 3 ? cleaned.slice(0, 12) : undefined;+}++/**+ * Look a customer up on a connected account.+ *+ * Returns null — rather than throwing — when the id no longer resolves, so a+ * stale `externalIntegrationMapping` row degrades into "offer to create one"+ * instead of a 500 in the middle of posting an invoice. Stripe returns deleted+ * customers as a `{ deleted: true }` stub rather than a 404, so both shapes+ * have to collapse to the same answer.+ */+export async function retrieveConnectCustomer(+ stripeAccountId: string,+ stripeCustomerId: string+): Promise<Stripe.Customer | null> {+ if (!stripe) {+ throw new Error("Stripe secret key is not configured.");+ }++ try {+ const customer = await stripe.customers.retrieve(+ stripeCustomerId,+ {},+ { stripeAccount: stripeAccountId }+ );+ return customer.deleted ? null : (customer as Stripe.Customer);+ } catch (err) {+ if (+ err instanceof Stripe.errors.StripeError &&+ err.code === "resource_missing"+ ) {+ return null;+ }+ throw err;+ }+}++/**+ * Find customers on a connected account by exact email.+ *+ * Uses `customers.list({ email })` rather than `customers.search`: search runs+ * against an index that lags writes by up to a minute, so a customer created+ * moments ago would not be found and would be duplicated. `list` reads straight+ * through.+ *+ * `limit: 2` is deliberate — the caller only needs to know "none", "exactly+ * one", or "more than one". A shared AP mailbox across subsidiaries produces+ * several, and that ambiguity must reach the user rather than be resolved by+ * taking the first row.+ */+export async function findConnectCustomersByEmail(+ stripeAccountId: string,+ email: string+): Promise<Stripe.Customer[]> {+ if (!stripe) {+ throw new Error("Stripe secret key is not configured.");+ }++ const matches = await stripe.customers.list(+ { email, limit: 2 },+ { stripeAccount: stripeAccountId }+ );++ return matches.data;+}++/**+ * Create a customer on a connected account, or update one that already exists.+ *+ * Two parameters are create-only and are therefore absent from the update path:+ * `invoice_prefix` (updatable in the API, but it must stay unique across the+ * account and rewriting it after invoices exist re-numbers nothing that already+ * shipped) and `tax_id_data`, which Stripe's update endpoint does not accept at+ * all — changing tax ids there means `createTaxId`/`deleteTaxId`.+ */+export async function upsertConnectCustomer(+ stripeAccountId: string,+ stripeCustomerId: string | null,+ input: ConnectCustomerInput+): Promise<string> {+ if (!stripe) {+ throw new Error("Stripe secret key is not configured.");+ }++ const options = { stripeAccount: stripeAccountId };++ const payload: Stripe.CustomerUpdateParams = {+ name: input.name,+ business_name: input.name,+ email: input.email,+ phone: input.phone,+ address: input.address,+ shipping: input.shipping,+ description: input.website ? `Website: ${input.website}` : undefined,+ tax_exempt: input.taxExempt ?? "none",+ metadata: input.metadata+ };++ if (stripeCustomerId) {+ const updated = await stripe.customers.update(+ stripeCustomerId,+ payload,+ options+ );+ return updated.id;+ }++ // The idempotency key is scoped by this field — if it's ever missing, every+ // customer created for the account collapses onto the SAME key, and Stripe+ // returns the first-ever-created customer for every subsequent call,+ // silently pointing every later invoice at the wrong Stripe customer.+ const carbonCustomerId = input.metadata.carbon_customer_id;+ if (!carbonCustomerId) {+ throw new Error(+ "ConnectCustomerInput.metadata.carbon_customer_id is required to create a Stripe customer."+ );+ }++ const created = await stripe.customers.create(+ {+ ...payload,+ invoice_prefix: toInvoicePrefix(input.readableId)+ },+ {+ ...options,+ idempotencyKey: `customer:${stripeAccountId}:${carbonCustomerId}`+ }+ );++ return created.id;+}++/**+ * One Carbon `salesInvoiceLine`, as the Stripe mapping needs to see it.+ *+ * The cost components are NOT interchangeable and — apart from `unitPrice` —+ * are NOT per-unit. This mirrors the `salesInvoices` view, which is the single+ * definition of what a Carbon sales invoice is worth (migration+ * `20260702224219_fix-ar-ap-legacy-paid.sql`):+ *+ * subtotal = Σ (quantity·unitPrice + addOnCost + nonTaxableAddOnCost + shippingCost)+ * totalTax = Σ taxPercent·(quantity·unitPrice + addOnCost + shippingCost)+ * total = subtotal + totalTax + salesInvoiceShipment.shippingCost+ *+ * Three consequences worth stating out loud, because each one is a way to bill+ * the customer an amount Carbon's ledger disagrees with:+ * - `nonTaxableAddOnCost` counts toward the subtotal but NOT the tax base.+ * - the header-level shipping cost is added AFTER tax and is never taxed.+ * - `setupPrice` appears in neither sum, so it is deliberately absent from+ * this type. Billing it would collect more cash than the invoice is owed,+ * and `recordStripeConnectPayment` settles whatever Stripe collected.+ */+export type ConnectInvoiceLineInput = {+ description: string;+ /** `salesInvoiceLine.quantity` — NUMERIC, so genuinely fractional. */+ quantity: number;+ /** Per-unit price, in the invoice currency (never the `converted*` mirror). */+ unitPrice: number;+ /** Flat per-line surcharge, taxable. Not multiplied by quantity. */+ addOnCost?: number;+ /** Flat per-line freight, taxable. Not multiplied by quantity. */+ shippingCost?: number;+ /** Flat per-line surcharge, NOT taxed. */+ nonTaxableAddOnCost?: number;+ /**+ * A FRACTION in [0, 1] — that is the column's CHECK constraint, not a+ * percent. 0.0825 means 8.25%. Passing 8.25 here would bill 825% tax.+ */+ taxPercent?: number;+ unitOfMeasureCode?: string | null;+ /** Carbon ids for traceability; merged into every item this line emits. */+ metadata?: Record<string, string>;+};++export type ConnectInvoiceInput = {+ lines: ConnectInvoiceLineInput[];+ currencyCode: string;+ /** `salesInvoiceShipment.shippingCost` — invoice-level, and never taxed. */+ shippingCost?: number;+ /** Carbon's human-readable `invoiceId`, printed as Stripe's invoice number. */+ invoiceNumber?: string;+ /**+ * Unix SECONDS. The caller resolves Carbon's calendar date on the company's+ * business timezone — this package has no business calendar of its own.+ */+ dueDate?: number;+ /** Unix SECONDS. Overrides the "Date of issue" printed on the Stripe PDF. */+ effectiveAt?: number;+ /** Fallback when `dueDate` is absent; Stripe takes one or the other. */+ daysUntilDue?: number;+ /** Customer-facing. Carbon's external notes, already flattened to text. */+ description?: string;+ footer?: string;+ /** Stripe renders at most 4. */+ customFields?: { name: string; value: string }[];+ shippingDetails?: {+ name: string;+ phone?: string;+ address: {+ line1?: string;+ line2?: string;+ city?: string;+ state?: string;+ postal_code?: string;+ /** ISO 3166-1 alpha-2, which is what Carbon's `countryCode` already is. */+ country?: string;+ };+ };+ metadata?: Record<string, string>;+};++/**+ * What Carbon says this invoice is worth, by the `salesInvoices` view's own+ * arithmetic. Exported so callers gate on the same number Stripe will be+ * reconciled against instead of an independent (and quietly different) sum.+ */+export function expectedConnectInvoiceTotal(params: {+ lines: ConnectInvoiceLineInput[];+ shippingCost?: number;+}): { subtotal: number; tax: number; shipping: number; total: number } {+ let subtotal = 0;+ let tax = 0;++ for (const line of params.lines) {+ const taxable =+ line.unitPrice * line.quantity ++ (line.addOnCost ?? 0) ++ (line.shippingCost ?? 0);+ subtotal += taxable + (line.nonTaxableAddOnCost ?? 0);+ tax += (line.taxPercent ?? 0) * taxable;+ }++ const shipping = params.shippingCost ?? 0;+ return { subtotal, tax, shipping, total: subtotal + tax + shipping };+}++// Tax rate ids resolved this process, keyed by account + percentage. Stripe has+// no upsert for tax rates, so without this every line of every invoice would+// re-list (and race to re-create) the same rate.+const TAX_RATE_IDS = new Map<string, string>();++/** Carbon's `taxPercent` fraction → Stripe's `percentage`, which is out of 100. */+function toStripePercentage(taxPercent: number): number {+ // 0.0825 * 100 is 8.250000000000002 in floating point, and Stripe takes at+ // most four decimal places on `percentage`.+ return Math.round(taxPercent * 1_000_000) / 10_000;+}++/**+ * The connected account's Stripe Tax Rate for a given percentage, created on+ * first use. Carbon stores a bare number per line; Stripe only accepts ids.+ *+ * Scoped to the connected account (`stripeAccount`) — a rate created on the+ * platform account is invisible to the account actually issuing the invoice.+ */+async function resolveConnectTaxRateId(+ stripeAccountId: string,+ percentage: number+): Promise<string> {+ if (!stripe) {+ throw new Error("Stripe secret key is not configured.");+ }++ const cacheKey = `${stripeAccountId}:${percentage}`;+ const cached = TAX_RATE_IDS.get(cacheKey);+ if (cached) return cached;++ const options = { stripeAccount: stripeAccountId };++ // `list` returns 10 per page by default. Matching against only the first page+ // is how an account ends up with a dozen identical 8.25% rates.+ let match: Stripe.TaxRate | undefined;+ await stripe.taxRates+ .list({ active: true, inclusive: false, limit: 100 }, options)+ .autoPagingEach((rate) => {+ if (rate.percentage === percentage) {+ match = rate;+ return false;+ }+ });++ const taxRate =+ match ??+ (await stripe.taxRates.create(+ {+ display_name: "Tax",+ description: `Carbon ${percentage}%`,+ percentage,+ // Carbon's totals add tax ON TOP of the subtotal, so the rate is+ // exclusive. An inclusive rate would carve the tax out of the price and+ // undercharge by exactly the tax.+ inclusive: false,+ metadata: { carbonTaxPercent: String(percentage) }+ },+ options+ ));++ TAX_RATE_IDS.set(cacheKey, taxRate.id);+ return taxRate.id;+}++export async function createAndSendConnectInvoice(+ stripeAccountId: string,+ stripeCustomerId: string,+ params: ConnectInvoiceInput+): Promise<{+ id: string;+ hostedInvoiceUrl: string | null;+ invoicePdf: string | null;+}> {+ if (!stripe) {+ throw new Error("Stripe secret key is not configured.");+ }++ const currency = params.currencyCode.toLowerCase();+ const options = { stripeAccount: stripeAccountId };+ const expected = expectedConnectInvoiceTotal(params);+ const expectedMinor = toStripeAmount(expected.total, currency);++ // Stripe refuses to send a zero-amount invoice, and the resulting API error+ // ("This invoice cannot be sent right now") gives no hint why — so fail here+ // with something actionable instead.+ if (!params.lines.length || expectedMinor <= 0) {+ throw new Error(+ "the invoice has no billable lines (Stripe cannot send a zero-amount invoice)"+ );+ }++ // Carbon splits one line into components that tax differently and that Stripe+ // has no single-item representation for, so one Carbon line becomes up to+ // four Stripe items. Built before the draft exists so a bad line (an+ // unresolvable tax rate) fails without leaving an orphaned draft behind.+ const items: Stripe.InvoiceItemCreateParams[] = [];++ for (const line of params.lines) {+ const label = line.description?.trim() || "Item";+ const percentage = line.taxPercent+ ? toStripePercentage(line.taxPercent)+ : 0;+ const taxRates = percentage+ ? [await resolveConnectTaxRateId(stripeAccountId, percentage)]+ : [];++ const base = {+ customer: stripeCustomerId,+ currency+ } satisfies Partial<Stripe.InvoiceItemCreateParams>;++ // Emitted even at a unit price of zero: a free or included line contributes+ // nothing to the total but is still something the customer expects to read+ // on the invoice, and Stripe accepts zero-amount items.+ if (line.quantity > 0) {+ items.push({+ ...base,+ description: line.unitOfMeasureCode+ ? `${label} (${line.unitOfMeasureCode})`+ : label,+ // `amount` is mutually exclusive with the quantity fields, so the unit+ // breakdown only survives onto the PDF via this pair. `quantity` alone+ // is an integer and would truncate Carbon's fractional quantities —+ // 2.5 hours would bill as 2.+ unit_amount_decimal: toStripeMinorDecimal(line.unitPrice, currency),+ quantity_decimal: Stripe.Decimal.from(String(line.quantity)),+ tax_rates: taxRates,+ metadata: { ...line.metadata, carbonComponent: "unit" }+ });+ }++ // The flat components carry no quantity, so they use `amount` directly.+ if (line.addOnCost) {+ items.push({+ ...base,+ description: `${label} — Additional charges`,+ amount: toStripeAmount(line.addOnCost, currency),+ tax_rates: taxRates,+ metadata: { ...line.metadata, carbonComponent: "addOnCost" }+ });+ }++ if (line.shippingCost) {+ items.push({+ ...base,+ description: `${label} — Freight`,+ amount: toStripeAmount(line.shippingCost, currency),+ tax_rates: taxRates,+ metadata: { ...line.metadata, carbonComponent: "shippingCost" }+ });+ }++ if (line.nonTaxableAddOnCost) {+ items.push({+ ...base,+ description: `${label} — Additional charges (non-taxable)`,+ amount: toStripeAmount(line.nonTaxableAddOnCost, currency),+ // Deliberately no `tax_rates` — this component is outside the tax base+ // in the view, and an empty array here is what keeps it that way.+ tax_rates: [],+ metadata: { ...line.metadata, carbonComponent: "nonTaxableAddOnCost" }+ });+ }+ }++ if (params.shippingCost) {+ items.push({+ customer: stripeCustomerId,+ currency,+ description: "Shipping",+ amount: toStripeAmount(params.shippingCost, currency),+ tax_rates: [],+ metadata: { carbonComponent: "invoiceShippingCost" }+ });+ }++ // Create the draft FIRST, then attach each item to it by id. Creating items+ // against the customer alone leaves them as *pending* items that a standalone+ // invoice does not pick up unless it passes `pending_invoice_items_behavior:+ // "include"` — and any item left unconsumed silently lands on the next+ // invoice created for that customer. Attaching explicitly avoids both traps.+ const invoice = await stripe.invoices.create(+ {+ customer: stripeCustomerId,+ currency,+ collection_method: "send_invoice",+ ...(params.dueDate+ ? { due_date: params.dueDate }+ : params.daysUntilDue+ ? { days_until_due: params.daysUntilDue }+ : {}),+ ...(params.effectiveAt ? { effective_at: params.effectiveAt } : {}),+ ...(params.invoiceNumber ? { number: params.invoiceNumber } : {}),+ ...(params.description ? { description: params.description } : {}),+ ...(params.footer ? { footer: params.footer } : {}),+ ...(params.customFields?.length+ ? { custom_fields: params.customFields.slice(0, 4) }+ : {}),+ ...(params.shippingDetails+ ? { shipping_details: params.shippingDetails }+ : {}),+ auto_advance: false,+ metadata: params.metadata+ },+ options+ );++ // Sequential, not Promise.all: invoice items render in creation order, and a+ // reordered PDF would not match the Carbon invoice beside it.+ for (const item of items) {+ await stripe.invoiceItems.create(+ { ...item, invoice: invoice.id! },+ options+ );+ }++ // Stripe totals the draft itself, which makes it the only honest check that+ // this mapping is complete: whatever it says here is what the customer pays+ // and what `recordStripeConnectPayment` will settle against the Carbon+ // invoice. A silent divergence leaves a permanent residual balance.+ const draft = await stripe.invoices.retrieve(invoice.id!, {}, options);+ const drift = Math.abs((draft.total ?? 0) - expectedMinor);+ // Carbon rounds tax once over the whole invoice; Stripe rounds per item. Each+ // item can therefore land a single minor unit either way, and Carbon forgives+ // sub-cent residuals (`INVOICE_DUST_THRESHOLD`). Anything past that is a+ // mapping bug, not rounding.+ if (drift > items.length) {+ await stripe.invoices.del(invoice.id!, {}, options);+ throw new Error(+ `the Stripe invoice totals ${fromStripeAmount(draft.total ?? 0, currency)} ${currency.toUpperCase()} but the Carbon invoice totals ${expected.total} — refusing to send`+ );+ }+ // TODO: Accounting journal entry for this?+ if (drift > 0) {+ log.warn("Stripe Connect invoice total differs from Carbon by rounding", {+ stripeAccountId,+ invoiceId: invoice.id,+ driftMinorUnits: drift+ });+ }++ const finalized = await stripe.invoices.finalizeInvoice(+ invoice.id!,+ {},+ options+ );+ const sent = await stripe.invoices.sendInvoice(finalized.id!, {}, options);++ return {+ id: sent.id!,+ hostedInvoiceUrl: sent.hosted_invoice_url ?? null,+ invoicePdf: sent.invoice_pdf ?? null+ };+}++// --- Connect webhooks ---+// Connected-account events arrive at a SEPARATE endpoint registered with+// `connect: true`, signed with its own secret and carrying `event.account`.+// Deliberately kept out of `processStripeEvent` (@carbon/stripe/AGENTS.md fences+// that to platform subscription state).++// Re-exported so consumers (the ERP app) can type webhook payloads without+// taking a direct dependency on the `stripe` package themselves.+export type ConnectWebhookEvent = Stripe.Event;+export type ConnectInvoice = Stripe.Invoice;+export type ConnectCharge = Stripe.Charge;+export type ConnectDispute = Stripe.Dispute;++export function constructConnectWebhookEvent({+ body,+ signature+}: {+ body: string;+ signature: string;+}) {+ if (!stripe) {+ return {+ success: false as const,+ event: null,+ error: new Error("Stripe is not initialized")+ };+ }++ if (!STRIPE_CONNECT_WEBHOOK_SECRET) {+ return {+ success: false as const,+ event: null,+ error: new Error("STRIPE_CONNECT_WEBHOOK_SECRET is not configured")+ };+ }++ try {+ const event = stripe.webhooks.constructEvent(+ body,+ signature,+ STRIPE_CONNECT_WEBHOOK_SECRET+ );+ return { success: true as const, event, error: null };+ } catch (err) {+ return { success: false as const, event: null, error: err as Error };+ }+}++export type ConnectInvoicePaymentDetails = {+ /** Charge ids behind this invoice's payments, for traceability. */+ chargeIds: string[];+ /**+ * Stripe's processing fee, as a decimal amount in `feeCurrency`. When Stripe+ * settled the charge into a different currency than it was presented in,+ * this is already converted back to the charge's own currency using the+ * balance transaction's own `exchange_rate` — the same rate Stripe applied —+ * so callers can book it directly against the invoice.+ */+ feeAmount: number;+ /**+ * Currency `feeAmount` is expressed in — the charge's own currency (which,+ * for Stripe Invoicing, is always the invoice currency) whenever a rate was+ * available to convert into it. Falls back to the account's raw SETTLEMENT+ * currency only when Stripe settled into a different currency with no+ * `exchange_rate` to convert by (should not happen, but Stripe doesn't+ * guarantee it) — callers must compare this against the invoice currency+ * before booking in that residual case.+ */+ feeCurrency: string | null;+ /**+ * Set only when Stripe settled this charge into a currency other than+ * `feeCurrency` — the raw settlement currency, kept for audit/reconciliation+ * traceability alongside the (possibly converted) `feeAmount` above.+ */+ settlementCurrency: string | null;+ /**+ * The realized rate Stripe actually settled this payment's charge(s) at —+ * `balance_transaction.exchange_rate`, converts FROM the charge's own+ * currency TO the settlement currency — captured from the same balance+ * transaction the fee conversion above already reads. `null` when no+ * conversion happened (charge currency == settlement currency), in which+ * case the caller should fall back to the invoice's own booked rate.+ */+ exchangeRate: number | null;+};++/**+ * The charges (and Stripe's fee) behind a paid invoice on a connected account.+ *+ * The shared v1 client is pinned to `2025-06-30.basil`, where `invoice.charge`+ * and `invoice.payment_intent` no longer exist — payments hang off+ * `invoice.payments` as InvoicePayment objects instead. The fee itself only+ * lives on the charge's balance transaction, so each payment costs one extra+ * expanded retrieve.+ *+ * Never throws: a fee we can't resolve returns `feeAmount: 0` with a logged+ * warning, because failing to book a fee must not cost us the payment itself.+ */+export async function getConnectInvoicePaymentDetails(+ stripeAccountId: string,+ invoiceId: string+): Promise<ConnectInvoicePaymentDetails> {+ const empty: ConnectInvoicePaymentDetails = {+ chargeIds: [],+ feeAmount: 0,+ feeCurrency: null,+ settlementCurrency: null,+ exchangeRate: null+ };++ if (!stripe) return empty;++ const options = { stripeAccount: stripeAccountId };++ try {+ // Listed rather than read off the webhook's invoice snapshot: `payments` is+ // an expandable sub-list, so the delivered payload may carry only the first+ // page (or none at all).+ const payments = await stripe.invoicePayments.list(+ { invoice: invoiceId, limit: 100 },+ options+ );++ const chargeIds: string[] = [];+ let feeMinor = 0;+ let feeCurrency: string | null = null;+ let settlementCurrency: string | null = null;+ let exchangeRate: number | null = null;++ for (const payment of payments.data) {+ if (payment.status !== "paid") continue;++ let charge: Stripe.Charge | null = null;+ const source = payment.payment;++ if (source.charge) {+ const chargeId =+ typeof source.charge === "string" ? source.charge : source.charge.id;+ charge = await stripe.charges.retrieve(+ chargeId,+ { expand: ["balance_transaction"] },+ options+ );+ } else if (source.payment_intent) {+ const paymentIntentId =+ typeof source.payment_intent === "string"+ ? source.payment_intent+ : source.payment_intent.id;+ const paymentIntent = await stripe.paymentIntents.retrieve(+ paymentIntentId,+ { expand: ["latest_charge.balance_transaction"] },+ options+ );+ charge =+ typeof paymentIntent.latest_charge === "string"+ ? null+ : (paymentIntent.latest_charge ?? null);+ }++ if (!charge) continue;+ chargeIds.push(charge.id);++ const balanceTransaction = charge.balance_transaction;+ if (balanceTransaction && typeof balanceTransaction !== "string") {+ const chargeCurrency = charge.currency.toUpperCase();+ const txnCurrency = balanceTransaction.currency.toUpperCase();+ if (txnCurrency !== chargeCurrency) settlementCurrency = txnCurrency;++ if (+ txnCurrency === chargeCurrency ||+ !balanceTransaction.exchange_rate+ ) {+ // Same currency, or (rare) no rate to convert with — report the fee+ // as Stripe assessed it. The caller compares feeCurrency against the+ // invoice currency before booking.+ feeMinor += balanceTransaction.fee;+ feeCurrency = txnCurrency;+ } else {+ // Stripe settled this charge into a different currency than it was+ // presented in (e.g. the connected account hasn't enabled the+ // charge's currency as a settlement currency). Per Stripe's docs,+ // balance_transaction.exchange_rate converts FROM the charge's own+ // currency TO the settlement currency (chargeAmount × exchange_rate+ // = settlementAmount) — the same rate Stripe actually applied, so+ // divide it back out rather than reaching for an unrelated FX rate.+ // feeCurrency becomes the charge's own currency, which for Stripe+ // Invoicing is always the invoice currency.+ feeMinor += balanceTransaction.fee / balanceTransaction.exchange_rate;+ feeCurrency = chargeCurrency;+ exchangeRate = balanceTransaction.exchange_rate;+ }+ }+ }++ return {+ chargeIds,+ feeAmount: feeCurrency ? fromStripeAmount(feeMinor, feeCurrency) : 0,+ feeCurrency,+ settlementCurrency,+ exchangeRate+ };+ } catch (err) {+ log.warn("Failed to resolve Stripe Connect invoice payment details", {+ error: err,+ invoiceId,+ stripeAccountId+ });+ return empty;+ }+}diff --git a/packages/stripe/stripe.dev.ts b/packages/stripe/stripe.dev.tsindex 62ce2e7712..9fd1701824 100644--- a/packages/stripe/stripe.dev.ts+++ b/packages/stripe/stripe.dev.ts@@ -37,10 +37,23 @@ const events: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = ["payment_intent.canceled",];+// Events raised on CONNECTED accounts (Stripe Connect). These arrive on a+// separate CLI stream (`--forward-connect-to`) with their OWN signing secret —+// the one the CLI prints as the "connect" secret, which belongs in+// STRIPE_CONNECT_WEBHOOK_SECRET, not STRIPE_WEBHOOK_SECRET.+const connectEvents: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [+ "invoice.paid",+ "invoice.payment_succeeded",+ "invoice.payment_failed",+ "invoice.marked_uncollectible",+];+console.log("🔄 Setting up Stripe webhook endpoint...");const url = `${process.env.VERCEL_URL}/api/webhook/stripe`;+const connectUrl = `${process.env.VERCEL_URL}/api/webhook/stripe-connect`;console.log("🔄 Webhook URL:", url);+console.log("🔄 Connect webhook URL:", connectUrl);if (!url.includes("localhost:")) {throw new Error("Running in production mode");@@ -48,6 +61,9 @@ if (!url.includes("localhost:")) {console.log("🔄 Running in local development mode");console.log("🔄 Starting Stripe CLI webhook forwarder...");+// Two listeners rather than one: a single `stripe listen` signs everything it+// forwards with the same secret, so account and connect events must be split to+// keep their secrets distinct (matching how the deployed endpoints are signed).const stripeProcess = spawn("stripe", ["listen","--events",@@ -56,26 +72,45 @@ const stripeProcess = spawn("stripe", [url,]);-stripeProcess.stdout.on("data", (data) => {- console.log(`${data}`);- if (data.toString().includes("Ready!")) {- console.log("✅ Stripe CLI webhook forwarder is ready");- }-});+const stripeConnectProcess = spawn("stripe", [+ "listen",+ "--events",+ connectEvents.join(","),+ "--forward-connect-to",+ connectUrl,+]);-stripeProcess.stderr.on("data", (data) => {- console.error(`${data}`);-});+const processes = [+ { name: "account", process: stripeProcess },+ { name: "connect", process: stripeConnectProcess },+];-stripeProcess.on("close", (code) => {- if (code !== 0) {- console.error(`❌ Stripe CLI webhook forwarder exited with code ${code}`);- process.exit(1);- }-});+for (const { name, process: child } of processes) {+ child.stdout.on("data", (data) => {+ console.log(`[${name}] ${data}`);+ if (data.toString().includes("Ready!")) {+ console.log(`✅ Stripe CLI ${name} webhook forwarder is ready`);+ }+ });++ child.stderr.on("data", (data) => {+ console.error(`[${name}] ${data}`);+ });++ child.on("close", (code) => {+ if (code !== 0) {+ console.error(+ `❌ Stripe CLI ${name} webhook forwarder exited with code ${code}`+ );+ process.exit(1);+ }+ });+}// Keep the process runningprocess.on("SIGINT", () => {- stripeProcess.kill();+ for (const { process: child } of processes) {+ child.kill();+ }process.exit(0);});diff --git a/packages/stripe/stripe.register.ts b/packages/stripe/stripe.register.tsindex 27a87fbcaa..09e6ba1d53 100644--- a/packages/stripe/stripe.register.ts+++ b/packages/stripe/stripe.register.ts@@ -45,36 +45,61 @@ const events: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = ["payment_intent.canceled",];+const connectEvents: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [+ "invoice.paid",+ "invoice.payment_succeeded",+ "invoice.payment_failed",+ "invoice.marked_uncollectible",+];+// const webhookUrl = `https://${VERCEL_URL}/api/webhook/stripe`;const webhookUrl = `${ERP_URL}/api/webhook/stripe`;+const connectWebhookUrl = `${ERP_URL}/api/webhook/stripe-connect`;if (webhookUrl.includes("localhost")) {throw new Error("Cannot register webhook in local development mode");}-async function registerWebhook() {- console.log(`🔄 Registering Stripe webhook for ${webhookUrl}...`);+async function registerWebhook({+ url,+ enabledEvents,+ connect,+ secretEnvVar,+}: {+ url: string;+ enabledEvents: Stripe.WebhookEndpointCreateParams.EnabledEvent[];+ connect: boolean;+ secretEnvVar: string;+}) {+ console.log(`🔄 Registering Stripe webhook for ${url}...`);try {- // First, list existing webhooks to avoid duplicates- const existingEndpoints = await stripe.webhookEndpoints.list();+ // First, list existing webhooks to avoid duplicates. Stripe's default+ // page size is 10 — without an explicit limit, an account with more than+ // 10 webhooks would miss the existing endpoint here and create a+ // duplicate on every run.+ const existingEndpoints = await stripe.webhookEndpoints.list({+ limit: 100,+ });// Check if we already have a webhook for this URLconst existingEndpoint = existingEndpoints.data.find(- (endpoint) => endpoint.url === webhookUrl+ (endpoint) => endpoint.url === url);if (existingEndpoint) {- console.log(`ℹ️ Webhook already exists for ${webhookUrl}`);+ console.log(`ℹ️ Webhook already exists for ${url}`);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+ // Update the existing webhook with the current event types. `connect` is+ // fixed at creation and cannot be updated — recreate the endpoint if it+ // needs to change.const updatedEndpoint = await stripe.webhookEndpoints.update(existingEndpoint.id,{- enabled_events: events,+ enabled_events: enabledEvents,});@@ -84,8 +109,9 @@ async function registerWebhook() {// Create a new webhook endpointconst endpoint = await stripe.webhookEndpoints.create({- url: webhookUrl,- enabled_events: events,+ url,+ enabled_events: enabledEvents,+ connect,description: `Webhook for ${VERCEL_URL}`,});@@ -94,7 +120,7 @@ async function registerWebhook() {console.log(`ℹ️ Webhook Secret: ${endpoint.secret}`);console.log(`⚠️ IMPORTANT: Add this webhook secret to your environment variables:-STRIPE_WEBHOOK_SECRET=${endpoint.secret}+${secretEnvVar}=${endpoint.secret}`);return endpoint;@@ -104,11 +130,26 @@ STRIPE_WEBHOOK_SECRET=${endpoint.secret}}}-registerWebhook()+async function registerWebhooks() {+ await registerWebhook({+ url: webhookUrl,+ enabledEvents: events,+ connect: false,+ secretEnvVar: "STRIPE_WEBHOOK_SECRET",+ });+ await registerWebhook({+ url: connectWebhookUrl,+ enabledEvents: connectEvents,+ connect: true,+ secretEnvVar: "STRIPE_CONNECT_WEBHOOK_SECRET",+ });+}++registerWebhooks().then(() => {console.log(`-🎉 All done! Your Stripe webhook is now registered.-📝 Remember to add the webhook secret to your Vercel environment variables.+🎉 All done! Your Stripe webhooks are now registered.+📝 Remember to add the webhook secrets to your Vercel environment variables.`);}).catch((error) => {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c868be0a10..9d6110af35 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2222,6 +2222,9 @@ importers:'@carbon/react':specifier: workspace:*version: link:../react+ '@carbon/stripe':+ specifier: workspace:*+ version: link:../stripe'@carbon/utils':specifier: workspace:*version: link:../utils@@ -3282,8 +3285,8 @@ importers:specifier: 'catalog:'version: 2.80.0stripe:- specifier: 18.5.0- version: 18.5.0(@types/[email protected])+ specifier: 22.4.0+ version: 22.4.0(@types/[email protected])devDependencies:'@carbon/config':specifier: workspace:*@@ -15651,11 +15654,11 @@ packages:resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}engines: {node: '>=0.10.0'}- resolution: {integrity: sha512-Hp+wFiEQtCB0LlNgcFh5uVyKznpDjzyUZ+CNVEf+I3fhlYvh7rZruIg+jOwzJRCpy0ZTPMjlzm7J2/M2N6d+DA==}- engines: {node: '>=12.*'}+ resolution: {integrity: sha512-LVJ+tcSYeqOSnXr3i+Kz2tZ7y0crLLdP2uwD/4wccrmEVyn0g/Heo0pF7as7rxS/sOjJzrb1lxgZY0Y0Dx1pSA==}+ engines: {node: '>=18'}peerDependencies:- '@types/node': '>=12.x.x'+ '@types/node': '>=18'peerDependenciesMeta:'@types/node':optional: true@@ -30757,9 +30760,7 @@ snapshots:- [email protected](@types/[email protected]):- dependencies:- qs: 6.15.1+ [email protected](@types/[email protected]):optionalDependencies:'@types/node': 20.19.39diff --git a/sst.config.ts b/sst.config.tsindex 98bd480b60..baa5c00c49 100644--- a/sst.config.ts+++ b/sst.config.ts@@ -89,6 +89,8 @@ export default $config({STRIPE_BYPASS_COMPANY_IDS: process.env.STRIPE_BYPASS_COMPANY_IDS,STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,+ STRIPE_CONNECT_WEBHOOK_SECRET:+ process.env.STRIPE_CONNECT_WEBHOOK_SECRET,SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY,SUPABASE_DB_URL: process.env.SUPABASE_DB_URL,SUPABASE_JWT_SECRET: process.env.SUPABASE_JWT_SECRET,