@12-apps/marketplace 1.6.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 (74) 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 +38 -6
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-CCWMqt2g.d.ts → adapter-CYJzu1c9.d.ts} +81 -2
  7. package/dist/{chunk-4CJ7B5OR.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-NFZT5TWR.js → chunk-BMCERPQX.js} +214 -24
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-RGMSD7S7.js → chunk-HEXLCTOG.js} +7 -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-w2TgRrlc.d.ts → engine-wmW-VuBL.d.ts} +123 -9
  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 +66 -6
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +119 -12
  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 +23 -5
  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 +48 -4
  35. package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql +16 -0
  36. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  37. package/src/99food/index.ts +6 -0
  38. package/src/99food/normalize.ts +7 -1
  39. package/src/99food/outbound.ts +62 -2
  40. package/src/core/adapter.ts +58 -3
  41. package/src/core/bulk.ts +1 -1
  42. package/src/core/cancellation.ts +4 -1
  43. package/src/core/catalogue.ts +4 -3
  44. package/src/core/decisions.ts +3 -2
  45. package/src/core/engine.ts +9 -0
  46. package/src/core/fetch-order.ts +2 -2
  47. package/src/core/ingest.ts +6 -0
  48. package/src/core/integration.ts +17 -0
  49. package/src/core/lifecycle-port.ts +16 -0
  50. package/src/core/lifecycle.ts +133 -0
  51. package/src/core/order-fetch-marks.ts +13 -8
  52. package/src/core/outbound-queue.ts +24 -4
  53. package/src/core/outbound-sweep.ts +49 -5
  54. package/src/core/outbound.ts +26 -11
  55. package/src/core/pipeline.ts +35 -3
  56. package/src/core/ports.ts +54 -7
  57. package/src/core/state.ts +1 -1
  58. package/src/core/status-inform.ts +51 -0
  59. package/src/core/status-job.ts +207 -0
  60. package/src/core/status-store.ts +85 -0
  61. package/src/core/types.ts +39 -0
  62. package/src/ifood/index.ts +7 -1
  63. package/src/ifood/normalize.ts +70 -0
  64. package/src/ifood/outbound.ts +37 -1
  65. package/src/index.ts +9 -0
  66. package/src/rappi/index.ts +6 -1
  67. package/src/rappi/normalize.ts +6 -0
  68. package/src/rappi/outbound.ts +33 -3
  69. package/src/server/mcp.ts +2 -0
  70. package/src/server/webhook.ts +3 -1
  71. package/dist/chunk-4CJ7B5OR.js.map +0 -1
  72. package/dist/chunk-NFZT5TWR.js.map +0 -1
  73. package/dist/chunk-RGMSD7S7.js.map +0 -1
  74. package/dist/chunk-UYFYGGCS.js.map +0 -1
@@ -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
@@ -69,6 +69,18 @@ export type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
69
69
  /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
70
70
  export type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
71
71
 
72
+ /** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */
73
+ export type MarketplaceDiscountSponsor = "MERCHANT" | "MARKETPLACE" | "OTHER";
74
+
75
+ /** One discount on an order, as the part one sponsor pays. */
76
+ export interface NormalizedOrderDiscount {
77
+ /** The discount's value in the smallest currency unit. */
78
+ cents: number;
79
+ sponsor: MarketplaceDiscountSponsor;
80
+ /** What the marketplace called the campaign, when it says. */
81
+ name?: string;
82
+ }
83
+
72
84
  /** An incoming marketplace order, normalized. */
