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(integrations): address review of the Mount integration
Raul3a5f4186c999
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 415d16020c..989d389d10 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1467,7 +1467,8 @@ export async function updateSupplierTax(return client.from("supplierTax").update(sanitize({ ...supplierTax, updatedAt: new Date().toISOString() }))- .eq("supplierId", supplierTax.supplierId);+ .eq("supplierId", supplierTax.supplierId)+ .eq("companyId", supplierTax.companyId);}export async function insertPurchaseOrder(diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex 754a8b169a..1cdba86e34 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -22,7 +22,6 @@ import {} from "@carbon/form";import {Accordion,- AccordionContent,AccordionItem,AccordionTrigger,Badge,@@ -617,6 +616,7 @@ export function IntegrationForm({// Mapping") update the search param, and this effect switches the tab// without a remount. Manual tab clicks don't write the URL.const [activeTab, setActiveTab] = useState(defaultTab ?? "settings");+ const [settingsOpen, setSettingsOpen] = useState(false);useEffect(() => {if (defaultTab) setActiveTab(defaultTab);}, [defaultTab]);@@ -817,22 +817,32 @@ export function IntegrationForm({</>);- // Collapsed by default: the fields still mount, so the form posts every- // value whether or not the section is open.+ // Collapsed by default. The accordion only draws the trigger: its content+ // unmounts when closed, which would drop these fields from the submitted+ // form. So they sit outside it, always mounted, and are only hidden.const settingsBody = collapseSettings ? (- <Accordion type="single" collapsible className="w-full">- <AccordionItem value="settings" className="border-none">- <AccordionTrigger className="py-2 text-sm font-medium hover:no-underline">- {settingsLabel ?? <Trans>Settings</Trans>}- </AccordionTrigger>- <AccordionContent>- <VStack spacing={4} className="w-full pt-2">- {setupInstructions}- {settingsFields}- </VStack>- </AccordionContent>- </AccordionItem>- </Accordion>+ <div className="flex w-full flex-col">+ <Accordion+ type="single"+ collapsible+ value={settingsOpen ? "settings" : ""}+ onValueChange={(value) => setSettingsOpen(value === "settings")}+ className="w-full"+ >+ <AccordionItem value="settings" className="border-none">+ <AccordionTrigger className="py-2 text-sm font-medium hover:no-underline">+ {settingsLabel ?? <Trans>Settings</Trans>}+ </AccordionTrigger>+ </AccordionItem>+ </Accordion>+ <VStack+ spacing={4}+ className={cn("w-full pt-2", !settingsOpen && "hidden")}+ >+ {setupInstructions}+ {settingsFields}+ </VStack>+ </div>) : (settingsFields);diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex c53a892101..c1e5a2ad39 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -1722,6 +1722,7 @@ export async function action({ request, params }: ActionFunctionArgs) {// callback, so they are never blocked here.const FORM_SECRET_INTEGRATIONS = new Set(["linear",+ "mount","paperless-parts","email","ramp",diff --git a/packages/ee/src/accounting/core/external-mapping.ts b/packages/ee/src/accounting/core/external-mapping.tsindex cdfcb63d95..b0d5d4df6e 100644--- a/packages/ee/src/accounting/core/external-mapping.ts+++ b/packages/ee/src/accounting/core/external-mapping.ts@@ -19,6 +19,13 @@ export interface ExternalIntegrationMapping {export interface LinkOptions {metadata?: Record<string, unknown>;remoteUpdatedAt?: Date | string;+ /**+ * When the Carbon side was read for this sync. Defaults to now. A caller that+ * detects changes by comparing `lastSyncedAt` with the entity's `updatedAt`+ * passes its read time, so an edit made while the sync was in flight still+ * reads as newer and is picked up next time.+ */+ lastSyncedAt?: Date | string;createdBy?: string;/*** When true, allows multiple Carbon entities to map to the same external ID.@@ -56,6 +63,10 @@ export class ExternalIntegrationMappingService {options?.remoteUpdatedAt instanceof Date? options.remoteUpdatedAt.toISOString(): (options?.remoteUpdatedAt ?? now);+ const lastSyncedAt =+ options?.lastSyncedAt instanceof Date+ ? options.lastSyncedAt.toISOString()+ : (options?.lastSyncedAt ?? now);const allowDuplicateExternalId = options?.allowDuplicateExternalId ?? false;await this.db@@ -68,7 +79,7 @@ export class ExternalIntegrationMappingService {allowDuplicateExternalId,companyId: this.companyId,metadata: options?.metadata ?? null,- lastSyncedAt: now,+ lastSyncedAt,remoteUpdatedAt,createdBy: options?.createdBy ?? null,createdAt: now,@@ -81,7 +92,7 @@ export class ExternalIntegrationMappingService {externalId,allowDuplicateExternalId,metadata: (options?.metadata ?? null) as any,- lastSyncedAt: now,+ lastSyncedAt,remoteUpdatedAt,updatedAt: now})diff --git a/packages/ee/src/mount/lib/client.ts b/packages/ee/src/mount/lib/client.tsindex fe8d6f574a..3251a05775 100644--- a/packages/ee/src/mount/lib/client.ts+++ b/packages/ee/src/mount/lib/client.ts@@ -30,7 +30,12 @@ type MountSettings = {scope?: string;};-type CachedToken = { accessToken: string; expiresAt: number };+type CachedToken = {+ accessToken: string;+ expiresAt: number;+ /** The settings the token was issued under; see `connectionKey`. */+ connection: string;+};/*** Re-exchange this long before a token actually lapses, so a request never@@ -62,6 +67,11 @@ const TOKEN_EXPIRY_MARGIN_MS = 60_000;export class MountClient {instance: AxiosInstance;private tokens = new Map<string, CachedToken>();+ /** One pending exchange per company, shared by concurrent callers. */+ private inflight = new Map<+ string,+ { connection: string; exchange: Promise<string> }+ >();/** Domain setting (identifier or title) -> id, per company. */private domainIds = new Map<string, string>();@@ -76,15 +86,40 @@ export class MountClient {settings: MountSettings,{ force = false }: { force?: boolean } = {}): Promise<string> {+ const connection = connectionKey(settings);const cached = this.tokens.get(companyId);if (!force &&cached &&+ cached.connection === connection &&cached.expiresAt - TOKEN_EXPIRY_MARGIN_MS > Date.now()) {return cached.accessToken;}+ // A publish run resolves its settings with several requests at once;+ // without this each of them would exchange its own token.+ const pending = this.inflight.get(companyId);+ if (!force && pending?.connection === connection) {+ return await pending.exchange;+ }++ const exchange = this.exchangeToken(companyId, settings, connection);+ this.inflight.set(companyId, { connection, exchange });+ try {+ return await exchange;+ } finally {+ if (this.inflight.get(companyId)?.exchange === exchange) {+ this.inflight.delete(companyId);+ }+ }+ }++ private async exchangeToken(+ companyId: string,+ settings: MountSettings,+ connection: string+ ): Promise<string> {const body = new URLSearchParams({grant_type: "client_credentials",client_id: settings.clientId,@@ -112,7 +147,8 @@ export class MountClient {this.tokens.set(companyId, {accessToken,- expiresAt: Date.parse(expiresAt)+ expiresAt: Date.parse(expiresAt),+ connection});return accessToken;@@ -167,7 +203,7 @@ export class MountClient {if (!scope) return null;if (UUID_PATTERN.test(scope)) return scope;- const key = `${companyId}:${scope}`;+ const key = `${companyId}:${connectionKey(settings)}:${scope}`;const cached = this.domainIds.get(key);if (cached) return cached;@@ -415,6 +451,20 @@ export class MountClient {}}+/**+ * Identifies the Mount connection a cached value belongs to. Changing the+ * client, secret, tenant or API URL in settings must not keep serving a token+ * or domain id issued under the old ones. In memory only, never persisted.+ */+function connectionKey(settings: MountSettings) {+ return [+ settings.baseUrl || MOUNT_DEFAULT_BASE_URL,+ settings.tenant,+ settings.clientId,+ settings.clientSecret+ ].join("\u0000");+}+const UUID_PATTERN =/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;diff --git a/packages/ee/src/mount/lib/publish.test.ts b/packages/ee/src/mount/lib/publish.test.tsindex 638f1f693a..41bd230a8e 100644--- a/packages/ee/src/mount/lib/publish.test.ts+++ b/packages/ee/src/mount/lib/publish.test.ts@@ -184,6 +184,36 @@ describe("publishEntityType", () => {expect(summary.failed[0]?.reason).toContain("readableId");});+ it("records the read time, not the link time, as lastSyncedAt", async () => {+ const { api } = createFakeMount();+ const synced: Array<string | undefined> = [];+ const mappings: MountMappingPort = {+ async getExternalId() {+ return null;+ },+ async link(_t, _id, _i, _ext, options) {+ synced.push(options?.lastSyncedAt);+ }+ };+ let listedAt = "";+ const source: MountPublishSource = {+ async listStale() {+ listedAt = new Date().toISOString();+ // An edit landing after the read must still sort after lastSyncedAt.+ await new Promise((resolve) => setTimeout(resolve, 5));+ return [{ id: "i1", readableId: "P-1", name: "Bracket" }];+ }+ };++ await publishEntityType(source, mappings, api, COMPANY_ID, "item", {+ partDefinitionId: PART_DEFINITION+ });++ expect(synced).toHaveLength(1);+ expect(synced[0]).toBeDefined();+ expect(synced[0]! <= listedAt).toBe(true);+ });+describe("records that keep failing", () => {const parts: PublishablePart[] = Array.from({ length: 5 }, (_, i) => ({id: `i${i}`,diff --git a/packages/ee/src/mount/lib/publish.ts b/packages/ee/src/mount/lib/publish.tsindex aaff316b9d..01eb0219cd 100644--- a/packages/ee/src/mount/lib/publish.ts+++ b/packages/ee/src/mount/lib/publish.ts@@ -1,3 +1,4 @@+import { datetime } from "@carbon/utils";import {type CarbonCompanyRecord,type CarbonItemRecord,@@ -112,6 +113,8 @@ export async function publishEntityType(return summary;}+ // Taken before the read, so anything edited after it stays stale.+ const readAt = datetime.timestamp();const records = await source.listStale(entityType, limit + 1, deferIds);const batch = records.slice(0, limit);const deferSet = new Set(deferIds);@@ -130,7 +133,8 @@ export async function publishEntityType(companyId,entityType,record,- settings+ settings,+ readAt);if (outcome.status === "created") summary.created++;@@ -183,7 +187,8 @@ async function publishOne(companyId: string,entityType: MountEntityType,record: PublishableCustomer | PublishableSupplier | PublishablePart,- settings: MountPublishSettings+ settings: MountPublishSettings,+ readAt: string): Promise<PushOutcome> {if (entityType === "item") {return await pushItemToMount(@@ -195,7 +200,8 @@ async function publishOne(record as PublishablePart,// Checked by the caller before the loop.settings.partDefinitionId as string- )+ ),+ readAt);}@@ -216,7 +222,8 @@ async function publishOne(companyId,entityType,record.id,- input+ input,+ readAt);}diff --git a/packages/ee/src/mount/lib/push.ts b/packages/ee/src/mount/lib/push.tsindex 4ec40b7a7c..66b2ae2fa4 100644--- a/packages/ee/src/mount/lib/push.ts+++ b/packages/ee/src/mount/lib/push.ts@@ -28,6 +28,7 @@ export type MountMappingPort = {options?: {metadata?: Record<string, unknown>;allowDuplicateExternalId?: boolean;+ lastSyncedAt?: string;}): Promise<void>;};@@ -84,7 +85,8 @@ export async function pushCompanyToMount(companyId: string,entityType: Extract<MountEntityType, "customer" | "supplier">,entityId: string,- input: MountCompanyInput+ input: MountCompanyInput,+ readAt?: string): Promise<PushOutcome> {const externalId = await mappings.getExternalId(entityType,@@ -95,7 +97,7 @@ export async function pushCompanyToMount(if (externalId) {try {await api.updateCompany(companyId, externalId, input);- await link(mappings, entityType, entityId, externalId, input);+ await link(mappings, entityType, entityId, externalId, input, readAt);return { status: "updated", externalId };} catch (error) {if (!(error instanceof MountNotFoundError)) throw error;@@ -125,7 +127,7 @@ export async function pushCompanyToMount(mountId = (await api.createCompany(companyId, input)).id;}- await link(mappings, entityType, entityId, mountId, input);+ await link(mappings, entityType, entityId, mountId, input, readAt);return { status: match ? "updated" : "created", externalId: mountId };}@@ -135,7 +137,8 @@ export async function pushItemToMount(api: MountApiPort,companyId: string,entityId: string,- input: MountObjectInput+ input: MountObjectInput,+ readAt?: string): Promise<PushOutcome> {const externalId = await mappings.getExternalId("item",@@ -146,7 +149,7 @@ export async function pushItemToMount(if (externalId) {try {await api.updateObject(companyId, externalId, input);- await link(mappings, "item", entityId, externalId, input);+ await link(mappings, "item", entityId, externalId, input, readAt);return { status: "updated", externalId };} catch (error) {if (!(error instanceof MountNotFoundError)) throw error;@@ -177,7 +180,7 @@ export async function pushItemToMount(mountId = (await api.createObject(companyId, input)).id;}- await link(mappings, "item", entityId, mountId, input);+ await link(mappings, "item", entityId, mountId, input, readAt);return { status: match ? "updated" : "created", externalId: mountId };}@@ -185,16 +188,23 @@ export async function pushItemToMount(/*** The mapping's metadata records what Carbon last sent. Mount's PATCH does not* return the record, so the payload is the only snapshot available on update.+ *+ * `readAt` is when the record was read from Carbon, stored as `lastSyncedAt`.+ * Stamping the link time instead would hide an edit made between the read and+ * the push: its `updatedAt` would sort before `lastSyncedAt` and the sweep+ * would never send it.*/async function link(mappings: MountMappingPort,entityType: MountEntityType,entityId: string,mountId: string,- sent: MountCompanyInput | MountObjectInput+ sent: MountCompanyInput | MountObjectInput,+ readAt?: string) {await mappings.link(entityType, entityId, MOUNT_INTEGRATION_ID, mountId, {metadata: sent,+ lastSyncedAt: readAt,// A Mount part is per part number, and each Carbon revision is its own// item. When a new revision is released it takes over the Mount record,// while the superseded revision's row still points at it.diff --git a/packages/ee/src/mount/lib/run.ts b/packages/ee/src/mount/lib/run.tsindex 13e6a55ecc..6dfe5e8c8f 100644--- a/packages/ee/src/mount/lib/run.ts+++ b/packages/ee/src/mount/lib/run.ts@@ -1,5 +1,7 @@import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { getLogger } from "@carbon/logger";+import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { createMappingService } from "../../accounting/core/external-mapping";import { getMountClient } from "./client";@@ -14,6 +16,8 @@ import { getMountIntegration } from "./service";import { createMountPublishSource } from "./source";import type { MountEntityType } from "./types";+const logger = getLogger("ee", "mount");+/*** One publish run: resolve settings, sweep, record the outcome. The* `mount-publish` job calls it for the integration's push actions, and a cron@@ -105,11 +109,18 @@ async function recordOutcome(companyId: string,summaries: MountPublishSummary[]) {+ // Throw rather than carry on: writing back without the stored metadata+ // would drop the saved settings, and a lost write drops the deferred ids.+ // A throw fails the job step, which Inngest retries.const current = await getMountIntegration(serviceRole, companyId);- const metadata = (current.data?.[0]?.metadata ?? {}) as Record<- string,- unknown- >;+ if (current.error || !current.data?.[0]) {+ logger.error("Failed to read Mount integration to record publish outcome", {+ companyId,+ error: current.error+ });+ throw new Error("Failed to read Mount integration");+ }+ const metadata = (current.data[0].metadata ?? {}) as Record<string, unknown>;const lastPublish = {...((metadata.lastPublish as Record<string, unknown>) ?? {}),@@ -117,7 +128,7 @@ async function recordOutcome(summaries.map((summary) => [summary.entityType,{- at: new Date().toISOString(),+ at: datetime.timestamp(),created: summary.created,updated: summary.updated,more: summary.more,@@ -129,9 +140,17 @@ async function recordOutcome()};- await serviceRole+ const update = await serviceRole.from("companyIntegration").update({ metadata: { ...metadata, lastPublish } as never }).eq("companyId", companyId).eq("id", MOUNT_INTEGRATION_ID);++ if (update.error) {+ logger.error("Failed to record Mount publish outcome", {+ companyId,+ error: update.error+ });+ throw new Error("Failed to record Mount publish outcome");+ }}