@12-apps/marketplace 1.14.0 → 1.15.1

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 (47) hide show
  1. package/ADOPTING.md +120 -2
  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-R3BUW5PX.js → chunk-DJIMUEHT.js} +2 -2
  6. package/dist/{chunk-BD7DS3XM.js → chunk-E4XJXHUK.js} +20 -1
  7. package/dist/chunk-E4XJXHUK.js.map +1 -0
  8. package/dist/chunk-H2VQRD3B.js +16 -0
  9. package/dist/chunk-H2VQRD3B.js.map +1 -0
  10. package/dist/{chunk-MDXSVE7Q.js → chunk-TICWLBSA.js} +31 -12
  11. package/dist/chunk-TICWLBSA.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-DSRj7qnC.d.ts} +17 -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 +6 -5
  36. package/src/core/order-reasons.ts +46 -8
  37. package/src/core/order-types.ts +8 -0
  38. package/src/core/payload-read.ts +24 -0
  39. package/src/core/types.ts +111 -2
  40. package/src/ifood/normalize.ts +22 -5
  41. package/src/ifood/order-details.ts +120 -0
  42. package/src/index.ts +6 -0
  43. package/src/open-delivery/normalize.ts +9 -0
  44. package/dist/chunk-BD7DS3XM.js.map +0 -1
  45. package/dist/chunk-BNWRIR5J.js.map +0 -1
  46. package/dist/chunk-MDXSVE7Q.js.map +0 -1
  47. /package/dist/{chunk-R3BUW5PX.js.map → chunk-DJIMUEHT.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-DSRj7qnC.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-DJIMUEHT.js";
5
5
  import "../chunk-SGOTN5PX.js";
6
- import "../chunk-MDXSVE7Q.js";
6
+ import "../chunk-TICWLBSA.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-DSRj7qnC.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-DJIMUEHT.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-TICWLBSA.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.1",
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.",
@@ -1,4 +1,3 @@
1
- import { applyDeferredConfirmations } from "./marketplace-confirmed";
2
1
  import { enqueueOrderReasons } from "./order-reasons";
3
2
  import { markMarketplaceEventSeen } from "./integration";
4
3
  import { resolveSkus } from "./menu-links";
@@ -82,6 +81,7 @@ async function composeLines(
82
81
  note: line.note,
83
82
  subjectRef: mapping.get(line.externalSku)?.menuItemId ?? null,
84
83
  variationRef: mapping.get(line.externalSku)?.variationId ?? null,
84
+ ...(line.options ? { options: line.options } : {}),
85
85
  }));
86
86
  }
87
87
 
@@ -208,10 +208,11 @@ export async function ingestMarketplaceOrder(
208
208
  }
209
209
 
210
210
  ctx.ports.publishChanged(clientId);
211
- // After the commit: the order's own cancellation reasons are read by a job, and a
212
- // confirmation on the marketplace that outran this order is applied (FUT-5984, FUT-5653).
213
- await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider });
214
- if (!accepted) await applyDeferredConfirmations(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId });
211
+ // After the commit, in one job: the order's own cancellation reasons are read and,
212
+ // for an order nobody accepted yet, a confirmation on the marketplace that outran it
213
+ // is applied (FUT-5984, FUT-5653). Never inline: that read almost always finds
214
+ // nothing, and the expiry sweep applies what a late job has not yet.
215
+ await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider, deferredConfirmations: !accepted });
215
216
 
216
217
  return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
217
218
  }
@@ -1,5 +1,6 @@
1
1
  import type { CancellationReason, OrderCancellationReason } from "./adapter";
2
2
  import { readOutboundConnection } from "./integration";
3
+ import { applyDeferredConfirmations } from "./marketplace-confirmed";
3
4
  import type { EngineContext, MarketplaceDb } from "./ports";
4
5
  import { reasonsForOrder, storedReasons } from "./registry";
5
6
  import type { MarketplaceProvider } from "./types";
@@ -11,6 +12,13 @@ import type { MarketplaceProvider } from "./types";
11
12
  * kept on the acceptance row (`cancellation_reasons`) for the order's life.
12
13
  * The adapter's static list is the fallback while, or when, that read did not
13
14
  * land: a refusal is never held on the marketplace.
15
+ *
16
+ * The same job, for an order the store did not auto-accept, first applies a
17
+ * confirmation on the marketplace that arrived before the order (FUT-5653's
18
+ * C5). It runs here, a few seconds after the ingest, rather than inside it, so
19
+ * the ingest pays no inbox read that almost always finds nothing (FUT-5984).
20
+ * A job that is late or lost loses nothing: the expiry sweep applies a deferred
21
+ * confirmation before it expires the order (`applyOwedConfirmations`).
14
22
  */
