@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
package/ADOPTING.md CHANGED
@@ -517,7 +517,7 @@ Events `webhook-overview`, `webhook-best-practices`, `presence`,
517
517
  | A4 | an enqueue lost, or a job that gave up | — | the `marketplace.reconcile-inbox` pass also re-queues one job per (store, marketplace) with events still owed inside the window | same |
518
518
  | A5 | an event older than 8 h | — | never acknowledged (iFood keeps events 8 h) | same |
519
519
  | A6 | a marketplace whose adapter states no `acknowledgement` (99Food, Keeta, Rappi) | nothing | nothing | same |
520
- | R1 | an iFood order ingested | static reasons only, no call | `marketplace.cancellation-reasons` `{ clientId, orderId }` queued after the ingest's commit, key `…:<orderId>` | `__tests__/cancellation-reasons.test.ts` |
520
+ | R1 | an iFood order ingested | static reasons only, no call | `marketplace.cancellation-reasons` `{ clientId, orderId }` queued after the ingest's commit, key `…:<orderId>`; an order not auto-accepted adds `deferredConfirmations: true` (C5) | `__tests__/cancellation-reasons.test.ts` |
521
521
  | R2 | the job | none exists | `GET /order/v1.0/orders/{id}/cancellationReasons` with the connection's bearer; `{ reasons: [{ code, description }] }` (or a bare array) is kept on the order (`marketplace_acceptances.cancellation_reasons`) for its life; a second run calls nobody. `engine.orderReasons(clientId, orderId)` and `orderStates(…).cancellationReasons` answer it, each code labelled by the pack when the pack names it, else by iFood's own `description` | same |
522
522
  | R3 | the read fails | — | retried (3 attempts); the last leaves the column null and the order's reasons are the adapter's static list (the fallback) | same |
523
523
  | R4 | the store refuses with a code of the order's list | the code must be in the static list; the body was `{ reason: <label>, cancellationCode: <code> }` | accepted; the body is exactly `{ "reason": "<code>" }` (`cancellation`: `-d '{"reason": "503"}'`) | same |
@@ -546,7 +546,7 @@ Events `webhook-overview`, `webhook-best-practices`, `presence`,
546
546
  | C3 | an order accepted or stamped by CFM, past its deadline | expired | never expired: the expiry predicate adds `confirmed_at IS NULL` | same |
