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
fix(ramp): link spend vendors to the seat-holder's accounting vendor (#1779)
Brad Barbin9375d4513f29
diff --git a/.claude/rules/ramp-integration.md b/.claude/rules/ramp-integration.mdindex a1653c3bd5..0b83b3e1c8 100644--- a/.claude/rules/ramp-integration.md+++ b/.claude/rules/ramp-integration.md@@ -800,6 +800,19 @@ keyset helpers and its two metadata cursors are gone.pushed this way reads back with `provider_name: "RILLET"`.`GET /developer/v1/bills/drafts/{id}` DOES exist and returns the stored coding,which is how this was confirmed.+- **The vendor is the seat-holder's too.** A bill's "Accounting Merchant" comes from+ the Ramp vendor's `accounting_vendor_remote_id`, and a vendor Carbon creates or+ matches has none — so in push-only every bill arrived with it empty even though the+ lines were coded. `decideRampSpendVendor` (`lib/spend.ts`, pure, tested) reads the+ seat-holder's vendor mapping (`rillet` / `vendor`) and: adopts the Ramp vendor that+ accounting vendor is ALREADY linked to (Ramp allows one); else links the mapped /+ matched / newly created vendor with `PATCH /vendors/{id}`. The link is a separate,+ best-effort call — never in the create body — so a refused link cannot fail the bill.+ A vendor a human linked to a DIFFERENT accounting vendor is left alone. The link is+ recorded on the `ramp` vendor mapping's `metadata.accountingVendorRemoteId`, so a+ linked supplier costs no Ramp call afterwards. <!-- UNVERIFIED: not yet live-tested+ that Ramp's accounting-vendor remote id equals the Rillet vendor id Carbon stores+ (the account ids do match — see above). -->- **A delegated family's OWNER keeps its own entities.** `applyLedgerDelegation`takes the `integrationId` whose config is being resolved; without it, resolvingRamp's config disabled Ramp's `bill` entity (Ramp owns `ap` in push-only), so thediff --git a/packages/ee/src/ramp/entities/bill.ts b/packages/ee/src/ramp/entities/bill.tsindex 70932cb12a..73b8adf8dc 100644--- a/packages/ee/src/ramp/entities/bill.ts+++ b/packages/ee/src/ramp/entities/bill.ts@@ -35,7 +35,10 @@ import { isPushableInvoiceStatus } from "../../spend/gates";import { describeMissingVendorFields } from "../../spend/parties";import { buildRampIdempotencyKey } from "../lib/client";import { buildLineCodingSelections } from "../lib/coding";-import { resolveOrCreateRampSpendVendor } from "../lib/spend";+import {+ prepareRampVendorResolution,+ resolveOrCreateRampSpendVendor+} from "../lib/spend";import { RampPushOnlyEntitySyncer } from "./shared";export type RampBillRemote = {@@ -146,6 +149,21 @@ export class RampBillSyncer extends RampPushOnlyEntitySyncer<}protected async mapToRemote(local: SpendBillSource): Promise<RampBillRemote> {+ /**+ * Whose identifiers Ramp's coding options — and its accounting vendors —+ * are keyed by.+ *+ * When another system holds Ramp's accounting seat it published the+ * options, so the mappings to read are ITS (`rillet`'s account → its+ * external id), and the external id is what Ramp knows the option by.+ * Reading Ramp's own mappings there finds nothing — Carbon never pushed a+ * chart of accounts in that mode — so every line degraded to uncoded and the+ * bill landed needing manual coding before the seat-holder could post it.+ * The same system owns the accounting vendor the bill posts against, so the+ * Ramp vendor is linked to ITS vendor id too.+ */+ const delegatedTo = this.rampProvider.codingIdentityIntegrationId;+// A bill REQUIRES a vendor_id, unlike a PO where it is optional — so Ramp's// own rejection is the only actionable diagnosis and must not be swallowed.const vendorId = await resolveOrCreateRampSpendVendor(@@ -153,7 +171,12 @@ export class RampBillSyncer extends RampPushOnlyEntitySyncer<this.ramp,local.supplier,this.companyId,- undefined,+ await prepareRampVendorResolution(+ this.mappingService,+ this.ramp,+ [local.supplier],+ { accountingIntegration: delegatedTo }+ ),{ surfaceCreateError: true });if (!vendorId) {@@ -166,17 +189,6 @@ export class RampBillSyncer extends RampPushOnlyEntitySyncer<);}- /**- * Whose coding options these lines address.- *- * When another system holds Ramp's accounting seat it published the options,- * so the mappings to read are ITS (`rillet`'s account → its external id), and- * the external id is what Ramp knows the option by. Reading Ramp's own- * mappings there finds nothing — Carbon never pushed a chart of accounts in- * that mode — so every line degraded to uncoded and the bill landed needing- * manual coding before the seat-holder could post it.- */- const delegatedTo = this.rampProvider.codingIdentityIntegrationId;const pushed = await loadPushedCoding(this.mappingService,delegatedTo ?? "ramp",diff --git a/packages/ee/src/ramp/entities/purchase-order.ts b/packages/ee/src/ramp/entities/purchase-order.tsindex b6aab00ff2..6aa7afe301 100644--- a/packages/ee/src/ramp/entities/purchase-order.ts+++ b/packages/ee/src/ramp/entities/purchase-order.ts@@ -27,6 +27,7 @@ import {import { buildRampIdempotencyKey, RampApiError } from "../lib/client";import {prepareRampPurchaseOrderBatch,+ prepareRampVendorResolution,type RampPurchaseOrderBatch,resolveOrCreateRampSpendVendor} from "../lib/spend";@@ -131,7 +132,12 @@ export class RampPurchaseOrderSyncer extends RampPushOnlyEntitySyncer<[...orders.keys()],[...orders.values()].filter((order) => !isSettledPurchaseOrderStatus(order.status))- .map((order) => order.supplier)+ .map((order) => order.supplier),+ // When another system holds Ramp's accounting seat, link each vendor to+ // that system's accounting vendor — see `linkAccountingVendor`.+ {+ accountingIntegration: this.rampProvider.codingIdentityIntegrationId+ });return orders;@@ -177,7 +183,16 @@ export class RampPurchaseOrderSyncer extends RampPushOnlyEntitySyncer<this.ramp,local.supplier,this.companyId,- this.batch+ this.batch ??+ (await prepareRampVendorResolution(+ this.mappingService,+ this.ramp,+ [local.supplier],+ {+ accountingIntegration:+ this.rampProvider.codingIdentityIntegrationId+ }+ )))) ?? undefined);return {diff --git a/packages/ee/src/ramp/lib/__tests__/spend.test.ts b/packages/ee/src/ramp/lib/__tests__/spend.test.tsnew file mode 100644index 0000000000..479b40c124--- /dev/null+++ b/packages/ee/src/ramp/lib/__tests__/spend.test.ts@@ -0,0 +1,202 @@+import { describe, expect, it } from "vitest";+import type { RampVendor } from "../models";+import { buildRampVendorResolution, decideRampSpendVendor } from "../spend";++/**+ * The bug: in push-only mode Rillet holds Ramp's accounting seat, and Carbon+ * pushed each bill against a Ramp vendor it matched or created — a bill-pay+ * vendor with NO accounting vendor. Ramp showed the bill's "Accounting+ * Merchant" empty, so someone had to pick the Rillet vendor by hand before+ * Rillet could post it. The lines were already coded with Rillet's account+ * ids; the vendor was the half Carbon never addressed by Rillet's id.+ *+ * These pin the DECISION; performing it (the PATCH, the mapping write) is glue.+ */++const supplier = { id: "sup_amazon", name: "Amazon" };+const RILLET_VENDOR = "019f-rillet-amazon";++const rilletMapping = { entityId: "sup_amazon", externalId: RILLET_VENDOR };+const rampMapping = (+ externalId: string,+ metadata: Record<string, unknown> | null = null+) => ({ entityId: "sup_amazon", externalId, metadata });++function decide(args: {+ vendorMappings?: ReturnType<typeof rampMapping>[];+ delegated?: boolean;+ vendors?: RampVendor[];+}) {+ return decideRampSpendVendor(+ buildRampVendorResolution({+ vendorMappings: args.vendorMappings ?? [],+ accountingVendorMappings: args.delegated ? [rilletMapping] : [],+ vendors: args.vendors+ }),+ supplier+ );+}++describe("decideRampSpendVendor — Carbon holds the seat", () => {+ it("uses a mapped vendor as-is", () => {+ expect(decide({ vendorMappings: [rampMapping("rv_1")] })).toEqual({+ action: "use",+ vendorId: "rv_1"+ });+ });++ it("matches by name without linking — Carbon publishes no accounting vendors", () => {+ expect(decide({ vendors: [{ id: "rv_1", name: "Amazon" }] })).toEqual({+ action: "match",+ vendorId: "rv_1"+ });+ });+});++describe("decideRampSpendVendor — another system holds the seat", () => {+ it("links a vendor Carbon mapped before linking existed", () => {+ // Every install that pushed a bill before this change has a mapping with no+ // link. The first push after it must repair the vendor, not skip it.+ expect(+ decide({+ delegated: true,+ vendorMappings: [rampMapping("rv_1")],+ vendors: [{ id: "rv_1", name: "Amazon" }]+ })+ ).toEqual({ action: "match", vendorId: "rv_1", linkTo: RILLET_VENDOR });+ });++ it("uses the mapping alone once the link is recorded", () => {+ expect(+ decide({+ delegated: true,+ vendorMappings: [+ rampMapping("rv_1", { accountingVendorRemoteId: RILLET_VENDOR })+ ]+ })+ ).toEqual({ action: "use", vendorId: "rv_1" });+ });++ it("re-links when the seat-holder's vendor changed since the link was recorded", () => {+ expect(+ decide({+ delegated: true,+ vendorMappings: [+ rampMapping("rv_1", { accountingVendorRemoteId: "019f-old" })+ ],+ vendors: [{ id: "rv_1", name: "Amazon" }]+ })+ ).toEqual({ action: "match", vendorId: "rv_1", linkTo: RILLET_VENDOR });+ });++ it("adopts the Ramp vendor the accounting vendor is already linked to", () => {+ // Ramp allows an accounting vendor ONE linked vendor — typically one Ramp+ // made from the seat-holder's own vendor sync. That is where this+ // supplier's bills belong, even over a vendor Carbon mapped or created, and+ // linking Carbon's instead would be refused as a second link.+ expect(+ decide({+ delegated: true,+ vendorMappings: [rampMapping("rv_carbon")],+ vendors: [+ { id: "rv_carbon", name: "Amazon" },+ {+ id: "rv_from_rillet",+ name: "Amazon.com",+ accounting_vendor_remote_id: RILLET_VENDOR+ }+ ]+ })+ ).toEqual({+ action: "match",+ vendorId: "rv_from_rillet",+ linkedTo: RILLET_VENDOR+ });+ });++ it("links a vendor matched by name", () => {+ expect(+ decide({ delegated: true, vendors: [{ id: "rv_1", name: "amazon " }] })+ ).toEqual({ action: "match", vendorId: "rv_1", linkTo: RILLET_VENDOR });+ });++ it("records an existing link without re-sending it", () => {+ expect(+ decide({+ delegated: true,+ vendorMappings: [rampMapping("rv_1")],+ vendors: [+ {+ id: "rv_1",+ name: "Amazon",+ accounting_vendor_remote_id: RILLET_VENDOR+ }+ ]+ })+ ).toEqual({ action: "match", vendorId: "rv_1", linkedTo: RILLET_VENDOR });+ });++ it("leaves a vendor a human linked to a DIFFERENT accounting vendor", () => {+ expect(+ decide({+ delegated: true,+ vendorMappings: [rampMapping("rv_1")],+ vendors: [+ {+ id: "rv_1",+ name: "Amazon",+ accounting_vendor_remote_id: "019f-rillet-aws"+ }+ ]+ })+ ).toEqual({+ action: "match",+ vendorId: "rv_1",+ conflict: "019f-rillet-aws"+ });+ });++ it("creates and then links when no Ramp vendor matches", () => {+ expect(decide({ delegated: true, vendors: [] })).toEqual({+ action: "create",+ linkTo: RILLET_VENDOR+ });+ });++ it("creates rather than guessing between two same-named vendors", () => {+ expect(+ decide({+ delegated: true,+ vendors: [+ { id: "rv_1", name: "Amazon" },+ { id: "rv_2", name: "AMAZON" }+ ]+ })+ ).toEqual({ action: "create", linkTo: RILLET_VENDOR });+ });++ it("behaves as before for a supplier the seat-holder does not have yet", () => {+ expect(+ decideRampSpendVendor(+ buildRampVendorResolution({+ vendorMappings: [rampMapping("rv_1")],+ accountingVendorMappings: []+ }),+ supplier+ )+ ).toEqual({ action: "use", vendorId: "rv_1" });+ });++ it("keeps a mapped vendor when the vendor list could not be read", () => {+ const resolution = buildRampVendorResolution({+ vendorMappings: [rampMapping("rv_1")],+ accountingVendorMappings: [rilletMapping]+ });+ resolution.vendorLookup = { ok: false, error: new Error("503") };++ expect(decideRampSpendVendor(resolution, supplier)).toEqual({+ action: "use",+ vendorId: "rv_1"+ });+ });+});diff --git a/packages/ee/src/ramp/lib/client.ts b/packages/ee/src/ramp/lib/client.tsindex 7bba99e94a..2c9acc9fa2 100644--- a/packages/ee/src/ramp/lib/client.ts+++ b/packages/ee/src/ramp/lib/client.ts@@ -581,6 +581,17 @@ export class RampClient {});}+ /**+ * Update a Ramp SPEND vendor (`PATCH /developer/v1/vendors/{id}`). Carbon uses+ * it for one field: `accounting_vendor_remote_id`, the link to the accounting+ * vendor the seat-holder published — Ramp's documented way to join a bill-pay+ * vendor to its GL vendor ("Creating a bill-pay vendor does not auto-create an+ * accounting vendor. Link them explicitly via PATCH /vendors/{id}").+ */+ updateSpendVendor<T = unknown>(id: string, body: unknown): Promise<T> {+ return this.request<T>("PATCH", `/developer/v1/vendors/${id}`, { body });+ }+// ---- Business entities (for the required PO `entity_id`) ----getEntities<T = unknown>(): Promise<T> {diff --git a/packages/ee/src/ramp/lib/service.ts b/packages/ee/src/ramp/lib/service.tsindex 9bbc8ecaa6..ee37afbfda 100644--- a/packages/ee/src/ramp/lib/service.ts+++ b/packages/ee/src/ramp/lib/service.ts@@ -44,9 +44,14 @@ export {projectFingerprint,pushProjects} from "./projects";-export type { RampPurchaseOrderBatch, RampVendorSupplier } from "./spend";+export type {+ RampPurchaseOrderBatch,+ RampVendorResolution,+ RampVendorSupplier+} from "./spend";export {prepareRampPurchaseOrderBatch,+ prepareRampVendorResolution,resolveOrCreateRampSpendVendor} from "./spend";export {diff --git a/packages/ee/src/ramp/lib/spend.ts b/packages/ee/src/ramp/lib/spend.tsindex a6e8f1cab7..139a648ab9 100644--- a/packages/ee/src/ramp/lib/spend.ts+++ b/packages/ee/src/ramp/lib/spend.ts@@ -15,135 +15,375 @@ import type { RampVendor } from "./models";*/export type RampVendorSupplier = SpendVendorParty;-export type RampPurchaseOrderBatch = {- purchaseOrderIds: Map<string, string>;+/**+ * Where the Ramp vendor mapping keeps the accounting vendor Carbon last linked+ * that Ramp vendor to. Recorded so a linked supplier resolves from the mapping+ * alone, with no Ramp call, on every push after the first.+ */+const LINKED_ACCOUNTING_VENDOR_KEY = "accountingVendorRemoteId";++/**+ * Everything one push needs to resolve its suppliers' Ramp spend vendors,+ * loaded up front so a page of documents costs a fixed number of reads.+ */+export type RampVendorResolution = {+ /** supplier id → Ramp spend vendor id, from Carbon's `ramp` vendor mappings. */vendorIds: Map<string, string>;+ /**+ * supplier id → the accounting vendor Carbon last linked that Ramp vendor to+ * (the mapping's metadata). Compared against `accountingVendorIds` to decide+ * whether a mapped vendor still needs linking.+ */+ linkedAccountingVendorIds: Map<string, string>;+ /**+ * supplier id → the SEAT-HOLDER's vendor id for it (e.g. the Rillet vendor+ * Carbon pushed). Empty when Carbon holds Ramp's accounting seat — Carbon+ * publishes no accounting vendors, so there is nothing to link to.+ */+ accountingVendorIds: Map<string, string>;+ vendorsById: Map<string, RampVendor>;vendorsByExternalId: Map<string, RampVendor>;vendorsByName: Map<string, RampVendor | null>;+ vendorsByAccountingVendorId: Map<string, RampVendor>;vendorLookup: { ok: true } | { ok: false; error: unknown };};-function indexSpendVendor(batch: RampPurchaseOrderBatch, vendor: RampVendor) {+export type RampPurchaseOrderBatch = RampVendorResolution & {+ purchaseOrderIds: Map<string, string>;+};++function indexSpendVendor(+ resolution: RampVendorResolution,+ vendor: RampVendor+) {+ resolution.vendorsById.set(vendor.id, vendor);if (typeof vendor.external_vendor_id === "string" &&- !batch.vendorsByExternalId.has(vendor.external_vendor_id)+ !resolution.vendorsByExternalId.has(vendor.external_vendor_id)) {- batch.vendorsByExternalId.set(vendor.external_vendor_id, vendor);+ resolution.vendorsByExternalId.set(vendor.external_vendor_id, vendor);+ }+ // Ramp allows an accounting vendor to be linked to ONE Ramp vendor, so this+ // key is unique by construction.+ if (vendor.accounting_vendor_remote_id) {+ resolution.vendorsByAccountingVendorId.set(+ vendor.accounting_vendor_remote_id,+ vendor+ );}const name = (vendor.name ?? "").trim().toLowerCase();if (name)- batch.vendorsByName.set(+ resolution.vendorsByName.set(name,- batch.vendorsByName.has(name) ? null : vendor+ resolution.vendorsByName.has(name) ? null : vendor);}-/** One mapping read per entity kind and one paginated provider snapshot per PO page. */-export async function prepareRampPurchaseOrderBatch(- mapping: ExternalIntegrationMappingService,- client: RampClient,- purchaseOrderIds: string[],- suppliers: RampVendorSupplier[]-): Promise<RampPurchaseOrderBatch> {- const uniqueSuppliers = [- ...new Map(suppliers.map((supplier) => [supplier.id, supplier])).values()- ];- const [poMappings, vendorMappings] = await Promise.all([- mapping.getByEntities("purchaseOrder", purchaseOrderIds, RAMP),- mapping.getByEntities(- "vendor",- uniqueSuppliers.map((supplier) => supplier.id),- RAMP- )- ]);- const batch: RampPurchaseOrderBatch = {- purchaseOrderIds: new Map(- [...poMappings].map(([id, row]) => [id, row.externalId])- ),+function linkedAccountingVendorId(+ metadata: Record<string, unknown> | null | undefined+): string | undefined {+ const value = metadata?.[LINKED_ACCOUNTING_VENDOR_KEY];+ return typeof value === "string" && value ? value : undefined;+}++type VendorMappingRow = {+ entityId: string;+ externalId: string | null;+ metadata?: Record<string, unknown> | null;+};++/**+ * The resolution state from already-loaded rows. Pure —+ * `prepareRampVendorResolution` is this plus the reads.+ */+export function buildRampVendorResolution(args: {+ /** Carbon's `ramp` vendor mappings. */+ vendorMappings: VendorMappingRow[];+ /** The seat-holder's vendor mappings; empty when Carbon holds the seat. */+ accountingVendorMappings?: VendorMappingRow[];+ /** The Ramp vendor snapshot, when one was read. */+ vendors?: RampVendor[];+}): RampVendorResolution {+ const resolution: RampVendorResolution = {vendorIds: new Map(- [...vendorMappings].map(([id, row]) => [id, row.externalId])+ args.vendorMappings.flatMap((row) =>+ row.externalId ? [[row.entityId, row.externalId] as const] : []+ )+ ),+ linkedAccountingVendorIds: new Map(+ args.vendorMappings.flatMap((row) => {+ const linked = linkedAccountingVendorId(row.metadata);+ return linked ? [[row.entityId, linked] as const] : [];+ })+ ),+ accountingVendorIds: new Map(+ (args.accountingVendorMappings ?? []).flatMap((row) =>+ row.externalId ? [[row.entityId, row.externalId] as const] : []+ )),+ vendorsById: new Map(),vendorsByExternalId: new Map(),vendorsByName: new Map(),+ vendorsByAccountingVendorId: new Map(),vendorLookup: { ok: true }};- if (- uniqueSuppliers.some(- (supplier) => !batch.vendorIds.has(supplier.id) && supplier.name?.trim()- )- ) {+ for (const vendor of args.vendors ?? []) indexSpendVendor(resolution, vendor);+ return resolution;+}++/**+ * One mapping read per integration and, only when some supplier still needs+ * resolving or linking, one paginated Ramp vendor snapshot.+ *+ * `accountingIntegration` is the integration that holds Ramp's accounting seat+ * when it is not Carbon (`RampProvider.codingIdentityIntegrationId`). Its+ * vendor mappings name the accounting vendor each supplier's Ramp vendor must+ * be linked to.+ */+export async function prepareRampVendorResolution(+ mapping: ExternalIntegrationMappingService,+ client: RampClient,+ suppliers: RampVendorSupplier[],+ options: { accountingIntegration?: string } = {}+): Promise<RampVendorResolution> {+ const uniqueSuppliers = [+ ...new Map(suppliers.map((supplier) => [supplier.id, supplier])).values()+ ];+ const supplierIds = uniqueSuppliers.map((supplier) => supplier.id);+ const [vendorMappings, accountingVendorMappings] = await Promise.all([+ mapping.getByEntities("vendor", supplierIds, RAMP),+ options.accountingIntegration+ ? mapping.getByEntities(+ "vendor",+ supplierIds,+ options.accountingIntegration+ )+ : Promise.resolve(new Map())+ ]);++ const resolution = buildRampVendorResolution({+ vendorMappings: [...vendorMappings.values()],+ accountingVendorMappings: [...accountingVendorMappings.values()]+ });++ if (uniqueSuppliers.some((supplier) => needsLookup(resolution, supplier))) {try {for await (const page of client.listVendors()) {- for (const vendor of page) indexSpendVendor(batch, vendor);+ for (const vendor of page) indexSpendVendor(resolution, vendor);}} catch (error) {- // Mapped vendors and archive-only orders can still proceed. Only a PO- // needing this provider lookup inherits the error and holds the cursor.- batch.vendorLookup = { ok: false, error };+ // Mapped vendors and archive-only orders can still proceed. Only a+ // supplier needing this provider lookup inherits the error.+ resolution.vendorLookup = { ok: false, error };}}- return batch;+ return resolution;}-/** First Ramp spend vendor matching a filter (`external_vendor_id` or `name`), or null. */-async function findRampSpendVendor(+/** One mapping read per entity kind and one paginated provider snapshot per PO page. */+export async function prepareRampPurchaseOrderBatch(+ mapping: ExternalIntegrationMappingService,client: RampClient,- params: { external_vendor_id?: string; name?: string }-): Promise<RampVendor | null> {- for await (const page of client.listVendors(params)) {- if (page.length > 0) return page[0] ?? null;+ purchaseOrderIds: string[],+ suppliers: RampVendorSupplier[],+ options: { accountingIntegration?: string } = {}+): Promise<RampPurchaseOrderBatch> {+ const [poMappings, resolution] = await Promise.all([+ mapping.getByEntities("purchaseOrder", purchaseOrderIds, RAMP),+ prepareRampVendorResolution(mapping, client, suppliers, options)+ ]);+ return {+ ...resolution,+ purchaseOrderIds: new Map(+ [...poMappings].map(([id, row]) => [id, row.externalId])+ )+ };+}++/** Whether resolving this supplier needs the Ramp vendor snapshot. */+function needsLookup(+ resolution: RampVendorResolution,+ supplier: Pick<RampVendorSupplier, "id" | "name">+): boolean {+ const mapped = resolution.vendorIds.get(supplier.id);+ if (!mapped) return Boolean(supplier.name?.trim());+ const accountingVendorId = resolution.accountingVendorIds.get(supplier.id);+ return (+ accountingVendorId !== undefined &&+ resolution.linkedAccountingVendorIds.get(supplier.id) !== accountingVendorId+ );+}++/**+ * What resolving one supplier's Ramp spend vendor must DO — pure, so the+ * choice is tested with real values and the executor only performs it.+ *+ * - `use` — the mapped vendor, already linked (or nothing to link): no writes.+ * - `match` — record the mapping to `vendorId`; when `linkTo` is set, link the+ * vendor to that accounting vendor first. `linkedTo` is a link that already+ * exists in Ramp; `conflict` is one a human made to a DIFFERENT accounting+ * vendor, which is left alone.+ * - `create` — no vendor to use; create one, then link it when `linkTo` is set.+ * - `none` — nothing to match and no name to create with.+ * - `fail` — the vendor snapshot could not be read and there is no mapping.+ */+export type RampSpendVendorDecision =+ | { action: "use"; vendorId: string }+ | {+ action: "match";+ vendorId: string;+ linkTo?: string;+ linkedTo?: string;+ conflict?: string;+ }+ | { action: "create"; linkTo?: string }+ | { action: "none" }+ | { action: "fail"; error: unknown };++/**+ * The resolution ladder for one supplier:+ *+ * 1. an existing `("vendor", supplier.id, "ramp")` mapping — used as-is unless+ * it still needs linking to the seat-holder's accounting vendor,+ * 2. the Ramp vendor the seat-holder's accounting vendor is ALREADY linked to+ * (Ramp allows one, so it is the vendor this supplier's bills belong on —+ * typically one Ramp created from the accounting provider's own sync),+ * 3. a Ramp vendor already carrying our `external_vendor_id`,+ * 4. a Ramp vendor whose name matches exactly (case-insensitive) and uniquely+ * — a shared name is not an identity key, so an ambiguous one creates,+ * 5. otherwise create.+ */+export function decideRampSpendVendor(+ resolution: RampVendorResolution,+ supplier: Pick<RampVendorSupplier, "id" | "name">+): RampSpendVendorDecision {+ const mapped = resolution.vendorIds.get(supplier.id);+ const accountingVendorId = resolution.accountingVendorIds.get(supplier.id);+ if (mapped && !needsLookup(resolution, supplier)) {+ return { action: "use", vendorId: mapped };}- return null;++ const name = (supplier.name ?? "").trim();+ if (!mapped && !name) return { action: "none" };+ if (!resolution.vendorLookup.ok) {+ // A mapped vendor is still a valid `vendor_id`; the link is retried on the+ // next push rather than holding this one on a failed list read.+ return mapped+ ? { action: "use", vendorId: mapped }+ : { action: "fail", error: resolution.vendorLookup.error };+ }++ const alreadyLinked = accountingVendorId+ ? resolution.vendorsByAccountingVendorId.get(accountingVendorId)+ : undefined;+ if (alreadyLinked) {+ return {+ action: "match",+ vendorId: alreadyLinked.id,+ linkedTo: accountingVendorId+ };+ }++ const matched: Pick<RampVendor, "id" | "accounting_vendor_remote_id"> | null =+ mapped+ ? (resolution.vendorsById.get(mapped) ?? { id: mapped })+ : (resolution.vendorsByExternalId.get(supplier.id) ??+ resolution.vendorsByName.get(name.toLowerCase()) ??+ null);+ if (!matched) return { action: "create", linkTo: accountingVendorId };+ if (!accountingVendorId) return { action: "match", vendorId: matched.id };++ const current = matched.accounting_vendor_remote_id;+ if (current === accountingVendorId) {+ return { action: "match", vendorId: matched.id, linkedTo: current };+ }+ if (current) {+ // Someone linked this vendor to a DIFFERENT GL vendor on purpose. Carbon's+ // mapping is weaker evidence than a human's choice, so leave it alone+ // rather than silently re-pointing their bills.+ return { action: "match", vendorId: matched.id, conflict: current };+ }+ return { action: "match", vendorId: matched.id, linkTo: accountingVendorId };}/**- * The single Ramp spend vendor whose name EXACTLY (case-insensitively) matches- * `name`, or null when there is none — OR more than one. A vendor name is not an- * identity key: two Ramp vendors can share one, and binding a Carbon supplier to- * an arbitrary same-named vendor would push its bills under the wrong Ramp- * vendor. An ambiguous name therefore falls through to a create instead of- * linking.+ * Link a Ramp SPEND vendor to the seat-holder's ACCOUNTING vendor.+ *+ * Three counterparty objects, three id spaces — Ramp's guide calls confusing+ * them "the most common integration error":+ *+ * - **Merchant** — the card-network counterparty on a transaction. Read-only.+ * - **Vendor** (`/developer/v1/vendors`) — the bill-pay payee. What a PO/bill+ * `vendor_id` names, and what Carbon creates.+ * - **Accounting vendor** (`/developer/v1/accounting/vendors`) — the GL vendor,+ * published by whoever holds the accounting connection. Ramp shows it on a+ * bill as "Accounting Merchant", and it is what the bill posts against.+ *+ * A vendor Carbon creates carries no accounting vendor, so without this link a+ * bill reaches Ramp with "Accounting Merchant" empty and someone has to pick it+ * before the seat-holder can post the bill.+ *+ * Best-effort: the bill still pushes when the link fails, exactly as it did+ * before linking existed, so a refusal here can never block a payable. Returns+ * the accounting vendor the Ramp vendor is now linked to, or undefined when it+ * is not (so the next push tries again).*/-async function findUniqueRampSpendVendorByName(+async function linkAccountingVendor(client: RampClient,- name: string-): Promise<RampVendor | null> {- const target = name.trim().toLowerCase();- if (!target) return null;- let match: RampVendor | null = null;- for await (const page of client.listVendors({ name })) {- for (const vendor of page) {- if ((vendor.name ?? "").trim().toLowerCase() !== target) continue;- if (match) return null; // more than one exact match → ambiguous- match = vendor;- }+ rampVendorId: string,+ accountingVendorId: string+): Promise<string | undefined> {+ try {+ await client.updateSpendVendor(rampVendorId, {+ accounting_vendor_remote_id: accountingVendorId+ });+ return accountingVendorId;+ } catch (error) {+ console.error(+ `[RAMP] failed to link vendor ${rampVendorId} to accounting vendor ${accountingVendorId}`,+ error+ );+ return undefined;}- return match;+}++async function recordSpendVendor(+ mapping: ExternalIntegrationMappingService,+ resolution: RampVendorResolution,+ supplierId: string,+ rampVendorId: string,+ linkedTo: string | undefined+) {+ await mapping.link("vendor", supplierId, RAMP, rampVendorId, {+ createdBy: "system",+ ...(linkedTo+ ? { metadata: { [LINKED_ACCOUNTING_VENDOR_KEY]: linkedTo } }+ : {})+ });+ resolution.vendorIds.set(supplierId, rampVendorId);+ if (linkedTo) resolution.linkedAccountingVendorIds.set(supplierId, linkedTo);+ else resolution.linkedAccountingVendorIds.delete(supplierId);}/*** Resolve the Ramp SPEND-vendor id a PO/bill `vendor_id` needs for a Carbon- * supplier — matching first, creating only as a last resort (option B):- *- * 1. an existing `("vendor", supplier.id, "ramp")` mapping,- * 2. a Ramp vendor already carrying our `external_vendor_id`,- * 3. a Ramp vendor whose name matches exactly (case-insensitive) — links to a- * pre-existing spend vendor instead of duplicating it,- * 4. otherwise CREATE one (`POST /vendors`) with the supplier's synced contact- * email + country (+ address when present) and `external_vendor_id`.+ * supplier — matching first, creating only as a last resort. The ladder is+ * `decideRampSpendVendor`; this performs what it decides. A create sends the+ * supplier's synced contact email + country (+ address when present) and+ * `external_vendor_id`.** Returns `null` (never throws) when the supplier has no name, or has no* matching vendor AND lacks the email/country a create requires — the caller* decides (a PO omits the optional `vendor_id`; a bill, which requires one, is- * skipped). Accounting vendors (`/accounting/vendors`, for coding) are a- * DIFFERENT id space Ramp rejects here — do not use them.+ * skipped). Accounting vendors (`/accounting/vendors`) are a DIFFERENT id space+ * a PO/bill `vendor_id` rejects — see `linkAccountingVendor`.*/export async function resolveOrCreateRampSpendVendor(mapping: ExternalIntegrationMappingService,client: RampClient,supplier: RampVendorSupplier,- companyId?: string,- batch?: RampPurchaseOrderBatch,+ companyId: string,+ resolution: RampVendorResolution,opts?: {/*** Rethrow Ramp's rejection instead of returning null.@@ -157,35 +397,30 @@ export async function resolveOrCreateRampSpendVendor(surfaceCreateError?: boolean;}): Promise<string | null> {- const existing = batch- ? batch.vendorIds.get(supplier.id)- : await mapping.getExternalId("vendor", supplier.id, RAMP);- if (existing) return existing;-- const name = (supplier.name ?? "").trim();- if (!name) return null;- if (batch && !batch.vendorLookup.ok) throw batch.vendorLookup.error;-- // Prefer an exact identity match on our own external_vendor_id. Fall back to a- // name match ONLY when it is unambiguous — exactly one Ramp vendor carries- // this exact (case-insensitive) name — since a shared name is not an identity- // key and would otherwise link this supplier to the wrong Ramp vendor.- const byExternal = batch- ? batch.vendorsByExternalId.get(supplier.id)- : await findRampSpendVendor(client, { external_vendor_id: supplier.id });- const matched =- byExternal ??- (batch- ? batch.vendorsByName.get(name.toLowerCase())- : await findUniqueRampSpendVendorByName(client, name));- if (matched?.id) {- await mapping.link("vendor", supplier.id, RAMP, matched.id, {- createdBy: "system"- });- batch?.vendorIds.set(supplier.id, matched.id);- return matched.id;+ const decision = decideRampSpendVendor(resolution, supplier);+ if (decision.action === "use") return decision.vendorId;+ if (decision.action === "none") return null;+ if (decision.action === "fail") throw decision.error;+ if (decision.action === "match") {+ if (decision.conflict) {+ console.warn(+ `[RAMP] vendor ${decision.vendorId} is linked to accounting vendor ${decision.conflict}, not the one mapped for supplier ${supplier.id}; leaving it`+ );+ }+ const linkedTo = decision.linkTo+ ? await linkAccountingVendor(client, decision.vendorId, decision.linkTo)+ : decision.linkedTo;+ await recordSpendVendor(+ mapping,+ resolution,+ supplier.id,+ decision.vendorId,+ linkedTo+ );+ return decision.vendorId;}+ const name = (supplier.name ?? "").trim();// Create — Ramp requires a country and at least one contact email (and, for// US, a two-letter state). Best-effort: a create that Ramp rejects (missing// state, bad data) returns null rather than throwing, so a PO still pushes@@ -198,6 +433,10 @@ export async function resolveOrCreateRampSpendVendor(// `business_vendor_contacts` is a SINGLE object despite the plural name// (OpenAPI `allOf` of one contact schema — an array is rejected "Invalid input// type"). `state` is required for US and lives at the vendor top level.+ //+ // The accounting-vendor link is deliberately NOT part of the create body: a+ // link Ramp refuses would then fail the create, and with it the bill. It is+ // made by a separate best-effort PATCH below.let created: { id?: string } | null;try {created = (await client.createSpendVendor(@@ -228,15 +467,12 @@ export async function resolveOrCreateRampSpendVendor(: {})},// Entity-scoped idempotency key (keyed on the Carbon supplier id) so a- // retried push cannot create a duplicate Ramp spend vendor. Only when the- // caller supplied a companyId (the helper needs it to derive the key).- companyId- ? buildRampIdempotencyKey({- companyId,- operation: "createSpendVendor",- scope: supplier.id- })- : undefined+ // retried push cannot create a duplicate Ramp spend vendor.+ buildRampIdempotencyKey({+ companyId,+ operation: "createSpendVendor",+ scope: supplier.id+ }))) as { id?: string } | null;} catch (createError) {console.error(@@ -250,16 +486,21 @@ export async function resolveOrCreateRampSpendVendor(const rampVendorId = created?.id ?? null;if (!rampVendorId) return null;- await mapping.link("vendor", supplier.id, RAMP, rampVendorId, {- createdBy: "system"+ const linkedTo = decision.linkTo+ ? await linkAccountingVendor(client, rampVendorId, decision.linkTo)+ : undefined;+ await recordSpendVendor(+ mapping,+ resolution,+ supplier.id,+ rampVendorId,+ linkedTo+ );+ indexSpendVendor(resolution, {+ id: rampVendorId,+ name,+ external_vendor_id: supplier.id,+ accounting_vendor_remote_id: linkedTo});- if (batch) {- batch.vendorIds.set(supplier.id, rampVendorId);- indexSpendVendor(batch, {- id: rampVendorId,- name,- external_vendor_id: supplier.id- });- }return rampVendorId;}diff --git a/scripts/ramp-bill-probe.ts b/scripts/ramp-bill-probe.tsnew file mode 100644index 0000000000..07f3d69d36--- /dev/null+++ b/scripts/ramp-bill-probe.ts@@ -0,0 +1,152 @@+/**+ * Report what Ramp stored for ONE pushed bill, next to what Carbon would code it+ * with — to tell "Carbon sent the wrong ids" from "Ramp did not keep them".+ *+ * Written for push-only installs, where the seat-holder (Rillet) owns both the+ * chart of accounts and the accounting vendors, and a bill arrived in Ramp with+ * neither its GL categories nor its Accounting Merchant selected.+ *+ * Prints, in order:+ * 1. Carbon's side — the draft-bill mapping (when it was pushed), and for every+ * account on the posted journal the seat-holder's id Carbon codes with.+ * 2. `GET /bills/drafts/{id}` — the vendor and each line's stored+ * `accounting_field_selections`. A line with no GL selection here means Ramp+ * did not keep (or never got) the coding.+ * 3. `GET /vendors/{id}` — the Ramp vendor's `accounting_vendor_remote_id`, the+ * link that fills the bill's Accounting Merchant.+ * 4. `GET /accounting/accounts` — whether Ramp knows each seat-holder account id+ * at all (a miss means the ids differ between Carbon's mapping and Ramp).+ *+ * Read-only. Every Ramp call is a GET; nothing in Carbon is written.+ *+ * Usage:+ * pnpm exec tsx scripts/ramp-bill-probe.ts <companyId> <purchaseInvoiceId>+ */++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { getRampIntegration } from "@carbon/ee/ramp.server";++const [companyId, purchaseInvoiceId] = process.argv.slice(2);++if (!companyId || !purchaseInvoiceId) {+ console.error(+ "usage: ramp-bill-probe.ts <companyId> <purchaseInvoiceId>"+ );+ process.exit(1);+}++async function attempt<T>(+ label: string,+ fn: () => Promise<T>+): Promise<T | undefined> {+ try {+ const result = await fn();+ console.log(`\n[ok] ${label}`);+ console.log(JSON.stringify(result, null, 2));+ return result;+ } catch (error) {+ console.log(`\n[refused] ${label}`);+ console.log(` ${(error as Error).message}`);+ return undefined;+ }+}++async function main() {+ const serviceRole = getCarbonServiceRole();+ const integration = await getRampIntegration(serviceRole, companyId);+ if (!integration) {+ console.log(`No active Ramp integration for company ${companyId}`);+ return;+ }+ const { client } = integration;++ console.log("=== Carbon ===");+ const invoice = await serviceRole+ .from("purchaseInvoice")+ .select("invoiceId, supplierId, postingDate")+ .eq("companyId", companyId)+ .eq("id", purchaseInvoiceId)+ .single();+ console.log(JSON.stringify(invoice.data ?? invoice.error, null, 2));++ const mappings = await serviceRole+ .from("externalIntegrationMapping")+ .select("entityType, entityId, integration, externalId, metadata, createdAt")+ .eq("companyId", companyId)+ .in("entityId", [purchaseInvoiceId, invoice.data?.supplierId ?? ""]);+ console.log(JSON.stringify(mappings.data ?? mappings.error, null, 2));++ const draftId = mappings.data?.find(+ (m) => m.entityType === "bill" && m.integration === "ramp"+ )?.externalId;+ const rampVendorId = mappings.data?.find(+ (m) => m.entityType === "vendor" && m.integration === "ramp"+ )?.externalId;++ const lines = await serviceRole+ .from("journalLine")+ .select("accountId, journal!inner(sourceType, status)")+ .eq("companyId", companyId)+ .eq("documentType", "Invoice")+ .eq("documentId", purchaseInvoiceId)+ .eq("journal.sourceType", "Purchase Invoice")+ .eq("journal.status", "Posted");+ const accountIds = [+ ...new Set((lines.data ?? []).map((line) => line.accountId).filter(Boolean))+ ] as string[];+ const accountMappings = await serviceRole+ .from("externalIntegrationMapping")+ .select("entityId, integration, externalId, metadata")+ .eq("companyId", companyId)+ .eq("entityType", "account")+ .in("entityId", accountIds);+ console.log("\naccount mappings for the posted journal:");+ console.log(JSON.stringify(accountMappings.data ?? accountMappings.error, null, 2));++ console.log("\n=== Ramp ===");+ if (draftId) {+ await attempt(`GET /bills/drafts/${draftId}`, () =>+ client.request("GET", `/developer/v1/bills/drafts/${draftId}`)+ );+ } else {+ console.log("\nno ramp bill mapping — the invoice was never pushed");+ }++ if (rampVendorId) {+ await attempt(`GET /vendors/${rampVendorId}`, () =>+ client.request("GET", `/developer/v1/vendors/${rampVendorId}`)+ );+ }++ const wanted = new Set(+ (accountMappings.data ?? [])+ .filter((m) => m.integration !== "ramp")+ .map((m) => m.externalId)+ );+ const known = await attempt("GET /accounting/accounts (matches only)", async () => {+ const found: unknown[] = [];+ let path: string | null = "/developer/v1/accounting/accounts?page_size=100";+ while (path) {+ const page: { data?: Array<Record<string, unknown>>; page?: { next?: string | null } } =+ await client.request("GET", path);+ for (const account of page.data ?? []) {+ if (wanted.has(String(account.id)) || wanted.has(String(account.remote_id)) || wanted.has(String(account.external_id))) {+ found.push(account);+ }+ }+ const next = page.page?.next;+ path = next ? `${new URL(next).pathname}${new URL(next).search}` : null;+ }+ return found;+ });+ if (known) {+ console.log(+ `\n${(known as unknown[]).length} of ${wanted.size} seat-holder account ids are known to Ramp`+ );+ }+}++main().catch((error) => {+ console.error(error);+ process.exit(1);+});