@12-apps/marketplace 1.1.0 → 1.3.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 (92) hide show
  1. package/ADOPTING.md +37 -7
  2. package/README.md +238 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +162 -0
  7. package/dist/99food/index.js +444 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
  13. package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
  14. package/dist/chunk-AYYBRQJV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/chunk-M2V4RFMA.js +23 -0
  18. package/dist/chunk-M2V4RFMA.js.map +1 -0
  19. package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
  20. package/dist/chunk-RVBTARIY.js.map +1 -0
  21. package/dist/chunk-XUAFXNOH.js +1604 -0
  22. package/dist/chunk-XUAFXNOH.js.map +1 -0
  23. package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
  24. package/dist/hono/index.d.ts +2 -2
  25. package/dist/hono/index.js +2 -2
  26. package/dist/ifood/index.d.ts +16 -12
  27. package/dist/ifood/index.js +248 -121
  28. package/dist/ifood/index.js.map +1 -1
  29. package/dist/index.d.ts +30 -4
  30. package/dist/index.js +189 -346
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +4 -2
  33. package/dist/manifest/server.js +2 -2
  34. package/dist/rappi/en-US.d.ts +14 -0
  35. package/dist/rappi/en-US.js +18 -0
  36. package/dist/rappi/en-US.js.map +1 -0
  37. package/dist/rappi/index.d.ts +190 -0
  38. package/dist/rappi/index.js +359 -0
  39. package/dist/rappi/index.js.map +1 -0
  40. package/dist/rappi/pt-BR.d.ts +18 -0
  41. package/dist/rappi/pt-BR.js +18 -0
  42. package/dist/rappi/pt-BR.js.map +1 -0
  43. package/dist/server/index.d.ts +19 -8
  44. package/dist/server/index.js +4 -2
  45. package/package.json +26 -2
  46. package/prisma/marketplace.prisma +97 -2
  47. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  48. package/src/99food/catalogue.ts +117 -0
  49. package/src/99food/copy.ts +36 -0
  50. package/src/99food/en-US.ts +19 -0
  51. package/src/99food/index.ts +125 -0
  52. package/src/99food/normalize.ts +263 -0
  53. package/src/99food/outbound.ts +220 -0
  54. package/src/99food/pt-BR.ts +23 -0
  55. package/src/core/adapter.ts +27 -2
  56. package/src/core/catalogue-category.ts +119 -0
  57. package/src/core/catalogue-ids.ts +23 -0
  58. package/src/core/catalogue-job.ts +332 -0
  59. package/src/core/catalogue-port.ts +173 -0
  60. package/src/core/catalogue-store.ts +172 -0
  61. package/src/core/catalogue-sweep.ts +43 -0
  62. package/src/core/catalogue.ts +226 -0
  63. package/src/core/decisions.ts +16 -4
  64. package/src/core/engine.ts +54 -0
  65. package/src/core/fetch-order.ts +253 -0
  66. package/src/core/inbox.ts +8 -2
  67. package/src/core/ingest.ts +10 -2
  68. package/src/core/integration.ts +30 -1
  69. package/src/core/order-fetch-marks.ts +63 -0
  70. package/src/core/outbound-sweep.ts +7 -2
  71. package/src/core/outbound.ts +22 -2
  72. package/src/core/payload-read.ts +101 -0
  73. package/src/core/pipeline.ts +64 -15
  74. package/src/core/ports.ts +36 -0
  75. package/src/core/types.ts +14 -0
  76. package/src/ifood/catalogue.ts +273 -0
  77. package/src/ifood/index.ts +4 -0
  78. package/src/ifood/normalize.ts +15 -88
  79. package/src/ifood/outbound.ts +9 -6
  80. package/src/index.ts +49 -1
  81. package/src/rappi/copy.ts +39 -0
  82. package/src/rappi/en-US.ts +14 -0
  83. package/src/rappi/index.ts +161 -0
  84. package/src/rappi/normalize.ts +314 -0
  85. package/src/rappi/outbound.ts +182 -0
  86. package/src/rappi/pt-BR.ts +18 -0
  87. package/src/server/index.ts +1 -0
  88. package/src/server/jobs.ts +71 -8
  89. package/dist/chunk-7BYVGNU5.js.map +0 -1
  90. package/dist/chunk-DVIRN42O.js +0 -707
  91. package/dist/chunk-DVIRN42O.js.map +0 -1
  92. package/dist/chunk-NGNEL4HS.js.map +0 -1
package/ADOPTING.md CHANGED
@@ -11,7 +11,7 @@ error at mount, never a default that quietly adopts another host's policy.
11
11
 
12
12
  | port | type | what the host answers |
13
13
  |---|---|---|
14
- | `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance`. |
14
+ | `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance`, and the catalogue's `marketplaceCataloguePublication` (optional in the type; the catalogue calls need it). |
15
15
  | `transaction` | `<T>(fn: (db: MarketplaceDb) => Promise<T>) => Promise<T>` | Prisma's interactive `$transaction`: run `fn` with the transaction's client; a throw rolls back. Every bulk write and every decision (admission + claim) is one transaction. |
16
16
  | `order.admit` | `(request: { clientId; orderId; decision: "ACCEPT" \| "REJECT"; admission: MarketplaceAdmission; db: MarketplaceDb }) => Promise<{ admitted: true } \| { admitted: false; code: string; message: string; details?: unknown }>` | Judge each decision BEFORE its claim commits, inside the claim's transaction (`request.db` is the transaction's client: draw the stock there, and a refusal anywhere in the call rolls the draw back). `admission` is `{ admitStockPastZero?: boolean }` as the person stated it. Refuse with your own code: the route answers 409 with it (`MARKETPLACE_STOCK_ASK` and the short lines in `details`). Never called for an ingest or `recordStoreCancellation`. |
17
17
  | `order.create` | `(clientId, order: NormalizedMarketplaceOrder, lines: readonly ResolvedOrderLine[], db: MarketplaceDb) => Promise<string>` | Create the host's own order from a normalized one; return its id. `lines[i].subjectRef` is the mapped catalog id or null (never refuse the order for a null). `db` is the ingest's transaction client: write the order through it, so the order and the acceptance row commit together (a lost race rolls the host's order back instead of leaving an orphan a redelivery would duplicate). |
@@ -22,15 +22,16 @@ error at mount, never a default that quietly adopts another host's policy.
22
22
  | `order.onCancellationFailed` | OPTIONAL. `(clientId, orderId, reason: "REFUSED" \| "TIMEOUT") => Promise<void>` | The store's request FAILED: REFUSED (the marketplace's refusal event, the job's 4xx, its last attempt dying, or — request first — a marketplace whose API cannot take it, at once) or TIMEOUT (the outbound sweep, past the marketplace's answer window, or the 24-hour give-up). Called once, by the path that moved the row. Request first: the order stays as it was (AWAITING or ACCEPTED) and may be accepted again; show the adapter's app link and tell the person. A throw is logged. |
23
23
  | `order.summarize` | `(clientId, orderIds: readonly string[]) => Promise<Map<string, MarketplaceOrderSummary>>` | The queue's host facts in one read: `{ buyerName, totalCents, unmappedLines, createdAt }`. |
24
24
  | `secrets` | `{ seal(plaintext): string; open(sealed): string }` | Seal and open the credential blob with the host's key. `open` THROWS on a blob that will not open. |