547
547
  | C4 | CFM of an ACCEPTED order whose confirm is stamped (our confirm's echo), or of a REJECTED or EXPIRED one | IGNORED | IGNORED, unchanged | same |
548
548
  | C9 | CFM of an ACCEPTED order whose confirm is not stamped (`confirmed_at` null, `confirm_failed_at` either way): a person's aceite raced the tablet's, or our confirm timed out but landed | IGNORED; the queued confirm is sent again (and a 4xx stamps `confirm_failed_at`, which S2 would then make stop every step) | `confirmed_at` stamped, no host call: the queued confirm skips ("already stamped"). With `confirm_failed_at` already set (the tablet confirmed, a person's aceite claimed it here, our duplicate confirm got a 4xx before the CFM landed) it is cleared too: iFood says the order IS confirmed, and leaving the failure would make S2 skip every later step of a confirmed order and the host show "não confirmou" (worse than `main`, where steps ignored the confirm) | same |
549
- | C5 | CFM before its order (the PLACED's fetch still running) | IGNORED, lost | DEFERRED (PENDING, `confirmed before its order`); when an adapter that `marketplaceConfirms` ingests that order, the deferred confirmation is applied right after the ingest's commit | same |
549
+ | C5 | CFM before its order (the PLACED's fetch still running) | IGNORED, lost | DEFERRED (PENDING, `confirmed before its order`); when an adapter that `marketplaceConfirms` ingests that order and does not auto-accept it, the deferred confirmation is applied by the `marketplace.cancellation-reasons` job, a few seconds after the ingest's commit (FUT-5984: the ingest itself reads no inbox row; C7 covers a late job) | same, `__tests__/deferred-confirmation-job.test.ts` |
550
550
  | C6 | CFM while the store's cancellation request stands | IGNORED | `confirmed_at` stamped (the request's answer or window ends the order, not the clock); no admit, no claim | same |
551
551
  | C7 | a deferred CFM still PENDING when the clock runs out | expired | the expiry sweep applies it first (one inbox read, only when rows lapsed), so the order is accepted, not expired | same |
552
552
  | C8 | an AWAITING order with no CFM past its deadline | expired | expired, unchanged | same |
@@ -571,6 +571,9 @@ Events `webhook-overview`, `webhook-best-practices`, `presence`,
571
571
  draw), never a bypass; a refused admit leaves the order for a person.
572
572
  - **The normal webhook path costs no new statement.** The answer status is an
573
573
  adapter constant; the acknowledge enqueue is a queue call.
574
+ - **A deferred confirmation now applies in the `marketplace.cancellation-reasons`
575
+ job, a few seconds after ingest**, never inside the ingest (FUT-5984: 1.14.0's
576
+ inline read added one statement to every iFood ingest not auto-accepted).
574
577
 
575
578
  ### 12.3 What is still ESTIMATED
576
579
 
@@ -627,3 +630,118 @@ Events `webhook-overview`, `webhook-best-practices`, `presence`,
627
630
  go with it; and until the refusal dialog reads the order's own reasons
628
631
  (step 5), a static code iFood did not list for that order is refused
629
632
  `INVALID_REASON` instead of being sent.
633
+
634
+ ## 13. Options, payment, fees and the buyer's document (FUT-5803)
635
+
636
+ An iFood order used to land without its complementos, its payment, its fees
637
+ besides delivery, the buyer's CPF/CNPJ and its eat-in types, and its lines
638
+ could sum to less than the receipt (a line was priced `unitPrice` only). Every
639
+ case below is a test in `src/ifood/__tests__/order-details.test.ts`, replayed
640
+ with the order shape of iFood's order-details guide
641
+ ("Detalhes do pedido" on iFood's developer portal; the page answered 404 and 403
642
+ from this environment on 2026-12-02, so the shape was not checked against it), that failed
643
+ on `main` (`3e8ce550`: 14 failed; the 3 "absent when unstated" cases passed and
644
+ stay pinned).
645
+
646
+ ### 13.1 The shape (additive, provider-neutral)
647
+
648
+ | field | meaning | iFood source | other adapters |
649
+ |---|---|---|---|
650
+ | `NormalizedOrderLine.options?: NormalizedLineOption[]` | each option the buyer chose: `externalCode`, `name`, `groupName`, `quantity` (for the WHOLE line), `unitPriceCents`, `totalCents` (always `unitPriceCents × quantity`). An option whose stated price does not divide by its count arrives as two rows of the same name (the floor, then one unit carrying the remainder), so the counts still sum to the stated count. Present only when there is at least one; then `unitPriceCents` is the item ALONE | `items[].options[]` (`name`, `externalCode`, `groupName`, `quantity`, `unitPrice`, `price`) | absent: Open Delivery (99Food, Keeta) and Rappi keep folding option prices into `unitPriceCents` and option names into `note`, as on `main` |
651
+ | `normalizedLineTotalCents(line)` | what a line costs: `unitPriceCents × quantity + Σ options[].totalCents`. Σ over the lines is the items' subtotal | iFood's `totalPrice` (`price + optionsPrice`) | equals `unitPriceCents × quantity` (no options) |
652
+ | `ResolvedOrderLine.options?` | the same options, handed to `order.create` with the resolved lines | — | absent |
653
+ | `NormalizedBuyer.document?` | the CPF or CNPJ for the invoice, digits only | `customer.documentNumber`, else `customer.document` | Open Delivery's `customer.documentNumber` |
654
+ | `NormalizedBuyer.phoneLocalizer?` | the extension that reaches the buyer through the marketplace's masked number | `customer.phone.localizer` | absent |
655
+ | `MarketplaceOrderType` gains `DINE_IN` and `INDOOR` | eaten at the store; ordered from inside it (a table) | `orderType` | unchanged (Open Delivery's `INDOOR` still reads null) |
656
+ | `NormalizedMarketplaceOrder.payments?: NormalizedPayments` | `prepaidCents`, `pendingCents`, `methods[]`: `method` (`CREDIT`, `DEBIT`, `MEAL_VOUCHER`, `FOOD_VOUCHER`, `PIX`, `CASH`, `DIGITAL_WALLET`, else `OTHER`), `statedMethod` (verbatim), `prepaid` (true online, false at the door, null unstated), `valueCents`, `cardBrand`, `changeForCents` (cash: the note the buyer pays with) | `payments.prepaid`, `payments.pending`, `payments.methods[]` (`method`, `type` ONLINE/OFFLINE, else `prepaid`, `value`, `card.brand`, `cash.changeFor`) | absent |
657
+ | `NormalizedMarketplaceOrder.additionalFees?: NormalizedOrderFee[]` | fees besides delivery, inside `totalCents`: `kind` (verbatim), `cents`, `name?` | top-level `additionalFees[]` (`type`, `value`, `description`) | absent |
658
+
659
+ Every new field is optional, and an unstated one is ABSENT (not null): a
660
+ payload that states none of these parts normalizes deep-equal to what `main`
661
+ produced. A payload that states them does not, and a host that deep-compares
662
+ normalized orders sees each of these:
663
+
664
+ - an iFood line with `options[]` gains `options`;
665
+ - an iFood order gains `payments` when it states `payments` (every real order
666
+ does), and `additionalFees` when it states `additionalFees[]`;
667
+ - an iFood buyer gains `document` (`customer.documentNumber` or `document`)
668
+ and `phoneLocalizer` (`customer.phone.localizer`);
669
+ - an iFood `orderType` of `DINE_IN` or `INDOOR` reads as that value, where
670
+ `main` read null;
671
+ - an Open Delivery buyer (99Food, Keeta) gains `document` when the order
672
+ states `customer.documentNumber`.
673
+
674
+ ### 13.2 The cases
675
+
676
+ | id | order | `main` | this release |
677
+ |---|---|---|---|
678
+ | O1 | a pizza with "Borda recheada" R$ 8, "Bacon extra" 2 × R$ 2, "Sem cebola" R$ 0 | options dropped | each option on the line, a free one included (the kitchen reads it) |
679
+ | O2 | the same order | lines sum R$ 57 against a subtotal of R$ 69 | Σ `normalizedLineTotalCents` = `subtotalCents`, and subtotal + delivery fee = total |
680
+ | O3 | no `total` stated | total = Σ unit × quantity, options lost | total = Σ line totals, options included |
681
+ | O4 | an option whose `price` is not `unitPrice × quantity` (3 × Borda at R$ 10.00) | — | the stated `price` is the total, split over the stated count: 2 × 3.33 + 1 × 3.34, still 3 × Borda; one row at `price / quantity` when it divides (O4b) |
682
+ | O6 | 2 × Pizza, each with a Borda (option `quantity: 2`, `price: 16`) | options dropped, line R$ 90 against a `totalPrice` of R$ 106 | line R$ 90 + 2 × Borda R$ 16 = R$ 106; the lines add up to the subtotal |
683
+ | O5 | the order ingested | — | `order.create` receives the options on the resolved lines; a line with none carries no key |
684
+ | P1 | online credit card | dropped | `CREDIT`, prepaid, brand, value |
685
+ | P2 | cash at the door with change for R$ 100 | dropped | `CASH`, not prepaid, `changeForCents: 10000`, `pendingCents` the whole total |
686
+ | P3 | debit at the door, a gift card online | dropped | `DEBIT` not prepaid with its brand; `OTHER` with `statedMethod: "GIFT_CARD"` |
687
+ | P4 | any stated payment | — | Σ `methods[].valueCents` = `totalCents` = prepaid + pending, as iFood states them |
688
+ | F1 | a small-order fee R$ 2.99 | dropped (inside the total, nowhere else) | `additionalFees: [{ kind: "SMALL_ORDER_FEE", cents: 299, name }]`; lines + delivery fee + fees = total |
689
+ | B1/B2 | a CPF as `documentNumber`, a CNPJ as `document` | dropped | `buyer.document`, digits only; the phone's localizer in `buyer.phoneLocalizer` |
690
+ | T1/T2 | `INDOOR`, `DINE_IN` | `orderType: null` | `orderType: "INDOOR"` / `"DINE_IN"`, no deliverer, no address |
691
+
692
+ ### 13.3 What is still ESTIMATED
693
+
694
+ - iFood's option `quantity`: read as the count for the whole line. The money
695
+ is right either way (the option's stated `price` is used), but if iFood's
696
+ count is per unit of the item, a line of 2 shows "1 × Borda" where the
697
+ kitchen makes two. Test O6 pins the whole-line reading. Confirming it on a
698
+ real order with an item quantity above 1 is a gate of the HOST bump (its
699
+ step 1 puts the count on the kitchen ticket), not of this release.
700
+ - An option's nested `customizations[]` (a sub-choice inside an option) are
701
+ not read: their price is assumed inside the option's `price`.
702
+ - An item stating `optionsPrice` with no `options[]` listed keeps only its
703
+ `unitPrice × quantity`; the stated order total is unaffected.
704
+ - `additionalFees[].liabilities` (who keeps the fee) is not read.
705
+ - A tax id stated as a NUMBER lost its leading zeros on the wire; it is padded
706
+ back to 11 digits (CPF), or 14 (CNPJ) when longer (test B4). A CNPJ sent as
707
+ a number with three or more leading zeros has 11 digits or fewer and reads
708
+ as a CPF; a bare number cannot tell the two apart. Both providers document
709
+ the field as a string.
710
+
711
+ ### 13.4 What the host binds on the bump
712
+
713
+ The engine adds no table and no migration: everything travels on the order and
714
+ lines `order.create` already receives. Where a host keeps it is the host's
715
+ call; for a host with a line-extras model and a door-payment model (the origin
716
+ host), the mapping is:
717
+
718
+ 1. **Options → the line's extras.** For each `options[]` entry write one extra
719
+ row (an option split in two rows, O4, is two extras of the same name) (name snapshot = `name`, unit price = `unitPriceCents`,
720
+ quantity = `quantity`, no catalogue id): every reader that already shows a
721
+ storefront line's extras (the order board card, the kitchen ticket, the
722
+ fiscal and till sums: `unit × quantity + Σ extra unit × extra quantity`)
723
+ then shows and sums them unchanged. Keep the line's own unit price as
724
+ `unitPriceCents` (the item alone). A host that ignores `options` keeps
725
+ `main`'s behaviour, lines short by the options' price.
726
+ 2. **The buyer's document** goes where the host keeps a buyer tax id for the
727
+ invoice (encrypted at rest like any CPF), never in a log.
728
+ 3. **Payment.** `payments.pendingCents > 0` is money the store's courier or
729
+ counter still collects: draw the pedido's payment line from the pending
730
+ method (`CASH` with `changeForCents` reads as cash with change for that
731
+ amount, the vocabulary a door payment already has; `CREDIT`, `DEBIT`,
732
+ `PIX`, `MEAL_VOUCHER`, `FOOD_VOUCHER` map one to one; `DIGITAL_WALLET` and
733
+ `OTHER` read as the marketplace's own word). Whether such a pedido is
734
+ still born PAID is the host's decision; a prepaid order (`pendingCents`
735
+ 0) reads "Pago no <marketplace>" with the method and brand.
736
+ 4. **Additional fees** are inside `totalCents` already. A host whose order-fee
737
+ table has a closed kind list widens it (an additive CHECK change, a host
738
+ migration) or shows them from the order's own record; summing them again
739
+ would charge them twice.
740
+ 5. **Order type.** `DINE_IN` / `INDOOR` are not deliveries: route them like a
741
+ counter or table order (no delivery run, no address), never by the
742
+ `deliveredBy` fallback that treats an unknown type as a delivery.
743
+ 6. **TypeScript-visible additions** (a minor): the optional fields above;
744
+ `MarketplaceOrderType` widens (an exhaustive switch adds two cases); new
745
+ exports `normalizedLineTotalCents`, `NormalizedLineOption`,
746
+ `NormalizedPayments`, `NormalizedPaymentMethod`, `MarketplacePaymentMethod`,
747
+ `NormalizedOrderFee`.
@@ -1,5 +1,5 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-szxo9ohc.js';
2
- import { O as OpenDeliveryApiBaseUrls } from '../client-CaZiG7Lw.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CjVdMhZ2.js';
2
+ import { O as OpenDeliveryApiBaseUrls } from '../client-DgzCkl8u.js';
3
3
 
4
4
  /**
5
5
  * The words the 99Food adapter needs from its host, and nothing else.
@@ -12,9 +12,9 @@ import {
12
12
  openDeliveryStatus,
13
13
  openDeliverySwitchAvailability,
14
14
  verifyOpenDeliverySignature
15
- } from "../chunk-BNWRIR5J.js";
15
+ } from "../chunk-TRUK5ZBE.js";
16
16
  import "../chunk-M2V4RFMA.js";
17
- import "../chunk-BD7DS3XM.js";
17
+ import "../chunk-E4XJXHUK.js";
18
18
  import "../chunk-BTKVZAJI.js";
19
19
  import {
20
20
  __name
@@ -199,13 +199,53 @@ interface NormalizedOrderLine {
199
199
  unitPriceCents: number;
200
200
  /** The buyer's note on this line, when they left one. */
201
201
  note: string | null;
202
+ /**
203
+ * OPTIONAL (FUT-5803). The options the buyer chose on this line (a
204
+ * complemento: "borda recheada", "sem cebola"), each priced on its own. When
205
+ * present, `unitPriceCents` is the item ALONE and the line costs
206
+ * `unitPriceCents × quantity + Σ options[].totalCents`
207
+ * ({@link normalizedLineTotalCents}). Absent: none is itemized. Open
208
+ * Delivery and Rappi then fold the options' price into `unitPriceCents`;
209
+ * iFood does not, so an iFood item that states `optionsPrice` but lists no
210
+ * `options[]` is priced as the item alone. Never an empty array.
211
+ */
212
+ options?: NormalizedLineOption[];
202
213
  }
214
+ /** One option on an order line, as the marketplace priced it (FUT-5803). */
215
+ interface NormalizedLineOption {
216
+ /** The marketplace's own code for the option, when it gives one. */
217
+ externalCode: string | null;
218
+ name: string;
219
+ /** The group the marketplace shows it under ("Borda", "Adicionais"), when it says. */
220
+ groupName: string | null;
221
+ /** How many, for the WHOLE line (never per unit of it). */
222
+ quantity: number;
223
+ unitPriceCents: number;
224
+ /**
225
+ * Always exactly `unitPriceCents × quantity`. A stated price that does not
226
+ * divide by its count arrives as two rows of the same option (the floor,
227
+ * then one unit carrying the remainder), whose counts sum to the stated one.
228
+ */
229
+ totalCents: number;
230
+ }
231
+ /** What a line costs: the item times its quantity, plus each of its options. */
232
+ declare function normalizedLineTotalCents(line: Pick<NormalizedOrderLine, "unitPriceCents" | "quantity" | "options">): number;
203
233
  /** The buyer, as much of them as the marketplace discloses. */
204
234
  interface NormalizedBuyer {
205
235
  /** The marketplace's own stable id for this customer, when it gives one. */
206
236
  externalId: string | null;
207
237
  name: string | null;
208
238
  phone: string | null;
239
+ /**
240
+ * OPTIONAL (FUT-5803). The buyer's tax id for the invoice (a CPF or a CNPJ),
241
+ * digits only. Absent: the marketplace states none.
242
+ */
243
+ document?: string | null;
244
+ /**
245
+ * OPTIONAL (FUT-5803). The extension that reaches the buyer through the
246
+ * marketplace's masked number in `phone` (iFood's `phone.localizer`). Absent: none.
247
+ */
248
+ phoneLocalizer?: string | null;
209
249
  }
210
250
  /** Where a delivery goes, as much of it as the marketplace states. */
211
251
  interface NormalizedAddress {
@@ -219,8 +259,12 @@ interface NormalizedAddress {
219
259
  city: string | null;
220
260
  state: string | null;
221
261
  }
222
- /** How the order reaches the buyer: brought to the door, or collected. */
223
- type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
262
+ /**
263
+ * How the order reaches the buyer: brought to the door (`DELIVERY`), collected
264
+ * (`TAKEOUT`), eaten at the store (`DINE_IN`), or ordered from inside it, at a
265
+ * table or a spot the buyer names (`INDOOR`, FUT-5803).
266
+ */
267
+ type MarketplaceOrderType = "DELIVERY" | "TAKEOUT" | "DINE_IN" | "INDOOR";
224
268
  /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
225
269
  type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
226
270
  /** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */
@@ -233,6 +277,44 @@ interface NormalizedOrderDiscount {
233
277
  /** What the marketplace called the campaign, when it says. */
234
278
  name?: string;
235
279
  }
280
+ /**
281
+ * How a buyer paid, as a closed set a host has words for. `OTHER`: stated,
282
+ * and none of these (the marketplace's own word is in `statedMethod`).
283
+ */
284
+ type MarketplacePaymentMethod = "CREDIT" | "DEBIT" | "MEAL_VOUCHER" | "FOOD_VOUCHER" | "PIX" | "CASH" | "DIGITAL_WALLET" | "OTHER";
285
+ /** One way the buyer pays an order (FUT-5803). */
286
+ interface NormalizedPaymentMethod {
287
+ method: MarketplacePaymentMethod;
288
+ /** The marketplace's own word for the method, verbatim; null when it states none. */
289
+ statedMethod: string | null;
290
+ /**
291
+ * True: already paid on the marketplace. False: to collect from the buyer at
292
+ * the door or the counter. Null: unstated.
293
+ */
294
+ prepaid: boolean | null;
295
+ /** What this method pays, in the smallest currency unit. */
296
+ valueCents: number;
297
+ /** The card's brand as the marketplace names it ("VISA"), when it does. */
298
+ cardBrand: string | null;
299
+ /** On cash: the note the buyer pays with, so the courier brings the change. Null: no change asked, or unstated. */
300
+ changeForCents: number | null;
301
+ }
302
+ /** The order's payment, as the marketplace states it (FUT-5803). */
303
+ interface NormalizedPayments {
304
+ /** What the marketplace already collected. Null: unstated. */
305
+ prepaidCents: number | null;
306
+ /** What is still to collect from the buyer. Null: unstated. */
307
+ pendingCents: number | null;
308
+ methods: NormalizedPaymentMethod[];
309
+ }
310
+ /** A fee the marketplace charged the buyer besides delivery (FUT-5803), such as a small-order fee. */
311
+ interface NormalizedOrderFee {
312
+ /** The marketplace's own kind, verbatim (`SMALL_ORDER_FEE`). */
313
+ kind: string;
314
+ cents: number;
315
+ /** What the marketplace called it, when it says. */
316
+ name?: string;
317
+ }
236
318
  /** An incoming marketplace order, normalized. */
237
319
  interface NormalizedMarketplaceOrder {
238
320
  provider: MarketplaceProvider;
@@ -287,6 +369,17 @@ interface NormalizedMarketplaceOrder {
287
369
  * the bag itself).
288
370
  */
289
371
  pickupCode?: string | null;
372
+ /**
373
+ * OPTIONAL (FUT-5803). How the buyer pays: each method, what is prepaid and
374
+ * what is still to collect, and the change a cash buyer asks for. Absent:
375
+ * the marketplace states none.
376
+ */
377
+ payments?: NormalizedPayments;
378
+ /**
379
+ * OPTIONAL (FUT-5803). The fees besides delivery, inside `totalCents`.
380
+ * Absent is "did not say"; an empty array is "none".
381
+ */
382
+ additionalFees?: NormalizedOrderFee[];
290
383
  }
291
384
  /**
292
385
  * What an event says about the STORE's own cancellation request: `CONFIRMED`
@@ -1193,4 +1286,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
1193
1286
  /** A call that never got an answer is a retry, with the reason a log can read. */
1194
1287
  declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
1195
1288
 
1196
- export { type MarketplaceCapabilities as $, type AdapterCallContext as A, type CatalogueReadResult as B, type CatalogueMenuEntry as C, type CatalogueReadWarning as D, type CatalogueReadWarningCode as E, type FetchOrderResult as F, type CatalogueSnapshot as G, type CatalogueSnapshotCategory as H, type CatalogueSnapshotItem as I, type CatalogueSnapshotOption as J, type CatalogueSnapshotOptionGroup as K, type CatalogueStoredImage as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CatalogueWarningCode as Q, type CourierTrackingCallResult as R, type StorePauseRequest as S, type CourierTrackingResult as T, type LinkCallContext as U, type LinkCode as V, type LinkGrant as W, type LinkResult as X, type LinkedMerchant as Y, type MarketplaceAcknowledgement as Z, type MarketplaceAppCredentialsPort as _, type NormalizedMarketplaceOrder as a, type MarketplaceCatalogue as a0, type MarketplaceCourier as a1, type MarketplaceCourierAnswer as a2, type MarketplaceCourierEngine as a3, type MarketplaceCourierFacts as a4, type MarketplaceCourierStep as a5, type MarketplaceCourierTracking as a6, type MarketplaceCourierVehicle as a7, type MarketplaceCredentials as a8, type MarketplaceDeliveredBy as a9, type MarketplaceDiscountSponsor as aa, type MarketplaceHttp as ab, type MarketplaceHttpRequest as ac, type MarketplaceHttpResponse as ad, type MarketplaceLifecycle as ae, type MarketplaceLinkAttemptDelegate as af, type MarketplaceOrderType as ag, type NormalizedAddress as ah, type NormalizedBuyer as ai, type NormalizedOrderDiscount as aj, type NormalizedOrderLine as ak, type OrderCancellationReason as al, type OrderCancellationReasonsResult as am, type OutboundOrderRef as an, PROVIDER_ID_PATTERN as ao, type PickupCodeCallResult as ap, type PickupCodeValidation as aq, type PresenceProbe as ar, type StatusFacts as as, type StatusStep as at, type ValidatePickupCodeInput as au, answered as av, centsFromMajor as aw, outboundResultOf as ax, tokenGrantResultOf as ay, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type MarketplaceCourierApi as h, type NormalizedCourierEvent as i, type StorePauseResult as j, type StorePauseRef as k, type MarketplaceProvider as l, type CancellationReason as m, type AdapterGrant as n, type AdapterTokenCache as o, type CancellationOutcome as p, type CancellationRequestInput as q, type CatalogueCallContext as r, type CatalogueFailure as s, type CatalogueImage as t, type CatalogueItem as u, type CatalogueItemRef as v, type CataloguePublishResult as w, type CatalogueReadContext as x, type CatalogueReadNotice as y, type CatalogueReadRefusalCode as z };
1289
+ export { type MarketplaceCapabilities as $, type AdapterCallContext as A, type CatalogueReadResult as B, type CatalogueMenuEntry as C, type CatalogueReadWarning as D, type CatalogueReadWarningCode as E, type FetchOrderResult as F, type CatalogueSnapshot as G, type CatalogueSnapshotCategory as H, type CatalogueSnapshotItem as I, type CatalogueSnapshotOption as J, type CatalogueSnapshotOptionGroup as K, type CatalogueStoredImage as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CatalogueWarningCode as Q, type CourierTrackingCallResult as R, type StorePauseRequest as S, type CourierTrackingResult as T, type LinkCallContext as U, type LinkCode as V, type LinkGrant as W, type LinkResult as X, type LinkedMerchant as Y, type MarketplaceAcknowledgement as Z, type MarketplaceAppCredentialsPort as _, type NormalizedMarketplaceOrder as a, type MarketplaceCatalogue as a0, type MarketplaceCourier as a1, type MarketplaceCourierAnswer as a2, type MarketplaceCourierEngine as a3, type MarketplaceCourierFacts as a4, type MarketplaceCourierStep as a5, type MarketplaceCourierTracking as a6, type MarketplaceCourierVehicle as a7, type MarketplaceCredentials as a8, type MarketplaceDeliveredBy as a9, answered as aA, centsFromMajor as aB, normalizedLineTotalCents as aC, outboundResultOf as aD, tokenGrantResultOf as aE, type MarketplaceDiscountSponsor as aa, type MarketplaceHttp as ab, type MarketplaceHttpRequest as ac, type MarketplaceHttpResponse as ad, type MarketplaceLifecycle as ae, type MarketplaceLinkAttemptDelegate as af, type MarketplaceOrderType as ag, type MarketplacePaymentMethod as ah, type NormalizedAddress as ai, type NormalizedBuyer as aj, type NormalizedLineOption as ak, type NormalizedOrderDiscount as al, type NormalizedOrderFee as am, type NormalizedOrderLine as an, type NormalizedPaymentMethod as ao, type NormalizedPayments as ap, type OrderCancellationReason as aq, type OrderCancellationReasonsResult as ar, type OutboundOrderRef as as, PROVIDER_ID_PATTERN as at, type PickupCodeCallResult as au, type PickupCodeValidation as av, type PresenceProbe as aw, type StatusFacts as ax, type StatusStep as ay, type ValidatePickupCodeInput as az, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type MarketplaceCourierApi as h, type NormalizedCourierEvent as i, type StorePauseResult as j, type StorePauseRef as k, type MarketplaceProvider as l, type CancellationReason as m, type AdapterGrant as n, type AdapterTokenCache as o, type CancellationOutcome as p, type CancellationRequestInput as q, type CatalogueCallContext as r, type CatalogueFailure as s, type CatalogueImage as t, type CatalogueItem as u, type CatalogueItemRef as v, type CataloguePublishResult as w, type CatalogueReadContext as x, type CatalogueReadNotice as y, type CatalogueReadRefusalCode as z };
@@ -20,7 +20,7 @@ import {
20
20
  CatalogueRetryError,
21
21
  FetchOrderRetryError,
22
22
  OutboundRetryError
23
- } from "./chunk-MDXSVE7Q.js";
23
+ } from "./chunk-TICWLBSA.js";
24
24
  import {
25
25
  __name
26
26
  } from "./chunk-7QVYU63E.js";
@@ -698,4 +698,4 @@ export {
698
698
  MARKETPLACE_JOBS,
699
699
  createApiMarketplace
700
700
  };
701
- //# sourceMappingURL=chunk-R3BUW5PX.js.map
701
+ //# sourceMappingURL=chunk-DJIMUEHT.js.map
@@ -41,6 +41,24 @@ function firstCents(source, paths) {
41
41
  return null;
42
42
  }
43
43
  __name(firstCents, "firstCents");
44
+ function toTaxId(value) {
45
+ if (typeof value === "number") {
46
+ if (!Number.isSafeInteger(value) || value <= 0) return null;
47
+ const digits2 = String(value);
48
+ return digits2.padStart(digits2.length <= 11 ? 11 : 14, "0");
49
+ }
50
+ const digits = asString(value)?.replace(/\D/g, "");
51
+ return digits ? digits : null;
52
+ }
53
+ __name(toTaxId, "toTaxId");
54
+ function firstTaxId(source, paths) {
55
+ for (const path of paths) {
56
+ const found = toTaxId(pick(source, ...path));
57
+ if (found !== null) return found;
58
+ }
59
+ return null;
60
+ }
61
+ __name(firstTaxId, "firstTaxId");
44
62
  function toDate(value) {
45
63
  const raw = asString(value);
46
64
  if (!raw) return null;
@@ -72,7 +90,8 @@ export {
72
90
  firstString,
73
91
  toCents,
74
92
  firstCents,
93
+ firstTaxId,
75
94
  firstDate,
76
95
  verifyHmacSha256Hex
77
96
  };
78
- //# sourceMappingURL=chunk-BD7DS3XM.js.map
97
+ //# sourceMappingURL=chunk-E4XJXHUK.js.map
@@ -0,0 +1 @@
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/**\n * A CPF or CNPJ → its digits, or null. Text keeps its digits (`123.456.789-09`).\n * A number lost its leading zeros on the way, so it is padded back to a CPF's\n * 11 digits, or a CNPJ's 14 when it is longer than a CPF.\n */\nfunction toTaxId(value: unknown): string | null {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value <= 0) return null;\n const digits = String(value);\n return digits.padStart(digits.length <= 11 ? 11 : 14, \"0\");\n }\n const digits = asString(value)?.replace(/\\D/g, \"\");\n return digits ? digits : null;\n}\n\n/** {@link firstString} for a tax id (CPF or CNPJ), digits only. */\nexport function firstTaxId(source: unknown, paths: string[][]): string | null {\n for (const path of paths) {\n const found = toTaxId(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;AAahB,SAAS,QAAQ,OAA+B;AAC9C,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,EAAG,QAAO;AACvD,UAAMA,UAAS,OAAO,KAAK;AAC3B,WAAOA,QAAO,SAASA,QAAO,UAAU,KAAK,KAAK,IAAI,GAAG;AAAA,EAC3D;AACA,QAAM,SAAS,SAAS,KAAK,GAAG,QAAQ,OAAO,EAAE;AACjD,SAAO,SAAS,SAAS;AAC3B;AARS;AAWF,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":["digits"]}
@@ -0,0 +1,16 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/core/types.ts
6
+ var PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;
7
+ function normalizedLineTotalCents(line) {
8
+ return line.unitPriceCents * line.quantity + (line.options ?? []).reduce((sum, option) => sum + option.totalCents, 0);
9
+ }
10
+ __name(normalizedLineTotalCents, "normalizedLineTotalCents");
11
+
12
+ export {
13
+ PROVIDER_ID_PATTERN,
14
+ normalizedLineTotalCents
15
+ };
16
+ //# sourceMappingURL=chunk-H2VQRD3B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/types.ts"],"sourcesContent":["/**\n * The canonical shape every marketplace adapter normalizes INTO.\n *\n * This type is the seam. The engine below it knows no marketplace by name: a\n * marketplace is an adapter registered with the engine (`./adapter`), and the\n * provider id is whatever that adapter says it is. A second marketplace is a\n * second adapter, never a second pipeline, a second acceptance clock or a\n * second idea of what an order is.\n *\n * Deliberately POORER than any marketplace's own payload. Everything a store\n * operates on is here; everything else stays in the inbox row's raw `payload`,\n * which is where a normalization bug is reconstructed from.\n */\n\n/**\n * A marketplace's id, as its adapter declares it (`\"IFOOD\"`). Uppercase\n * letters, digits and underscores; the migration's CHECK holds the same shape.\n * A string rather than a closed union, because the set of marketplaces is the\n * set of registered adapters, and a union would make a new one a code change\n * in the engine.\n */\nexport type MarketplaceProvider = string;\n\n/** The shape a provider id must have. Shared by the registry and the CHECK. */\nexport const PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\n\n/** One line of an incoming order, before it is resolved against the catalog. */\nexport interface NormalizedOrderLine {\n /** The marketplace's own SKU — the key the SKU map is matched on. */\n externalSku: string;\n /** What the marketplace called it. Snapshotted, and the fallback line text. */\n name: string;\n quantity: number;\n /**\n * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A\n * marketplace's menu carries its own prices, and the buyer's receipt is the\n * marketplace's one: re-pricing from the host's catalog would produce a\n * total nobody was charged.\n */\n unitPriceCents: number;\n /** The buyer's note on this line, when they left one. */\n note: string | null;\n /**\n * OPTIONAL (FUT-5803). The options the buyer chose on this line (a\n * complemento: \"borda recheada\", \"sem cebola\"), each priced on its own. When\n * present, `unitPriceCents` is the item ALONE and the line costs\n * `unitPriceCents × quantity + Σ options[].totalCents`\n * ({@link normalizedLineTotalCents}). Absent: none is itemized. Open\n * Delivery and Rappi then fold the options' price into `unitPriceCents`;\n * iFood does not, so an iFood item that states `optionsPrice` but lists no\n * `options[]` is priced as the item alone. Never an empty array.\n */\n options?: NormalizedLineOption[];\n}\n\n/** One option on an order line, as the marketplace priced it (FUT-5803). */\nexport interface NormalizedLineOption {\n /** The marketplace's own code for the option, when it gives one. */\n externalCode: string | null;\n name: string;\n /** The group the marketplace shows it under (\"Borda\", \"Adicionais\"), when it says. */\n groupName: string | null;\n /** How many, for the WHOLE line (never per unit of it). */\n quantity: number;\n unitPriceCents: number;\n /**\n * Always exactly `unitPriceCents × quantity`. A stated price that does not\n * divide by its count arrives as two rows of the same option (the floor,\n * then one unit carrying the remainder), whose counts sum to the stated one.\n */\n totalCents: number;\n}\n\n/** What a line costs: the item times its quantity, plus each of its options. */\nexport function normalizedLineTotalCents(line: Pick<NormalizedOrderLine, \"unitPriceCents\" | \"quantity\" | \"options\">): number {\n return line.unitPriceCents * line.quantity + (line.options ?? []).reduce((sum, option) => sum + option.totalCents, 0);\n}\n\n/** The buyer, as much of them as the marketplace discloses. */\nexport interface NormalizedBuyer {\n /** The marketplace's own stable id for this customer, when it gives one. */\n externalId: string | null;\n name: string | null;\n phone: string | null;\n /**\n * OPTIONAL (FUT-5803). The buyer's tax id for the invoice (a CPF or a CNPJ),\n * digits only. Absent: the marketplace states none.\n */\n document?: string | null;\n /**\n * OPTIONAL (FUT-5803). The extension that reaches the buyer through the\n * marketplace's masked number in `phone` (iFood's `phone.localizer`). Absent: none.\n */\n phoneLocalizer?: string | null;\n}\n\n/** Where a delivery goes, as much of it as the marketplace states. */\nexport interface NormalizedAddress {\n street: string;\n number: string;\n neighborhood: string;\n complement: string | null;\n /** The sentence that finds the door. */\n reference: string | null;\n postalCode: string | null;\n city: string | null;\n state: string | null;\n}\n\n/**\n * How the order reaches the buyer: brought to the door (`DELIVERY`), collected\n * (`TAKEOUT`), eaten at the store (`DINE_IN`), or ordered from inside it, at a\n * table or a spot the buyer names (`INDOOR`, FUT-5803).\n */\nexport type MarketplaceOrderType = \"DELIVERY\" | \"TAKEOUT\" | \"DINE_IN\" | \"INDOOR\";\n\n/** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */\nexport type MarketplaceDeliveredBy = \"MERCHANT\" | \"MARKETPLACE\";\n\n/** WHO pays for a discount: the store, the marketplace's own campaign, or someone else (a card issuer, a voucher). */\nexport type MarketplaceDiscountSponsor = \"MERCHANT\" | \"MARKETPLACE\" | \"OTHER\";\n\n/** One discount on an order, as the part one sponsor pays. */\nexport interface NormalizedOrderDiscount {\n /** The discount's value in the smallest currency unit. */\n cents: number;\n sponsor: MarketplaceDiscountSponsor;\n /** What the marketplace called the campaign, when it says. */\n name?: string;\n}\n\n/**\n * How a buyer paid, as a closed set a host has words for. `OTHER`: stated,\n * and none of these (the marketplace's own word is in `statedMethod`).\n */\nexport type MarketplacePaymentMethod =\n | \"CREDIT\"\n | \"DEBIT\"\n | \"MEAL_VOUCHER\"\n | \"FOOD_VOUCHER\"\n | \"PIX\"\n | \"CASH\"\n | \"DIGITAL_WALLET\"\n | \"OTHER\";\n\n/** One way the buyer pays an order (FUT-5803). */\nexport interface NormalizedPaymentMethod {\n method: MarketplacePaymentMethod;\n /** The marketplace's own word for the method, verbatim; null when it states none. */\n statedMethod: string | null;\n /**\n * True: already paid on the marketplace. False: to collect from the buyer at\n * the door or the counter. Null: unstated.\n */\n prepaid: boolean | null;\n /** What this method pays, in the smallest currency unit. */\n valueCents: number;\n /** The card's brand as the marketplace names it (\"VISA\"), when it does. */\n cardBrand: string | null;\n /** On cash: the note the buyer pays with, so the courier brings the change. Null: no change asked, or unstated. */\n changeForCents: number | null;\n}\n\n/** The order's payment, as the marketplace states it (FUT-5803). */\nexport interface NormalizedPayments {\n /** What the marketplace already collected. Null: unstated. */\n prepaidCents: number | null;\n /** What is still to collect from the buyer. Null: unstated. */\n pendingCents: number | null;\n methods: NormalizedPaymentMethod[];\n}\n\n/** A fee the marketplace charged the buyer besides delivery (FUT-5803), such as a small-order fee. */\nexport interface NormalizedOrderFee {\n /** The marketplace's own kind, verbatim (`SMALL_ORDER_FEE`). */\n kind: string;\n cents: number;\n /** What the marketplace called it, when it says. */\n name?: string;\n}\n\n/** An incoming marketplace order, normalized. */\nexport interface NormalizedMarketplaceOrder {\n provider: MarketplaceProvider;\n /** The marketplace's order id — THE idempotency key for the whole pipeline. */\n externalOrderId: string;\n /** The short code the courier and the buyer say out loud. */\n externalDisplayId: string | null;\n buyer: NormalizedBuyer;\n lines: NormalizedOrderLine[];\n /**\n * What the buyer paid, gross. NOT derived from the lines when the\n * marketplace states it: its total carries fees, promotions and rounding the\n * line sum does not, and the number that must match the receipt is this one.\n */\n totalCents: number;\n /** The marketplace's cut, when it states one. NULL is \"did not say\", not 0. */\n commissionCents: number | null;\n /** The marketplace's own promise to the buyer. */\n deliveryDueAt: Date | null;\n /** When the marketplace says the order was placed. */\n placedAt: Date;\n /** Null when the payload does not say. */\n orderType?: MarketplaceOrderType | null;\n /** Null on a take-out and when unstated. */\n deliveredBy?: MarketplaceDeliveredBy | null;\n /** Null on a take-out and when unstated. */\n deliveryAddress?: NormalizedAddress | null;\n /**\n * OPTIONAL. The delivery fee the buyer was charged, in the smallest currency\n * unit. 0 is a free delivery; null or absent is \"did not say\".\n */\n deliveryFeeCents?: number | null;\n /** OPTIONAL. The items' sum as the marketplace states it, before fees and discounts. Null or absent is \"did not say\". */\n subtotalCents?: number | null;\n /**\n * OPTIONAL. The discounts on the order, one entry per sponsor's share, so a\n * host can tell what the store gave from what the marketplace paid for.\n * Absent is \"did not say\"; an empty array is \"no discount\".\n */\n discounts?: NormalizedOrderDiscount[];\n /**\n * OPTIONAL. The merchant the order names, when its body says (Open\n * Delivery's `merchant.id`). A fetched order naming another merchant than\n * the connection's is refused.\n */\n externalMerchantId?: string | null;\n /**\n * OPTIONAL (FUT-5665). The code the marketplace's courier states at the\n * counter to collect the bag (iFood's `delivery.pickupCode`), for the host\n * to check locally at the hand-over. Null or absent: the marketplace asks\n * none for this order (the check is off for the store, or the store carries\n * the bag itself).\n */\n pickupCode?: string | null;\n /**\n * OPTIONAL (FUT-5803). How the buyer pays: each method, what is prepaid and\n * what is still to collect, and the change a cash buyer asks for. Absent:\n * the marketplace states none.\n */\n payments?: NormalizedPayments;\n /**\n * OPTIONAL (FUT-5803). The fees besides delivery, inside `totalCents`.\n * Absent is \"did not say\"; an empty array is \"none\".\n */\n additionalFees?: NormalizedOrderFee[];\n}\n\n/**\n * What an event says about the STORE's own cancellation request: `CONFIRMED`\n * when the marketplace cancelled the order (a pending request is answered),\n * `FAILED` when it refused the request.\n */\nexport type CancellationOutcome = \"CONFIRMED\" | \"FAILED\";\n\n/**\n * A step of the order's life a marketplace announces about an order it\n * already has (FUT-4653): the courier left (`DISPATCHED`), the marketplace's\n * courier has the bag (`COLLECTED`, FUT-5665: for a fleet bag it is the same\n * hand-over as `DISPATCHED`) or the order is finished (`CONCLUDED`). An event\n * that names one moves nothing by itself; the engine asks the host to move the\n * order forward (`onLifecycle`).\n */\nexport type MarketplaceLifecycle = \"DISPATCHED\" | \"COLLECTED\" | \"CONCLUDED\";\n\n/**\n * Where the marketplace's own courier is with a bag (FUT-5665), provider-\n * neutral: named (`ASSIGNED`), on the way to the store (`GOING_TO_ORIGIN`),\n * at the counter (`ARRIVED_AT_ORIGIN`), holding the bag (`COLLECTED`), or\n * bringing it back (`RETURNING_TO_ORIGIN`, then `RETURNED_TO_ORIGIN`).\n */\nexport type MarketplaceCourierStep =\n | \"ASSIGNED\"\n | \"GOING_TO_ORIGIN\"\n | \"ARRIVED_AT_ORIGIN\"\n | \"COLLECTED\"\n | \"RETURNING_TO_ORIGIN\"\n | \"RETURNED_TO_ORIGIN\";\n\n/** What the courier rides, as a closed set the host has words for. `OTHER`: stated, and none of these. */\nexport type MarketplaceCourierVehicle = \"MOTORCYCLE\" | \"BICYCLE\" | \"CAR\" | \"OTHER\";\n\n/** Who the marketplace sent, as much as it says. */\nexport interface MarketplaceCourier {\n name: string | null;\n /** An https URL of the courier's photo, or null (any other scheme is dropped). */\n photoUrl: string | null;\n vehicle: MarketplaceCourierVehicle | null;\n}\n\n/** One courier event, normalized (FUT-5665). */\nexport interface NormalizedCourierEvent {\n step: MarketplaceCourierStep;\n /** When the marketplace says it happened; null when it does not (the engine then hands the host its clock). */\n at: Date | null;\n /** Who is coming: on `ASSIGNED`, when the marketplace names them; null otherwise. */\n courier: MarketplaceCourier | null;\n /** The bag is coming back (`RETURNING`) or is back (`RETURNED`); null on every other step. */\n returning: \"RETURNING\" | \"RETURNED\" | null;\n}\n\n/** What an adapter makes of one inbound delivery. */\nexport interface NormalizedEvent {\n provider: MarketplaceProvider;\n /** The delivery's own id — the inbox dedup key, paired with the provider. */\n eventId: string;\n /** The provider's event type verbatim, kept for the inbox row and the log. */\n eventType: string;\n /** The merchant this event names, used to attribute it to a tenant. */\n externalMerchantId: string | null;\n externalOrderId: string | null;\n /**\n * The order this event carries, or null when the event is one the engine\n * understands and does not ingest. A null here is an IGNORED inbox row (or a\n * cancellation, below), never a failure.\n */\n order: NormalizedMarketplaceOrder | null;\n /** The marketplace has CANCELLED the order. */\n cancelled: boolean;\n /**\n * The answer to the store's own cancellation request, when this event is\n * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.\n */\n cancellationOutcome?: CancellationOutcome | null;\n /**\n * OPTIONAL. This event announces an order whose body the marketplace serves\n * separately (Open Delivery's `CREATED` carries only the order's id): the\n * engine fetches it through the adapter's `fetchOrder`, in the\n * `marketplace.fetch-order` job, never inside the request that delivered\n * the event. Ignored when `order` is present.\n */\n orderToFetch?: boolean;\n /**\n * OPTIONAL. The lifecycle step this event announces about an order the\n * engine already has. Absent or null: the event names none. An event that\n * names one carries no order body.\n */\n lifecycle?: MarketplaceLifecycle | null;\n /**\n * OPTIONAL (FUT-5665). Where the marketplace's courier is, when this event\n * says. A `COLLECTED` names the lifecycle too. Absent or null: the event\n * names no courier step.\n */\n courier?: NormalizedCourierEvent | null;\n /**\n * OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own\n * app (iFood's `CFM`): an order still AWAITING here is accepted through the\n * host's admit, with no confirm sent back. Carries no order body.\n */\n marketplaceConfirmed?: boolean;\n}\n"],"mappings":";;;;;AAwBO,IAAM,sBAAsB;AAkD5B,SAAS,yBAAyB,MAAoF;AAC3H,SAAO,KAAK,iBAAiB,KAAK,YAAY,KAAK,WAAW,CAAC,GAAG,OAAO,CAAC,KAAK,WAAW,MAAM,OAAO,YAAY,CAAC;AACtH;AAFgB;","names":[]}
@@ -1,10 +1,10 @@
1
+ import {
2
+ PROVIDER_ID_PATTERN
3
+ } from "./chunk-H2VQRD3B.js";
1
4
  import {
2
5
  __name
3
6
  } from "./chunk-7QVYU63E.js";
4
7
 
5
- // src/core/types.ts
6
- var PROVIDER_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;
7
-
8
8
  // src/core/registry.ts
9
9
  var MarketplaceAdapterRegistrationError = class extends Error {
10
10
  static {
@@ -1296,8 +1296,14 @@ var CancellationReasonsRetryError = class extends Error {
1296
1296
  }
1297
1297
  };
1298
1298
  async function enqueueOrderReasons(ctx, input) {
1299
- if (!ctx.registry.get(input.provider)?.orderCancellationReasons) return;
1300
- const payload = { clientId: input.clientId, orderId: input.orderId };
1299
+ const adapter = ctx.registry.get(input.provider);
1300
+ const deferred = input.deferredConfirmations === true && adapter?.capabilities.marketplaceConfirms === true;
1301
+ if (!adapter?.orderCancellationReasons && !deferred) return;
1302
+ const payload = {
1303
+ clientId: input.clientId,
1304
+ orderId: input.orderId,
1305
+ ...deferred ? { deferredConfirmations: true } : {}
1306
+ };
1301
1307
  const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
1302
1308
  dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`
1303
1309
  });
@@ -1318,12 +1324,26 @@ async function keep(ctx, db, clientId, orderId, reasons) {
1318
1324
  return { kind: "done", count: reasons.length };
1319
1325
  }
1320
1326
  __name(keep, "keep");
1321
- async function runCancellationReasons(ctx, payload, attempt) {
1322
- const db = await ctx.ports.db();
1327
+ async function applyEarlyConfirmations(ctx, clientId, row) {
1328
+ try {
1329
+ await applyDeferredConfirmations(ctx, { clientId, provider: row.provider, externalOrderId: row.externalOrderId });
1330
+ } catch (error) {
1331
+ ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${row.orderId}: a deferred confirmation was not applied; the expiry sweep applies it`, error);
1332
+ }
1333
+ }
1334
+ __name(applyEarlyConfirmations, "applyEarlyConfirmations");
1335
+ async function loadOrder(ctx, db, payload) {
1323
1336
  const row = await db.marketplaceAcceptance.findFirst({
1324
1337
  where: { orderId: payload.orderId, clientId: payload.clientId },
1325
1338
  select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true }
1326
1339
  });
1340
+ if (row && payload.deferredConfirmations) await applyEarlyConfirmations(ctx, payload.clientId, row);
1341
+ return row;
1342
+ }
1343
+ __name(loadOrder, "loadOrder");
1344
+ async function runCancellationReasons(ctx, payload, attempt) {
1345
+ const db = await ctx.ports.db();
1346
+ const row = await loadOrder(ctx, db, payload);
1327
1347
  if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
1328
1348
  if (storedReasons(row.cancellationReasons) !== null) return { kind: "skipped", reason: "the order's reasons are already kept" };
1329
1349
  const read = ctx.registry.get(row.provider)?.orderCancellationReasons;
@@ -1466,7 +1486,8 @@ async function composeLines(db, clientId, order, seenAt) {
1466
1486
  unitPriceCents: line.unitPriceCents,
1467
1487
  note: line.note,
1468
1488
  subjectRef: mapping.get(line.externalSku)?.menuItemId ?? null,
1469
- variationRef: mapping.get(line.externalSku)?.variationId ?? null
1489
+ variationRef: mapping.get(line.externalSku)?.variationId ?? null,
1490
+ ...line.options ? { options: line.options } : {}
1470
1491
  }));
