Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(rillet): import customers and vendors from Rillet into Carbon (#1641)
Brad Barbind0b38f3e0a16
diff --git a/.ai/plans/2026-09-15-rillet-import-contacts.md b/.ai/plans/2026-09-15-rillet-import-contacts.mdnew file mode 100644index 0000000000..67982c72db--- /dev/null+++ b/.ai/plans/2026-09-15-rillet-import-contacts.md@@ -0,0 +1,47 @@+# Rillet: import customers and vendors++Add a **Import customers & vendors** action to the Rillet integration that pulls+Rillet Customers and Vendors into Carbon and records the+`externalIntegrationMapping` rows, so a later Carbon sales order / invoice pushes+onto the EXISTING Rillet customer instead of creating a duplicate.++## Why the mapping retention is (mostly) free++`RilletCustomerSyncer.upsertRemote` already calls `getRemoteId(localId)` first and+does a `PUT /customers/{id}` when a mapping exists — only a mapping-less local id+reaches `createCustomer`. Same for vendors. So linking on import is the whole job:+`BaseEntitySyncer.pullFromAccounting/pullBatchFromAccounting` call `linkEntities`+after `upsertLocal`, which writes the mapping row.++## Tasks++1. `providers/rillet/entities/shared.ts` — split `RilletEntitySyncer` (Rillet+ plumbing + structured-error push override) from a new+ `RilletPushOnlyEntitySyncer` that owns the four pull rejections.+ `RilletTransactionSyncer` extends the push-only one.+2. `entities/item.ts` — extend `RilletPushOnlyEntitySyncer` (unchanged behavior).+3. `entities/customer.ts` / `entities/vendor.ts` — extend `RilletEntitySyncer` and+ implement the pull half: pure `mapRilletCustomerToLocal` /+ `mapRilletVendorToLocal`, plus `upsertLocal` with the match ladder+ mapping → `carbon` external_reference → unique name, and a `fetchRemoteBatch`+ that indexes ONE cursor-drained list instead of N single GETs.+4. `providers/rillet/provider.ts` — document that customer/vendor stay+ `push-to-accounting` / `owner: "carbon"`: the import is an explicit+ `pull-from-accounting` ledger operation, and `owner: "carbon"` is what stops a+ re-import from clobbering a linked Carbon record.+5. `packages/jobs/.../integrations/rillet-import-contacts.ts` — new Inngest+ function: list customers + vendors, enqueue `pull-from-accounting` ledger+ operations in chunks, drain each chunk through `drainSyncOperations`.+6. `packages/lib/src/events.ts` + `trigger.ts` + `inngest/index.ts` — register the+ event and the function.+7. `apps/erp/app/routes/api+/integrations.rillet.import-contacts.ts` — POST+ endpoint (`update: "settings"`), verifies the integration is installed/active.+8. `packages/ee/src/rillet/config.tsx` — the `actions` entry (the button).+9. Tests: the pure mappers + the match ladder + the batch list indexing.++## Deliberately NOT done++- Addresses are not imported. Both the Xero and QBO pulls skip them, Carbon's+ `address.countryCode` is an FK to `country.alpha2` (a Rillet free-text country+ would fail the whole row), and a location needs a name Rillet does not carry.+- `direction` stays push-only, so no cron starts pulling contacts on its own.diff --git a/.claude/rules/accounting-sync-handlers.md b/.claude/rules/accounting-sync-handlers.mdindex 8b33f92764..aa6f62b5e2 100644--- a/.claude/rules/accounting-sync-handlers.md+++ b/.claude/rules/accounting-sync-handlers.md@@ -26,7 +26,7 @@ The sync engine lives in `packages/ee/src/accounting/` (package `@carbon/ee/acco`AccountingEntityType` = `customer | vendor | item | employee | purchaseOrder | bill | salesOrder | invoice | payment | inventoryAdjustment | journalEntry`. `payment` is `dependsOn: ['invoice','bill']` and **two-way** (Phase G): provider-recorded payments pull back (Phase F) and Carbon-born Posted payments push out as provider payment documents. Routing is per-record by origin (the `payment` mapping), not a static direction — see Payment sync-back.-`SyncDirection` = `"two-way" | "push-to-accounting" | "pull-from-accounting"` (NOT the old `from-/to-/bi-directional`). Each entity has an `EntityConfig { enabled, direction, owner: "carbon" | "accounting", syncFromDate? }`. Per-entity defaults live in `DEFAULT_SYNC_CONFIG`, deep-merged with the company's stored `syncConfig`; providers then force an entity's config in their `build{Xero,Qbo,Rillet}SyncConfig`. **Carbon owns everything** is the standardized stance: every provider forces the master + document entities `customer`/`vendor`/`item`/`invoice`/`bill` to `push-to-accounting` / `owner: "carbon"` (`XERO_CARBON_OWNED_ENTITIES`, `QBO_CARBON_OWNED_ENTITIES`, Rillet's `RILLET_PUSH_ONLY_ENTITIES`) — the provider is a downstream mirror. `payment` is the one accounting-owned exception (forced `pull-from-accounting` / `owner: "accounting"`; Rillet two-way for Phase G push-back). There is **no** per-entity "Source of Truth" setting — it was removed; `owner` is provider-forced, not user-configurable. `owner` decides the winner on conflict: for a Carbon-owned entity, an inbound provider change to an already-linked record is skipped (`BaseEntitySyncer.pullBatchFromAccounting`, `core/types.ts`). Note the webhook path sends an explicit `pull-from-accounting` that overrides `direction`, so a net-new record created directly in the provider can still be ingested — `owner: "carbon"` only guards *linked* records; QBO's CDC pull-sweep (`listChanges`) does honor `direction` and skips push-only entities entirely.+`SyncDirection` = `"two-way" | "push-to-accounting" | "pull-from-accounting"` (NOT the old `from-/to-/bi-directional`). Each entity has an `EntityConfig { enabled, direction, owner: "carbon" | "accounting", syncFromDate? }`. Per-entity defaults live in `DEFAULT_SYNC_CONFIG`, deep-merged with the company's stored `syncConfig`; providers then force an entity's config in their `build{Xero,Qbo,Rillet}SyncConfig`. **Carbon owns everything** is the standardized stance: every provider forces the master + document entities `customer`/`vendor`/`item`/`invoice`/`bill` to `push-to-accounting` / `owner: "carbon"` (`XERO_CARBON_OWNED_ENTITIES`, `QBO_CARBON_OWNED_ENTITIES`, Rillet's `RILLET_PUSH_ONLY_ENTITIES`) — the provider is a downstream mirror. `payment` is the one accounting-owned exception (forced `pull-from-accounting` / `owner: "accounting"`; Rillet two-way for Phase G push-back). There is **no** per-entity "Source of Truth" setting — it was removed; `owner` is provider-forced, not user-configurable. Rillet's `customer`/`vendor` are the one place a Carbon-owned entity has a working PULL path: the explicit contact import below enqueues `pull-from-accounting` operations by hand (see the Rillet contact import section) — the automatic direction is unchanged, and `owner: "carbon"` is exactly what keeps a re-import from overwriting a linked record. `owner` decides the winner on conflict: for a Carbon-owned entity, an inbound provider change to an already-linked record is skipped (`BaseEntitySyncer.pullBatchFromAccounting`, `core/types.ts`). Note the webhook path sends an explicit `pull-from-accounting` that overrides `direction`, so a net-new record created directly in the provider can still be ingested — `owner: "carbon"` only guards *linked* records; QBO's CDC pull-sweep (`listChanges`) does honor `direction` and skips push-only entities entirely.## Inngest functions (entry points)@@ -38,6 +38,7 @@ These live in `packages/jobs/src/inngest/functions/integrations/` (+ `events/syn| `accounting-pull-sweep` | — | `accounting-pull-sweep.ts` | cron `*/30 * * * *`; iterates every active integration that implements `SupportsIncrementalPull` (`listChanges`) — the **INBOUND correctness guarantee** behind the webhooks (webhooks are latency, not correctness) || `accounting-outbound-sweep` | — | `accounting-outbound-sweep.ts` | cron `15,45 * * * *` (offset from the pull sweep) — the **OUTBOUND correctness guarantee** (v4 Pillar B); see the sweep section below || `accounting-backfill` | `carbon/accounting-backfill` | `accounting-backfill.ts` | `accounting-backfill` |+| `rillet-import-contacts` | `carbon/rillet-import-contacts` | `rillet-import-contacts.ts` | the Rillet integration's **Import customers & vendors** action; the only on-demand PULL of master data — see the Rillet contact import section below || `accounting-consolidation` | — | `accounting-consolidation.ts` | cron `0 2 * * *`; pushes one aggregated provider journal per posting date for daily-consolidation configs (drains hold those journal ops for it) || `accounting-reconciliation` | — | `accounting-reconciliation.ts` | cron `0 3 * * 1` (Mondays 03:00 UTC) — presence drift check + `accountingSyncTieOut` writer; see the tie-out section below || `event-handler-sync` | `carbon/event-sync` | `events/sync.ts` | the SYNC event-system handler (see event-system.md) — DB writes -> push to the provider |@@ -318,3 +319,59 @@ is dead config for Rillet only, left in place for the capped providers.- DELETE sync is not implemented anywhere yet.- Don't hand-edit generated DB types; read the newest migration for schema truth.</content>++## Rillet contact import (on-demand pull)++`rillet-import-contacts.ts` + `apps/erp/app/routes/api+/integrations.rillet.import-contacts.ts`,+reached from the **Import customers & vendors** action on the Rillet integration+settings page (`actions` in `packages/ee/src/rillet/config.tsx`).++Seeds Carbon from a Rillet organization that already has contacts, and — the actual+point — writes the `externalIntegrationMapping` rows. `RilletCustomerSyncer.upsertRemote`+resolves `getRemoteId(localId)` before writing, so once a Carbon customer is linked, a+sales invoice raised in Carbon PUTs the ORIGINAL Rillet customer instead of creating a+second one. Same for vendors and bills.++- The job lists customers and vendors in ONE step (Rillet cursors expire after 2 h and+ are never resumed), then enqueues `pull-from-accounting` ledger operations in batches+ of `IMPORT_BATCH_SIZE` and drains each batch through the shared `drainSyncOperations`.+ `concurrency: { key: "event.data.companyId", limit: 1 }` — two concurrent imports would+ race on the name-match ladder below.+- **Direction is NOT changed.** `buildRilletSyncConfig` still forces+ `push-to-accounting` / `owner: "carbon"` for both entities, so no sweep, webhook or+ event pulls a contact on its own. The ledger row's own `direction` is what routes the+ drain to `pullBatchFromAccounting` — the same override the inbound webhook path uses.+- **Re-running is safe at two levels.** A linked record is skipped by+ `pullBatchFromAccounting`'s `owner: "carbon"` gate (Rillet never overwrites a+ Carbon-owned record), and an unlinked one resolves through `upsertLocal`'s match ladder:+ mapping row → the Carbon id on the record's own `carbon` external_reference (qualified+ by `carbon-company`, so another Carbon instance's colliding id is refused) → the name,+ which `customer_name_unique`/`supplier_name_unique (name, companyId)` makes a real key.+ A name match onto a supplier/customer already linked to a DIFFERENT Rillet record+ THROWS (named ids, visible in Sync Activity) rather than silently re-pointing the+ mapping.+- `RilletEntitySyncer` is now Rillet plumbing only; the pull rejections moved to+ `RilletPushOnlyEntitySyncer`, which `RilletItemSyncer` and `RilletTransactionSyncer`+ extend. Customer and vendor extend `RilletEntitySyncer` and implement+ `mapToLocal`/`upsertLocal`.+- `fetchRemoteBatch` on both syncers reads ONE cursor-drained list for a multi-id batch+ and keeps the direct GET for a single id — Rillet has no get-many endpoint, so the+ alternative is N GETs. The list is memoized on the **provider** (`listCustomers`/+ `listVendors` in `provider.ts`), and the import builds ONE provider and reuses it for+ the id-listing step and every batch, so the full drain per entity type runs once for+ the whole import instead of once per 50-id batch (the drain builds a fresh syncer per+ batch, so per-syncer memoization alone would rescan). A failed list is not cached, so a+ retried batch can list again. On an Inngest replay the list step is skipped and the+ provider is fresh, so the first re-executing batch re-lists once — bounded, never+ per-batch.+- A Rillet contact email that collides with an existing same-class contact+ (`contact_email_companyId_unique (email, companyId, isCustomer)`, and `contact.email`+ is nullable) is **skipped**, not created/filled — the insert or fill-missing UPDATE+ would throw inside the shared pull transaction and roll back the mapping the import+ exists to write. The contact is secondary; the checked-up-front guard covers both the+ insert and the fill branches.+- **Not imported:** addresses (`address.countryCode` is an FK to `country.alpha2`, and a+ free-text Rillet country would fail the whole row) and payment terms (Carbon's is an FK+ to `paymentTerm`, and the outbound mapper does not read it either). A contact person is+ created only when Rillet carries an email — a Rillet contact has no person name, so+ with no email there is nothing a contact row would say that the customer row does not.diff --git a/apps/erp/app/routes/api+/integrations.rillet.import-contacts.ts b/apps/erp/app/routes/api+/integrations.rillet.import-contacts.tsnew file mode 100644index 0000000000..3848b789a2--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.rillet.import-contacts.ts@@ -0,0 +1,58 @@+import { assertIsPost } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { ProviderID } from "@carbon/ee/accounting";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";++const logger = getLogger("erp", "integrations-rillet-import-contacts");++export const config = {+ runtime: "nodejs"+};++/**+ * POST — start the Rillet contact import (the "Import customers & vendors"+ * action on the integration settings page). Fire-and-forget: the+ * `rillet-import-contacts` job does the work, and its per-record outcome is+ * the ledger, visible in Sync Activity.+ */+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const integration = await client+ .from("companyIntegration")+ .select("active")+ .eq("companyId", companyId)+ .eq("id", ProviderID.RILLET)+ .single();++ if (integration.error || !integration.data?.active) {+ return data(+ { error: "Rillet integration not found or inactive" },+ { status: 400 }+ );+ }++ try {+ await trigger("rillet-import-contacts", {+ companyId,+ entityTypes: { customers: true, vendors: true }+ });++ return data({+ success: true,+ message: "Customer and vendor import started"+ });+ } catch (error) {+ logger.error("Failed to start Rillet contact import", { error });+ return data(+ { error: "Failed to start customer and vendor import" },+ { status: 500 }+ );+ }+}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex f89549cfd1..6a89262b67 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -110049,7 +110049,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},@@ -110098,7 +110098,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string"},diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex e65ad8171b..5d794cb2c9 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -70999,14 +70999,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -76357,21 +76357,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex e65ad8171b..5d794cb2c9 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -70999,14 +70999,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -76357,21 +76357,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex 00057d5e08..3faf79e934 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -39,6 +39,7 @@ pnpm --filter @carbon/ee typecheck # tsgo --noEmit- **Rillet idempotency keys are entity-scoped**: `buildRilletIdempotencyKey({companyId, operation, localId})` — the payload is deliberately NOT hashed, so a crash-retry with a drifted payload cannot double-create the remote document- **Tie-out remote reads**: `accounting/core/remote-journal.ts` `fetchRemoteJournalTotals()` — provider-agnostic debit-signed per-account journal totals for the reconciliation tie-out- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)+- **Rillet contact import**: the `actions` entry in `src/rillet/config.tsx` posts to `/api/integrations/rillet/import-contacts`, which fires `rillet-import-contacts` (`@carbon/jobs`). It is the only on-demand PULL of master data — `buildRilletSyncConfig` still forces customer/vendor `push-to-accounting`, and the job enqueues `pull-from-accounting` ledger rows by hand. `RilletCustomerSyncer`/`RilletVendorSyncer` implement `mapToLocal`/`upsertLocal` for it and extend `RilletEntitySyncer`; the pull rejections now live in `RilletPushOnlyEntitySyncer` (item + every transaction syncer). Importing exists to write the mapping row: `upsertRemote` reads `getRemoteId(localId)` first, so a Carbon sales invoice for an imported customer PUTs the original Rillet customer instead of creating a duplicate- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.diff --git a/packages/ee/src/accounting/providers/rillet/entities/__tests__/contact-import.test.ts b/packages/ee/src/accounting/providers/rillet/entities/__tests__/contact-import.test.tsnew file mode 100644index 0000000000..216dde68d5--- /dev/null+++ b/packages/ee/src/accounting/providers/rillet/entities/__tests__/contact-import.test.ts@@ -0,0 +1,767 @@+import { describe, expect, it, vi } from "vitest";+import type { Rillet } from "../../models";+import { mapRilletCustomerToLocal, RilletCustomerSyncer } from "../customer";+import { readCarbonExternalReference, splitRilletContactName } from "../shared";+import { mapRilletVendorToLocal, RilletVendorSyncer } from "../vendor";++/**+ * The INBOUND half of the Rillet contact syncers — the "Import customers &+ * vendors" action. The outbound mappers live in contact.test.ts.+ */++const COMPANY_ID = "company-1";++const customer = (overrides: Partial<Rillet.Customer> = {}): Rillet.Customer =>+ ({+ id: "ril-cus-1",+ name: "Acme Manufacturing",+ ...overrides+ }) as Rillet.Customer;++const vendor = (overrides: Partial<Rillet.Vendor> = {}): Rillet.Vendor =>+ ({+ id: "ril-ven-1",+ name: "Bolt Supply Co",+ ...overrides+ }) as Rillet.Vendor;++// /********************************************************\+// * Pure mappers *+// \********************************************************/++describe("readCarbonExternalReference", () => {+ it("returns the carbon id when the carbon-company tag names this company", () => {+ expect(+ readCarbonExternalReference(+ [+ { type: "carbon", id: "cus-local" },+ { type: "carbon-company", id: COMPANY_ID }+ ],+ COMPANY_ID+ )+ ).toBe("cus-local");+ });++ it("refuses a carbon id tagged for a DIFFERENT Carbon instance", () => {+ // Several Carbon instances can write into one Rillet organization and+ // entity ids are only unique per database, so an unqualified match could+ // link this company's mapping row to another instance's customer id.+ expect(+ readCarbonExternalReference(+ [+ { type: "carbon", id: "cus-local" },+ { type: "carbon-company", id: "another-company" }+ ],+ COMPANY_ID+ )+ ).toBeNull();+ });++ it("accepts a carbon id with no company tag (written before the tag shipped)", () => {+ expect(+ readCarbonExternalReference(+ [{ type: "carbon", id: "cus-local" }],+ COMPANY_ID+ )+ ).toBe("cus-local");+ });++ it("returns null for no references and for foreign reference types", () => {+ expect(readCarbonExternalReference(undefined, COMPANY_ID)).toBeNull();+ expect(+ readCarbonExternalReference(+ [{ type: "CUSTOMER_CUSTOM", id: "cus-local" }],+ COMPANY_ID+ )+ ).toBeNull();+ });+});++describe("splitRilletContactName", () => {+ it.each([+ ["Jane Doe", { firstName: "Jane", lastName: "Doe" }],+ [+ "Acme Industrial Supply",+ { firstName: "Acme Industrial", lastName: "Supply" }+ ],+ ["Acme", { firstName: "Acme", lastName: "" }],+ [" Jane Doe ", { firstName: "Jane", lastName: "Doe" }]+ ])("splits %j on the last space", (name, expected) => {+ expect(splitRilletContactName(name as string)).toEqual(expected);+ });+});++describe("mapRilletCustomerToLocal", () => {+ it("prefers the MAIN_SENDER email over CC/BCC", () => {+ const local = mapRilletCustomerToLocal(+ customer({+ emails: [+ { email: "[email protected]", type: "CC" },+ { email: "[email protected]", type: "MAIN_SENDER" }+ ]+ }),+ { companyId: COMPANY_ID }+ );++ expect(local.email).toBe("[email protected]");+ });++ it("falls back to the first email when none is MAIN_SENDER", () => {+ const local = mapRilletCustomerToLocal(+ customer({ emails: [{ email: "[email protected]", type: "CC" }] }),+ { companyId: COMPANY_ID }+ );++ expect(local.email).toBe("[email protected]");+ });++ it("carries the claimed Carbon id, the split name and the customer flags", () => {+ const local = mapRilletCustomerToLocal(+ customer({+ external_references: [+ { type: "carbon", id: "cus-local" },+ { type: "carbon-company", id: COMPANY_ID }+ ]+ }),+ { companyId: COMPANY_ID }+ );++ expect(local).toMatchObject({+ id: "cus-local",+ name: "Acme Manufacturing",+ companyId: COMPANY_ID,+ firstName: "Acme",+ lastName: "Manufacturing",+ isCustomer: true,+ isVendor: false+ });+ });++ it("omits id entirely when the record claims no Carbon customer", () => {+ expect(+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID })+ ).not.toHaveProperty("id");+ });+});++describe("mapRilletVendorToLocal", () => {+ it("maps the flat email and tax id onto the supplier shape", () => {+ expect(+ mapRilletVendorToLocal(+ vendor({ email: "[email protected]", tax_id: "12-3456789" }),+ { companyId: COMPANY_ID }+ )+ ).toMatchObject({+ name: "Bolt Supply Co",+ email: "[email protected]",+ taxId: "12-3456789",+ isCustomer: false,+ isVendor: true+ });+ });++ it("nulls the tax id when Rillet has none", () => {+ expect(+ mapRilletVendorToLocal(vendor(), { companyId: COMPANY_ID }).taxId+ ).toBeNull();+ });+});++// /********************************************************\+// * Remote batch fetch strategy *+// \********************************************************/++function setupCustomerSyncer(remote: Rillet.Customer[]) {+ const getCustomer = vi.fn(+ async (id: string) => remote.find((c) => c.id === id) ?? null+ );+ const listCustomers = vi.fn(async () => remote);++ const syncer = new RilletCustomerSyncer({+ database: {} as never,+ companyId: COMPANY_ID,+ provider: { id: "rillet", getCustomer, listCustomers } as never,+ config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },+ entityType: "customer"+ });++ return { syncer, getCustomer, listCustomers };+}++describe("RilletCustomerSyncer.fetchRemoteBatch", () => {+ it("takes the direct GET for a single id", async () => {+ const test = setupCustomerSyncer([customer()]);++ const result = await (test.syncer as any).fetchRemoteBatch(["ril-cus-1"]);++ expect([...result.keys()]).toEqual(["ril-cus-1"]);+ expect(test.getCustomer).toHaveBeenCalledOnce();+ expect(test.listCustomers).not.toHaveBeenCalled();+ });++ it("drains the list ONCE for a batch and reuses it across calls", async () => {+ // Rillet has no get-many endpoint, so N single GETs is the alternative;+ // one cursor drain costs the same no matter how many ids are asked for.+ const test = setupCustomerSyncer([+ customer({ id: "a" }),+ customer({ id: "b" }),+ customer({ id: "c" })+ ]);++ const first = await (test.syncer as any).fetchRemoteBatch(["a", "b"]);+ const second = await (test.syncer as any).fetchRemoteBatch(["b", "c"]);++ expect([...first.keys()]).toEqual(["a", "b"]);+ expect([...second.keys()]).toEqual(["b", "c"]);+ expect(test.listCustomers).toHaveBeenCalledOnce();+ expect(test.getCustomer).not.toHaveBeenCalled();+ });++ it("omits an id the list does not carry rather than inventing a row", async () => {+ const test = setupCustomerSyncer([customer({ id: "a" })]);++ const result = await (test.syncer as any).fetchRemoteBatch(["a", "gone"]);++ expect([...result.keys()]).toEqual(["a"]);+ });+});++describe("RilletVendorSyncer.fetchRemoteBatch", () => {+ it("drains the vendor list once for a batch", async () => {+ const remote = [vendor({ id: "a" }), vendor({ id: "b" })];+ const getVendor = vi.fn(+ async (id: string) => remote.find((v) => v.id === id) ?? null+ );+ const listVendors = vi.fn(async () => remote);++ const syncer = new RilletVendorSyncer({+ database: {} as never,+ companyId: COMPANY_ID,+ provider: { id: "rillet", getVendor, listVendors } as never,+ config: {+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"+ },+ entityType: "vendor"+ });++ expect([+ ...(await (syncer as any).fetchRemoteBatch(["a", "b"])).keys()+ ]).toEqual(["a", "b"]);+ expect(listVendors).toHaveBeenCalledOnce();+ expect(getVendor).not.toHaveBeenCalled();+ });+});++// /********************************************************\+// * The match ladder *+// \********************************************************/++type Rows = Record<string, Array<Record<string, unknown>>>;++/**+ * Minimal chainable stand-in for the Kysely transaction the syncers use:+ * enough of `selectFrom/select/where/executeTakeFirst` and+ * `insertInto/values/returning/executeTakeFirstOrThrow` to exercise the+ * match ladder without a database. `where(col, "=", value)` filters on+ * equality; `where(col, "is", null)` filters on null, matching the guards+ * in the contact updates.+ */+function makeTx(rows: Rows) {+ let nextId = 0;++ const column = (col: string) => col.split(".").pop() as string;++ const select = (table: string) => {+ const clauses: Array<(row: Record<string, unknown>) => boolean> = [];+ const builder: any = {+ select: () => builder,+ where(col: string, op: string, value: unknown) {+ clauses.push((row) =>+ op === "is" ? row[column(col)] == null : row[column(col)] === value+ );+ return builder;+ },+ async executeTakeFirst() {+ return (rows[table] ?? []).find((row) =>+ clauses.every((clause) => clause(row))+ );+ }+ };+ return builder;+ };++ const insert = (table: string) => {+ let inserted: Record<string, unknown> = {};+ const builder: any = {+ values(value: Record<string, unknown>) {+ nextId += 1;+ inserted = { id: `${table}-${nextId}`, ...value };+ (rows[table] ??= []).push(inserted);+ return builder;+ },+ returning: () => builder,+ onConflict: () => builder,+ async execute() {+ return [];+ },+ async executeTakeFirstOrThrow() {+ return inserted;+ }+ };+ return builder;+ };++ const update = (table: string) => {+ const clauses: Array<(row: Record<string, unknown>) => boolean> = [];+ let patch: Record<string, unknown> = {};+ const builder: any = {+ set(value: Record<string, unknown>) {+ patch = value;+ return builder;+ },+ where(col: string, op: string, value: unknown) {+ clauses.push((row) =>+ op === "is" ? row[column(col)] == null : row[column(col)] === value+ );+ return builder;+ },+ async execute() {+ for (const row of rows[table] ?? []) {+ if (clauses.every((clause) => clause(row))) Object.assign(row, patch);+ }+ return [];+ }+ };+ return builder;+ };++ return {+ rows,+ tx: {+ selectFrom: select,+ insertInto: insert,+ updateTable: update+ } as never+ };+}++function customerSyncerFor(+ mappedLocalId: string | null,+ linkedRemoteIdByLocalId: Record<string, string> = {}+) {+ const syncer = new RilletCustomerSyncer({+ database: {} as never,+ companyId: COMPANY_ID,+ provider: { id: "rillet" } as never,+ config: { enabled: true, direction: "push-to-accounting", owner: "carbon" },+ entityType: "customer"+ });+ (syncer as any).getLocalId = async () => mappedLocalId;+ (syncer as any).getRemoteId = async (localId: string) =>+ linkedRemoteIdByLocalId[localId] ?? null;+ return syncer;+}++describe("RilletCustomerSyncer.upsertLocal match ladder", () => {+ it("prefers the existing mapping row over every other candidate", async () => {+ const syncer = customerSyncerFor("cus-mapped");+ const { tx, rows } = makeTx({+ customer: [+ { id: "cus-mapped", name: "Old Name", companyId: COMPANY_ID },+ { id: "cus-by-name", name: "Acme Manufacturing", companyId: COMPANY_ID }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID }),+ "ril-cus-1"+ );++ expect(id).toBe("cus-mapped");+ expect(rows.customer).toHaveLength(2);+ });++ it("links to the Carbon customer named by the record's carbon reference", async () => {+ const syncer = customerSyncerFor(null);+ const { tx, rows } = makeTx({+ customer: [{ id: "cus-local", name: "Acme", companyId: COMPANY_ID }]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(+ customer({+ external_references: [+ { type: "carbon", id: "cus-local" },+ { type: "carbon-company", id: COMPANY_ID }+ ]+ }),+ { companyId: COMPANY_ID }+ ),+ "ril-cus-1"+ );++ // Matched on the reference even though the NAMES disagree.+ expect(id).toBe("cus-local");+ expect(rows.customer).toHaveLength(1);+ });++ it("falls through to the name when the claimed Carbon id is stale", async () => {+ // A deleted customer, or a reference written by another Carbon instance,+ // must not link the mapping row to an id that does not exist.+ const syncer = customerSyncerFor(null);+ const { tx, rows } = makeTx({+ customer: [+ { id: "cus-real", name: "Acme Manufacturing", companyId: COMPANY_ID }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(+ customer({+ external_references: [{ type: "carbon", id: "cus-deleted" }]+ }),+ { companyId: COMPANY_ID }+ ),+ "ril-cus-1"+ );++ expect(id).toBe("cus-real");+ expect(rows.customer).toHaveLength(1);+ });++ it("matches a previously-pushed customer by name instead of inserting a duplicate", async () => {+ // customer_name_unique (name, companyId) would reject the insert, failing+ // the whole record — the name match is what makes a re-import survivable.+ const syncer = customerSyncerFor(null);+ const { tx, rows } = makeTx({+ customer: [+ {+ id: "cus-existing",+ name: "Acme Manufacturing",+ companyId: COMPANY_ID+ }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID }),+ "ril-cus-1"+ );++ expect(id).toBe("cus-existing");+ expect(rows.customer).toHaveLength(1);+ });++ it("ignores a same-named customer belonging to ANOTHER company", async () => {+ const syncer = customerSyncerFor(null);+ const { tx, rows } = makeTx({+ customer: [+ {+ id: "cus-other-tenant",+ name: "Acme Manufacturing",+ companyId: "another-company"+ }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID }),+ "ril-cus-1"+ );++ expect(id).not.toBe("cus-other-tenant");+ expect(rows.customer).toHaveLength(2);+ expect(rows.customer?.[1]).toMatchObject({ companyId: COMPANY_ID });+ });++ it("inserts the customer and its contact when nothing matches", async () => {+ const syncer = customerSyncerFor(null);+ const { tx, rows } = makeTx({ customer: [] });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(+ customer({+ emails: [{ email: "[email protected]", type: "MAIN_SENDER" }]+ }),+ { companyId: COMPANY_ID }+ ),+ "ril-cus-1"+ );++ expect(rows.customer?.[0]).toMatchObject({+ id,+ name: "Acme Manufacturing",+ companyId: COMPANY_ID+ });+ expect(rows.contact?.[0]).toMatchObject({+ email: "[email protected]",+ firstName: "Acme",+ lastName: "Manufacturing",+ isCustomer: true+ });+ expect(rows.customerContact?.[0]).toMatchObject({ customerId: id });+ });++ it("creates no contact at all when Rillet has no email for the customer", async () => {+ const syncer = customerSyncerFor(null);+ const { tx, rows } = makeTx({ customer: [] });++ await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID }),+ "ril-cus-1"+ );++ expect(rows.contact).toBeUndefined();+ expect(rows.customerContact).toBeUndefined();+ });++ it("skips the contact rather than failing the link when the email is already taken", async () => {+ // contact_email_companyId_unique (email, companyId, isCustomer) would make+ // a second contact with this email throw, and upsertLocal runs in the same+ // transaction as linkEntities — so failing here would roll back the mapping+ // the whole import exists to write. The customer must still resolve.+ const syncer = customerSyncerFor(null, { "cus-existing": "ril-cus-1" });+ const { tx, rows } = makeTx({+ customer: [+ {+ id: "cus-existing",+ name: "Acme Manufacturing",+ companyId: COMPANY_ID+ }+ ],+ contact: [+ {+ id: "con-other",+ email: "[email protected]",+ companyId: COMPANY_ID,+ isCustomer: true+ }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(+ customer({+ emails: [{ email: "[email protected]", type: "MAIN_SENDER" }]+ }),+ { companyId: COMPANY_ID }+ ),+ "ril-cus-1"+ );++ expect(id).toBe("cus-existing");+ expect(rows.contact).toHaveLength(1);+ expect(rows.customerContact).toBeUndefined();+ });++ it("does not fill an existing contact's null email when another contact owns it", async () => {+ // The fill-missing UPDATE would violate the same partial unique index and+ // roll back the mapping, so the collision check gates it too.+ const syncer = customerSyncerFor("cus-linked");+ const { tx, rows } = makeTx({+ customer: [+ { id: "cus-linked", name: "Acme Manufacturing", companyId: COMPANY_ID }+ ],+ customerContact: [+ {+ id: "cc-1",+ customerId: "cus-linked",+ contactId: "con-self",+ companyId: COMPANY_ID+ }+ ],+ contact: [+ {+ id: "con-self",+ email: null,+ companyId: COMPANY_ID,+ isCustomer: true+ },+ {+ id: "con-other",+ email: "[email protected]",+ companyId: COMPANY_ID,+ isCustomer: true+ }+ ]+ });++ await (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(+ customer({+ emails: [{ email: "[email protected]", type: "MAIN_SENDER" }]+ }),+ { companyId: COMPANY_ID }+ ),+ "ril-cus-1"+ );++ expect(rows.contact?.find((c) => c.id === "con-self")?.email).toBeNull();+ });++ it("refuses to steal a Carbon customer already linked to another Rillet customer", async () => {+ // Rillet is not known to enforce unique customer names. Re-pointing the+ // mapping would silently unlink the first Rillet customer, and inserting+ // past the match would violate customer_name_unique with a cryptic error.+ const syncer = customerSyncerFor(null, { "cus-taken": "ril-cus-other" });+ const { tx, rows } = makeTx({+ customer: [+ { id: "cus-taken", name: "Acme Manufacturing", companyId: COMPANY_ID }+ ]+ });++ await expect(+ (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID }),+ "ril-cus-1"+ )+ ).rejects.toThrow(/already linked to Rillet customer ril-cus-other/);+ expect(rows.customer).toHaveLength(1);+ });++ it("re-links a name match that already points at THIS Rillet customer", async () => {+ const syncer = customerSyncerFor(null, { "cus-existing": "ril-cus-1" });+ const { tx } = makeTx({+ customer: [+ {+ id: "cus-existing",+ name: "Acme Manufacturing",+ companyId: COMPANY_ID+ }+ ]+ });++ await expect(+ (syncer as any).upsertLocal(+ tx,+ mapRilletCustomerToLocal(customer(), { companyId: COMPANY_ID }),+ "ril-cus-1"+ )+ ).resolves.toBe("cus-existing");+ });++ it("refuses a nameless Rillet customer rather than inserting a blank one", async () => {+ const syncer = customerSyncerFor(null);+ const { tx } = makeTx({ customer: [] });++ await expect(+ (syncer as any).upsertLocal(tx, { companyId: COMPANY_ID }, "ril-cus-1")+ ).rejects.toThrow(/ril-cus-1/);+ });+});++describe("RilletVendorSyncer.upsertLocal", () => {+ function vendorSyncerFor(mappedLocalId: string | null) {+ const syncer = new RilletVendorSyncer({+ database: {} as never,+ companyId: COMPANY_ID,+ provider: { id: "rillet" } as never,+ config: {+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"+ },+ entityType: "vendor"+ });+ (syncer as any).getLocalId = async () => mappedLocalId;+ (syncer as any).getRemoteId = async () => null;+ return syncer;+ }++ it("matches an existing supplier by name and leaves the row alone", async () => {+ const syncer = vendorSyncerFor(null);+ const { tx, rows } = makeTx({+ supplier: [+ { id: "sup-existing", name: "Bolt Supply Co", companyId: COMPANY_ID }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletVendorToLocal(vendor(), { companyId: COMPANY_ID }),+ "ril-ven-1"+ );++ expect(id).toBe("sup-existing");+ expect(rows.supplier).toHaveLength(1);+ });++ it("inserts the supplier, its tax id and its contact when nothing matches", async () => {+ const syncer = vendorSyncerFor(null);+ const { tx, rows } = makeTx({ supplier: [] });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletVendorToLocal(+ vendor({ email: "[email protected]", tax_id: "12-3456789" }),+ { companyId: COMPANY_ID }+ ),+ "ril-ven-1"+ );++ expect(rows.supplier?.[0]).toMatchObject({ id, name: "Bolt Supply Co" });+ expect(rows.supplierTax?.[0]).toMatchObject({+ supplierId: id,+ taxId: "12-3456789"+ });+ expect(rows.contact?.[0]).toMatchObject({+ email: "[email protected]",+ isCustomer: false+ });+ expect(rows.supplierContact?.[0]).toMatchObject({ supplierId: id });+ });++ it("skips the contact rather than failing the link when the email is already taken", async () => {+ const syncer = vendorSyncerFor(null);+ const { tx, rows } = makeTx({+ supplier: [+ { id: "sup-existing", name: "Bolt Supply Co", companyId: COMPANY_ID }+ ],+ contact: [+ {+ id: "con-other",+ email: "[email protected]",+ companyId: COMPANY_ID,+ isCustomer: false+ }+ ]+ });++ const id = await (syncer as any).upsertLocal(+ tx,+ mapRilletVendorToLocal(vendor({ email: "[email protected]" }), {+ companyId: COMPANY_ID+ }),+ "ril-ven-1"+ );++ expect(id).toBe("sup-existing");+ expect(rows.contact).toHaveLength(1);+ expect(rows.supplierContact).toBeUndefined();+ });++ it("writes no supplierTax row when Rillet carries no tax id", async () => {+ const syncer = vendorSyncerFor(null);+ const { tx, rows } = makeTx({ supplier: [] });++ await (syncer as any).upsertLocal(+ tx,+ mapRilletVendorToLocal(vendor(), { companyId: COMPANY_ID }),+ "ril-ven-1"+ );++ expect(rows.supplierTax).toBeUndefined();+ });+});diff --git a/packages/ee/src/accounting/providers/rillet/entities/customer.ts b/packages/ee/src/accounting/providers/rillet/entities/customer.tsindex b6044ccd11..dffb0c2fe8 100644--- a/packages/ee/src/accounting/providers/rillet/entities/customer.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/customer.ts@@ -1,3 +1,4 @@+import type { KyselyTx } from "@carbon/database/client";import type { Accounting } from "../../../core/types";import type { Rillet, RilletCustomerWrite, RilletWriteOmit } from "../models";import { buildRilletIdempotencyKey } from "../provider";@@ -7,20 +8,35 @@ import {mapContactAddressToRilletAddress,mapPaymentTermsToRilletDays,RilletEntitySyncer,+ readCarbonExternalReference,+ splitRilletContactName,writeDroppingUnregisteredReferences} from "./shared";/**- * RilletCustomerSyncer — Carbon customers → Rillet Customer objects.- * PUSH-ONLY in v1 (buildRilletSyncConfig forces direction/owner): pull- * methods come from RilletEntitySyncer's push-only rejections.+ * RilletCustomerSyncer — Carbon customers ↔ Rillet Customer objects.** Rillet keeps customers and vendors as separate objects (like QBO, not* Xero's dual-flag Contact), so this syncer reads the customer tables* only and mapping rows live under entityType "customer". No- * name-matching lookup before create (unlike QBO's smart match) — the- * carbon external_reference plus the create Idempotency-Key are the- * duplicate guards in v1.+ * name-matching lookup before create on the PUSH side (unlike QBO's smart+ * match) — the carbon external_reference plus the create Idempotency-Key+ * are the duplicate guards there.+ *+ * AUTOMATIC sync is push-only: buildRilletSyncConfig forces+ * `push-to-accounting` / `owner: "carbon"`, so no sweep or webhook ever+ * pulls a customer on its own. The PULL half exists for the explicit+ * "Import customers & vendors" action, which enqueues+ * `pull-from-accounting` ledger operations directly+ * (`rillet-import-contacts`). That is also why `owner: "carbon"` matters:+ * `pullBatchFromAccounting` skips an ALREADY-LINKED record, so re-running+ * the import never lets Rillet overwrite a Carbon-owned customer.+ *+ * Linking is the point of the import. Once a mapping row exists,+ * `upsertRemote` below finds it through `getRemoteId` and PUTs the+ * existing Rillet customer — so a sales order raised in Carbon for an+ * imported customer posts against the ORIGINAL Rillet record instead of+ * creating a second one.*/// Row shape for customer queries with address and contact joins (mirrors@@ -81,15 +97,48 @@ export function mapContactToRilletCustomer(};}+/**+ * Map a Rillet Customer onto the Carbon contact shape. Pure — exported for+ * tests.+ *+ * `id` carries the Carbon customer id this Rillet record claims, read off+ * its `carbon` external_reference and qualified by `carbon-company`+ * (`readCarbonExternalReference`). It is a MATCH CANDIDATE, not a+ * guarantee — `upsertLocal` still verifies the row exists in this+ * company before linking to it.+ *+ * The MAIN_SENDER address is Rillet's invoice recipient, so it wins over+ * the CC/BCC entries when a customer carries several.+ */+export function mapRilletCustomerToLocal(+ remote: Rillet.Customer,+ args: { companyId: string }+): Partial<Accounting.Contact> {+ const email =+ remote.emails?.find((entry) => entry.type === "MAIN_SENDER")?.email ??+ remote.emails?.[0]?.email;++ const claimedCarbonId = readCarbonExternalReference(+ remote.external_references,+ args.companyId+ );++ return {+ ...(claimedCarbonId ? { id: claimedCarbonId } : {}),+ name: remote.name,+ companyId: args.companyId,+ ...(email ? { email } : {}),+ ...splitRilletContactName(remote.name),+ isCustomer: true,+ isVendor: false+ };+}+export class RilletCustomerSyncer extends RilletEntitySyncer<Accounting.Contact,Rillet.Customer,RilletWriteOmit> {- protected get pushOnlyEntityLabel(): string {- return "Customers";- }-// =================================================================// 1. LOCAL FETCH (Single + Batch)// =================================================================@@ -217,17 +266,49 @@ export class RilletCustomerSyncer extends RilletEntitySyncer<return this.rilletProvider.getCustomer(id);}+ /**+ * Rillet has no get-many endpoint, so a batch is either N single GETs or+ * ONE cursor-drained `GET /customers`. The import enqueues a claim-sized+ * batch per drain, and a full list costs+ * ceil(customers / RILLET_PAGE_SIZE) requests no matter how many ids are+ * asked for — so anything past a single id reads the list once and+ * indexes it. A lone id (the single-record path) still takes the cheaper+ * direct GET. The list is memoized per syncer INSTANCE, which the drain+ * builds fresh per batch, so the import never reuses a stale snapshot+ * across batches.+ */protected async fetchRemoteBatch(ids: string[]): Promise<Map<string, Rillet.Customer>> {const result = new Map<string, Rillet.Customer>();- for (const id of ids) {- const customer = await this.rilletProvider.getCustomer(id);+ if (ids.length === 0) return result;++ if (ids.length === 1) {+ const customer = await this.rilletProvider.getCustomer(ids[0]!);if (customer) result.set(customer.id, customer);+ return result;+ }++ const byId = await this.listRemoteCustomersById();+ for (const id of ids) {+ const customer = byId.get(id);+ if (customer) result.set(id, customer);}return result;}+ private listedCustomers: Promise<Map<string, Rillet.Customer>> | null = null;++ private listRemoteCustomersById(): Promise<Map<string, Rillet.Customer>> {+ this.listedCustomers ??= this.rilletProvider+ .listCustomers()+ .then(+ (customers) =>+ new Map(customers.map((customer) => [customer.id, customer]))+ );+ return this.listedCustomers;+ }+// =================================================================// 3. TRANSFORMATION (Carbon -> Rillet)// =================================================================@@ -239,7 +320,228 @@ export class RilletCustomerSyncer extends RilletEntitySyncer<}// =================================================================- // 4. UPSERT REMOTE (create with idempotency key, or PUT update)+ // 4. TRANSFORMATION (Rillet -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Rillet.Customer+ ): Promise<Partial<Accounting.Contact>> {+ return mapRilletCustomerToLocal(remote, { companyId: this.companyId });+ }++ // =================================================================+ // 5. UPSERT LOCAL+ // =================================================================++ /**+ * Resolve the Carbon customer this Rillet record belongs to, then link it.+ *+ * Match ladder, most to least authoritative:+ * 1. the mapping row (this Rillet id has been linked before),+ * 2. the Carbon id on the record's own `carbon` external_reference —+ * i.e. Carbon pushed this customer to Rillet in the first place,+ * 3. the name, which `customer_name_unique (name, companyId)` makes a+ * real key. Without this an import of a previously-pushed customer+ * would try to INSERT a duplicate name and fail the whole row.+ *+ * On a match, Carbon stays the system of record — the import's job on an+ * existing record is to LINK it, never to let Rillet overwrite it.+ */+ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ remoteId: string+ ): Promise<string> {+ if (!data.name) {+ throw new Error(+ `Rillet customer ${remoteId} has no name — cannot create a Carbon customer`+ );+ }++ const existingId =+ (await this.getLocalId(remoteId)) ??+ (await this.findCustomerById(tx, data.id)) ??+ (await this.findCustomerByName(tx, data.name, remoteId));++ // A matched customer is updated with NOTHING: Rillet's Customer carries+ // no field Carbon keeps on `customer` beyond the name it was matched on+ // (no phone, fax, website, currency or tax id — see+ // Rillet.CustomerSchema). Linking it is the whole job.+ const customerId = existingId ?? (await this.insertCustomer(tx, data));++ await this.upsertContactAndLink(tx, data, customerId);++ return customerId;+ }++ /**+ * The Carbon id claimed by the record's `carbon` external_reference, kept+ * only when a customer with that id really exists in THIS company — a+ * stale reference (the customer was deleted, or the reference came from+ * another Carbon instance) must fall through to the name match rather+ * than link a mapping row to a missing id.+ */+ private async findCustomerById(+ tx: KyselyTx,+ claimedId: string | undefined+ ): Promise<string | null> {+ if (!claimedId) return null;++ const match = await tx+ .selectFrom("customer")+ .select("id")+ .where("id", "=", claimedId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return match?.id ?? null;+ }++ /**+ * `customer_name_unique (name, companyId)` makes the name a real key, so a+ * name match is a genuine identity claim — and an insert past one would+ * fail on that constraint anyway.+ *+ * Refuse the match when that Carbon customer is already linked to a+ * DIFFERENT Rillet customer. Rillet is not known to enforce unique+ * customer names, and silently re-pointing the mapping would unlink the+ * first Rillet customer without saying so. Failing this one record names+ * both ids in Sync Activity, where the operator can act on it.+ */+ private async findCustomerByName(+ tx: KyselyTx,+ name: string,+ remoteId: string+ ): Promise<string | null> {+ const match = await tx+ .selectFrom("customer")+ .select("id")+ .where("name", "=", name)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!match) return null;++ const linkedRemoteId = await this.getRemoteId(match.id);+ if (linkedRemoteId && linkedRemoteId !== remoteId) {+ throw new Error(+ `Carbon customer "${name}" is already linked to Rillet customer ${linkedRemoteId}; Rillet customer ${remoteId} has the same name and cannot be linked too`+ );+ }++ return match.id;+ }++ private async insertCustomer(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>+ ): Promise<string> {+ // readableId is filled by the customer BEFORE INSERT trigger from the+ // company's `customer` sequence (withTriggersDisabled only sets the+ // app.sync_in_progress flag the EVENT triggers read, so this one runs).+ const inserted = await tx+ .insertInto("customer")+ .values({+ companyId: this.companyId,+ name: data.name!,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ return inserted.id;+ }++ /**+ * A Rillet Customer has emails but no person, so the contact stands in+ * for the company itself: the name is split off the customer name and the+ * MAIN_SENDER email is the one the AR invoices go to. With NO email there+ * is nothing to record that the customer row does not already say, so no+ * contact is created — an empty contact person is noise on a screen, not+ * data.+ *+ * The contact is SECONDARY to the mapping row this whole import exists to+ * write. `contact_email_companyId_unique (email, companyId, isCustomer)`+ * means a second contact with the same email throws, and this runs in the+ * same transaction as `linkEntities` — so a blind insert would roll the+ * mapping back on any email collision (two Rillet customers sharing an+ * address, or an email that already belongs to another Carbon contact).+ * When a same-email contact already exists we therefore skip creating one+ * rather than fail the link; it belongs to another customer (this one has+ * no junction, or the branch above would have caught it), so stealing it+ * would be wrong anyway.+ */+ private async upsertContactAndLink(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ customerId: string+ ): Promise<void> {+ if (!data.email) return;++ // Is this email already held by a DIFFERENT same-class contact? The+ // partial unique index (email, companyId, isCustomer) rejects BOTH the+ // fill-missing UPDATE below (contact.email is nullable) and a fresh+ // INSERT — and this runs in the same transaction as linkEntities, so+ // either rejection rolls back the mapping the import exists to write.+ // Checked up front and honoured in both branches. (concurrency:1 on the+ // job serialises the import, so a pre-check is sufficient here; a+ // concurrent writer racing the same email would need savepoint-scoped+ // conflict handling, which the shared pull transaction does not offer.)+ const emailTaken = await tx+ .selectFrom("contact")+ .select("id")+ .where("email", "=", data.email)+ .where("companyId", "=", this.companyId)+ .where("isCustomer", "=", true)+ .executeTakeFirst();++ const existingJunction = await tx+ .selectFrom("customerContact")+ .select("contactId")+ .where("customerId", "=", customerId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (existingJunction) {+ // Only fill a MISSING email, and only when nothing else owns it.+ if (emailTaken) return;+ await tx+ .updateTable("contact")+ .set({ email: data.email })+ .where("id", "=", existingJunction.contactId)+ .where("companyId", "=", this.companyId)+ .where("email", "is", null)+ .execute();+ return;+ }++ if (emailTaken) return;++ const contact = await tx+ .insertInto("contact")+ .values({+ companyId: this.companyId,+ email: data.email,+ firstName: data.firstName ?? "",+ lastName: data.lastName ?? "",+ isCustomer: true+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ await tx+ .insertInto("customerContact")+ .values({+ companyId: this.companyId,+ customerId,+ contactId: contact.id+ })+ .execute();+ }++ // =================================================================+ // 6. UPSERT REMOTE (create with idempotency key, or PUT update)// =================================================================protected async upsertRemote(diff --git a/packages/ee/src/accounting/providers/rillet/entities/item.ts b/packages/ee/src/accounting/providers/rillet/entities/item.tsindex c9d57e7e1e..0923cd4017 100644--- a/packages/ee/src/accounting/providers/rillet/entities/item.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/item.ts@@ -11,7 +11,7 @@ import {loadCompanyBaseCurrency,loadCurrencyDecimalPlaces,loadRilletAccountCodesById,- RilletEntitySyncer,+ RilletPushOnlyEntitySyncer,toRilletMoney,writeDroppingUnregisteredReferences} from "./shared";@@ -163,7 +163,7 @@ function mergeProductWrite(};}-export class RilletItemSyncer extends RilletEntitySyncer<+export class RilletItemSyncer extends RilletPushOnlyEntitySyncer<Accounting.Item,Rillet.Product,RilletWriteOmitdiff --git a/packages/ee/src/accounting/providers/rillet/entities/shared.ts b/packages/ee/src/accounting/providers/rillet/entities/shared.tsindex ae323c0044..7a2d0406a0 100644--- a/packages/ee/src/accounting/providers/rillet/entities/shared.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/shared.ts@@ -75,6 +75,54 @@ export function carbonCompanyExternalReference(return { type: RILLET_CARBON_COMPANY_REFERENCE_TYPE, id: companyId };}+/**+ * The Carbon entity id a Rillet record was pushed FROM, read back off its+ * `external_references`. Only trusted when the record also carries this+ * company's `carbon-company` reference: several Carbon instances can write+ * into one Rillet organization, and entity ids are only unique within one+ * database, so an unqualified `carbon` reference could name a DIFFERENT+ * instance's customer whose id happens to collide. A reference with no+ * company tag at all is from before that tag shipped and is accepted.+ */+export function readCarbonExternalReference(+ references: Rillet.ExternalReference[] | undefined,+ companyId: string+): string | null {+ if (!references?.length) return null;++ const companyRefs = references.filter(+ (reference) => reference.type === RILLET_CARBON_COMPANY_REFERENCE_TYPE+ );+ if (companyRefs.length > 0 && !companyRefs.some((r) => r.id === companyId)) {+ return null;+ }++ const carbonRef = references.find(+ (reference) => reference.type === RILLET_CARBON_REFERENCE_TYPE+ );+ return carbonRef?.id ?? null;+}++/**+ * Rillet carries one flat contact `name`, Carbon a first/last pair. Split+ * on the LAST space so "Acme Industrial Supply" keeps everything but the+ * final word in `firstName` rather than inventing a middle name; a+ * single-word name leaves `lastName` empty. Both apps render `fullName`+ * (a generated column), so the join is what the user actually sees.+ */+export function splitRilletContactName(name: string): {+ firstName: string;+ lastName: string;+} {+ const trimmed = name.trim().replace(/\s+/g, " ");+ const lastSpace = trimmed.lastIndexOf(" ");+ if (lastSpace === -1) return { firstName: trimmed, lastName: "" };+ return {+ firstName: trimmed.slice(0, lastSpace),+ lastName: trimmed.slice(lastSpace + 1)+ };+}+/*** Rillet's built-in "custom source" external-reference type. When a Rillet org* has Revenue Recognition enabled, rev-rec validation rejects an AR invoice@@ -311,16 +359,19 @@ export async function loadCurrencyDecimalPlaces(export type RilletTimestamped = { updated_at?: string };/**- * Base class for the push-only Rillet master-data syncers (customer,- * vendor, item).+ * Base class for the Rillet master-data syncers (customer, vendor, item).** Reimplements the push workflow with the SAME behavior as* BaseEntitySyncer.pushToAccounting (mapping check, shouldSync gate,* lastSyncedAt fast bailout, map → upsert → link) so that a thrown* JournalEntrySyncError reaches the caller as the structured failure* object on `SyncResult.error` — the base catch flattens every throw to a- * string, which would lose errorCode/warning/metadata. Also centralizes- * the push-only pull rejections (v1 forces push for these entities).+ * string, which would lose errorCode/warning/metadata.+ *+ * The PULL half is inherited from BaseEntitySyncer, so a subclass that+ * implements `mapToLocal` + `upsertLocal` is pullable (customer and vendor,+ * for the Rillet contact import). Subclasses with no inbound mapping extend+ * `RilletPushOnlyEntitySyncer` below instead.*/export abstract class RilletEntitySyncer<TLocal,@@ -331,9 +382,6 @@ export abstract class RilletEntitySyncer<return this.provider as RilletProvider;}- /** Plural label used in push-only rejection messages, e.g. "Customers". */- protected abstract get pushOnlyEntityLabel(): string;-protected getRemoteUpdatedAt(remote: TRemote): Date | null {return parseRilletDate(remote.updated_at);}@@ -494,6 +542,22 @@ export abstract class RilletEntitySyncer<skippedCount: results.filter((r) => r.status === "skipped").length};}+}++/**+ * Base class for the Rillet syncers with no inbound mapping: Rillet is a+ * downstream mirror for them, so a pull is refused rather than silently+ * doing nothing. Splitting this out of `RilletEntitySyncer` is what lets+ * customer and vendor keep the base pull workflow for the contact import+ * while item and every transaction syncer stay push-only.+ */+export abstract class RilletPushOnlyEntitySyncer<+ TLocal,+ TRemote extends RilletTimestamped,+ TOmit extends string | symbol | number+> extends RilletEntitySyncer<TLocal, TRemote, TOmit> {+ /** Plural label used in push-only rejection messages, e.g. "Items". */+ protected abstract get pushOnlyEntityLabel(): string;// =================================================================// PULL WORKFLOW - Not supported (v1 forces push for these entities)@@ -550,7 +614,7 @@ export abstract class RilletTransactionSyncer<TLocal,TRemote extends RilletTimestamped,TOmit extends string | symbol | number-> extends RilletEntitySyncer<TLocal, TRemote, TOmit> {+> extends RilletPushOnlyEntitySyncer<TLocal, TRemote, TOmit> {protected isVoided(_local: TLocal): boolean {return false;}diff --git a/packages/ee/src/accounting/providers/rillet/entities/vendor.ts b/packages/ee/src/accounting/providers/rillet/entities/vendor.tsindex f967f68594..8006063299 100644--- a/packages/ee/src/accounting/providers/rillet/entities/vendor.ts+++ b/packages/ee/src/accounting/providers/rillet/entities/vendor.ts@@ -1,3 +1,4 @@+import type { KyselyTx } from "@carbon/database/client";import type { Accounting } from "../../../core/types";import type { Rillet, RilletVendorWrite, RilletWriteOmit } from "../models";import { buildRilletIdempotencyKey } from "../provider";@@ -7,20 +8,26 @@ import {mapContactAddressToRilletAddress,mapPaymentTermsToRilletDays,RilletEntitySyncer,+ readCarbonExternalReference,+ splitRilletContactName,writeDroppingUnregisteredReferences} from "./shared";/**- * RilletVendorSyncer — Carbon suppliers → Rillet Vendor objects.- * PUSH-ONLY in v1 (buildRilletSyncConfig forces direction/owner): pull- * methods come from RilletEntitySyncer's push-only rejections.+ * RilletVendorSyncer — Carbon suppliers ↔ Rillet Vendor objects.** The vendor half of what Xero handles with one dual-flag ContactSyncer:* Rillet Vendors are a separate object, so this syncer reads the supplier- * tables only, with mapping rows under entityType "vendor". Same- * contract as RilletCustomerSyncer — no name-matching lookup before- * create; the carbon external_reference plus the create Idempotency-Key- * are the duplicate guards in v1.+ * tables only, with mapping rows under entityType "vendor". Same contract+ * as RilletCustomerSyncer on the push side — no name-matching lookup+ * before create; the carbon external_reference plus the create+ * Idempotency-Key are the duplicate guards there.+ *+ * Automatic sync is push-only (buildRilletSyncConfig forces+ * `push-to-accounting` / `owner: "carbon"`); the PULL half exists for the+ * explicit "Import customers & vendors" action, which enqueues+ * `pull-from-accounting` ledger operations directly. See+ * RilletCustomerSyncer for the full rationale — the two are symmetric.*//** Rillet caps vendor payment terms at 180 days. */@@ -85,15 +92,43 @@ export function mapContactToRilletVendor(};}+/**+ * Map a Rillet Vendor onto the Carbon contact shape. Pure — exported for+ * tests.+ *+ * `id` carries the Carbon supplier id this Rillet record claims, read off+ * its `carbon` external_reference and qualified by `carbon-company`; it is+ * a MATCH CANDIDATE that `upsertLocal` still verifies. Vendors carry one+ * flat `email` (unlike the customer `emails[]` list) and a `tax_id`, which+ * is the one Rillet field that lands on a real Carbon column+ * (`supplierTax.taxId`).+ */+export function mapRilletVendorToLocal(+ remote: Rillet.Vendor,+ args: { companyId: string }+): Partial<Accounting.Contact> {+ const claimedCarbonId = readCarbonExternalReference(+ remote.external_references,+ args.companyId+ );++ return {+ ...(claimedCarbonId ? { id: claimedCarbonId } : {}),+ name: remote.name,+ companyId: args.companyId,+ ...(remote.email ? { email: remote.email } : {}),+ ...splitRilletContactName(remote.name),+ taxId: remote.tax_id ?? null,+ isCustomer: false,+ isVendor: true+ };+}+export class RilletVendorSyncer extends RilletEntitySyncer<Accounting.Contact,Rillet.Vendor,RilletWriteOmit> {- protected get pushOnlyEntityLabel(): string {- return "Vendors";- }-// =================================================================// 1. LOCAL FETCH (Single + Batch)// =================================================================@@ -221,17 +256,41 @@ export class RilletVendorSyncer extends RilletEntitySyncer<return this.rilletProvider.getVendor(id);}+ /**+ * One cursor-drained `GET /vendors` beats N single GETs for anything past+ * a single id — see RilletCustomerSyncer.fetchRemoteBatch for the full+ * reasoning. Memoized per syncer instance, which the drain builds fresh+ * per batch.+ */protected async fetchRemoteBatch(ids: string[]): Promise<Map<string, Rillet.Vendor>> {const result = new Map<string, Rillet.Vendor>();- for (const id of ids) {- const vendor = await this.rilletProvider.getVendor(id);+ if (ids.length === 0) return result;++ if (ids.length === 1) {+ const vendor = await this.rilletProvider.getVendor(ids[0]!);if (vendor) result.set(vendor.id, vendor);+ return result;+ }++ const byId = await this.listRemoteVendorsById();+ for (const id of ids) {+ const vendor = byId.get(id);+ if (vendor) result.set(id, vendor);}return result;}+ private listedVendors: Promise<Map<string, Rillet.Vendor>> | null = null;++ private listRemoteVendorsById(): Promise<Map<string, Rillet.Vendor>> {+ this.listedVendors ??= this.rilletProvider+ .listVendors()+ .then((vendors) => new Map(vendors.map((vendor) => [vendor.id, vendor])));+ return this.listedVendors;+ }+// =================================================================// 3. TRANSFORMATION (Carbon -> Rillet)// =================================================================@@ -243,7 +302,232 @@ export class RilletVendorSyncer extends RilletEntitySyncer<}// =================================================================- // 4. UPSERT REMOTE (create with idempotency key, or PUT update)+ // 4. TRANSFORMATION (Rillet -> Carbon)+ // =================================================================++ protected async mapToLocal(+ remote: Rillet.Vendor+ ): Promise<Partial<Accounting.Contact>> {+ return mapRilletVendorToLocal(remote, { companyId: this.companyId });+ }++ // =================================================================+ // 5. UPSERT LOCAL+ // =================================================================++ /**+ * Resolve the Carbon supplier this Rillet vendor belongs to, then link it.+ * Same match ladder as the customer syncer: mapping row → the Carbon id+ * on the record's own `carbon` external_reference → the name, which+ * `supplier_name_unique (name, companyId)` makes a real key.+ *+ * On a match, Carbon stays the system of record: the ONE field that can be+ * written is a tax id Carbon does not have yet.+ */+ protected async upsertLocal(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ remoteId: string+ ): Promise<string> {+ if (!data.name) {+ throw new Error(+ `Rillet vendor ${remoteId} has no name — cannot create a Carbon supplier`+ );+ }++ const existingId =+ (await this.getLocalId(remoteId)) ??+ (await this.findSupplierById(tx, data.id)) ??+ (await this.findSupplierByName(tx, data.name, remoteId));++ const supplierId = existingId ?? (await this.insertSupplier(tx, data));++ await this.fillMissingSupplierTaxId(tx, supplierId, data.taxId ?? null);+ await this.upsertContactAndLink(tx, data, supplierId);++ return supplierId;+ }++ /**+ * The Carbon id claimed by the record's `carbon` external_reference, kept+ * only when a supplier with that id really exists in THIS company — a+ * stale reference must fall through to the name match rather than link a+ * mapping row to a missing id.+ */+ private async findSupplierById(+ tx: KyselyTx,+ claimedId: string | undefined+ ): Promise<string | null> {+ if (!claimedId) return null;++ const match = await tx+ .selectFrom("supplier")+ .select("id")+ .where("id", "=", claimedId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ return match?.id ?? null;+ }++ /**+ * `supplier_name_unique (name, companyId)` makes the name a real key. As+ * with customers, refuse the match when that supplier is already linked to+ * a DIFFERENT Rillet vendor rather than silently re-pointing the mapping.+ */+ private async findSupplierByName(+ tx: KyselyTx,+ name: string,+ remoteId: string+ ): Promise<string | null> {+ const match = await tx+ .selectFrom("supplier")+ .select("id")+ .where("name", "=", name)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (!match) return null;++ const linkedRemoteId = await this.getRemoteId(match.id);+ if (linkedRemoteId && linkedRemoteId !== remoteId) {+ throw new Error(+ `Carbon supplier "${name}" is already linked to Rillet vendor ${linkedRemoteId}; Rillet vendor ${remoteId} has the same name and cannot be linked too`+ );+ }++ return match.id;+ }++ private async insertSupplier(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>+ ): Promise<string> {+ // readableId is filled by the supplier BEFORE INSERT trigger from the+ // company's `supplier` sequence (withTriggersDisabled only sets the+ // app.sync_in_progress flag the EVENT triggers read, so this one runs).+ const inserted = await tx+ .insertInto("supplier")+ .values({+ companyId: this.companyId,+ name: data.name!,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString()+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ return inserted.id;+ }++ /**+ * Write Rillet's tax id onto the supplier only when Carbon has none.+ * `supplierTax` is a 1:1 side table keyed by supplierId, and a supplier+ * Carbon already knows the tax id for is not Rillet's to correct.+ */+ private async fillMissingSupplierTaxId(+ tx: KyselyTx,+ supplierId: string,+ taxId: string | null+ ): Promise<void> {+ if (!taxId) return;++ await tx+ .insertInto("supplierTax")+ .values({+ supplierId,+ taxId,+ companyId: this.companyId,+ updatedAt: new Date().toISOString()+ })+ .onConflict((oc) =>+ oc+ .column("supplierId")+ .doUpdateSet({ taxId, updatedAt: new Date().toISOString() })+ .where("supplierTax.taxId", "is", null)+ )+ .execute();+ }++ /**+ * A Rillet Vendor has an email but no person, so the contact stands in for+ * the vendor itself — name split off the vendor name, email as given.+ * With NO email there is nothing to record that the supplier row does not+ * already say, so no contact is created.+ *+ * The contact is SECONDARY to the mapping row this import exists to write.+ * `contact_email_companyId_unique (email, companyId, isCustomer)` means a+ * second contact with the same email throws, and this runs in the same+ * transaction as `linkEntities` — so a blind insert would roll the mapping+ * back on any email collision. When a same-email contact already exists we+ * skip creating one rather than fail the link (see RilletCustomerSyncer for+ * the full rationale — the two are symmetric).+ */+ private async upsertContactAndLink(+ tx: KyselyTx,+ data: Partial<Accounting.Contact>,+ supplierId: string+ ): Promise<void> {+ if (!data.email) return;++ // See RilletCustomerSyncer.upsertContactAndLink — the partial unique index+ // (email, companyId, isCustomer) rejects both the fill-missing UPDATE and a+ // fresh INSERT on a collision, and that rollback would take the mapping+ // with it. Checked up front, honoured in both branches.+ const emailTaken = await tx+ .selectFrom("contact")+ .select("id")+ .where("email", "=", data.email)+ .where("companyId", "=", this.companyId)+ .where("isCustomer", "=", false)+ .executeTakeFirst();++ const existingJunction = await tx+ .selectFrom("supplierContact")+ .select("contactId")+ .where("supplierId", "=", supplierId)+ .where("companyId", "=", this.companyId)+ .executeTakeFirst();++ if (existingJunction) {+ // Only fill a MISSING email, and only when nothing else owns it.+ if (emailTaken) return;+ await tx+ .updateTable("contact")+ .set({ email: data.email })+ .where("id", "=", existingJunction.contactId)+ .where("companyId", "=", this.companyId)+ .where("email", "is", null)+ .execute();+ return;+ }++ if (emailTaken) return;++ const contact = await tx+ .insertInto("contact")+ .values({+ companyId: this.companyId,+ email: data.email,+ firstName: data.firstName ?? "",+ lastName: data.lastName ?? "",+ isCustomer: false+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ await tx+ .insertInto("supplierContact")+ .values({+ companyId: this.companyId,+ supplierId,+ contactId: contact.id+ })+ .execute();+ }++ // =================================================================+ // 6. UPSERT REMOTE (create with idempotency key, or PUT update)// =================================================================protected async upsertRemote(diff --git a/packages/ee/src/accounting/providers/rillet/provider.ts b/packages/ee/src/accounting/providers/rillet/provider.tsindex 7070ab5ef9..624970ef3b 100644--- a/packages/ee/src/accounting/providers/rillet/provider.ts+++ b/packages/ee/src/accounting/providers/rillet/provider.ts@@ -230,9 +230,18 @@ export function buildRilletIdempotencyKey(args: {// \********************************************************//**- * Entities Rillet syncs in v1 — every one of them PUSH-ONLY (Carbon →- * Rillet). Rillet is the ledger of record for what Carbon pushes; pulling- * master data back is a follow-up.+ * Entities whose AUTOMATIC sync is PUSH-ONLY (Carbon → Rillet). Carbon is+ * the system of record for all of them, so no sweep, webhook or event ever+ * pulls one on its own.+ *+ * `customer` and `vendor` are still pullable ON DEMAND: the "Import+ * customers & vendors" action (`rillet-import-contacts`) enqueues explicit+ * `pull-from-accounting` ledger operations, which the drain routes to the+ * syncer's pull path regardless of this direction — the same override the+ * inbound webhook path uses. `owner: "carbon"` below is what keeps that+ * safe: `BaseEntitySyncer.pullBatchFromAccounting` skips a record that is+ * already linked, so a re-import can seed new Rillet contacts but can never+ * overwrite a Carbon-owned one.*/export const RILLET_PUSH_ONLY_ENTITIES = ["customer",@@ -721,20 +730,40 @@ export class RilletProvider extends BaseProvider {});}- /** All Rillet customers (cursor-drained). Throws on API failure. */+ // Memoized per provider INSTANCE. The contact import lists the full set+ // once (to enqueue ids) and then each drained batch re-reads it through the+ // customer/vendor syncer's fetchRemoteBatch — Rillet has no get-many+ // endpoint, so without this a 10k-record import re-scans /customers once per+ // 50-id batch (~200 full cursor drains). Reusing ONE provider across the+ // whole import collapses that to a single drain per entity type. Not shared+ // across provider instances, so an unrelated caller that wants fresh data+ // constructs its own provider (as every sweep/webhook already does).+ private listedCustomers?: Promise<Rillet.Customer[]>;+ private listedVendors?: Promise<Rillet.Vendor[]>;++ /** All Rillet customers (cursor-drained, memoized). Throws on API failure. */async listCustomers(): Promise<Rillet.Customer[]> {- return this.listPaginated<Rillet.Customer>(+ this.listedCustomers ??= this.listPaginated<Rillet.Customer>("/customers",(data) => data.customers as Rillet.Customer[] | undefined- );+ ).catch((err) => {+ // Don't cache a rejection — a retried batch must be able to list again.+ this.listedCustomers = undefined;+ throw err;+ });+ return this.listedCustomers;}- /** All Rillet vendors (cursor-drained). Throws on API failure. */+ /** All Rillet vendors (cursor-drained, memoized). Throws on API failure. */async listVendors(): Promise<Rillet.Vendor[]> {- return this.listPaginated<Rillet.Vendor>(+ this.listedVendors ??= this.listPaginated<Rillet.Vendor>("/vendors",(data) => data.vendors as Rillet.Vendor[] | undefined- );+ ).catch((err) => {+ this.listedVendors = undefined;+ throw err;+ });+ return this.listedVendors;}// =================================================================diff --git a/packages/ee/src/rillet/config.tsx b/packages/ee/src/rillet/config.tsxindex 43ebcb2415..006c57b671 100644--- a/packages/ee/src/rillet/config.tsx+++ b/packages/ee/src/rillet/config.tsx@@ -87,7 +87,16 @@ export const Rillet = defineIntegration({value: ""}],- schema: RilletSettingsSchema+ schema: RilletSettingsSchema,+ actions: [+ {+ id: "import-contacts",+ label: "Import customers & vendors",+ description:+ "Pull the customers and vendors already in Rillet into Carbon and link them, so documents Carbon posts later reuse the original Rillet records instead of creating duplicates",+ endpoint: "/api/integrations/rillet/import-contacts"+ }+ ]});function SetupInstructions({ companyId }: { companyId: string }) {diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.tsindex f08e3ac5f1..0a8352d40a 100644--- a/packages/jobs/src/inngest/functions/integrations/index.ts+++ b/packages/jobs/src/inngest/functions/integrations/index.ts@@ -8,6 +8,7 @@ export { linearSyncFunction, syncIssueFromLinearSchema } from "./linear";export { onshapeBackfillFunction } from "./onshape-backfill";export { onshapeRevisionSyncFunction } from "./onshape-revision-sync";export { paperlessPartsFunction } from "./paperless-parts";+export { rilletImportContactsFunction } from "./rillet-import-contacts";export {slackDocumentAssignmentUpdateFunction,slackDocumentCreatedFunction,diff --git a/packages/jobs/src/inngest/functions/integrations/rillet-import-contacts.ts b/packages/jobs/src/inngest/functions/integrations/rillet-import-contacts.tsnew file mode 100644index 0000000000..f6b761d5cf--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/rillet-import-contacts.ts@@ -0,0 +1,270 @@+/**+ * Rillet contact import — the "Import customers & vendors" action on the+ * Rillet integration settings page.+ *+ * Rillet's Customers and Vendors are pushed to, never pulled from, by the+ * automatic sync (`buildRilletSyncConfig` forces `push-to-accounting` /+ * `owner: "carbon"` for both). This job is the one place that goes the+ * other way, and only because a person asked it to: it lists the Rillet+ * organization's customers and vendors and enqueues explicit+ * `pull-from-accounting` ledger operations, which `drainSyncOperations`+ * routes to the syncers' pull path — the same direction override the+ * inbound webhook path uses.+ *+ * What the import is FOR is the mapping row. `RilletCustomerSyncer`'s+ * `upsertRemote` resolves `getRemoteId(localId)` before writing, so once a+ * Carbon customer is linked to a Rillet customer, a sales invoice raised in+ * Carbon PUTs that existing Rillet customer instead of creating a second+ * one. Same for vendors and bills.+ *+ * Re-running is safe by construction, at two levels: a record that already+ * carries a mapping is skipped by `pullBatchFromAccounting`'s+ * `owner: "carbon"` gate (Rillet never overwrites a linked Carbon record),+ * and an unlinked Rillet record resolves to an existing Carbon customer+ * through the syncer's match ladder (mapping → `carbon` external_reference+ * → unique name) rather than inserting a duplicate.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import {+ type AccountingEntityType,+ type AccountingProvider,+ getAccountingIntegration,+ getProviderIntegration,+ ProviderID,+ type RilletProvider,+ type SyncContext+} from "@carbon/ee/accounting";+import { getLogger } from "@carbon/logger";+import { chunkArray } from "@carbon/utils";+import { PostgresDriver } from "kysely";+import z from "zod";+import { inngest } from "../../client";+import {+ drainSyncOperations,+ enqueueSyncOperations,+ getSyncOperationActor,+ type SyncOperationRequest+} from "./accounting-sync-operations";++/**+ * Remote ids enqueued and drained per step. Kept at the shared claim limit's+ * order of magnitude so one step is one drain pass, and small enough that a+ * step's work is re-doable if Inngest retries it.+ */+const log = getLogger("jobs", "rillet-import-contacts");++const IMPORT_BATCH_SIZE = 50;++const ImportPayloadSchema = z.object({+ companyId: z.string(),+ entityTypes: z+ .object({+ customers: z.boolean().default(true),+ vendors: z.boolean().default(true)+ })+ .prefault({})+});++export type RilletImportContactsPayload = z.input<typeof ImportPayloadSchema>;++type ImportedCounts = { imported: number; skipped: number; failed: number };++const emptyCounts = (): ImportedCounts => ({+ imported: 0,+ skipped: 0,+ failed: 0+});++export const rilletImportContactsFunction = inngest.createFunction(+ {+ id: "rillet-import-contacts",+ retries: 3,+ // One import per company at a time: two concurrent runs would race on+ // the same name-match ladder and could insert the same customer twice.+ concurrency: { key: "event.data.companyId", limit: 1 }+ },+ { event: "carbon/rillet-import-contacts" },+ async ({ event, step, runId }) => {+ const payload = ImportPayloadSchema.parse(event.data);++ // Scopes the ledger idempotency keys to this run: a retried step+ // re-enqueues onto its own rows, while a fresh import is never blocked+ // by the Completed rows of the last one.+ const importRunId = event.id ?? runId;++ const result = {+ customers: emptyCounts(),+ vendors: emptyCounts()+ };++ // ONE client / integration / provider for the whole import, reused across+ // the id-listing step and every batch. The provider memoizes+ // listCustomers/listVendors, and Rillet has no get-many endpoint, so+ // sharing the instance means the full cursor drain per entity type runs+ // ONCE (in the list step) and every batch's fetchRemoteBatch reads that+ // cached list — instead of re-scanning /customers per 50-id batch. On an+ // Inngest replay the list step is skipped and this provider is fresh, so+ // the first re-executing batch re-lists once; still bounded, never+ // per-batch. (Created outside step.run because provider construction is a+ // cheap local + one companyIntegration read, safe to repeat on replay.)+ const client = getCarbonServiceRole();+ const integration = await getAccountingIntegration(+ client,+ payload.companyId,+ ProviderID.RILLET+ );+ const provider = getProviderIntegration(+ client,+ payload.companyId,+ integration.id,+ integration.metadata+ ) as RilletProvider;+ const database = getPostgresClient(+ getPostgresConnectionPool(5),+ PostgresDriver+ );++ // List both families up front, in ONE step. Rillet cursors expire after+ // 2 hours and are never resumed across runs, so the list is a single pass.+ const listed = await step.run("list-rillet-contacts", async () => {+ const customers = payload.entityTypes.customers+ ? (await provider.listCustomers()).map((customer) => customer.id)+ : [];+ const vendors = payload.entityTypes.vendors+ ? (await provider.listVendors()).map((vendor) => vendor.id)+ : [];++ return { customers, vendors };+ });++ for (const [entityType, remoteIds] of [+ ["customer", listed.customers],+ ["vendor", listed.vendors]+ ] as const) {+ const batches = chunkArray(remoteIds, IMPORT_BATCH_SIZE);++ for (const [index, batch] of batches.entries()) {+ const counts = await step.run(+ `import-${entityType}-batch-${index}`,+ () =>+ importBatch({+ client,+ integration,+ provider,+ database,+ companyId: payload.companyId,+ entityType,+ remoteIds: batch,+ scope: importRunId+ })+ );++ const target = entityType === "customer" ? "customers" : "vendors";+ result[target].imported += counts.imported;+ result[target].skipped += counts.skipped;+ result[target].failed += counts.failed;+ }+ }++ return {+ companyId: payload.companyId,+ listed: {+ customers: listed.customers.length,+ vendors: listed.vendors.length+ },+ ...result+ };+ }+);++/**+ * Enqueue one batch of remote ids as `pull-from-accounting` operations and+ * drain them, using the import's shared client / integration / provider / db+ * (see the function body for why they are shared). A drain failure lands+ * Failed ledger rows (visible and retryable in Sync Activity) rather than+ * throwing, so one unmappable Rillet record cannot abandon the rest of the+ * import — except a RatelimitError, which propagates so Inngest retries the+ * step and the idempotency keys absorb the re-enqueue.+ */+async function importBatch(args: {+ client: ReturnType<typeof getCarbonServiceRole>;+ integration: Awaited<ReturnType<typeof getAccountingIntegration>>;+ provider: AccountingProvider;+ database: SyncContext["database"];+ companyId: string;+ entityType: AccountingEntityType;+ remoteIds: string[];+ scope: string;+}): Promise<ImportedCounts> {+ const {+ client,+ integration,+ provider,+ database,+ companyId,+ entityType,+ remoteIds,+ scope+ } = args;+ const counts = emptyCounts();+ if (remoteIds.length === 0) return counts;++ // enqueueSyncOperations derives the idempotency key from+ // (entityType, entityId, direction, scope) itself.+ const requests: SyncOperationRequest[] = remoteIds.map((remoteId) => ({+ entityType,+ entityId: remoteId,+ direction: "pull-from-accounting"+ }));++ const outcomes = await enqueueSyncOperations(client, {+ companyId,+ integration: ProviderID.RILLET,+ trigger: "backfill",+ createdBy: getSyncOperationActor(integration),+ scope,+ requests+ });++ for (const outcome of outcomes) {+ if (outcome.outcome === "error") {+ counts.failed++;+ log.error("Failed to enqueue a contact import operation", {+ companyId,+ entityType: outcome.entityType,+ entityId: outcome.entityId,+ error: outcome.error+ });+ }+ }++ const drained = await drainSyncOperations({+ client,+ database,+ companyId,+ integration: ProviderID.RILLET,+ provider,+ integrationMetadata: integration.metadata+ });++ // A drain processes every claimable op for the company, not just this+ // batch's. Attributing its result to THIS batch is correct only because+ // `concurrency: { limit: 1 }` + the sequential batch loop mean earlier+ // batches are already Completed (never re-claimed) and later ones are not+ // enqueued yet — so the only pull-from-accounting/`entityType` ops in flight+ // are the ones this batch just enqueued. The filters guard against unrelated+ // push ops the drain also picks up. Revisit if either invariant changes.+ for (const group of drained.groups) {+ if (group.direction !== "pull-from-accounting") continue;+ if (group.entityType !== entityType) continue;+ counts.imported += group.result.successCount;+ counts.skipped += group.result.skippedCount;+ counts.failed += group.result.errorCount;+ }++ return counts;+}diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex 789ebc2606..21aba3d6cb 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -39,6 +39,7 @@ import {onshapeBackfillFunction,onshapeRevisionSyncFunction,paperlessPartsFunction,+ rilletImportContactsFunction,slackDocumentAssignmentUpdateFunction,slackDocumentCreatedFunction,slackDocumentStatusUpdateFunction,@@ -160,6 +161,7 @@ export const functions = [accountingOutboundSweepFunction,accountingReconciliationFunction,accountingPullSweepFunction,+ rilletImportContactsFunction,onshapeBackfillFunction,onshapeRevisionSyncFunction,syncExternalAccountingFunction,diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex 01322fe01b..2b265d8ec2 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -582,6 +582,18 @@ export type Events = {};};+ // Rillet contact import (the integration's "Import customers & vendors"+ // action): pull Rillet Customers and Vendors into Carbon and link them+ "carbon/rillet-import-contacts": {+ data: {+ companyId: string;+ entityTypes?: {+ customers?: boolean;+ vendors?: boolean;+ };+ };+ };+// Onshape released-asset backfill / reconcile"carbon/onshape-backfill": {data: {diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.tsindex 6c54f68179..aacf9edcae 100644--- a/packages/lib/src/trigger.ts+++ b/packages/lib/src/trigger.ts@@ -30,6 +30,7 @@ const taskToEvent = {"print-job-deliver": "carbon/print-job-deliver","print-job": "carbon/print-job",recalculate: "carbon/recalculate",+ "rillet-import-contacts": "carbon/rillet-import-contacts","schedule-inputs-changed": "carbon/schedule.inputs.changed","send-email": "carbon/send-email","send-slack": "carbon/send-slack",