@12-apps/marketplace 1.7.0 → 1.8.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.
Files changed (67) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +56 -0
  3. package/dist/99food/index.d.ts +4 -2
  4. package/dist/99food/index.js +32 -3
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -3
  18. package/dist/ifood/index.d.ts +1 -1
  19. package/dist/ifood/index.js +29 -3
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +104 -7
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/index.d.ts +3 -0
  25. package/dist/manifest/index.js +1 -1
  26. package/dist/manifest/server.d.ts +2 -2
  27. package/dist/manifest/server.js +3 -3
  28. package/dist/rappi/index.d.ts +7 -1
  29. package/dist/rappi/index.js +20 -3
  30. package/dist/rappi/index.js.map +1 -1
  31. package/dist/server/index.d.ts +6 -2
  32. package/dist/server/index.js +3 -3
  33. package/package.json +1 -1
  34. package/prisma/marketplace.prisma +45 -1
  35. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  36. package/src/99food/index.ts +6 -0
  37. package/src/99food/normalize.ts +7 -1
  38. package/src/99food/outbound.ts +55 -0
  39. package/src/core/adapter.ts +41 -1
  40. package/src/core/bulk.ts +1 -1
  41. package/src/core/engine.ts +9 -0
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +17 -0
  44. package/src/core/lifecycle-port.ts +16 -0
  45. package/src/core/lifecycle.ts +133 -0
  46. package/src/core/outbound-queue.ts +24 -4
  47. package/src/core/outbound-sweep.ts +49 -5
  48. package/src/core/outbound.ts +11 -0
  49. package/src/core/pipeline.ts +22 -2
  50. package/src/core/ports.ts +39 -3
  51. package/src/core/status-inform.ts +51 -0
  52. package/src/core/status-job.ts +207 -0
  53. package/src/core/status-store.ts +85 -0
  54. package/src/core/types.ts +14 -0
  55. package/src/ifood/index.ts +7 -1
  56. package/src/ifood/normalize.ts +17 -0
  57. package/src/ifood/outbound.ts +35 -0
  58. package/src/index.ts +6 -0
  59. package/src/rappi/index.ts +6 -1
  60. package/src/rappi/normalize.ts +6 -0
  61. package/src/rappi/outbound.ts +31 -2
  62. package/src/server/mcp.ts +2 -0
  63. package/src/server/webhook.ts +3 -1
  64. package/dist/chunk-L3DCOZUU.js.map +0 -1
  65. package/dist/chunk-SJUKBCVO.js.map +0 -1
  66. package/dist/chunk-UYFYGGCS.js.map +0 -1
  67. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -8,6 +8,7 @@ import {
8
8
  verifyHmacSha256Hex,
9
9
  } from "../core/payload-read";
10
10
  import type {
11
+ MarketplaceLifecycle,
11
12
  MarketplaceDeliveredBy,
12
13
  MarketplaceOrderType,
13
14
  NormalizedAddress,
@@ -39,6 +40,8 @@ export const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
39
40
  const CREATED = "CREATED";
40
41
  /** The order is cancelled: the store's request was granted, or a mandatory cancellation. */
41
42
  const CANCELLED = "CANCELLED";
43
+ /** The order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */
44
+ const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: "DISPATCHED", CONCLUDED: "CONCLUDED" };
42
45
  /** The marketplace refused the store's own cancellation request. */
43
46
  const CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
44
47
 
@@ -68,7 +71,9 @@ export function verifyOpenDeliverySignature(
68
71
  * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
69
72
  * - `CANCELLED` is a cancellation, whether the store asked for it or not.
70
73
  * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
71
- * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the
74
+ * - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine
75
+ * asks the host to move the order forward, when the store follows them.
76
+ * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, the
72
77
  * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
73
78
  * recorded, and acts on nothing: an IGNORED inbox row.
74
79
  *
@@ -93,6 +98,7 @@ export function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent |
93
98
  orderToFetch: eventType === CREATED,
94
99
  cancelled,
95
100
  cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
101
+ ...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),
96
102
  };
97
103
  }
98
104
 
