@12-apps/marketplace 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +29 -4
- package/README.md +92 -3
- package/dist/99food/index.d.ts +48 -2
- package/dist/99food/index.js +84 -1
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
- package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
- package/dist/chunk-AYYBRQJV.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
- package/dist/chunk-RVBTARIY.js.map +1 -0
- package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
- package/dist/chunk-XUAFXNOH.js.map +1 -0
- package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +10 -2
- package/dist/ifood/index.js +246 -69
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +148 -9
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +3 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +7 -1
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +12 -8
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +92 -1
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/index.ts +4 -0
- package/src/99food/outbound.ts +3 -3
- package/src/core/adapter.ts +10 -1
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/engine.ts +46 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/ports.ts +36 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/outbound.ts +9 -6
- package/src/index.ts +40 -0
- package/src/rappi/index.ts +6 -0
- package/src/server/jobs.ts +39 -9
- package/dist/chunk-24RQZPSV.js.map +0 -1
- package/dist/chunk-CRYFYDQ2.js.map +0 -1
- package/dist/chunk-D2X7TOR6.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/core/registry.ts","../src/core/outbound-queue.ts","../src/core/catalogue-category.ts","../src/core/integration.ts","../src/core/catalogue-store.ts","../src/core/catalogue-job.ts","../src/core/inbox.ts","../src/core/menu-links.ts","../src/core/ingest.ts","../src/core/cancellation-outcome.ts","../src/core/cancellation.ts","../src/core/acceptance.ts","../src/core/order-fetch-marks.ts","../src/core/fetch-order.ts","../src/core/catalogue-sweep.ts","../src/core/outbound-sweep.ts","../src/core/outbound.ts"],"sourcesContent":["/**\n * The canonical shape every marketplace adapter normalizes INTO.\n *\n * This type is the seam. The engine below it knows no marketplace by name: a\n * marketplace is an adapter registered with the engine (`./adapter`), and the\n * provider id is whatever that adapter says it is. A second marketplace is a\n * second adapter, never a second pipeline, a second acceptance clock or a\n * second idea of what an order is.\n *\n * Deliberately POORER than any marketplace's own payload. Everything a store\n * operates on is here; everything else stays in the inbox row's raw `payload`,\n * which is where a normalization bug is reconstructed from.\n */\n\n/**\n * A marketplace's id, as its adapter declares it (`\"IFOOD\"`). Uppercase\n * letters, digits and underscores; the migration's CHECK holds the same shape.\n * A string rather than a closed union, because the set of marketplaces is the\n * set of registered adapters, and a union would make a new one a code change\n * in the engine.\n */\nexport type MarketplaceProvider = string;\n\n/** The shape a provider id must have. Shared by the registry and the CHECK. */\nexport const PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\n\n/** One line of an incoming order, before it is resolved against the catalog. */\nexport interface NormalizedOrderLine {\n /** The marketplace's own SKU — the key the SKU map is matched on. */\n externalSku: string;\n /** What the marketplace called it. Snapshotted, and the fallback line text. */\n name: string;\n quantity: number;\n /**\n * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A\n * marketplace's menu carries its own prices, and the buyer's receipt is the\n * marketplace's one: re-pricing from the host's catalog would produce a\n * total nobody was charged.\n */\n unitPriceCents: number;\n /** The buyer's note on this line, when they left one. */\n note: string | null;\n}\n\n/** The buyer, as much of them as the marketplace discloses. */\nexport interface NormalizedBuyer {\n /** The marketplace's own stable id for this customer, when it gives one. */\n externalId: string | null;\n name: string | null;\n phone: string | null;\n}\n\n/** Where a delivery goes, as much of it as the marketplace states. */\nexport interface NormalizedAddress {\n street: string;\n number: string;\n neighborhood: string;\n complement: string | null;\n /** The sentence that finds the door. */\n reference: string | null;\n postalCode: string | null;\n city: string | null;\n state: string | null;\n}\n\n/** How the order reaches the buyer: brought to the door, or collected. */\nexport type MarketplaceOrderType = \"DELIVERY\" | \"TAKEOUT\";\n\n/** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */\nexport type MarketplaceDeliveredBy = \"MERCHANT\" | \"MARKETPLACE\";\n\n/** An incoming marketplace order, normalized. */\nexport interface NormalizedMarketplaceOrder {\n provider: MarketplaceProvider;\n /** The marketplace's order id — THE idempotency key for the whole pipeline. */\n externalOrderId: string;\n /** The short code the courier and the buyer say out loud. */\n externalDisplayId: string | null;\n buyer: NormalizedBuyer;\n lines: NormalizedOrderLine[];\n /**\n * What the buyer paid, gross. NOT derived from the lines when the\n * marketplace states it: its total carries fees, promotions and rounding the\n * line sum does not, and the number that must match the receipt is this one.\n */\n totalCents: number;\n /** The marketplace's cut, when it states one. NULL is \"did not say\", not 0. */\n commissionCents: number | null;\n /** The marketplace's own promise to the buyer. */\n deliveryDueAt: Date | null;\n /** When the marketplace says the order was placed. */\n placedAt: Date;\n /** Null when the payload does not say. */\n orderType?: MarketplaceOrderType | null;\n /** Null on a take-out and when unstated. */\n deliveredBy?: MarketplaceDeliveredBy | null;\n /** Null on a take-out and when unstated. */\n deliveryAddress?: NormalizedAddress | null;\n /**\n * OPTIONAL. The merchant the order names, when its body says (Open\n * Delivery's `merchant.id`). A fetched order naming another merchant than\n * the connection's is refused.\n */\n externalMerchantId?: string | null;\n}\n\n/**\n * What an event says about the STORE's own cancellation request: `CONFIRMED`\n * when the marketplace cancelled the order (a pending request is answered),\n * `FAILED` when it refused the request.\n */\nexport type CancellationOutcome = \"CONFIRMED\" | \"FAILED\";\n\n/** What an adapter makes of one inbound delivery. */\nexport interface NormalizedEvent {\n provider: MarketplaceProvider;\n /** The delivery's own id — the inbox dedup key, paired with the provider. */\n eventId: string;\n /** The provider's event type verbatim, kept for the inbox row and the log. */\n eventType: string;\n /** The merchant this event names, used to attribute it to a tenant. */\n externalMerchantId: string | null;\n externalOrderId: string | null;\n /**\n * The order this event carries, or null when the event is one the engine\n * understands and does not ingest. A null here is an IGNORED inbox row (or a\n * cancellation, below), never a failure.\n */\n order: NormalizedMarketplaceOrder | null;\n /** The marketplace has CANCELLED the order. */\n cancelled: boolean;\n /**\n * The answer to the store's own cancellation request, when this event is\n * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.\n */\n cancellationOutcome?: CancellationOutcome | null;\n /**\n * OPTIONAL. This event announces an order whose body the marketplace serves\n * separately (Open Delivery's `CREATED` carries only the order's id): the\n * engine fetches it through the adapter's `fetchOrder`, in the\n * `marketplace.fetch-order` job, never inside the request that delivered\n * the event. Ignored when `order` is present.\n */\n orderToFetch?: boolean;\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"./adapter\";\nimport { PROVIDER_ID_PATTERN, type MarketplaceProvider } from \"./types\";\n\n/**\n * The adapter registry: the ONE place a provider id becomes a marketplace.\n *\n * Every dispatch in the engine — normalize, signature, outbound, reasons, the\n * app link — asks this registry, so no module below it holds a branch on a\n * provider id. Registering an adapter is the whole cost of a marketplace.\n */\nexport interface AdapterRegistry {\n /** The adapter for this provider, or null when none is registered. */\n get(provider: string): MarketplaceAdapter | null;\n /** Whether a provider id names a registered adapter (URL segments arrive as text). */\n has(provider: string): provider is MarketplaceProvider;\n /** Every registered provider, in registration order. */\n providers(): readonly MarketplaceProvider[];\n}\n\n/** Thrown at mount when the adapter list cannot be a registry. */\nexport class MarketplaceAdapterRegistrationError extends Error {\n constructor(message: string) {\n super(`@12-apps/marketplace: ${message}`);\n this.name = \"MarketplaceAdapterRegistrationError\";\n }\n}\n\nfunction assertReasons(adapter: MarketplaceAdapter): void {\n const codes = new Set<string>();\n for (const reason of adapter.cancellationReasons()) {\n if (reason.code.trim() === \"\") {\n throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);\n }\n if (codes.has(reason.code)) {\n throw new MarketplaceAdapterRegistrationError(\n `${adapter.provider} declares the reason code \"${reason.code}\" twice.`,\n );\n }\n codes.add(reason.code);\n }\n if (adapter.capabilities.apiCancel && codes.size === 0) {\n throw new MarketplaceAdapterRegistrationError(\n `${adapter.provider} can cancel through its API but declares no reason to cancel with.`,\n );\n }\n}\n\n/**\n * Build the registry, refusing what would only fail later: an empty list, a\n * malformed id, a duplicate provider, a reason list that cannot be validated\n * against.\n */\nexport function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]): AdapterRegistry {\n if (adapters.length === 0) {\n throw new MarketplaceAdapterRegistrationError(\"an engine needs at least one adapter.\");\n }\n const byProvider = new Map<string, MarketplaceAdapter>();\n for (const adapter of adapters) {\n if (!PROVIDER_ID_PATTERN.test(adapter.provider)) {\n throw new MarketplaceAdapterRegistrationError(\n `provider id \"${adapter.provider}\" must be uppercase letters, digits and underscores.`,\n );\n }\n if (byProvider.has(adapter.provider)) {\n throw new MarketplaceAdapterRegistrationError(`two adapters claim \"${adapter.provider}\".`);\n }\n assertReasons(adapter);\n byProvider.set(adapter.provider, adapter);\n }\n const providers = [...byProvider.keys()];\n return {\n get: (provider) => byProvider.get(provider) ?? null,\n has: (provider): provider is MarketplaceProvider => byProvider.has(provider),\n providers: () => providers,\n };\n}\n\n/**\n * The reason a refusal carries: the one named by `code`, or — when the store\n * named none — the adapter's first. `null` when the code is not one of the\n * adapter's, which a caller answers as a refusal of the whole request.\n */\nexport function resolveReason(\n adapter: MarketplaceAdapter,\n code: string | null | undefined,\n): CancellationReason | null {\n const reasons = adapter.cancellationReasons();\n if (code === null || code === undefined) return reasons[0] ?? null;\n return reasons.find((reason) => reason.code === code) ?? null;\n}\n\n/**\n * The reason a host should preselect: the adapter's \"item unavailable\" reason\n * when the order cannot be covered, else its first. The SHORTAGE is the\n * host's to judge (stock is the host's), so it arrives as a boolean.\n */\nexport function suggestReason(\n adapter: MarketplaceAdapter,\n input: { itemUnavailable: boolean },\n): CancellationReason | null {\n const reasons = adapter.cancellationReasons();\n if (input.itemUnavailable) {\n const unavailable = reasons.find((reason) => reason.itemUnavailable);\n if (unavailable) return unavailable;\n }\n return reasons[0] ?? null;\n}\n","import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The outbound job's name and payload — what a decision QUEUES.\n *\n * No path that answers a request ever calls a marketplace: an aceite, a\n * refusal, a webhook and an ingest only enqueue this, and the job does the\n * call. The payload carries identifiers only; the reason code and every\n * outcome live on the acceptance row, so a replayed or duplicated job reads\n * the truth rather than a stale copy of it.\n */\n\n/** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */\nexport const MARKETPLACE_OUTBOUND_JOB = \"marketplace.outbound\";\n\n/** What goes out: the store's aceite, or the store's cancellation request. */\nexport type OutboundAction = \"confirm\" | \"requestCancellation\";\n\n/** The outbound job's payload. Identifiers only. */\nexport interface OutboundJobPayload {\n clientId: string;\n orderId: string;\n action: OutboundAction;\n}\n\n/** The dedupe key: at most one queued call per (order, action). */\nexport function outboundDedupeKey(payload: OutboundJobPayload): string {\n return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;\n}\n\n/**\n * Queue one outbound call, when the marketplace's API can take it at all.\n *\n * A marketplace whose adapter states no API for the action gets nothing\n * queued: there is nobody to call, and the host shows the app link instead.\n * The queue port never throws. A refusal to enqueue is logged AND recovered:\n * the row still owes the call (PENDING, or ACCEPTED with no confirm stamp),\n * and the outbound sweep re-queues every such row (`./outbound-sweep.ts`).\n *\n * `dedupeKey` defaults to the job's own key; the sweep passes its own, since a\n * queue keeps a finished job's id and would swallow a re-queue under it.\n */\nexport async function enqueueOutbound(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n provider: MarketplaceProvider,\n dedupeKey: string = outboundDedupeKey(payload),\n): Promise<boolean> {\n const adapter = ctx.registry.get(provider);\n if (!adapter) return false;\n const able =\n payload.action === \"confirm\" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;\n if (!able) return false;\n const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });\n if (!outcome.enqueued) {\n ctx.ports.logger.warn(\n `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` +\n (outcome.reason ? ` (${outcome.reason})` : \"\"),\n );\n }\n return outcome.enqueued;\n}\n","import type { CatalogueFailure } from \"./catalogue-port\";\nimport type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The marketplace's id for a host category, found or created ONCE per\n * (connection, name) and reused (FUT-4768).\n *\n * A push marketplace issues its own category ids, so an adapter finds a\n * category by name and creates it when it is missing. Two products switched\n * on at once into a new category would each miss it and each create it,\n * leaving two categories of the same name in front of the buyer. So the engine\n * stores the id, and the first publish to need it CLAIMS the creation: its\n * row holds the name with no id yet; a second publish meanwhile is told to\n * retry (the job's backoff), and finds the id stored when it does. A claim\n * whose publish died is taken over once it is older than {@link CLAIM_STALE_MS}.\n */\n\n/**\n * A claim older than this was left by a publish that died; another takes it\n * over. Well above three slow marketplace calls, so a live holder on a slow\n * call keeps its claim (a shorter window let a second publish create the\n * category again). A publish that only waited is left PUBLISHING for the\n * sweep, which re-queues it after 10 minutes, so a long window costs nothing.\n */\nconst CLAIM_STALE_MS = 3 * 60_000;\n\n/** What one publish learnt about the category claims it met: whether another held one. */\nexport interface CategoryRunState {\n waited: boolean;\n}\n\ntype CategoryTable = NonNullable<MarketplaceDb[\"marketplaceCatalogueCategory\"]>;\n\ninterface CategoryRow {\n externalId: string | null;\n}\n\n/** Take the creation of this category, or learn someone else holds it. */\nasync function claim(table: CategoryTable, key: Record<string, string>, row: CategoryRow | null, now: Date): Promise<boolean> {\n if (!row) {\n try {\n await table.create({ data: { ...key, claimedAt: now } });\n return true;\n } catch (error) {\n if ((error as { code?: string }).code === \"P2002\") return false;\n throw error;\n }\n }\n const stale = new Date(now.getTime() - CLAIM_STALE_MS);\n const moved = await table.updateMany({\n where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },\n data: { claimedAt: now },\n });\n return moved.count > 0;\n}\n\n/**\n * Store the id this publish resolved, or release its claim. Only this\n * publish's own claim (`claimedAt` it set) is released: one taken over\n * meanwhile stays its new holder's.\n */\nasync function release(table: CategoryTable, key: Record<string, string>, claimedAt: Date, id: string | null): Promise<void> {\n if (id !== null) {\n await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });\n return;\n }\n await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });\n}\n\n/**\n * The category's id: the stored one, else `resolve()` (the adapter's find or\n * create) run under this publish's claim and stored. A host without the\n * category table resolves every time, unserialized, as before it.\n */\nexport async function resolveCategory(\n ctx: EngineContext,\n connection: { clientId: string; provider: MarketplaceProvider },\n name: string,\n resolve: () => Promise<{ id: string } | CatalogueFailure>,\n state: CategoryRunState = { waited: false },\n): Promise<{ id: string } | CatalogueFailure> {\n const table = (await ctx.ports.db()).marketplaceCatalogueCategory;\n if (!table) return resolve();\n const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };\n const row = (await table.findFirst({ where: key, select: { externalId: true } })) as CategoryRow | null;\n if (row?.externalId) return { id: row.externalId };\n const now = ctx.ports.clock.now();\n if (!(await claim(table, key, row, now))) {\n state.waited = true;\n return { kind: \"retry\", reason: `another publish is creating the category \"${key.name}\"` };\n }\n let result: { id: string } | CatalogueFailure = { kind: \"retry\", reason: \"the category was not resolved\" };\n try {\n result = await resolve();\n } catch (error) {\n // A call that never got an answer (a timeout) is a retry, like every outbound call.\n result = { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n } finally {\n // The claim is released whatever happened, so the next attempt (this\n // publish's or another's) goes on at once instead of waiting it out.\n await release(table, key, now, \"id\" in result ? result.id : null);\n }\n return result;\n}\n\n/** Forget a stored category id the marketplace no longer has, so the next resolve finds or creates it again. */\nexport async function forgetCategory(\n ctx: EngineContext,\n connection: { clientId: string; provider: MarketplaceProvider },\n name: string,\n): Promise<void> {\n const table = (await ctx.ports.db()).marketplaceCatalogueCategory;\n if (!table) return;\n await table.updateMany({\n where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },\n data: { externalId: null, claimedAt: null },\n });\n}\n","import type { MarketplaceCredentials } from \"./adapter\";\nimport type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The (tenant, marketplace) connection repository .\n *\n * Nothing here ever returns the credential blob. The read every surface uses\n * answers whether a connection EXISTS and how it is configured, never what it\n * is configured with. The one opening read is {@link resolveIngestionTarget},\n * which the webhook path needs and nobody else calls.\n */\n\n/** A connection as every read surface sees it: no secrets, ever. */\nexport interface MarketplaceIntegrationView {\n provider: MarketplaceProvider;\n enabled: boolean;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n status: \"UNVERIFIED\" | \"VERIFIED\" | \"FAILED\";\n externalMerchantId: string | null;\n autoAccept: boolean;\n ackSlaSeconds: number;\n /**\n * Whether the store has a usable connection — i.e. whether secrets are on\n * file at all. Named for the STATE rather than for the blob behind it: the\n * only fact anyone needs about a stored secret is that one exists, and it is\n * the only one that can be answered without disclosing it.\n */\n connected: boolean;\n lastEventAt: Date | null;\n lastVerifiedAt: Date | null;\n /** Archived connections ingest nothing; null while live. */\n archivedAt: Date | null;\n}\n\ninterface IntegrationRow {\n provider: string;\n enabled: boolean;\n environment: string;\n status: string;\n externalMerchantId: string | null;\n autoAccept: boolean;\n ackSlaSeconds: number;\n credentials: string;\n lastEventAt: Date | null;\n lastVerifiedAt: Date | null;\n archivedAt: Date | null;\n}\n\nconst VIEW_SELECT = {\n provider: true,\n enabled: true,\n environment: true,\n status: true,\n externalMerchantId: true,\n autoAccept: true,\n ackSlaSeconds: true,\n credentials: true,\n lastEventAt: true,\n lastVerifiedAt: true,\n archivedAt: true,\n} as const;\n\nfunction toView(row: IntegrationRow): MarketplaceIntegrationView {\n return {\n provider: row.provider as MarketplaceProvider,\n enabled: row.enabled,\n environment: row.environment as MarketplaceIntegrationView[\"environment\"],\n status: row.status as MarketplaceIntegrationView[\"status\"],\n externalMerchantId: row.externalMerchantId,\n autoAccept: row.autoAccept,\n ackSlaSeconds: row.ackSlaSeconds,\n connected: row.credentials !== \"\",\n lastEventAt: row.lastEventAt,\n lastVerifiedAt: row.lastVerifiedAt,\n archivedAt: row.archivedAt ?? null,\n };\n}\n\n/**\n * This store's marketplace connections, secrets withheld: the live ones, or\n * with `includeArchived` the archived too; `providers` narrows to those ids.\n */\nexport async function listMarketplaceIntegrations(\n ctx: EngineContext,\n clientId: string,\n options: { providers?: readonly string[]; includeArchived?: boolean } = {},\n): Promise<MarketplaceIntegrationView[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceIntegration.findMany({\n where: {\n clientId,\n ...(options.providers ? { provider: { in: [...options.providers] } } : {}),\n ...(options.includeArchived ? {} : { archivedAt: null }),\n },\n select: VIEW_SELECT,\n orderBy: { provider: \"asc\" },\n })) as IntegrationRow[];\n return rows.map(toView);\n}\n\n/** What a save may change. Absent keys leave their column alone. */\nexport interface SaveMarketplaceIntegrationInput {\n clientId: string;\n provider: MarketplaceProvider;\n enabled?: boolean;\n environment?: \"SANDBOX\" | \"PRODUCTION\";\n externalMerchantId?: string | null;\n autoAccept?: boolean;\n ackSlaSeconds?: number;\n /**\n * The secrets, when the operator re-entered them. Absent means \"leave the\n * stored blob alone\", which is what makes it possible to flip `autoAccept`\n * without retyping a client secret nobody can read back off the screen.\n */\n credentials?: MarketplaceCredentials;\n}\n\n/**\n * Create or update a store's connection to one marketplace.\n *\n * An upsert on `(clientId, provider)` — the row IS the connection, so there is\n * no separate \"connect\" and \"edit\". A CREATE with no credentials stores the\n * empty blob rather than refusing: a merchant mid-homologation has a merchant\n * id and no secrets for weeks, and that half-connected state is exactly what\n * the screen exists to show them.\n *\n * Re-entering credentials resets `status` to UNVERIFIED. The stored status is a\n * claim about a specific secret; carrying VERIFIED across a credential change\n * would assert that a probe which never ran had passed.\n */\nexport async function saveMarketplaceIntegration(\n ctx: EngineContext,\n input: SaveMarketplaceIntegrationInput,\n db: MarketplaceDb,\n): Promise<MarketplaceIntegrationView> {\n const sealed = input.credentials\n ? ctx.ports.secrets.seal(JSON.stringify(input.credentials))\n : undefined;\n const mutable = {\n ...(input.enabled === undefined ? {} : { enabled: input.enabled }),\n ...(input.environment === undefined ? {} : { environment: input.environment }),\n ...(input.externalMerchantId === undefined\n ? {}\n : { externalMerchantId: input.externalMerchantId }),\n ...(input.autoAccept === undefined ? {} : { autoAccept: input.autoAccept }),\n ...(input.ackSlaSeconds === undefined ? {} : { ackSlaSeconds: input.ackSlaSeconds }),\n ...(sealed === undefined ? {} : { credentials: sealed, status: \"UNVERIFIED\" }),\n };\n const row = (await db.marketplaceIntegration.upsert({\n where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n credentials: sealed ?? \"\",\n ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,\n ...mutable,\n },\n update: mutable,\n select: VIEW_SELECT,\n })) as IntegrationRow;\n return toView(row);\n}\n\n/** What the ingestion path needs to know about a store's connection. */\nexport interface IngestionTarget {\n enabled: boolean;\n autoAccept: boolean;\n ackSlaSeconds: number;\n webhookSecret: string | null;\n /** The merchant the store connected; a fetched order naming another is refused. */\n externalMerchantId: string | null;\n}\n\n/**\n * The merchant id a store's live connection states, read alone: no\n * credentials are opened. Null when it states none, or when there is no live\n * connection (archived or absent).\n */\nexport async function connectionMerchantId(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n): Promise<string | null> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceIntegration.findUnique({\n where: { clientId_provider: { clientId, provider } },\n select: { externalMerchantId: true, archivedAt: true },\n })) as { externalMerchantId: string | null; archivedAt: Date | null } | null;\n return row && !row.archivedAt ? (row.externalMerchantId ?? null) : null;\n}\n\n/**\n * The connection a delivery belongs to, plus the two things the webhook path\n * needs from it: the shared secret to verify against, and whether the store has\n * the connection ON.\n *\n * A DISABLED connection still resolves. The caller decides what to do with that\n * (it stores the event and does not ingest it), and it must be able to tell\n * \"this store turned the channel off\" apart from \"this store has no channel\",\n * because only one of them is a misconfiguration worth shouting about.\n */\nexport async function resolveIngestionTarget(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n): Promise<IngestionTarget | null> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceIntegration.findUnique({\n where: { clientId_provider: { clientId, provider } },\n select: {\n enabled: true,\n autoAccept: true,\n ackSlaSeconds: true,\n credentials: true,\n archivedAt: true,\n externalMerchantId: true,\n },\n })) as {\n externalMerchantId: string | null;\n enabled: boolean;\n autoAccept: boolean;\n ackSlaSeconds: number;\n credentials: string;\n archivedAt: Date | null;\n } | null;\n // An archived connection is no connection: its deliveries are refused.\n if (!row || row.archivedAt) return null;\n return {\n enabled: row.enabled,\n autoAccept: row.autoAccept,\n ackSlaSeconds: row.ackSlaSeconds,\n externalMerchantId: row.externalMerchantId ?? null,\n // An unopenable blob must not read as \"no secret configured\" — that would\n // turn a key-rotation problem into an endpoint that accepts unsigned\n // deliveries. The secrets port throws instead, and the caller answers 401.\n webhookSecret:\n row.credentials === \"\" ? null : openCredentials(ctx, row.credentials).webhookSecret,\n };\n}\n\n/**\n * Open a stored credential set.\n *\n * Throws on a ciphertext that will not open, by way of the host's secrets port\n * — which is the right outcome and not a hypothetical: a row written under a\n * key that has since rotated cannot be used to talk to anyone, and treating it\n * as \"no credentials\" would silently turn a KEY problem into a connection that\n * looks merely unconfigured.\n */\nfunction openCredentials(\n ctx: EngineContext,\n sealed: string,\n): MarketplaceCredentials {\n const parsed: unknown = JSON.parse(ctx.ports.secrets.open(sealed));\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(\"Stored marketplace credentials are not an object.\");\n }\n const record = parsed as Partial<MarketplaceCredentials>;\n return {\n clientId: String(record.clientId ?? \"\"),\n clientSecret: String(record.clientSecret ?? \"\"),\n webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null,\n };\n}\n\n/**\n * Which tenant a delivery belongs to, resolved from the merchant id the\n * marketplace names.\n *\n * Matched against the column OUTSIDE the ciphertext, which is the whole reason\n * `externalMerchantId` lives there: attributing a delivery must not require\n * decrypting every store's secrets to find the match.\n */\nexport async function resolveTenantByMerchant(\n ctx: EngineContext,\n provider: MarketplaceProvider,\n externalMerchantId: string,\n): Promise<string | null> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceIntegration.findMany({\n where: { provider, externalMerchantId, archivedAt: null },\n select: { clientId: true },\n take: 1,\n })) as { clientId: string }[];\n return rows[0]?.clientId ?? null;\n}\n\n/** Stamp the connection's liveness marker. Best-effort; never blocks ingestion. */\nexport async function markMarketplaceEventSeen(\n db: MarketplaceDb,\n clientId: string,\n provider: MarketplaceProvider,\n at: Date,\n): Promise<void> {\n await db.marketplaceIntegration.updateMany({\n where: { clientId, provider },\n data: { lastEventAt: at },\n });\n}\n\n/** What the outbound engine needs to talk to a marketplace for one store. */\nexport interface OutboundConnection {\n environment: \"SANDBOX\" | \"PRODUCTION\";\n credentials: MarketplaceCredentials;\n}\n\n/**\n * The opened connection for one (tenant, marketplace), or null when there is\n * no connection or no credentials on file. Throws when the stored blob will\n * not open — the outbound engine records that as a failure rather than\n * mistaking a key problem for an unconfigured store.\n */\nexport async function readOutboundConnection(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n): Promise<OutboundConnection | null> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceIntegration.findUnique({\n where: { clientId_provider: { clientId, provider } },\n select: { environment: true, credentials: true },\n })) as { environment: string; credentials: string } | null;\n if (!row || row.credentials === \"\") return null;\n return {\n environment: row.environment === \"PRODUCTION\" ? \"PRODUCTION\" : \"SANDBOX\",\n credentials: openCredentials(ctx, row.credentials),\n };\n}\n","import { forgetCategory, resolveCategory, type CategoryRunState } from \"./catalogue-category\";\nimport type { CatalogueCallContext, CatalogueWarningCode } from \"./catalogue-port\";\nimport { connectionMerchantId, readOutboundConnection } from \"./integration\";\nimport type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The catalogue publication's rows and the reads every catalogue path shares\n * (FUT-4768). The table is `marketplace_catalogue_publications`; its states\n * are the mechanism's vocabulary, never a language.\n */\n\n/** Where one product stands in one marketplace's catalogue. */\nexport type CatalogueStatus = \"PUBLISHING\" | \"PUBLISHED\" | \"WITHDRAWING\" | \"WITHDRAWN\" | \"FAILED\";\n\n/** Which action a FAILED row failed at. */\nexport type CatalogueFailedAction = \"PUBLISH\" | \"WITHDRAW\";\n\n/**\n * Why a row FAILED, as a code the host turns into its own words. Vocabulary,\n * not copy: the engine writes no sentence a person reads.\n *\n * - `REFUSED` — the marketplace said no; its own words are in `failureReason`.\n * - `UNAVAILABLE` — no usable answer on any attempt (5xx, 429, timeouts).\n * - `TIMEOUT` — still on its way a day later (the sweep gave up).\n * - `NOT_CONNECTED` — no live connection with a merchant id (archived, removed).\n * - `CREDENTIALS` — no credentials on file, or they would not open.\n * - `PRODUCT_GONE` — the host's catalogue no longer has the product.\n * - `UNSUPPORTED` — the marketplace has no catalogue capability any more.\n * - `INTERNAL` — the engine or the adapter threw (logged, never shown).\n */\nexport type CatalogueFailureCode =\n | \"REFUSED\"\n | \"UNAVAILABLE\"\n | \"TIMEOUT\"\n | \"NOT_CONNECTED\"\n | \"CREDENTIALS\"\n | \"PRODUCT_GONE\"\n | \"UNSUPPORTED\"\n | \"INTERNAL\";\n\n/** One publication as a host reads it. */\nexport interface CataloguePublicationView {\n provider: MarketplaceProvider;\n productId: string;\n status: CatalogueStatus;\n /** The store's price for this marketplace; null is \"the store's own price\". */\n priceCents: number | null;\n /** The price the last successful publish sent. */\n sentPriceCents: number | null;\n /** The marketplace's id for the item, from the last successful publish. */\n externalId: string | null;\n /** What the last successful publish could not do (the photo); null when it did everything. */\n warningCode: CatalogueWarningCode | null;\n failedAction: CatalogueFailedAction | null;\n /** Why it FAILED; null unless FAILED. The host's copy is keyed by it. */\n failureCode: CatalogueFailureCode | null;\n /**\n * The marketplace's OWN words for a `REFUSED` (its answer's body, truncated);\n * null for every other code. Never an engine or internal message.\n */\n failureReason: string | null;\n requestedAt: Date;\n publishedAt: Date | null;\n withdrawnAt: Date | null;\n failedAt: Date | null;\n}\n\n/** A publication row, with the engine's own columns. */\nexport interface CatalogueRow extends CataloguePublicationView {\n id: string;\n clientId: string;\n imageRef: string | null;\n imageSourceUrl: string | null;\n}\n\nexport const CATALOGUE_ROW_SELECT = {\n id: true,\n clientId: true,\n provider: true,\n productId: true,\n status: true,\n priceCents: true,\n sentPriceCents: true,\n externalId: true,\n imageRef: true,\n imageSourceUrl: true,\n warningCode: true,\n failedAction: true,\n failureCode: true,\n failureReason: true,\n requestedAt: true,\n publishedAt: true,\n withdrawnAt: true,\n failedAt: true,\n} as const;\n\n/** The delegate, or null on a host that has not composed the catalogue model. */\nexport type CatalogueTable = NonNullable<MarketplaceDb[\"marketplaceCataloguePublication\"]>;\n\nexport async function catalogueTable(ctx: EngineContext): Promise<CatalogueTable | null> {\n return (await ctx.ports.db()).marketplaceCataloguePublication ?? null;\n}\n\n/** A row without the engine's own columns. */\nexport function viewOf(row: CatalogueRow): CataloguePublicationView {\n return {\n provider: row.provider,\n productId: row.productId,\n status: row.status,\n priceCents: row.priceCents,\n sentPriceCents: row.sentPriceCents,\n externalId: row.externalId,\n warningCode: row.warningCode,\n failedAction: row.failedAction,\n failureCode: row.failureCode,\n failureReason: row.failureReason,\n requestedAt: row.requestedAt,\n publishedAt: row.publishedAt,\n withdrawnAt: row.withdrawnAt,\n failedAt: row.failedAt,\n };\n}\n\n/** The failure columns cleared, for every write that leaves FAILED. */\nexport const NO_FAILURE = { failedAction: null, failureCode: null, failureReason: null, failedAt: null } as const;\n\n/** The longest failure reason a row keeps: the column is read by a person in a list. */\nconst REASON_LIMIT = 300;\n\nexport function truncateReason(reason: string): string {\n return reason.length > REASON_LIMIT ? reason.slice(0, REASON_LIMIT) : reason;\n}\n\n/** Why a connection cannot carry a catalogue call. */\ninterface ConnectionProblem {\n problem: \"NOT_CONNECTED\" | \"CREDENTIALS\";\n}\n\n/**\n * Everything one catalogue call needs from the store's connection, or why it\n * cannot be used: NOT_CONNECTED (none, archived, no merchant id) or\n * CREDENTIALS (none on file, or they will not open).\n */\nexport async function catalogueConnection(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n categoryState?: CategoryRunState,\n): Promise<Omit<CatalogueCallContext, \"now\"> | ConnectionProblem> {\n const merchantId = await connectionMerchantId(ctx, clientId, provider);\n if (merchantId === null) return { problem: \"NOT_CONNECTED\" };\n try {\n const connection = await readOutboundConnection(ctx, clientId, provider);\n if (!connection) return { problem: \"CREDENTIALS\" };\n const catalogue = ctx.ports.catalogue;\n return {\n ...connection,\n http: ctx.ports.http,\n tokens: ctx.tokens,\n externalMerchantId: merchantId,\n loadImage: (url) => (catalogue ? catalogue.image(url) : Promise.resolve(null)),\n category: (name, resolve) => resolveCategory(ctx, { clientId, provider }, name, resolve, categoryState),\n forgetCategory: (name) => forgetCategory(ctx, { clientId, provider }, name),\n };\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.catalogue: ${provider} credentials of ${clientId} do not open: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { problem: \"CREDENTIALS\" };\n }\n}\n","import type { OutboundResult } from \"./adapter\";\nimport type { CatalogueCallContext, CatalogueFailure, CataloguePublishResult, MarketplaceCatalogue } from \"./catalogue-port\";\nimport {\n CATALOGUE_ROW_SELECT,\n NO_FAILURE,\n catalogueConnection,\n catalogueTable,\n truncateReason,\n type CatalogueFailureCode,\n type CatalogueRow,\n type CatalogueTable,\n} from \"./catalogue-store\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The catalogue job (`marketplace.catalogue`): one publish or withdraw of one\n * product on one marketplace, start to finish (FUT-4768).\n *\n * The same rules as the outbound job, for the same reasons:\n *\n * - **idempotent by the ROW** — a run acts only while the row still asks for\n * its action (PUBLISHING for a publish, WITHDRAWING for a withdraw) at the\n * instant it was asked (`requested_at`), so a duplicate or stale job calls\n * nobody, and a stamp never overwrites a newer ask;\n * - **2xx done, a final 4xx FAILED with the marketplace's reason, anything\n * else retried** until the last attempt, which ends FAILED;\n * - **queued, never called inline** — `publish` and `withdraw` only stamp and\n * enqueue; the sweep re-queues a row still owed.\n *\n * Push or pull is the adapter's `catalogue.mode`, never a provider check: a\n * push marketplace gets the item written or withdrawn; a pull marketplace is\n * told its menu changed (the host serves the document, which already reflects\n * the row).\n */\n\n/** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */\nexport const MARKETPLACE_CATALOGUE_JOB = \"marketplace.catalogue\";\n\n/** What one run does to its row. */\nexport type CatalogueAction = \"publish\" | \"withdraw\";\n\n/** The job's payload. Identifiers only: what to send lives on the row and in the host's catalogue. */\nexport interface CatalogueJobPayload {\n clientId: string;\n publicationId: string;\n action: CatalogueAction;\n}\n\n/** What one run did. */\nexport type CatalogueOutcome =\n | { kind: \"skipped\"; reason: string }\n | { kind: \"done\"; action: CatalogueAction }\n /** `reason` is the row's failure code; the detail went to the log. */\n | { kind: \"failed\"; action: CatalogueAction; reason: string };\n\n/** Thrown so the queue retries. Its message is what the job log reads. */\nexport class CatalogueRetryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CatalogueRetryError\";\n }\n}\n\nconst WANTED: Record<CatalogueAction, string> = { publish: \"PUBLISHING\", withdraw: \"WITHDRAWING\" };\n\n/** The dedupe key: one queued run per (row, ask). A re-ask carries a new instant, so it is never swallowed. */\nexport function catalogueDedupeKey(payload: CatalogueJobPayload, requestedAt: Date): string {\n return `${MARKETPLACE_CATALOGUE_JOB}:${payload.action}:${payload.publicationId}:${requestedAt.getTime()}`;\n}\n\n/** Queue one run. The queue port never throws; a refusal is logged, and the sweep re-queues the row. */\nexport async function enqueueCatalogue(ctx: EngineContext, payload: CatalogueJobPayload, dedupeKey: string): Promise<void> {\n const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CATALOGUE_JOB, payload, { dedupeKey });\n if (outcome.enqueued) return;\n ctx.ports.logger.warn(\n `${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} was not queued; the outbound sweep will re-queue it` +\n (outcome.reason ? ` (${outcome.reason})` : \"\"),\n );\n}\n\ntype RunResult = CataloguePublishResult | OutboundResult;\n\n/** What a run did instead of a call: an engine-side reason it cannot be made. */\ntype Run =\n | { result: RunResult; sentPriceCents: number | null; name?: string; waited?: boolean }\n | { code: CatalogueFailureCode };\n\n/** The call this run makes, or the code that stands in for it. */\nasync function callFor(\n ctx: EngineContext,\n row: CatalogueRow,\n action: CatalogueAction,\n catalogue: MarketplaceCatalogue,\n call: CatalogueCallContext,\n): Promise<Run> {\n if (action === \"withdraw\") {\n if (catalogue.mode === \"pull\") return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: null };\n const ref = { ref: row.id, productId: row.productId, externalId: row.externalId };\n return { result: await catalogue.withdrawItem(call, ref), sentPriceCents: null };\n }\n const item = (await ctx.ports.catalogue?.items(row.clientId, [row.productId]))?.get(row.productId);\n if (!item) return { code: \"PRODUCT_GONE\" };\n const priceCents = row.priceCents ?? item.priceCents;\n if (catalogue.mode === \"pull\") {\n return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: priceCents, name: item.name };\n }\n const storedImage = row.imageRef && row.imageSourceUrl ? { ref: row.imageRef, sourceUrl: row.imageSourceUrl } : null;\n const out = { ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage };\n return { result: await catalogue.publishItem(call, out), sentPriceCents: priceCents, name: item.name };\n}\n\n/** The predicate a stamp holds to: the row still asks for this action, at the instant this run read. */\nconst stillAsked = (row: CatalogueRow, action: CatalogueAction) => ({\n id: row.id,\n status: WANTED[action],\n requestedAt: row.requestedAt,\n});\n\n/**\n * A publish that landed after the store asked for the product out (a withdraw\n * while publishing): the item is on the marketplace now, so the withdraw is\n * owed again. The row goes back to WITHDRAWING with a fresh ask, carrying the\n * id the publish answered, and the withdraw is queued.\n */\nasync function withdrawLateLanding(ctx: EngineContext, table: CatalogueTable, row: CatalogueRow, externalId: string | null): Promise<void> {\n const now = ctx.ports.clock.now();\n const moved = await table.updateMany({\n where: { id: row.id, status: { in: [\"WITHDRAWING\", \"WITHDRAWN\"] } },\n data: { status: \"WITHDRAWING\", requestedAt: now, ...(externalId === null ? {} : { externalId }) },\n });\n if (moved.count === 0) return;\n const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action: \"withdraw\" };\n await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));\n}\n\n/**\n * A withdraw that landed after the store switched the product back on (a\n * publish while withdrawing): the item is out on the marketplace now, so the\n * publish is owed again, whether or not its own run already went out. The row\n * takes a fresh ask and the publish is queued: the store's last tap wins.\n */\nasync function publishLateLanding(ctx: EngineContext, table: CatalogueTable, row: CatalogueRow): Promise<void> {\n const now = ctx.ports.clock.now();\n const moved = await table.updateMany({\n where: { id: row.id, status: { in: [\"PUBLISHING\", \"PUBLISHED\"] } },\n data: { status: \"PUBLISHING\", requestedAt: now },\n });\n if (moved.count === 0) return;\n const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action: \"publish\" };\n await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));\n}\n\n/**\n * Map the SKU the marketplace's orders will carry for a published item to the\n * host's product, so those orders arrive mapped instead of on the attention\n * list — only when the SKU has no link yet, or an unmapped one: a store that\n * mapped it to another product on purpose keeps its own mapping. Kept on a\n * withdraw: an order placed before it still maps.\n */\nasync function mapPublishedSku(ctx: EngineContext, row: CatalogueRow, result: RunResult, name: string | undefined): Promise<void> {\n const sku = (result.kind === \"published\" ? result.sku : undefined) ?? row.productId;\n const db = await ctx.ports.db();\n const key = { clientId: row.clientId, provider: row.provider, externalSku: sku };\n const existing = (await db.marketplaceMenuLink.findMany({ where: key, select: { menuItemId: true }, take: 1 })) as {\n menuItemId: string | null;\n }[];\n if (existing[0]?.menuItemId) return;\n await db.marketplaceMenuLink.upsert({\n where: { clientId_provider_externalSku: key },\n create: { ...key, externalName: name ?? null, menuItemId: row.productId, lastSeenAt: ctx.ports.clock.now() },\n update: { menuItemId: row.productId },\n });\n}\n\n/** What a successful publish leaves on the row beyond its state: the item's id, the photo held, the warning. */\nfunction publishedExtras(result: RunResult): Record<string, unknown> {\n if (result.kind !== \"published\") return { warningCode: null };\n const image =\n result.image === undefined\n ? {}\n : { imageRef: result.image?.ref ?? null, imageSourceUrl: result.image?.sourceUrl ?? null };\n return { externalId: result.externalId, warningCode: result.warning ?? null, ...image };\n}\n\nasync function stampSuccess(\n ctx: EngineContext,\n table: CatalogueTable,\n row: CatalogueRow,\n action: CatalogueAction,\n result: RunResult,\n sentPriceCents: number | null,\n): Promise<void> {\n const now = ctx.ports.clock.now();\n const externalId = result.kind === \"published\" ? result.externalId : null;\n const data =\n action === \"publish\"\n ? { status: \"PUBLISHED\", publishedAt: now, sentPriceCents, ...publishedExtras(result), ...NO_FAILURE }\n : { status: \"WITHDRAWN\", withdrawnAt: now, ...NO_FAILURE };\n const moved = await table.updateMany({ where: stillAsked(row, action), data });\n if (moved.count > 0) return;\n if (action === \"publish\") await withdrawLateLanding(ctx, table, row, externalId);\n else await publishLateLanding(ctx, table, row);\n}\n\n/** One failure, as the row keeps it: a code, and the marketplace's own words only for a refusal. */\ninterface Failure {\n code: CatalogueFailureCode;\n reason: string | null;\n}\n\nasync function stampFailure(table: CatalogueTable, row: CatalogueRow, action: CatalogueAction, failure: Failure, now: Date): Promise<void> {\n await table.updateMany({\n where: stillAsked(row, action),\n data: {\n status: \"FAILED\",\n failedAction: action === \"publish\" ? \"PUBLISH\" : \"WITHDRAW\",\n failureCode: failure.code,\n failureReason: failure.reason === null ? null : truncateReason(failure.reason),\n failedAt: now,\n },\n });\n}\n\n/** A final answer as the row keeps it: the marketplace's refusal with its words, or UNAVAILABLE. */\nfunction failureOf(result: CatalogueFailure): Failure {\n if (result.kind === \"retry\") return { code: \"UNAVAILABLE\", reason: null };\n return { code: \"REFUSED\", reason: result.message === \"\" ? null : result.message };\n}\n\n/** The run this row gets: the adapter's call, or the code that stands in for it. */\nasync function runFor(ctx: EngineContext, row: CatalogueRow, action: CatalogueAction): Promise<Run> {\n const catalogue = ctx.registry.get(row.provider)?.catalogue;\n if (!catalogue) return { code: \"UNSUPPORTED\" };\n const categoryState = { waited: false };\n const connection = await catalogueConnection(ctx, row.clientId, row.provider, categoryState);\n // A withdraw for a connection that is gone (archived, removed) has nobody to tell: it is out.\n if (\"problem\" in connection && connection.problem === \"NOT_CONNECTED\" && action === \"withdraw\") {\n return { result: { kind: \"accepted\" }, sentPriceCents: null };\n }\n if (\"problem\" in connection) return { code: connection.problem };\n const run = await callFor(ctx, row, action, catalogue, { ...connection, now: ctx.ports.clock.now() });\n return \"result\" in run ? { ...run, waited: categoryState.waited } : run;\n}\n\n/**\n * The last attempt of a publish that only ever WAITED for another publish to\n * create its category: not a failure of this item. The row stays PUBLISHING\n * (the store still sees \"sending…\") and the outbound sweep re-queues it; by\n * then the category is stored, or its claim is stale and taken over.\n */\nfunction waitedOut(ctx: EngineContext, row: CatalogueRow, action: CatalogueAction, detail: string): CatalogueOutcome {\n ctx.ports.logger.warn(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} left for the sweep: ${detail}`);\n return { kind: \"skipped\", reason: detail };\n}\n\nasync function fail(ctx: EngineContext, table: CatalogueTable, row: CatalogueRow, action: CatalogueAction, failure: Failure, detail: string) {\n await stampFailure(table, row, action, failure, ctx.ports.clock.now());\n ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} failed (${failure.code}): ${detail}`);\n ctx.ports.publishChanged(row.clientId);\n return { kind: \"failed\" as const, action, reason: failure.code };\n}\n\nasync function runOnce(\n ctx: EngineContext,\n table: CatalogueTable,\n payload: CatalogueJobPayload,\n attempt: { attempt: number; maxAttempts: number },\n): Promise<CatalogueOutcome> {\n const row = await readRow(table, payload);\n if (!row) return { kind: \"skipped\", reason: \"no such publication for this tenant\" };\n const { action } = payload;\n if (row.status !== WANTED[action]) return { kind: \"skipped\", reason: `the publication is ${row.status}, not ${WANTED[action]}` };\n const run = await runFor(ctx, row, action);\n if (\"code\" in run) return fail(ctx, table, row, action, { code: run.code, reason: null }, run.code);\n return settle(ctx, table, row, action, run, attempt);\n}\n\n/** Turn a call's answer into the row's stamp, a retry, a wait for the sweep, or a failure. */\nasync function settle(\n ctx: EngineContext,\n table: CatalogueTable,\n row: CatalogueRow,\n action: CatalogueAction,\n run: Exclude<Run, { code: CatalogueFailureCode }>,\n attempt: { attempt: number; maxAttempts: number },\n): Promise<CatalogueOutcome> {\n const { result } = run;\n if (result.kind === \"accepted\" || result.kind === \"published\") {\n await stampSuccess(ctx, table, row, action, result, run.sentPriceCents);\n if (action === \"publish\") await mapPublishedSku(ctx, row, result, run.name);\n ctx.ports.publishChanged(row.clientId);\n return { kind: \"done\", action };\n }\n const detail = result.kind === \"retry\" ? result.reason : `refused ${result.status}: ${result.message}`;\n if (result.kind === \"retry\" && attempt.attempt < attempt.maxAttempts) {\n throw new CatalogueRetryError(`${action} of ${row.productId} on ${row.provider}: ${detail}`);\n }\n if (result.kind === \"retry\" && run.waited) return waitedOut(ctx, row, action, detail);\n return fail(ctx, table, row, action, failureOf(result), detail);\n}\n\nfunction readRow(table: CatalogueTable, payload: CatalogueJobPayload): Promise<CatalogueRow | null> {\n return table.findFirst({\n where: { id: payload.publicationId, clientId: payload.clientId },\n select: CATALOGUE_ROW_SELECT,\n }) as Promise<CatalogueRow | null>;\n}\n\n/**\n * Run one queued catalogue call. Throws {@link CatalogueRetryError} for an\n * answer worth retrying before the last attempt; any other throw is rethrown\n * for the queue to retry, and on the last attempt ends FAILED, INTERNAL (the\n * message is logged, never stored).\n */\nexport async function runCatalogue(\n ctx: EngineContext,\n payload: CatalogueJobPayload,\n attempt: { attempt: number; maxAttempts: number },\n): Promise<CatalogueOutcome> {\n const table = await catalogueTable(ctx);\n if (!table) return { kind: \"skipped\", reason: \"the host has no catalogue table\" };\n try {\n return await runOnce(ctx, table, payload, attempt);\n } catch (error) {\n if (error instanceof CatalogueRetryError || attempt.attempt < attempt.maxAttempts) throw error;\n const detail = error instanceof Error ? error.message : String(error);\n const row = await readRow(table, payload);\n if (row && row.status === WANTED[payload.action]) return fail(ctx, table, row, payload.action, { code: \"INTERNAL\", reason: null }, detail);\n ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} failed: ${detail}`);\n return { kind: \"failed\", action: payload.action, reason: \"INTERNAL\" };\n }\n}\n","import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * The durable inbox , needed here for two reasons rather than one.\n *\n * A marketplace's delivery is not reliably exactly-once, so the SAME event\n * arrives more than once and the pipeline must be able to say \"already seen\".\n * It is not reliably at-least-once either, so reconciliation polling has to be\n * able to inject an event the webhook never brought. Both paths write here, and\n * `(provider, eventId)` is what collapses them onto one row — a duplicate is a\n * DB-level no-op rather than a second order.\n *\n * The RAW payload is stored because normalization is the part most likely to be\n * wrong. When a mapping bug drops a line, the only way to reconstruct what the\n * marketplace actually said is to have kept it.\n */\n\n/** What {@link recordInboxEvent} tells the caller about a delivery. */\ninterface InboxRecord {\n id: string;\n /** False when this exact delivery had already been recorded. */\n fresh: boolean;\n}\n\n/**\n * Record one delivery, deduped on `(provider, eventId)`.\n *\n * Returns `fresh: false` for a redelivery, which is the pipeline's whole\n * idempotency story at the door: the caller stops there and answers the\n * marketplace 200. Answering 200 to a duplicate matters as much as processing\n * the original — a marketplace that gets an error redelivers, and a pipeline\n * that errors on its own duplicates never stops receiving them.\n */\nexport async function recordInboxEvent(\n ctx: EngineContext,\n input: { clientId: string | null; event: NormalizedEvent; payload: unknown },\n): Promise<InboxRecord> {\n const db = await ctx.ports.db();\n const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };\n const existing = (await db.marketplaceInboxEvent.findUnique({\n where: key,\n select: { id: true },\n })) as { id: string } | null;\n if (existing) return { id: existing.id, fresh: false };\n\n try {\n const row = (await db.marketplaceInboxEvent.create({\n data: {\n clientId: input.clientId,\n provider: input.event.provider,\n eventId: input.event.eventId,\n eventType: input.event.eventType,\n externalOrderId: input.event.externalOrderId,\n payload: input.payload,\n // The engine's clock, not the database's: an announced order's\n // acceptance window counts from here (`./fetch-order.ts`).\n receivedAt: ctx.ports.clock.now(),\n },\n select: { id: true },\n })) as { id: string };\n return { id: row.id, fresh: true };\n } catch (error) {\n // The check-then-insert above is not atomic, and two simultaneous\n // redeliveries are exactly the shape that loses that race. The unique index\n // is the real guard; this turns losing the race into the same answer the\n // check would have given, rather than a 500 that provokes another retry.\n if ((error as { code?: string }).code !== \"P2002\") throw error;\n const raced = (await db.marketplaceInboxEvent.findUnique({\n where: key,\n select: { id: true },\n })) as { id: string } | null;\n return { id: raced?.id ?? \"\", fresh: false };\n }\n}\n\n/** How an inbox row ended up. */\ntype InboxOutcome = \"PROCESSED\" | \"FAILED\" | \"IGNORED\";\n\n/**\n * Close out an inbox row.\n *\n * `attempts` increments on every close, including the successful one, so the\n * count reads as \"how many times did we touch this\" rather than \"how many times\n * did we fail\" — a row PROCESSED on its third attempt is a different story from\n * one processed on its first, and only the incrementing version can tell them\n * apart.\n */\nexport async function settleInboxEvent(\n ctx: EngineContext,\n id: string,\n outcome: InboxOutcome,\n error?: string,\n): Promise<void> {\n if (!id) return;\n const db = await ctx.ports.db();\n await db.marketplaceInboxEvent.update({\n where: { id },\n data: {\n status: outcome,\n // Truncated: a provider's error body can be a page of HTML, and the\n // column exists to be read by a human in a list.\n error: error ? error.slice(0, 500) : null,\n processedAt: ctx.ports.clock.now(),\n attempts: { increment: 1 },\n },\n });\n}\n\n/**\n * Leave a row PENDING with its reason recorded, and count the attempt.\n *\n * The state between \"done\" and \"broken\": the delivery is fine and the STORE is\n * not ready for it — the channel is switched off, or was mid-onboarding when\n * the order came in. Settling it either way would be a lie (IGNORED discards an\n * order that could still be ingested; FAILED blames the payload), so it stays\n * PENDING and the sweep picks it up again.\n *\n * The attempt still counts, which is what stops the churn: the sweep's own\n * attempt bound retires a row after a few passes over a store that never turned\n * the channel on, instead of re-reading it forever.\n */\nexport async function deferInboxEvent(\n ctx: EngineContext,\n id: string,\n reason: string,\n): Promise<void> {\n if (!id) return;\n const db = await ctx.ports.db();\n await db.marketplaceInboxEvent.update({\n where: { id },\n data: { error: reason.slice(0, 500), attempts: { increment: 1 } },\n });\n}\n\n/** One stored delivery, as the retry sweep re-reads it. */\nexport interface PendingInboxEvent {\n id: string;\n clientId: string;\n provider: MarketplaceProvider;\n payload: unknown;\n /** When the delivery was recorded. */\n receivedAt?: Date | null;\n}\n\n/**\n * Deliveries recorded but never processed, oldest first.\n *\n * PENDING and FAILED both qualify: a row left PENDING is one whose process died\n * between recording and processing — the exact crash the durable inbox exists\n * to survive — and dropping it would make the inbox a log rather than a queue.\n *\n * Unattributed events (`clientId` null) are deliberately NOT returned. There is\n * no tenant to ingest them into, so retrying achieves nothing; they stay in the\n * table as the evidence of a half-finished onboarding.\n */\nexport async function listRetryableInboxEvents(\n ctx: EngineContext,\n): Promise<PendingInboxEvent[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceInboxEvent.findMany({\n where: {\n status: { in: [\"PENDING\", \"FAILED\"] },\n clientId: { not: null },\n attempts: { lt: ctx.ports.maxInboxAttempts },\n },\n orderBy: { receivedAt: \"asc\" },\n take: ctx.ports.reconcileBatchSize,\n select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true },\n })) as { id: string; clientId: string; provider: string; payload: unknown; receivedAt: Date | null }[];\n return rows.map((row) => ({\n id: row.id,\n clientId: row.clientId,\n provider: row.provider as MarketplaceProvider,\n payload: row.payload,\n receivedAt: row.receivedAt,\n }));\n}\n","import type { EngineContext, MarketplaceDb } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * External SKU ↔ catalog mapping .\n *\n * The rule the whole module is built around: an unmapped SKU is a ROW, not an\n * absence. Every SKU an order has ever carried has a link row, mapped or not,\n * so the attention list is a query rather than a reconciliation, and mapping\n * one is an update on something the store can already see. Manual mapping\n * upkeep has to be visibly cheap or it does not happen — and a store that stops\n * doing it is a store quietly selling food it cannot make.\n *\n * The package never dereferences `menuItemId`. It asks the host whether the id\n * is theirs (`order.catalogHas`, in `./bulk.ts`) and stores it; what the id\n * MEANS is the host's.\n */\n\n/** A link as every read surface sees it. */\nexport interface MarketplaceMenuLinkView {\n id: string;\n provider: MarketplaceProvider;\n externalSku: string;\n externalName: string;\n /** The host catalog id, or null while the SKU is unmapped. */\n menuItemId: string | null;\n lastSeenAt: Date;\n}\n\nconst LINK_SELECT = {\n id: true,\n provider: true,\n externalSku: true,\n externalName: true,\n menuItemId: true,\n lastSeenAt: true,\n} as const;\n\ninterface LinkRow {\n id: string;\n provider: string;\n externalSku: string;\n externalName: string | null;\n menuItemId: string | null;\n lastSeenAt: Date;\n}\n\nfunction toView(row: LinkRow): MarketplaceMenuLinkView {\n return {\n id: row.id,\n provider: row.provider as MarketplaceProvider,\n externalSku: row.externalSku,\n externalName: row.externalName ?? row.externalSku,\n menuItemId: row.menuItemId,\n lastSeenAt: row.lastSeenAt,\n };\n}\n\n/**\n * A store's SKU map. `unmappedOnly` is the attention list.\n *\n * Ordered by `lastSeenAt` descending, which is the ordering that matters for\n * the unmapped half: a store fixing five mappings should fix the five that are\n * costing them money right now, not the five that happen to be oldest.\n */\nexport async function listMarketplaceMenuLinks(\n ctx: EngineContext,\n input: { clientId: string; provider?: MarketplaceProvider; unmappedOnly?: boolean; ids?: readonly string[] },\n): Promise<MarketplaceMenuLinkView[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceMenuLink.findMany({\n where: {\n clientId: input.clientId,\n ...(input.ids ? { id: { in: [...input.ids] } } : {}),\n ...(input.provider ? { provider: input.provider } : {}),\n ...(input.unmappedOnly ? { menuItemId: null } : {}),\n },\n select: LINK_SELECT,\n orderBy: { lastSeenAt: \"desc\" },\n })) as LinkRow[];\n return rows.map(toView);\n}\n\n/**\n * Point an external SKU at a catalog id, or unmap it, inside the caller's\n * transaction. The caller has already checked the id is this tenant's\n * (`order.catalogHas`). Creates the link if the SKU has never been seen: an\n * operator mapping ahead of the first order is doing the right thing.\n */\nexport async function upsertLink(\n db: MarketplaceDb,\n input: {\n clientId: string;\n provider: MarketplaceProvider;\n externalSku: string;\n externalName?: string;\n menuItemId: string | null;\n },\n): Promise<MarketplaceMenuLinkView> {\n const row = (await db.marketplaceMenuLink.upsert({\n where: {\n clientId_provider_externalSku: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: input.externalSku,\n },\n },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: input.externalSku,\n externalName: input.externalName ?? input.externalSku,\n menuItemId: input.menuItemId,\n },\n // `externalName` is NOT rewritten here. It is the marketplace's snapshot of\n // what it called the item, and an operator's typing is not a better record\n // of that than the marketplace's own text.\n update: { menuItemId: input.menuItemId },\n select: LINK_SELECT,\n })) as LinkRow;\n return toView(row);\n}\n\n/**\n * Resolve an order's SKUs to catalog ids, recording every one of them.\n *\n * Called on the ingestion path, so it does two jobs at once and both are\n * required: it answers what each SKU maps to, and it makes sure a row exists\n * for each — including the ones that map to nothing, which is how an unmapped\n * SKU reaches the attention list at all. Upserting on the ingest path is what\n * makes the list self-maintaining; a store never has to discover the gap by\n * reading a ticket.\n */\nexport async function resolveSkus(\n db: MarketplaceDb,\n input: {\n clientId: string;\n provider: MarketplaceProvider;\n skus: { externalSku: string; name: string }[];\n seenAt: Date;\n },\n): Promise<Map<string, string | null>> {\n const resolved = new Map<string, string | null>();\n for (const sku of input.skus) {\n const row = (await db.marketplaceMenuLink.upsert({\n where: {\n clientId_provider_externalSku: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: sku.externalSku,\n },\n },\n create: {\n clientId: input.clientId,\n provider: input.provider,\n externalSku: sku.externalSku,\n externalName: sku.name,\n lastSeenAt: input.seenAt,\n },\n update: { lastSeenAt: input.seenAt },\n select: { menuItemId: true },\n })) as { menuItemId: string | null };\n resolved.set(sku.externalSku, row.menuItemId);\n }\n return resolved;\n}\n","import { markMarketplaceEventSeen } from \"./integration\";\nimport { resolveSkus } from \"./menu-links\";\nimport { enqueueOutbound } from \"./outbound-queue\";\nimport type { EngineContext, MarketplaceDb, ResolvedOrderLine } from \"./ports\";\nimport type { NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * Normalized marketplace order → the host's own order.\n *\n * The rule this module is written around, stated once so every decision below\n * reads against it: **losing a paid marketplace order is the one unforgivable\n * failure.** An unmapped SKU, a buyer with no name, a total that does not equal\n * the line sum — none of them reject the order. They land, flagged, on a screen\n * a human can act on. The only thing that stops an ingestion is a condition\n * under which persisting would be WRONG rather than incomplete.\n *\n * Idempotent on `(provider, externalOrderId)`, which the acceptance table's\n * unique enforces. That is what makes a redelivered webhook, a reconciliation\n * poll racing it, and a retry after a crash all safe: each either creates the\n * one order or finds it already there. The pre-read below is a fast path, not\n * the guarantee — two concurrent deliveries both miss it and only one of them\n * reaches a row.\n */\n\n/** What one ingestion did. */\nexport interface IngestResult {\n /** The HOST's order id. */\n orderId: string;\n /** False when the order already existed — a redelivery, not a second sale. */\n created: boolean;\n /** SKUs that arrived with nothing behind them, in this order. */\n unmappedSkus: string[];\n /** Whether the connection's policy made this order born accepted. */\n autoAccepted: boolean;\n}\n\n/** The store's operating decisions, read from the connection at ingest time. */\nexport interface IngestSettings {\n autoAccept: boolean;\n ackSlaSeconds: number;\n}\n\n/**\n * Resolve the order's SKUs and compose its lines.\n *\n * `resolveSkus` does double duty on this path: it answers what each SKU maps to\n * AND records every one of them, which is how an unmapped SKU reaches the\n * store's attention list without anyone having to notice it first.\n */\nasync function composeLines(\n db: MarketplaceDb,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n seenAt: Date,\n): Promise<ResolvedOrderLine[]> {\n const mapping = await resolveSkus(db, {\n clientId,\n provider: order.provider,\n skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),\n seenAt,\n });\n return order.lines.map((line) => ({\n externalSku: line.externalSku,\n // The MARKETPLACE's text, never the catalog's, even for a mapped line.\n // Every other order snapshots what the buyer was shown, and what this buyer\n // was shown is the marketplace's menu — a mapped line renamed to the host's\n // own product name would quietly disagree with the receipt in the bag.\n name: line.name,\n quantity: line.quantity,\n unitPriceCents: line.unitPriceCents,\n note: line.note,\n subjectRef: mapping.get(line.externalSku) ?? null,\n }));\n}\n\n/** The acceptance row an ingest writes: born ACCEPTED or on the clock. */\nfunction acceptanceData(\n clientId: string,\n orderId: string,\n order: NormalizedMarketplaceOrder,\n settings: IngestSettings,\n now: Date,\n clockStartsAt: Date,\n): Record<string, unknown> {\n const accepted = settings.autoAccept;\n return {\n clientId,\n orderId,\n provider: order.provider,\n externalOrderId: order.externalOrderId,\n externalDisplayId: order.externalDisplayId,\n // Who carries a delivery: the merchant's courier or the marketplace's fleet.\n deliveredBy: order.deliveredBy ?? null,\n status: accepted ? \"ACCEPTED\" : \"AWAITING\",\n acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1000),\n acknowledgedAt: accepted ? now : null,\n externalDueAt: order.deliveryDueAt,\n commissionCents: order.commissionCents,\n // The order's SKUs: what a cancellation's offending SKUs are checked against.\n lineSkus: [...new Set(order.lines.map((line) => line.externalSku))],\n };\n}\n\n/**\n * Ingest one order.\n *\n * The deadline is stamped HERE, from the connection's SLA, and never recomputed\n * afterwards: a store that later lengthens its SLA must not move the deadline of\n * an order already on the clock, and one that shortens it must not retroactively\n * expire orders that were fine when they arrived.\n *\n * The acceptance row and the host's order are written in that dependency order\n * — the host creates its own row first and hands back an id, because only the\n * host knows what creating one costs. Auto-accept is decided at arrival so the\n * order is BORN accepted rather than created and immediately updated: the\n * two-step version has a window in which a crash leaves an order the store\n * believes was auto-accepted sitting on a clock nobody is watching.\n */\nexport async function ingestMarketplaceOrder(\n ctx: EngineContext,\n input: {\n clientId: string;\n order: NormalizedMarketplaceOrder;\n settings: IngestSettings;\n now?: Date;\n /**\n * When the acceptance window started, if not `now`: the arrival of the\n * event that announced an order fetched later. Moves ONLY the deadline;\n * the liveness stamp and an auto-accept's time stay `now`.\n */\n clockStartsAt?: Date;\n },\n): Promise<IngestResult> {\n const { clientId, order, settings } = input;\n const now = input.now ?? ctx.ports.clock.now();\n const clockStartsAt = input.clockStartsAt ?? now;\n\n const db = await ctx.ports.db();\n // Answered from this package's OWN table rather than through a port: the\n // idempotency key is `(provider, externalOrderId)` on `marketplace_acceptances`,\n // so the package holds it and no host has to be trusted to re-implement it.\n const existing = (await db.marketplaceAcceptance.findFirst({\n where: { provider: order.provider, externalOrderId: order.externalOrderId },\n select: { orderId: true },\n })) as { orderId: string } | null;\n if (existing) {\n return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };\n }\n\n const accepted = settings.autoAccept;\n // ONE transaction for the host's order, the SKU rows, the acceptance row and\n // the liveness stamp: the host's `create` is handed the transaction's client,\n // so an acceptance that cannot be written (a concurrent ingest won the\n // unique) rolls the host's order back with it, and a redelivery never meets\n // an orphan host order to duplicate.\n const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {\n const lines = await composeLines(tx, clientId, order, now);\n const created = await ctx.ports.order.create(clientId, order, lines, tx);\n await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });\n await markMarketplaceEventSeen(tx, clientId, order.provider, now);\n return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };\n });\n\n if (accepted) {\n // Born accepted is still an acceptance the marketplace must hear about.\n // Queued FIRST, never called (no ingest waits on a marketplace's API), so\n // a host half that throws cannot lose it; the sweep re-queues it if the\n // queue refused it.\n await enqueueOutbound(ctx, { clientId, orderId, action: \"confirm\" }, order.provider);\n await ctx.ports.order.onAccepted(clientId, orderId);\n }\n\n ctx.ports.publishChanged(clientId);\n\n return { orderId, created: true, unmappedSkus, autoAccepted: accepted };\n}\n","import type { MarketplaceAdapter } from \"./adapter\";\nimport type { CancellationFailureReason, EngineContext, MarketplaceDb } from \"./ports\";\n\n/**\n * How the store's own cancellation request ENDS, told to the host (FUT-4758).\n *\n * A host that requests first and cancels only on the marketplace's answer\n * needs both ends: the confirmation, to run its cancel, and the failure, to\n * put the pedido back in a person's hands. Both are optional order-port\n * callbacks, so a 1.0.0 host compiles and behaves unchanged. Each is called by\n * whichever path moved the row (the outbound job, the marketplace's event, the\n * sweep's expiry), once, and a host failure is logged, never rethrown: the\n * row's stamp has committed, and a host that fails its half must not undo it.\n */\n\nasync function tell(ctx: EngineContext, what: string, orderId: string, call: () => Promise<void>): Promise<void> {\n try {\n await call();\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/**\n * Whether the host REQUESTS FIRST and cancels on the marketplace's\n * confirmation: it binds `onCancellationConfirmed` (FUT-4758). A host that\n * does not keeps 1.0.0's behaviour exactly — the store's cancel is stamped\n * REJECTED at request time and `onRefused` runs then.\n */\nexport function requestsFirst(ctx: EngineContext): boolean {\n return ctx.ports.order.onCancellationConfirmed !== undefined;\n}\n\n/**\n * Move a row whose cancellation was just confirmed off the clock: REJECTED,\n * acknowledged now when it was still AWAITING (the table's CHECK pairs the\n * two); an accepted row keeps its acceptance instant.\n */\nexport async function rejectConfirmed(db: MarketplaceDb, orderId: string, now: Date): Promise<void> {\n await db.marketplaceAcceptance.updateMany({\n where: { orderId, status: \"AWAITING\" },\n data: { status: \"REJECTED\", acknowledgedAt: now },\n });\n await db.marketplaceAcceptance.updateMany({\n where: { orderId, status: { in: [\"ACCEPTED\", \"EXPIRED\"] } },\n data: { status: \"REJECTED\" },\n });\n}\n\n/**\n * The store's confirmed request, told to the host: `onCancellationConfirmed`\n * when bound, else `onRefused(…, \"CANCELLED\")` as in 1.0.0.\n */\nexport async function confirmedToHost(ctx: EngineContext, clientId: string, orderId: string): Promise<void> {\n if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;\n await ctx.ports.order.onRefused(clientId, orderId, \"CANCELLED\");\n}\n\n/** The marketplace confirmed the store's request. Returns whether the host took it (it has the callback). */\nexport async function tellCancellationConfirmed(ctx: EngineContext, clientId: string, orderId: string): Promise<boolean> {\n const hook = ctx.ports.order.onCancellationConfirmed;\n if (!hook) return false;\n await tell(ctx, \"was cancelled on the store's request\", orderId, () => hook.call(ctx.ports.order, clientId, orderId));\n return true;\n}\n\n/** The store's request failed, refused or timed out. */\nexport async function tellCancellationFailed(\n ctx: EngineContext,\n clientId: string,\n orderId: string,\n reason: CancellationFailureReason,\n): Promise<void> {\n const hook = ctx.ports.order.onCancellationFailed;\n if (!hook) return;\n await tell(ctx, `had its cancellation request fail (${reason})`, orderId, () =>\n hook.call(ctx.ports.order, clientId, orderId, reason),\n );\n}\n\n/** How long a request to this adapter may wait for its answer: the engine's override, else the adapter's own. */\nexport function cancellationWindowMs(ctx: EngineContext, adapter: MarketplaceAdapter): number | null {\n return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;\n}\n\n/** The columns a request that FAILED for `reason` writes. */\nexport function failedRequestData(reason: CancellationFailureReason): Record<string, unknown> {\n return { cancellationStatus: \"FAILED\", cancellationFailureReason: reason };\n}\n","import type { AcceptanceStatus, CancellationStatus } from \"./acceptance\";\nimport type { CancellationReason, MarketplaceAdapter } from \"./adapter\";\nimport { failedRequestData, tellCancellationFailed } from \"./cancellation-outcome\";\nimport type { EngineContext } from \"./ports\";\nimport { resolveReason } from \"./registry\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The store's own CANCELLATION REQUEST — the half of a refusal that must reach\n * the marketplace. Lives on the acceptance row:\n *\n * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED\n * │ ├──job 4xx / last attempt / event──▶ FAILED (REFUSED) ──event──▶ CONFIRMED\n * │ └──past the window (sweep)──▶ FAILED (TIMEOUT)\n * └──event (the marketplace cancelled)──▶ CONFIRMED\n *\n * CONFIRMED is terminal; every write is predicated on the statuses it may come\n * from, so an out-of-order event cannot undo it. A FAILED request stands for\n * nothing: the order may be decided again, or the cancellation asked again\n * (FUT-4758: a refused or timed-out request leaves the order as it was).\n */\n\n/** No request of the store's is waiting on the marketplace: never asked, or asked and FAILED. */\nfunction noStandingRequest(cancellationStatus: string | null): boolean {\n return cancellationStatus === null || cancellationStatus === \"FAILED\";\n}\n\n/** The same, as the `where` a claim is predicated on. */\nexport const NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: \"FAILED\" }] } as const;\n\n/** Why a decision (or a store cancellation) was refused. Vocabulary, not copy. */\nexport type DecisionProblemCode =\n | \"DUPLICATE\"\n | \"NOT_FOUND\"\n | \"ALREADY_DECIDED\"\n | \"EXPIRED\"\n | \"CONFLICT\"\n | \"INVALID_REASON\"\n | \"ITEMS_REQUIRED\"\n | \"UNKNOWN_ITEM\"\n | \"HOST_REFUSED\";\n\n/** One refusal, with the path of the input it is about. Nothing was written. */\nexport interface DecisionProblem {\n path: (string | number)[];\n code: DecisionProblemCode;\n /** The row's current status, for NOT-pending refusals (ALREADY_DECIDED, EXPIRED). */\n status?: AcceptanceStatus;\n /** The marketplace's codes, for INVALID_REASON. */\n validCodes?: string[];\n /** The host's own refusal, for HOST_REFUSED. */\n host?: { code: string; message: string; details?: unknown };\n}\n\n/** The acceptance row a claim reads first. */\nexport interface ClaimRow {\n orderId: string;\n provider: string;\n status: string;\n cancellationStatus: string | null;\n lineSkus: unknown;\n}\n\nexport const CLAIM_SELECT = {\n orderId: true,\n provider: true,\n status: true,\n cancellationStatus: true,\n lineSkus: true,\n} as const;\n\n/** The refusal a row that is no longer on the clock earns, or null. */\nexport function notPendingProblem(\n row: ClaimRow | undefined | null,\n path: (string | number)[],\n allowed: readonly string[] = [\"AWAITING\"],\n): DecisionProblem | null {\n if (!row) return { path: [...path, \"orderId\"], code: \"NOT_FOUND\" };\n if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;\n const status = row.status as AcceptanceStatus;\n return { path: [...path, \"orderId\"], code: status === \"EXPIRED\" ? \"EXPIRED\" : \"ALREADY_DECIDED\", status };\n}\n\n/** What a refusal stamps, and with which reason and SKUs. */\nexport interface CancellationPlan {\n status: CancellationStatus | null;\n reason: CancellationReason | null;\n skus: string[];\n}\n\nfunction lineSkusOf(row: ClaimRow): Set<string> | null {\n return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;\n}\n\n/** Every refusal the named SKUs earn: none when the reason needs some, an unknown one. */\nfunction skuProblems(\n reason: CancellationReason | null,\n skus: string[],\n row: ClaimRow,\n path: (string | number)[],\n): DecisionProblem[] {\n if (reason?.needsItems && skus.length === 0) return [{ path: [...path, \"offendingSkus\"], code: \"ITEMS_REQUIRED\" }];\n const known = lineSkusOf(row);\n // A row from before `line_skus` existed cannot be checked; its SKUs pass.\n if (!known) return [];\n return skus.flatMap((sku, index) =>\n known.has(sku) ? [] : [{ path: [...path, \"offendingSkus\", index], code: \"UNKNOWN_ITEM\" as const }],\n );\n}\n\n/** The refusal of a named code that is not the marketplace's, or null. */\nfunction invalidReasonProblem(\n adapter: MarketplaceAdapter,\n reason: CancellationReason | null,\n code: string | null | undefined,\n path: (string | number)[],\n): DecisionProblem | null {\n if (code === null || code === undefined || reason) return null;\n const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);\n return { path: [...path, \"reasonCode\"], code: \"INVALID_REASON\", validCodes };\n}\n\n/**\n * Plan the cancellation half of a refusal, or say what is wrong with it.\n *\n * - No adapter (a provider nobody registers any more): nothing goes out.\n * - The code must be the marketplace's; with none, its first reason is taken.\n * - A reason that `needsItems` needs offending SKUs, each one of the order's.\n * - An API that cannot cancel — at all, or after an accept — stamps FAILED at\n * once: the request cannot be made from here, and FAILED is what puts the\n * adapter's app link in front of a person.\n * - Otherwise PENDING, for the outbound job.\n */\nexport function planCancellation(\n adapter: MarketplaceAdapter | null,\n input: { reasonCode?: string | null; offendingSkus?: readonly string[] },\n row: ClaimRow,\n path: (string | number)[],\n): CancellationPlan | DecisionProblem[] {\n if (!adapter) return { status: null, reason: null, skus: [] };\n const reason = resolveReason(adapter, input.reasonCode);\n const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);\n if (invalid) return [invalid];\n const skus = [...new Set(input.offendingSkus ?? [])];\n const problems = skuProblems(reason, skus, row, path);\n if (problems.length > 0) return problems;\n const { apiCancel, cancelAfterAccept } = adapter.capabilities;\n const canAsk = apiCancel && reason !== null && (row.status === \"AWAITING\" || cancelAfterAccept);\n return { status: canAsk ? \"PENDING\" : \"FAILED\", reason, skus };\n}\n\n/** The columns one refusal writes, from the status it leaves. */\nexport function refusalData(plan: CancellationPlan, fromStatus: string, now: Date): Record<string, unknown> {\n return {\n status: \"REJECTED\",\n // An accepted row keeps the instant it was accepted; a row leaving the\n // clock is acknowledged now (the table's CHECK pairs the two).\n ...(fromStatus === \"AWAITING\" ? { acknowledgedAt: now } : {}),\n cancellationStatus: plan.status,\n cancellationReasonCode: plan.reason?.code ?? null,\n cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,\n cancellationRequestedAt: plan.status === \"PENDING\" ? now : null,\n cancellationFailureReason: plan.status === \"FAILED\" ? \"REFUSED\" : null,\n };\n}\n\n/**\n * The columns the store's own cancellation REQUEST writes (FUT-4758): the\n * request alone. The decision status stays as it is (AWAITING or ACCEPTED)\n * while the marketplace answers, so a refused or timed-out request leaves the\n * order acceptable and still on the acceptance clock; only the marketplace's\n * confirmation moves it to REJECTED.\n */\nexport function requestData(plan: CancellationPlan, now: Date): Record<string, unknown> {\n return {\n cancellationStatus: plan.status,\n cancellationReasonCode: plan.reason?.code ?? null,\n cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,\n cancellationRequestedAt: plan.status === \"PENDING\" ? now : null,\n cancellationFailureReason: plan.status === \"FAILED\" ? \"REFUSED\" : null,\n };\n}\n\n/**\n * The marketplace refused the store's cancellation request. FAILED (REFUSED),\n * from PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving\n * after the cancellation changes nothing. The host hears it once, from the\n * call that moved the row. Returns whether a row moved.\n */\nexport async function failCancellationRequest(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };\n const row = (await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } })) as { orderId: string } | null;\n if (!row) return false;\n const moved = await db.marketplaceAcceptance.updateMany({\n where: { ...where, cancellationStatus: { in: [\"PENDING\", \"REQUESTED\"] } },\n data: failedRequestData(\"REFUSED\"),\n });\n if (moved.count === 0) return false;\n ctx.ports.publishChanged(input.clientId);\n await tellCancellationFailed(ctx, input.clientId, row.orderId, \"REFUSED\");\n return true;\n}\n","import { NO_STANDING_REQUEST } from \"./cancellation\";\nimport { rejectConfirmed, tellCancellationConfirmed } from \"./cancellation-outcome\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * The acceptance clock — the store saying yes (or no) to an order.\n *\n * A first-class state rather than a notification, because a marketplace\n * CANCELS an order nobody acknowledged. This module is the only thing that\n * moves an order between the states it can be in:\n *\n * AWAITING ──accept──▶ ACCEPTED ──store cancel──▶ REJECTED\n * │ └──reject───▶ REJECTED\n * └──sweep───────▶ EXPIRED\n *\n * Every transition is guarded on the CURRENT state in the WHERE clause rather\n * than read-then-written, so the sweep and a person deciding in the same\n * second cannot both win. The decisions themselves are `./decisions.ts`;\n * this module holds the queue, the sweep and the marketplace's own cancel.\n *\n * Beside the clock sits the store's own CANCELLATION REQUEST, on the same row:\n *\n * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED\n * │ └──job 4xx / last retry──▶ FAILED ──event──▶ CONFIRMED\n * └──event (the marketplace cancelled)──▶ CONFIRMED\n *\n * CONFIRMED is terminal; every write to the column is predicated on the\n * statuses it may come from, so an out-of-order event cannot undo it.\n */\n\n/** The states an acceptance can be in. The host renders them; they are not copy. */\nexport type AcceptanceStatus = \"AWAITING\" | \"ACCEPTED\" | \"REJECTED\" | \"EXPIRED\";\n\n/** Where the store's own cancellation request stands. */\nexport type CancellationStatus = \"PENDING\" | \"REQUESTED\" | \"CONFIRMED\" | \"FAILED\";\n\n/** An order waiting on the store, as the acceptance queue shows it. */\nexport interface PendingAcceptance {\n id: string;\n /** The HOST's order id — what every host-side surface keys off. */\n orderId: string;\n provider: MarketplaceProvider;\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The deadline itself, so a client counts down against a real instant. */\n acknowledgeBy: Date | null;\n externalDueAt: Date | null;\n commissionCents: number | null;\n buyerName: string | null;\n totalCents: number;\n unmappedLines: number;\n createdAt: string | null;\n}\n\ninterface PendingRow {\n id: string;\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n acknowledgeBy: Date | null;\n externalDueAt: Date | null;\n commissionCents: number | null;\n}\n\n/**\n * Orders still on the clock, soonest DEADLINE first — the one about to lapse\n * is the one that has to be at the top of the screen. The host's half of each\n * row arrives in ONE `summarize` call.\n */\nexport async function listPendingAcceptances(\n ctx: EngineContext,\n clientId: string,\n orderIds?: readonly string[],\n): Promise<PendingAcceptance[]> {\n const db = await ctx.ports.db();\n const rows = (await db.marketplaceAcceptance.findMany({\n where: { clientId, status: \"AWAITING\", ...(orderIds ? { orderId: { in: [...orderIds] } } : {}) },\n orderBy: { acknowledgeBy: \"asc\" },\n select: {\n id: true,\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n acknowledgeBy: true,\n externalDueAt: true,\n commissionCents: true,\n },\n })) as PendingRow[];\n if (rows.length === 0) return [];\n\n const summaries = await ctx.ports.order.summarize(\n clientId,\n rows.map((row) => row.orderId),\n );\n return rows.map((row) => {\n const summary = summaries.get(row.orderId);\n return {\n ...row,\n buyerName: summary?.buyerName ?? null,\n totalCents: summary?.totalCents ?? 0,\n unmappedLines: summary?.unmappedLines ?? 0,\n createdAt: summary?.createdAt ?? null,\n };\n });\n}\n\n/** What one sweep pass did. */\nexport interface ExpirySweepResult {\n expired: number;\n tenants: number;\n}\n\n/**\n * Expire every order whose deadline has passed.\n *\n * The marketplace has already cancelled these on its own side — that is what\n * the deadline MEANS — so this records what the engine now knows happened.\n * Idempotent by durable marker: `status` is in the predicate, and an ACCEPTED\n * row is never touched, so an order a person accepted is never expired.\n */\nexport async function expireLapsedAcceptances(\n ctx: EngineContext,\n now: Date,\n): Promise<ExpirySweepResult> {\n const db = await ctx.ports.db();\n const lapsed = (await db.marketplaceAcceptance.findMany({\n // An order whose cancellation request waits is left to that request: its\n // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host\n // never hears EXPIRED and then the confirmation for one order.\n where: { status: \"AWAITING\", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },\n select: { id: true, clientId: true, orderId: true },\n })) as { id: string; clientId: string; orderId: string }[];\n if (lapsed.length === 0) return { expired: 0, tenants: 0 };\n\n const result = await db.marketplaceAcceptance.updateMany({\n where: { id: { in: lapsed.map((row) => row.id) }, status: \"AWAITING\", ...NO_STANDING_REQUEST },\n data: { status: \"EXPIRED\", acknowledgedAt: now },\n });\n\n // The host's half must not be able to fail the sweep: one tenant's broken\n // cancellation cannot leave every other tenant's lapsed orders on the clock.\n for (const row of lapsed) {\n try {\n await ctx.ports.order.onRefused(row.clientId, row.orderId, \"EXPIRED\");\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n }\n\n const tenants = new Set(lapsed.map((row) => row.clientId));\n for (const clientId of tenants) ctx.ports.publishChanged(clientId);\n return { expired: result.count, tenants: tenants.size };\n}\n\n/**\n * The marketplace cancelled an order it had already given us.\n *\n * Terminal on the acceptance side whatever state it was in. A cancellation\n * request the store made is answered: CONFIRMED, from PENDING, REQUESTED or\n * FAILED (a refusal followed by a cancellation is still a cancellation), and\n * the host hears it through `onCancellationConfirmed` when it has one;\n * otherwise, and for a cancellation the store never asked for,\n * `onRefused(…, \"CANCELLED\")`. Returns false when no acceptance stands for this external order — a\n * cancellation can outrun the placement it refers to.\n */\n/** Whether the host takes a confirmed request through `onCancellationConfirmed` (FUT-4758). */\nfunction hasConfirmHook(ctx: EngineContext): boolean {\n return ctx.ports.order.onCancellationConfirmed !== undefined;\n}\n\nexport async function cancelAcceptance(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string; now?: Date },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceAcceptance.findFirst({\n where: {\n clientId: input.clientId,\n provider: input.provider,\n externalOrderId: input.externalOrderId,\n },\n select: { orderId: true, cancellationStatus: true },\n })) as { orderId: string; cancellationStatus: string | null } | null;\n if (!row) return false;\n\n // The two stamps commit together: a cancelled order never shows a request\n // still PENDING. The host's cancel runs after; if it throws, the inbox row\n // is FAILED and the retry sweep re-runs this, whose stamps are idempotent.\n const answered = await ctx.ports.transaction(async (tx) => {\n await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());\n const confirmed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: { in: [\"PENDING\", \"REQUESTED\", \"FAILED\"] } },\n data: { cancellationStatus: \"CONFIRMED\", cancellationFailureReason: null },\n });\n return confirmed.count > 0;\n });\n // The store's own request, answered (FUT-4758): a host that cancels on the\n // confirmation hears it as such; any other cancellation is the marketplace's.\n // A redelivered confirmation of a request already answered tells a host\n // with the callback nothing more (it heard the first one).\n const storeAsked = answered || row.cancellationStatus === \"CONFIRMED\";\n const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));\n if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, \"CANCELLED\");\n ctx.ports.publishChanged(input.clientId);\n return true;\n}\n\n","import type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider } from \"./types\";\n\n/**\n * A cancellation that outran its order's body.\n *\n * For a marketplace whose events only announce an order (`fetchOrder`), the\n * marketplace's CANCELLED can arrive while the fetch is still queued, held or\n * retrying, and the fetched body (Open Delivery's `Order` has no status) cannot\n * say the order was cancelled. Without a trace the fetch would then ingest a\n * cancelled order, send it to the kitchen and confirm it.\n *\n * So when a cancellation finds no acceptance to cancel, it leaves a MARKER: an\n * IGNORED inbox row under a key derived from the order (`engine:cancelled:<id>`),\n * found again through the inbox's own unique `(provider, eventId)` index, with\n * no new column or table. The fetch reads it before it ingests.\n */\n\nconst MARKER_TYPE = \"ENGINE_CANCELLED_BEFORE_INGEST\";\n\nconst markerId = (externalOrderId: string): string => `engine:cancelled:${externalOrderId}`;\n\n/** Leave the marker, for an adapter that fetches its orders. Idempotent. */\nexport async function markCancelledBeforeIngest(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },\n): Promise<void> {\n if (!ctx.registry.get(input.provider)?.fetchOrder) return;\n const db = await ctx.ports.db();\n try {\n await db.marketplaceInboxEvent.create({\n data: {\n clientId: input.clientId,\n provider: input.provider,\n eventId: markerId(input.externalOrderId),\n eventType: MARKER_TYPE,\n externalOrderId: input.externalOrderId,\n payload: {},\n status: \"IGNORED\",\n error: \"cancelled before the order was ingested\",\n receivedAt: ctx.ports.clock.now(),\n processedAt: ctx.ports.clock.now(),\n },\n select: { id: true },\n });\n } catch (error) {\n // A redelivered cancellation: the marker is already there.\n if ((error as { code?: string }).code !== \"P2002\") throw error;\n }\n}\n\n/** Whether this store's order was cancelled before it was ingested. */\nexport async function cancelledBeforeIngest(\n ctx: EngineContext,\n input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },\n): Promise<boolean> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceInboxEvent.findUnique({\n where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },\n select: { clientId: true },\n })) as { clientId: string | null } | null;\n return row !== null && row.clientId === input.clientId;\n}\n","import { deferInboxEvent, settleInboxEvent } from \"./inbox\";\nimport { ingestMarketplaceOrder } from \"./ingest\";\nimport { readOutboundConnection, resolveIngestionTarget } from \"./integration\";\nimport type { FetchOrderResult } from \"./adapter\";\nimport { cancelAcceptance } from \"./acceptance\";\nimport { cancelledBeforeIngest } from \"./order-fetch-marks\";\nimport type { EngineContext } from \"./ports\";\nimport type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from \"./types\";\n\n/**\n * Fetching an order the event only announced — the engine's half of a\n * marketplace whose events carry no order body (Open Delivery's `CREATED`).\n *\n * The rule this keeps: no path that answers a request calls a marketplace. So\n * the webhook only RECORDS the delivery (PENDING, \"order details to fetch\")\n * and queues `marketplace.fetch-order`; the job reads the row, asks the\n * adapter's `fetchOrder` through the host's HTTP port with the store's own\n * credentials, and ingests what comes back through the one ingest path. The\n * inbox reconciliation sweep re-queues the job for a row that is still owed\n * once it is older than the job's own retry span ({@link FETCH_REQUEUE_AGE_MS}),\n * so a refused enqueue or a dead worker loses nothing — and it never fetches\n * itself, so a host that holds the job (its enqueue port answers \"held\")\n * holds every fetch.\n *\n * Two things are judged before a fetched order is ingested: a cancellation\n * that outran the fetch (`./order-fetch-marks.ts`) wins, and an order naming a\n * merchant other than the connection's is refused.\n *\n * Nothing here knows a marketplace: which events need a fetch is the adapter's\n * `orderToFetch`, and how to fetch is its `fetchOrder`.\n */\n\n/** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */\nexport const MARKETPLACE_FETCH_ORDER_JOB = \"marketplace.fetch-order\";\n\n/** The job's payload. Identifiers only: the event itself is the inbox row's. */\nexport interface FetchOrderJobPayload {\n clientId: string;\n inboxId: string;\n}\n\n/** What one run did. */\nexport type FetchOrderOutcome =\n | { kind: \"skipped\"; reason: string }\n | { kind: \"ingested\"; orderId: string; unmappedSkus: string[] }\n | { kind: \"failed\"; reason: string };\n\n/** Thrown so the queue retries the fetch. Its message is what the job log reads. */\nexport class FetchOrderRetryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FetchOrderRetryError\";\n }\n}\n\n/** The reason a recorded row waits for its fetch. */\nconst AWAITING_ORDER_REASON = \"order details to fetch\";\n\n/**\n * A row waiting for its fetch is left alone by the reconciliation sweep this\n * long: the job's own three attempts (5 s, then 10 s apart) finish well inside\n * it. Past it the sweep re-queues, and only then counts an attempt, so a slow\n * queue never spends the row's attempts while its first job still waits.\n */\nexport const FETCH_REQUEUE_AGE_MS = 2 * 60_000;\n\n/**\n * Leave the row PENDING for its fetch and queue the job. The queue port never\n * throws; a refusal is logged and recovered by the reconciliation sweep.\n * `dedupeKey` defaults to the row's own; a re-queue passes a fresh one, since\n * a queue may keep a finished job's id and swallow a re-queue under it.\n */\nexport async function awaitOrderBody(\n ctx: EngineContext,\n clientId: string,\n inboxId: string,\n dedupeKey: string = `${MARKETPLACE_FETCH_ORDER_JOB}:${inboxId}`,\n): Promise<void> {\n await deferInboxEvent(ctx, inboxId, AWAITING_ORDER_REASON);\n const payload: FetchOrderJobPayload = { clientId, inboxId };\n const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_FETCH_ORDER_JOB, payload, { dedupeKey });\n if (!outcome.enqueued) {\n ctx.ports.logger.warn(\n `${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${inboxId} was not queued; the reconciliation sweep will re-queue it` +\n (outcome.reason ? ` (${outcome.reason})` : \"\"),\n );\n }\n}\n\n/**\n * The reconciliation sweep's answer to a row still waiting for its order body:\n * untouched while younger than {@link FETCH_REQUEUE_AGE_MS} (no attempt\n * counted, nothing queued), else re-queued under a fresh key with a warning,\n * so a hold or a dead worker is visible rather than silent.\n */\nexport async function requeueOwedFetch(\n ctx: EngineContext,\n input: { id: string; clientId: string; receivedAt?: Date | null },\n): Promise<{ kind: \"awaitingOrder\" }> {\n const now = ctx.ports.clock.now();\n const age = input.receivedAt ? now.getTime() - input.receivedAt.getTime() : Number.POSITIVE_INFINITY;\n if (age < FETCH_REQUEUE_AGE_MS) return { kind: \"awaitingOrder\" };\n ctx.ports.logger.warn(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${input.id} still waits for its order body; re-queued`);\n await awaitOrderBody(ctx, input.clientId, input.id, `${MARKETPLACE_FETCH_ORDER_JOB}:${input.id}:${now.getTime()}`);\n return { kind: \"awaitingOrder\" };\n}\n\ninterface InboxRow {\n id: string;\n clientId: string | null;\n provider: string;\n payload: unknown;\n status: string;\n receivedAt: Date | null;\n}\n\n/** The recorded row and its event, or why there is nothing to fetch. */\nasync function owedFetch(\n ctx: EngineContext,\n payload: FetchOrderJobPayload,\n): Promise<{ row: InboxRow; event: NormalizedEvent } | string> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceInboxEvent.findUnique({\n where: { id: payload.inboxId },\n select: { id: true, clientId: true, provider: true, payload: true, status: true, receivedAt: true },\n })) as InboxRow | null;\n if (!row || row.clientId !== payload.clientId) return \"no such inbox row for this tenant\";\n if (row.status !== \"PENDING\" && row.status !== \"FAILED\") return `the row is already ${row.status}`;\n const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;\n if (!event?.orderToFetch || event.order) return \"the event announces no order to fetch\";\n return { row, event };\n}\n\n/** One call to the adapter, or the refusal that stands in for it. */\nasync function fetchThroughAdapter(\n ctx: EngineContext,\n clientId: string,\n provider: MarketplaceProvider,\n externalOrderId: string,\n): Promise<FetchOrderResult> {\n const adapter = ctx.registry.get(provider);\n if (!adapter?.fetchOrder) return { kind: \"refused\", status: 0, message: `${provider} cannot fetch an order` };\n let connection;\n try {\n connection = await readOutboundConnection(ctx, clientId, provider);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n return { kind: \"refused\", status: 0, message: `credentials do not open: ${reason}` };\n }\n if (!connection) return { kind: \"refused\", status: 0, message: \"no credentials on file\" };\n try {\n return await adapter.fetchOrder(\n { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },\n { externalOrderId },\n );\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/**\n * Why a fetched order must not be ingested, or null. A cancellation recorded\n * before the body arrived wins: the order is cancelled, so no pedido and no\n * confirm. An order naming another merchant than the connection's is someone\n * else's order delivered to this store's URL (a wrong webhook URL, a replay).\n */\nasync function refusalOf(\n ctx: EngineContext,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n connectionMerchantId: string | null,\n): Promise<{ settle: \"IGNORED\" | \"FAILED\"; reason: string; failed: boolean } | null> {\n if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {\n return { settle: \"IGNORED\", reason: \"cancelled before its order body arrived\", failed: false };\n }\n const mismatch = merchantMismatch(order, connectionMerchantId);\n // FAILED, not IGNORED: a connection whose merchant id was entered wrong is\n // corrected, and the reconciliation sweep then retries within its bound.\n return mismatch ? { settle: \"FAILED\", reason: mismatch, failed: true } : null;\n}\n\n/**\n * Why an order naming a merchant cannot be this connection's, or null. An\n * order that names none, or a connection that states none, is not judged.\n * Shared by the fetched path and an order the event carries (`./pipeline.ts`).\n */\nexport function merchantMismatch(order: NormalizedMarketplaceOrder, connectionMerchantId: string | null): string | null {\n const named = order.externalMerchantId ?? null;\n if (named === null || connectionMerchantId === null || named === connectionMerchantId) return null;\n return `the order names merchant ${named}, not this connection's`;\n}\n\n/** Ingest a fetched order, unless {@link refusalOf} says otherwise. */\nasync function ingestFetched(\n ctx: EngineContext,\n row: InboxRow,\n clientId: string,\n order: NormalizedMarketplaceOrder,\n target: { autoAccept: boolean; ackSlaSeconds: number; externalMerchantId: string | null },\n): Promise<FetchOrderOutcome> {\n const refusal = await refusalOf(ctx, clientId, order, target.externalMerchantId);\n if (refusal) {\n await settleInboxEvent(ctx, row.id, refusal.settle, refusal.reason);\n if (!refusal.failed) return { kind: \"skipped\", reason: refusal.reason };\n ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} refused: ${refusal.reason}`);\n return { kind: \"failed\", reason: refusal.reason };\n }\n const ingested = await ingestMarketplaceOrder(ctx, {\n clientId,\n order,\n settings: { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },\n // The store's acceptance window starts when the event arrived, not when a\n // delayed fetch finished: the marketplace's own clock started then.\n clockStartsAt: row.receivedAt ?? undefined,\n });\n // A CANCELLED that read the acceptances while this ingest's transaction was\n // still open found none and left its marker: honour it now, through the\n // ordinary cancel path (the order is cancelled; no confirm is owed).\n const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };\n if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);\n await settleInboxEvent(ctx, row.id, \"PROCESSED\");\n return { kind: \"ingested\", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };\n}\n\n/**\n * Run one queued fetch. Returns what it did; throws {@link FetchOrderRetryError}\n * for an answer worth retrying before the last attempt. A refusal, or the last\n * attempt's retry, settles the row FAILED: the reconciliation sweep re-queues\n * it within the inbox's attempt bound.\n */\nexport async function runFetchOrder(\n ctx: EngineContext,\n payload: FetchOrderJobPayload,\n attempt: { attempt: number; maxAttempts: number },\n): Promise<FetchOrderOutcome> {\n const owed = await owedFetch(ctx, payload);\n if (typeof owed === \"string\") return { kind: \"skipped\", reason: owed };\n const { row, event } = owed;\n const target = await resolveIngestionTarget(ctx, payload.clientId, event.provider);\n if (!target?.enabled) {\n await deferInboxEvent(ctx, row.id, \"integration is not enabled\");\n return { kind: \"skipped\", reason: \"integration is not enabled\" };\n }\n const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? \"\");\n if (result.kind === \"order\") return ingestFetched(ctx, row, payload.clientId, result.order, target);\n const reason = result.kind === \"refused\" ? `refused ${result.status}: ${result.message}` : result.reason;\n if (result.kind === \"retry\" && attempt.attempt < attempt.maxAttempts) {\n throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? \"?\"} (inbox ${row.id}): ${reason}`);\n }\n await settleInboxEvent(ctx, row.id, \"FAILED\", `order fetch failed: ${reason}`);\n ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);\n return { kind: \"failed\", reason };\n}\n","import { catalogueDedupeKey, enqueueCatalogue, type CatalogueJobPayload } from \"./catalogue-job\";\nimport { CATALOGUE_ROW_SELECT, catalogueTable, type CatalogueRow } from \"./catalogue-store\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The outbound sweep's catalogue half (FUT-4768): nothing the store switched\n * on or off is lost, and nothing waits forever on \"sending\".\n *\n * A row still owed (PUBLISHING or WITHDRAWING) older than the catalogue job's\n * own retry span is re-queued under a key of its own per pass; one older than\n * the give-up is FAILED, with the action it failed at, so the host shows the\n * reason and \"try again\" instead of a switch stuck on its way.\n */\n\n/** Longer than the catalogue job's three attempts with their backoff. */\nexport const CATALOGUE_STALE_MS = 10 * 60_000;\n\n/** Past this, the marketplace is not going to answer this ask. */\nexport const CATALOGUE_GIVE_UP_MS = 24 * 60 * 60_000;\n\n/** One pass. Returns how many runs it re-queued. */\nexport async function sweepCatalogue(ctx: EngineContext, now: Date): Promise<number> {\n const table = await catalogueTable(ctx);\n if (!table) return 0;\n const stale = new Date(now.getTime() - CATALOGUE_STALE_MS);\n const giveUp = new Date(now.getTime() - CATALOGUE_GIVE_UP_MS);\n for (const [status, failedAction] of [[\"PUBLISHING\", \"PUBLISH\"], [\"WITHDRAWING\", \"WITHDRAW\"]] as const) {\n await table.updateMany({\n where: { status, requestedAt: { lt: giveUp } },\n data: { status: \"FAILED\", failedAction, failureCode: \"TIMEOUT\", failureReason: null, failedAt: now },\n });\n }\n const rows = (await table.findMany({\n where: { status: { in: [\"PUBLISHING\", \"WITHDRAWING\"] }, requestedAt: { lt: stale, gte: giveUp } },\n select: CATALOGUE_ROW_SELECT,\n })) as CatalogueRow[];\n for (const row of rows) {\n const action = row.status === \"PUBLISHING\" ? \"publish\" : \"withdraw\";\n const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action };\n await enqueueCatalogue(ctx, payload, `${catalogueDedupeKey(payload, row.requestedAt)}:sweep:${now.getTime()}`);\n }\n return rows.length;\n}\n","import { NO_STANDING_REQUEST } from \"./cancellation\";\nimport { sweepCatalogue } from \"./catalogue-sweep\";\nimport { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from \"./cancellation-outcome\";\nimport { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from \"./outbound-queue\";\nimport type { EngineContext } from \"./ports\";\n\n/**\n * The outbound sweep: nothing owed to a marketplace is lost.\n *\n * A decision queues its call right after the commit, but a queue can refuse\n * the job, a process can die between the commit and the enqueue, and a job can\n * die without stamping. The ROW still says what is owed — a PENDING request,\n * or an ACCEPTED order with neither confirm stamp — so this pass re-queues\n * every such row once it is older than the outbound job's own retry span.\n *\n * Bounded both ways:\n * - younger than {@link OUTBOUND_STALE_MS}: the original job may still be\n * retrying, so it is left alone;\n * - older than {@link OUTBOUND_GIVE_UP_MS}: a marketplace has long since\n * settled the order on its own clock. A request still waiting that old is\n * stamped FAILED, TIMEOUT (a person finishes it on the marketplace, through\n * the app link),\n * and an accept that old is never confirmed — which is also what keeps a\n * host's ACCEPTED history from before this engine from being confirmed on\n * the first pass.\n *\n * For a host that REQUESTS FIRST (it binds `onCancellationConfirmed`; a 1.0.0\n * host keeps the re-queue and the give-up below, unchanged), and before\n * anything else, a store's cancellation request still waiting (PENDING:\n * never delivered, or REQUESTED: delivered and unanswered) past its\n * marketplace's answer window — the engine's `cancellationWindowMs`, else the\n * adapter's `cancellationAnswerWindowMs`, counted from the request — is FAILED\n * as TIMEOUT, and the host hears it through `onCancellationFailed` (FUT-4758,\n * the owner: \"it cannot stay in that state with nothing happening\"). The\n * store then cancels in the marketplace's own app. A PENDING request's\n * retries stop with it: the job re-reads the row and sends only from PENDING,\n * a run that starts past the window ends TIMEOUT itself without calling, and\n * this sweep re-queues no FAILED row. The window is read at the sweep's own\n * cadence, so a request ends between the window and the window plus one pass.\n *\n * Re-queued under a key of its own per pass: a queue keeps a finished job's id\n * and would swallow a re-queue under the job's plain key. The job itself is\n * idempotent by the row, so a duplicate run calls nobody twice.\n */\n\n/** Longer than the outbound job's three attempts with their backoff. */\nexport const OUTBOUND_STALE_MS = 10 * 60_000;\n\n/** Past this, a marketplace has settled the order without us. */\nexport const OUTBOUND_GIVE_UP_MS = 24 * 60 * 60_000;\n\n/** What one sweep pass did. */\nexport interface OutboundSweepResult {\n requeued: number;\n /** Requests still waiting past {@link OUTBOUND_GIVE_UP_MS}, failed as TIMEOUT. */\n givenUp: number;\n /** Requests failed as TIMEOUT past their marketplace's answer window. */\n timedOut: number;\n /** Catalogue publishes and withdraws still owed, re-queued (FUT-4768). */\n catalogueRequeued: number;\n}\n\n/** A store's cancellation request still waiting on the marketplace. */\nconst WAITING = [\"PENDING\", \"REQUESTED\"];\n\ninterface OwedRow {\n clientId: string;\n orderId: string;\n provider: string;\n}\n\nconst OWED_SELECT = { clientId: true, orderId: true, provider: true } as const;\n\n/** The sweep's own dedupe key: distinct from the job's, and per pass. */\nfunction sweepDedupeKey(action: OutboundAction, orderId: string, now: Date): string {\n return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;\n}\n\nasync function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {\n let queued = 0;\n for (const row of rows) {\n const payload = { clientId: row.clientId, orderId: row.orderId, action };\n if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;\n }\n return queued;\n}\n\n/** Re-queue every owed call older than the job's retry span; give up on the ancient ones. */\n/**\n * Fail as TIMEOUT every request in `rows` still waiting, one predicated write\n * each, so a confirmation that lands meanwhile wins and its host hears nothing\n * twice. Returns how many moved.\n */\nexport async function failAsTimeout(ctx: EngineContext, rows: readonly OwedRow[]): Promise<number> {\n const db = await ctx.ports.db();\n let failed = 0;\n for (const row of rows) {\n const moved = await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },\n data: failedRequestData(\"TIMEOUT\"),\n });\n if (moved.count === 0) continue;\n failed += 1;\n ctx.ports.publishChanged(row.clientId);\n await tellCancellationFailed(ctx, row.clientId, row.orderId, \"TIMEOUT\");\n }\n return failed;\n}\n\n/** Every request in `statuses` since before `cutoff`, for one provider or all. */\nasync function waitingSince(\n ctx: EngineContext,\n cutoff: Date,\n statuses: readonly string[],\n provider?: string,\n): Promise<OwedRow[]> {\n const db = await ctx.ports.db();\n return (await db.marketplaceAcceptance.findMany({\n where: { ...(provider ? { provider } : {}), cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },\n select: OWED_SELECT,\n })) as OwedRow[];\n}\n\n/** Fail every request still waiting past its marketplace's window; no window, only the give-up. */\nasync function expireUnanswered(ctx: EngineContext, now: Date): Promise<number> {\n // Only for a host that requests first: a 1.0.0 host (it cancelled already)\n // keeps the re-queue and the 24-hour give-up exactly as before.\n if (!requestsFirst(ctx)) return 0;\n let expired = 0;\n for (const provider of ctx.registry.providers()) {\n const adapter = ctx.registry.get(provider);\n const window = adapter ? cancellationWindowMs(ctx, adapter) : null;\n if (window === null) continue;\n const cutoff = new Date(now.getTime() - window);\n expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));\n }\n return expired;\n}\n\n/**\n * One sweep pass: expire the requests nobody answered, give up on the very old,\n * and re-queue what is still owed, the catalogue's publishes and withdraws\n * included (`./catalogue-sweep.ts`).\n */\nexport async function sweepOutbound(ctx: EngineContext, now: Date): Promise<OutboundSweepResult> {\n const db = await ctx.ports.db();\n const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);\n const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);\n\n const timedOut = await expireUnanswered(ctx, now);\n // 1.0.0 gave up on PENDING requests only; a host that requests first, on any still waiting.\n const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : [\"PENDING\"]));\n const cancellations = (await db.marketplaceAcceptance.findMany({\n where: { cancellationStatus: \"PENDING\", cancellationRequestedAt: { lt: stale, gte: giveUp } },\n select: OWED_SELECT,\n })) as OwedRow[];\n const confirms = (await db.marketplaceAcceptance.findMany({\n where: {\n status: \"ACCEPTED\",\n confirmedAt: null,\n confirmFailedAt: null,\n acknowledgedAt: { lt: stale, gte: giveUp },\n // An accept the store asked to cancel is not confirmed while the request waits.\n ...NO_STANDING_REQUEST,\n },\n select: OWED_SELECT,\n })) as OwedRow[];\n\n const requeued =\n (await requeue(ctx, cancellations, \"requestCancellation\", now)) + (await requeue(ctx, confirms, \"confirm\", now));\n if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);\n const catalogueRequeued = await sweepCatalogue(ctx, now);\n return { requeued, givenUp, timedOut, catalogueRequeued };\n}\n","import type { MarketplaceAdapter, OutboundOrderRef, OutboundResult } from \"./adapter\";\nimport {\n cancellationWindowMs,\n confirmedToHost,\n failedRequestData,\n rejectConfirmed,\n requestsFirst,\n tellCancellationFailed,\n} from \"./cancellation-outcome\";\nimport { readOutboundConnection, type OutboundConnection } from \"./integration\";\nimport type { OutboundJobPayload } from \"./outbound-queue\";\nimport { failAsTimeout } from \"./outbound-sweep\";\nimport type { EngineContext } from \"./ports\";\nimport { resolveReason } from \"./registry\";\n\n/**\n * The outbound engine: one queued call to a marketplace, start to finish.\n *\n * The job (`marketplace.outbound`) is the only caller. It re-reads the row,\n * decides whether a call is still owed, makes it through the adapter with the\n * host's HTTP client, and stamps the outcome. The rule for an answer is the\n * same for every marketplace:\n *\n * - **2xx** — done: `confirmed_at`, or REQUESTED (CONFIRMED for a marketplace\n * that answers a cancellation in the response rather than by event);\n * - **4xx** — refused, final, never retried: `confirm_failed_at`, or FAILED;\n * - **anything else** (5xx, timeout, network) — retried by the queue: this\n * THROWS {@link OutboundRetryError}, until the last attempt, which stamps the\n * failure and returns.\n *\n * Idempotent by the ROW, never by the queue's dedupe alone: a stamped confirm\n * (`confirmed_at` or `confirm_failed_at`) is never sent again, and a request\n * is only sent from PENDING. A confirm is never sent for an order that is no\n * longer ACCEPTED here.\n */\n\n/** What one run did. */\nexport type OutboundOutcome =\n | { kind: \"skipped\"; reason: string }\n | { kind: \"done\"; action: OutboundJobPayload[\"action\"] }\n | { kind: \"failed\"; action: OutboundJobPayload[\"action\"]; reason: string };\n\n/** Thrown so the queue retries. Its message is what the job log reads. */\nexport class OutboundRetryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OutboundRetryError\";\n }\n}\n\n/** Which attempt this is, as the job runner says. */\nexport interface OutboundAttempt {\n attempt: number;\n maxAttempts: number;\n}\n\ninterface OutboundRow {\n orderId: string;\n provider: string;\n externalOrderId: string;\n externalDisplayId: string | null;\n status: string;\n confirmedAt: Date | null;\n confirmFailedAt: Date | null;\n cancellationStatus: string | null;\n cancellationReasonCode: string | null;\n cancellationOffendingSkus: unknown;\n cancellationRequestedAt: Date | null;\n preparationMinutes: number | null;\n createdAt: Date;\n}\n\nconst ROW_SELECT = {\n orderId: true,\n provider: true,\n externalOrderId: true,\n externalDisplayId: true,\n status: true,\n confirmedAt: true,\n confirmFailedAt: true,\n cancellationStatus: true,\n cancellationReasonCode: true,\n cancellationOffendingSkus: true,\n cancellationRequestedAt: true,\n preparationMinutes: true,\n createdAt: true,\n} as const;\n\nfunction refOf(row: OutboundRow): OutboundOrderRef {\n return {\n externalOrderId: row.externalOrderId,\n externalDisplayId: row.externalDisplayId,\n hostOrderCode: row.orderId,\n placedAt: row.createdAt,\n };\n}\n\n/** Why a confirm is not owed, or null when it is. */\nfunction confirmSkip(row: OutboundRow, adapter: MarketplaceAdapter): string | null {\n if (row.status !== \"ACCEPTED\") return `the order is ${row.status}, not ACCEPTED`;\n // A request to cancel stands (FUT-4758: the status stays ACCEPTED while it\n // waits): confirming now would tell the marketplace the opposite.\n if (row.cancellationStatus !== null && row.cancellationStatus !== \"FAILED\") {\n return `a cancellation request is ${row.cancellationStatus}`;\n }\n if (row.confirmedAt || row.confirmFailedAt) return \"the confirm is already stamped\";\n if (!adapter.capabilities.apiConfirm) return \"the marketplace has no confirm API\";\n return null;\n}\n\n/** The stamps one confirm outcome writes, predicated on the confirm still being owed. */\nasync function stampConfirm(\n ctx: EngineContext,\n row: OutboundRow,\n succeeded: boolean,\n now: Date,\n): Promise<void> {\n const db = await ctx.ports.db();\n await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, confirmedAt: null, confirmFailedAt: null },\n data: succeeded ? { confirmedAt: now } : { confirmFailedAt: now },\n });\n}\n\n/**\n * The cancellation stamp, predicated on the request still being PENDING, and\n * the host told how it ended when this run is what ended it (FUT-4758): a\n * marketplace that answers in the response CONFIRMS here, and a refusal FAILS\n * here. REQUESTED tells nobody: the answer is still to come, by event.\n */\nasync function stampCancellation(\n ctx: EngineContext,\n row: OutboundRow,\n status: \"REQUESTED\" | \"CONFIRMED\" | \"FAILED\",\n clientId: string,\n): Promise<void> {\n if (status === \"CONFIRMED\") return stampConfirmedCancellation(ctx, row, clientId);\n const db = await ctx.ports.db();\n const data = status === \"FAILED\" ? failedRequestData(\"REFUSED\") : { cancellationStatus: status };\n const moved = await db.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, cancellationStatus: \"PENDING\" },\n data,\n });\n if (moved.count > 0 && status === \"FAILED\") await tellCancellationFailed(ctx, clientId, row.orderId, \"REFUSED\");\n}\n\n/**\n * Which rows a synchronous \"cancelled\" answers: the request still waiting or\n * FAILED, or the tombstone an accept left of THIS request (no status, the\n * same `cancellation_requested_at` the job read) on an order STILL ACCEPTED.\n * A later request of the store carries a new instant and a status of its own,\n * so it is never mistaken for it; and once the marketplace's own cancel event\n * has moved the order to REJECTED (and told the host), the tombstone answers\n * nothing more, so the host is never told twice.\n */\nfunction answerableRequest(row: OutboundRow): Record<string, unknown>[] {\n const waiting = { cancellationStatus: { in: [\"PENDING\", \"FAILED\"] } };\n if (row.cancellationRequestedAt === null) return [waiting];\n const tombstone = { status: \"ACCEPTED\", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };\n return [waiting, tombstone];\n}\n\n/**\n * A marketplace that confirms in its answer: the same stamps as its\n * CANCELLED event (`cancelAcceptance`) — CONFIRMED and REJECTED in one\n * transaction — then the host's `onCancellationConfirmed`, or\n * `onRefused(…, \"CANCELLED\")` when it binds none. A host failure is logged:\n * the stamps have committed.\n */\nasync function stampConfirmedCancellation(ctx: EngineContext, row: OutboundRow, clientId: string): Promise<void> {\n const now = ctx.ports.clock.now();\n const moved = await ctx.ports.transaction(async (tx) => {\n // From FAILED too: the sweep may have timed the request out while this\n // call was in flight, and a marketplace that answers in the response sends\n // no event — its \"cancelled\" is the only word that it did (the event path's\n // own rule: a confirmation after a TIMEOUT still confirms). And from the\n // TOMBSTONE of this same request (FUT-4765, R3-N2): the store may have\n // accepted the order once the request timed out, which clears the request\n // but keeps its `cancellation_requested_at`. The order is cancelled on the\n // marketplace, so it is cancelled here too, and the host hears it.\n const confirmed = await tx.marketplaceAcceptance.updateMany({\n where: { orderId: row.orderId, OR: answerableRequest(row) },\n data: { cancellationStatus: \"CONFIRMED\", cancellationFailureReason: null },\n });\n if (confirmed.count === 0) return false;\n await rejectConfirmed(tx, row.orderId, now);\n return true;\n });\n if (!moved) return;\n try {\n await confirmedToHost(ctx, clientId, row.orderId);\n } catch (error) {\n ctx.ports.logger.error(\n `marketplace.outbound: order ${row.orderId} was cancelled on the store's request but the host's half failed: ` +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/** The connection, or the reason it cannot be used (a refusal: no retry fixes it). */\nasync function connectionFor(\n ctx: EngineContext,\n clientId: string,\n provider: string,\n): Promise<OutboundConnection | string> {\n try {\n return (await readOutboundConnection(ctx, clientId, provider)) ?? \"no credentials on file\";\n } catch (error) {\n return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\n/** Turn a call's answer into the stamp and the outcome, or a retry. */\nasync function settle(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n row: OutboundRow,\n result: OutboundResult,\n attempt: OutboundAttempt,\n succeed: () => Promise<void>,\n fail: () => Promise<void>,\n): Promise<OutboundOutcome> {\n if (result.kind === \"accepted\") {\n await succeed();\n ctx.ports.publishChanged(payload.clientId);\n return { kind: \"done\", action: payload.action };\n }\n const reason = result.kind === \"refused\" ? `refused ${result.status}: ${result.message}` : result.reason;\n if (result.kind === \"retry\" && attempt.attempt < attempt.maxAttempts) {\n throw new OutboundRetryError(`${payload.action} for order ${row.orderId}: ${reason}`);\n }\n await fail();\n ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${row.orderId} failed: ${reason}`);\n ctx.ports.publishChanged(payload.clientId);\n return { kind: \"failed\", action: payload.action, reason };\n}\n\nasync function runConfirm(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n row: OutboundRow,\n adapter: MarketplaceAdapter,\n attempt: OutboundAttempt,\n): Promise<OutboundOutcome> {\n const skip = confirmSkip(row, adapter);\n if (skip) return { kind: \"skipped\", reason: skip };\n const now = ctx.ports.clock.now();\n const connection = await connectionFor(ctx, payload.clientId, row.provider);\n const result: OutboundResult =\n typeof connection === \"string\"\n ? { kind: \"refused\", status: 0, message: connection }\n : await adapter.confirm(\n { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },\n refOf(row),\n // The stated preparation time, for a marketplace whose confirm takes one.\n { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null },\n );\n return settle(\n ctx,\n payload,\n row,\n result,\n attempt,\n () => stampConfirm(ctx, row, true, now),\n () => stampConfirm(ctx, row, false, now),\n );\n}\n\n/** Whether a request is older than its marketplace's answer window, so it must not be sent any more. */\nfunction pastWindow(ctx: EngineContext, row: OutboundRow, adapter: MarketplaceAdapter): boolean {\n // A 1.0.0 host (no `onCancellationConfirmed`) has no window: it retries, as before.\n if (!requestsFirst(ctx)) return false;\n const window = cancellationWindowMs(ctx, adapter);\n if (window === null || row.cancellationRequestedAt === null) return false;\n return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;\n}\n\n/** The offending SKUs stored with the request. */\nfunction skusOf(row: OutboundRow): string[] {\n return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];\n}\n\nasync function runCancellation(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n row: OutboundRow,\n adapter: MarketplaceAdapter,\n attempt: OutboundAttempt,\n): Promise<OutboundOutcome> {\n if (row.cancellationStatus !== \"PENDING\") {\n return { kind: \"skipped\", reason: `the request is ${row.cancellationStatus ?? \"absent\"}, not PENDING` };\n }\n if (pastWindow(ctx, row, adapter)) {\n // A retry that comes after the window never delivers (FUT-4758): the host\n // was, or is now, told TIMEOUT, and the store cancels in the marketplace's app.\n await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);\n return { kind: \"failed\", action: payload.action, reason: \"past the marketplace's answer window\" };\n }\n const reason = resolveReason(adapter, row.cancellationReasonCode);\n const connection = await connectionFor(ctx, payload.clientId, row.provider);\n let result: OutboundResult;\n if (!reason) result = { kind: \"refused\", status: 0, message: \"the stored reason is not the marketplace's\" };\n else if (typeof connection === \"string\") result = { kind: \"refused\", status: 0, message: connection };\n else {\n result = await adapter.requestCancellation(\n { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },\n refOf(row),\n { reason, text: \"\", mode: \"MANUAL\", offendingSkus: skusOf(row) },\n );\n }\n const taken = adapter.capabilities.asyncCancellationOutcome ? \"REQUESTED\" : \"CONFIRMED\";\n return settle(\n ctx,\n payload,\n row,\n result,\n attempt,\n () => stampCancellation(ctx, row, taken, payload.clientId),\n () => stampCancellation(ctx, row, \"FAILED\", payload.clientId),\n );\n}\n\n/**\n * The failure stamp a run that died on its LAST attempt leaves: FAILED, never\n * PENDING, so a person is shown the app link. Best-effort: if the database is\n * what failed, the row stays owed and the outbound sweep picks it up.\n */\nasync function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {\n const reason = error instanceof Error ? error.message : String(error);\n const db = await ctx.ports.db();\n const moved = await (payload.action === \"confirm\"\n ? db.marketplaceAcceptance.updateMany({\n where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },\n data: { confirmFailedAt: ctx.ports.clock.now() },\n })\n : db.marketplaceAcceptance.updateMany({\n where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: \"PENDING\" },\n data: failedRequestData(\"REFUSED\"),\n }));\n ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);\n ctx.ports.publishChanged(payload.clientId);\n if (payload.action === \"requestCancellation\" && moved.count > 0) {\n await tellCancellationFailed(ctx, payload.clientId, payload.orderId, \"REFUSED\");\n }\n return { kind: \"failed\", action: payload.action, reason };\n}\n\nasync function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome> {\n const db = await ctx.ports.db();\n const row = (await db.marketplaceAcceptance.findFirst({\n where: { orderId: payload.orderId, clientId: payload.clientId },\n select: ROW_SELECT,\n })) as OutboundRow | null;\n if (!row) return { kind: \"skipped\", reason: \"no acceptance for this order\" };\n const adapter = ctx.registry.get(row.provider);\n if (!adapter) return { kind: \"skipped\", reason: `no adapter for ${row.provider}` };\n return payload.action === \"confirm\"\n ? runConfirm(ctx, payload, row, adapter, attempt)\n : runCancellation(ctx, payload, row, adapter, attempt);\n}\n\n/**\n * Run one queued outbound call. Returns what it did; throws\n * {@link OutboundRetryError} for an answer worth retrying before the last\n * attempt. Any OTHER throw (an adapter bug, a database error while stamping)\n * is rethrown for the queue to retry, and on the last attempt ends FAILED.\n */\nexport async function runOutbound(\n ctx: EngineContext,\n payload: OutboundJobPayload,\n attempt: OutboundAttempt,\n): Promise<OutboundOutcome> {\n try {\n return await runOnce(ctx, payload, attempt);\n } catch (error) {\n if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;\n return stampLastAttemptFailure(ctx, payload, error);\n }\n}\n"],"mappings":";;;;;AAwBO,IAAM,sBAAsB;;;ACJ5B,IAAM,sCAAN,cAAkD,MAAM;AAAA,EApB/D,OAoB+D;AAAA;AAAA;AAAA,EAC7D,YAAY,SAAiB;AAC3B,UAAM,yBAAyB,OAAO,EAAE;AACxC,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,cAAc,SAAmC;AACxD,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,UAAU,QAAQ,oBAA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