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(integrations): publish customers, suppliers and parts to Mount
Raul35b7a673328b
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex dc9d223620..415d16020c 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1466,7 +1466,7 @@ export async function updateSupplierTax() {return client.from("supplierTax")- .update(sanitize(supplierTax))+ .update(sanitize({ ...supplierTax, updatedAt: new Date().toISOString() })).eq("supplierId", supplierTax.supplierId);}diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 7219350684..d8c8df99b9 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -3224,7 +3224,7 @@ export async function updateCustomerTax() {return client.from("customerTax")- .update(sanitize(customerTax))+ .update(sanitize({ ...customerTax, updatedAt: new Date().toISOString() })).eq("customerId", customerTax.customerId);}diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex 062c9b5a8c..754a8b169a 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -21,6 +21,10 @@ import {ValidatedForm} from "@carbon/form";import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,Badge,Button,cn,@@ -566,6 +570,14 @@ export type IntegrationFormTab = {interface IntegrationFormProps {metadata: Record<string, unknown>;installed: boolean;+ /**+ * Collapse the settings and setup instructions behind a disclosure,+ * labelled with `settingsLabel`, and move the actions above them. For an+ * integration whose day-to-day surface is its actions: the credentials are+ * entered once and then only re-read when something breaks.+ */+ collapseSettings?: boolean;+ settingsLabel?: ReactNode;onClose: () => void;/** Dynamic options to merge into settings (e.g., fetched from external APIs) */dynamicOptions?: Record<@@ -582,6 +594,8 @@ interface IntegrationFormProps {export function IntegrationForm({installed,metadata,+ collapseSettings = false,+ settingsLabel,onClose,dynamicOptions = {},tabs = [],@@ -762,6 +776,95 @@ export function IntegrationForm({const hasTabs = tabs.length > 0;+ // Rendered above the settings. When the settings are collapsed they move+ // inside with them: the instructions exist to help fill those fields in, so+ // they belong behind the same disclosure rather than above a section the+ // reader has not opened.+ const setupInstructions = SetupInstructions ? (+ <div className="flex flex-col gap-2">+ <Subheading variant="light" className="block">+ <Trans>Setup instructions</Trans>+ </Subheading>+ <SetupInstructions+ companyId={companyId}+ metadata={metadata}+ installed={installed}+ mode={installMode?.id}+ />+ </div>+ ) : null;++ const settingsFields = (+ <>+ {/* Ungrouped settings appear first */}+ {ungroupedSettings.length > 0 && (+ <VStack spacing={4} className="w-full">+ {ungroupedSettings.map((setting) => (+ <SettingField key={setting.name} setting={setting} />+ ))}+ </VStack>+ )}++ {/* Grouped settings in flat sections */}+ {groupNames.map((groupName) => (+ <ConditionalSettingsGroup+ key={groupName}+ name={groupName}+ description={groupDescriptions.get(groupName)}+ settings={groupedSettings.get(groupName) ?? []}+ />+ ))}+ </>+ );++ // Collapsed by default: the fields still mount, so the form posts every+ // value whether or not the section is open.+ 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>+ ) : (+ settingsFields+ );++ const actionsSection = installed && integrationActions.length > 0 && (+ // `has-[button]` collapses the whole section (header included)+ // when every gated action is hidden, so the toggle live-controls+ // visibility without leaving an empty "Actions" header.+ <div className="hidden has-[button]:flex w-full flex-col gap-3 border-t border-border pt-4">+ <Subheading variant="light" className="block">+ <Trans>Actions</Trans>+ </Subheading>+ <VStack spacing={2} className="w-full">+ {integrationActions.map((action) =>+ action.enabledWhenSetting ? (+ <GatedIntegrationActionButton+ key={action.id}+ action={action}+ isDisabled={isDisabled}+ />+ ) : (+ <IntegrationActionButton+ key={action.id}+ action={action}+ isDisabled={isDisabled}+ />+ )+ )}+ </VStack>+ </div>+ );+const headerContent = (<div className="flex flex-col gap-3"><div className="flex items-center gap-3">@@ -863,66 +966,13 @@ export function IntegrationForm({integration.description}</p>- {SetupInstructions && (- <div className="flex flex-col gap-2">- <Subheading variant="light" className="block">- <Trans>Setup instructions</Trans>- </Subheading>- <SetupInstructions- companyId={companyId}- metadata={metadata}- installed={installed}- mode={installMode?.id}- />- </div>- )}+ {!collapseSettings && setupInstructions}- {/* Ungrouped settings appear first */}- {ungroupedSettings.length > 0 && (- <VStack spacing={4} className="w-full">- {ungroupedSettings.map((setting) => (- <SettingField key={setting.name} setting={setting} />- ))}- </VStack>- )}+ {collapseSettings && actionsSection}- {/* Grouped settings in flat sections */}- {groupNames.map((groupName) => (- <ConditionalSettingsGroup- key={groupName}- name={groupName}- description={groupDescriptions.get(groupName)}- settings={groupedSettings.get(groupName) ?? []}- />- ))}+ {settingsBody}- {installed && integrationActions.length > 0 && (- // `has-[button]` collapses the whole section (header included)- // when every gated action is hidden, so the toggle live-controls- // visibility without leaving an empty "Actions" header.- <div className="hidden has-[button]:flex w-full flex-col gap-3 border-t border-border pt-4">- <Subheading variant="light" className="block">- <Trans>Actions</Trans>- </Subheading>- <VStack spacing={2} className="w-full">- {integrationActions.map((action) =>- action.enabledWhenSetting ? (- <GatedIntegrationActionButton- key={action.id}- action={action}- isDisabled={isDisabled}- />- ) : (- <IntegrationActionButton- key={action.id}- action={action}- isDisabled={isDisabled}- />- )- )}- </VStack>- </div>- )}+ {!collapseSettings && actionsSection}</VStack></ScrollArea><div className="mt-2">diff --git a/apps/erp/app/routes/api+/integrations.mount.publish.ts b/apps/erp/app/routes/api+/integrations.mount.publish.tsnew file mode 100644index 0000000000..94124d7fb2--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.mount.publish.ts@@ -0,0 +1,64 @@+import { assertIsPost } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getMountIntegration } from "@carbon/ee/mount.server";+import { trigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { z } from "zod";++const logger = getLogger("erp", "integrations-mount-publish");++export const config = {+ runtime: "nodejs"+};++const PublishRequestSchema = z.object({+ entityType: z.enum(["customer", "supplier", "item"])+});++/**+ * POST — start a Mount publish for one family of records (the "Push+ * customers / suppliers / parts" actions on the integration settings page).+ * Fire-and-forget: the `mount-publish` job does the work, one run per company+ * at a time, and records its outcome on the integration's metadata.+ */+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const parsed = PublishRequestSchema.safeParse({+ entityType: new URL(request.url).searchParams.get("entityType")+ });++ if (!parsed.success) {+ return data({ error: "Invalid entity type" }, { status: 400 });+ }++ const integration = await getMountIntegration(client, companyId);++ if (integration.error || !integration.data?.[0]?.active) {+ return data(+ { error: "Mount integration not found or inactive" },+ { status: 400 }+ );+ }++ try {+ await trigger("mount-publish", {+ companyId,+ entityTypes: [parsed.data.entityType]+ });++ return data({ success: true, message: "Mount publish started" });+ } catch (error) {+ logger.error("Failed to start Mount publish", {+ companyId,+ entityType: parsed.data.entityType,+ error+ });+ return data({ error: "Failed to start Mount publish" }, { status: 500 });+ }+}diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 91fc2ca57e..c53a892101 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -79,6 +79,7 @@ import {redirect,useLoaderData,useNavigate,+ useParams,useSearchParams} from "react-router";// Deep service import (not the ~/modules/accounting barrel) to keep this@@ -1881,6 +1882,11 @@ export default function IntegrationRoute() {const navigate = useNavigate();const [searchParams] = useSearchParams();+ const { id: integrationId } = useParams();++ // Mount is used through its push actions once connected, so its credentials+ // fold away beneath them.+ const collapseSettings = integrationId === "mount" && installed;// Accounting-category integrations get Account Mapping, Posting, Dimensions// and Sync Activity tabs next to the Settings form (deep-linkable via@@ -1978,6 +1984,10 @@ export default function IntegrationRoute() {<IntegrationForminstalled={installed}metadata={metadata}+ collapseSettings={collapseSettings}+ settingsLabel={+ collapseSettings ? <Trans>Integration credentials</Trans> : undefined+ }dynamicOptions={dynamicOptions}tabs={tabs.length > 0 ? tabs : undefined}defaultTab={defaultTab}diff --git a/packages/database/supabase/migrations/20260928120657_mount-integration.sql b/packages/database/supabase/migrations/20260928120657_mount-integration.sqlnew file mode 100644index 0000000000..1a5c5e9afe--- /dev/null+++ b/packages/database/supabase/migrations/20260928120657_mount-integration.sql@@ -0,0 +1,7 @@+-- Seed the Mount integration registry row. companyIntegration.id has an FK+-- to integration.id (20240119095150_integrations.sql), so installing the+-- integration fails without this row — the route surfaces the FK violation as+-- a bare "Failed to install integration" with no detail.+INSERT INTO "integration" ("id", "jsonschema")+VALUES ('mount', '{"type": "object", "properties": {}}'::json)+ON CONFLICT ("id") DO NOTHING;diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 8fb7837a19..0ff42a107d 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -25,6 +25,9 @@"./jira.server": "./src/jira/lib/index.server.ts","./linear": "./src/linear/lib/index.ts","./linear.server": "./src/linear/lib/index.server.ts",+ "./mount": "./src/mount/lib/index.ts",+ "./mount.server": "./src/mount/lib/index.server.ts",+ "./mount/hooks.server": "./src/mount/hooks.server.ts","./notifications": "./src/notifications/index.ts","./onshape": "./src/onshape/lib/index.ts","./paperless-parts": "./src/paperless-parts/lib/index.ts",diff --git a/packages/ee/src/hooks.server.ts b/packages/ee/src/hooks.server.tsindex 8070609b0e..4c7ebfc7f2 100644--- a/packages/ee/src/hooks.server.ts+++ b/packages/ee/src/hooks.server.ts@@ -1,6 +1,7 @@import { emailHealthcheck } from "./email/hooks.server";import { jiraHealthcheck } from "./jira/hooks.server";import { linearHealthcheck } from "./linear/hooks.server";+import { mountHealthcheck } from "./mount/hooks.server";import { onshapeOnUninstall } from "./onshape/hooks.server";import {quickbooksOnInstall,@@ -56,6 +57,9 @@ const serverHooks: Record<string, IntegrationServerHooks> = {linear: {onHealthcheck: linearHealthcheck},+ mount: {+ onHealthcheck: mountHealthcheck+ },onshape: {onUninstall: onshapeOnUninstall},diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.tsindex bc5afa25d2..e3b948c94c 100644--- a/packages/ee/src/index.ts+++ b/packages/ee/src/index.ts@@ -1,6 +1,7 @@import { Email } from "./email/config";import { Jira } from "./jira/config";import { Linear } from "./linear/config";+import { Mount } from "./mount/config";import { Onshape } from "./onshape/config";import { PaperlessParts } from "./paperless-parts/config";import { QuickBooks } from "./quickbooks/config";@@ -52,6 +53,7 @@ export const integrations = [Email,Jira,Linear,+ Mount,Onshape,PaperlessParts,QuickBooks,@@ -66,6 +68,7 @@ export const integrations = [export type IntegrationID = (typeof integrations)[number]["id"];export { Jira } from "./jira/config";+export { Mount } from "./mount/config";export { Logo as OnshapeLogo, Onshape } from "./onshape/config";// TODO: export as @carbon/ee/paperlessexport { PaperlessPartsClient } from "./paperless-parts/lib/client";diff --git a/packages/ee/src/integrations/secrets.ts b/packages/ee/src/integrations/secrets.tsindex c125933546..30c616d384 100644--- a/packages/ee/src/integrations/secrets.ts+++ b/packages/ee/src/integrations/secrets.ts@@ -23,6 +23,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";*/export const SECRET_KEYS: Record<string, string[]> = {linear: ["apiKey", "webhookSigningSecret"],+ mount: ["clientSecret"],slack: ["access_token"],jira: ["credentials.accessToken",diff --git a/packages/ee/src/mount/config.tsx b/packages/ee/src/mount/config.tsxnew file mode 100644index 0000000000..05624d8285--- /dev/null+++ b/packages/ee/src/mount/config.tsx@@ -0,0 +1,240 @@+import type { ComponentProps } from "react";+import { z } from "zod";+import { defineIntegration } from "../fns";+import { MOUNT_DEFAULT_BASE_URL } from "./lib/constants";++const MountSettingsSchema = z.object({+ clientId: z.string().min(1),+ // Empty means "keep the existing vaulted secret"; presence enforced at install.+ clientSecret: z.string(),+ baseUrl: z.string().url().default(MOUNT_DEFAULT_BASE_URL),+ tenant: z.string().min(1),+ scope: z.string().optional(),+ // Slug and titles, not ids. Mount never shows a user a UUID: the object+ // definition's slug is in its settings URL, and company types are listed by+ // title. The client resolves both to ids at publish time.+ partDefinitionSlug: z.string().min(1),+ customerTypeTitle: z.string().optional(),+ supplierTypeTitle: z.string().optional()+});++export const Mount = defineIntegration({+ name: "Mount",+ id: "mount",+ active: true,+ category: "Quality",+ logo: Logo,+ setupInstructions: SetupInstructions,+ shortDescription:+ "Publish customers, suppliers, and parts to your Mount quality system.",+ description:+ "Mount is a quality management system, where teams record non-conformances and corrective actions, run audits, and manage risk and compliance. This integration will push data from Carbon to Mount.",+ images: [],+ settingGroups: [+ {+ name: "Connection",+ description: "API access to your Mount tenant"+ },+ {+ name: "Mapping",+ description:+ "Where Carbon records land in Mount. Parts are Objects under a definition you choose; customers and suppliers are Companies distinguished by type."+ }+ ],+ settings: [+ {+ name: "clientId",+ label: "Client ID",+ description:+ "From the API client you created in Mount. Shown at the top of the client, under Client ID.",+ group: "Connection",+ type: "text" as const,+ required: true,+ value: ""+ },+ {+ name: "clientSecret",+ label: "Client secret",+ description:+ "The key Mount showed once when you created the secret. Exchanged for a short-lived access token on every run; never sent as-is.",+ group: "Connection",+ type: "secret" as const,+ required: true,+ value: ""+ },+ {+ name: "tenant",+ label: "Tenant",+ description:+ "Mount configures each tenant separately. A Carbon company connects to exactly one.",+ group: "Connection",+ type: "text" as const,+ required: true,+ value: ""+ },+ {+ name: "scope",+ label: "Domain",+ description:+ "Optional. The domain's identifier or title, e.g. qa or Quality. Selects a domain within the tenant when Mount is partitioned into several.",+ group: "Connection",+ type: "text" as const,+ required: false,+ value: ""+ },+ {+ name: "baseUrl",+ label: "API URL",+ group: "Connection",+ type: "text" as const,+ required: false,+ value: MOUNT_DEFAULT_BASE_URL+ },+ {+ name: "partDefinitionSlug",+ label: "Part definition slug",+ description:+ "Mount has no native part entity, so parts are objects under a definition you create. Use its slug — the last part of its settings URL, e.g. parts.",+ group: "Mapping",+ type: "text" as const,+ required: true,+ value: "parts"+ },+ {+ name: "customerTypeTitle",+ label: "Customer company type",+ description:+ "Optional, but without it published customers appear under All rather than the Customers tab. The type's title, exactly as Mount lists it.",+ group: "Mapping",+ type: "text" as const,+ required: false,+ value: "Customer"+ },+ {+ name: "supplierTypeTitle",+ label: "Supplier company type",+ description:+ "Optional, but without it published suppliers appear under All rather than the Suppliers tab. The type's title, exactly as Mount lists it.",+ group: "Mapping",+ type: "text" as const,+ required: false,+ value: "Supplier"+ }+ ],+ schema: MountSettingsSchema,+ actions: [+ {+ id: "push-customers",+ label: "Push customers",+ description:+ "Send customers Mount does not have yet, or holds out of date, as Companies of the customer type",+ endpoint: "/api/integrations/mount/publish?entityType=customer"+ },+ {+ id: "push-suppliers",+ label: "Push suppliers",+ description:+ "Send suppliers Mount does not have yet, or holds out of date, as Companies of the supplier type",+ endpoint: "/api/integrations/mount/publish?entityType=supplier"+ },+ {+ id: "push-parts",+ label: "Push parts",+ description:+ "Send parts Mount does not have yet, or holds out of date, as Objects under the part definition",+ endpoint: "/api/integrations/mount/publish?entityType=item"+ }+ ]+});++/**+ * Steps verified against Mount's own admin UI, and against the API itself.+ * Member ID is called out because a client with no member is refused on every+ * request with a bare 403, and the integration can only report "unhealthy".+ */+function SetupInstructions() {+ return (+ <>+ <p className="text-sm text-muted-foreground">+ 1. In Mount, go to Settings → API → API Clients and press Create. Give+ the client a name, for example <span className="font-mono">carbon</span>+ .+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 2. On the client, set <strong>Member ID</strong> to a member allowed to+ view and edit companies and objects — every request acts as that member+ and inherits their permissions — and press Save. Leave{" "}+ <strong>Allow direct key auth</strong> off: it applies to Mount's MCP+ endpoint, not the API Carbon uses.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 3. Copy the <strong>Client ID</strong> from the top of the client into+ the field below. Then, under Create secret, name the secret, optionally+ set an expiry, and press Create secret. Copy the key straight away —+ Mount shows it once — and paste it into Client secret.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 4. Tenant is the first part of your Mount web address. At{" "}+ <span className="font-mono">acme.mount.cloud</span> the tenant is{" "}+ <span className="font-mono">acme</span>.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 5. Domain is only needed when your Mount tenant is split into several+ (quality, ESG, information security) and Carbon should work within one+ of them. Enter the domain's title as Mount shows it, for example{" "}+ <span className="font-mono">Quality</span>, or its identifier from the+ address bar. Leave it empty otherwise.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 6. For the part definition, go to Settings → Definitions → Objects.+ Mount has no built-in part entity, so if there is no definition for+ parts, press New to create one. Open it and read the slug from the+ address bar:{" "}+ <span className="font-mono">/settings/definitions/objects/parts</span>{" "}+ means the slug is <span className="font-mono">parts</span>.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ 7. For the company types, go to Settings → Types → Company types and+ copy the titles used for customers and suppliers exactly as shown,+ creating them with New if needed. Without them, published companies+ appear under All but under neither the Customers nor the Suppliers tab.+ </p>+ <p className="mt-3 text-sm text-muted-foreground">+ If the integration reports unhealthy after saving, re-check the Member+ ID in step 2 — a client with no member is refused on every request.+ Saving these settings again re-runs the check immediately; otherwise the+ status refreshes within five minutes.+ </p>+ </>+ );+}++/**+ * Placeholder mark in `currentColor`, matching the other integration logos.+ * Replace with Mount's own asset when they provide one.+ */+function Logo(props: ComponentProps<"svg">) {+ return (+ <svg+ {...props}+ viewBox="0 0 40 40"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ focusable="false"+ >+ <title>Mount</title>+ <path+ d="M2 30.5 14.2 9.2a1.6 1.6 0 0 1 2.8 0l6.1 10.6-4.2 7.3-2.6-4.6-4.7 8.2a1.6 1.6 0 0 1-1.4.8H2Z"+ fill="currentColor"+ fillOpacity="0.55"+ />+ <path+ d="M24.6 14.6a1.6 1.6 0 0 1 2.8 0L38 30.5H17.9a1.6 1.6 0 0 1-1.4-2.4l8.1-13.5Z"+ fill="currentColor"+ />+ </svg>+ );+}++export { Logo };diff --git a/packages/ee/src/mount/hooks.server.ts b/packages/ee/src/mount/hooks.server.tsnew file mode 100644index 0000000000..4b5c543a87--- /dev/null+++ b/packages/ee/src/mount/hooks.server.ts@@ -0,0 +1,21 @@+import { getMountClient } from "./lib/client";++/**+ * Mount has no install-time server state to converge.+ *+ * An earlier revision registered event-system subscriptions here so a write to+ * customer/supplier/item would push immediately. That was wrong twice over:+ * the event queue routes every SYNC record into the accounting sync function,+ * whose payload schema only admits accounting providers — a Mount record would+ * fail the parse for the whole chunk, taking any accounting records batched+ * with it. Delivery is the publish sweep instead (see lib/publish.ts), which+ * needs no subscriptions and is its own retry.+ *+ * If near-real-time publishing is ever wanted, the way in is a new event-system+ * handler type (the path SEARCH, AUDIT and EMBEDDING took), not a SYNC+ * subscription — and the sweep still has to sit underneath it, because a+ * dropped event is otherwise invisible.+ */+export async function mountHealthcheck(companyId: string) {+ return await getMountClient().healthcheck(companyId);+}diff --git a/packages/ee/src/mount/lib/client.ts b/packages/ee/src/mount/lib/client.tsnew file mode 100644index 0000000000..fe8d6f574a--- /dev/null+++ b/packages/ee/src/mount/lib/client.ts@@ -0,0 +1,433 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { getLogger } from "@carbon/logger";+import axios, { type AxiosInstance } from "axios";+import { resolveIntegrationSecrets } from "../../integrations/secrets";+import { MOUNT_API_VERSION, MOUNT_DEFAULT_BASE_URL } from "./constants";+import { getMountIntegration, MOUNT_INTEGRATION_ID } from "./service";+import {+ type MountChange,+ type MountCompany,+ type MountCompanyInput,+ MountCompanySchema,+ type MountCompanyType,+ MountCompanyTypeSchema,+ MountDomainSchema,+ MountNotFoundError,+ type MountObject,+ type MountObjectDefinition,+ MountObjectDefinitionSchema,+ type MountObjectInput,+ MountObjectSchema+} from "./types";++const logger = getLogger("ee", "mount");++type MountSettings = {+ clientId: string;+ clientSecret: string;+ baseUrl?: string;+ tenant: string;+ scope?: string;+};++type CachedToken = { accessToken: string; expiresAt: number };++/**+ * Re-exchange this long before a token actually lapses, so a request never+ * races the expiry it was issued under.+ */+const TOKEN_EXPIRY_MARGIN_MS = 60_000;++/**+ * Mount's OpenAPI spec declares no `securitySchemes` at all, so the shape here+ * comes from its admin UI's own usage instructions: OAuth 2.0 client+ * credentials against `/auth/v2/token`, then a bearer token plus `X-Tenant` on+ * every call. Tenants are configured separately, so one Carbon company maps to+ * one Mount tenant.+ *+ * Mount also offers "direct key auth", sending the client secret itself as the+ * bearer. Do not use it here: that mode is only honoured by Mount's MCP+ * endpoint, and the REST API answers every request with a bare 403 — no body,+ * no explanation — which reads exactly like a permissions problem.+ *+ * The token response is NOT the OAuth-standard shape. It is camelCase with an+ * absolute expiry (`accessToken`, `refreshToken`, `expiresAt`,+ * `refreshExpiresAt`) and carries no `token_type` or `expires_in`.+ *+ * Tokens are cached in memory per company and never persisted. There is no+ * refresh-token handling on purpose: the secret is vaulted, so a new token is+ * always one call away, which avoids the concurrent-rotation problem the+ * accounting OAuth clients carry.+ */+export class MountClient {+ instance: AxiosInstance;+ private tokens = new Map<string, CachedToken>();+ /** Domain setting (identifier or title) -> id, per company. */+ private domainIds = new Map<string, string>();++ constructor() {+ this.instance = axios.create({+ headers: { "Content-Type": "application/json" }+ });+ }++ private async getAccessToken(+ companyId: string,+ settings: MountSettings,+ { force = false }: { force?: boolean } = {}+ ): Promise<string> {+ const cached = this.tokens.get(companyId);+ if (+ !force &&+ cached &&+ cached.expiresAt - TOKEN_EXPIRY_MARGIN_MS > Date.now()+ ) {+ return cached.accessToken;+ }++ const body = new URLSearchParams({+ grant_type: "client_credentials",+ client_id: settings.clientId,+ client_secret: settings.clientSecret+ });++ const response = await this.instance.request<{+ accessToken: string;+ expiresAt: string;+ }>({+ method: "POST",+ baseURL: settings.baseUrl || MOUNT_DEFAULT_BASE_URL,+ url: "/auth/v2/token",+ data: body.toString(),+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ "X-Tenant": settings.tenant+ }+ });++ const { accessToken, expiresAt } = response.data;+ if (!accessToken) {+ throw new Error("Mount token endpoint returned no access token");+ }++ this.tokens.set(companyId, {+ accessToken,+ expiresAt: Date.parse(expiresAt)+ });++ return accessToken;+ }++ /** Drops a company's cached token; the next call re-exchanges. */+ invalidateToken(companyId: string) {+ this.tokens.delete(companyId);+ }++ async getSettings(companyId: string): Promise<MountSettings> {+ const serviceRole = getCarbonServiceRole();+ const { data } = await getMountIntegration(serviceRole, companyId);+ const integration = data?.[0];++ if (!integration) {+ throw new Error("Mount integration not found for company");+ }++ const metadata = (await resolveIntegrationSecrets(+ serviceRole,+ companyId,+ MOUNT_INTEGRATION_ID,+ integration.metadata,+ integration.secretRef+ )) as MountSettings;++ if (!metadata?.clientSecret) {+ throw new Error("Mount integration is missing a client secret");+ }++ if (!metadata?.clientId) {+ throw new Error("Mount integration is missing a client ID");+ }++ return metadata;+ }++ /**+ * `X-Domain-Id` only filters when it carries the domain's id; any other+ * value is silently ignored and the request runs tenant-wide. Users know a+ * domain by its identifier (the `qa` in its URL) or its title, so the+ * setting takes either and is resolved here. An unmatched value fails every+ * request, which surfaces as an unhealthy integration instead of an+ * unfiltered one.+ */+ private async resolveDomainId(+ companyId: string,+ settings: MountSettings+ ): Promise<string | null> {+ const scope = settings.scope?.trim();+ if (!scope) return null;+ if (UUID_PATTERN.test(scope)) return scope;++ const key = `${companyId}:${scope}`;+ const cached = this.domainIds.get(key);+ if (cached) return cached;++ const domains = await this.request<unknown[]>(+ companyId,+ { method: "GET", path: "/Domains" },+ { withDomain: false }+ );+ const wanted = scope.toLowerCase();+ const match = MountDomainSchema.array()+ .parse(domains)+ .find(+ (domain) =>+ domain.identifier?.toLowerCase() === wanted ||+ domain.title.toLowerCase() === wanted+ );++ if (!match) {+ throw new Error(+ `Mount domain "${scope}" not found. Use its identifier or title, as listed in Mount.`+ );+ }++ this.domainIds.set(key, match.id);+ return match.id;+ }++ private async request<T>(+ companyId: string,+ config: {+ method: "GET" | "POST" | "PATCH" | "DELETE";+ path: string;+ params?: Record<string, string | number>;+ data?: unknown;+ },+ {+ retryOnUnauthorized = true,+ withDomain = true+ }: { retryOnUnauthorized?: boolean; withDomain?: boolean } = {}+ ): Promise<T> {+ const settings = await this.getSettings(companyId);+ const accessToken = await this.getAccessToken(companyId, settings);+ const domainId = withDomain+ ? await this.resolveDomainId(companyId, settings)+ : null;++ try {+ const response = await this.instance.request<T>({+ method: config.method,+ baseURL: settings.baseUrl || MOUNT_DEFAULT_BASE_URL,+ url: config.path,+ params: config.params,+ data: config.data,+ headers: {+ Authorization: `Bearer ${accessToken}`,+ // Optional, and defaults to `latest` when omitted — which is exactly+ // how a breaking change arrives unannounced. Always pinned.+ "Api-Version": MOUNT_API_VERSION,+ "X-Tenant": settings.tenant,+ ...(domainId ? { "X-Domain-Id": domainId } : {})+ }+ });++ return response.data;+ } catch (error) {+ // A token revoked or invalidated mid-life reads as 401. Re-exchange once+ // and replay; a second 401 is a real credential problem, not staleness.+ if (+ retryOnUnauthorized &&+ axios.isAxiosError(error) &&+ error.response?.status === 401+ ) {+ this.invalidateToken(companyId);+ return await this.request<T>(companyId, config, {+ retryOnUnauthorized: false,+ withDomain+ });+ }+ throw error;+ }+ }++ async healthcheck(companyId: string) {+ try {+ await this.request(companyId, {+ method: "GET",+ path: "/Companies",+ params: { $top: 1 }+ });+ return true;+ } catch (error) {+ logger.error("Mount healthcheck failed", { companyId, error });+ return false;+ }+ }++ async listObjectDefinitions(+ companyId: string+ ): Promise<MountObjectDefinition[]> {+ const data = await this.request<unknown[]>(companyId, {+ method: "GET",+ path: "/ObjectDefinitions"+ });+ return MountObjectDefinitionSchema.array().parse(data);+ }++ /**+ * Resolve the definition a user named by slug. The slug is what Mount shows+ * them (it is the definition's settings URL); the id is what the write+ * payload needs. Resolved per publish run, not stored, so renaming a+ * definition in Mount does not silently strand the integration.+ */+ async findObjectDefinitionBySlug(+ companyId: string,+ slug: string+ ): Promise<MountObjectDefinition | null> {+ const data = await this.request<unknown[]>(companyId, {+ method: "GET",+ path: "/ObjectDefinitions",+ params: { $filter: `slug eq '${escapeODataString(slug)}'` }+ });+ const [match] = MountObjectDefinitionSchema.array().parse(data);+ return match ?? null;+ }++ /** Company types are listed to users by title; the payload needs the id. */+ async findCompanyTypeByTitle(+ companyId: string,+ title: string+ ): Promise<MountCompanyType | null> {+ const data = await this.request<unknown[]>(companyId, {+ method: "GET",+ path: "/CompanyTypes",+ params: { $filter: `title eq '${escapeODataString(title)}'` }+ });+ const [match] = MountCompanyTypeSchema.array().parse(data);+ return match ?? null;+ }++ async listCompanyTypes(companyId: string): Promise<MountCompanyType[]> {+ const data = await this.request<unknown[]>(companyId, {+ method: "GET",+ path: "/CompanyTypes"+ });+ return MountCompanyTypeSchema.array().parse(data);+ }++ /**+ * `identifier` is not enforced unique by Mount, so this can legitimately+ * return more than one row. The caller treats >1 as ambiguous rather than+ * picking one — silently patching the wrong record is worse than failing.+ */+ async findCompaniesByIdentifier(+ companyId: string,+ identifier: string+ ): Promise<MountCompany[]> {+ const data = await this.request<unknown[]>(companyId, {+ method: "GET",+ path: "/Companies",+ params: { $filter: `identifier eq '${escapeODataString(identifier)}'` }+ });+ return MountCompanySchema.array().parse(data);+ }++ async createCompany(+ companyId: string,+ input: MountCompanyInput+ ): Promise<MountCompany> {+ const data = await this.request<unknown>(companyId, {+ method: "POST",+ path: "/Companies",+ data: input+ });+ return MountCompanySchema.parse(data);+ }++ async updateCompany(+ companyId: string,+ mountId: string,+ input: Partial<MountCompanyInput>+ ): Promise<MountChange[]> {+ return await this.patch(companyId, "Companies", mountId, input);+ }++ async findObjectsByIdentifier(+ companyId: string,+ definitionId: string,+ identifier: string+ ): Promise<MountObject[]> {+ const data = await this.request<unknown[]>(companyId, {+ method: "GET",+ path: "/Objects",+ params: {+ $filter: `definitionId eq ${definitionId} and identifier eq '${escapeODataString(+ identifier+ )}'`+ }+ });+ return MountObjectSchema.array().parse(data);+ }++ async createObject(+ companyId: string,+ input: MountObjectInput+ ): Promise<MountObject> {+ const data = await this.request<unknown>(companyId, {+ method: "POST",+ path: "/Objects",+ data: input+ });+ return MountObjectSchema.parse(data);+ }++ async updateObject(+ companyId: string,+ mountId: string,+ input: Partial<MountObjectInput>+ ): Promise<MountChange[]> {+ return await this.patch(companyId, "Objects", mountId, input);+ }++ /**+ * PATCH answers with the list of changed fields, not the record, so there+ * is nothing to parse into a Company or Object. A 404 means the record was+ * deleted in Mount, which the caller handles by publishing it again.+ */+ private async patch(+ companyId: string,+ collection: "Companies" | "Objects",+ mountId: string,+ input: unknown+ ): Promise<MountChange[]> {+ try {+ return await this.request<MountChange[]>(companyId, {+ method: "PATCH",+ path: `/${collection}/${mountId}`,+ data: input+ });+ } catch (error) {+ if (axios.isAxiosError(error) && error.response?.status === 404) {+ throw new MountNotFoundError(collection, mountId);+ }+ throw error;+ }+ }+}++const UUID_PATTERN =+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** OData string literals escape a single quote by doubling it. */+export function escapeODataString(value: string) {+ return value.replace(/'/g, "''");+}++let mountClient: MountClient | null = null;++export function getMountClient() {+ if (!mountClient) {+ mountClient = new MountClient();+ }+ return mountClient;+}diff --git a/packages/ee/src/mount/lib/constants.ts b/packages/ee/src/mount/lib/constants.tsnew file mode 100644index 0000000000..75a991b54a--- /dev/null+++ b/packages/ee/src/mount/lib/constants.ts@@ -0,0 +1,18 @@+/**+ * Values shared by the integration config (bundled for BOTH client and+ * server) and the API client (server-only). They live here, free of imports,+ * because anything `config.tsx` reaches must be safe to serve to the browser —+ * importing these from `client.ts` pulled `@carbon/auth/client.server` into the+ * client bundle, Vite refused to serve it, and the whole app stopped hydrating.+ */++export const MOUNT_DEFAULT_BASE_URL = "https://api.mount.cloud";++/**+ * Mount versions its API by date. Omitting the header defaults to `latest`,+ * so this is always sent. Bumping it is a breaking-change review:+ * 2026-04-01 -> 2026-06-01 already changed the update payload shape.+ */+export const MOUNT_API_VERSION = "2026-06-01";++export const MOUNT_INTEGRATION_ID = "mount";diff --git a/packages/ee/src/mount/lib/index.server.ts b/packages/ee/src/mount/lib/index.server.tsnew file mode 100644index 0000000000..5e47203c53--- /dev/null+++ b/packages/ee/src/mount/lib/index.server.ts@@ -0,0 +1,9 @@+export * from "./client";+export * from "./constants";+export * from "./mappers";+export * from "./publish";+export * from "./push";+export * from "./run";+export * from "./service";+export * from "./source";+export * from "./types";diff --git a/packages/ee/src/mount/lib/index.ts b/packages/ee/src/mount/lib/index.tsnew file mode 100644index 0000000000..dcf9aac647--- /dev/null+++ b/packages/ee/src/mount/lib/index.ts@@ -0,0 +1,3 @@+export * from "./constants";+export * from "./mappers";+export * from "./types";diff --git a/packages/ee/src/mount/lib/mappers.ts b/packages/ee/src/mount/lib/mappers.tsnew file mode 100644index 0000000000..9382dab7b9--- /dev/null+++ b/packages/ee/src/mount/lib/mappers.ts@@ -0,0 +1,100 @@+import type { MountCompanyInput, MountObjectInput } from "./types";++/**+ * Carbon is the master for every field below. Mount holds no field that Carbon+ * does not, so the mapping is one-way by construction — nothing here reads a+ * Mount value back.+ *+ * Every record publishes, active or not. A non-conformance raised today can be+ * about a part discontinued last year, and the handler still has to select it;+ * withholding inactive records would leave a part that exists in Carbon,+ * was never published, and cannot be picked in Mount. Nothing is ever removed+ * from Mount either, so filtering on the way in is the+ * only thing that could create that gap.+ *+ * PENDING DECISION — status. Mount exposes `statusId` on both write payloads,+ * pointing at a `CompanyStatus`/`ObjectStatus` record whose `systemStatus` is+ * one of draft/published/archived (CompanyStatus also carries an `unavailable`+ * flag). Mapping Carbon's inactive records onto an archived Mount status would+ * let Mount grey them out or drop them from pickers instead of listing them+ * alongside live parts. Deliberately unset for now: it needs a per-tenant+ * status id in settings, and Carbon's three shapes (customer status rows,+ * the supplier status enum, item.active) do not map one-to-one onto it.+ * Additive whenever we decide — a PATCH can set `statusId` on records already+ * published, so nothing has to be re-pushed.+ */++export type CarbonCompanyRecord = {+ readableId: string | null;+ name: string;+ taxId?: string | null;+ vatNumber?: string | null;+ website?: string | null;+};++export type CarbonItemRecord = {+ readableId: string | null;+ name: string;+};++export class MissingIdentifierError extends Error {+ constructor(entity: string) {+ super(+ `${entity} has no readableId; Mount needs a stable identifier to match on`+ );+ this.name = "MissingIdentifierError";+ }+}++export function mapCustomerToMountCompany(+ customer: CarbonCompanyRecord,+ typeId?: string | null+): MountCompanyInput {+ if (!customer.readableId) throw new MissingIdentifierError("Customer");++ return {+ identifier: customer.readableId,+ name: customer.name,+ // Carbon keeps one `taxId` per party; for EU entities that is the+ // registration number, with VAT recorded separately.+ organizationNumber: customer.taxId ?? null,+ vatNumber: customer.vatNumber ?? null,+ website: customer.website ?? null,+ typeId: typeId ?? null+ };+}++export function mapSupplierToMountCompany(+ supplier: CarbonCompanyRecord,+ typeId?: string | null+): MountCompanyInput {+ if (!supplier.readableId) throw new MissingIdentifierError("Supplier");++ return {+ identifier: supplier.readableId,+ name: supplier.name,+ organizationNumber: supplier.taxId ?? null,+ vatNumber: supplier.vatNumber ?? null,+ website: supplier.website ?? null,+ typeId: typeId ?? null+ };+}++/**+ * Part number -> `identifier`, part name -> `title`. Mount generates an+ * identifier from the definition's prefix when one is not supplied, so passing+ * Carbon's part number explicitly is what keeps the two sides legible to a+ * quality handler.+ */+export function mapItemToMountObject(+ item: CarbonItemRecord,+ definitionId: string+): MountObjectInput {+ if (!item.readableId) throw new MissingIdentifierError("Item");++ return {+ identifier: item.readableId,+ title: item.name,+ definitionId+ };+}diff --git a/packages/ee/src/mount/lib/publish.test.ts b/packages/ee/src/mount/lib/publish.test.tsnew file mode 100644index 0000000000..638f1f693a--- /dev/null+++ b/packages/ee/src/mount/lib/publish.test.ts@@ -0,0 +1,271 @@+import { describe, expect, it } from "vitest";+import {+ type MountPublishSource,+ type PublishablePart,+ publishEntityType+} from "./publish";+import type { MountApiPort, MountMappingPort } from "./push";+import {+ type MountCompany,+ MountNotFoundError,+ type MountObject+} from "./types";++const COMPANY_ID = "co_1";+const PART_DEFINITION = "def_part";++function createFakeMount(overrides: Partial<MountApiPort> = {}) {+ const objects: MountObject[] = [];+ const companies: MountCompany[] = [];+ let next = 0;++ const api: MountApiPort = {+ async findCompaniesByIdentifier(_c, identifier) {+ return companies.filter((c) => c.identifier === identifier);+ },+ async createCompany(_c, input) {+ const created = { ...input, id: `cmp_${++next}` };+ companies.push(created);+ return created;+ },+ async updateCompany(_c, mountId, input) {+ const existing = companies.find((c) => c.id === mountId);+ if (!existing) throw new MountNotFoundError("record", mountId);+ Object.assign(existing, input);+ // Mount answers a PATCH with the changed fields, not the record.+ return [];+ },+ async findObjectsByIdentifier(_c, definitionId, identifier) {+ return objects.filter(+ (o) => o.definitionId === definitionId && o.identifier === identifier+ );+ },+ async createObject(_c, input) {+ const created = { ...input, id: `obj_${++next}` };+ objects.push(created);+ return created;+ },+ async updateObject(_c, mountId, input) {+ const existing = objects.find((o) => o.id === mountId);+ if (!existing) throw new MountNotFoundError("record", mountId);+ Object.assign(existing, input);+ // Mount answers a PATCH with the changed fields, not the record.+ return [];+ },+ ...overrides+ };++ return { api, objects, companies };+}++function createFakeMappings() {+ const rows = new Map<string, string>();+ const mappings: MountMappingPort = {+ async getExternalId(entityType, entityId, integration) {+ return rows.get(`${integration}:${entityType}:${entityId}`) ?? null;+ },+ async link(entityType, entityId, integration, externalId) {+ rows.set(`${integration}:${entityType}:${entityId}`, externalId);+ }+ };+ return { mappings, rows };+}++/** Mirrors the real source's ordering: deferred records sort last. */+function partSource(parts: PublishablePart[]): MountPublishSource {+ return {+ async listStale(_entityType, limit, deferIds = []) {+ const deferred = new Set(deferIds);+ return [+ ...parts.filter((p) => !deferred.has(p.id)),+ ...parts.filter((p) => deferred.has(p.id))+ ].slice(0, limit);+ }+ };+}++function failingOn(identifiers: string[]) {+ return createFakeMount({+ async createObject(_c, input) {+ if (identifiers.includes(input.identifier)) throw new Error("rejected");+ return { ...input, id: `obj_${input.identifier}` };+ }+ });+}++describe("publishEntityType", () => {+ it("refuses parts with no object definition instead of inventing one", async () => {+ const { api, objects } = createFakeMount();+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource([{ id: "i1", readableId: "P-1", name: "Bracket" }]),+ mappings,+ api,+ COMPANY_ID,+ "item",+ {}+ );++ expect(summary.failed).toHaveLength(1);+ expect(summary.failed[0]?.reason).toContain("part object definition");+ expect(objects).toHaveLength(0);+ });++ it("reports more when the cap is hit, without publishing past it", async () => {+ const { api, objects } = createFakeMount();+ const { mappings } = createFakeMappings();++ const parts: PublishablePart[] = Array.from({ length: 5 }, (_, i) => ({+ id: `i${i}`,+ readableId: `P-${i}`,+ name: `Part ${i}`+ }));++ const summary = await publishEntityType(+ partSource(parts),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION },+ 3+ );++ expect(summary.created).toBe(3);+ expect(summary.more).toBe(true);+ expect(objects).toHaveLength(3);+ });++ it("keeps going after one record fails, and names the one that did", async () => {+ const { api, objects } = createFakeMount({+ async createObject(_c, input) {+ if (input.identifier === "P-2") throw new Error("Mount said no");+ return { ...input, id: `obj_${input.identifier}` };+ }+ });+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource([+ { id: "i1", readableId: "P-1", name: "One" },+ { id: "i2", readableId: "P-2", name: "Two" },+ { id: "i3", readableId: "P-3", name: "Three" }+ ]),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION }+ );++ expect(summary.created).toBe(2);+ expect(summary.failed).toEqual([+ { entityId: "i2", reason: "Mount said no" }+ ]);+ expect(objects).toHaveLength(0); // the overridden create does not record+ });++ it("records a record with no identifier as failed rather than throwing", async () => {+ const { api } = createFakeMount();+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource([{ id: "i1", readableId: null, name: "Nameless" }]),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION }+ );++ expect(summary.created).toBe(0);+ expect(summary.failed[0]?.entityId).toBe("i1");+ expect(summary.failed[0]?.reason).toContain("readableId");+ });++ describe("records that keep failing", () => {+ const parts: PublishablePart[] = Array.from({ length: 5 }, (_, i) => ({+ id: `i${i}`,+ readableId: `P-${i}`,+ name: `Part ${i}`+ }));++ it("defers this run's failures to the next run", async () => {+ const { api } = failingOn(["P-0"]);+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource(parts),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION }+ );++ expect(summary.deferred).toEqual(["i0"]);+ });++ it("spends the cap on fresh records before retrying deferred ones", async () => {+ const { api } = failingOn(["P-0", "P-1"]);+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource(parts),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION },+ 2,+ ["i0", "i1"]+ );++ expect(summary.created).toBe(2);+ expect(summary.failed).toHaveLength(0);+ expect(summary.more).toBe(true); // i4 is fresh and did not fit+ expect(summary.deferred.sort()).toEqual(["i0", "i1"]);+ });++ it("does not report more when only deferred records remain", async () => {+ const { api } = failingOn(["P-0", "P-1"]);+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource(parts),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION },+ 4,+ ["i0", "i1"]+ );++ expect(summary.created).toBe(3);+ expect(summary.failed).toEqual([{ entityId: "i0", reason: "rejected" }]);+ expect(summary.more).toBe(false);+ expect(summary.deferred.sort()).toEqual(["i0", "i1"]);+ });++ it("drops a deferred record once it publishes", async () => {+ const { api } = createFakeMount();+ const { mappings } = createFakeMappings();++ const summary = await publishEntityType(+ partSource(parts),+ mappings,+ api,+ COMPANY_ID,+ "item",+ { partDefinitionId: PART_DEFINITION },+ 10,+ ["i0"]+ );++ expect(summary.created).toBe(5);+ expect(summary.deferred).toEqual([]);+ });+ });+});diff --git a/packages/ee/src/mount/lib/publish.ts b/packages/ee/src/mount/lib/publish.tsnew file mode 100644index 0000000000..aaff316b9d--- /dev/null+++ b/packages/ee/src/mount/lib/publish.ts@@ -0,0 +1,223 @@+import {+ type CarbonCompanyRecord,+ type CarbonItemRecord,+ MissingIdentifierError,+ mapCustomerToMountCompany,+ mapItemToMountObject,+ mapSupplierToMountCompany+} from "./mappers";+import {+ type MountApiPort,+ type MountMappingPort,+ type PushOutcome,+ pushCompanyToMount,+ pushItemToMount+} from "./push";+import { MOUNT_INTEGRATION_ID } from "./service";+import type { MountEntityType } from "./types";++/**+ * The publish sweep: find Carbon records Mount does not have (or has stale),+ * and push them one at a time.+ *+ * This is deliberately the WHOLE delivery mechanism rather than a repair pass+ * behind an event stream. A record that fails is simply still stale on the+ * next run, so the sweep is its own retry and there is no operation ledger to+ * keep truthful. Mount documents no rate limit — the spec has no 429, no+ * Retry-After and in fact no non-200 response at all — so pushing serially+ * under a per-run cap keeps the call rate ours to control rather than a+ * function of how busy the shop floor is.+ *+ * Today it is driven by the buttons on the integration's detail page. A cron+ * is a second caller of this same function, per active integration.+ */++export type PublishableCustomer = CarbonCompanyRecord & { id: string };+export type PublishableSupplier = CarbonCompanyRecord & { id: string };+export type PublishablePart = CarbonItemRecord & { id: string };++export type MountPublishSource = {+ /**+ * Carbon records of this type that are missing from Mount or changed since+ * they were last published. Ordered oldest-change first so a capped run+ * always makes progress instead of re-reading the same head, with+ * `deferIds` after everything else.+ */+ listStale(+ entityType: MountEntityType,+ limit: number,+ deferIds?: string[]+ ): Promise<+ Array<PublishableCustomer | PublishableSupplier | PublishablePart>+ >;+};++export type MountPublishSettings = {+ partDefinitionId?: string | null;+ customerTypeId?: string | null;+ supplierTypeId?: string | null;+};++export type MountPublishSummary = {+ entityType: MountEntityType;+ created: number;+ updated: number;+ /** Identifier matched more than one Mount record; a person must resolve it. */+ ambiguous: Array<{ entityId: string; identifier: string; matches: number }>;+ /** Record could not be mapped or the push threw. */+ failed: Array<{ entityId: string; reason: string }>;+ /** True when the cap was hit and records not already deferred remain. */+ more: boolean;+ /**+ * Records to sort last on the next run: this run's failures and ambiguous+ * matches, plus earlier ones the cap kept this run from reaching. Without+ * it a record that can never publish stays stale, sorts first by age, and+ * takes a slot in every run ahead of records that would succeed.+ */+ deferred: string[];+};++/** Records per run. A cap keeps one button press bounded and re-runnable. */+export const MOUNT_PUBLISH_BATCH_SIZE = 200;++export async function publishEntityType(+ source: MountPublishSource,+ mappings: MountMappingPort,+ api: MountApiPort,+ companyId: string,+ entityType: MountEntityType,+ settings: MountPublishSettings,+ limit: number = MOUNT_PUBLISH_BATCH_SIZE,+ deferIds: string[] = []+): Promise<MountPublishSummary> {+ const summary: MountPublishSummary = {+ entityType,+ created: 0,+ updated: 0,+ ambiguous: [],+ failed: [],+ more: false,+ deferred: deferIds+ };++ if (entityType === "item" && !settings.partDefinitionId) {+ // Without a definition there is no register to write into. Fail the run+ // rather than creating one — planting a register in someone's tenant is+ // not a side effect of pressing Publish.+ summary.failed.push({+ entityId: "*",+ reason:+ "No Mount part object definition configured. Set one in the integration settings."+ });+ return summary;+ }++ const records = await source.listStale(entityType, limit + 1, deferIds);+ const batch = records.slice(0, limit);+ const deferSet = new Set(deferIds);+ const overflow = records[limit];++ // Deferred records sort last, so a deferred record in the overflow slot+ // means everything else fit. Reporting `more` then would ask the user to+ // push again for records that are only going to fail again.+ summary.more = overflow !== undefined && !deferSet.has(overflow.id);++ for (const record of batch) {+ try {+ const outcome = await publishOne(+ api,+ mappings,+ companyId,+ entityType,+ record,+ settings+ );++ if (outcome.status === "created") summary.created++;+ else if (outcome.status === "updated") summary.updated++;+ else if (outcome.status === "ambiguous") {+ summary.ambiguous.push({+ entityId: record.id,+ identifier: outcome.identifier,+ matches: outcome.matches+ });+ }+ } catch (error) {+ // One bad record must not end the run — the other 199 are fine, and a+ // record that failed is still stale next time.+ summary.failed.push({+ entityId: record.id,+ reason:+ error instanceof MissingIdentifierError+ ? error.message+ : error instanceof Error+ ? error.message+ : "Unknown error"+ });+ }+ }++ const blocked = new Set([+ ...summary.failed.map((f) => f.entityId).filter((id) => id !== "*"),+ ...summary.ambiguous.map((a) => a.entityId)+ ]);++ // When the whole stale set fit in this run, anything not re-failed has+ // published or stopped being stale. Otherwise carry forward the deferred+ // records the cap kept this run from reaching.+ if (overflow !== undefined) {+ const attempted = new Set(batch.map((record) => record.id));+ for (const id of deferIds) {+ if (!attempted.has(id)) blocked.add(id);+ }+ }++ summary.deferred = [...blocked];++ return summary;+}++async function publishOne(+ api: MountApiPort,+ mappings: MountMappingPort,+ companyId: string,+ entityType: MountEntityType,+ record: PublishableCustomer | PublishableSupplier | PublishablePart,+ settings: MountPublishSettings+): Promise<PushOutcome> {+ if (entityType === "item") {+ return await pushItemToMount(+ mappings,+ api,+ companyId,+ record.id,+ mapItemToMountObject(+ record as PublishablePart,+ // Checked by the caller before the loop.+ settings.partDefinitionId as string+ )+ );+ }++ const input =+ entityType === "customer"+ ? mapCustomerToMountCompany(+ record as PublishableCustomer,+ settings.customerTypeId+ )+ : mapSupplierToMountCompany(+ record as PublishableSupplier,+ settings.supplierTypeId+ );++ return await pushCompanyToMount(+ mappings,+ api,+ companyId,+ entityType,+ record.id,+ input+ );+}++export { MOUNT_INTEGRATION_ID };diff --git a/packages/ee/src/mount/lib/push.test.ts b/packages/ee/src/mount/lib/push.test.tsnew file mode 100644index 0000000000..8edacec55c--- /dev/null+++ b/packages/ee/src/mount/lib/push.test.ts@@ -0,0 +1,271 @@+import { describe, expect, it } from "vitest";+import { mapItemToMountObject, mapSupplierToMountCompany } from "./mappers";+import {+ type MountApiPort,+ type MountMappingPort,+ pushCompanyToMount,+ pushItemToMount+} from "./push";+import {+ type MountCompany,+ MountNotFoundError,+ type MountObject+} from "./types";++const COMPANY_ID = "co_1";+const PART_DEFINITION = "def_part";++/**+ * An in-memory stand-in for Mount that behaves the way the real API does,+ * including the part that matters most here: `identifier` is NOT unique, so a+ * second create with the same identifier succeeds and leaves two rows.+ */+function createFakeMount() {+ const companies: MountCompany[] = [];+ const objects: MountObject[] = [];+ let next = 0;+ const id = (prefix: string) => `${prefix}_${++next}`;++ const api: MountApiPort = {+ async findCompaniesByIdentifier(_companyId, identifier) {+ return companies.filter((c) => c.identifier === identifier);+ },+ async createCompany(_companyId, input) {+ const created: MountCompany = { ...input, id: id("cmp") };+ companies.push(created);+ return created;+ },+ async updateCompany(_companyId, mountId, input) {+ const existing = companies.find((c) => c.id === mountId);+ if (!existing) throw new MountNotFoundError("record", mountId);+ Object.assign(existing, input);+ // Mount answers a PATCH with the changed fields, not the record.+ return [];+ },+ async findObjectsByIdentifier(_companyId, definitionId, identifier) {+ return objects.filter(+ (o) => o.definitionId === definitionId && o.identifier === identifier+ );+ },+ async createObject(_companyId, input) {+ const created: MountObject = { ...input, id: id("obj") };+ objects.push(created);+ return created;+ },+ async updateObject(_companyId, mountId, input) {+ const existing = objects.find((o) => o.id === mountId);+ if (!existing) throw new MountNotFoundError("record", mountId);+ Object.assign(existing, input);+ // Mount answers a PATCH with the changed fields, not the record.+ return [];+ }+ };++ return { api, companies, objects };+}++function createFakeMappings() {+ const rows = new Map<string, string>();+ const key = (entityType: string, entityId: string, integration: string) =>+ `${integration}:${entityType}:${entityId}`;++ const mappings: MountMappingPort = {+ async getExternalId(entityType, entityId, integration) {+ return rows.get(key(entityType, entityId, integration)) ?? null;+ },+ async link(entityType, entityId, integration, externalId) {+ rows.set(key(entityType, entityId, integration), externalId);+ }+ };++ return { mappings, rows };+}++describe("pushCompanyToMount", () => {+ it("creates once, then updates the same record on re-push", async () => {+ const { api, companies } = createFakeMount();+ const { mappings } = createFakeMappings();++ const input = mapSupplierToMountCompany({+ readableId: "SUP000123",+ name: "Northline Metals",+ taxId: "912345671"+ });++ const first = await pushCompanyToMount(+ mappings,+ api,+ COMPANY_ID,+ "supplier",+ "sup_1",+ input+ );+ const second = await pushCompanyToMount(+ mappings,+ api,+ COMPANY_ID,+ "supplier",+ "sup_1",+ { ...input, name: "Northline Metals AS" }+ );++ expect(first.status).toBe("created");+ expect(second.status).toBe("updated");+ expect(companies).toHaveLength(1);+ expect(companies[0]?.name).toBe("Northline Metals AS");+ });++ it("publishes again when the mapped record was deleted in Mount", async () => {+ const { api, companies } = createFakeMount();+ const { mappings } = createFakeMappings();++ const input = mapSupplierToMountCompany({+ readableId: "SUP000124",+ name: "Fjord Fasteners"+ });++ const first = await pushCompanyToMount(+ mappings,+ api,+ COMPANY_ID,+ "supplier",+ "sup_2",+ input+ );+ companies.splice(0, companies.length);++ const second = await pushCompanyToMount(+ mappings,+ api,+ COMPANY_ID,+ "supplier",+ "sup_2",+ input+ );++ expect(second.status).toBe("created");+ expect(second).not.toEqual(first);+ expect(companies).toHaveLength(1);+ expect(await mappings.getExternalId("supplier", "sup_2", "mount")).toBe(+ companies[0]?.id+ );+ });++ it("adopts a record created by hand in Mount instead of duplicating it", async () => {+ const { api, companies } = createFakeMount();+ const { mappings, rows } = createFakeMappings();++ await api.createCompany(COMPANY_ID, {+ identifier: "CUS000007",+ name: "Typed in by a quality lead"+ });++ const outcome = await pushCompanyToMount(+ mappings,+ api,+ COMPANY_ID,+ "customer",+ "cust_1",+ mapSupplierToMountCompany({+ readableId: "CUS000007",+ name: "Nordvik Transport"+ })+ );++ expect(outcome.status).toBe("updated");+ expect(companies).toHaveLength(1);+ expect(companies[0]?.name).toBe("Nordvik Transport");+ expect(rows.size).toBe(1);+ });++ it("refuses to guess when Mount holds two records with the identifier", async () => {+ const { api, companies } = createFakeMount();+ const { mappings, rows } = createFakeMappings();++ await api.createCompany(COMPANY_ID, {+ identifier: "SUP000123",+ name: "One"+ });+ await api.createCompany(COMPANY_ID, {+ identifier: "SUP000123",+ name: "Two"+ });++ const outcome = await pushCompanyToMount(+ mappings,+ api,+ COMPANY_ID,+ "supplier",+ "sup_1",+ mapSupplierToMountCompany({+ readableId: "SUP000123",+ name: "Northline Metals"+ })+ );++ expect(outcome).toEqual({+ status: "ambiguous",+ identifier: "SUP000123",+ matches: 2+ });+ // Nothing was written, and nothing was mapped.+ expect(companies.map((c) => c.name)).toEqual(["One", "Two"]);+ expect(rows.size).toBe(0);+ });+});++describe("pushItemToMount", () => {+ it("writes the part number as identifier and the part name as title", async () => {+ const { api, objects } = createFakeMount();+ const { mappings } = createFakeMappings();++ await pushItemToMount(+ mappings,+ api,+ COMPANY_ID,+ "item_1",+ mapItemToMountObject(+ { readableId: "P-1042", name: "Left Wing Bracket" },+ PART_DEFINITION+ )+ );++ expect(objects).toEqual([+ {+ id: "obj_1",+ identifier: "P-1042",+ title: "Left Wing Bracket",+ definitionId: PART_DEFINITION+ }+ ]);+ });++ it("scopes the adopt lookup to the part definition", async () => {+ const { api, objects } = createFakeMount();+ const { mappings } = createFakeMappings();++ // An object in a DIFFERENT register that happens to share the identifier.+ await api.createObject(COMPANY_ID, {+ identifier: "P-1042",+ title: "An equipment record",+ definitionId: "def_equipment"+ });++ const outcome = await pushItemToMount(+ mappings,+ api,+ COMPANY_ID,+ "item_1",+ mapItemToMountObject(+ { readableId: "P-1042", name: "Left Wing Bracket" },+ PART_DEFINITION+ )+ );++ expect(outcome.status).toBe("created");+ expect(objects).toHaveLength(2);+ expect(objects.find((o) => o.definitionId === "def_equipment")?.title).toBe(+ "An equipment record"+ );+ });+});diff --git a/packages/ee/src/mount/lib/push.ts b/packages/ee/src/mount/lib/push.tsnew file mode 100644index 0000000000..4ec40b7a7c--- /dev/null+++ b/packages/ee/src/mount/lib/push.ts@@ -0,0 +1,203 @@+import { MOUNT_INTEGRATION_ID } from "./service";+import {+ type MountChange,+ type MountCompany,+ type MountCompanyInput,+ type MountEntityType,+ MountNotFoundError,+ type MountObject,+ type MountObjectInput+} from "./types";++/**+ * The slice of `ExternalIntegrationMappingService` a push needs. Mount has no+ * external-id field, no idempotency key and no ETag, so this table is the only+ * record of which Mount row a Carbon record owns.+ */+export type MountMappingPort = {+ getExternalId(+ entityType: string,+ entityId: string,+ integration: string+ ): Promise<string | null>;+ link(+ entityType: string,+ entityId: string,+ integration: string,+ externalId: string,+ options?: {+ metadata?: Record<string, unknown>;+ allowDuplicateExternalId?: boolean;+ }+ ): Promise<void>;+};++/** The slice of `MountClient` a push needs. */+export type MountApiPort = {+ findCompaniesByIdentifier(+ companyId: string,+ identifier: string+ ): Promise<MountCompany[]>;+ createCompany(+ companyId: string,+ input: MountCompanyInput+ ): Promise<MountCompany>;+ updateCompany(+ companyId: string,+ mountId: string,+ input: Partial<MountCompanyInput>+ ): Promise<MountChange[]>;+ findObjectsByIdentifier(+ companyId: string,+ definitionId: string,+ identifier: string+ ): Promise<MountObject[]>;+ createObject(+ companyId: string,+ input: MountObjectInput+ ): Promise<MountObject>;+ updateObject(+ companyId: string,+ mountId: string,+ input: Partial<MountObjectInput>+ ): Promise<MountChange[]>;+};++export type PushOutcome =+ | { status: "created"; externalId: string }+ | { status: "updated"; externalId: string }+ | { status: "ambiguous"; identifier: string; matches: number };++/**+ * Resolution order for every push: the mapping row first, then a lookup by+ * identifier to adopt a record someone created by hand, then create. Mount+ * accepts duplicate identifiers, so more than one match is reported rather+ * than resolved — patching an arbitrary one of two records is worse than+ * failing loudly.+ *+ * A mapped record that was deleted in Mount falls through to the lookup and+ * is published again: Carbon is the master, so Mount does not get to drop it.+ */+export async function pushCompanyToMount(+ mappings: MountMappingPort,+ api: MountApiPort,+ companyId: string,+ entityType: Extract<MountEntityType, "customer" | "supplier">,+ entityId: string,+ input: MountCompanyInput+): Promise<PushOutcome> {+ const externalId = await mappings.getExternalId(+ entityType,+ entityId,+ MOUNT_INTEGRATION_ID+ );++ if (externalId) {+ try {+ await api.updateCompany(companyId, externalId, input);+ await link(mappings, entityType, entityId, externalId, input);+ return { status: "updated", externalId };+ } catch (error) {+ if (!(error instanceof MountNotFoundError)) throw error;+ }+ }++ const existing = await api.findCompaniesByIdentifier(+ companyId,+ input.identifier+ );++ if (existing.length > 1) {+ return {+ status: "ambiguous",+ identifier: input.identifier,+ matches: existing.length+ };+ }++ const [match] = existing;++ let mountId: string;+ if (match) {+ await api.updateCompany(companyId, match.id, input);+ mountId = match.id;+ } else {+ mountId = (await api.createCompany(companyId, input)).id;+ }++ await link(mappings, entityType, entityId, mountId, input);++ return { status: match ? "updated" : "created", externalId: mountId };+}++export async function pushItemToMount(+ mappings: MountMappingPort,+ api: MountApiPort,+ companyId: string,+ entityId: string,+ input: MountObjectInput+): Promise<PushOutcome> {+ const externalId = await mappings.getExternalId(+ "item",+ entityId,+ MOUNT_INTEGRATION_ID+ );++ if (externalId) {+ try {+ await api.updateObject(companyId, externalId, input);+ await link(mappings, "item", entityId, externalId, input);+ return { status: "updated", externalId };+ } catch (error) {+ if (!(error instanceof MountNotFoundError)) throw error;+ }+ }++ const existing = await api.findObjectsByIdentifier(+ companyId,+ input.definitionId,+ input.identifier+ );++ if (existing.length > 1) {+ return {+ status: "ambiguous",+ identifier: input.identifier,+ matches: existing.length+ };+ }++ const [match] = existing;++ let mountId: string;+ if (match) {+ await api.updateObject(companyId, match.id, input);+ mountId = match.id;+ } else {+ mountId = (await api.createObject(companyId, input)).id;+ }++ await link(mappings, "item", entityId, mountId, input);++ return { status: match ? "updated" : "created", externalId: mountId };+}++/**+ * 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.+ */+async function link(+ mappings: MountMappingPort,+ entityType: MountEntityType,+ entityId: string,+ mountId: string,+ sent: MountCompanyInput | MountObjectInput+) {+ await mappings.link(entityType, entityId, MOUNT_INTEGRATION_ID, mountId, {+ metadata: sent,+ // 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.+ allowDuplicateExternalId: entityType === "item"+ });+}diff --git a/packages/ee/src/mount/lib/run.ts b/packages/ee/src/mount/lib/run.tsnew file mode 100644index 0000000000..13e6a55ecc--- /dev/null+++ b/packages/ee/src/mount/lib/run.ts@@ -0,0 +1,137 @@+import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import type { SupabaseClient } from "@supabase/supabase-js";+import { createMappingService } from "../../accounting/core/external-mapping";+import { getMountClient } from "./client";+import { MOUNT_INTEGRATION_ID } from "./constants";+import {+ MOUNT_PUBLISH_BATCH_SIZE,+ type MountPublishSettings,+ type MountPublishSummary,+ publishEntityType+} from "./publish";+import { getMountIntegration } from "./service";+import { createMountPublishSource } from "./source";+import type { MountEntityType } from "./types";++/**+ * One publish run: resolve settings, sweep, record the outcome. The+ * `mount-publish` job calls it for the integration's push actions, and a cron+ * would call it the same way.+ */+export async function runMountPublish({+ serviceRole,+ db,+ companyId,+ entityTypes,+ limit = MOUNT_PUBLISH_BATCH_SIZE+}: {+ serviceRole: SupabaseClient<Database>;+ db: Kysely<KyselyDatabase>;+ companyId: string;+ entityTypes: MountEntityType[];+ limit?: number;+}): Promise<+ { status: "inactive" } | { status: "ran"; summaries: MountPublishSummary[] }+> {+ const integration = await getMountIntegration(serviceRole, companyId);+ if (integration.error || !integration.data?.[0]?.active) {+ return { status: "inactive" };+ }++ const stored = (integration.data[0].metadata ?? {}) as {+ partDefinitionSlug?: string;+ customerTypeTitle?: string;+ supplierTypeTitle?: string;+ lastPublish?: Partial<+ Record<MountEntityType, { deferred?: string[] } | undefined>+ >;+ };++ const api = getMountClient();++ // Settings hold what a Mount user can actually see — the definition's slug+ // and the company types' titles. Resolve them to ids per run rather than+ // storing ids the user has no way to read back.+ const [definition, customerType, supplierType] = await Promise.all([+ stored.partDefinitionSlug+ ? api.findObjectDefinitionBySlug(companyId, stored.partDefinitionSlug)+ : null,+ stored.customerTypeTitle+ ? api.findCompanyTypeByTitle(companyId, stored.customerTypeTitle)+ : null,+ stored.supplierTypeTitle+ ? api.findCompanyTypeByTitle(companyId, stored.supplierTypeTitle)+ : null+ ]);++ const settings: MountPublishSettings = {+ partDefinitionId: definition?.id ?? null,+ customerTypeId: customerType?.id ?? null,+ supplierTypeId: supplierType?.id ?? null+ };++ const mappings = createMappingService(db, companyId);+ const source = createMountPublishSource(db, companyId);++ const summaries: MountPublishSummary[] = [];+ for (const entityType of entityTypes) {+ summaries.push(+ await publishEntityType(+ source,+ mappings,+ api,+ companyId,+ entityType,+ settings,+ limit,+ stored.lastPublish?.[entityType]?.deferred ?? []+ )+ );+ }++ await recordOutcome(serviceRole, companyId, summaries);++ return { status: "ran", summaries };+}++/**+ * Persist what happened, including the deferred ids the next run sorts last.+ * A record that never published has no mapping row to carry a reason, so+ * this is the only record of why it failed or was ambiguous.+ */+async function recordOutcome(+ serviceRole: SupabaseClient<Database>,+ companyId: string,+ summaries: MountPublishSummary[]+) {+ const current = await getMountIntegration(serviceRole, companyId);+ const metadata = (current.data?.[0]?.metadata ?? {}) as Record<+ string,+ unknown+ >;++ const lastPublish = {+ ...((metadata.lastPublish as Record<string, unknown>) ?? {}),+ ...Object.fromEntries(+ summaries.map((summary) => [+ summary.entityType,+ {+ at: new Date().toISOString(),+ created: summary.created,+ updated: summary.updated,+ more: summary.more,+ ambiguous: summary.ambiguous,+ failed: summary.failed,+ deferred: summary.deferred+ }+ ])+ )+ };++ await serviceRole+ .from("companyIntegration")+ .update({ metadata: { ...metadata, lastPublish } as never })+ .eq("companyId", companyId)+ .eq("id", MOUNT_INTEGRATION_ID);+}diff --git a/packages/ee/src/mount/lib/service.ts b/packages/ee/src/mount/lib/service.tsnew file mode 100644index 0000000000..6e0a25468a--- /dev/null+++ b/packages/ee/src/mount/lib/service.ts@@ -0,0 +1,18 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++export { MOUNT_INTEGRATION_ID } from "./constants";++import { MOUNT_INTEGRATION_ID } from "./constants";++export async function getMountIntegration(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return await client+ .from("companyIntegration")+ .select("*")+ .eq("companyId", companyId)+ .eq("id", MOUNT_INTEGRATION_ID)+ .limit(1);+}diff --git a/packages/ee/src/mount/lib/source.ts b/packages/ee/src/mount/lib/source.tsnew file mode 100644index 0000000000..7dc8061453--- /dev/null+++ b/packages/ee/src/mount/lib/source.ts@@ -0,0 +1,200 @@+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import type {+ MountPublishSource,+ PublishableCustomer,+ PublishablePart,+ PublishableSupplier+} from "./publish";+import { MOUNT_INTEGRATION_ID } from "./service";+import type { MountEntityType } from "./types";++/**+ * "Stale" is: no mapping row, or the Carbon record changed after it was last+ * published. That definition is what makes the sweep idempotent — a run that+ * succeeds takes a record out of the set, and a run that fails leaves it in.+ *+ * Records that failed or were ambiguous on earlier runs (`deferIds`) sort+ * after everything else, so they only take capacity the rest of the stale set+ * leaves over.+ *+ * Every record publishes regardless of active status; see the note in+ * mappers.ts.+ */+export function createMountPublishSource(+ db: Kysely<KyselyDatabase>,+ companyId: string+): MountPublishSource {+ async function listStaleParts(+ limit: number,+ deferIds: string[]+ ): Promise<PublishablePart[]> {+ const rows = await db+ .selectFrom("item")+ .leftJoin("externalIntegrationMapping as m", (join) =>+ join+ .onRef("m.entityId", "=", "item.id")+ .on("m.entityType", "=", "item")+ .on("m.integration", "=", MOUNT_INTEGRATION_ID)+ .on("m.companyId", "=", companyId)+ )+ .select("item.id")+ .select("item.readableId")+ .select("item.name")+ .where("item.companyId", "=", companyId)+ .where("item.type", "=", "Part")+ // One Mount part per part number, fed by the revision the `parts` view+ // surfaces (released before draft, then newest). An unreleased revision+ // minted by a change notice never overwrites the released one in Mount.+ .where("item.id", "in", (eb) =>+ eb+ .selectFrom("parts")+ .select("parts.id")+ .where("parts.companyId", "=", companyId)+ )+ .where((eb) =>+ eb.or([+ eb("m.externalId", "is", null),+ eb("m.lastSyncedAt", "is", null),+ eb("m.lastSyncedAt", "<", eb.ref("item.updatedAt"))+ ])+ )+ .$if(deferIds.length > 0, (qb) =>+ qb.orderBy((eb) =>+ eb.case().when("item.id", "in", deferIds).then(1).else(0).end()+ )+ )+ .orderBy("item.updatedAt", "asc")+ .limit(limit)+ .execute();++ return rows.map((row) => ({+ id: row.id,+ readableId: row.readableId,+ name: row.name+ }));+ }++ async function listStaleCustomers(+ limit: number,+ deferIds: string[]+ ): Promise<PublishableCustomer[]> {+ const rows = await db+ .selectFrom("customer")+ .leftJoin("externalIntegrationMapping as m", (join) =>+ join+ .onRef("m.entityId", "=", "customer.id")+ .on("m.entityType", "=", "customer")+ .on("m.integration", "=", MOUNT_INTEGRATION_ID)+ .on("m.companyId", "=", companyId)+ )+ // taxId and vatNumber moved off customer/supplier into these tables in+ // migration 20260430000001_tax-status; the `customers` view joins them+ // back the same way.+ .leftJoin("customerTax as tax", (join) =>+ join+ .onRef("tax.customerId", "=", "customer.id")+ .on("tax.companyId", "=", companyId)+ )+ .select("customer.id")+ .select("customer.readableId")+ .select("customer.name")+ .select("tax.taxId")+ .select("tax.vatNumber")+ .select("customer.website")+ .where("customer.companyId", "=", companyId)+ .where((eb) =>+ eb.or([+ eb("m.externalId", "is", null),+ eb("m.lastSyncedAt", "is", null),+ eb("m.lastSyncedAt", "<", eb.ref("customer.updatedAt")),+ // Org number and VAT live on the tax row, which has its own+ // updatedAt; an edit there leaves the parent row untouched.+ eb("m.lastSyncedAt", "<", eb.ref("tax.updatedAt"))+ ])+ )+ .$if(deferIds.length > 0, (qb) =>+ qb.orderBy((eb) =>+ eb.case().when("customer.id", "in", deferIds).then(1).else(0).end()+ )+ )+ .orderBy("customer.updatedAt", "asc")+ .limit(limit)+ .execute();++ return rows.map((row) => ({+ id: row.id,+ readableId: row.readableId,+ name: row.name,+ taxId: row.taxId,+ vatNumber: row.vatNumber,+ website: row.website+ }));+ }++ async function listStaleSuppliers(+ limit: number,+ deferIds: string[]+ ): Promise<PublishableSupplier[]> {+ const rows = await db+ .selectFrom("supplier")+ .leftJoin("externalIntegrationMapping as m", (join) =>+ join+ .onRef("m.entityId", "=", "supplier.id")+ .on("m.entityType", "=", "supplier")+ .on("m.integration", "=", MOUNT_INTEGRATION_ID)+ .on("m.companyId", "=", companyId)+ )+ .leftJoin("supplierTax as tax", (join) =>+ join+ .onRef("tax.supplierId", "=", "supplier.id")+ .on("tax.companyId", "=", companyId)+ )+ .select("supplier.id")+ .select("supplier.readableId")+ .select("supplier.name")+ .select("tax.taxId")+ .select("tax.vatNumber")+ .select("supplier.website")+ .where("supplier.companyId", "=", companyId)+ .where((eb) =>+ eb.or([+ eb("m.externalId", "is", null),+ eb("m.lastSyncedAt", "is", null),+ eb("m.lastSyncedAt", "<", eb.ref("supplier.updatedAt")),+ // Org number and VAT live on the tax row, which has its own+ // updatedAt; an edit there leaves the parent row untouched.+ eb("m.lastSyncedAt", "<", eb.ref("tax.updatedAt"))+ ])+ )+ .$if(deferIds.length > 0, (qb) =>+ qb.orderBy((eb) =>+ eb.case().when("supplier.id", "in", deferIds).then(1).else(0).end()+ )+ )+ .orderBy("supplier.updatedAt", "asc")+ .limit(limit)+ .execute();++ return rows.map((row) => ({+ id: row.id,+ readableId: row.readableId,+ name: row.name,+ taxId: row.taxId,+ vatNumber: row.vatNumber,+ website: row.website+ }));+ }++ return {+ async listStale(+ entityType: MountEntityType,+ limit: number,+ deferIds: string[] = []+ ) {+ if (entityType === "item") return await listStaleParts(limit, deferIds);+ if (entityType === "customer")+ return await listStaleCustomers(limit, deferIds);+ return await listStaleSuppliers(limit, deferIds);+ }+ };+}diff --git a/packages/ee/src/mount/lib/types.ts b/packages/ee/src/mount/lib/types.tsnew file mode 100644index 0000000000..f0aad94e83--- /dev/null+++ b/packages/ee/src/mount/lib/types.ts@@ -0,0 +1,93 @@+import { z } from "zod";++/**+ * Mount models customers and suppliers as one `Company` collection; a+ * `CompanyType` distinguishes them. Parts are not a native entity — they are+ * `Object` rows under an `ObjectDefinition`, so the definition to write into is+ * per-tenant configuration rather than a constant.+ */++export const MountCompanySchema = z.object({+ id: z.string(),+ identifier: z.string().nullable().optional(),+ name: z.string(),+ organizationNumber: z.string().nullable().optional(),+ vatNumber: z.string().nullable().optional(),+ website: z.string().nullable().optional(),+ email: z.string().nullable().optional(),+ typeId: z.string().nullable().optional(),+ statusId: z.string().nullable().optional(),+ updatedAt: z.string().nullable().optional()+});++export const MountObjectSchema = z.object({+ id: z.string(),+ identifier: z.string().nullable().optional(),+ title: z.string(),+ definitionId: z.string(),+ description: z.string().nullable().optional(),+ updatedAt: z.string().nullable().optional()+});++export const MountObjectDefinitionSchema = z.object({+ id: z.string(),+ title: z.string(),+ singular: z.string().nullable().optional(),+ slug: z.string().nullable().optional(),+ identifierPrefix: z.string().nullable().optional(),+ enabled: z.boolean().nullable().optional()+});++export const MountDomainSchema = z.object({+ id: z.string(),+ identifier: z.string().nullable().optional(),+ title: z.string()+});++export const MountCompanyTypeSchema = z.object({+ id: z.string(),+ title: z.string()+});++export type MountCompany = z.infer<typeof MountCompanySchema>;+export type MountObject = z.infer<typeof MountObjectSchema>;+export type MountObjectDefinition = z.infer<typeof MountObjectDefinitionSchema>;+export type MountCompanyType = z.infer<typeof MountCompanyTypeSchema>;++/** The Carbon-side entity types this integration pushes. */+export const MOUNT_ENTITY_TYPES = ["customer", "supplier", "item"] as const;+export type MountEntityType = (typeof MOUNT_ENTITY_TYPES)[number];++/** Write payloads. Mount names these `*Partial` in its OpenAPI spec. */+export type MountCompanyInput = {+ identifier: string;+ name: string;+ organizationNumber?: string | null;+ vatNumber?: string | null;+ website?: string | null;+ typeId?: string | null;+};++export type MountObjectInput = {+ identifier: string;+ title: string;+ definitionId: string;+};++/**+ * What `PATCH /X/{id}` returns: the fields that changed, not the record. An+ * update that changes nothing returns an empty list.+ */+export type MountChange = {+ field: string;+ oldValue?: unknown;+ newValue?: unknown;+};++/** The Mount record a mapping row points at no longer exists. */+export class MountNotFoundError extends Error {+ constructor(collection: string, mountId: string) {+ super(`Mount ${collection} ${mountId} not found`);+ this.name = "MountNotFoundError";+ }+}diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.tsindex 5655b538a4..2e6e5d3dbc 100644--- a/packages/jobs/src/inngest/functions/integrations/index.ts+++ b/packages/jobs/src/inngest/functions/integrations/index.ts@@ -6,6 +6,7 @@ export { accountingPullSweepFunction } from "./accounting-pull-sweep";export { accountingReconciliationFunction } from "./accounting-reconciliation";export { jiraSyncFunction, syncIssueFromJiraSchema } from "./jira";export { linearSyncFunction, syncIssueFromLinearSchema } from "./linear";+export { mountPublishFunction } from "./mount-publish";export { onshapeBackfillFunction } from "./onshape-backfill";export { onshapeRevisionSyncFunction } from "./onshape-revision-sync";export { paperlessPartsFunction } from "./paperless-parts";diff --git a/packages/jobs/src/inngest/functions/integrations/mount-publish.ts b/packages/jobs/src/inngest/functions/integrations/mount-publish.tsnew file mode 100644index 0000000000..0412a6ff7b--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/mount-publish.ts@@ -0,0 +1,85 @@+/**+ * Mount publish sweep — the "Push customers / suppliers / parts" actions on+ * the Mount integration's detail page.+ *+ * Carbon is the master for all three; Mount is a downstream mirror that is+ * never read back. The sweep finds records Mount is missing or holds stale+ * (no mapping row, or the Carbon row changed after it was last published)+ * and pushes them one at a time.+ *+ * The sweep IS the retry. A record that fails is still stale on the next run,+ * so there is no operation ledger to keep truthful and no queue to drain —+ * deliberately less machinery than the accounting sync, which needs provable+ * completeness because it moves money.+ *+ * Started from the integration's actions today. A cron is a second trigger on+ * this same function, iterating every active Mount integration; nothing here+ * assumes a human started it.+ */+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ getPostgresClient,+ getPostgresConnectionPool+} from "@carbon/database/client";+import { runMountPublish } from "@carbon/ee/mount.server";+import { getLogger } from "@carbon/logger";+import { PostgresDriver } from "kysely";+import z from "zod";+import { inngest } from "../../client";++const log = getLogger("jobs", "mount-publish");++const MountPublishPayloadSchema = z.object({+ companyId: z.string(),+ entityTypes: z+ .array(z.enum(["customer", "supplier", "item"]))+ .min(1)+ .default(["customer", "supplier", "item"])+});++export const mountPublishFunction = inngest.createFunction(+ {+ id: "mount-publish",+ retries: 2,+ // One publish run per company at a time. Two overlapping runs would race+ // on the same stale set and double-POST records Mount cannot de-duplicate+ // for us — it has no idempotency key.+ concurrency: { key: "event.data.companyId", limit: 1 }+ },+ { event: "carbon/mount-publish" },+ async ({ event, step }) => {+ const { companyId, entityTypes } = MountPublishPayloadSchema.parse(+ event.data+ );++ // One step for the whole run: the sweep is idempotent, so a retry+ // replaying records that already published is harmless.+ const result = await step.run("publish", async () =>+ runMountPublish({+ serviceRole: getCarbonServiceRole(),+ db: getPostgresClient(getPostgresConnectionPool(5), PostgresDriver),+ companyId,+ entityTypes+ })+ );++ if (result.status === "inactive") {+ log.warn("Mount integration missing or inactive", { companyId });+ return { skipped: "integration-inactive" as const };+ }++ log.info("Mount publish complete", {+ companyId,+ summaries: result.summaries.map((summary) => ({+ entityType: summary.entityType,+ created: summary.created,+ updated: summary.updated,+ ambiguous: summary.ambiguous.length,+ failed: summary.failed.length,+ more: summary.more+ }))+ });++ return result;+ }+);diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex cee3f328cb..ae140d8b6f 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -37,6 +37,7 @@ import {accountingReconciliationFunction,jiraSyncFunction,linearSyncFunction,+ mountPublishFunction,onshapeBackfillFunction,onshapeRevisionSyncFunction,paperlessPartsFunction,@@ -164,6 +165,7 @@ export const functions = [accountingOutboundSweepFunction,accountingReconciliationFunction,accountingPullSweepFunction,+ mountPublishFunction,onshapeBackfillFunction,onshapeRevisionSyncFunction,rampSyncFunction,diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex a3e966f03d..00911fb8b7 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -595,6 +595,15 @@ export type Events = {};};+ // Mount publish sweep (the integration's "Push customers / suppliers /+ // parts" actions): push Carbon records Mount is missing or holds stale+ "carbon/mount-publish": {+ data: {+ companyId: string;+ entityTypes?: Array<"customer" | "supplier" | "item">;+ };+ };+// Onshape released-asset backfill / reconcile"carbon/onshape-backfill": {data: {diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.tsindex 22815e79f5..9226cc60ed 100644--- a/packages/lib/src/trigger.ts+++ b/packages/lib/src/trigger.ts@@ -24,6 +24,7 @@ const taskToEvent = {"model-optimize": "carbon/model-optimize",notify: "carbon/notify",onboard: "carbon/onboard",+ "mount-publish": "carbon/mount-publish","onshape-backfill": "carbon/onshape-backfill","onshape-revision-sync": "carbon/onshape-revision-sync","paperless-parts": "carbon/paperless-parts",diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex fc0d238cbd..7f4d9a4825 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -9211,6 +9211,9 @@ msgstr "Anweisungen werden von der Verfahrensanweisung geerbt."msgid "Integration"msgstr "Integration"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Integration nicht gefunden"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex d6c12a6d84..06235bfeea 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -9211,6 +9211,9 @@ msgstr "Instructions are inherited from the procedure."msgid "Integration"msgstr "Integration"+msgid "Integration credentials"+msgstr "Integration credentials"+msgid "Integration not found"msgstr "Integration not found"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 65f02fb168..cb8115f1d7 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -9211,6 +9211,9 @@ msgstr "Las instrucciones se heredan del procedimiento."msgid "Integration"msgstr "Integración"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Integración no encontrada"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 64dc416599..e48a3dbc7d 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -9211,6 +9211,9 @@ msgstr "Les instructions sont héritées de la procédure."msgid "Integration"msgstr "Intégration"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Intégration introuvable"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 5f0db54e47..d13ac013f2 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -9211,6 +9211,9 @@ msgstr "निर्देश कार्यविधि से विरासmsgid "Integration"msgstr "एकीकरण"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "एकीकरण नहीं मिला"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 3900d16038..34174797c3 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -9211,6 +9211,9 @@ msgstr "Le istruzioni sono ereditate dalla procedura."msgid "Integration"msgstr "Integrazione"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Integrazione non trovata"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex e987e47b6d..fa8ab195cf 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -9211,6 +9211,9 @@ msgstr "手順は手順書から継承されています。"msgid "Integration"msgstr "連携"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "連携が見つかりません"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 06bdad05f6..70e8713d6d 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -9211,6 +9211,9 @@ msgstr "지시사항은 절차서에서 상속됩니다."msgid "Integration"msgstr "연동"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "연동을 찾을 수 없습니다"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 349f625e08..41bde78d03 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -9211,6 +9211,9 @@ msgstr "Instrukcje są dziedziczone z procedury."msgid "Integration"msgstr "Integracja"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Integracja nie znaleziona"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 03c13522ca..6143042b73 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -9211,6 +9211,9 @@ msgstr "As instruções são herdadas do procedimento."msgid "Integration"msgstr "Integração"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Integração não encontrada"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex ee7de6564f..091e4e646a 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -9211,6 +9211,9 @@ msgstr "Инструкции наследуются из процедуры."msgid "Integration"msgstr "Интеграция"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Интеграция не найдена"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 328d8b149c..011976ee7d 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -9211,6 +9211,9 @@ msgstr "Talimatlar prosedürden miras alınır."msgid "Integration"msgstr "Entegrasyon"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "Entegrasyon bulunamadı"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex a9578f4460..0c639db67b 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -9211,6 +9211,9 @@ msgstr "说明从程序文件继承。"msgid "Integration"msgstr "集成"+msgid "Integration credentials"+msgstr ""+msgid "Integration not found"msgstr "集成未找到"