25
- | `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. |
25
+ | `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. `method` is `GET`, `POST`, `PUT` or, since the catalogue (1.2), `PATCH`. |
26
26
  | `audit` | `{ record(entry: { clientId; actorId: string \| null; action: "marketplace.integration.archive" \| "marketplace.integration.unarchive"; provider; reason: string \| null; at: Date }, db: MarketplaceDb): Promise<void> }` | Every archive and unarchive of a connection, INSIDE the same transaction: write the line through `db`, so an archive never lands without its line and a failing audit rolls the archive back. `actorId` is `MarketplaceActor.userId`. |
27
- | `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) => Promise<{ enqueued: boolean; reason?: string }> }` | The wiring `JobsEnqueuePort`. The engine queues only `marketplace.outbound` with `{ clientId, orderId, action }` and dedupe key `marketplace.outbound:<action>:<orderId>`. Never throws. |
27
+ | `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) => Promise<{ enqueued: boolean; reason?: string }> }` | The wiring `JobsEnqueuePort`. Never throws. The engine queues only its own three on-demand jobs: `marketplace.outbound` (`{ clientId, orderId, action }`, dedupe key `marketplace.outbound:<action>:<orderId>`), `marketplace.fetch-order` (`{ clientId, inboxId }`, dedupe key `marketplace.fetch-order:<inboxId>`) and `marketplace.catalogue` (`{ clientId, publicationId, action }`, dedupe key `marketplace.catalogue:<action>:<publicationId>:<asked at, ms>`); the sweeps re-queue each under a key of their own. |
28
28
  | `clock` | `{ now(): Date }` | What time it is. |
29
29
  | `logger` | `{ info, warn, error }` | The wiring `LoggerPort`; bind `assembled.loggers["@12-apps/marketplace"]`. |
30
30
  | `publishChanged` | `(clientId) => void` | Tell the staff surfaces something moved. Fire-and-forget. |
31
31
  | `defaultAckSlaSeconds` | `number` | The acceptance window a new connection gets (the origin host: 300). |
32
32
  | `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
33
33
  | `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
34
+ | `catalogue` | OPTIONAL. `{ items(clientId, productIds) => Promise<Map<string, CatalogueItem>>; image(url) => Promise<{ contentType; base64 } \| null> }` | Catalogue publishing (1.2, FUT-4768). `items` maps the host's products into `{ name, description, imageUrl, categoryName, priceCents }` (the store's price, smallest unit; the photo an absolute https URL that CHANGES when the photo changes, such as a content hash or upload id in it: a marketplace's uploaded copy is reused while the URL is the same), keyed by product id; a missing id is a product that no longer exists. Called at publish (to check it exists) and by the job when it sends, so what goes out is the product as it is then. `image` reads a photo's bytes for a marketplace that takes an upload (iFood); null publishes without a photo. Absent: every catalogue call answers `UNSUPPORTED`. |
34
35
  | `cancellationWindowMs` | OPTIONAL. `number` | For a host that requests first (binds `onCancellationConfirmed`): how long a store's cancellation request may wait (PENDING: not yet delivered, or REQUESTED: delivered and unanswered) before the outbound sweep fails it as TIMEOUT, for every adapter; a PENDING request's retries stop with it. A 1.0.0 host has no window: its requests are re-queued and given up after 24 hours, as before. Absent: each adapter's `capabilities.cancellationAnswerWindowMs` (iFood: 5 minutes, estimated); an adapter with none is given up on only after 24 hours. |
35
36
 
36
37
  Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
