@12-apps/marketplace 1.0.0 → 1.1.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 +35 -5
- package/README.md +2 -2
- package/dist/{adapter-CgCAYBSJ.d.ts → adapter-BggtVFf9.d.ts} +6 -0
- package/dist/{chunk-OEKTWUQH.js → chunk-7BYVGNU5.js} +1 -1
- package/dist/chunk-7BYVGNU5.js.map +1 -0
- package/dist/{chunk-6OODIO3E.js → chunk-DVIRN42O.js} +325 -13
- package/dist/chunk-DVIRN42O.js.map +1 -0
- package/dist/{chunk-BEMTRJYM.js → chunk-NGNEL4HS.js} +4 -4
- package/dist/{chunk-BEMTRJYM.js.map → chunk-NGNEL4HS.js.map} +1 -1
- package/dist/{engine-DDE0mnTu.d.ts → engine-KrgZ4pA4.d.ts} +61 -17
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +4 -2
- package/dist/ifood/index.js +10 -2
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +81 -169
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +7 -0
- package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
- package/src/core/acceptance.ts +30 -14
- package/src/core/adapter.ts +6 -0
- package/src/core/cancellation-outcome.ts +92 -0
- package/src/core/cancellation.ts +46 -15
- package/src/core/decisions.ts +82 -19
- package/src/core/outbound-sweep.ts +87 -8
- package/src/core/outbound.ts +83 -7
- package/src/core/ports.ts +32 -0
- package/src/core/state.ts +6 -1
- package/src/ifood/index.ts +9 -0
- package/src/index.ts +1 -0
- package/src/server/jobs.ts +3 -2
- package/dist/chunk-6OODIO3E.js.map +0 -1
- package/dist/chunk-OEKTWUQH.js.map +0 -1
package/ADOPTING.md
CHANGED
|
@@ -6,8 +6,8 @@ Everything below is what a host binds, in the order it binds it.
|
|
|
6
6
|
|
|
7
7
|
## 1. The host ports (`MarketplacePorts`)
|
|
8
8
|
|
|
9
|
-
Every field is REQUIRED. A missing one is a type
|
|
10
|
-
default that quietly adopts another host's policy.
|
|
9
|
+
Every field is REQUIRED unless marked OPTIONAL. A missing required one is a type
|
|
10
|
+
error at mount, never a default that quietly adopts another host's policy.
|
|
11
11
|
|
|
12
12
|
| port | type | what the host answers |
|
|
13
13
|
|---|---|---|
|
|
@@ -17,7 +17,9 @@ default that quietly adopts another host's policy.
|
|
|
17
17
|
| `order.create` | `(clientId, order: NormalizedMarketplaceOrder, lines: readonly ResolvedOrderLine[], db: MarketplaceDb) => Promise<string>` | Create the host's own order from a normalized one; return its id. `lines[i].subjectRef` is the mapped catalog id or null (never refuse the order for a null). `db` is the ingest's transaction client: write the order through it, so the order and the acceptance row commit together (a lost race rolls the host's order back instead of leaving an orphan a redelivery would duplicate). |
|
|
18
18
|
| `order.catalogHas` | `(clientId, subjectRef) => Promise<boolean>` | Does this catalog id exist and belong to this tenant? Asked before a SKU is mapped. |
|
|
19
19
|
| `order.onAccepted` | `(clientId, orderId) => Promise<void>` | The store accepted, or the connection auto-accepts. Start whatever accepting means here (the ticket, the board). Runs after the commit and AFTER the confirm is queued; a throw is logged and cannot un-accept or lose the confirm. Atomic work (the stock draw) belongs in `admit`. |
|
|
20
|
-
| `order.onRefused` | `(clientId, orderId, reason: "REJECTED" \| "EXPIRED" \| "CANCELLED") => Promise<void>` | Refuse/cancel the host order: the store refused on the clock, the clock lapsed, or the marketplace cancelled. After the commit and after the cancellation request is queued; a throw on a decision is logged. NOT called for `recordStoreCancellation` (the
|
|
20
|
+
| `order.onRefused` | `(clientId, orderId, reason: "REJECTED" \| "EXPIRED" \| "CANCELLED") => Promise<void>` | Refuse/cancel the host order: the store refused on the clock, the clock lapsed, or the marketplace cancelled. After the commit and after the cancellation request is queued; a throw on a decision is logged. NOT called for `recordStoreCancellation`. A host that binds `onCancellationConfirmed` (request first) does not get `"REJECTED"` from `decide` either, nor `"CANCELLED"` for a cancellation the store asked for: `onCancellationConfirmed` replaces both. |
|
|
21
|
+
| `order.onCancellationConfirmed` | OPTIONAL — binding it OPTS IN to request first. `(clientId, orderId) => Promise<void>` | The marketplace CONFIRMED the store's own cancellation request (its event, or the job's answer for a marketplace that answers in the response); the row is REJECTED/CONFIRMED by then. Run the host's cancel here. Bound: the store's refusals and cancels (`decide` REJECT, `recordStoreCancellation`) only REQUEST the cancellation and keep the order as it was until this is called, once (a redelivered confirmation calls nothing), INSTEAD of `onRefused`. Not bound (a 1.0.0 host): everything as 1.0.0 — REJECTED at request time, `onRefused(…, "REJECTED")` from `decide`, and `onRefused(…, "CANCELLED")` on the confirmation. A throw is logged. |
|
|
22
|
+
| `order.onCancellationFailed` | OPTIONAL. `(clientId, orderId, reason: "REFUSED" \| "TIMEOUT") => Promise<void>` | The store's request FAILED: REFUSED (the marketplace's refusal event, the job's 4xx, its last attempt dying, or — request first — a marketplace whose API cannot take it, at once) or TIMEOUT (the outbound sweep, past the marketplace's answer window, or the 24-hour give-up). Called once, by the path that moved the row. Request first: the order stays as it was (AWAITING or ACCEPTED) and may be accepted again; show the adapter's app link and tell the person. A throw is logged. |
|
|
21
23
|
| `order.summarize` | `(clientId, orderIds: readonly string[]) => Promise<Map<string, MarketplaceOrderSummary>>` | The queue's host facts in one read: `{ buyerName, totalCents, unmappedLines, createdAt }`. |
|
|
22
24
|
| `secrets` | `{ seal(plaintext): string; open(sealed): string }` | Seal and open the credential blob with the host's key. `open` THROWS on a blob that will not open. |
|
|
23
25
|
| `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. |
|
|
@@ -29,6 +31,7 @@ default that quietly adopts another host's policy.
|
|
|
29
31
|
| `defaultAckSlaSeconds` | `number` | The acceptance window a new connection gets (the origin host: 300). |
|
|
30
32
|
| `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
|
|
31
33
|
| `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
|
|
34
|
+
| `cancellationWindowMs` | OPTIONAL. `number` | For a host that requests first (binds `onCancellationConfirmed`): how long a store's cancellation request may wait (PENDING: not yet delivered, or REQUESTED: delivered and unanswered) before the outbound sweep fails it as TIMEOUT, for every adapter; a PENDING request's retries stop with it. A 1.0.0 host has no window: its requests are re-queued and given up after 24 hours, as before. Absent: each adapter's `capabilities.cancellationAnswerWindowMs` (iFood: 5 minutes, estimated); an adapter with none is given up on only after 24 hours. |
|
|
32
35
|
|
|
33
36
|
Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
|
|
34
37
|
sells through. The list is validated at mount (ids, duplicates, reason lists).
|
|
@@ -61,9 +64,9 @@ export const engine = createMarketplaceEngine({
|
|
|
61
64
|
| call | when |
|
|
62
65
|
|---|---|
|
|
63
66
|
| `decideMany({ clientId, decisions, validateOnly? })` / `decide({ clientId, ...decision })` | Every accept or refusal of an order on the clock, from every surface (the board, the admin route, the MCP tool). One decide path, all-or-nothing. A decision is `{ orderId, decision: "ACCEPT", admission?, preparationMinutes? }` or `{ orderId, decision: "REJECT", reasonCode?, offendingSkus? }`. `decide` answers `decided`, `stale` with `reason` (`ALREADY_DECIDED` with the `status` — answer an ACCEPTED one as done, I4 — `EXPIRED`, `NOT_FOUND`, `CONFLICT`), `invalidReason` (`INVALID_REASON`, `ITEMS_REQUIRED`, `UNKNOWN_ITEM`), or `refusedByHost` (your `admit`'s code). |
|
|
64
|
-
| `recordStoreCancellation({ clientId, orderId, reasonCode?, offendingSkus? })` |
|
|
67
|
+
| `recordStoreCancellation({ clientId, orderId, reasonCode?, offendingSkus? })` | The store cancels a marketplace order (before or after accepting it). Stamps the request and queues it. A host that binds no `onCancellationConfirmed` cancelled first and gets 1.0.0's stamps (REJECTED at once). A host that binds it (request first) gets the REQUEST only: the status stays AWAITING or ACCEPTED (and `decided.status` says so) until the marketplace confirms; a FAILED request may be asked again. `stale` when the marketplace already cancelled it or a request is already waiting. |
|
|
65
68
|
| `suggestReason(provider, { itemUnavailable })` | To preselect a reason in the refusal dialog. The host judges the shortage. |
|
|
66
|
-
| `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, appUrl }` per marketplace order, one query. |
|
|
69
|
+
| `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, cancellationFailure, appUrl }` per marketplace order, one query. `cancellation` PENDING or REQUESTED is a request still waiting: draw it as such. `cancellationFailure` is REFUSED or TIMEOUT when `cancellation` is FAILED. |
|
|
67
70
|
| `adapter(provider)`, `reasons(provider)`, `appLink(provider, ref)` | The marketplace's capabilities, reasons and link, without naming it. |
|
|
68
71
|
| `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
|
|
69
72
|
|
|
@@ -142,6 +145,25 @@ each.
|
|
|
142
145
|
number included, never the host's global client inside the callback: on PGlite, which
|
|
143
146
|
runs one transaction at a time, a write on the global client hangs the ingest, and on
|
|
144
147
|
Postgres a rolled-back ingest would leave an orphan order and a burnt order number.
|
|
148
|
+
13. **Request first, cancel on confirm (1.1, FUT-4758) — opt in by binding
|
|
149
|
+
`order.onCancellationConfirmed`.** Without it, 1.0.0's behaviour holds, with two
|
|
150
|
+
differences, both harmless to a host whose cancel is idempotent: a marketplace that
|
|
151
|
+
confirms in its response now also moves the row to REJECTED and calls
|
|
152
|
+
`onRefused(…, "CANCELLED")` (1.0.0 called nothing there), and the event path keeps an
|
|
153
|
+
accepted order's `acknowledged_at` instead of overwriting it with the cancel time. With it, the
|
|
154
|
+
store's refusals and cancels (`decide` REJECT and `recordStoreCancellation`) only request
|
|
155
|
+
the cancellation; the order keeps its status until the marketplace confirms, and the
|
|
156
|
+
acceptance clock leaves an order with a waiting request alone (the request's window ends
|
|
157
|
+
it first). To opt in:
|
|
158
|
+
- bind `order.onCancellationConfirmed` (run the ordinary cancel there);
|
|
159
|
+
- call `recordStoreCancellation` from every cancel entry point, without cancelling;
|
|
160
|
+
- draw `orderStates(…).cancellation` PENDING/REQUESTED as "waiting for the marketplace";
|
|
161
|
+
- keep the store's own reason (its loss record, who asked) for that cancel: the engine
|
|
162
|
+
carries only the marketplace's code;
|
|
163
|
+
- bind `order.onCancellationFailed` (REFUSED or TIMEOUT: the order stays, show the app link);
|
|
164
|
+
- expect the answer window: a request still waiting past it (delivered or not) ends TIMEOUT;
|
|
165
|
+
- run migration `20261112120000_marketplace_cancellation_failure` (one nullable column,
|
|
166
|
+
its CHECK and an index), through the host's plugin-migration sync like the first.
|
|
145
167
|
|
|
146
168
|
## 5. The database
|
|
147
169
|
|
|
@@ -153,6 +175,14 @@ migration:
|
|
|
153
175
|
- `marketplace_acceptances.order_id → <orders>(id) ON DELETE CASCADE`
|
|
154
176
|
- `marketplace_menu_links.menu_item_id → <catalog>(id) ON DELETE SET NULL`
|
|
155
177
|
|
|
178
|
+
The migrations are replay-safe. `20261112120000_marketplace_cancellation_failure`
|
|
179
|
+
(1.1) adds `marketplace_acceptances.cancellation_failure_reason` (REFUSED or
|
|
180
|
+
TIMEOUT, CHECKed), and a PARTIAL index the expiry of waiting requests reads
|
|
181
|
+
(`marketplace_acceptances_cancellation_waiting_idx`, `WHERE cancellation_status IN
|
|
182
|
+
('PENDING','REQUESTED')`). Prisma cannot express a partial index, so it is SQL-only and
|
|
183
|
+
the partial declares none: a host that diffs its schema against its database ignores it,
|
|
184
|
+
as it already does for the first migration's partial indexes.
|
|
185
|
+
|
|
156
186
|
The migration `20261111200000_marketplace_engine` is replay-safe. On a host
|
|
157
187
|
that already has the predecessor's tables it adds the outbound columns
|
|
158
188
|
(including `cancellation_offending_skus`, `cancellation_requested_at`,
|
package/README.md
CHANGED
|
@@ -40,10 +40,10 @@ engine code (`src/__tests__/second-adapter.test.ts`).
|
|
|
40
40
|
| **Pipeline** | normalize → inbox → ingest / cancel / cancellation-refused / ignore. Never throws. |
|
|
41
41
|
| **Ingest** | Idempotent on `(provider, externalOrderId)`. Unmapped SKUs are rows on the attention list, never a rejection. The deadline is stamped at ingest; auto-accept is born accepted in one write and queues the confirm. |
|
|
42
42
|
| **Acceptance clock** | `AWAITING → ACCEPTED | REJECTED | EXPIRED`, every transition predicated on the current state. The sweep never touches an accepted order. |
|
|
43
|
-
| **Decisions** | Many at once, all-or-nothing: accept (with the person's admission and a preparation time), or refuse with a reason code validated against the adapter's own list and, for a reason that needs them, the order's offending SKUs. The host admits each decision inside the claim's transaction (`order.admit`: the stock ask, the draw).
|
|
43
|
+
| **Decisions** | Many at once, all-or-nothing: accept (with the person's admission and a preparation time), or refuse with a reason code validated against the adapter's own list and, for a reason that needs them, the order's offending SKUs. The host admits each decision inside the claim's transaction (`order.admit`: the stock ask, the draw). For a host that binds `onCancellationConfirmed`, the store's refusal or cancel is a REQUEST: only the request moves, the order stays as it was until the marketplace answers, and the host hears the answer through the optional `onCancellationConfirmed` / `onCancellationFailed` (REFUSED or TIMEOUT). `suggestReason` preselects the item-unavailable reason when the host says stock is short. |
|
|
44
44
|
| **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. |
|
|
45
45
|
| **Integration settings** | Enabled, environment, merchant id, auto-accept, acknowledgement window; credentials sealed as one blob by the host's secrets port, never returned. A connection is archived (reversible, audited), never deleted. |
|
|
46
|
-
| **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. |
|
|
46
|
+
| **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
|
|
47
47
|
| **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
|
|
48
48
|
| **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, and `capabilities`. |
|
|
49
49
|
|
|
@@ -185,6 +185,12 @@ interface MarketplaceCapabilities {
|
|
|
185
185
|
perOrderAppLink: boolean;
|
|
186
186
|
/** Confirming states a preparation time. */
|
|
187
187
|
confirmTakesPreparationTime: boolean;
|
|
188
|
+
/**
|
|
189
|
+
* OPTIONAL. How long the marketplace takes, at most, to answer a store's
|
|
190
|
+
* cancellation request, in milliseconds: past it the outbound sweep fails
|
|
191
|
+
* the request as TIMEOUT. Absent: only the 24-hour give-up applies.
|
|
192
|
+
*/
|
|
193
|
+
cancellationAnswerWindowMs?: number;
|
|
188
194
|
}
|
|
189
195
|
/** One reason a store may give for refusing or cancelling an order. */
|
|
190
196
|
interface CancellationReason {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceProvider, NormalizedEvent } from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n method: \"GET\" | \"POST\" | \"PUT\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /** A final 4xx (not 408/425/429): never retried. */\n | { kind: \"refused\"; status: number; message: string }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAsKA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAShB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
|
|
@@ -76,6 +76,259 @@ function suggestReason(adapter, input) {
|
|
|
76
76
|
}
|
|
77
77
|
__name(suggestReason, "suggestReason");
|
|
78
78
|
|
|
79
|
+
// src/core/outbound-queue.ts
|
|
80
|
+
var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
|
|
81
|
+
function outboundDedupeKey(payload) {
|
|
82
|
+
return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
|
|
83
|
+
}
|
|
84
|
+
__name(outboundDedupeKey, "outboundDedupeKey");
|
|
85
|
+
async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
|
|
86
|
+
const adapter = ctx.registry.get(provider);
|
|
87
|
+
if (!adapter) return false;
|
|
88
|
+
const able = payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
|
|
89
|
+
if (!able) return false;
|
|
90
|
+
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
|
|
91
|
+
if (!outcome.enqueued) {
|
|
92
|
+
ctx.ports.logger.warn(
|
|
93
|
+
`${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return outcome.enqueued;
|
|
97
|
+
}
|
|
98
|
+
__name(enqueueOutbound, "enqueueOutbound");
|
|
99
|
+
|
|
100
|
+
// src/core/cancellation-outcome.ts
|
|
101
|
+
async function tell(ctx, what, orderId, call) {
|
|
102
|
+
try {
|
|
103
|
+
await call();
|
|
104
|
+
} catch (error) {
|
|
105
|
+
ctx.ports.logger.error(
|
|
106
|
+
`marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
__name(tell, "tell");
|
|
111
|
+
function requestsFirst(ctx) {
|
|
112
|
+
return ctx.ports.order.onCancellationConfirmed !== void 0;
|
|
113
|
+
}
|
|
114
|
+
__name(requestsFirst, "requestsFirst");
|
|
115
|
+
async function rejectConfirmed(db, orderId, now) {
|
|
116
|
+
await db.marketplaceAcceptance.updateMany({
|
|
117
|
+
where: { orderId, status: "AWAITING" },
|
|
118
|
+
data: { status: "REJECTED", acknowledgedAt: now }
|
|
119
|
+
});
|
|
120
|
+
await db.marketplaceAcceptance.updateMany({
|
|
121
|
+
where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
|
|
122
|
+
data: { status: "REJECTED" }
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
__name(rejectConfirmed, "rejectConfirmed");
|
|
126
|
+
async function confirmedToHost(ctx, clientId, orderId) {
|
|
127
|
+
if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
|
|
128
|
+
await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
|
|
129
|
+
}
|
|
130
|
+
__name(confirmedToHost, "confirmedToHost");
|
|
131
|
+
async function tellCancellationConfirmed(ctx, clientId, orderId) {
|
|
132
|
+
const hook = ctx.ports.order.onCancellationConfirmed;
|
|
133
|
+
if (!hook) return false;
|
|
134
|
+
await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
__name(tellCancellationConfirmed, "tellCancellationConfirmed");
|
|
138
|
+
async function tellCancellationFailed(ctx, clientId, orderId, reason) {
|
|
139
|
+
const hook = ctx.ports.order.onCancellationFailed;
|
|
140
|
+
if (!hook) return;
|
|
141
|
+
await tell(
|
|
142
|
+
ctx,
|
|
143
|
+
`had its cancellation request fail (${reason})`,
|
|
144
|
+
orderId,
|
|
145
|
+
() => hook.call(ctx.ports.order, clientId, orderId, reason)
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
__name(tellCancellationFailed, "tellCancellationFailed");
|
|
149
|
+
function cancellationWindowMs(ctx, adapter) {
|
|
150
|
+
return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
|
|
151
|
+
}
|
|
152
|
+
__name(cancellationWindowMs, "cancellationWindowMs");
|
|
153
|
+
function failedRequestData(reason) {
|
|
154
|
+
return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
|
|
155
|
+
}
|
|
156
|
+
__name(failedRequestData, "failedRequestData");
|
|
157
|
+
|
|
158
|
+
// src/core/cancellation.ts
|
|
159
|
+
function noStandingRequest(cancellationStatus) {
|
|
160
|
+
return cancellationStatus === null || cancellationStatus === "FAILED";
|
|
161
|
+
}
|
|
162
|
+
__name(noStandingRequest, "noStandingRequest");
|
|
163
|
+
var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
|
|
164
|
+
var CLAIM_SELECT = {
|
|
165
|
+
orderId: true,
|
|
166
|
+
provider: true,
|
|
167
|
+
status: true,
|
|
168
|
+
cancellationStatus: true,
|
|
169
|
+
lineSkus: true
|
|
170
|
+
};
|
|
171
|
+
function notPendingProblem(row, path, allowed = ["AWAITING"]) {
|
|
172
|
+
if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
|
|
173
|
+
if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
|
|
174
|
+
const status = row.status;
|
|
175
|
+
return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
|
|
176
|
+
}
|
|
177
|
+
__name(notPendingProblem, "notPendingProblem");
|
|
178
|
+
function lineSkusOf(row) {
|
|
179
|
+
return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
|
|
180
|
+
}
|
|
181
|
+
__name(lineSkusOf, "lineSkusOf");
|
|
182
|
+
function skuProblems(reason, skus, row, path) {
|
|
183
|
+
if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
|
|
184
|
+
const known = lineSkusOf(row);
|
|
185
|
+
if (!known) return [];
|
|
186
|
+
return skus.flatMap(
|
|
187
|
+
(sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
__name(skuProblems, "skuProblems");
|
|
191
|
+
function invalidReasonProblem(adapter, reason, code, path) {
|
|
192
|
+
if (code === null || code === void 0 || reason) return null;
|
|
193
|
+
const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
|
|
194
|
+
return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
|
|
195
|
+
}
|
|
196
|
+
__name(invalidReasonProblem, "invalidReasonProblem");
|
|
197
|
+
function planCancellation(adapter, input, row, path) {
|
|
198
|
+
if (!adapter) return { status: null, reason: null, skus: [] };
|
|
199
|
+
const reason = resolveReason(adapter, input.reasonCode);
|
|
200
|
+
const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
|
|
201
|
+
if (invalid) return [invalid];
|
|
202
|
+
const skus = [...new Set(input.offendingSkus ?? [])];
|
|
203
|
+
const problems = skuProblems(reason, skus, row, path);
|
|
204
|
+
if (problems.length > 0) return problems;
|
|
205
|
+
const { apiCancel, cancelAfterAccept } = adapter.capabilities;
|
|
206
|
+
const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
|
|
207
|
+
return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
|
|
208
|
+
}
|
|
209
|
+
__name(planCancellation, "planCancellation");
|
|
210
|
+
function refusalData(plan, fromStatus, now) {
|
|
211
|
+
return {
|
|
212
|
+
status: "REJECTED",
|
|
213
|
+
// An accepted row keeps the instant it was accepted; a row leaving the
|
|
214
|
+
// clock is acknowledged now (the table's CHECK pairs the two).
|
|
215
|
+
...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
|
|
216
|
+
cancellationStatus: plan.status,
|
|
217
|
+
cancellationReasonCode: plan.reason?.code ?? null,
|
|
218
|
+
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
219
|
+
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
220
|
+
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
__name(refusalData, "refusalData");
|
|
224
|
+
function requestData(plan, now) {
|
|
225
|
+
return {
|
|
226
|
+
cancellationStatus: plan.status,
|
|
227
|
+
cancellationReasonCode: plan.reason?.code ?? null,
|
|
228
|
+
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
229
|
+
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
230
|
+
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
__name(requestData, "requestData");
|
|
234
|
+
async function failCancellationRequest(ctx, input) {
|
|
235
|
+
const db = await ctx.ports.db();
|
|
236
|
+
const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
|
|
237
|
+
const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
|
|
238
|
+
if (!row) return false;
|
|
239
|
+
const moved = await db.marketplaceAcceptance.updateMany({
|
|
240
|
+
where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
|
|
241
|
+
data: failedRequestData("REFUSED")
|
|
242
|
+
});
|
|
243
|
+
if (moved.count === 0) return false;
|
|
244
|
+
ctx.ports.publishChanged(input.clientId);
|
|
245
|
+
await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
|
|
246
|
+
return true;
|
|
247
|
+
}
|
|
248
|
+
__name(failCancellationRequest, "failCancellationRequest");
|
|
249
|
+
|
|
250
|
+
// src/core/outbound-sweep.ts
|
|
251
|
+
var OUTBOUND_STALE_MS = 10 * 6e4;
|
|
252
|
+
var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
|
|
253
|
+
var WAITING = ["PENDING", "REQUESTED"];
|
|
254
|
+
var OWED_SELECT = { clientId: true, orderId: true, provider: true };
|
|
255
|
+
function sweepDedupeKey(action, orderId, now) {
|
|
256
|
+
return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
|
|
257
|
+
}
|
|
258
|
+
__name(sweepDedupeKey, "sweepDedupeKey");
|
|
259
|
+
async function requeue(ctx, rows, action, now) {
|
|
260
|
+
let queued = 0;
|
|
261
|
+
for (const row of rows) {
|
|
262
|
+
const payload = { clientId: row.clientId, orderId: row.orderId, action };
|
|
263
|
+
if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
|
|
264
|
+
}
|
|
265
|
+
return queued;
|
|
266
|
+
}
|
|
267
|
+
__name(requeue, "requeue");
|
|
268
|
+
async function failAsTimeout(ctx, rows) {
|
|
269
|
+
const db = await ctx.ports.db();
|
|
270
|
+
let failed = 0;
|
|
271
|
+
for (const row of rows) {
|
|
272
|
+
const moved = await db.marketplaceAcceptance.updateMany({
|
|
273
|
+
where: { orderId: row.orderId, clientId: row.clientId, cancellationStatus: { in: WAITING } },
|
|
274
|
+
data: failedRequestData("TIMEOUT")
|
|
275
|
+
});
|
|
276
|
+
if (moved.count === 0) continue;
|
|
277
|
+
failed += 1;
|
|
278
|
+
ctx.ports.publishChanged(row.clientId);
|
|
279
|
+
await tellCancellationFailed(ctx, row.clientId, row.orderId, "TIMEOUT");
|
|
280
|
+
}
|
|
281
|
+
return failed;
|
|
282
|
+
}
|
|
283
|
+
__name(failAsTimeout, "failAsTimeout");
|
|
284
|
+
async function waitingSince(ctx, cutoff, statuses, provider) {
|
|
285
|
+
const db = await ctx.ports.db();
|
|
286
|
+
return await db.marketplaceAcceptance.findMany({
|
|
287
|
+
where: { ...provider ? { provider } : {}, cancellationStatus: { in: statuses }, cancellationRequestedAt: { lt: cutoff } },
|
|
288
|
+
select: OWED_SELECT
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
__name(waitingSince, "waitingSince");
|
|
292
|
+
async function expireUnanswered(ctx, now) {
|
|
293
|
+
if (!requestsFirst(ctx)) return 0;
|
|
294
|
+
let expired = 0;
|
|
295
|
+
for (const provider of ctx.registry.providers()) {
|
|
296
|
+
const adapter = ctx.registry.get(provider);
|
|
297
|
+
const window = adapter ? cancellationWindowMs(ctx, adapter) : null;
|
|
298
|
+
if (window === null) continue;
|
|
299
|
+
const cutoff = new Date(now.getTime() - window);
|
|
300
|
+
expired += await failAsTimeout(ctx, await waitingSince(ctx, cutoff, WAITING, provider));
|
|
301
|
+
}
|
|
302
|
+
return expired;
|
|
303
|
+
}
|
|
304
|
+
__name(expireUnanswered, "expireUnanswered");
|
|
305
|
+
async function sweepOutbound(ctx, now) {
|
|
306
|
+
const db = await ctx.ports.db();
|
|
307
|
+
const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
|
|
308
|
+
const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
|
|
309
|
+
const timedOut = await expireUnanswered(ctx, now);
|
|
310
|
+
const givenUp = await failAsTimeout(ctx, await waitingSince(ctx, giveUp, requestsFirst(ctx) ? WAITING : ["PENDING"]));
|
|
311
|
+
const cancellations = await db.marketplaceAcceptance.findMany({
|
|
312
|
+
where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
|
|
313
|
+
select: OWED_SELECT
|
|
314
|
+
});
|
|
315
|
+
const confirms = await db.marketplaceAcceptance.findMany({
|
|
316
|
+
where: {
|
|
317
|
+
status: "ACCEPTED",
|
|
318
|
+
confirmedAt: null,
|
|
319
|
+
confirmFailedAt: null,
|
|
320
|
+
acknowledgedAt: { lt: stale, gte: giveUp },
|
|
321
|
+
// An accept the store asked to cancel is not confirmed while the request waits.
|
|
322
|
+
...NO_STANDING_REQUEST
|
|
323
|
+
},
|
|
324
|
+
select: OWED_SELECT
|
|
325
|
+
});
|
|
326
|
+
const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
|
|
327
|
+
if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
|
|
328
|
+
return { requeued, givenUp, timedOut };
|
|
329
|
+
}
|
|
330
|
+
__name(sweepOutbound, "sweepOutbound");
|
|
331
|
+
|
|
79
332
|
// src/core/integration.ts
|
|
80
333
|
var VIEW_SELECT = {
|
|
81
334
|
provider: true,
|
|
@@ -228,6 +481,7 @@ var ROW_SELECT = {
|
|
|
228
481
|
cancellationStatus: true,
|
|
229
482
|
cancellationReasonCode: true,
|
|
230
483
|
cancellationOffendingSkus: true,
|
|
484
|
+
cancellationRequestedAt: true,
|
|
231
485
|
preparationMinutes: true,
|
|
232
486
|
createdAt: true
|
|
233
487
|
};
|
|
@@ -242,6 +496,9 @@ function refOf(row) {
|
|
|
242
496
|
__name(refOf, "refOf");
|
|
243
497
|
function confirmSkip(row, adapter) {
|
|
244
498
|
if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
|
|
499
|
+
if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
|
|
500
|
+
return `a cancellation request is ${row.cancellationStatus}`;
|
|
501
|
+
}
|
|
245
502
|
if (row.confirmedAt || row.confirmFailedAt) return "the confirm is already stamped";
|
|
246
503
|
if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
|
|
247
504
|
return null;
|
|
@@ -255,14 +512,38 @@ async function stampConfirm(ctx, row, succeeded, now) {
|
|
|
255
512
|
});
|
|
256
513
|
}
|
|
257
514
|
__name(stampConfirm, "stampConfirm");
|
|
258
|
-
async function stampCancellation(ctx, row, status) {
|
|
515
|
+
async function stampCancellation(ctx, row, status, clientId) {
|
|
516
|
+
if (status === "CONFIRMED") return stampConfirmedCancellation(ctx, row, clientId);
|
|
259
517
|
const db = await ctx.ports.db();
|
|
260
|
-
|
|
518
|
+
const data = status === "FAILED" ? failedRequestData("REFUSED") : { cancellationStatus: status };
|
|
519
|
+
const moved = await db.marketplaceAcceptance.updateMany({
|
|
261
520
|
where: { orderId: row.orderId, cancellationStatus: "PENDING" },
|
|
262
|
-
data
|
|
521
|
+
data
|
|
263
522
|
});
|
|
523
|
+
if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
|
|
264
524
|
}
|
|
265
525
|
__name(stampCancellation, "stampCancellation");
|
|
526
|
+
async function stampConfirmedCancellation(ctx, row, clientId) {
|
|
527
|
+
const now = ctx.ports.clock.now();
|
|
528
|
+
const moved = await ctx.ports.transaction(async (tx) => {
|
|
529
|
+
const confirmed = await tx.marketplaceAcceptance.updateMany({
|
|
530
|
+
where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "FAILED"] } },
|
|
531
|
+
data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
|
|
532
|
+
});
|
|
533
|
+
if (confirmed.count === 0) return false;
|
|
534
|
+
await rejectConfirmed(tx, row.orderId, now);
|
|
535
|
+
return true;
|
|
536
|
+
});
|
|
537
|
+
if (!moved) return;
|
|
538
|
+
try {
|
|
539
|
+
await confirmedToHost(ctx, clientId, row.orderId);
|
|
540
|
+
} catch (error) {
|
|
541
|
+
ctx.ports.logger.error(
|
|
542
|
+
`marketplace.outbound: order ${row.orderId} was cancelled on the store's request but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
__name(stampConfirmedCancellation, "stampConfirmedCancellation");
|
|
266
547
|
async function connectionFor(ctx, clientId, provider) {
|
|
267
548
|
try {
|
|
268
549
|
return await readOutboundConnection(ctx, clientId, provider) ?? "no credentials on file";
|
|
@@ -309,6 +590,13 @@ async function runConfirm(ctx, payload, row, adapter, attempt) {
|
|
|
309
590
|
);
|
|
310
591
|
}
|
|
311
592
|
__name(runConfirm, "runConfirm");
|
|
593
|
+
function pastWindow(ctx, row, adapter) {
|
|
594
|
+
if (!requestsFirst(ctx)) return false;
|
|
595
|
+
const window = cancellationWindowMs(ctx, adapter);
|
|
596
|
+
if (window === null || row.cancellationRequestedAt === null) return false;
|
|
597
|
+
return ctx.ports.clock.now().getTime() - row.cancellationRequestedAt.getTime() > window;
|
|
598
|
+
}
|
|
599
|
+
__name(pastWindow, "pastWindow");
|
|
312
600
|
function skusOf(row) {
|
|
313
601
|
return Array.isArray(row.cancellationOffendingSkus) ? row.cancellationOffendingSkus.map(String) : [];
|
|
314
602
|
}
|
|
@@ -317,6 +605,10 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
|
|
|
317
605
|
if (row.cancellationStatus !== "PENDING") {
|
|
318
606
|
return { kind: "skipped", reason: `the request is ${row.cancellationStatus ?? "absent"}, not PENDING` };
|
|
319
607
|
}
|
|
608
|
+
if (pastWindow(ctx, row, adapter)) {
|
|
609
|
+
await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
|
|
610
|
+
return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
|
|
611
|
+
}
|
|
320
612
|
const reason = resolveReason(adapter, row.cancellationReasonCode);
|
|
321
613
|
const connection = await connectionFor(ctx, payload.clientId, row.provider);
|
|
322
614
|
let result;
|
|
@@ -336,23 +628,26 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
|
|
|
336
628
|
row,
|
|
337
629
|
result,
|
|
338
630
|
attempt,
|
|
339
|
-
() => stampCancellation(ctx, row, taken),
|
|
340
|
-
() => stampCancellation(ctx, row, "FAILED")
|
|
631
|
+
() => stampCancellation(ctx, row, taken, payload.clientId),
|
|
632
|
+
() => stampCancellation(ctx, row, "FAILED", payload.clientId)
|
|
341
633
|
);
|
|
342
634
|
}
|
|
343
635
|
__name(runCancellation, "runCancellation");
|
|
344
636
|
async function stampLastAttemptFailure(ctx, payload, error) {
|
|
345
637
|
const reason = error instanceof Error ? error.message : String(error);
|
|
346
638
|
const db = await ctx.ports.db();
|
|
347
|
-
await (payload.action === "confirm" ? db.marketplaceAcceptance.updateMany({
|
|
639
|
+
const moved = await (payload.action === "confirm" ? db.marketplaceAcceptance.updateMany({
|
|
348
640
|
where: { orderId: payload.orderId, clientId: payload.clientId, confirmedAt: null, confirmFailedAt: null },
|
|
349
641
|
data: { confirmFailedAt: ctx.ports.clock.now() }
|
|
350
642
|
}) : db.marketplaceAcceptance.updateMany({
|
|
351
643
|
where: { orderId: payload.orderId, clientId: payload.clientId, cancellationStatus: "PENDING" },
|
|
352
|
-
data:
|
|
644
|
+
data: failedRequestData("REFUSED")
|
|
353
645
|
}));
|
|
354
646
|
ctx.ports.logger.error(`marketplace.outbound: ${payload.action} for order ${payload.orderId} failed: ${reason}`);
|
|
355
647
|
ctx.ports.publishChanged(payload.clientId);
|
|
648
|
+
if (payload.action === "requestCancellation" && moved.count > 0) {
|
|
649
|
+
await tellCancellationFailed(ctx, payload.clientId, payload.orderId, "REFUSED");
|
|
650
|
+
}
|
|
356
651
|
return { kind: "failed", action: payload.action, reason };
|
|
357
652
|
}
|
|
358
653
|
__name(stampLastAttemptFailure, "stampLastAttemptFailure");
|
|
@@ -379,17 +674,34 @@ async function runOutbound(ctx, payload, attempt) {
|
|
|
379
674
|
__name(runOutbound, "runOutbound");
|
|
380
675
|
|
|
381
676
|
export {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
markMarketplaceEventSeen,
|
|
677
|
+
requestsFirst,
|
|
678
|
+
rejectConfirmed,
|
|
679
|
+
tellCancellationConfirmed,
|
|
680
|
+
tellCancellationFailed,
|
|
387
681
|
PROVIDER_ID_PATTERN,
|
|
388
682
|
MarketplaceAdapterRegistrationError,
|
|
389
683
|
createAdapterRegistry,
|
|
390
684
|
resolveReason,
|
|
391
685
|
suggestReason,
|
|
686
|
+
NO_STANDING_REQUEST,
|
|
687
|
+
CLAIM_SELECT,
|
|
688
|
+
notPendingProblem,
|
|
689
|
+
planCancellation,
|
|
690
|
+
refusalData,
|
|
691
|
+
requestData,
|
|
692
|
+
failCancellationRequest,
|
|
693
|
+
listMarketplaceIntegrations,
|
|
694
|
+
saveMarketplaceIntegration,
|
|
695
|
+
resolveIngestionTarget,
|
|
696
|
+
resolveTenantByMerchant,
|
|
697
|
+
markMarketplaceEventSeen,
|
|
698
|
+
MARKETPLACE_OUTBOUND_JOB,
|
|
699
|
+
outboundDedupeKey,
|
|
700
|
+
enqueueOutbound,
|
|
701
|
+
OUTBOUND_STALE_MS,
|
|
702
|
+
OUTBOUND_GIVE_UP_MS,
|
|
703
|
+
sweepOutbound,
|
|
392
704
|
OutboundRetryError,
|
|
393
705
|
runOutbound
|
|
394
706
|
};
|
|
395
|
-
//# sourceMappingURL=chunk-
|
|
707
|
+
//# sourceMappingURL=chunk-DVIRN42O.js.map
|