1471
1492
  }
1472
1493
  __name(composeLines, "composeLines");
@@ -1528,8 +1549,7 @@ async function ingestMarketplaceOrder(ctx, input) {
1528
1549
  await ctx.ports.order.onAccepted(clientId, orderId);
1529
1550
  }
1530
1551
  ctx.ports.publishChanged(clientId);
1531
- await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider });
1532
- if (!accepted) await applyDeferredConfirmations(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId });
1552
+ await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider, deferredConfirmations: !accepted });
1533
1553
  return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
1534
1554
  }
1535
1555
  __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
@@ -2838,7 +2858,6 @@ __name(runAvailability, "runAvailability");
2838
2858
  export {
2839
2859
  requestsFirst,
2840
2860
  tellCancellationFailed,
2841
- PROVIDER_ID_PATTERN,
2842
2861
  MarketplaceAdapterRegistrationError,
2843
2862
  createAdapterRegistry,
2844
2863
  storedReasons,
@@ -2932,4 +2951,4 @@ export {
2932
2951
  AvailabilityRetryError,
2933
2952
  runAvailability
2934
2953
  };
2935
- //# sourceMappingURL=chunk-MDXSVE7Q.js.map
2954
+ //# sourceMappingURL=chunk-TICWLBSA.js.map