@12-apps/marketplace 1.13.0 → 1.15.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 (72) hide show
  1. package/ADOPTING.md +258 -3
  2. package/README.md +27 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +3 -3
  5. package/dist/{adapter-CQ4QiZPi.d.ts → adapter-CjVdMhZ2.d.ts} +177 -4
  6. package/dist/{chunk-CEWTV2TC.js → chunk-B4DYPQFE.js} +657 -251
  7. package/dist/chunk-B4DYPQFE.js.map +1 -0
  8. package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
  9. package/dist/chunk-BTKVZAJI.js.map +1 -0
  10. package/dist/{chunk-BD7DS3XM.js → chunk-E4XJXHUK.js} +20 -1
  11. package/dist/chunk-E4XJXHUK.js.map +1 -0
  12. package/dist/{chunk-W57TITU4.js → chunk-FQI56NGC.js} +53 -6
  13. package/dist/chunk-FQI56NGC.js.map +1 -0
  14. package/dist/chunk-H2VQRD3B.js +16 -0
  15. package/dist/chunk-H2VQRD3B.js.map +1 -0
  16. package/dist/{chunk-NFJQQWG4.js → chunk-TRUK5ZBE.js} +12 -4
  17. package/dist/chunk-TRUK5ZBE.js.map +1 -0
  18. package/dist/{client-CCSnylou.d.ts → client-DgzCkl8u.d.ts} +1 -1
  19. package/dist/{engine-1KlJ_8jK.d.ts → engine-BSLdhAGC.d.ts} +134 -3
  20. package/dist/hono/index.d.ts +2 -2
  21. package/dist/hono/index.js +3 -2
  22. package/dist/hono/index.js.map +1 -1
  23. package/dist/ifood/index.d.ts +13 -3
  24. package/dist/ifood/index.js +219 -29
  25. package/dist/ifood/index.js.map +1 -1
  26. package/dist/index.d.ts +29 -5
  27. package/dist/index.js +59 -7
  28. package/dist/index.js.map +1 -1
  29. package/dist/keeta/index.d.ts +2 -2
  30. package/dist/keeta/index.js +3 -3
  31. package/dist/manifest/server.d.ts +4 -2
  32. package/dist/manifest/server.js +3 -2
  33. package/dist/manifest/server.js.map +1 -1
  34. package/dist/rappi/index.d.ts +1 -1
  35. package/dist/rappi/index.js +2 -2
  36. package/dist/server/index.d.ts +14 -5
  37. package/dist/server/index.js +3 -2
  38. package/package.json +1 -1
  39. package/prisma/marketplace.prisma +17 -3
  40. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  41. package/src/core/acceptance.ts +12 -6
  42. package/src/core/acknowledge.ts +189 -0
  43. package/src/core/adapter.ts +74 -1
  44. package/src/core/cancellation.ts +10 -6
  45. package/src/core/conformity.ts +63 -0
  46. package/src/core/engine.ts +3 -2
  47. package/src/core/ingest.ts +7 -0
  48. package/src/core/link-store.ts +2 -4
  49. package/src/core/marketplace-confirmed.ts +229 -0
  50. package/src/core/order-reasons.ts +119 -0
  51. package/src/core/order-types.ts +8 -0
  52. package/src/core/outbound.ts +5 -1
  53. package/src/core/payload-read.ts +24 -0
  54. package/src/core/pipeline.ts +27 -1
  55. package/src/core/ports.ts +2 -0
  56. package/src/core/registry.ts +28 -2
  57. package/src/core/state.ts +10 -0
  58. package/src/core/status-job.ts +86 -3
  59. package/src/core/types.ts +117 -2
  60. package/src/ifood/index.ts +27 -4
  61. package/src/ifood/normalize.ts +38 -5
  62. package/src/ifood/order-details.ts +120 -0
  63. package/src/ifood/outbound.ts +131 -27
  64. package/src/index.ts +24 -0
  65. package/src/open-delivery/normalize.ts +9 -0
  66. package/src/server/jobs.ts +57 -4
  67. package/src/server/webhook.ts +27 -4
  68. package/dist/chunk-4J2KJ3ZW.js.map +0 -1
  69. package/dist/chunk-BD7DS3XM.js.map +0 -1
  70. package/dist/chunk-CEWTV2TC.js.map +0 -1
  71. package/dist/chunk-NFJQQWG4.js.map +0 -1
  72. package/dist/chunk-W57TITU4.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import type { CancellationReason, MarketplaceAdapter } from "./adapter";