@@ -8,6 +8,7 @@ import {
8
8
  type MarketplaceHttpResponse,
9
9
  type OutboundOrderRef,
10
10
  type OutboundResult,
11
+ type StatusFacts,
11
12
  } from "../core/adapter";
12
13
  import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from "./normalize";
13
14
 
@@ -223,3 +224,57 @@ export function openDeliveryRequestCancellation(
223
224
  return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
224
225
  });
225
226
  }
227
+
228
+ /**
229
+ * What 99Food is told per step (FUT-4653), from Open Delivery v1.7.1's
230
+ * `openapi.yaml` (https://abrasel-nacional.github.io/opendelivery/openapi.yaml,
231
+ * read 2026-11-25, paths at lines 1605-1890):
232
+ *
233
+ * - READY: `POST /v1/orders/{id}/readyForPickup`, "ready for pickup by the
234
+ * customer or delivery person"; 202. Every kind of order.
235
+ * - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`
236
+ * (`deliveryTrackingInfo` optional, sent empty), and "a DISPATCHED event is
237
+ * expected after this action". Only where the logistics is the merchant's.
238
+ * - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a
239
+ * take-out `POST /v1/orders/{id}/pickedUp`. Both optional in the spec. The
240
+ * marketplace's own fleet: none.
241
+ *
242
+ * The kind of order is `deliveredBy` (null: a take-out). That a take-out's
243
+ * order states no `deliveredBy` is how 99Food's order reads (ESTIMATED: an
244
+ * order that merely omits it reads as a take-out here).
245
+ */
246
+ const STATUS_PATH: Readonly<Record<string, (facts: StatusFacts) => { action: string; body?: unknown } | null>> = {
247
+ READY: () => ({ action: "readyForPickup" }),
248
+ DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null),
249
+ HANDED_OVER: (facts) =>
250
+ facts.deliveredBy === "MERCHANT"
251
+ ? { action: "delivered", body: {} }
252
+ : facts.deliveredBy === null
253
+ ? { action: "pickedUp", body: {} }
254
+ : null,
255
+ };
256
+
257
+ /** Whether 99Food takes this step for this kind of order: answered offline. */
258
+ export function openDeliveryStatusSupported(facts: StatusFacts): boolean {
259
+ return STATUS_PATH[facts.step]?.(facts) != null;
260
+ }
261
+
262
+ /** Tell 99Food a step happened. `unsupported` when the spec has no call for it. */
263
+ export function openDeliveryInformStatus(
264
+ ctx: AdapterCallContext,
265
+ bases: NinetyNineFoodApiBaseUrls,
266
+ order: OutboundOrderRef,
267
+ facts: StatusFacts,
268
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
269
+ const path = STATUS_PATH[facts.step]?.(facts) ?? null;
270
+ if (path === null) return Promise.resolve({ kind: "unsupported" });
271
+ return answered(async () => {
272
+ const response = await callOrder(ctx, bases, {
273
+ method: "POST",
274
+ externalOrderId: order.externalOrderId,
275
+ action: path.action,
276
+ ...(path.body === undefined ? {} : { body: path.body }),
277
+ });
278
+ return "kind" in response ? response : outboundResultOf(response);
279
+ });
280
+ }
@@ -1,7 +1,12 @@
1
1
  import type { MarketplaceCatalogue } from "./catalogue-port";
2
2
  import type { CatalogueReader } from "./catalogue-read-port";
3
3
  import type { MarketplaceAvailability } from "./pause-port";
4
- import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
4
+ import type {
5
+ MarketplaceDeliveredBy,
6
+ MarketplaceProvider,
7
+ NormalizedEvent,
8
+ NormalizedMarketplaceOrder,
9
+ } from "./types";
5
10
 
6
11
  /**
7
12
  * The adapter port: everything one marketplace is, behind one shape.
@@ -83,6 +88,23 @@ export interface MarketplaceCapabilities {
83
88
  * the request as TIMEOUT. Absent: only the 24-hour give-up applies.
84
89
  */
85
90
  cancellationAnswerWindowMs?: number;