73
85
  export interface NormalizedMarketplaceOrder {
74
86
  provider: MarketplaceProvider;
@@ -96,6 +108,19 @@ export interface NormalizedMarketplaceOrder {
96
108
  deliveredBy?: MarketplaceDeliveredBy | null;
97
109
  /** Null on a take-out and when unstated. */
98
110
  deliveryAddress?: NormalizedAddress | null;
111
+ /**
112
+ * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency
113
+ * unit. 0 is a free delivery; null or absent is "did not say".
114
+ */
115
+ deliveryFeeCents?: number | null;
116
+ /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is "did not say". */
117
+ subtotalCents?: number | null;
118
+ /**
119
+ * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a
120
+ * host can tell what the store gave from what the marketplace paid for.
121
+ * Absent is "did not say"; an empty array is "no discount".
122
+ */
123
+ discounts?: NormalizedOrderDiscount[];
99
124
  /**
100
125
  * OPTIONAL. The merchant the order names, when its body says (Open
101
126
  * Delivery's `merchant.id`). A fetched order naming another merchant than
@@ -111,6 +136,14 @@ export interface NormalizedMarketplaceOrder {
111
136
  */
112
137
  export type CancellationOutcome = "CONFIRMED" | "FAILED";
113
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
+
114
147
  /** What an adapter makes of one inbound delivery. */
115
148
  export interface NormalizedEvent {
116
149
  provider: MarketplaceProvider;
@@ -142,4 +175,10 @@ export interface NormalizedEvent {
142
175
  * the event. Ignored when `order` is present.
143
176
  */
144
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;
145
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,10 +1,13 @@
1
1
  import type {
2
+ MarketplaceLifecycle,
2
3
  MarketplaceDeliveredBy,
4
+ MarketplaceDiscountSponsor,
3
5
  MarketplaceOrderType,
4
6
  NormalizedAddress,
5
7
  NormalizedBuyer,
6
8
  NormalizedEvent,
7
9
  NormalizedMarketplaceOrder,
10
+ NormalizedOrderDiscount,
8
11
  NormalizedOrderLine,
9
12
  } from "../core/types";
10
13
  import {
@@ -13,6 +16,7 @@ import {
13
16
  firstDate,
14
17
  firstString,
15
18
  pick,
19
+ toCents,
16
20
  verifyHmacSha256Hex,
17
21
  } from "../core/payload-read";
18
22
 
@@ -36,6 +40,21 @@ const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
36
40
  /** iFood refused the store's own cancellation request. */
37
41
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
38
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
+
39
58
  /**
40
59
  * Verify a delivery against the merchant's webhook secret: iFood signs the raw
41
60
  * body with HMAC-SHA256, hex. The rule (an unset secret accepts; a set one
@@ -112,6 +131,45 @@ function readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {
112
131
  return stated === "MERCHANT" ? "MERCHANT" : null;
113
132
  }
114
133
 
134
+ /**
135
+ * iFood's sponsor names as who pays. ESTIMATED: the names are the ones iFood's
136
+ * order-details guide documents for `benefits[].sponsorshipValues[].name`, but
137
+ * no recorded payload in this repo carries them; confirm against a real order
138
+ * (https://developer.ifood.com.br/en-US/docs/guides/order/details).
139
+ */
140
+ function sponsorOf(name: string | null): MarketplaceDiscountSponsor {
141
+ const stated = name?.toUpperCase();
142
+ if (stated === "IFOOD") return "MARKETPLACE";
143
+ return stated === "MERCHANT" ? "MERCHANT" : "OTHER";
144
+ }
145
+
146
+ /**
147
+ * The discounts on an order, one per sponsor's share of each benefit.
148
+ * ESTIMATED shape (see {@link sponsorOf}): `benefits[]` with a `value` and
149
+ * `sponsorshipValues[{ name, value, description? }]`. A benefit that names no
150
+ * sponsor is the whole `value` under OTHER; a share with no usable amount is
151
+ * skipped. Absent `benefits` is undefined ("did not say").
152
+ */
153
+ function readDiscounts(order: unknown): NormalizedOrderDiscount[] | undefined {
154
+ const benefits = pick(order, "benefits");
155
+ if (!Array.isArray(benefits)) return undefined;
156
+ return benefits.flatMap((benefit): NormalizedOrderDiscount[] => {
157
+ const shares = pick(benefit, "sponsorshipValues");
158
+ const parts = Array.isArray(shares)
159
+ ? shares.map((share) => ({
160
+ cents: toCents(pick(share, "value")),
161
+ sponsor: sponsorOf(firstString(share, [["name"]])),
162
+ name: firstString(share, [["description"]]),
163
+ }))
164
+ : [{ cents: toCents(pick(benefit, "value")), sponsor: "OTHER" as const, name: null }];
165
+ return parts.flatMap((part) =>
166
+ part.cents === null || part.cents <= 0
167
+ ? []
168
+ : [{ cents: part.cents, sponsor: part.sponsor, ...(part.name === null ? {} : { name: part.name }) }],
169
+ );
170
+ });
171
+ }
172
+
115
173
  /**
116
174
  * Where a delivery goes. The street is what a courier cannot find a door
117
175
  * without, so an address with none is none; a missing number reads as the
@@ -135,6 +193,11 @@ function readAddress(order: unknown, missingStreetNumber: string): NormalizedAdd
135
193
  };
136
194
  }
137
195
 
196
+ /** `{ key: value }` unless the value is undefined, so an unstated field is absent rather than `undefined`. */
197
+ function optional<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {
198
+ return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });
199
+ }
200
+
138
201
  /** The order body of a placed-order event, or null when it carries none. */
139
202
  function readOrder(
140
203
  payload: unknown,
@@ -168,6 +231,12 @@ function readOrder(
168
231
  orderType: readOrderType(order),
169
232
  deliveredBy: readDeliveredBy(order),
170
233
  deliveryAddress: readAddress(order, missingStreetNumber),
234
+ // ESTIMATED names (iFood's order-details guide: `total.deliveryFee`,
235
+ // `total.subTotal`, `benefits[]`). Fee and subtotal are null when unstated,
236
+ // never 0; `discounts` is absent when `benefits` is.
237
+ deliveryFeeCents: firstCents(order, [["total", "deliveryFee"]]),
238
+ subtotalCents: firstCents(order, [["total", "subTotal"]]),
239
+ ...optional("discounts", readDiscounts(order)),
171
240
  };
172
241
  }
173
242
 
@@ -204,5 +273,6 @@ export function normalizeIfoodEvent(
204
273
  order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
205
274
  cancelled,
206
275
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
276
+ ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
207
277
  };
208
278
  }
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  answered,
3
3
  outboundResultOf,
4
+ tokenGrantResultOf,
4
5
  type AdapterCallContext,
5
6
  type CancellationRequestInput,
6
7
  type OutboundOrderRef,
7
8
  type OutboundResult,
9
+ type StatusFacts,
8
10
  } from "../core/adapter";
9
11
 
10
12
  /**
@@ -70,7 +72,7 @@ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string }
70
72
  clientSecret: ctx.credentials.clientSecret,
71
73
  }).toString(),
72
74
  });
73
- if (response.status < 200 || response.status >= 300) return outboundResultOf(response);
75
+ if (response.status < 200 || response.status >= 300) return tokenGrantResultOf(response);
74
76
  const token = tokenOf(response.body);
75
77
  if (!token) return { kind: "retry", reason: "iFood answered the token grant without a token" };
76
78
  ctx.tokens.set(key, { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
@@ -113,3 +115,37 @@ export function ifoodRequestCancellation(
113
115
  cancellationCode: input.reason.code,
114
116
  });
115
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
@@ -25,6 +25,7 @@ export { stableUuid } from "./core/catalogue-ids";
25
25
  export {
26
26
  answered,
27
27
  outboundResultOf,
28
+ tokenGrantResultOf,
28
29
  type AdapterCallContext,
29
30
  type AdapterTokenCache,
30
31
  type CancellationReason,
@@ -37,6 +38,8 @@ export {
37
38
  type MarketplaceHttpRequest,
38
39
  type MarketplaceHttpResponse,
39
40
  type OutboundOrderRef,
41
+ type StatusFacts,
42
+ type StatusStep,
40
43
  type OutboundResult,
41
44
  } from "./core/adapter";
42
45
  export {
@@ -58,6 +61,8 @@ export type {
58
61
  MarketplaceDb,
59
62
  MarketplaceEngineConfig,
60
63
  MarketplaceEnqueuePort,
64
+ MarketplaceLifecycleAnswer,
65
+ MarketplaceLifecycleFacts,
61
66
  MarketplaceLogger,
62
67
  MarketplaceOrderPort,
63
68
  MarketplaceOrderSummary,
@@ -70,12 +75,15 @@ export {
70
75
  PROVIDER_ID_PATTERN,
71
76
  type CancellationOutcome,
72
77
  type MarketplaceDeliveredBy,
78
+ type MarketplaceDiscountSponsor,
73
79
  type MarketplaceOrderType,
74
80
  type MarketplaceProvider,
75
81
  type NormalizedAddress,
76
82
  type NormalizedBuyer,
83
+ type MarketplaceLifecycle,
77
84
  type NormalizedEvent,
78
85
  type NormalizedMarketplaceOrder,
86
+ type NormalizedOrderDiscount,
79
87
  type NormalizedOrderLine,
80
88
  } from "./core/types";
81
89
  export type {
@@ -124,6 +132,7 @@ export {
124
132
  type OutboundJobPayload,
125
133
  } from "./core/outbound-queue";
126
134
  export type { DeliveryOutcome } from "./core/pipeline";
135
+ export type { InformStatusInput } from "./core/status-inform";
127
136
  export {
128
137
  FetchOrderRetryError,
129
138
  MARKETPLACE_FETCH_ORDER_JOB,