1
+ import type { CancellationReason, MarketplaceAdapter, OrderCancellationReason } from "./adapter";
2
2
  import { PROVIDER_ID_PATTERN, type MarketplaceProvider } from "./types";
3
3
 
4
4
  /**
@@ -75,6 +75,30 @@ export function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]):
75
75
  };
76
76
  }
77
77
 
78
+ /** The stored list, read defensively: anything that is not a list of codes is "not read". */
79
+ export function storedReasons(value: unknown): OrderCancellationReason[] | null {
80
+ // An empty list is "not read": every refusal would be refused, so the static list applies.
81
+ if (!Array.isArray(value) || value.length === 0) return null;
82
+ return value.flatMap((entry: unknown) => {
83
+ const { code, description } = (entry ?? {}) as { code?: unknown; description?: unknown };
84
+ return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
85
+ });
86
+ }
87
+
88
+ /**
89
+ * The reasons an order may be refused or cancelled with: its own list when it
90
+ * was read (each labelled by the adapter's pack when the pack names the code,
91
+ * else by the marketplace's own words), else the adapter's static list.
92
+ */
93
+ export function reasonsForOrder(adapter: MarketplaceAdapter, stored: unknown): readonly CancellationReason[] {
94
+ const own = storedReasons(stored);
95
+ if (own === null) return adapter.cancellationReasons();
96
+ const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
97
+ return own.map(
98
+ (reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false },
99
+ );
100
+ }
101
+
78
102
  /**
79
103
  * The reason a refusal carries: the one named by `code`, or — when the store
80
104
  * named none — the adapter's first. `null` when the code is not one of the
@@ -83,8 +107,10 @@ export function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]):
83
107
  export function resolveReason(
84
108
  adapter: MarketplaceAdapter,
85
109
  code: string | null | undefined,
110
+ /** The order's own list (`cancellation_reasons`, FUT-5984); absent or unread: the static one. */
111
+ stored?: unknown,
86
112
  ): CancellationReason | null {
87
- const reasons = adapter.cancellationReasons();
113
+ const reasons = reasonsForOrder(adapter, stored);
88
114
  if (code === null || code === undefined) return reasons[0] ?? null;
89
115
  return reasons.find((reason) => reason.code === code) ?? null;
90
116
  }
package/src/core/state.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
+ import type { CancellationReason } from "./adapter";
2
3
  import type { CancellationFailureReason, EngineContext } from "./ports";
4
+ import { reasonsForOrder, storedReasons } from "./registry";
3
5
  import type { MarketplaceProvider } from "./types";
4
6
 
5
7
  /**
@@ -21,6 +23,11 @@ export interface MarketplaceOrderState {
21
23
  cancellationFailure: CancellationFailureReason | null;
22
24
  /** The adapter's app link, or null when no adapter is registered for it. */
23
25
  appUrl: string | null;
26
+ /**
27
+ * This order's own reasons, read from the marketplace (FUT-5984); null while
28
+ * or when they were not read: the adapter's static `reasons(provider)` then.
29
+ */
30
+ cancellationReasons: readonly CancellationReason[] | null;
24
31
  }
25
32
 
26
33
  interface StateRow {
@@ -34,6 +41,7 @@ interface StateRow {
34
41
  cancellationStatus: string | null;
35
42
  cancellationReasonCode: string | null;
36
43
  cancellationFailureReason: string | null;
44
+ cancellationReasons: unknown;
37
45
  }
38
46
 
39
47
  /** The state of each of these orders that is a marketplace order, keyed by id. */
@@ -57,6 +65,7 @@ export async function readOrderStates(
57
65
  cancellationStatus: true,
58
66
  cancellationReasonCode: true,
59
67
  cancellationFailureReason: true,
68
+ cancellationReasons: true,
60
69
  },
61
70
  })) as StateRow[];