91
+ /**
92
+ * OPTIONAL. The steps this marketplace can be told about (`informStatus`).
93
+ * Absent or empty: the engine tells it nothing.
94
+ */
95
+ statusSteps?: readonly StatusStep[];
96
+ }
97
+
98
+ /**
99
+ * A step of the order the store tells the marketplace about (FUT-4653): the
100
+ * order is ready for pickup, the courier left, the order was handed over.
101
+ */
102
+ export type StatusStep = "READY" | "DISPATCHED" | "HANDED_OVER";
103
+
104
+ /** What a status call is told about the order: who carries it (null: a take-out, or unstated). */
105
+ export interface StatusFacts {
106
+ step: StatusStep;
107
+ deliveredBy: MarketplaceDeliveredBy | null;
86
108
  }
87
109
 
88
110
  /** One reason a store may give for refusing or cancelling an order. */
@@ -176,6 +198,24 @@ export interface MarketplaceAdapter {
176
198
  order: OutboundOrderRef,
177
199
  input: CancellationRequestInput,
178
200
  ): Promise<OutboundResult>;
201
+ /**
202
+ * OPTIONAL. Whether this marketplace takes this step for this kind of order,
203
+ * answered offline, with no call: the job asks it BEFORE it claims anything
204
+ * (an unsupported step leaves no row). Absent: every step in
205
+ * `capabilities.statusSteps` is taken for every order.
206
+ */
207
+ statusSupported?(facts: StatusFacts): boolean;
208
+ /**
209
+ * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called
210
+ * only from the `marketplace.outbound` job, action `status`. `unsupported`
211
+ * (no endpoint for this step and this kind of order) ends the job with no
212
+ * row. Absent: the marketplace is told nothing.
213
+ */
214
+ informStatus?(
215
+ ctx: AdapterCallContext,
216
+ order: OutboundOrderRef,
217
+ facts: StatusFacts,
218
+ ): Promise<OutboundResult | { kind: "unsupported" }>;
179
219
  /**
180
220
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
181
221
  * marketplace whose events carry no order body). Called only from the
package/src/core/bulk.ts CHANGED
@@ -67,7 +67,7 @@ function unknownProviders(ctx: EngineContext, rows: readonly { provider: string
67
67
  );
68
68
  }
69
69
 
70
- const SETTING_KEYS = ["enabled", "environment", "externalMerchantId", "autoAccept", "ackSlaSeconds", "credentials"] as const;
70
+ const SETTING_KEYS = ["enabled", "environment", "externalMerchantId", "autoAccept", "followStatus", "ackSlaSeconds", "credentials"] as const;
71
71
 
72
72
  function integrationRowProblems(
73
73
  row: IntegrationRowInput,
@@ -60,6 +60,7 @@ import {
60
60
  } from "./integration";
61
61
  import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
62
62
  import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
63
+ import { informStatus, type InformStatusInput } from "./status-inform";
63
64
  import {
64
65
  availabilityState,
65
66
  pauseStore,
@@ -195,6 +196,13 @@ export interface MarketplaceEngine {
195
196
  sweepOutbound(now?: Date): Promise<OutboundSweepResult>;
196
197
  /** Run one queued outbound call (the `marketplace.outbound` job's body). */
197
198
  runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;
199
+ /**
200
+ * Tell the marketplace the order reached a step (FUT-4653): ONE enqueue of
201
+ * the `marketplace.outbound` job, action `status`. Never throws, runs no
202
+ * statement and calls nobody: the job decides everything else. True when the
203
+ * queue took it.
204
+ */
205
+ informStatus(input: InformStatusInput): Promise<boolean>;
198
206
  /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */
199
207
  runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;
200
208
 
@@ -310,6 +318,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
310
318
  sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),
311
319
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
312
320
  runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
321
+ informStatus: (input) => informStatus(ctx, input),
313
322
 
314
323
  // Null too when the host bound no catalogue port: nothing could be published.
315
324
  catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
