@12-apps/marketplace 1.14.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 (46) hide show
  1. package/ADOPTING.md +115 -0
  2. package/dist/99food/index.d.ts +2 -2
  3. package/dist/99food/index.js +2 -2
  4. package/dist/{adapter-szxo9ohc.d.ts → adapter-CjVdMhZ2.d.ts} +96 -3
  5. package/dist/{chunk-MDXSVE7Q.js → chunk-B4DYPQFE.js} +6 -6
  6. package/dist/chunk-B4DYPQFE.js.map +1 -0
  7. package/dist/{chunk-BD7DS3XM.js → chunk-E4XJXHUK.js} +20 -1
  8. package/dist/chunk-E4XJXHUK.js.map +1 -0
  9. package/dist/{chunk-R3BUW5PX.js → chunk-FQI56NGC.js} +2 -2
  10. package/dist/chunk-H2VQRD3B.js +16 -0
  11. package/dist/chunk-H2VQRD3B.js.map +1 -0
  12. package/dist/{chunk-BNWRIR5J.js → chunk-TRUK5ZBE.js} +11 -3
  13. package/dist/chunk-TRUK5ZBE.js.map +1 -0
  14. package/dist/{client-CaZiG7Lw.d.ts → client-DgzCkl8u.d.ts} +1 -1
  15. package/dist/{engine-CgKBbk9J.d.ts → engine-BSLdhAGC.d.ts} +8 -1
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -2
  18. package/dist/hono/index.js.map +1 -1
  19. package/dist/ifood/index.d.ts +1 -1
  20. package/dist/ifood/index.js +105 -6
  21. package/dist/ifood/index.js.map +1 -1
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +6 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/keeta/index.d.ts +2 -2
  26. package/dist/keeta/index.js +2 -2
  27. package/dist/manifest/server.d.ts +2 -2
  28. package/dist/manifest/server.js +3 -2
  29. package/dist/manifest/server.js.map +1 -1
  30. package/dist/rappi/index.d.ts +1 -1
  31. package/dist/rappi/index.js +1 -1
  32. package/dist/server/index.d.ts +2 -2
  33. package/dist/server/index.js +3 -2
  34. package/package.json +1 -1
  35. package/src/core/ingest.ts +1 -0
  36. package/src/core/order-types.ts +8 -0
  37. package/src/core/payload-read.ts +24 -0
  38. package/src/core/types.ts +111 -2
  39. package/src/ifood/normalize.ts +22 -5
  40. package/src/ifood/order-details.ts +120 -0
  41. package/src/index.ts +6 -0
  42. package/src/open-delivery/normalize.ts +9 -0
  43. package/dist/chunk-BD7DS3XM.js.map +0 -1
  44. package/dist/chunk-BNWRIR5J.js.map +0 -1
  45. package/dist/chunk-MDXSVE7Q.js.map +0 -1
  46. /package/dist/{chunk-R3BUW5PX.js.map → chunk-FQI56NGC.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-szxo9ohc.js';
2
- import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CaZiG7Lw.js';
1
+ import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-CjVdMhZ2.js';
2
+ import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-DgzCkl8u.js';
3
3
 
4
4
  /**
5
5
  * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
@@ -13,14 +13,14 @@ import {
13
13
  openDeliveryRequestCancellation,
14
14
  openDeliveryStatus,
15
15
  openDeliverySwitchAvailability
16
- } from "../chunk-BNWRIR5J.js";
16
+ } from "../chunk-TRUK5ZBE.js";
17
17
  import "../chunk-M2V4RFMA.js";
18
18
  import {
19
19
  asString,
20
20
  firstDate,
21
21
  firstString,
22
22
  pick
23
- } from "../chunk-BD7DS3XM.js";
23
+ } from "../chunk-E4XJXHUK.js";
24
24
  import {
25
25
  outboundResultOf
26
26
  } from "../chunk-BTKVZAJI.js";
@@ -1,7 +1,7 @@
1
- import { av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-CgKBbk9J.js';
1
+ import { av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-BSLdhAGC.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-szxo9ohc.js';
4
+ import '../adapter-CjVdMhZ2.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-R3BUW5PX.js";
4
+ } from "../chunk-FQI56NGC.js";
5
5
  import "../chunk-SGOTN5PX.js";
6
- import "../chunk-MDXSVE7Q.js";
6
+ import "../chunk-B4DYPQFE.js";
7
+ import "../chunk-H2VQRD3B.js";
7
8
  import "../chunk-7QVYU63E.js";
8
9
 
9
10
  // src/manifest/server.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/manifest/server.ts"],"sourcesContent":["/**\n * `@12-apps/marketplace/manifest/server` — the server capabilities.\n *\n * `http.create` IS `createApiMarketplace`, unchanged: its descriptors already\n * satisfy the wiring contract's `WireRoute`, policy half included, so a host's\n * gates read each route's permission off the assembled table. `jobs` is the\n * engine's own cadence (`../server/jobs`); a host binds `{ engine }` and\n * deletes its hand-rolled sweeps.\n */\n\nimport type { AnyServerManifest } from \"@12-apps/wiring\";\n\nimport { createApiMarketplace } from \"../server\";\nimport { MARKETPLACE_JOBS } from \"../server/jobs\";\n\nexport const marketplaceServerManifest = {\n name: \"@12-apps/marketplace\",\n http: { create: createApiMarketplace },\n jobs: MARKETPLACE_JOBS,\n} as const satisfies AnyServerManifest;\n"],"mappings":";;;;;;;;;AAeO,IAAM,4BAA4B;AAAA,EACvC,MAAM;AAAA,EACN,MAAM,EAAE,QAAQ,qBAAqB;AAAA,EACrC,MAAM;AACR;","names":[]}