62
71
  return new Map(
@@ -74,6 +83,7 @@ export async function readOrderStates(
74
83
  cancellationReasonCode: row.cancellationReasonCode,
75
84
  cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,
76
85
  appUrl: adapter ? adapter.appLink(row) : null,
86
+ cancellationReasons: adapter && storedReasons(row.cancellationReasons) !== null ? reasonsForOrder(adapter, row.cancellationReasons) : null,
77
87
  };
78
88
  return [row.orderId, state];
79
89
  }),
@@ -11,7 +11,11 @@ import type { MarketplaceDeliveredBy } from "./types";
11
11
  *
12
12
  * In order, stopping at the first rule that fails, with no row and no call:
13
13
  *
14
- * 1. the acceptance is ACCEPTED and no cancellation request stands;
14
+ * 1. the acceptance is ACCEPTED and no cancellation request stands, and the
15
+ * marketplace took the store's confirm (`confirmedAt`, FUT-5673), for a
16
+ * marketplace that states `statusAfterConfirm` (iFood): while the confirm
17
+ * is still owed the job is retried, and once it failed (`confirmFailedAt`)
18
+ * or on the last attempt it is skipped; any other marketplace never waits;
15
19
  * 2. the adapter states the step and takes it for this kind of order;
16
20
  * 3. the host says the order still holds the step (a dispatch undone inside
17
21
  * the board's undo window sends nothing);
@@ -19,7 +23,12 @@ import type { MarketplaceDeliveredBy } from "./types";
19
23
  * the order (a step it announced itself is in the same table);
20
24
  * 5. claim: insert the row (STORE, SENDING), unique on (order, step); a lost
21
25
  * claim stops the run;
22
- * 6. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
26
+ * 6. a step the adapter says must follow another for this order
27
+ * (`statusPrerequisite`: iFood's dispatch of a merchant bag follows its
28
+ * `readyToPickup`, FUT-5984) sends that one first, under its own row,
29
+ * unless it is already SENT or FAILED; one still SENDING under another run
30
+ * makes this one wait (retried);
31
+ * 7. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
23
32
  * retried; 408/425/429/5xx/timeout retried, the last attempt FAILED. A run
24
33
  * on a SENDING row it owns (a retry, or the sweep's re-queue) calls again.
25
34
  *
@@ -34,6 +43,8 @@ interface StatusJobRow {
34
43
  status: string;
35
44
  cancellationStatus: string | null;
36
45
  deliveredBy: string | null;
46
+ confirmedAt?: Date | null;
47
+ confirmFailedAt?: Date | null;
37
48
  }
38
49
 
39
50
  /** What one run did, in the outbound job's own shape. */
@@ -61,6 +72,20 @@ function acceptanceSkip(row: StatusJobRow): string | null {
61
72
  return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
62
73
  }
63
74
 
75
+ /**
76
+ * Rule 1's second half (FUT-5673): why the confirm stops the job, or null once
77
+ * the marketplace took it. Still owed and attempts left: retried.
78
+ */
79
+ function confirmSkip(row: StatusJobRow, adapter: MarketplaceAdapter, deps: StatusJobDeps): string | null {
80
+ // Only a marketplace that states it (iFood, FUT-5673): every other one tells its steps as before.
81
+ if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
82
+ if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
83
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) {
84
+ throw deps.retryError(`status for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
85
+ }
86
+ return "the store's confirm has not reached the marketplace";
87
+ }
88
+
64
89
  /** Why rules 2 and 3 stop the job, or null. Rule 3 asks the host, so it comes last. */
65
90
  async function adapterAndHostSkip(
66
91
  ctx: EngineContext,
@@ -177,7 +202,7 @@ export async function runStatus(
177
202
  ): Promise<StatusJobOutcome> {
178
203
  const step = payload.step;
179
204
  if (!step) return skipped("a status call names no step");
180
- const stopped = acceptanceSkip(row) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
205
+ const stopped = acceptanceSkip(row) ?? confirmSkip(row, adapter, deps) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
181
206
  if (stopped) return skipped(stopped);
182
207
  const db = await ctx.ports.db();
183
208
  const table = statusTable(db);
@@ -194,10 +219,68 @@ export async function runStatus(
194
219
  const key = payload.claimKey ?? "";
195
220
  const unclaimed = await claim(table, payload, row, step, key);
196
221
  if (unclaimed) return skipped(unclaimed);
222
+ const before = await sendPrerequisite(ctx, { table, payload, row, step, key, connection, adapter }, deps);
223
+ if (before) return before;
197
224
  const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
198
225
  return settle(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
199
226
  }
200
227
 
228
+ /** What rule 6 needs: the claimed step's run, and the connection it calls with. */
229
+ interface PrerequisiteRun {
230
+ table: NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>;
231
+ payload: OutboundJobPayload;
232
+ row: StatusJobRow;
233
+ step: StatusStep;
234
+ key: string;
235
+ connection: OutboundConnection;
236
+ adapter: MarketplaceAdapter;
237
+ }
238
+
239
+ /**
240
+ * Whether a prerequisite row lets this run go on: `proceed` (it stands SENT or
241
+ * FAILED), `send` (absent, or this run's own claim), or a wait. A wait is
242
+ * retried; on the last attempt it ends skipped, never sent out of order.
243
+ */
244
+ function prerequisiteState(
245
+ found: StatusRow | undefined,
246
+ key: string,
247
+ run: PrerequisiteRun,
248
+ first: StatusStep,
249
+ deps: StatusJobDeps,
250
+ ): "proceed" | "send" | StatusJobOutcome {
251
+ if (!found || ownsClaim(found, key)) return "send";
252
+ if (found.state !== "SENDING") return "proceed";
253
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) {
254
+ throw deps.retryError(`status ${run.step} for order ${run.row.orderId}: waiting for ${first}, held by another run`);
255
+ }
256
+ return skipped(`${first} is still being sent by another run`);
257
+ }
258
+
259
+ /**
260
+ * Rule 6: the step this one must follow, sent first under its own row and key
261
+ * (`<key>:<step>`, so this run's retry owns it), or null when there is none or
262
+ * it already stands. A prerequisite refused is FAILED and logged; the step
263
+ * itself still goes.
264
+ */
265
+ async function sendPrerequisite(ctx: EngineContext, run: PrerequisiteRun, deps: StatusJobDeps): Promise<StatusJobOutcome | null> {
266
+ const first = run.adapter.statusPrerequisite?.({ step: run.step, deliveredBy: deliveredByOf(run.row) }) ?? null;
267
+ if (first === null) return null;
268
+ const key = `${run.key}:${first}`;
269
+ const [found] = await readStatusRows(run.table, run.row.orderId, [first]);
270
+ const state = prerequisiteState(found, key, run, first, deps);
271
+ if (state === "proceed") return null;
272
+ if (typeof state !== "string") return state;
273
+ if (!found) {
274
+ const row = { clientId: run.payload.clientId, orderId: run.row.orderId, provider: run.row.provider };
275
+ const claimed = await insertStatusRow(run.table, { ...row, step: first, source: "STORE", state: "SENDING", claimKey: key });
276
+ if (!claimed) return sendPrerequisite(ctx, run, deps);
277
+ }
278
+ const result = await callAdapter(ctx, run.connection, run.adapter, run.row, first, deps.ref);
279
+ const outcome = await settle(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
280
+ return outcome.kind === "skipped" ? outcome : null;
281
+ }
282
+
283
+
201
284
  /** The last attempt died without an answer: FAILED, never left SENDING. Best-effort. */
202
285
  export async function failStatusRow(ctx: EngineContext, payload: OutboundJobPayload): Promise<void> {
203
286
  const table = statusTable(await ctx.ports.db());
package/src/core/types.ts CHANGED
@@ -40,6 +40,40 @@ export interface NormalizedOrderLine {
40
40
  unitPriceCents: number;
41
41
  /** The buyer's note on this line, when they left one. */
42
42
  note: string | null;
43
+ /**
44
+ * OPTIONAL (FUT-5803). The options the buyer chose on this line (a
45
+ * complemento: "borda recheada", "sem cebola"), each priced on its own. When
46
+ * present, `unitPriceCents` is the item ALONE and the line costs
47
+ * `unitPriceCents × quantity + Σ options[].totalCents`
48
+ * ({@link normalizedLineTotalCents}). Absent: none is itemized. Open
49
+ * Delivery and Rappi then fold the options' price into `unitPriceCents`;
50
+ * iFood does not, so an iFood item that states `optionsPrice` but lists no
51
+ * `options[]` is priced as the item alone. Never an empty array.
52
+ */
53
+ options?: NormalizedLineOption[];
54
+ }
55
+
56
+ /** One option on an order line, as the marketplace priced it (FUT-5803). */
57
+ export interface NormalizedLineOption {
58
+ /** The marketplace's own code for the option, when it gives one. */
59
+ externalCode: string | null;
60
+ name: string;
61
+ /** The group the marketplace shows it under ("Borda", "Adicionais"), when it says. */
62
+ groupName: string | null;
63
+ /** How many, for the WHOLE line (never per unit of it). */
64
+ quantity: number;
65
+ unitPriceCents: number;
66
+ /**
67
+ * Always exactly `unitPriceCents × quantity`. A stated price that does not
68
+ * divide by its count arrives as two rows of the same option (the floor,
69
+ * then one unit carrying the remainder), whose counts sum to the stated one.
70
+ */
71
+ totalCents: number;
72
+ }
73
+
74
+ /** What a line costs: the item times its quantity, plus each of its options. */
75
+ export function normalizedLineTotalCents(line: Pick<NormalizedOrderLine, "unitPriceCents" | "quantity" | "options">): number {
76
+ return line.unitPriceCents * line.quantity + (line.options ?? []).reduce((sum, option) => sum + option.totalCents, 0);
43
77
  }
44
78
 
45
79
  /** The buyer, as much of them as the marketplace discloses. */
@@ -48,6 +82,16 @@ export interface NormalizedBuyer {
48
82
  externalId: string | null;
49
83
  name: string | null;
50
84
  phone: string | null;
85
+ /**
86
+ * OPTIONAL (FUT-5803). The buyer's tax id for the invoice (a CPF or a CNPJ),
87
+ * digits only. Absent: the marketplace states none.
88
+ */
89
+ document?: string | null;
90
+ /**
91
+ * OPTIONAL (FUT-5803). The extension that reaches the buyer through the
92
+ * marketplace's masked number in `phone` (iFood's `phone.localizer`). Absent: none.
93
+ */
94
+ phoneLocalizer?: string | null;
51
95
  }
52
96
 
53
97
  /** Where a delivery goes, as much of it as the marketplace states. */
@@ -63,8 +107,12 @@ export interface NormalizedAddress {
63
107
  state: string | null;
64
108
  }
65
109
 
66
- /** How the order reaches the buyer: brought to the door, or collected. */
67
- export type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
110
+ /**
111
+ * How the order reaches the buyer: brought to the door (`DELIVERY`), collected
112
+ * (`TAKEOUT`), eaten at the store (`DINE_IN`), or ordered from inside it, at a
113
+ * table or a spot the buyer names (`INDOOR`, FUT-5803).
114
+ */
115
+ export type MarketplaceOrderType = "DELIVERY" | "TAKEOUT" | "DINE_IN" | "INDOOR";
68
116
 
69
117
  /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
70
118
  export type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
@@ -81,6 +129,56 @@ export interface NormalizedOrderDiscount {
81
129
  name?: string;
82
130
  }
83
131
 
132
+ /**
133
+ * How a buyer paid, as a closed set a host has words for. `OTHER`: stated,
134
+ * and none of these (the marketplace's own word is in `statedMethod`).
135
+ */
136
+ export type MarketplacePaymentMethod =
137
+ | "CREDIT"
138
+ | "DEBIT"
139
+ | "MEAL_VOUCHER"
140
+ | "FOOD_VOUCHER"
141
+ | "PIX"
142
+ | "CASH"
143
+ | "DIGITAL_WALLET"
144
+ | "OTHER";
145
+
146
+ /** One way the buyer pays an order (FUT-5803). */
147
+ export interface NormalizedPaymentMethod {
148
+ method: MarketplacePaymentMethod;
149
+ /** The marketplace's own word for the method, verbatim; null when it states none. */
150
+ statedMethod: string | null;
151
+ /**
152
+ * True: already paid on the marketplace. False: to collect from the buyer at
153
+ * the door or the counter. Null: unstated.
154
+ */
155
+ prepaid: boolean | null;
156
+ /** What this method pays, in the smallest currency unit. */
157
+ valueCents: number;
158
+ /** The card's brand as the marketplace names it ("VISA"), when it does. */
159
+ cardBrand: string | null;
160
+ /** On cash: the note the buyer pays with, so the courier brings the change. Null: no change asked, or unstated. */
161
+ changeForCents: number | null;
162
+ }
163
+
164
+ /** The order's payment, as the marketplace states it (FUT-5803). */
165
+ export interface NormalizedPayments {
166
+ /** What the marketplace already collected. Null: unstated. */
167
+ prepaidCents: number | null;
168
+ /** What is still to collect from the buyer. Null: unstated. */
169
+ pendingCents: number | null;
170
+ methods: NormalizedPaymentMethod[];
171
+ }
172
+
173
+ /** A fee the marketplace charged the buyer besides delivery (FUT-5803), such as a small-order fee. */
174
+ export interface NormalizedOrderFee {
175
+ /** The marketplace's own kind, verbatim (`SMALL_ORDER_FEE`). */
176
+ kind: string;
177
+ cents: number;
178
+ /** What the marketplace called it, when it says. */
179
+ name?: string;
180
+ }
181
+
84
182
  /** An incoming marketplace order, normalized. */
85
183
  export interface NormalizedMarketplaceOrder {
86
184
  provider: MarketplaceProvider;
@@ -135,6 +233,17 @@ export interface NormalizedMarketplaceOrder {
135
233
  * the bag itself).
136
234
  */
137
235
  pickupCode?: string | null;
236
+ /**
237
+ * OPTIONAL (FUT-5803). How the buyer pays: each method, what is prepaid and
238
+ * what is still to collect, and the change a cash buyer asks for. Absent:
239
+ * the marketplace states none.
240
+ */
241
+ payments?: NormalizedPayments;
242
+ /**
243
+ * OPTIONAL (FUT-5803). The fees besides delivery, inside `totalCents`.
244
+ * Absent is "did not say"; an empty array is "none".
245
+ */
246
+ additionalFees?: NormalizedOrderFee[];
138
247
  }
139
248
 
140
249
  /**
@@ -233,4 +342,10 @@ export interface NormalizedEvent {
233
342
  * names no courier step.
234
343
  */
235
344
  courier?: NormalizedCourierEvent | null;
345
+ /**
346
+ * OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own
347
+ * app (iFood's `CFM`): an order still AWAITING here is accepted through the
348
+ * host's admit, with no confirm sent back. Carries no order body.
349
+ */
350
+ marketplaceConfirmed?: boolean;
236
351
  }
@@ -5,8 +5,17 @@ import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { IFOOD_COURIER } from "./courier";
6
6
  import { ifoodFetchOrder } from "./fetch-order";
7
7
  import { IFOOD_LINKING } from "./linking";
8
- import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
9
- import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
8
+ import { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from "./normalize";
9
+ import {
10
+ IFOOD_ACKNOWLEDGEMENT,
11
+ IFOOD_PORTAL_URL,
12
+ ifoodConfirm,
13
+ ifoodInformStatus,
14
+ ifoodOrderCancellationReasons,
15
+ ifoodRequestCancellation,
16
+ ifoodStatusPrerequisite,
17
+ ifoodStatusSupported,
18
+ } from "./outbound";
10
19
  import { IFOOD_AVAILABILITY } from "./pause";
11
20
 
12
21
  /**
@@ -39,7 +48,10 @@ export interface IfoodAdapterConfig {
39
48
  copy: IfoodAdapterCopy;
40
49
  }
41
50
 
42
- /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
51
+ /**
52
+ * Build the iFood adapter. Its static reasons are the fallback: each order's
53
+ * own are read from iFood in a job after its ingest (FUT-5984).
54
+ */
43
55
  export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {
44
56
  const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({
45
57
  code,
@@ -67,6 +79,12 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
67
79
  // pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
68
80
  // CONCLUDED is that.
69
81
  statusSteps: ["READY", "DISPATCHED"],
82
+ // "Retorne `202 Accepted` em até 5 segundos" (Events `webhook-overview`, FUT-5984).
83
+ webhookAnswerStatus: 202,
84
+ // CFM: the store accepted on iFood's own app (FUT-5653).
85
+ marketplaceConfirms: true,
86
+ // A step is told only once iFood took the confirm (FUT-5673).
87
+ statusAfterConfirm: true,
70
88
  },
71
89
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
72
90
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
@@ -82,6 +100,11 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
82
100
  fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),
83
101
  statusSupported: ifoodStatusSupported,
84
102
  informStatus: ifoodInformStatus,
103
+ statusPrerequisite: ifoodStatusPrerequisite,
104
+ // The presence heartbeat, the events' acknowledgment and each order's own reasons (FUT-5984).
105
+ presence: readIfoodPresence,
106
+ acknowledgement: IFOOD_ACKNOWLEDGEMENT,
107
+ orderCancellationReasons: ifoodOrderCancellationReasons,
85
108
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
86
109
  availability: IFOOD_AVAILABILITY,
87
110
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
@@ -95,7 +118,7 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
95
118
  }
96
119
 
97
120
  export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
98
- export { normalizeIfoodEvent, readIfoodOrder, verifyIfoodSignature } from "./normalize";
121
+ export { normalizeIfoodEvent, readIfoodOrder, readIfoodPresence, verifyIfoodSignature } from "./normalize";
99
122
  export { ifoodFetchOrder } from "./fetch-order";
100
123
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
101
124
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
@@ -10,6 +10,7 @@ import type {
10
10
  NormalizedOrderDiscount,
11
11
  NormalizedOrderLine,
12
12
  } from "../core/types";
13
+ import { normalizedLineTotalCents } from "../core/types";
13
14
  import {
14
15
  asString,
15
16
  firstCents,
@@ -20,6 +21,7 @@ import {
20
21
  verifyHmacSha256Hex,
21
22
  } from "../core/payload-read";
22
23
  import { readIfoodCourierEvent } from "./courier";
24
+ import { readIfoodAdditionalFees, readIfoodBuyerDocument, readIfoodOptions, readIfoodPayments } from "./order-details";
23
25
 
24
26
  /**
25
27
  * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.
@@ -38,6 +40,10 @@ import { readIfoodCourierEvent } from "./courier";
38
40
  /** iFood event codes this ingestion acts on. */
39
41
  const ORDER_PLACED = new Set(["PLC", "PLACED", "ORDER_PLACED"]);
40
42
  const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
43
+ /** The store accepted the order on iFood's own app (FUT-5653). Also the echo of our own confirm. */
44
+ const ORDER_CONFIRMED = new Set(["CFM", "CONFIRMED"]);
45
+ /** iFood's presence heartbeat (FUT-5984, `presence.md`): every 30 s, naming no order. */
46
+ const KEEPALIVE = "KEEPALIVE";
41
47
  /** iFood refused the store's own cancellation request. */
42
48
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
43
49
 
@@ -75,7 +81,10 @@ export function verifyIfoodSignature(
75
81
  return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
76
82
  }
77
83
 
78
- /** The buyer, as much of them as iFood discloses on the order. */
84
+ /**
85
+ * The buyer, as much of them as iFood discloses on the order. The document
86
+ * (for the invoice) and the masked phone's localizer are absent when unstated.
87
+ */
79
88
  function readBuyer(order: unknown): NormalizedBuyer {
80
89
  return {
81
90
  externalId: asString(pick(order, "customer", "id")),
@@ -84,6 +93,8 @@ function readBuyer(order: unknown): NormalizedBuyer {
84
93
  ["customer", "phone", "number"],
85
94
  ["customer", "phone"],
86
95
  ]),
96
+ ...optional("document", readIfoodBuyerDocument(order) ?? undefined),
97
+ ...optional("phoneLocalizer", firstString(order, [["customer", "phone", "localizer"]]) ?? undefined),
87
98
  };
88
99
  }
89
100
 
@@ -95,6 +106,10 @@ function readBuyer(order: unknown): NormalizedBuyer {
95
106
  * real work — an unmapped line is recoverable (the store maps it and it is
96
107
  * fixed forever), a DROPPED line is not, because nothing downstream can tell
97
108
  * that food is missing from the ticket.
109
+ *
110
+ * Its options (FUT-5803) ride on the line, priced on their own: the line costs
111
+ * `unitPrice × quantity` plus each option's `price`, which is iFood's
112
+ * `totalPrice` (`price + optionsPrice`).
98
113
  */
99
114
  function readLine(item: unknown): NormalizedOrderLine | null {
100
115
  const name = firstString(item, [["name"], ["description"]]);
@@ -107,6 +122,7 @@ function readLine(item: unknown): NormalizedOrderLine | null {
107
122
  quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,
108
123
  unitPriceCents: firstCents(item, [["unitPrice"], ["price"]]) ?? 0,
109
124
  note: firstString(item, [["observations"], ["note"]]),
125
+ ...optional("options", readIfoodOptions(item)),
110
126
  };
111
127
  }
112
128
 
@@ -122,10 +138,12 @@ function readCommission(order: unknown): number | null {
122
138
  return firstCents(order, [["total", "commission"], ["commission"], ["payments", "commission"]]);
123
139
  }
124
140
 
125
- /** iFood's `orderType` as the two ways an order reaches the buyer, or null when it says neither. */
141
+ const ORDER_TYPES: ReadonlySet<string> = new Set<MarketplaceOrderType>(["DELIVERY", "TAKEOUT", "DINE_IN", "INDOOR"]);
142
+
143
+ /** iFood's `orderType` (DELIVERY, TAKEOUT, DINE_IN, INDOOR), or null when it says none of them. */
126
144
  function readOrderType(order: unknown): MarketplaceOrderType | null {
127
145
  const stated = firstString(order, [["orderType"]])?.toUpperCase();
128
- return stated === "DELIVERY" || stated === "TAKEOUT" ? stated : null;
146
+ return stated !== undefined && ORDER_TYPES.has(stated) ? (stated as MarketplaceOrderType) : null;
129
147
  }
130
148
 
131
149
  /** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */
@@ -139,7 +157,7 @@ function readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {
139
157
  * iFood's sponsor names as who pays. ESTIMATED: the names are the ones iFood's
140
158
  * order-details guide documents for `benefits[].sponsorshipValues[].name`, but
141
159
  * no recorded payload in this repo carries them; confirm against a real order
142
- * (https://developer.ifood.com.br/en-US/docs/guides/order/details).
160
+ * (iFood's Order API guide "Detalhes do pedido").
143
161
  */
144
162
  function sponsorOf(name: string | null): MarketplaceDiscountSponsor {
145
163
  const stated = name?.toUpperCase();
@@ -231,7 +249,7 @@ export function readIfoodOrder(
231
249
  // carries delivery fees, its promotions and its rounding, and it is the
232
250
  // number on the buyer's receipt. Summing lines when iFood did say is how a
233
251
  // store's revenue quietly stops matching its iFood statement.
234
- totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),
252
+ totalCents: stated ?? lines.reduce((sum, line) => sum + normalizedLineTotalCents(line), 0),
235
253
  commissionCents: readCommission(order),
236
254
  deliveryDueAt: firstDate(order, [["delivery", "deliveryDateTime"], ["preparationStartDateTime"]]),
237
255
  placedAt:
@@ -247,6 +265,9 @@ export function readIfoodOrder(
247
265
  ...optional("discounts", readDiscounts(order)),
248
266
  // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.
249
267
  pickupCode: firstString(order, [["delivery", "pickupCode"]]),
268
+ // FUT-5803: how the buyer pays and the fees besides delivery; absent when unstated.
269
+ ...optional("payments", readIfoodPayments(order)),
270
+ ...optional("additionalFees", readIfoodAdditionalFees(order)),
250
271
  };
251
272
  }
252
273
 
@@ -301,5 +322,17 @@ export function normalizeIfoodEvent(
301
322
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
302
323
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
303
324
  ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
325
+ ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
304
326
  };
305
327
  }
328
+
329
+ /**
330
+ * iFood's `KEEPALIVE` (FUT-5984): `{ code, fullCode, id }`, and `merchantIds`
331
+ * in the per-merchant mode. Null for any other delivery.
332
+ */
333
+ export function readIfoodPresence(payload: unknown): { merchantIds: readonly string[] | null } | null {
334
+ const code = firstString(payload, [["fullCode"], ["code"]]);
335
+ if (code?.toUpperCase() !== KEEPALIVE) return null;
336
+ const ids = pick(payload, "merchantIds");
337
+ return { merchantIds: Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : null };
338
+ }