@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
@@ -6,7 +6,8 @@ import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
6
6
  import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
7
  import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, markCancelledBeforeIngest } from "./order-fetch-marks";
8
8
  import type { EngineContext } from "./ports";
9
- import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
9
+ import type { MarketplaceLifecycle, MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
10
+ import { followLifecycle } from "./lifecycle";
10
11
 
11
12
  /**
12
13
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -34,6 +35,8 @@ export function normalizeEvent(
34
35
  /** How a delivery ended. `duplicate` and `ignored` are both ordinary outcomes. */
35
36
  export type DeliveryOutcome =
36
37
  | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
38
+ /** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */
39
+ | { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
37
40
  | { kind: "cancelled" }
38
41
  | { kind: "cancellationFailed" }
39
42
  /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
@@ -160,6 +163,23 @@ async function applyEvent(
160
163
  return { kind: "awaitingOrder" };
161
164
  }
162
165
 
166
+ // A lifecycle event (dispatched, concluded) of an order we hold: with the
167
+ // connection's switch ON and a host that binds the hook, the order follows.
168
+ // Anything else falls through to "understood, nothing to do", as before.
169
+ const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
170
+ if (followed) return followed;
171
+ return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
172
+ }
173
+
174
+ /** An event with no order body is understood and ignored; one that carries an order is ingested. */
175
+ async function ingestOrIgnore(
176
+ ctx: EngineContext,
177
+ inboxId: string,
178
+ clientId: string,
179
+ event: NormalizedEvent,
180
+ settings: IngestSettings,
181
+ now: Date | undefined,
182
+ ): Promise<DeliveryOutcome> {
163
183
  if (!event.order) {
164
184
  // An event type this ingestion does not act on. Marketplaces emit a wide
165
185
  // stream (dispatched, concluded, driver assigned…) and most of it is not an
@@ -243,7 +263,7 @@ export async function reprocessStoredDelivery(
243
263
  input.id,
244
264
  input.clientId,
245
265
  event,
246
- { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
266
+ { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus },
247
267
  undefined,
248
268
  );
249
269
  } catch (error) {
package/src/core/ports.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import type { AdapterRegistry } from "./registry";
2
- import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp } from "./adapter";
2
+ import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
3
3
  import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
4
- import type { NormalizedMarketplaceOrder } from "./types";
4
+ import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
+ import type { NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
6
+
7
+ export type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
8
 
6
9
  /**
7
10
  * What the engine needs FROM its host, and nothing more.
@@ -81,6 +84,16 @@ export interface MarketplaceDb {
81
84
  upsert(args: unknown): Promise<unknown>;
82
85
  updateMany(args: unknown): Promise<{ count: number }>;
83
86
  };
87
+ /**
88
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
89
+ * status model still compiles; the lifecycle and status paths do nothing
90
+ * without it (FUT-4653, migration `20261126120000_marketplace_status_updates`).
91
+ */
92
+ marketplaceStatusUpdate?: {
93
+ findMany(args: unknown): Promise<unknown[]>;
94
+ create(args: unknown): Promise<unknown>;
95
+ updateMany(args: unknown): Promise<{ count: number }>;
96
+ };
84
97
  }
85
98
 
86
99
  /**
@@ -226,6 +239,29 @@ export interface MarketplaceOrderPort {
226
239
  * marketplace's: a person finishes it there, through the adapter's app link.
227
240
  */
228
241
  onCancellationFailed?(clientId: string, orderId: string, reason: CancellationFailureReason): Promise<void>;
242
+ /**
243
+ * OPTIONAL. The marketplace announced a step of an order the engine holds
244
+ * (`DISPATCHED`, `CONCLUDED`), the connection follows the marketplace's
245
+ * status, and the order is ACCEPTED with no cancellation request standing.
246
+ * Move the order FORWARD to the step if it is not there yet, and never
247
+ * otherwise: answer `unchanged` for an order already there or past it, or
248
+ * one that has no such step. Idempotent by forward-only: a hook that throws
249
+ * leaves the inbox row FAILED and the reconcile pass runs it again. Absent:
250
+ * every lifecycle event is understood and ignored, as before FUT-4653.
251
+ */
252
+ onLifecycle?(
253
+ clientId: string,
254
+ orderId: string,
255
+ event: NormalizedEvent,
256
+ facts: MarketplaceLifecycleFacts,
257
+ ): Promise<MarketplaceLifecycleAnswer>;
258
+ /**
259
+ * OPTIONAL. Does the order still hold this step: the card is at it or past
260
+ * it, not canceled or failed. Asked by the status job right before it tells
261
+ * the marketplace, so a step the store undid in the meantime is never sent.
262
+ * Absent: the engine cannot tell, and sends nothing.
263
+ */
264
+ statusHolds?(clientId: string, orderId: string, step: StatusStep): Promise<boolean>;
229
265
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
230
266
  summarize(
231
267
  clientId: string,
@@ -253,7 +289,7 @@ export interface MarketplaceEnqueuePort {
253
289
  enqueue(
254
290
  name: string,
255
291
  payload: unknown,
256
- options?: { dedupeKey?: string },
292
+ options?: { dedupeKey?: string; delayMs?: number },
257
293
  ): Promise<{ enqueued: boolean; reason?: string }>;
258
294
  }
259
295
 
@@ -0,0 +1,51 @@
1
+ import type { StatusStep } from "./adapter";
2
+ import { MARKETPLACE_OUTBOUND_JOB, statusDedupeKey } from "./outbound-queue";
3
+ import type { EngineContext } from "./ports";
4
+
5
+ /** What the host says when an order reaches a step (FUT-4653). */
6
+ export interface InformStatusInput {
7
+ clientId: string;
8
+ /** The host's order id. */
9
+ orderId: string;
10
+ step: StatusStep;
11
+ /**
12
+ * The instant of the move (the card's own timestamp), which makes the job's
13
+ * key: a re-dispatch after an undo is another instant, and a queue keeps a
14
+ * finished job's id and would swallow the same key.
15
+ */
16
+ at: Date;
17
+ /** OPTIONAL. Run the job this much later: the board's undo window for a dispatch. */
18
+ delayMs?: number;
19
+ }
20
+
21
+ /**
22
+ * One enqueue and nothing else: no statement, no call to a marketplace, no
23
+ * provider lookup (the host knows the order is a marketplace's, not whose).
24
+ * The job asks the adapter whether it takes the step. A refused or throwing
25
+ * queue is logged and answers false; nothing owed is recorded, so nothing is
26
+ * re-queued (no row exists before the job, and writing one in the host's tap
27
+ * would cost a statement on every move).
28
+ */
29
+ export async function informStatus(ctx: EngineContext, input: InformStatusInput): Promise<boolean> {
30
+ const payload = { clientId: input.clientId, orderId: input.orderId, action: "status" as const, step: input.step, claimKey: String(input.at.getTime()) };
31
+ const options = {
32
+ dedupeKey: statusDedupeKey(input.step, input.orderId, input.at),
33
+ ...(input.delayMs === undefined ? {} : { delayMs: input.delayMs }),
34
+ };
35
+ try {
36
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);
37
+ if (!outcome.enqueued) {
38
+ ctx.ports.logger.warn(
39
+ `${MARKETPLACE_OUTBOUND_JOB}: status ${input.step} for order ${input.orderId} was not queued` +
40
+ (outcome.reason ? ` (${outcome.reason})` : ""),
41
+ );
42
+ }
43
+ return outcome.enqueued;
44
+ } catch (error) {
45
+ ctx.ports.logger.warn(
46
+ `${MARKETPLACE_OUTBOUND_JOB}: status ${input.step} for order ${input.orderId} was not queued: ` +
47
+ (error instanceof Error ? error.message : String(error)),
48
+ );
49
+ return false;
50
+ }
51
+ }
@@ -0,0 +1,207 @@
1
+ import type { MarketplaceAdapter, OutboundOrderRef, OutboundResult, StatusStep } from "./adapter";
2
+ import { readOutboundConnection, type OutboundConnection } from "./integration";
3
+ import { MARKETPLACE_OUTBOUND_JOB, type OutboundJobPayload } from "./outbound-queue";
4
+ import type { EngineContext, MarketplaceDb } from "./ports";
5
+ import { insertStatusRow, readStatusRows, settleStatusRow, statusTable, type StatusRow } from "./status-store";
6
+ import type { MarketplaceDeliveredBy } from "./types";
7
+
8
+ /**
9
+ * The status job's body (FUT-4653), `marketplace.outbound` with action
10
+ * `status`: tell the marketplace the order reached a step.
11
+ *
12
+ * In order, stopping at the first rule that fails, with no row and no call:
13
+ *
14
+ * 1. the acceptance is ACCEPTED and no cancellation request stands;
15
+ * 2. the adapter states the step and takes it for this kind of order;
16
+ * 3. the host says the order still holds the step (a dispatch undone inside
17
+ * the board's undo window sends nothing);
18
+ * 4. no row exists for (order, step), and the marketplace has not CONCLUDED
19
+ * the order (a step it announced itself is in the same table);
20
+ * 5. claim: insert the row (STORE, SENDING), unique on (order, step); a lost
21
+ * claim stops the run;
22
+ * 6. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
23
+ * retried; 408/425/429/5xx/timeout retried, the last attempt FAILED. A run
24
+ * on a SENDING row it owns (a retry, or the sweep's re-queue) calls again.
25
+ *
26
+ * Nothing here touches the order: a failed, refused or lost status call
27
+ * changes nothing in the host.
28
+ */
29
+
30
+ /** What the job reads of the acceptance row. */
31
+ interface StatusJobRow {
32
+ orderId: string;
33
+ provider: string;
34
+ status: string;
35
+ cancellationStatus: string | null;
36
+ deliveredBy: string | null;
37
+ }
38
+
39
+ /** What one run did, in the outbound job's own shape. */
40
+ type StatusJobOutcome =
41
+ | { kind: "skipped"; reason: string }
42
+ | { kind: "done"; action: "status" }
43
+ | { kind: "failed"; action: "status"; reason: string };
44
+
45
+ interface StatusJobDeps {
46
+ attempt: { attempt: number; maxAttempts: number };
47
+ ref: OutboundOrderRef;
48
+ retryError: (message: string) => Error;
49
+ }
50
+
51
+ function deliveredByOf(row: StatusJobRow): MarketplaceDeliveredBy | null {
52
+ return row.deliveredBy === "MERCHANT" || row.deliveredBy === "MARKETPLACE" ? row.deliveredBy : null;
53
+ }
54
+
55
+ const skipped = (reason: string): StatusJobOutcome => ({ kind: "skipped", reason });
56
+
57
+ /** Why rule 1 stops the job, or null. */
58
+ function acceptanceSkip(row: StatusJobRow): string | null {
59
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
60
+ const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
61
+ return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
62
+ }
63
+
64
+ /** Why rules 2 and 3 stop the job, or null. Rule 3 asks the host, so it comes last. */
65
+ async function adapterAndHostSkip(
66
+ ctx: EngineContext,
67
+ payload: OutboundJobPayload,
68
+ step: StatusStep,
69
+ row: StatusJobRow,
70
+ adapter: MarketplaceAdapter,
71
+ ): Promise<string | null> {
72
+ const takes =
73
+ adapter.informStatus !== undefined &&
74
+ adapter.capabilities.statusSteps?.includes(step) === true &&
75
+ adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
76
+ if (!takes) return `the marketplace does not take ${step} for this order`;
77
+ const holds = ctx.ports.order.statusHolds;
78
+ if (!holds) return "the host binds no statusHolds, so it cannot say the order still holds the step";
79
+ return (await holds.call(ctx.ports.order, payload.clientId, row.orderId, step)) ? null : `the order no longer holds ${step}`;
80
+ }
81
+
82
+ /** The opened connection, or why the store has none (disconnected, no secrets, secrets that do not open). */
83
+ async function connectionOf(ctx: EngineContext, clientId: string, provider: string): Promise<OutboundConnection | string> {
84
+ try {
85
+ return (await readOutboundConnection(ctx, clientId, provider)) ?? "no credentials on file";
86
+ } catch (error) {
87
+ return `credentials do not open: ${error instanceof Error ? error.message : String(error)}`;
88
+ }
89
+ }
90
+
91
+ /** Call the adapter with the opened connection. */
92
+ function callAdapter(
93
+ ctx: EngineContext,
94
+ connection: OutboundConnection,
95
+ adapter: MarketplaceAdapter,
96
+ row: StatusJobRow,
97
+ step: StatusStep,
98
+ ref: OutboundOrderRef,
99
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
100
+ const now = ctx.ports.clock.now();
101
+ return adapter.informStatus!({ http: ctx.ports.http, tokens: ctx.tokens, now, ...connection }, ref, {
102
+ step,
103
+ deliveredBy: deliveredByOf(row),
104
+ });
105
+ }
106
+
107
+ /** Stamp the answer; a retry throws until the last attempt. */
108
+ async function settle(
109
+ ctx: EngineContext,
110
+ db: MarketplaceDb,
111
+ where: { orderId: string; step: StatusStep; claimKey: string },
112
+ result: OutboundResult | { kind: "unsupported" },
113
+ deps: StatusJobDeps,
114
+ ): Promise<StatusJobOutcome> {
115
+ const table = statusTable(db)!;
116
+ if (result.kind === "accepted") {
117
+ await settleStatusRow(table, where, "SENT");
118
+ return { kind: "done", action: "status" };
119
+ }
120
+ const reason =
121
+ result.kind === "refused"
122
+ ? `refused ${result.status}: ${result.message}`
123
+ : result.kind === "retry"
124
+ ? result.reason
125
+ : "the adapter answered unsupported after the claim";
126
+ if (result.kind === "retry" && deps.attempt.attempt < deps.attempt.maxAttempts) {
127
+ throw deps.retryError(`status ${where.step} for order ${where.orderId}: ${reason}`);
128
+ }
129
+ await settleStatusRow(table, where, "FAILED");
130
+ ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
131
+ return { kind: "failed", action: "status", reason };
132
+ }
133
+
134
+ /** Whether a row is a SENDING claim of the run holding `key`. */
135
+ function ownsClaim(found: StatusRow, key: string): boolean {
136
+ return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
137
+ }
138
+
139
+ /**
140
+ * Rules 4 and 5: why the step is not ours to send (a row stands, or the
141
+ * marketplace concluded, or the claim was lost), or null once the row is ours.
142
+ */
143
+ async function claim(
144
+ table: NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>,
145
+ payload: OutboundJobPayload,
146
+ row: StatusJobRow,
147
+ step: StatusStep,
148
+ key: string,
149
+ ): Promise<string | null> {
150
+ const rows = await readStatusRows(table, row.orderId, [step, "CONCLUDED"]);
151
+ if (rows.some((found) => found.step === "CONCLUDED" && found.source === "MARKETPLACE")) {
152
+ return "the marketplace concluded this order";
153
+ }
154
+ const own = rows.find((found) => found.step === step);
155
+ // A SENDING row under THIS job's key is its own retry (or the sweep's re-claim of it): it
156
+ // calls again. Under any other key another move's job holds it, and sends nothing.
157
+ if (own) return ownsClaim(own, key) ? null : `${step} is already ${own.state}${own.state === "SENDING" ? ", held by another run" : ""}`;
158
+ const claimed = await insertStatusRow(table, {
159
+ clientId: payload.clientId,
160
+ orderId: row.orderId,
161
+ provider: row.provider,
162
+ step,
163
+ source: "STORE",
164
+ state: "SENDING",
165
+ claimKey: key,
166
+ });
167
+ return claimed ? null : `another run holds the claim on ${step}`;
168
+ }
169
+
170
+ /** Run one status job. `row` is the acceptance the outbound job already read. */
171
+ export async function runStatus(
172
+ ctx: EngineContext,
173
+ payload: OutboundJobPayload,
174
+ row: StatusJobRow,
175
+ adapter: MarketplaceAdapter,
176
+ deps: StatusJobDeps,
177
+ ): Promise<StatusJobOutcome> {
178
+ const step = payload.step;
179
+ if (!step) return skipped("a status call names no step");
180
+ const stopped = acceptanceSkip(row) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
181
+ if (stopped) return skipped(stopped);
182
+ const db = await ctx.ports.db();
183
+ const table = statusTable(db);
184
+ if (!table) return skipped("the host has not composed the status model");
185
+
186
+ // A store with no connection, or secrets that do not open, is not a failure of this step: it
187
+ // is asked before the claim so no row is left behind, and said at info (a disconnected store
188
+ // would otherwise log an error on every move).
189
+ const connection = await connectionOf(ctx, payload.clientId, row.provider);
190
+ if (typeof connection === "string") {
191
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: status ${step} for order ${row.orderId} not sent: ${connection}`);
192
+ return skipped(connection);
193
+ }
194
+ const key = payload.claimKey ?? "";
195
+ const unclaimed = await claim(table, payload, row, step, key);
196
+ if (unclaimed) return skipped(unclaimed);
197
+ const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
198
+ return settle(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
199
+ }
200
+
201
+ /** The last attempt died without an answer: FAILED, never left SENDING. Best-effort. */
202
+ export async function failStatusRow(ctx: EngineContext, payload: OutboundJobPayload): Promise<void> {
203
+ const table = statusTable(await ctx.ports.db());
204
+ if (table && payload.step) {
205
+ await settleStatusRow(table, { orderId: payload.orderId, step: payload.step, claimKey: payload.claimKey ?? "" }, "FAILED");
206
+ }
207
+ }
@@ -0,0 +1,85 @@
1
+ import type { StatusStep } from "./adapter";
2
+ import type { EngineContext, MarketplaceDb } from "./ports";
3
+ import type { MarketplaceLifecycle } from "./types";
4
+
5
+ /**
6
+ * The engine's memory of what was said about an order's steps, in
7
+ * `marketplace_status_updates` (FUT-4653): one row per (order, step), so the
8
+ * same row is the claim that keeps a step from being sent twice, the marker an
9
+ * inbound echo is recognised by, and the note of what the marketplace itself
10
+ * announced. Every function here is a statement or two, never a call out.
11
+ */
12
+
13
+ /** A step as the table holds it: the three the store informs, and the one only a marketplace announces. */
14
+ export type StatusRowStep = StatusStep | MarketplaceLifecycle;
15
+
16
+ /** Where a row stands. */
17
+ export type StatusRowState = "SENDING" | "SENT" | "FAILED" | "NOTED";
18
+
19
+ /** One row, as the engine reads it. */
20
+ export interface StatusRow {
21
+ orderId: string;
22
+ step: StatusRowStep;
23
+ source: "STORE" | "MARKETPLACE";
24
+ state: StatusRowState;
25
+ /** Which run holds a SENDING claim. */
26
+ claimKey: string;
27
+ }
28
+
29
+ type StatusTable = NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>;
30
+
31
+ /** The status delegate, or null on a host that has not composed the model: the paths that need it then do nothing. */
32
+ export function statusTable(db: MarketplaceDb): StatusTable | null {
33
+ return db.marketplaceStatusUpdate ?? null;
34
+ }
35
+
36
+ /** Every row of an order for these steps, in one read. */
37
+ export async function readStatusRows(
38
+ table: StatusTable,
39
+ orderId: string,
40
+ steps: readonly StatusRowStep[],
41
+ ): Promise<StatusRow[]> {
42
+ return (await table.findMany({
43
+ where: { orderId, step: { in: [...steps] } },
44
+ select: { orderId: true, step: true, source: true, state: true, claimKey: true },
45
+ })) as StatusRow[];
46
+ }
47
+
48
+ /**
49
+ * Insert one row. False when the (order, step) row already exists: the unique
50
+ * is the guard and losing it is an answer, not a failure.
51
+ */
52
+ export async function insertStatusRow(
53
+ table: StatusTable,
54
+ row: { clientId: string; orderId: string; provider: string; step: StatusRowStep; source: StatusRow["source"]; state: StatusRowState; claimKey: string },
55
+ ): Promise<boolean> {
56
+ try {
57
+ await table.create({ data: row });
58
+ return true;
59
+ } catch (error) {
60
+ if ((error as { code?: string }).code === "P2002") return false;
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ /** Remember a step the marketplace announced, so our own job never informs it back. */
66
+ export async function noteMarketplaceStep(
67
+ ctx: EngineContext,
68
+ row: { clientId: string; orderId: string; provider: string; step: MarketplaceLifecycle },
69
+ ): Promise<void> {
70
+ const table = statusTable(await ctx.ports.db());
71
+ if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
72
+ }
73
+
74
+ /**
75
+ * Move a row this run owns from SENDING to its answer; predicated on the state
76
+ * AND the run's claim key, so a settled row is never rewritten and a row
77
+ * another run holds is never settled by this one.
78
+ */
79
+ export async function settleStatusRow(
80
+ table: StatusTable,
81
+ where: { orderId: string; step: StatusRowStep; claimKey: string },
82
+ state: "SENT" | "FAILED",
83
+ ): Promise<number> {
84
+ return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
85
+ }
package/src/core/types.ts CHANGED
@@ -136,6 +136,14 @@ export interface NormalizedMarketplaceOrder {
136
136
  */
137
137
  export type CancellationOutcome = "CONFIRMED" | "FAILED";
138
138
 
139
+ /**
140
+ * A step of the order's life a marketplace announces about an order it
141
+ * already has (FUT-4653): the courier left (`DISPATCHED`) or the order is
142
+ * finished (`CONCLUDED`). An event that names one moves nothing by itself; the
143
+ * engine asks the host to move the order forward (`onLifecycle`).
144
+ */
145
+ export type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
146
+
139
147
  /** What an adapter makes of one inbound delivery. */
140
148
  export interface NormalizedEvent {
141
149
  provider: MarketplaceProvider;
@@ -167,4 +175,10 @@ export interface NormalizedEvent {
167
175
  * the event. Ignored when `order` is present.
168
176
  */
169
177
  orderToFetch?: boolean;
178
+ /**
179
+ * OPTIONAL. The lifecycle step this event announces about an order the
180
+ * engine already has. Absent or null: the event names none. An event that
181
+ * names one carries no order body.
182
+ */
183
+ lifecycle?: MarketplaceLifecycle | null;
170
184
  }
@@ -3,7 +3,7 @@ import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
6
- import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from "./outbound";
6
+ import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
7
7
  import { IFOOD_AVAILABILITY } from "./pause";
8
8
 
9
9
  /**
@@ -60,6 +60,10 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
60
60
  // request in seconds when it answers at all, so 5 minutes is generous.
61
61
  // A host overrides it with the engine's `cancellationWindowMs`.
62
62
  cancellationAnswerWindowMs: IFOOD_CANCELLATION_ANSWER_WINDOW_MS,
63
+ // Told what iFood has an endpoint for (ESTIMATED, see `./outbound.ts`): ready for
64
+ // pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
65
+ // CONCLUDED is that.
66
+ statusSteps: ["READY", "DISPATCHED"],
63
67
  },
64
68
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
65
69
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
@@ -71,6 +75,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
71
75
  catalogueReader: IFOOD_CATALOGUE_READER,
72
76
  confirm: (ctx, order) => ifoodConfirm(ctx, order),
73
77
  requestCancellation: ifoodRequestCancellation,
78
+ statusSupported: ifoodStatusSupported,
79
+ informStatus: ifoodInformStatus,
74
80
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
75
81
  availability: IFOOD_AVAILABILITY,
76
82
  // No per-order deep link is known, so the portal, where a live order is
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ MarketplaceLifecycle,
2
3
  MarketplaceDeliveredBy,
3
4
  MarketplaceDiscountSponsor,
4
5
  MarketplaceOrderType,
@@ -39,6 +40,21 @@ const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
39
40
  /** iFood refused the store's own cancellation request. */
40
41
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
41
42
 
43
+ /**
44
+ * The lifecycle events (FUT-4653): the order left (`DSP`) and the order is
45
+ * finished (`CON`). ESTIMATED: iFood's portal refused our reader (Cloudflare
46
+ * 403, https://developer.ifood.com.br, 2026-11-25), so these codes and their
47
+ * long forms are the ones iFood's event stream is commonly documented with,
48
+ * not read off a page. They sit here beside the sets above so homologation
49
+ * corrects one place.
50
+ */
51
+ const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = {
52
+ DSP: "DISPATCHED",
53
+ DISPATCHED: "DISPATCHED",
54
+ CON: "CONCLUDED",
55
+ CONCLUDED: "CONCLUDED",
56
+ };
57
+
42
58
  /**
43
59
  * Verify a delivery against the merchant's webhook secret: iFood signs the raw
44
60
  * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one
@@ -257,5 +273,6 @@ export function normalizeIfoodEvent(
257
273
  order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
258
274
  cancelled,
259
275
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
276
+ ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
260
277
  };
261
278
  }
@@ -6,6 +6,7 @@ import {
6
6
  type CancellationRequestInput,
7
7
  type OutboundOrderRef,
8
8
  type OutboundResult,
9
+ type StatusFacts,
9
10
  } from "../core/adapter";
10
11
 
11
12
  /**
@@ -114,3 +115,37 @@ export function ifoodRequestCancellation(
114
115
  cancellationCode: input.reason.code,
115
116
  });
116
117
  }
118
+
119
+ /**
120
+ * What iFood is told, per step (FUT-4653). ESTIMATED, every row: iFood's
121
+ * developer portal answered 403 behind Cloudflare to our reader
122
+ * (https://developer.ifood.com.br, 2026-11-25), so the endpoint names below are
123
+ * the Merchant API's commonly documented ones (`order/v1.0`), not read off a
124
+ * page.
125
+ *
126
+ * - READY: `POST /orders/{id}/readyToPickup`, for a take-out, and ESTIMATED
127
+ * whether iFood takes it for its own fleet; not for a bag the merchant
128
+ * delivers, which is dispatched, not made ready for pickup.
129
+ * - DISPATCHED: `POST /orders/{id}/dispatch`, only for `deliveredBy: MERCHANT`.
130
+ * - HANDED_OVER: none. iFood has no conclude endpoint for a merchant;
131
+ * CONCLUDED is iFood's own event.
132
+ */
133
+ const STATUS_ACTION: Readonly<Record<string, (facts: StatusFacts) => string | null>> = {
134
+ READY: (facts) => (facts.deliveredBy === "MERCHANT" ? null : "readyToPickup"),
135
+ DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? "dispatch" : null),
136
+ };
137
+
138
+ /** Whether iFood takes this step for this kind of order: answered offline. */
139
+ export function ifoodStatusSupported(facts: StatusFacts): boolean {
140
+ return STATUS_ACTION[facts.step]?.(facts) != null;
141
+ }
142
+
143
+ /** Tell iFood a step happened. `unsupported` when it has no endpoint for it. */
144
+ export async function ifoodInformStatus(
145
+ ctx: AdapterCallContext,
146
+ order: OutboundOrderRef,
147
+ facts: StatusFacts,
148
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
149
+ const action = STATUS_ACTION[facts.step]?.(facts) ?? null;
150
+ return action === null ? { kind: "unsupported" } : postOrder(ctx, order.externalOrderId, action);
151
+ }
package/src/index.ts CHANGED
@@ -38,6 +38,8 @@ export {
38
38
  type MarketplaceHttpRequest,
39
39
  type MarketplaceHttpResponse,
40
40
  type OutboundOrderRef,
41
+ type StatusFacts,
42
+ type StatusStep,
41
43
  type OutboundResult,
42
44
  } from "./core/adapter";
43
45
  export {
@@ -59,6 +61,8 @@ export type {
59
61
  MarketplaceDb,
60
62
  MarketplaceEngineConfig,
61
63
  MarketplaceEnqueuePort,
64
+ MarketplaceLifecycleAnswer,
65
+ MarketplaceLifecycleFacts,
62
66
  MarketplaceLogger,
63
67
  MarketplaceOrderPort,
64
68
  MarketplaceOrderSummary,
@@ -76,6 +80,7 @@ export {
76
80
  type MarketplaceProvider,
77
81
  type NormalizedAddress,
78
82
  type NormalizedBuyer,
83
+ type MarketplaceLifecycle,
79
84
  type NormalizedEvent,
80
85
  type NormalizedMarketplaceOrder,
81
86
  type NormalizedOrderDiscount,
@@ -127,6 +132,7 @@ export {
127
132
  type OutboundJobPayload,
128
133
  } from "./core/outbound-queue";
129
134
  export type { DeliveryOutcome } from "./core/pipeline";
135
+ export type { InformStatusInput } from "./core/status-inform";
130
136
  export {
131
137
  FetchOrderRetryError,
132
138
  MARKETPLACE_FETCH_ORDER_JOB,
@@ -7,7 +7,7 @@ import {
7
7
  verifyRappiSignature,
8
8
  type RappiAmountUnit,
9
9
  } from "./normalize";
10
- import { rappiReject, rappiTake, type RappiBaseUrls } from "./outbound";
10
+ import { rappiInformStatus, rappiReject, rappiStatusSupported, rappiTake, type RappiBaseUrls } from "./outbound";
11
11
  import { rappiAvailability } from "./pause";
12
12
 
13
13
  /**
@@ -148,6 +148,9 @@ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapt
148
148
  // `take/{cookingTime}`, in minutes.
149
149
  confirmTakesPreparationTime: true,
150
150
  cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,
151
+ // READY only, and ESTIMATED (see `./outbound.ts`). Rappi's normalizer maps no
152
+ // lifecycle event: its `event` values are undocumented (see `./normalize.ts`).
153
+ statusSteps: ["READY"],
151
154
  },
152
155
  normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),
153
156
  readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),
@@ -155,6 +158,8 @@ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapt
155
158
  cancellationReasons: () => reasons,
156
159
  confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),
157
160
  requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),
161
+ statusSupported: rappiStatusSupported,
162
+ informStatus: (ctx, order, facts) => rappiInformStatus(ctx, hosts, order, facts),
158
163
  appLink: () => config.portalUrl,
159
164
  ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),
160
165
  };
@@ -37,6 +37,12 @@ import type {
37
37
  * else is recorded and IGNORED: a missed cancellation is visible in the inbox,
38
38
  * a false one would cancel a live order.
39
39
  *
40
+ * Rappi maps NO lifecycle event (FUT-4653: no `lifecycle` on any event it
41
+ * normalizes). ESTIMATED: the `event` values of ORDER_OTHER_EVENT are
42
+ * undocumented (https://dev-portal.rappi.com/, read 2026-11-25), so nothing
43
+ * here can name "dispatched" or "concluded" without guessing; such an event
44
+ * stays IGNORED, as before.
45
+ *
40
46
  * Rappi payloads carry no event id, so the inbox key is derived from the
41
47
  * order and the event, deterministic so a redelivery collides on the inbox's
42
48
  * unique index.