15
23
 
16
24
  /** The wire name, `<namespace>.<blueprint>`. */
@@ -20,6 +28,8 @@ export const MARKETPLACE_CANCELLATION_REASONS_JOB = "marketplace.cancellation-re
20
28
  export interface CancellationReasonsJobPayload {
21
29
  clientId: string;
22
30
  orderId: string;
31
+ /** Set for an order not auto-accepted: apply a confirmation that outran it first. */
32
+ deferredConfirmations?: true;
23
33
  }
24
34
 
25
35
  /** What one run did. */
@@ -36,13 +46,22 @@ export class CancellationReasonsRetryError extends Error {
36
46
  }
37
47
  }
38
48
 
39
- /** Queue the read of a new order's reasons, when its marketplace lists them per order. Never throws. */
49
+ /**
50
+ * Queue the job after a new order's commit, when its marketplace lists reasons per
51
+ * order or (for an order not auto-accepted) confirms on its own side. Never throws.
52
+ */
40
53
  export async function enqueueOrderReasons(
41
54
  ctx: EngineContext,
42
- input: { clientId: string; orderId: string; provider: MarketplaceProvider },
55
+ input: { clientId: string; orderId: string; provider: MarketplaceProvider; deferredConfirmations?: boolean },
43
56
  ): Promise<void> {
44
- if (!ctx.registry.get(input.provider)?.orderCancellationReasons) return;
45
- const payload: CancellationReasonsJobPayload = { clientId: input.clientId, orderId: input.orderId };
57
+ const adapter = ctx.registry.get(input.provider);
58
+ const deferred = input.deferredConfirmations === true && adapter?.capabilities.marketplaceConfirms === true;
59
+ if (!adapter?.orderCancellationReasons && !deferred) return;
60
+ const payload: CancellationReasonsJobPayload = {
61
+ clientId: input.clientId,
62
+ orderId: input.orderId,
63
+ ...(deferred ? { deferredConfirmations: true as const } : {}),
64
+ };
46
65
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
47
66
  dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`,
48
67
  });
@@ -78,6 +97,28 @@ async function keep(
78
97
  return { kind: "done", count: reasons.length };
79
98
  }
80
99
 
100
+ /**
101
+ * Apply a confirmation deferred before this order. A failure is logged, never
102
+ * thrown: the reasons read still runs, and the expiry sweep applies it later.
103
+ */
104
+ async function applyEarlyConfirmations(ctx: EngineContext, clientId: string, row: ReasonsRow): Promise<void> {
105
+ try {
106
+ await applyDeferredConfirmations(ctx, { clientId, provider: row.provider, externalOrderId: row.externalOrderId });
107
+ } catch (error) {
108
+ ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${row.orderId}: a deferred confirmation was not applied; the expiry sweep applies it`, error);
109
+ }
110
+ }
111
+
112
+ /** The order's acceptance row; for an order not auto-accepted, its early confirmations applied first. */
113
+ async function loadOrder(ctx: EngineContext, db: MarketplaceDb, payload: CancellationReasonsJobPayload): Promise<ReasonsRow | null> {
114
+ const row = (await db.marketplaceAcceptance.findFirst({
115
+ where: { orderId: payload.orderId, clientId: payload.clientId },
116
+ select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true },
117
+ })) as ReasonsRow | null;
118
+ if (row && payload.deferredConfirmations) await applyEarlyConfirmations(ctx, payload.clientId, row);
119
+ return row;
120
+ }
121
+
81
122
  /** Run one read. Throws {@link CancellationReasonsRetryError} for a retryable answer before the last attempt. */
82
123
  export async function runCancellationReasons(
83
124
  ctx: EngineContext,
@@ -85,10 +126,7 @@ export async function runCancellationReasons(
85
126
  attempt: { attempt: number; maxAttempts: number },
86
127
  ): Promise<CancellationReasonsOutcome> {
87
128
  const db = await ctx.ports.db();
88
- const row = (await db.marketplaceAcceptance.findFirst({
89
- where: { orderId: payload.orderId, clientId: payload.clientId },
90
- select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true },
91
- })) as ReasonsRow | null;
129
+ const row = await loadOrder(ctx, db, payload);
92
130
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
93
131
  if (storedReasons(row.cancellationReasons) !== null) return { kind: "skipped", reason: "the order's reasons are already kept" };
94
132
  const read = ctx.registry.get(row.provider)?.orderCancellationReasons;
@@ -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