@@ -41,6 +41,12 @@ export interface IngestResult {
41
41
  export interface IngestSettings {
42
42
  autoAccept: boolean;
43
43
  ackSlaSeconds: number;
44
+ /**
45
+ * OPTIONAL. The connection's switch for following the marketplace's status
46
+ * (FUT-4653). Absent is OFF: a host that builds settings by hand keeps the
47
+ * behaviour it had before the switch existed.
48
+ */
49
+ followStatus?: boolean;
44
50
  }
45
51
 
46
52
  /**
@@ -19,6 +19,12 @@ export interface MarketplaceIntegrationView {
19
19
  status: "UNVERIFIED" | "VERIFIED" | "FAILED";
20
20
  externalMerchantId: string | null;
21
21
  autoAccept: boolean;
22
+ /**
23
+ * Whether the marketplace's DISPATCHED and CONCLUDED events move the order
24
+ * forward here (FUT-4653). Always set by this version; optional in the type
25
+ * so a view built by hand against 1.x still compiles.
26
+ */
27
+ followStatus?: boolean;
22
28
  ackSlaSeconds: number;
23
29
  /**
24
30
  * Whether the store has a usable connection — i.e. whether secrets are on
@@ -40,6 +46,7 @@ interface IntegrationRow {
40
46
  status: string;
41
47
  externalMerchantId: string | null;
42
48
  autoAccept: boolean;
49
+ followStatus?: boolean;
43
50
  ackSlaSeconds: number;
44
51
  credentials: string;
45
52
  lastEventAt: Date | null;
@@ -54,6 +61,7 @@ const VIEW_SELECT = {
54
61
  status: true,
55
62
  externalMerchantId: true,
56
63
  autoAccept: true,
64
+ followStatus: true,
57
65
  ackSlaSeconds: true,
58
66
  credentials: true,
59
67
  lastEventAt: true,
@@ -69,6 +77,7 @@ function toView(row: IntegrationRow): MarketplaceIntegrationView {
69
77
  status: row.status as MarketplaceIntegrationView["status"],
70
78
  externalMerchantId: row.externalMerchantId,
71
79
  autoAccept: row.autoAccept,
80
+ followStatus: row.followStatus ?? true,
72
81
  ackSlaSeconds: row.ackSlaSeconds,
73
82
  connected: row.credentials !== "",
74
83
  lastEventAt: row.lastEventAt,
@@ -107,6 +116,8 @@ export interface SaveMarketplaceIntegrationInput {
107
116
  environment?: "SANDBOX" | "PRODUCTION";
108
117
  externalMerchantId?: string | null;
109
118
  autoAccept?: boolean;
119
+ /** Whether the marketplace's DISPATCHED and CONCLUDED events move the order forward here. New connections: true. */
120
+ followStatus?: boolean;
110
121
  ackSlaSeconds?: number;
111
122
  /**
112
123
  * The secrets, when the operator re-entered them. Absent means "leave the
@@ -144,6 +155,7 @@ export async function saveMarketplaceIntegration(
144
155
  ? {}
145
156
  : { externalMerchantId: input.externalMerchantId }),
146
157
  ...(input.autoAccept === undefined ? {} : { autoAccept: input.autoAccept }),
158
+ ...(input.followStatus === undefined ? {} : { followStatus: input.followStatus }),
147
159
  ...(input.ackSlaSeconds === undefined ? {} : { ackSlaSeconds: input.ackSlaSeconds }),
148
160
  ...(sealed === undefined ? {} : { credentials: sealed, status: "UNVERIFIED" }),
149
161
  };
@@ -166,6 +178,8 @@ export async function saveMarketplaceIntegration(
166
178
  export interface IngestionTarget {
167
179
  enabled: boolean;
168
180
  autoAccept: boolean;
181
+ /** Whether lifecycle events move the order forward (FUT-4653). */
182
+ followStatus: boolean;
169
183
  ackSlaSeconds: number;
170
184
  webhookSecret: string | null;
171
185
  /** The merchant the store connected; a fetched order naming another is refused. */
@@ -211,6 +225,7 @@ export async function resolveIngestionTarget(
211
225
  select: {
212
226
  enabled: true,
213
227
  autoAccept: true,
228
+ followStatus: true,
214
229
  ackSlaSeconds: true,
215
230
  credentials: true,
216
231
  archivedAt: true,
@@ -220,6 +235,7 @@ export async function resolveIngestionTarget(
220
235
  externalMerchantId: string | null;
221
236
  enabled: boolean;
222
237
  autoAccept: boolean;
238
+ followStatus?: boolean;
223
239
  ackSlaSeconds: number;
224
240
  credentials: string;
225
241
  archivedAt: Date | null;
@@ -229,6 +245,7 @@ export async function resolveIngestionTarget(
229
245
  return {
230
246
  enabled: row.enabled,
231
247
  autoAccept: row.autoAccept,
248
+ followStatus: row.followStatus ?? true,
232
249
  ackSlaSeconds: row.ackSlaSeconds,
233
250
  externalMerchantId: row.externalMerchantId ?? null,
234
251
  // An unopenable blob must not read as "no secret configured" — that would
@@ -0,0 +1,16 @@
1
+ import type { MarketplaceDeliveredBy } from "./types";
2
+
3
+ /** What the engine tells the host about the order a lifecycle event names. */
4
+ export interface MarketplaceLifecycleFacts {
5
+ /** Who carries the delivery: the merchant's courier, the marketplace's fleet; null for a take-out or when unstated. */
6
+ deliveredBy: MarketplaceDeliveredBy | null;
7
+ }
8
+
9
+ /**
10
+ * The host's answer to a lifecycle event: `moved` (the order moved forward),
11
+ * `unchanged` (it did not, with the engine's default reason), or `unchanged`
12
+ * with the host's own reason, which becomes the inbox row's (an inbox row is
13
+ * a human's; "no courier named for a merchant delivery" is more use than
14
+ * "already at or past DISPATCHED").
15
+ */
16
+ export type MarketplaceLifecycleAnswer = "moved" | "unchanged" | { kind: "unchanged"; reason: string };
@@ -0,0 +1,133 @@
1
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
+ import type { IngestSettings } from "./ingest";
3
+ import type { DeliveryOutcome } from "./pipeline";
4
+ import type { EngineContext } from "./ports";
5
+ import { readStatusRows, noteMarketplaceStep, statusTable } from "./status-store";
6
+ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from "./types";
7
+
8
+ /**
9
+ * Inbound lifecycle (FUT-4653): the marketplace says the order was dispatched
10
+ * or concluded, and the order follows, FORWARD only.
11
+ *
12
+ * What the engine owns, in order, each stopping the event with a reason the
13
+ * inbox row keeps:
14
+ *
15
+ * 1. an order the engine does not hold yet is DEFERRED (PENDING, one attempt
16
+ * counted), so the reconcile pass applies the event after the order's own
17
+ * event ingests, and retires it after `maxInboxAttempts` like any row;
18
+ * 2. an order that is not ACCEPTED is never moved: the aceite is where the
19
+ * stock is judged, and an ended order is not revived;
20
+ * 3. a cancellation request standing (PENDING or REQUESTED) is the store's
21
+ * last word and nothing here contradicts it;
22
+ * 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or
23
+ * for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case
24
+ * of forward-only alone is the store's undo, where the echo would
25
+ * dispatch a card again with no courier.
26
+ *
27
+ * What the host owns (`onLifecycle`): whether the order can move, to where,
28
+ * and how. Whatever it answers, the step is NOTED as the marketplace's, so our
29
+ * own job never informs it back and nothing is informed after a CONCLUDED.
30
+ *
31
+ * A host that binds no `onLifecycle`, a connection with the switch OFF (or
32
+ * settings built by hand without it) and a host without the status model get
33
+ * `null`: the caller's old answer, "no order body", byte for byte.
34
+ */
35
+
36
+ /** The step of the table an event's echo is looked for under. */
37
+ const ECHO_OF: Record<MarketplaceLifecycle, "DISPATCHED" | "HANDED_OVER"> = {
38
+ DISPATCHED: "DISPATCHED",
39
+ CONCLUDED: "HANDED_OVER",
40
+ };
41
+
42
+ interface HeldAcceptance {
43
+ orderId: string;
44
+ status: string;
45
+ deliveredBy: string | null;
46
+ cancellationStatus: string | null;
47
+ }
48
+
49
+ /** Settle the row IGNORED with a reason, and answer it. */
50
+ async function ignored(ctx: EngineContext, inboxId: string, reason: string): Promise<DeliveryOutcome> {
51
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
52
+ return { kind: "ignored", reason };
53
+ }
54
+
55
+ /** Why a held order is not moved by the marketplace's word, or null when it may be. */
56
+ function refusal(held: HeldAcceptance): string | null {
57
+ if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
58
+ // A request that FAILED left the order the store's own: only a standing one stops us.
59
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
60
+ return `a cancellation request is ${held.cancellationStatus}`;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {
66
+ return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
67
+ }
68
+
69
+ /** What `followLifecycle` needs once it is known the connection follows this event. */
70
+ interface Following {
71
+ lifecycle: MarketplaceLifecycle;
72
+ externalOrderId: string;
73
+ hook: NonNullable<EngineContext["ports"]["order"]["onLifecycle"]>;
74
+ }
75
+
76
+ /** Whether this ingestion follows this event at all: a lifecycle, the switch ON, a host hook. */
77
+ function following(ctx: EngineContext, event: NormalizedEvent, settings: IngestSettings): Following | null {
78
+ const hook = ctx.ports.order.onLifecycle;
79
+ if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
80
+ return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
81
+ }
82
+
83
+ /**
84
+ * Apply one lifecycle event, or null when this ingestion does not follow it
85
+ * (no lifecycle, switch OFF, no hook, no status model): the caller then does
86
+ * what it did before FUT-4653.
87
+ */
88
+ export async function followLifecycle(
89
+ ctx: EngineContext,
90
+ inboxId: string,
91
+ clientId: string,
92
+ event: NormalizedEvent,
93
+ settings: IngestSettings,
94
+ ): Promise<DeliveryOutcome | null> {
95
+ const follow = following(ctx, event, settings);
96
+ if (!follow) return null;
97
+ const { lifecycle, hook } = follow;
98
+ const db = await ctx.ports.db();
99
+ const table = statusTable(db);
100
+ if (!table) return null;
101
+
102
+ const held = (await db.marketplaceAcceptance.findFirst({
103
+ where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
104
+ select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true },
105
+ })) as HeldAcceptance | null;
106
+ if (!held) {
107
+ const reason = "lifecycle before its order";
108
+ await deferInboxEvent(ctx, inboxId, reason);
109
+ return { kind: "ignored", reason };
110
+ }
111
+ const stopped = refusal(held);
112
+ if (stopped) return ignored(ctx, inboxId, stopped);
113
+
114
+ const echo = ECHO_OF[lifecycle];
115
+ const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
116
+ if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
117
+
118
+ // Two statements, not one: the echo was read above and the marketplace's word is noted below. A
119
+ // genuine event judged "no echo" can lose the unique on its note to our own job claiming in
120
+ // between, and that job then sends a step the marketplace already has. Harmless (at worst a 4xx,
121
+ // FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering
122
+ // would put a write before the host's answer on every event.
123
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
124
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
125
+ if (answer === "moved") {
126
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
127
+ ctx.ports.publishChanged(clientId);
128
+ return { kind: "moved", orderId: held.orderId, lifecycle };
129
+ }
130
+ const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
131
+ if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
132
+ return ignored(ctx, inboxId, reason);
133
+ }
@@ -1,3 +1,4 @@
1
+ import type { StatusStep } from "./adapter";
1
2
  import type { EngineContext } from "./ports";
2
3
  import type { MarketplaceProvider } from "./types";
3
4
 
@@ -14,19 +15,34 @@ import type { MarketplaceProvider } from "./types";
14
15
  /** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */
15
16
  export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
16
17
 
17
- /** What goes out: the store's aceite, or the store's cancellation request. */
18
- export type OutboundAction = "confirm" | "requestCancellation";
18
+ /**
19
+ * What goes out: the store's aceite, the store's cancellation request, or a
20
+ * step of the order the store reached (`status`, FUT-4653).
21
+ */
22
+ export type OutboundAction = "confirm" | "requestCancellation" | "status";
19
23
 
20
24
  /** The outbound job's payload. Identifiers only. */
21
25
  export interface OutboundJobPayload {
22
26
  clientId: string;
23
27
  orderId: string;
24
28
  action: OutboundAction;
29
+ /** OPTIONAL. The step a `status` call tells the marketplace about; absent on every other action. */
30
+ step?: StatusStep;
31
+ /**
32
+ * OPTIONAL. The key of the move (or of the sweep's re-claim) a `status` call
33
+ * belongs to: the owner of its SENDING claim. Absent on every other action.
34
+ */
35
+ claimKey?: string;
25
36
  }
26
37
 
27
38
  /** The dedupe key: at most one queued call per (order, action). */
28
39
  export function outboundDedupeKey(payload: OutboundJobPayload): string {
29
- return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
40
+ return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.step ? `${payload.step}:` : ""}${payload.orderId}`;
41
+ }
42
+
43
+ /** The dedupe key of one status move: a re-dispatch after an undo is another instant, so another key. */
44
+ export function statusDedupeKey(step: StatusStep, orderId: string, at: Date): string {
45
+ return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
30
46
  }
31
47
 
32
48
  /**
@@ -50,7 +66,11 @@ export async function enqueueOutbound(
50
66
  const adapter = ctx.registry.get(provider);
51
67
  if (!adapter) return false;
52
68
  const able =
53
- payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
69
+ payload.action === "status"
70
+ ? Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step))
71
+ : payload.action === "confirm"
72
+ ? adapter.capabilities.apiConfirm
73
+ : adapter.capabilities.apiCancel;
54
74
  if (!able) return false;
55
75
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
56
76
  if (!outcome.enqueued) {
@@ -2,6 +2,8 @@ import { NO_STANDING_REQUEST } from "./cancellation";
2
2
  import { sweepCatalogue } from "./catalogue-sweep";
3
3
  import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
4
4
  import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
5
+ import { statusTable, type StatusRowStep } from "./status-store";
6
+ import type { StatusStep } from "./adapter";
5
7
  import type { EngineContext } from "./ports";
6
8
 
7
9
  /**
@@ -67,20 +69,30 @@ interface OwedRow {
67
69
  clientId: string;
68
70
  orderId: string;
69
71
  provider: string;
72
+ /** Only a status row has one. */
73
+ step?: StatusRowStep;
74
+ /** Only a status row has one: the claim the sweep takes over. */
75
+ claimKey?: string;
70
76
  }
71
77
 
72
78
  const OWED_SELECT = { clientId: true, orderId: true, provider: true } as const;
73
79
 
74
80
  /** The sweep's own dedupe key: distinct from the job's, and per pass. */
75
- function sweepDedupeKey(action: OutboundAction, orderId: string, now: Date): string {
76
- return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
81
+ function sweepDedupeKey(action: OutboundAction, orderId: string, now: Date, step?: string): string {
82
+ return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${step ? `${step}:` : ""}${orderId}:sweep:${now.getTime()}`;
77
83
  }
78
84
 
79
85
  async function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {
80
86
  let queued = 0;
81
87
  for (const row of rows) {
82
- const payload = { clientId: row.clientId, orderId: row.orderId, action };
83
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
88
+ const payload = {
89
+ clientId: row.clientId,
90
+ orderId: row.orderId,
91
+ action,
92
+ ...(row.step ? { step: row.step as StatusStep } : {}),
93
+ ...(row.claimKey === undefined ? {} : { claimKey: row.claimKey }),
94
+ };
95
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
84
96
  }
85
97
  return queued;
86
98
  }
@@ -137,6 +149,37 @@ async function expireUnanswered(ctx: EngineContext, now: Date): Promise<number>
137
149
  return expired;
138
150
  }
139
151
 
152
+ /**
153
+ * The status calls a dead job left SENDING (FUT-4653): re-queued once older
154
+ * than the job's retry span, failed once older than the give-up (a marketplace
155
+ * has long settled the order). Returns how many it re-queued and gave up on.
156
+ */
157
+ async function sweepStatus(ctx: EngineContext, now: Date): Promise<{ requeued: number; givenUp: number }> {
158
+ const table = statusTable(await ctx.ports.db());
159
+ if (!table) return { requeued: 0, givenUp: 0 };
160
+ const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
161
+ const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
162
+ const givenUp = (await table.updateMany({ where: { state: "SENDING", updatedAt: { lt: giveUp } }, data: { state: "FAILED" } })).count;
163
+ if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} status call(s).`);
164
+ const owed = (await table.findMany({
165
+ where: { state: "SENDING", source: "STORE", updatedAt: { lt: stale, gte: giveUp } },
166
+ select: { clientId: true, orderId: true, provider: true, step: true, claimKey: true },
167
+ })) as OwedRow[];
168
+ // The stale claim is TAKEN OVER under a fresh key, predicated on the old one, before the job
169
+ // is queued under the new: a job still alive under the old key can then settle or fail
170
+ // nothing, and a second sweep pass finds nothing to take.
171
+ const claimed: OwedRow[] = [];
172
+ for (const row of owed) {
173
+ const fresh = `sweep:${now.getTime()}`;
174
+ const taken = await table.updateMany({
175
+ where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
176
+ data: { claimKey: fresh },
177
+ });
178
+ if (taken.count > 0) claimed.push({ ...row, claimKey: fresh });
179
+ }
180
+ return { requeued: await requeue(ctx, claimed, "status", now), givenUp };
181
+ }
182
+
140
183
  /**
141
184
  * One sweep pass: expire the requests nobody answered, give up on the very old,
142
185
  * and re-queue what is still owed, the catalogue's publishes and withdraws
@@ -170,5 +213,6 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
170
213
  (await requeue(ctx, cancellations, "requestCancellation", now)) + (await requeue(ctx, confirms, "confirm", now));
171
214
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
172
215
  const catalogueRequeued = await sweepCatalogue(ctx, now);
173
- return { requeued, givenUp, timedOut, catalogueRequeued };
216
+ const status = await sweepStatus(ctx, now);
217
+ return { requeued: requeued + status.requeued, givenUp: givenUp + status.givenUp, timedOut, catalogueRequeued };
174
218
  }
@@ -9,6 +9,7 @@ import {
9
9
  } from "./cancellation-outcome";
10
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
11
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
+ import { failStatusRow, runStatus } from "./status-job";
12
13
  import { failAsTimeout } from "./outbound-sweep";
13
14
  import type { CancellationFailureReason, EngineContext } from "./ports";
14
15
  import { resolveReason } from "./registry";
@@ -62,6 +63,7 @@ interface OutboundRow {
62
63
  status: string;
63
64
  confirmedAt: Date | null;
64
65
  confirmFailedAt: Date | null;
66
+ deliveredBy: string | null;
65
67
  cancellationStatus: string | null;
66
68
  cancellationReasonCode: string | null;
67
69
  cancellationOffendingSkus: unknown;
@@ -78,6 +80,7 @@ const ROW_SELECT = {
78
80
  status: true,
79
81
  confirmedAt: true,
80
82
  confirmFailedAt: true,
83
+ deliveredBy: true,
81
84
  cancellationStatus: true,
82
85
  cancellationReasonCode: true,
83
86
  cancellationOffendingSkus: true,
@@ -331,6 +334,11 @@ async function runCancellation(
331
334
  */
332
335
  async function stampLastAttemptFailure(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<OutboundOutcome> {
333
336
  const reason = error instanceof Error ? error.message : String(error);
337
+ if (payload.action === "status") {
338
+ await failStatusRow(ctx, payload);
339
+ ctx.ports.logger.error(`marketplace.outbound: status ${payload.step ?? ""} for order ${payload.orderId} failed: ${reason}`);
340
+ return { kind: "failed", action: payload.action, reason };
341
+ }
334
342
  const db = await ctx.ports.db();
335
343
  const moved = await (payload.action === "confirm"
336
344
  ? db.marketplaceAcceptance.updateMany({
@@ -358,6 +366,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
358
366
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
359
367
  const adapter = ctx.registry.get(row.provider);
360
368
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
369
+ if (payload.action === "status") {
370
+ return runStatus(ctx, payload, row, adapter, { attempt, ref: refOf(row), retryError: (m) => new OutboundRetryError(m) });
371
+ }
361
372
  return payload.action === "confirm"
362
373
  ? runConfirm(ctx, payload, row, adapter, attempt)
363
374
  : runCancellation(ctx, payload, row, adapter, attempt);