1
+ {"version":3,"sources":["../../src/manifest/server.ts"],"sourcesContent":["/**\n * `@12-apps/marketplace/manifest/server` — the server capabilities.\n *\n * `http.create` IS `createApiMarketplace`, unchanged: its descriptors already\n * satisfy the wiring contract's `WireRoute`, policy half included, so a host's\n * gates read each route's permission off the assembled table. `jobs` is the\n * engine's own cadence (`../server/jobs`); a host binds `{ engine }` and\n * deletes its hand-rolled sweeps.\n */\n\nimport type { AnyServerManifest } from \"@12-apps/wiring\";\n\nimport { createApiMarketplace } from \"../server\";\nimport { MARKETPLACE_JOBS } from \"../server/jobs\";\n\nexport const marketplaceServerManifest = {\n name: \"@12-apps/marketplace\",\n http: { create: createApiMarketplace },\n jobs: MARKETPLACE_JOBS,\n} as const satisfies AnyServerManifest;\n"],"mappings":";;;;;;;;;;AAeO,IAAM,4BAA4B;AAAA,EACvC,MAAM;AAAA,EACN,MAAM,EAAE,QAAQ,qBAAqB;AAAA,EACrC,MAAM;AACR;","names":[]}
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-szxo9ohc.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CjVdMhZ2.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -4,7 +4,7 @@ import {
4
4
  firstString,
5
5
  pick,
6
6
  verifyHmacSha256Hex
7
- } from "../chunk-BD7DS3XM.js";
7
+ } from "../chunk-E4XJXHUK.js";
8
8
  import {
9
9
  answered,
10
10
  outboundResultOf,
@@ -1,7 +1,7 @@
1
- import { I as DecisionProblemCode, i as BulkProblemCode, X as LinkRefusalCode, ac as MarketplaceEngine, ai as MarketplaceLogger, av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-CgKBbk9J.js';
1
+ import { I as DecisionProblemCode, i as BulkProblemCode, X as LinkRefusalCode, ac as MarketplaceEngine, ai as MarketplaceLogger, av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-BSLdhAGC.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-szxo9ohc.js';
4
+ import '../adapter-CjVdMhZ2.js';
5
5
 
6
6
  /**
7
7
  * Every problem code a route words from `problems`, decisions and bulk writes
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-R3BUW5PX.js";
9
+ } from "../chunk-FQI56NGC.js";
10
10
  import {
11
11
  MARKETPLACE_DECIDE,
12
12
  MARKETPLACE_MANAGE,
@@ -20,7 +20,8 @@ import {
20
20
  upsertMarketplaceIntegrationsBody,
21
21
  upsertMarketplaceMenuLinksBody
22
22
  } from "../chunk-SGOTN5PX.js";
23
- import "../chunk-MDXSVE7Q.js";
23
+ import "../chunk-B4DYPQFE.js";
24
+ import "../chunk-H2VQRD3B.js";
24
25
  import "../chunk-7QVYU63E.js";
25
26
  export {
26
27
  MARKETPLACE_AVAILABILITY_ATTEMPTS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food and ./keeta on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -82,6 +82,7 @@ async function composeLines(
82
82
  note: line.note,
83
83
  subjectRef: mapping.get(line.externalSku)?.menuItemId ?? null,
84
84
  variationRef: mapping.get(line.externalSku)?.variationId ?? null,
85
+ ...(line.options ? { options: line.options } : {}),
85
86
  }));
86
87
  }
87
88
 
@@ -5,6 +5,8 @@
5
5
  * re-exports every name, so a host imports them from there as before.
6
6
  */
7
7
 
8
+ import type { NormalizedLineOption } from "./types";
9
+
8
10
  /**
9
11
  * One order line after the engine has matched it against the SKU map.
10
12
  * `subjectRef` is the host catalog id, or null when the SKU was never mapped —
@@ -20,6 +22,12 @@ export interface ResolvedOrderLine {
20
22
  note: string | null;
21
23
  subjectRef: string | null;
22
24
  variationRef: string | null;
25
+ /**
26
+ * OPTIONAL (FUT-5803). The line's options, as the marketplace priced them;
27
+ * present only when the normalized line carries some. `unitPriceCents` is
28
+ * then the item alone (`normalizedLineTotalCents`).
29
+ */
30
+ options?: NormalizedLineOption[];
23
31
  }
24
32
 
25
33
  /** What the acceptance queue shows about an order, resolved by the host. */
@@ -64,6 +64,30 @@ export function firstCents(source: unknown, paths: string[][]): number | null {
64
64
  return null;
65
65
  }
66
66
 
67
+ /**
68
+ * A CPF or CNPJ → its digits, or null. Text keeps its digits (`123.456.789-09`).
69
+ * A number lost its leading zeros on the way, so it is padded back to a CPF's
70
+ * 11 digits, or a CNPJ's 14 when it is longer than a CPF.
71
+ */
72
+ function toTaxId(value: unknown): string | null {
73
+ if (typeof value === "number") {
74
+ if (!Number.isSafeInteger(value) || value <= 0) return null;
75
+ const digits = String(value);
76
+ return digits.padStart(digits.length <= 11 ? 11 : 14, "0");
77
+ }
78
+ const digits = asString(value)?.replace(/\D/g, "");
79
+ return digits ? digits : null;
80
+ }
81
+
82
+ /** {@link firstString} for a tax id (CPF or CNPJ), digits only. */
83
+ export function firstTaxId(source: unknown, paths: string[][]): string | null {
84
+ for (const path of paths) {
85
+ const found = toTaxId(pick(source, ...path));
86
+ if (found !== null) return found;
87
+ }
88
+ return null;
89
+ }
90
+
67
91
  /** An ISO timestamp → a Date, or null when absent or unparseable. */
68
92
  function toDate(value: unknown): Date | null {
69
93
  const raw = asString(value);
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
  /**
@@ -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}.
@@ -79,7 +81,10 @@ export function verifyIfoodSignature(
79
81
  return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
80
82
  }
81
83
 
82
- /** 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
+ */
83
88
  function readBuyer(order: unknown): NormalizedBuyer {
84
89
  return {
85
90
  externalId: asString(pick(order, "customer", "id")),
@@ -88,6 +93,8 @@ function readBuyer(order: unknown): NormalizedBuyer {
88
93
  ["customer", "phone", "number"],
89
94
  ["customer", "phone"],
90
95
  ]),
96
+ ...optional("document", readIfoodBuyerDocument(order) ?? undefined),
97
+ ...optional("phoneLocalizer", firstString(order, [["customer", "phone", "localizer"]]) ?? undefined),
91
98
  };
92
99
  }
93
100
 
@@ -99,6 +106,10 @@ function readBuyer(order: unknown): NormalizedBuyer {
99
106
  * real work — an unmapped line is recoverable (the store maps it and it is
100
107
  * fixed forever), a DROPPED line is not, because nothing downstream can tell
101
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`).
102
113
  */
103
114
  function readLine(item: unknown): NormalizedOrderLine | null {
104
115
  const name = firstString(item, [["name"], ["description"]]);
@@ -111,6 +122,7 @@ function readLine(item: unknown): NormalizedOrderLine | null {
111
122
  quantity: Number.isFinite(quantity) && quantity > 0 ? Math.round(quantity) : 1,
112
123
  unitPriceCents: firstCents(item, [["unitPrice"], ["price"]]) ?? 0,
113
124
  note: firstString(item, [["observations"], ["note"]]),
125
+ ...optional("options", readIfoodOptions(item)),
114
126
  };
115
127
  }
116
128
 
@@ -126,10 +138,12 @@ function readCommission(order: unknown): number | null {
126
138
  return firstCents(order, [["total", "commission"], ["commission"], ["payments", "commission"]]);
127
139
  }
128
140
 
129
- /** 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. */
130
144
  function readOrderType(order: unknown): MarketplaceOrderType | null {
131
145
  const stated = firstString(order, [["orderType"]])?.toUpperCase();
132
- return stated === "DELIVERY" || stated === "TAKEOUT" ? stated : null;
146
+ return stated !== undefined && ORDER_TYPES.has(stated) ? (stated as MarketplaceOrderType) : null;
133
147
  }
134
148
 
135
149
  /** `delivery.deliveredBy`: iFood's own fleet, or the merchant's. Anything else is unstated. */
@@ -143,7 +157,7 @@ function readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {
143
157
  * iFood's sponsor names as who pays. ESTIMATED: the names are the ones iFood's
144
158
  * order-details guide documents for `benefits[].sponsorshipValues[].name`, but
145
159
  * no recorded payload in this repo carries them; confirm against a real order
146
- * (https://developer.ifood.com.br/en-US/docs/guides/order/details).
160
+ * (iFood's Order API guide "Detalhes do pedido").
147
161
  */
148
162
  function sponsorOf(name: string | null): MarketplaceDiscountSponsor {
149
163
  const stated = name?.toUpperCase();
@@ -235,7 +249,7 @@ export function readIfoodOrder(
235
249
  // carries delivery fees, its promotions and its rounding, and it is the
236
250
  // number on the buyer's receipt. Summing lines when iFood did say is how a
237
251
  // store's revenue quietly stops matching its iFood statement.
238
- totalCents: stated ?? lines.reduce((sum, l) => sum + l.unitPriceCents * l.quantity, 0),
252
+ totalCents: stated ?? lines.reduce((sum, line) => sum + normalizedLineTotalCents(line), 0),
239
253
  commissionCents: readCommission(order),
240
254
  deliveryDueAt: firstDate(order, [["delivery", "deliveryDateTime"], ["preparationStartDateTime"]]),
241
255
  placedAt:
@@ -251,6 +265,9 @@ export function readIfoodOrder(
251
265
  ...optional("discounts", readDiscounts(order)),
252
266
  // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.
253
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)),
254
271
  };
255
272
  }
256
273
 
@@ -0,0 +1,120 @@
1
+ import type {
2
+ MarketplacePaymentMethod,
3
+ NormalizedLineOption,
4
+ NormalizedOrderFee,
5
+ NormalizedPaymentMethod,
6
+ NormalizedPayments,
7
+ } from "../core/types";
8
+ import { firstCents, firstString, firstTaxId, pick, toCents } from "../core/payload-read";
9
+
10
+ /**
11
+ * The parts of an iFood order beyond its items' base price (FUT-5803): each
12
+ * item's options, the payment, the fees besides delivery and the buyer's
13
+ * document. Field names follow iFood's order-details guide
14
+ * ("Detalhes do pedido", developer portal); read
15
+ * defensively like the rest of the adapter, so an absent part is absent,
16
+ * never a refused order.
17
+ */
18
+
19
+ /** A whole, positive count; 1 when absent or nonsense. */
20
+ function countOf(source: unknown): number {
21
+ const stated = Number(pick(source, "quantity") ?? 1);
22
+ return Number.isFinite(stated) && stated > 0 ? Math.round(stated) : 1;
23
+ }
24
+
25
+ /**
26
+ * The option's rows, each with `unitPriceCents × quantity` exactly its total,
27
+ * because a host writes the two and must read the stated price back. Kept as
28
+ * stated when they agree. Otherwise the stated total is split over the stated
29
+ * quantity, as Open Delivery's lines are: one row when it divides, else
30
+ * `quantity - 1` at the floor and one carrying the remainder (R$ 10.00 over 3
31
+ * is 2 × 3.33 + 1 × 3.34). The count the kitchen reads never changes.
32
+ */
33
+ function priced(quantity: number, unit: number | null, total: number): { quantity: number; unitPriceCents: number; totalCents: number }[] {
34
+ if (unit !== null && unit * quantity === total) return [{ quantity, unitPriceCents: unit, totalCents: total }];
35
+ const floor = Math.floor(total / quantity);
36
+ const remainder = total - floor * quantity;
37
+ if (remainder === 0) return [{ quantity, unitPriceCents: floor, totalCents: total }];
38
+ const last = { quantity: 1, unitPriceCents: floor + remainder, totalCents: floor + remainder };
39
+ return quantity === 1 ? [last] : [{ quantity: quantity - 1, unitPriceCents: floor, totalCents: floor * (quantity - 1) }, last];
40
+ }
41
+
42
+ /** One `items[].options[]` entry as its rows (one, or two when its price splits); none for one with no name and no price. */
43
+ function readOption(raw: unknown): NormalizedLineOption[] {
44
+ const quantity = countOf(raw);
45
+ const unit = toCents(pick(raw, "unitPrice"));
46
+ const total = toCents(pick(raw, "price")) ?? (unit ?? 0) * quantity;
47
+ const name = firstString(raw, [["name"], ["externalCode"]]);
48
+ if (name === null && total === 0) return [];
49
+ const option = { externalCode: firstString(raw, [["externalCode"]]), name: name ?? "", groupName: firstString(raw, [["groupName"]]) };
50
+ return priced(quantity, unit, total).map((row) => ({ ...option, ...row }));
51
+ }
52
+
53
+ /** An item's options; undefined when it states none, so a plain line stays as it was. */
54
+ export function readIfoodOptions(item: unknown): NormalizedLineOption[] | undefined {
55
+ const raw = pick(item, "options");
56
+ if (!Array.isArray(raw)) return undefined;
57
+ const options = raw.flatMap(readOption);
58
+ return options.length > 0 ? options : undefined;
59
+ }
60
+
61
+ const METHODS: ReadonlySet<string> = new Set<MarketplacePaymentMethod>([
62
+ "CREDIT",
63
+ "DEBIT",
64
+ "MEAL_VOUCHER",
65
+ "FOOD_VOUCHER",
66
+ "PIX",
67
+ "CASH",
68
+ "DIGITAL_WALLET",
69
+ ]);
70
+
71
+ /** `type` ONLINE is prepaid and OFFLINE is collected; failing both, the method's own `prepaid` flag. */
72
+ function prepaidOf(raw: unknown): boolean | null {
73
+ const type = firstString(raw, [["type"]])?.toUpperCase();
74
+ if (type === "ONLINE") return true;
75
+ if (type === "OFFLINE") return false;
76
+ const flag = pick(raw, "prepaid");
77
+ return typeof flag === "boolean" ? flag : null;
78
+ }
79
+
80
+ /** One `payments.methods[]` entry. A method with no value states 0: the method itself is what the door needs. */
81
+ function readMethod(raw: unknown): NormalizedPaymentMethod {
82
+ const stated = firstString(raw, [["method"]])?.toUpperCase() ?? null;
83
+ return {
84
+ method: stated !== null && METHODS.has(stated) ? (stated as MarketplacePaymentMethod) : "OTHER",
85
+ statedMethod: stated,
86
+ prepaid: prepaidOf(raw),
87
+ valueCents: toCents(pick(raw, "value")) ?? 0,
88
+ cardBrand: firstString(raw, [["card", "brand"]]),
89
+ changeForCents: firstCents(raw, [["cash", "changeFor"], ["changeFor"]]),
90
+ };
91
+ }
92
+
93
+ /** `payments`: what is prepaid, what is pending, and each method. Undefined when the order states no payment. */
94
+ export function readIfoodPayments(order: unknown): NormalizedPayments | undefined {
95
+ const payments = pick(order, "payments");
96
+ if (typeof payments !== "object" || payments === null) return undefined;
97
+ const methods = pick(payments, "methods");
98
+ return {
99
+ prepaidCents: firstCents(payments, [["prepaid"]]),
100
+ pendingCents: firstCents(payments, [["pending"]]),
101
+ methods: Array.isArray(methods) ? methods.map(readMethod) : [],
102
+ };
103
+ }
104
+
105
+ /** `additionalFees[]`: each with a type and a value. Undefined when unstated; a fee with no value is skipped. */
106
+ export function readIfoodAdditionalFees(order: unknown): NormalizedOrderFee[] | undefined {
107
+ const raw = pick(order, "additionalFees");
108
+ if (!Array.isArray(raw)) return undefined;
109
+ return raw.flatMap((fee): NormalizedOrderFee[] => {
110
+ const cents = toCents(pick(fee, "value"));
111
+ if (cents === null) return [];
112
+ const name = firstString(fee, [["description"]]);
113
+ return [{ kind: firstString(fee, [["type"]])?.toUpperCase() ?? "OTHER", cents, ...(name === null ? {} : { name }) }];
114
+ });
115
+ }
116
+
117
+ /** The buyer's CPF or CNPJ, digits only (`documentNumber`, or `document`, text or a number); null when unstated. */
118
+ export function readIfoodBuyerDocument(order: unknown): string | null {
119
+ return firstTaxId(order, [["customer", "documentNumber"], ["customer", "document"]]);
120
+ }
package/src/index.ts CHANGED
@@ -79,6 +79,7 @@ export type {
79
79
  } from "./core/ports";
80
80
  export {
81
81
  PROVIDER_ID_PATTERN,
82
+ normalizedLineTotalCents,
82
83
  type CancellationOutcome,
83
84
  type MarketplaceDeliveredBy,
84
85
  type MarketplaceDiscountSponsor,
@@ -95,6 +96,11 @@ export {
95
96
  type NormalizedMarketplaceOrder,
96
97
  type NormalizedOrderDiscount,
97
98
  type NormalizedOrderLine,
99
+ type NormalizedLineOption,
100
+ type MarketplacePaymentMethod,
101
+ type NormalizedPaymentMethod,
102
+ type NormalizedPayments,
103
+ type NormalizedOrderFee,
98
104
  } from "./core/types";
99
105
  export type {
100
106
  AcceptanceStatus,
@@ -3,6 +3,7 @@ import {
3
3
  firstCents,
4
4
  firstDate,
5
5
  firstString,
6
+ firstTaxId,
6
7
  pick,
7
8
  toCents,
8
9
  verifyHmacSha256Hex,
@@ -220,6 +221,12 @@ function readAddress(order: unknown, missingStreetNumber: string): NormalizedAdd
220
221
  };
221
222
  }
222
223
 
224
+ /** `customer.documentNumber` (text or a number), digits only, as `{ document }`; nothing when unstated. */
225
+ function buyerDocument(order: unknown): { document?: string } {
226
+ const digits = firstTaxId(order, [["customer", "documentNumber"]]);
227
+ return digits ? { document: digits } : {};
228
+ }
229
+
223
230
  /**
224
231
  * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when
225
232
  * it carries no id or no line.
@@ -248,6 +255,8 @@ export function normalizeOpenDeliveryOrderAs(
248
255
  externalId: firstString(order, [["customer", "id"]]),
249
256
  name: firstString(order, [["customer", "name"]]),
250
257
  phone: firstString(order, [["customer", "phone", "number"]]),
258
+ // FUT-5803: the CPF or CNPJ for the invoice, digits only; absent when unstated.
259
+ ...buyerDocument(order),
251
260
  },
252
261
  lines,
253
262
  // The line sum is the FALLBACK: the stated total carries the fees and
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/payload-read.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\n\n/**\n * The defensive readers every adapter's normalizer is built from.\n *\n * A marketplace payload is UNTRUSTED: a documented shape and the shape that\n * actually arrives drift, and a `TypeError` reading a missing field would\n * reject a paid order at the door. Every reader here produces a value or\n * null, never a throw. They are wire-format-neutral (no marketplace's key\n * names), which is why they live beside the engine rather than in an adapter.\n */\n\n/** Read a nested value without asserting the shape of anything on the way. */\nexport function pick(source: unknown, ...path: string[]): unknown {\n let cursor: unknown = source;\n for (const key of path) {\n if (typeof cursor !== \"object\" || cursor === null) return undefined;\n cursor = (cursor as Record<string, unknown>)[key];\n }\n return cursor;\n}\n\n/** A non-blank string (trimmed), a finite number as text, or null. */\nexport function asString(value: unknown): string | null {\n if (typeof value === \"string\" && value.trim() !== \"\") return value.trim();\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value);\n return null;\n}\n\n/**\n * The first of several candidate paths that yields a string.\n *\n * A marketplace states the same fact under different keys depending on which\n * API version delivered it, so nearly every read is a fallback chain. Expressed\n * as data rather than as `??` so a chain grows by one entry, not one branch.\n */\nexport function firstString(source: unknown, paths: string[][]): string | null {\n for (const path of paths) {\n const found = asString(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * Money stated in DECIMAL units (`12.9`) → integer cents.\n *\n * Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,\n * so truncation loses a cent on ordinary prices, always in the store's\n * disfavour.\n */\nexport function toCents(value: unknown): number | null {\n const numeric = typeof value === \"string\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(numeric * 100);\n}\n\n/** {@link firstString} for money. */\nexport function firstCents(source: unknown, paths: string[][]): number | null {\n for (const path of paths) {\n const found = toCents(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/** An ISO timestamp → a Date, or null when absent or unparseable. */\nfunction toDate(value: unknown): Date | null {\n const raw = asString(value);\n if (!raw) return null;\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n}\n\n/** {@link firstString} for timestamps. */\nexport function firstDate(source: unknown, paths: string[][]): Date | null {\n for (const path of paths) {\n const found = toDate(pick(source, ...path));\n if (found !== null) return found;\n }\n return null;\n}\n\n/**\n * Verify a lowercase-hex HMAC-SHA256 of the raw body (an optional `sha256=`\n * prefix tolerated), keyed by `secret`.\n *\n * Unsigned deliveries are refused whenever a secret is CONFIGURED; a store\n * that has not set one yet is accepted, and that state is visible on the\n * connection screen rather than silent. Compared in constant time over bytes:\n * an early-exit `===` on a hex digest leaks the prefix a forger already got\n * right, one request at a time.\n */\nexport function verifyHmacSha256Hex(rawBody: string, signature: string | null, secret: string | null): boolean {\n if (!secret) return true;\n if (!signature) return false;\n const expected = createHmac(\"sha256\", secret).update(rawBody, \"utf8\").digest(\"hex\");\n const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, \"\"), \"utf8\");\n const mine = Buffer.from(expected, \"utf8\");\n return given.length === mine.length && timingSafeEqual(given, mine);\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY,uBAAuB;AAarC,SAAS,KAAK,WAAoB,MAAyB;AAChE,MAAI,SAAkB;AACtB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;AAC1D,aAAU,OAAmC,GAAG;AAAA,EAClD;AACA,SAAO;AACT;AAPgB;AAUT,SAAS,SAAS,OAA+B;AACtD,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,GAAI,QAAO,MAAM,KAAK;AACxE,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO,OAAO,KAAK;AAC5E,SAAO;AACT;AAJgB;AAaT,SAAS,YAAY,QAAiB,OAAkC;AAC7E,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,SAAS,KAAK,QAAQ,GAAG,IAAI,CAAC;AAC5C,QAAI,UAAU,KAAM,QAAO;AAAA,EAC7B;AACA,SAAO;AACT;AANgB;AAeT,SAAS,QAAQ,OAA+B;AACrD,QAAM,UAAU,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;AAC5D,MAAI,OAAO,YAAY,YAAY,CAAC,OAAO,SAAS,OAAO,EAAG,QAAO;AACrE,SAAO,KAAK,MAAM,UAAU,GAAG;AACjC;AAJgB;AAOT,SAAS,WAAW,QAAiB,OAAkC;AAC5E,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,QAAQ,KAAK,QAAQ,GAAG,IAAI,CAAC;AAC3C,QAAI,UAAU,KAAM,QAAO;AAAA,EAC7B;AACA,SAAO;AACT;AANgB;AAShB,SAAS,OAAO,OAA6B;AAC3C,QAAM,MAAM,SAAS,KAAK;AAC1B,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,IAAI,KAAK,GAAG;AAC3B,SAAO,OAAO,MAAM,OAAO,QAAQ,CAAC,IAAI,OAAO;AACjD;AALS;AAQF,SAAS,UAAU,QAAiB,OAAgC;AACzE,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,OAAO,KAAK,QAAQ,GAAG,IAAI,CAAC;AAC1C,QAAI,UAAU,KAAM,QAAO;AAAA,EAC7B;AACA,SAAO;AACT;AANgB;AAkBT,SAAS,oBAAoB,SAAiB,WAA0B,QAAgC;AAC7G,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,WAAW,WAAW,UAAU,MAAM,EAAE,OAAO,SAAS,MAAM,EAAE,OAAO,KAAK;AAClF,QAAM,QAAQ,OAAO,KAAK,UAAU,KAAK,EAAE,YAAY,EAAE,QAAQ,aAAa,EAAE,GAAG,MAAM;AACzF,QAAM,OAAO,OAAO,KAAK,UAAU,MAAM;AACzC,SAAO,MAAM,WAAW,KAAK,UAAU,gBAAgB,OAAO,IAAI;AACpE;AAPgB;","names":[]}