@@ -68,6 +69,11 @@ export const engine = createMarketplaceEngine({
68
69
  | `suggestReason(provider, { itemUnavailable })` | To preselect a reason in the refusal dialog. The host judges the shortage. |
69
70
  | `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, cancellationFailure, appUrl }` per marketplace order, one query. `cancellation` PENDING or REQUESTED is a request still waiting: draw it as such. `cancellationFailure` is REFUSED or TIMEOUT when `cancellation` is FAILED. |
70
71
  | `adapter(provider)`, `reasons(provider)`, `appLink(provider, ref)` | The marketplace's capabilities, reasons and link, without naming it. |
72
+ | `catalogueMode(provider)` | `"push"`, `"pull"` or null: whether the product page can offer this marketplace's switch at all (null: say it cannot be published to). Null also while the host binds no `catalogue` port. |
73
+ | `publish({ clientId, provider, productId, priceCents? })` | The switch turned ON, a new marketplace price, or "try again" after FAILED. `priceCents` absent keeps the stored price, `null` goes back to the store's, a positive integer sets this marketplace's (never the store's own). Answers `queued` with the row (PUBLISHING), or `refused` with `UNSUPPORTED`, `NOT_CONNECTED` (no live connection with credentials and a merchant id), `UNKNOWN_PRODUCT` or `INVALID_PRICE`. Gate it with `marketplace:manage`. |
74
+ | `withdraw({ clientId, provider, productId })` | The switch turned OFF (and the undo of an ON). `queued` (WITHDRAWING), or `unchanged` when the product was never switched on, or is WITHDRAWN at once because its connection was archived or removed since. |
75
+ | `catalogueState({ clientId, productIds, providers? })` | The product page's read: one row per marketplace the product was ever switched on for, in one query. Draw PUBLISHED as "in the catalogue" (with your sentence for a `warningCode`, IMAGE_TOO_LARGE or IMAGE_REFUSED: it went out without its photo), PUBLISHING / WITHDRAWING as "sending…" (switch disabled), FAILED with your own sentence for its `failureCode` (REFUSED, UNAVAILABLE, TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL), the marketplace's own words from `failureReason` beside a REFUSED, and a retry (`publish` or `withdraw` again, per `failedAction`). The engine writes no sentence a person reads. No row is OFF. |
76
+ | `catalogueDocument({ clientId, provider, options: { menuName, currency } })` | PULL marketplaces only (99Food): the menu part of the document the marketplace reads. Serve it from the route the marketplace pulls (Open Delivery's `GET /v1/merchant`), merged into the rest of that document, which is the host's (`id`, `status`, `lastUpdate`, `TTL`, `basicInfo`, `services`). The menu's name and the currency are the host's words. |
71
77
  | `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
72
78
 
73
79
  A host never writes `provider === "IFOOD"`. A capability is asked of
@@ -91,15 +97,20 @@ host.adoptServer({
91
97
  | capability | what it is |
92
98
  |---|---|
93
99
  | `http` | `POST /webhooks/marketplace/:tenantSlug/:provider` (`kind: "webhook"`, needs the raw `request`), and per entity one read and one bulk write under `/admin/:tenantSlug/marketplace`: `GET`/`PUT` (connections), `GET`/`PUT /menu-links`, `GET`/`POST /acceptances` (decisions). `@12-apps/marketplace/hono`'s `marketplaceRouter({ ...config, resolveActor })` mounts them in one line. |
94
- | `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h). Bind `{ engine }`. |
100
+ | `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.fetch-order` (on demand, 3 attempts, exponential backoff 5 s: the order body an event only announced; a host that holds it through its `enqueue` port holds every fetch), `marketplace.catalogue` (on demand, 3 attempts, exponential backoff 10 s: one publish or withdraw; the last attempt ends FAILED with a `failureCode`, or leaves a publish that only waited for another's category PUBLISHING for the sweep), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h, re-queues a catalogue row still PUBLISHING or WITHDRAWING after 10 min, and FAILS one as TIMEOUT after 24 h). Bind `{ engine }`. |
95
101
  | `mcp` | Six tools, the bulk-upsert protocol: `listMarketplaceIntegrations` / `upsertMarketplaceIntegrations` (operations `upsert`, `archive`, `unarchive`), `listMarketplaceMenuLinks` / `upsertMarketplaceMenuLinks`, `listMarketplaceAcceptances` / `decideMarketplaceOrders`. Every write takes a list, is all-or-nothing in one transaction, supports `validateOnly`, answers every problem with its path; reads take `ids`. Descriptions are English. |
96
102
  | `permissions` | `marketplace:manage` (connect, map) and `marketplace:decide` (read and answer the queue). The host decides which roles hold them; each route declares its own. |
97
103
  | `db` | `prisma/marketplace.prisma` + `prisma/migrations` (composed). |
98
104
  | `observability` | namespace `marketplace`. |
99
105
 
100
- The route copy (`MarketplaceServerCopy`) and the iFood adapter's copy
101
- (`IfoodAdapterCopy`) are required config; pt-BR and en-US packs ship beside
102
- each.
106
+ The route copy (`MarketplaceServerCopy`) and each adapter's copy
107
+ (`IfoodAdapterCopy`, `NinetyNineFoodAdapterCopy`, `RappiAdapterCopy`) are
108
+ required config; pt-BR and en-US packs ship beside each. The 99Food adapter
109
+ also requires its `apiBaseUrl` per environment and its `portalUrl`, which
110
+ 99Food gives a partner at onboarding. The Rappi adapter requires its
111
+ `apiBaseUrl` and `tokenUrl` per environment (on Rappi's country domains), its
112
+ `portalUrl` and its `amountUnit` (how Rappi states money for the host's
113
+ country); see the README's Rappi section for what is still ESTIMATED.
103
114
 
104
115
  ## 4. What the origin host changes when it adopts this package
105
116
 
@@ -165,6 +176,19 @@ each.
165
176
  - run migration `20261112120000_marketplace_cancellation_failure` (one nullable column,
166
177
  its CHECK and an index), through the host's plugin-migration sync like the first.
167
178
 
179
+ 14. **Catalogue publishing (1.2, FUT-4768) — opt in by binding `catalogue`.** Nothing
180
+ changes for a host that does not. To offer the product page's marketplace switches:
181
+ - run migration `20261113120000_marketplace_catalogue` (one new table, additive) and
182
+ re-sync the partial (`prisma:sync-marketplace`), so `db` has the
183
+ `marketplaceCataloguePublication` and `marketplaceCatalogueCategory` delegates;
184
+ - bind `catalogue.items` (the product → item mapping) and `catalogue.image`;
185
+ - let the `http` port send `PATCH`;
186
+ - run the `marketplace.catalogue` job (it arrives with the jobs capability);
187
+ - gate `publish`/`withdraw` with `marketplace:manage`, and show a marketplace whose
188
+ `catalogueMode` is null as not publishable (Rappi, today);
189
+ - for 99Food, serve `catalogueDocument` inside Open Delivery's `GET /v1/merchant`
190
+ (the route 99Food pulls) and register that route with 99Food at onboarding.
191
+
168
192
  ## 5. The database
169
193
 
170
194
  The partial names no host table: `client_id`, `order_id` and `menu_item_id`
@@ -175,6 +199,12 @@ migration:
175
199
  - `marketplace_acceptances.order_id → <orders>(id) ON DELETE CASCADE`
176
200
  - `marketplace_menu_links.menu_item_id → <catalog>(id) ON DELETE SET NULL`
177
201
 
202
+ `20261113120000_marketplace_catalogue` (1.2) adds `marketplace_catalogue_publications`:
203
+ one row per (store, marketplace, product), its five states, its failed action and its
204
+ prices CHECKed, `product_id` by value; and `marketplace_catalogue_categories`, a push
205
+ marketplace's category id per (store, marketplace, category name), created once. A host that wants it adds
206
+ `marketplace_catalogue_publications.product_id → <catalog>(id) ON DELETE CASCADE`.
207
+
178
208
  The migrations are replay-safe. `20261112120000_marketplace_cancellation_failure`
179
209
  (1.1) adds `marketplace_acceptances.cancellation_failure_reason` (REFUSED or
180
210
  TIMEOUT, CHECKed), and a PARTIAL index the expiry of waiting requests reads
package/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  One integration engine for every marketplace a store sells through. Each
4
4
  marketplace is an **adapter** on that engine, shipped inside this package at
5
- its own subpath (`@12-apps/marketplace/ifood` today).
5
+ its own subpath (`@12-apps/marketplace/ifood`, `@12-apps/marketplace/99food`,
6
+ `@12-apps/marketplace/rappi`).
6
7
 
7
8
  ```ts
8
9
  import { createMarketplaceEngine } from "@12-apps/marketplace";
@@ -44,8 +45,10 @@ engine code (`src/__tests__/second-adapter.test.ts`).
44
45
  | **SKU map** | External SKU → host catalog id, every SKU ever seen a row; mapping checks the id is the tenant's. |
45
46
  | **Integration settings** | Enabled, environment, merchant id, auto-accept, acknowledgement window; credentials sealed as one blob by the host's secrets port, never returned. A connection is archived (reversible, audited), never deleted. |
46
47
  | **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
48
+ | **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. |
47
49
  | **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
48
- | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, and `capabilities`. |
50
+ | **Catalogue publishing** | A store turns a product ON or OFF per connected marketplace, with an optional price for that marketplace. One row per (store, marketplace, product): PUBLISHING → PUBLISHED, WITHDRAWING → WITHDRAWN, FAILED with a failure code (and the marketplace's own words for a refusal). The `marketplace.catalogue` job makes the call; the sweep re-queues what is owed. Push or pull is the adapter's. See [Catalogue publishing](#catalogue-publishing). |
51
+ | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, `capabilities`, and the optional `fetchOrder` and `catalogue`. |
49
52
 
50
53
  ## Subpaths
51
54
 
@@ -54,16 +57,247 @@ engine code (`src/__tests__/second-adapter.test.ts`).
54
57
  | `@12-apps/marketplace` | the engine, the adapter port and registry, every type |
55
58
  | `@12-apps/marketplace/ifood` | `createIfoodAdapter({ copy })` |
56
59
  | `@12-apps/marketplace/ifood/pt-BR`, `/en-US` | the iFood adapter's copy packs (reason labels, "no street number") |
60
+ | `@12-apps/marketplace/99food` | `createNinetyNineFoodAdapter({ copy, apiBaseUrl, portalUrl })`, provider `NINETY_NINE_FOOD`, on Open Delivery |
61
+ | `@12-apps/marketplace/99food/pt-BR`, `/en-US` | the 99Food adapter's copy packs |
62
+ | `@12-apps/marketplace/rappi` | `createRappiAdapter({ copy, apiBaseUrl, tokenUrl, portalUrl, amountUnit })`, provider `RAPPI` |
63
+ | `@12-apps/marketplace/rappi/pt-BR`, `/en-US` | the Rappi adapter's copy packs |
57
64
  | `@12-apps/marketplace/server` | `createApiMarketplace` (route descriptors), `MARKETPLACE_JOBS`, `MARKETPLACE_MCP_TOOLS` (six: a read and a bulk write per entity), `MARKETPLACE_PERMISSIONS`, the strict Zod inputs |
58
65
  | `@12-apps/marketplace/server/pt-BR`, `/en-US` | the routes' copy packs |
59
66
  | `@12-apps/marketplace/hono` | `marketplaceRouter(config)` — the routes as one Hono router (`hono` is an optional peer) |
60
67
  | `@12-apps/marketplace/manifest`, `/manifest/server` | the wiring manifests |
61
68
  | `prisma/marketplace.prisma`, `prisma/migrations/*` | the partial (no host table named) and its replay-safe migration |
62
69
 
70
+ ## Catalogue publishing
71
+
72
+ FUT-4768, approved by the owner on 2026-11-12: from a product's page the store
73
+ turns the product ON (in that marketplace's catalogue) or OFF (removed) per
74
+ connected marketplace, with an optional price for that marketplace that
75
+ defaults to the store's and never changes it. What goes out: name, photo,
76
+ description, category and the price. The states a host shows: in the
77
+ catalogue, "sending…", and refused with the marketplace's reason and a retry.
78
+ Why the engine now does this at all: the decision record
79
+ [`docs/marketplace/decisions/draft-the-engine-publishes-catalogues.md`](../../docs/marketplace/decisions/draft-the-engine-publishes-catalogues.md).
80
+
81
+ ```ts
82
+ engine.catalogueMode(provider); // "push" | "pull" | null (cannot be published to)
83
+ await engine.publish({ clientId, provider, productId, priceCents }); // priceCents: absent keeps, null = the store's price
84
+ await engine.withdraw({ clientId, provider, productId });
85
+ await engine.catalogueState({ clientId, productIds: [productId] }); // every marketplace, one read
86
+ await engine.catalogueDocument({ clientId, provider, options: { menuName, currency } }); // pull only: what the host serves
87
+ ```
88
+
89
+ | part | what it does |
90
+ |---|---|
91
+ | **The row** | `marketplace_catalogue_publications`, one per (store, marketplace, product): `status`, the marketplace price (`price_cents`, NULL = the store's), the price last sent, the marketplace's id for the item, the failed action, its code and the marketplace's own words, and when each thing happened. `product_id` is opaque: no host table is read. |
92
+ | **States** | `publish` → PUBLISHING → (job) PUBLISHED; `withdraw` → WITHDRAWING → (job) WITHDRAWN; a final refusal, or the last attempt, → FAILED with `failedAction` (PUBLISH / WITHDRAW) and a `failureCode` the host words (REFUSED, UNAVAILABLE, TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL); `failureReason` carries the marketplace's own words for a REFUSED only, never an engine or internal message. `publish` or `withdraw` again from FAILED is the retry. |
93
+ | **Idempotency** | A run acts only while the row still asks for its action at the instant it read (`requested_at`). A double tap while on its way keeps the same ask and the same dedupe key. The store's last tap wins: a withdraw while publishing makes the publish run call nobody, a publish that LANDS after the withdraw is withdrawn again, and a withdraw that lands after the product was switched back on is followed by the publish again. A withdraw is sent even after a failed publish (an answer lost after the item landed), and a marketplace answers a withdraw of an item it does not have as done; only a connection archived or removed since ends WITHDRAWN at once, with nobody to tell. |
94
+ | **The host's product** | Read through the host's `catalogue.items(clientId, productIds)` port when the job sends it, so what goes out is the product as it is then; `catalogue.image(url)` hands over a photo's bytes for a marketplace that takes an upload. |
95
+ | **SKU map** | A publish that succeeds maps the SKU the marketplace's orders will carry for the item (the adapter's `sku`, else the product id sent as its external code) to the product, so those orders arrive mapped rather than on the attention list; only when the SKU is not mapped yet, so a store's own mapping of it is never undone. A withdraw keeps the map: an order placed before it still maps. |
96
+ | **Categories** | A push marketplace's category id is found or created by name ONCE per (connection, name) and stored (`marketplace_catalogue_categories`). The first publish to need a new one claims its creation; a second one meanwhile is retried by the job and then reuses the stored id, so switching on several products of a new category at once creates it once. A claim is released whatever its publish met (a timeout included), and only by its own holder; one left by a dead publish is taken over after 3 minutes, well above three slow calls, so a live holder on a slow call keeps it. A publish that only waited stays PUBLISHING, and the sweep re-queues it after 10 minutes. |
97
+ | **Push** | `catalogue.publishItem` / `withdrawItem`: the adapter writes ONE item. The engine hands it a stable reference (the row's id), so an adapter that must invent the marketplace's id derives it (`stableUuid`) and a retry never creates a second item. |
98
+ | **Pull** | `catalogue.menuDocument` builds the marketplace's menu document from every item ON (PUBLISHING or PUBLISHED, and one published before, not withdrawn since, whose re-publish FAILED, kept at the price last sent until it is withdrawn); the host serves it. `notifyMenuChanged` tells the marketplace to read it again; PUBLISHED / WITHDRAWN once it took the notice. |
99
+ | **Sweep** | The `marketplace.outbound-sweep` pass re-queues a row still PUBLISHING or WITHDRAWING after 10 minutes, and FAILS one 24 hours old, so no switch says "sending" forever. |
100
+
101
+ ### What each marketplace offers, from its public documentation
102
+
103
+ Read 2026-11-13. CONFIRMED: read on the page linked. ESTIMATED: not stated
104
+ there, chosen in the adapter's code and marked so beside it.
105
+
106
+ **iFood — push, Catalog API v2.0** (`src/ifood/catalogue.ts`)
107
+
108
+ | fact | status |
109
+ |---|---|
110
+ | Base `https://merchant-api.ifood.com.br/catalog/v2.0/merchants/{merchantId}/…`; bearer token from the same OAuth grant as orders | CONFIRMED — [Introduction](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/introduction) |
111
+ | Hierarchy catalog → context (DEFAULT delivery, WHITELABEL, INDOOR) → category → item → products / option groups / options; each level has its own status | CONFIRMED — [Fundamentals](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/fundamentals) |
112
+ | `GET /catalogs`; `GET /categories` (`?include_items=true`); `POST /categories` `{ name, status, template: "DEFAULT" }` → `{ id, … }` | CONFIRMED — [Endpoints](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/endpoints) |
113
+ | `PUT /items` with `item`, `products`, `optionGroups`, `options` (all four always sent) creates or REPLACES the whole item; the item appears at once (synchronous) | CONFIRMED — Introduction, Endpoints |
114
+ | `item.id` and `products[].id` are UUID v4 the software generates (another shape answers 404); `externalCode` is the software's code, unique per merchant (409 when reused); `status` AVAILABLE / UNAVAILABLE; `price` `{ value, originalValue? }` in the major unit | CONFIRMED — Fundamentals, Introduction |
115
+ | `PATCH /items/status` `{ itemId, status }` and `PATCH /items/price` `{ itemId, price }`, synchronous; the batch forms (`/products/status`, `/products/price`) answer a `batchId` and run asynchronously | CONFIRMED — Endpoints, [Errors](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/errors-and-troubleshooting) |
116
+ | `POST /image/upload` `{ image: "data:image/png;base64,…" }` → `{ imagePath }`, reusable across items; jpg/jpeg/png, at most 5 MB (413 above) | CONFIRMED — Endpoints, Errors |
117
+ | The photo is uploaded once per photo URL, so the host's `imageUrl` must change when the photo does (a versioned URL); new bytes at an old URL are never re-uploaded: its `imagePath` is kept on the row and reused while the URL is the same; a loader that reads nothing keeps it (the PUT replaces the whole item); a refused upload (413, another 4xx) publishes without a photo with the warning IMAGE_TOO_LARGE / IMAGE_REFUSED | choice |
118
+ | Errors: 400 malformed, 401 token, 403 module not contracted (the catalogue module must be enabled for the app), 404, 409 `externalCode` reused, 422 business rule, 429 rate limit, 500; do not retry 4xx but 429 | CONFIRMED — Errors |
119
+ | Rate limits: 3000 req/min for `PUT /items` and the category calls, 5000 req/min for the item status and price PATCHes | CONFIRMED — [Rate limit](https://developer.ifood.com.br/en-US/docs/getting-started/documentation/rate-limit/) (it spells the PATCH paths `/item/status`, singular, where Endpoints spells `/items/status`; the adapter uses Endpoints') |
120
+ | The category list answers an array of `{ id, name }`, oldest first: after a create the adapter reads it again and adopts the first of that name, so a create whose answer was lost is not repeated | ESTIMATED |
121
+ | `item.productId` names the item's product, and `products[].imagePath` carries the uploaded photo | ESTIMATED (the pages read show neither field on a full example; the Errors page names `imagePath` as what the item carries) |
122
+ | OFF is the item paused (`UNAVAILABLE`): no item delete is listed on the Endpoints page; a paused item is not shown in the app | ESTIMATED as the meaning of "removed"; the call is CONFIRMED |
123
+ | A 404 on the withdraw means the item is already out | ESTIMATED |
124
+ | A category the store deleted on iFood's portal makes `PUT /items` answer 400 or 404; then the list is read again, and a category of that name with another id (or none) means the stored id is stale: it is forgotten, found or created again, and the PUT sent once more | ESTIMATED (the Errors page does not say which id a 400/404 is about) |
125
+ | A publish lands in the DEFAULT (delivery) context only; no `contextModifiers` are sent | choice |
126
+
127
+ **99Food — pull, Open Delivery v1.7.1** (`src/99food/catalogue.ts`)
128
+
129
+ | fact | status |
130
+ |---|---|
131
+ | The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`; the ordering application (99Food) pulls it. `Merchant` requires `lastUpdate`, `TTL` (500–86400 s: pulled again when it runs out), `id`, `status`, `basicInfo`, `services`, `items`, `menus`, `categories`, `itemOffers` | CONFIRMED — [openapi.yaml](https://abrasel-nacional.github.io/opendelivery/openapi.yaml), `getMerchant`, `Merchant` |
132
+ | `Menu { id, name, externalCode, categoryId[] }`; `Category { id (uuid), index, name, externalCode, status, itemOfferId[] }`; `Item { id (uuid), name, description, externalCode, unit, status?, image? { URL } }`; `ItemOffer { id, itemId, index, price { value, originalValue, currency } }` — the price lives on the offer | CONFIRMED — same, the schemas |
133
+ | `POST /v1/merchantUpdate` on 99Food, sent with an EMPTY body, makes it read `GET /v1/merchant` again; 200 or 204 | CONFIRMED — same, operation `menuUpdated` |
134
+ | `GET /v1/merchantStatus?merchantId=` answers the last read's outcome (SUCCESS, PROCESSING, FAIL) | CONFIRMED — same; not called by this adapter (a later check) |
135
+ | The notification's path: the prose and the route table say `/v1/merchantUpdate`, the path key says `/v1/menuUpdated`; the adapter sends the former | ESTIMATED |
136
+ | `X-App-MerchantId` on the notification (the operation lists no header) | ESTIMATED |
137
+ | A product in the document is PUBLISHED once 99Food took the notification, not once it read the menu | choice |
138
+
139
+ **Rappi — not supported** (no `catalogue` on the adapter)
140
+
141
+ | fact | status |
142
+ |---|---|
143
+ | The menu is written whole: `POST https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/menu` with `{ storeId, items[] }` (`name`, `description`, `imageUrl`, `price`, `sku`, `category`, `children` toppings), parent stores only | CONFIRMED — [Managing Store Menus](https://dev-portal.rappi.com/en/managing-store-menus/) |
144
+ | A sent menu goes to approval ("Menu updated and ready to be validated"), its status at `GET …/menu/approved/{storeId}`; while one is in approval, every further menu of the store is IGNORED; a rejection is a 400 with each failed validation | CONFIRMED — same |
145
+ | Availability by SKU, `PUT …/availability/stores/items` `[{ store_integration_id, items: { turn_on, turn_off } }]`, only turns items Rappi already has on or off | CONFIRMED — [Managing Availability](https://dev-portal.rappi.com/en/managing-availability/) (the page's URL line says `/token`, its heading `availability/stores/items`) |
146
+
147
+ So a per-product switch cannot be built honestly on Rappi's public API: each
148
+ publish would REPLACE the store's whole Rappi menu with the products switched
149
+ on here (wiping what the store keeps on Rappi's portal), and a second switch
150
+ inside the approval window would be dropped while the row said "in the
151
+ catalogue". The capability is absent, `engine.catalogueMode("RAPPI")` is null,
152
+ and the host shows Rappi as not publishable. Supporting it later is a pull-like
153
+ whole-menu mode over the same rows, once a store accepts that its Rappi menu
154
+ is exactly what it switches on here.
155
+
63
156
  ## iFood is unverified
64
157
 
65
- iFood's developer portal refused our reader, so the iFood adapter's URLs, body
66
- fields and reason codes come from the portal's search snippets (2026-11-11).
158
+ iFood's developer portal refused our reader, so the iFood adapter's ORDER URLs,
159
+ body fields and reason codes come from the portal's search snippets
160
+ (2026-11-11). (Its Catalog module's pages were read whole on 2026-11-13: see
161
+ [Catalogue publishing](#catalogue-publishing).)
67
162
  They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
68
163
  headers say so, so the homologation run corrects two files. Tests never reach
69
164
  iFood: the HTTP client is the host's port.
165
+
166
+ ## 99Food, on Open Delivery
167
+
168
+ 99Food completed Open Delivery (Abrasel) adherence, so its adapter speaks
169
+ [Open Delivery v1.7.1](https://abrasel-nacional.github.io/opendelivery/openapi.yaml)
170
+ and is registered as `NINETY_NINE_FOOD`. Its webhook is the engine's one
171
+ route, `POST /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.
172
+
173
+ ```ts
174
+ import { createNinetyNineFoodAdapter } from "@12-apps/marketplace/99food";
175
+ import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/99food/pt-BR";
176
+
177
+ createNinetyNineFoodAdapter({
178
+ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR,
179
+ apiBaseUrl: { SANDBOX: "https://…", PRODUCTION: "https://…" }, // from 99Food, at partner onboarding
180
+ portalUrl: "https://…", // the merchant portal
181
+ });
182
+ ```
183
+
184
+ | part | from the spec |
185
+ |---|---|
186
+ | Webhook | `X-App-Signature`: lowercase hex HMAC-SHA256 of the body, keyed by the CLIENT SECRET. A connection stores that same value as its `webhookSecret`, and a connection without one REFUSES every delivery (the key exists from the moment the store connects). The merchant is the `X-App-MerchantId` header; the engine attributes by the URL's store slug. |
187
+ | Merchant id | A connection's `externalMerchantId` for 99Food is the Open Delivery **merchant id** — the spec's `Merchant.id`, which the merchant's Software Service (the host) generates and registers with 99Food, and which 99Food echoes as `X-App-MerchantId` and `Order.merchant.id`. It is NOT 99Food's own internal id for the store shown on its portal. A fetched order whose `merchant.id` differs is refused and its inbox row settled FAILED, so correcting the connection's id lets the reconciliation sweep fetch it again within the attempt bound. |
188
+ | Events | `CREATED` → fetch the order (`GET /v1/orders/{orderId}`); `CANCELLED` → cancelled (answers a pending request; one that outruns the fetch leaves a marker, and the fetch then ingests nothing — or, when it lands while the ingest is being written, cancels the order it just wrote); `CANCELLATION_REQUEST_DENIED` → the request FAILED. The rest (`CONFIRMED`, `CANCELLATION_REQUESTED`, `ORDER_CANCELLATION_REQUEST`, `DISPATCHED`…) are recorded and IGNORED. |
189
+ | Auth | `POST /oauth/token`, form-encoded `client_credentials`; the token is cached per process. |
190
+ | Confirm | `POST /v1/orders/{orderId}/confirm` with `OrderConfirmed` (`orderExternalCode` = the host's order id, `createdAt`, `preparationTime` when stated). Every 422 is a refusal: the store sees "não confirmou" and the app link. The spec's 422 cannot tell a duplicate from a cancelled order, so a retried confirm whose first answer was lost shows that same harmless alarm. |
191
+ | Cancel | `POST /v1/orders/{orderId}/requestCancellation` with `{ reason, code, mode }`; the eleven merchant codes are the adapter's static reasons. 202, then an event. A 422 whose `cancellationStatus` is `CANCELLED` is done. |
192
+ | Order | `total.orderAmount` is the gross total. The `Order` states no commission, so `commissionCents` is null. An item's lines always add up to its `totalPrice`: a total that does not divide by the quantity is split into (q−1) units at the floor and one carrying the remainder, same SKU. Options and instructions go into the line's note; a weighed item is one line at its total. The acceptance deadline counts from the event's arrival; the liveness stamp and an auto-accept's time are the ingest's own. |
193
+
194
+ The fixtures are the spec's own examples (`src/99food/__tests__/fixtures.ts`).
195
+ `src/99food/__tests__/engine.test.ts` drives the engine through the adapter
196
+ end to end: event, fetch, ingest, aceite, confirm, cancel, the answer.
197
+
198
+ **ESTIMATED, to be checked live once 99Food grants partner access:**
199
+
200
+ - the base URLs and the portal: not public, so they are required config;
201
+ - `OrderConfirmed.createdAt` is sent as the moment of the confirmation (the
202
+ spec's description of that field is copied from the order's);
203
+ - the cancellation answer window, 5 minutes (the spec names none);
204
+ - a token with no `expires_in` lives an hour (the field is optional);
205
+ - `outOfStockItems` is not sent: the spec wants item uuids there, and the
206
+ engine keeps the marketplace's SKUs (`externalCode`);
207
+ - with no `totalPrice`, a line is `unitPrice × quantity + optionsPrice` (options added once: the spec calls it a line figure);
208
+ - with no `externalCode`, a line keys on the item id, which may be per order (then each such order adds an unmapped SKU row);
209
+ - that 99Food sends every event by webhook (Open Delivery also allows
210
+ polling, which this adapter does not do).
211
+
212
+ ## Rappi, from its public developer portal
213
+
214
+ Built now (owner, 2026-11-11) from what [dev-portal.rappi.com](https://dev-portal.rappi.com)
215
+ shows publicly (managing-user-orders, api-reference/orders, webhook-events,
216
+ authentication-process, read 2026-11-13), to be confirmed against Rappi's
217
+ sandbox once Rappi's account manager opens it. Registered as `RAPPI`; its
218
+ webhooks are the engine's one route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.
219
+
220
+ ```ts
221
+ import { createRappiAdapter } from "@12-apps/marketplace/rappi";
222
+ import { RAPPI_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/rappi/pt-BR";
223
+
224
+ createRappiAdapter({
225
+ copy: RAPPI_ADAPTER_COPY_PT_BR,
226
+ apiBaseUrl: { SANDBOX: "https://…", PRODUCTION: "https://…" }, // https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api
227
+ tokenUrl: { SANDBOX: "https://…", PRODUCTION: "https://…" }, // https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations
228
+ portalUrl: "https://…", // the partner portal
229
+ amountUnit: "MINOR_UNITS", // or "MAJOR_UNITS": how Rappi states money here
230
+ });
231
+ ```
232
+
233
+ | part | from the portal |
234
+ |---|---|
235
+ | Webhook | Register `NEW_ORDER` and `ORDER_EVENT_CANCEL` (each its own subscription, both pointing at this one URL). `Rappi-Signature: t=<timestamp>,sign=<signature>`, HMAC-SHA256 of `<t>.<raw body>` keyed by the webhook's secret. A connection stores that secret as its `webhookSecret`, and a connection without one REFUSES every delivery. |
236
+ | Events | Rappi's bodies do not name their event, so the adapter reads the shape. An `order_detail` is `NEW_ORDER` → ingested (with `action: "scheduled"` / `"cancelled"`, the two scheduled notices → IGNORED). `{ event, order_id, store_id }` naming a cancellation (`canceled_with_charge`) → cancelled. `ORDER_OTHER_EVENT` (it carries `event_time`) → IGNORED. PING, menu and store events name no order and are acknowledged 200 and dropped. |
237
+ | Merchant id | A connection's `externalMerchantId` for Rappi is **Rappi's store id**: `store.internal_id` on `NEW_ORDER`, `store_id` on every other event. A `NEW_ORDER` naming another store is settled FAILED (so the reconciliation sweep ingests it once the id is corrected) and the webhook answers 500. |
238
+ | Auth | `POST {tokenUrl}` (the portal's `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`), JSON `{ client_id, client_secret }` → `access_token`, valid one week; sent as `x-authorization: Bearer <token>`; cached per process. |
239
+ | Take (the confirm) | `PUT {apiBaseUrl}/orders/{orderId}/take/{cookingTime}` (the portal's base is `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`), the store's preparation minutes (`take/` keeps the order's own). 400 "Invalid state transition" and 404 are refusals: "não confirmou" and the app link. |
240
+ | Reject (the cancel) | `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type, items_skus }`: one of the portal's six `cancel_type`s, the three item ones requiring the offending SKUs. Only from SENT. The 200 IS the outcome (`asyncCancellationOutcome: false`): CONFIRMED at once. Every refused answer is a refusal (FAILED, the portal link). |
241
+ | Cancel after take | No public endpoint: `cancelAfterAccept: false`, so the store's cancel of a taken order is FAILED at once and opens the partner portal (`appLink`; Rappi names no per-order link). |
242
+ | Windows | Rappi gives a SENT order 6 minutes to be taken or rejected before its own TIMEOUT, so a reject still waiting 6 minutes after it was asked is failed as TIMEOUT (`cancellationAnswerWindowMs`). Rappi counts from the order's arrival and the engine from the request, so a reject asked late may still be sent after Rappi's TIMEOUT and come back 400 (FAILED, the portal link). A connection's acknowledgement window should be at most 360 s. |
243
+ | Order | `totals.total_order`, "the total amount that the restaurant receives", is the total; Rappi states no commission (`commissionCents` null). A line is an item at `price` plus its subitems, `× quantity`, so its rows add up exactly to it; subitems and comments go into the note; an item with no `sku` keys on Rappi's item id. `delivery` is Rappi's courier, `marketplace` the store's own, `pickup` a take-out. |
244
+
245
+ The fixtures are the portal's own examples (`src/rappi/__tests__/fixtures.ts`).
246
+ `src/rappi/__tests__/engine.test.ts` drives the engine through the adapter end
247
+ to end: webhook, ingest, aceite, take, reject, Rappi's cancel, and R3-N2.
248
+
249
+ **ESTIMATED, to be checked against the Rappi sandbox (api.dev.rappi.com):**
250
+
251
+ - the orders API's base and the token URL per environment, and the portal:
252
+ Rappi names its domains by country, so they are required config (whole
253
+ URLs, path included: the paths name the origin application's own noun);
254
+ - how money is stated: integers with no unit in the portal; `amountUnit` is
255
+ required config (`MINOR_UNITS` cents, `MAJOR_UNITS` whole units);
256
+ - that the `NEW_ORDER` body is ONE `GET orders` element (the portal says "the
257
+ same information" and shows no example);
258
+ - telling `ORDER_EVENT_CANCEL` from `ORDER_OTHER_EVENT`: no `event_time` or
259
+ `additional_information`, and `cancel` in the `event` name; anything else is
260
+ recorded and IGNORED, never a cancellation;
261
+ - the signature digest is lowercase hex (the example is 64 hex characters); no
262
+ timestamp tolerance is applied (the portal states none; a replay is an inbox
263
+ duplicate);
264
+ - the token answer's shape beyond `access_token`: an `expires_in` is read when
265
+ present, else the portal's one week;
266
+ - a subitem's `price × quantity` is per unit of its item;
267
+ - an offending item with no `sku` is sent in `items_skus` under Rappi's item
268
+ id, where the portal wants `items_ids`;
269
+ - no `PING` answer: the route answers `{ received: true }`, not Rappi's
270
+ `{ "status": "OK" }`, so do not subscribe `PING` until the host answers it;
271
+ - that Rappi sends every order by webhook: `GET orders` / `orders/status/sent`
272
+ polling is not done by this adapter;
273
+ - that Rappi serves `…/take/` with an empty cooking-time segment (the guide's
274
+ spelling) when the store states no preparation time;
275
+ - the reject window counted from the request, where Rappi counts from the
276
+ order's arrival (see Windows);
277
+ - that the 500 a merchant mismatch answers is harmless: Rappi redelivers, the
278
+ redelivery is an inbox duplicate answered 200; whether Rappi throttles or
279
+ disables a webhook after repeated 500s is not public.
280
+
281
+ Out of scope: the merchant check applies to the NEW_ORDER body only. An
282
+ `ORDER_EVENT_CANCEL` naming another `store_id` under this connection's secret
283
+ still cancels a matching order id: the signature binds the connection's own
284
+ secret, and judging event merchants in the engine would change iFood's path.
285
+
286
+ ### A late synchronous answer (R3-N2)
287
+
288
+ A synchronous marketplace answers a cancellation in the response. When the
289
+ outbound sweep times a request out while the call is still in flight, the
290
+ store may accept the order before the answer lands. The accept clears the
291
+ request but keeps its `cancellation_requested_at` as a TOMBSTONE, and the job
292
+ matches a status-less row of a STILL ACCEPTED order carrying the same
293
+ instant: a late "rejected" to the call in flight still moves the order to
294
+ REJECTED (CONFIRMED) and tells the host `onCancellationConfirmed`. A late
295
+ refusal matches nothing and leaves the accepted order as it is; and once the
296
+ marketplace's own cancel event has rejected the order (telling the host), the
297
+ tombstone answers nothing more, so the host is told once.
298
+
299
+ What it does NOT cover: a call Rappi APPLIED but answered with a 5xx or not at
300
+ all. Its retry runs after the store's accept, finds no request and sends
301
+ nothing, so the order stays ACCEPTED here while cancelled on Rappi. The take
302
+ the accept queued is then answered 400, so the order shows "não confirmou"
303
+ with the portal link and a person settles it there.
@@ -0,0 +1,19 @@
1
+ /** The 99Food adapter's en-US pack: the same reasons, in English. */
2
+ declare const NINETY_NINE_FOOD_ADAPTER_COPY_EN_US: {
3
+ readonly reasonLabels: {
4
+ readonly SYSTEMIC_ISSUES: "System problems";
5
+ readonly DUPLICATE_APPLICATION: "Duplicate order";
6
+ readonly UNAVAILABLE_ITEM: "Item unavailable";
7
+ readonly RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available";
8
+ readonly OUTDATED_MENU: "Menu out of date";
9
+ readonly ORDER_OUTSIDE_THE_DELIVERY_AREA: "Address outside the delivery area";
10
+ readonly BLOCKED_CUSTOMER: "Blocked customer";
11
+ readonly OUTSIDE_DELIVERY_HOURS: "Outside delivery hours";
12
+ readonly INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties";
13
+ readonly RISK_AREA: "Risk area";
14
+ readonly DELIVERY_PROBLEM: "Delivery problem";
15
+ };
16
+ readonly missingStreetNumber: "no number";
17
+ };
18
+
19
+ export { NINETY_NINE_FOOD_ADAPTER_COPY_EN_US };
@@ -0,0 +1,23 @@
1
+ import "../chunk-7QVYU63E.js";
2
+
3
+ // src/99food/en-US.ts
4
+ var NINETY_NINE_FOOD_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ SYSTEMIC_ISSUES: "System problems",
7
+ DUPLICATE_APPLICATION: "Duplicate order",
8
+ UNAVAILABLE_ITEM: "Item unavailable",
9
+ RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available",
10
+ OUTDATED_MENU: "Menu out of date",
11
+ ORDER_OUTSIDE_THE_DELIVERY_AREA: "Address outside the delivery area",
12
+ BLOCKED_CUSTOMER: "Blocked customer",
13
+ OUTSIDE_DELIVERY_HOURS: "Outside delivery hours",
14
+ INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties",
15
+ RISK_AREA: "Risk area",
16
+ DELIVERY_PROBLEM: "Delivery problem"
17
+ },
18
+ missingStreetNumber: "no number"
19
+ };
20
+ export {
21
+ NINETY_NINE_FOOD_ADAPTER_COPY_EN_US
22
+ };
23
+ //# sourceMappingURL=en-US.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/99food/en-US.ts"],"sourcesContent":["import type { NinetyNineFoodAdapterCopy } from \"./copy\";\n\n/** The 99Food adapter's en-US pack: the same reasons, in English. */\nexport const NINETY_NINE_FOOD_ADAPTER_COPY_EN_US = {\n reasonLabels: {\n SYSTEMIC_ISSUES: \"System problems\",\n DUPLICATE_APPLICATION: \"Duplicate order\",\n UNAVAILABLE_ITEM: \"Item unavailable\",\n RESTAURANT_WITHOUT_DELIVERY_PERSON: \"No courier available\",\n OUTDATED_MENU: \"Menu out of date\",\n ORDER_OUTSIDE_THE_DELIVERY_AREA: \"Address outside the delivery area\",\n BLOCKED_CUSTOMER: \"Blocked customer\",\n OUTSIDE_DELIVERY_HOURS: \"Outside delivery hours\",\n INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: \"Internal difficulties\",\n RISK_AREA: \"Risk area\",\n DELIVERY_PROBLEM: \"Delivery problem\",\n },\n missingStreetNumber: \"no number\",\n} as const satisfies NinetyNineFoodAdapterCopy;\n"],"mappings":";;;AAGO,IAAM,sCAAsC;AAAA,EACjD,cAAc;AAAA,IACZ,iBAAiB;AAAA,IACjB,uBAAuB;AAAA,IACvB,kBAAkB;AAAA,IAClB,oCAAoC;AAAA,IACpC,eAAe;AAAA,IACf,iCAAiC;AAAA,IACjC,kBAAkB;AAAA,IAClB,wBAAwB;AAAA,IACxB,yCAAyC;AAAA,IACzC,WAAW;AAAA,IACX,kBAAkB;AAAA,EACpB;AAAA,EACA,qBAAqB;AACvB;","names":[]}
@@ -0,0 +1,162 @@
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, P as PullCatalogue, C as CatalogueMenuEntry, b as CatalogueMenuOptions, M as MarketplaceAdapter } from '../adapter-0l_EmuJA.js';
2
+
3
+ /**
4
+ * The words the 99Food adapter needs from its host, and nothing else.
5
+ *
6
+ * Required and defaultless, like every copy port in this repo: the adapter
7
+ * ships no language of its own. Two packs sit beside it (`./pt-BR`,
8
+ * `./en-US`); a host passes one by hand, or its own.
9
+ */
10
+ /**
11
+ * The cancellation codes a merchant may send, verbatim from Open Delivery
12
+ * v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two
13
+ * codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,
14
+ * `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.
15
+ */
16
+ declare const NINETY_NINE_FOOD_REASON_CODES: readonly ["SYSTEMIC_ISSUES", "DUPLICATE_APPLICATION", "UNAVAILABLE_ITEM", "RESTAURANT_WITHOUT_DELIVERY_PERSON", "OUTDATED_MENU", "ORDER_OUTSIDE_THE_DELIVERY_AREA", "BLOCKED_CUSTOMER", "OUTSIDE_DELIVERY_HOURS", "INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT", "RISK_AREA", "DELIVERY_PROBLEM"];
17
+ type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];
18
+ interface NinetyNineFoodAdapterCopy {
19
+ /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */
20
+ reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;
21
+ /** What an address with no street number says instead. */
22
+ missingStreetNumber: string;
23
+ }
24
+
25
+ /**
26
+ * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth
27
+ * grant, the order fetch, confirm and requestCancellation. Paths, verbs,
28
+ * bodies and answers are the spec's; the job that calls these, its retries
29
+ * and what a failure shows are the engine's.
30
+ *
31
+ * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the
32
+ * paths under each Ordering Application's own base URL, and 99Food gives its
33
+ * base URLs to a partner at onboarding. So the base URL per environment is
34
+ * the adapter's REQUIRED config, never a guessed default. Tests never reach
35
+ * 99Food: the HTTP client is the host's port, answered by a fake.
36
+ */
37
+ /** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */
38
+ type NinetyNineFoodApiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
39
+
40
+ /**
41
+ * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).
42
+ *
43
+ * Open Delivery splits what iFood sends at once: the webhook's `Event` names
44
+ * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and
45
+ * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So
46
+ * there are two readers here: {@link normalizeOpenDeliveryEvent} for the
47
+ * webhook (a `CREATED` becomes `orderToFetch`), and
48
+ * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.
49
+ *
50
+ * Every shape below is the spec's (`components/schemas/Event`, `Order`,
51
+ * `Price`, `Address`), and every fixture in the tests is the spec's own
52
+ * example. Read defensively all the same: a missing field produces null, and
53
+ * only a missing order id refuses an event (it is the idempotency key).
54
+ */
55
+ /** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */
56
+ declare const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
57
+ /**
58
+ * Verify a delivery: Open Delivery's `X-App-Signature` is "a lowercased
59
+ * hexadecimal HMAC signature of the webhook HTTP request body, using the
60
+ * client secret as a key and SHA256 as the hash function". The key is the
61
+ * merchant app's CLIENT SECRET, so a store's connection keeps that same value
62
+ * as its webhook secret.
63
+ *
64
+ * Unlike iFood (whose secret is issued after certification), the key exists
65
+ * from the moment the store connects, so an unset secret REFUSES: an unsigned
66
+ * CANCELLED for a known order id would otherwise cancel it.
67
+ */
68
+ declare function verifyOpenDeliverySignature(rawBody: string, signature: string | null, webhookSecret: string | null): boolean;
69
+ /**
70
+ * Normalize one webhook `Event`. Null only when it names no order.
71
+ *
72
+ * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
73
+ * - `CANCELLED` is a cancellation, whether the store asked for it or not.
74
+ * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
75
+ * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the
76
+ * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
77
+ * recorded, and acts on nothing: an IGNORED inbox row.
78
+ *
79
+ * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the
80
+ * engine attributes a delivery by its URL's store slug, so it reads none.
81
+ */
82
+ declare function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null;
83
+ /**
84
+ * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when
85
+ * it carries no id or no line.
86
+ *
87
+ * The total is `total.orderAmount`, "the final value of the order (itemsPrice
88
+ * + otherFees - discounts)": the buyer's receipt, gross. Open Delivery's
89
+ * `Order` states NO commission field, so `commissionCents` is null ("did not
90
+ * say"), never 0; the marketplace's cut arrives with its statement.
91
+ */
92
+ declare function normalizeOpenDeliveryOrder(order: unknown, options: {
93
+ missingStreetNumber: string;
94
+ }): NormalizedMarketplaceOrder | null;
95
+
96
+ /** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */
97
+ declare function openDeliveryMenuDocument(input: {
98
+ externalMerchantId: string;
99
+ entries: readonly CatalogueMenuEntry[];
100
+ options: CatalogueMenuOptions;
101
+ }): {
102
+ menus: {
103
+ id: string;
104
+ name: string;
105
+ externalCode: string;
106
+ categoryId: string[];
107
+ }[];
108
+ categories: {
109
+ id: string;
110
+ index: number;
111
+ name: string;
112
+ externalCode: string;
113
+ status: string;
114
+ itemOfferId: string[];
115
+ }[];
116
+ items: {
117
+ image?: {
118
+ URL: string;
119
+ } | undefined;
120
+ id: string;
121
+ name: string;
122
+ description: string;
123
+ externalCode: string;
124
+ status: string;
125
+ unit: string;
126
+ }[];
127
+ itemOffers: {
128
+ id: string;
129
+ itemId: string;
130
+ index: number;
131
+ status: string;
132
+ price: {
133
+ value: number;
134
+ originalValue: number;
135
+ currency: string;
136
+ };
137
+ }[];
138
+ };
139
+ /** 99Food's catalogue capability, for the base URLs it was given. */
140
+ declare function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue;
141
+
142
+ /** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
143
+ declare const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS: number;
144
+ interface NinetyNineFoodAdapterConfig {
145
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
146
+ copy: NinetyNineFoodAdapterCopy;
147
+ /**
148
+ * Where 99Food serves Open Delivery, per environment: the base the spec's
149
+ * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at
150
+ * onboarding and not public, so required and defaultless. https only.
151
+ */
152
+ apiBaseUrl: NinetyNineFoodApiBaseUrls;
153
+ /**
154
+ * Where "open it on 99Food" goes: the merchant portal. Open Delivery names no
155
+ * per-order deep link, so the link is the portal. Required; https only.
156
+ */
157
+ portalUrl: string;
158
+ }
159
+ /** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
160
+ declare function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter;
161
+
162
+ export { NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS, NINETY_NINE_FOOD_PROVIDER, NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterConfig, type NinetyNineFoodAdapterCopy, type NinetyNineFoodApiBaseUrls, type NinetyNineFoodReasonCode, createNinetyNineFoodAdapter, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, openDeliveryCatalogue, openDeliveryMenuDocument, verifyOpenDeliverySignature };