@12-apps/marketplace 1.3.0 → 1.5.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 (59) hide show
  1. package/ADOPTING.md +47 -0
  2. package/README.md +122 -1
  3. package/dist/99food/index.d.ts +33 -2
  4. package/dist/99food/index.js +34 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-0l_EmuJA.d.ts → adapter-CCWMqt2g.d.ts} +275 -3
  7. package/dist/{chunk-XUAFXNOH.js → chunk-FKUEFVVA.js} +396 -4
  8. package/dist/chunk-FKUEFVVA.js.map +1 -0
  9. package/dist/{chunk-RVBTARIY.js → chunk-RGMSD7S7.js} +1 -1
  10. package/dist/chunk-RGMSD7S7.js.map +1 -0
  11. package/dist/{chunk-AYYBRQJV.js → chunk-UONWZIBO.js} +43 -3
  12. package/dist/chunk-UONWZIBO.js.map +1 -0
  13. package/dist/chunk-WN2EK4KX.js +15 -0
  14. package/dist/chunk-WN2EK4KX.js.map +1 -0
  15. package/dist/{engine-CZsP8KWd.d.ts → engine-C3uq_BJd.d.ts} +252 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +44 -2
  19. package/dist/ifood/index.js +441 -1
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +342 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +4 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +56 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +18 -7
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +67 -1
  33. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  34. package/src/99food/index.ts +10 -0
  35. package/src/99food/pause.ts +56 -0
  36. package/src/core/adapter.ts +19 -2
  37. package/src/core/catalogue-read-port.ts +151 -0
  38. package/src/core/catalogue-read.ts +51 -0
  39. package/src/core/engine.ts +46 -0
  40. package/src/core/pause-job.ts +381 -0
  41. package/src/core/pause-port.ts +110 -0
  42. package/src/core/pause-retired.ts +139 -0
  43. package/src/core/pause-store.ts +151 -0
  44. package/src/core/pause-sweep.ts +148 -0
  45. package/src/core/pause.ts +316 -0
  46. package/src/core/ports.ts +11 -0
  47. package/src/ifood/catalogue-read.ts +187 -0
  48. package/src/ifood/catalogue-snapshot.ts +246 -0
  49. package/src/ifood/index.ts +9 -0
  50. package/src/ifood/pause.ts +257 -0
  51. package/src/index.ts +39 -0
  52. package/src/rappi/index.ts +11 -0
  53. package/src/rappi/outbound.ts +2 -2
  54. package/src/rappi/pause.ts +98 -0
  55. package/src/server/index.ts +1 -0
  56. package/src/server/jobs.ts +64 -4
  57. package/dist/chunk-AYYBRQJV.js.map +0 -1
  58. package/dist/chunk-RVBTARIY.js.map +0 -1
  59. package/dist/chunk-XUAFXNOH.js.map +0 -1
package/ADOPTING.md CHANGED
@@ -227,3 +227,50 @@ The stock draw at the acceptance, the settlement effects, the board's and the
227
227
  order screen's UI, the cancel route itself, the HTTP client's timeout and CA,
228
228
  the jobs runtime and its leases, which roles hold the two permissions, and
229
229
  every sentence a person reads.
230
+
231
+ ## 7. Pausing a store
232
+
233
+ The store pause (FUT-4851) closes the store on every connected marketplace
234
+ while the host's kitchen is paused. Everything the host owns about it:
235
+
236
+ **When to call.** The host decides when its kitchen is paused and runs the
237
+ debounce (a store setting beside the cap, 3 minutes by default: pause at once
238
+ when the cap is passed, reopen only after the queue stayed under it that long).
239
+ The engine never debounces.
240
+
241
+ | call | who calls it, and when |
242
+ |---|---|
243
+ | `pauseStore({ clientId, until, reason, timeZone })` | The kitchen enters its pause, and again on every renewal while it stays paused (each time its estimated reopening time moves, later OR earlier: an earlier end is honoured too, so the store is never closed longer than the kitchen's pause; a renewal every few minutes is fine). `until` is the kitchen's ESTIMATED reopening time and must be in the future (else `{ kind: "invalid", code: "UNTIL_NOT_FUTURE" }`). `reason` is the host's own words (its copy, in the store's language), sent where the marketplace shows one. `timeZone` is the store's IANA zone (one the runtime does not know answers `{ kind: "invalid", code: "TIME_ZONE_INVALID" }`). Answers per live connection: `queued`, `unchanged` (a pause with exactly this end already stands or is on its way), `unsupported` (the adapter has no `availability`), `not-connected` (no credentials or no merchant id). |
244
+ | `resumeStore({ clientId })` | The moment the kitchen's pause is over (after the host's debounce). Deletes only what the engine created; answers `queued`, `open` (nothing of ours stood there: nobody is called) or `unchanged`. |
245
+ | `availabilityState(clientId)` | The screen: per live connection `{ provider, supported, kind, connected, state, wanted, until, sentUntil, failureCode, failureDetail, pausedAt, resumedAt, updatedAt }`. `state` is `OPEN`, `PAUSING`, `PAUSED`, `RESUMING` or `FAILED`; draw `supported: false` as "this marketplace cannot be paused from here". `failureCode` is a code for the host's copy; `failureDetail` is the marketplace's own words, never copy. |
246
+
247
+ If the host stops renewing (it died, or never called `resumeStore`), the
248
+ availability sweep resumes the store on its own once `until` has passed: the
249
+ store is never closed on a marketplace longer than the kitchen's own pause.
250
+
251
+ **The jobs.** Bind the two new blueprints with the rest of `MARKETPLACE_JOBS`
252
+ (`{ engine }`): `marketplace.availability` (on demand, three attempts, short
253
+ backoff) and `marketplace.availability-sweep` (every five minutes, on the
254
+ single-flight `sweeps` queue). A host that adopts the wiring manifest gets
255
+ them with the others. A host that declines `jobs` gets no pause at all: every
256
+ ask stays `PAUSING`, so it must not call `pauseStore`.
257
+
258
+ **The outbound gate.** No path that answers a request calls a marketplace:
259
+ `pauseStore` and `resumeStore` record the ask and queue the job, and the job
260
+ calls the adapter through the host's `http` port, as `confirm` does. A host
261
+ that gates outbound calls (an environment where nothing may reach a real
262
+ marketplace) gates the `http` port, and every pause call goes through it.
263
+
264
+ **The switches.** Rappi and 99Food can only switch a whole store on or off,
265
+ with no id and no end, so the engine cannot tell its own closure from one the
266
+ owner ALSO made by hand on the marketplace during the kitchen's pause (that
267
+ one would be reopened with it). Their adapters offer the capability only with
268
+ `pauseByStoreSwitch: true`; leave it off to keep them `unsupported`.
269
+
270
+ **The database.** Migration `20261113230000_marketplace_store_pause` adds
271
+ `marketplace_store_pauses` (one row per store and marketplace, CHECKed
272
+ vocabularies, no foreign key; add `client_id → <tenants>(id) ON DELETE CASCADE`
273
+ if you want one). The `MarketplaceDb.marketplaceStorePause` delegate is
274
+ OPTIONAL in the type, so a 1.x host compiles before it migrates; `pauseStore`
275
+ and `resumeStore` throw naming the migration until it does, and
276
+ `availabilityState` reads every marketplace OPEN.
package/README.md CHANGED
@@ -48,7 +48,7 @@ engine code (`src/__tests__/second-adapter.test.ts`).
48
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. |
49
49
  | **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
50
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`. |
51
+ | **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, `capabilities`, and the optional `fetchOrder`, `catalogue` and `catalogueReader`. |
52
52
 
53
53
  ## Subpaths
54
54
 
@@ -153,6 +153,56 @@ and the host shows Rappi as not publishable. Supporting it later is a pull-like
153
153
  whole-menu mode over the same rows, once a store accepts that its Rappi menu
154
154
  is exactly what it switches on here.
155
155
 
156
+ ## Catalogue reading
157
+
158
+ FUT-951: during onboarding a store imports the menu it already keeps on a
159
+ marketplace. The engine reads it through the store's OWN connection (its
160
+ merchant id and sealed credentials, the same client-credentials grant the
161
+ orders use): no platform app, no homologation credentials. Nothing is stamped
162
+ or queued; the host asks while the store waits.
163
+
164
+ ```ts
165
+ const result = await engine.readCatalogue({ clientId, provider: "IFOOD" });
166
+ // { kind: "snapshot", snapshot: { categories, notices } }
167
+ // { kind: "refused", code: "UNSUPPORTED" | "NOT_CONNECTED" | "CREDENTIALS" | "NOT_AUTHORIZED" | "REFUSED", status, message }
168
+ // { kind: "retry", reason } // 429, 5xx, a timeout: ask again later
169
+ ```
170
+
171
+ | part | what it is |
172
+ |---|---|
173
+ | **The port** | `adapter.catalogueReader.read(ctx)` (`CatalogueReader`), optional and independent of `catalogue`: a marketplace may be read without being published to. `ctx` is the outbound context plus `externalMerchantId`. |
174
+ | **The snapshot** | `categories[]` → `items[]`, each with `externalId`, `externalCode`, `name`, `description`, `priceCents` (null when none), `photoUrl` (absolute, or null), `available`, `optionGroups[]` (`name`, `min`, `max`, `options[]` with `name`, `priceDeltaCents`, `photoUrl`, `available`) and `warnings[]`. Sizes, flavours and add-ons are all option groups. |
175
+ | **Money** | Integer cents of the menu's currency, `centsFromMajor(value)`: cut to 12 significant digits (no float error), then rounded half up to the cent (`1.005` → 101). A negative or non-numeric price is no price. |
176
+ | **Nothing dropped silently** | A field that cannot be mapped is a warning on its item (`PRICE_MISSING`, `OPTION_PRICE_MISSING`, `OPTION_GROUP_UNREADABLE`, `OPTION_UNREADABLE`, `PHOTO_UNREADABLE`, `ITEM_TYPE_UNSUPPORTED`), naming the group or option; an item or category that cannot be read at all is a notice on the snapshot (`ITEM_UNREADABLE`, `CATEGORY_UNREADABLE`). Codes are vocabulary: the host words them. |
177
+ | **Failures** | Before any call the engine refuses `UNSUPPORTED` (no reader), `NOT_CONNECTED` (no live connection with a merchant id), `CREDENTIALS` (none on file, or they do not open), with `status`/`message` null. From the marketplace: `CREDENTIALS` (the token grant refused), `NOT_AUTHORIZED` (this app may not read this merchant), `REFUSED` (another final 4xx, or a category list that is not a list), or `retry`. One category answered in an unexpected shape is a `CATEGORY_UNREADABLE` notice, and the rest of the menu is still read. |
178
+
179
+ **iFood** (`src/ifood/catalogue-read.ts`, `src/ifood/catalogue-snapshot.ts`).
180
+ Read 2026-11-16: the Catalog module's Introduction was read whole; its
181
+ Endpoints, Fundamentals, How it works and Errors pages answered 403 to our
182
+ reader that day, so what they would settle is ESTIMATED below (the push's
183
+ 2026-11-13 reading of them is cited where it applies).
184
+
185
+ | fact | status |
186
+ |---|---|
187
+ | Same base and bearer token as the push: `https://merchant-api.ifood.com.br/catalog/v2.0/merchants/{merchantId}/…`, client-credentials grant of the store's own app | CONFIRMED — [Introduction](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/introduction) |
188
+ | `GET /categories` lists the merchant's categories | CONFIRMED — [Endpoints](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/endpoints), as read 2026-11-13 for the push |
189
+ | `GET /categories/{categoryId}/items` lists a category's items "with their associated complements" | CONFIRMED — Introduction, step 5 |
190
+ | An item is `item` (id, type, categoryId, status, `price { value }` in the major unit, externalCode), `products` (id, name, description, externalCode, and `optionGroups: [{ id, min, max }]` linking a product to its groups), `optionGroups` (id, name, status, `optionIds`), `options` (id, `productId` naming the product with its name, status, `price { value }`) | CONFIRMED as the `PUT /items` payload — Introduction, steps 3 and 4 |
191
+ | The category list answers an array of `{ id, name, status, externalCode }` | ESTIMATED (the push makes the same estimate) |
192
+ | `GET /categories/{categoryId}/items` answers the PUT's four lists as `{ items, products, optionGroups, options }` | ESTIMATED |
193
+ | `item.productId` names the item's product (its name, description, photo); without it the item's own `name` is used | ESTIMATED (the push sends the same field) |
194
+ | `products[].imagePath` is the photo, served under `https://static-images.ifood.com.br/image/upload/t_high/pratos/` (`IFOOD_IMAGE_BASE_URL`); an absolute https path is used as it is | ESTIMATED (the pages read name `imagePath` but not its host; the host is the one iFood's own app loads dish photos from) |
195
+ | No pagination: neither call shows a page, size or cursor parameter, so the menu is read one category per call | ESTIMATED |
196
+ | 401: the token is dropped and the call asked once more with a fresh one; a second 401 is a `retry` | choice (as the push's `call`) |
197
+ | The token grant refused (400/401/403) is `CREDENTIALS`; 403 on a catalogue call (the Errors page: the module is not enabled for the app) is `NOT_AUTHORIZED`; 429, 408, 425 and 5xx are a `retry`; another 4xx is `REFUSED` | CONFIRMED for the statuses — [Errors](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/errors-and-troubleshooting), as read 2026-11-13; the mapping is a choice |
198
+ | A 404 on the category list means this app has no such merchant: `NOT_AUTHORIZED`; a 404 on one category's items (deleted between the calls) leaves that category out with a `CATEGORY_UNREADABLE` notice | ESTIMATED |
199
+ | A photo path is used as a URL path as it is (an encoded `%20` stays); only characters a URL may not carry are encoded | choice |
200
+ | An item `type` other than `DEFAULT` (a pizza, a combo) is read as a plain item with `ITEM_TYPE_UNSUPPORTED` | choice |
201
+ | The read covers the merchant-level categories (the DEFAULT, delivery, context); other catalogs and `contextModifiers` prices are not read | ESTIMATED |
202
+
203
+ 99Food and Rappi state no `catalogueReader`: `engine.readCatalogue` answers
204
+ `UNSUPPORTED` for them.
205
+
156
206
  ## iFood is unverified
157
207
 
158
208
  iFood's developer portal refused our reader, so the iFood adapter's ORDER URLs,
@@ -301,3 +351,74 @@ all. Its retry runs after the store's accept, finds no request and sends
301
351
  nothing, so the order stays ACCEPTED here while cancelled on Rappi. The take
302
352
  the accept queued is then answered 400, so the order shows "não confirmou"
303
353
  with the portal link and a person settles it there.
354
+
355
+ ## Pausing a store (FUT-4851)
356
+
357
+ When the store's kitchen passes its cap, the host closes the store on every
358
+ connected marketplace until the kitchen's ESTIMATED reopening time, renews the
359
+ closure while the kitchen stays paused, and opens the store the moment the
360
+ pause is over. The host owns the debounce (a store setting, 3 minutes by
361
+ default); the engine only receives `pauseStore({ clientId, until, reason,
362
+ timeZone })` and `resumeStore({ clientId })`, and the screen reads
363
+ `availabilityState(clientId)`. The owner's rules and why each part is shaped
364
+ this way: [the decision draft](../../docs/marketplace/decisions/draft-a-store-pause-closes-every-marketplace.md).
365
+ What the host wires: [ADOPTING.md](./ADOPTING.md#7-pausing-a-store).
366
+
367
+ A marketplace is paused through an OPTIONAL adapter capability,
368
+ `availability`, in one of two shapes:
369
+
370
+ - **`interruption`**: the marketplace keeps a closure with its own id and an
371
+ end. The engine stores the id and deletes that id and nothing else, so a
372
+ closure the owner made by hand is never touched; and if every call after
373
+ the pause is lost, the marketplace still opens the store at the end it was
374
+ given.
375
+ - **`switch`**: a store-wide on/off with no id and no end. The engine turns a
376
+ store on only if its own record says it turned it off, and turns it on by
377
+ itself once `until` has passed unrenewed. It cannot tell its own closure
378
+ from one the owner ALSO made by hand meanwhile, so a switch adapter offers
379
+ the capability only when the host opts in (`pauseByStoreSwitch: true`).
380
+
381
+ ### What each marketplace offers, from public documentation only
382
+
383
+ CONFIRMED = read in the cited public document. ESTIMATED = not shown there;
384
+ assumed in code, confined to the adapter's `pause.ts`, to be checked in the
385
+ marketplace's sandbox.
386
+
387
+ | marketplace | fact | status | source |
388
+ |---|---|---|---|
389
+ | iFood | Interruptions: `GET`/`POST /merchant/v1.0/merchants/{merchantId}/interruptions`, `DELETE …/interruptions/{interruptionId}` on `https://merchant-api.ifood.com.br`; a temporary closure that does not change the opening hours | ESTIMATED (two independent public clients agree; iFood's portal, developer.ifood.com.br, answers our reader 403) | npm `@theyahia/ifood-mcp` (`dist/tools/*-interruption.js`), npm `n8n-nodes-ifood-completo`, npm `n8n-nodes-ifood` |
390
+ | iFood | Create body `{ description, start, end }`, 201 with the interruption; delete answers 204 | ESTIMATED (same clients) | as above |
391
+ | iFood | The client may send its own `id` in the create body (sent, as the idempotency key) | ESTIMATED, and not relied on: every create is preceded by a list, and an interruption is ours when it carries our id OR, where iFood assigned its own, exactly the end and the description the create sent (the end compared as the string sent, as an instant, or as the store's wall clock without offset). A retry after a lost answer reuses it, and a resume by key deletes it; a hand-made interruption matches neither. The key and the end it carried are written BEFORE the call, so a lost answer is never forgotten | none public |
392
+ | iFood | Times are read as the store's local clock, the payload's offset discarded | ESTIMATED (one client says so); the adapter sends the store's wall clock WITH its offset, which reads the same either way | `@theyahia/ifood-mcp` |
393
+ | iFood | No call moves an interruption's end | ESTIMATED; on a renewal (a later end OR an earlier one) the engine creates the new interruption first, then deletes the old, so the store is never open between them | none found |
394
+ | iFood | iFood ACCEPTS two overlapping interruptions for the moment of a renewal | ESTIMATED. If it refuses the overlap, the renewal is FAILED (`PAUSE_REFUSED`, iFood's words) and the old interruption still holds to its own end | none found |
395
+ | iFood | Auth: the merchant app's client-credentials token (`POST /authentication/v1.0/oauth/token`), as every other call of the adapter | ESTIMATED (as the rest of the iFood adapter, "iFood is unverified" above); no public scope list for the merchant module was readable | the adapter's existing outbound |
396
+ | iFood | Limits (rate, interruptions per merchant, maximum length, description length) | ESTIMATED: none published that we could read; a refusal is FAILED with iFood's own words | none |
397
+ | Rappi | `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`, synchronous, `{ stores: [{ store_id, is_enabled }] }`; 200 with `results[]` (`store_id`, `is_enabled`, `operation_result`, `operation_result_type`, `operation_result_message`, `suspended_reason`, `suspended_at`, `suspended_time`), 400, 403, 422 (over 300 stores), 502 | CONFIRMED | [dev-portal.rappi.com/en/api-reference/availability](https://dev-portal.rappi.com/en/api-reference/availability/) |
398
+ | Rappi | No end time or duration on the request: a switch; a store turned off stays off until turned on | CONFIRMED (no such parameter; the portal's FAQ: it stays off until enabled again) | same page; [dev-portal.rappi.com/en/frequently-asked-questions](https://dev-portal.rappi.com/en/frequently-asked-questions/) |
399
+ | Rappi | `store_id` is the connection's merchant id (Rappi's store id) | ESTIMATED (the page says "the one from your system" for this call and "the one in the rappi system" for the massive one) | same page |
400
+ | Rappi | A per-store failure reads as `operation_result: false` or an error-named `operation_result_type` | ESTIMATED (types not shown) | same page |
401
+ | 99Food | Open Delivery v1.7.1: the software PUSHES `POST /v1/merchantUpdate` with only `merchantStatus` (`AVAILABLE`/`UNAVAILABLE`) to open or close the merchant, OAuth2 `od.all`; 204 (200 for compatibility), 400, 401, 403, 404, 503 | CONFIRMED for the standard | [openapi.yaml v1.7.1](https://abrasel-nacional.github.io/opendelivery/openapi.yaml), "New Merchant Update Notification" |
402
+ | 99Food | `merchantStatus` has no end ("you don't know when the service will be re-established"): a switch | CONFIRMED for the standard | same |
403
+ | 99Food | The path is `/v1/merchantUpdate` (the spec files the webhook under the key `/v1/menuUpdated`, while its description and route table say `POST /v1/merchantUpdate`) | ESTIMATED | same |
404
+ | 99Food | 99Food implements `merchantUpdate`, and the token names the merchant (the body names none) | ESTIMATED | none public for 99Food |
405
+ | 99Food | The marketplace PULLING the status (`GET /v1/merchant/{id}/status`, host: the software) | Not used: the engine pushes, and serving the status is a host route this package does not ship | same spec |
406
+
407
+ ### Failure codes
408
+
409
+ No sentence a host shows is the engine's. A FAILED record carries a
410
+ `failureCode` (`UNSUPPORTED`, `NOT_CONNECTED`, `PAUSE_REFUSED`,
411
+ `PAUSE_UNANSWERED`, `RESUME_REFUSED`, `RESUME_UNANSWERED`) for the host's copy,
412
+ and the marketplace's own words, verbatim and cut to 300 characters, in
413
+ `failureDetail` — only for a refusal; an unanswered call, a missing connection
414
+ or an engine error leaves it null and goes to the logger.
415
+
416
+ ### Tests
417
+
418
+ - `src/__tests__/store-pause.test.ts`: the engine through fake marketplaces
419
+ (an interruption and a switch): fan-out, idempotency and renewal, the state
420
+ machine, deleting only what it created, the races (resume before and during
421
+ a pause, pause during a resume, a lost answer, two runs at once), the sweep.
422
+ - `src/ifood/__tests__/pause.test.ts`: the request shapes each adapter sends.
423
+ - `src/__tests__/store-pause-migration.test.ts`: the migration on PGlite,
424
+ index names against Prisma's, and a pause and resume on real Postgres.
@@ -1,4 +1,4 @@
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';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, P as PullCatalogue, C as CatalogueMenuEntry, b as CatalogueMenuOptions, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CCWMqt2g.js';
2
2
 
3
3
  /**
4
4
  * The words the 99Food adapter needs from its host, and nothing else.
@@ -139,6 +139,30 @@ declare function openDeliveryMenuDocument(input: {
139
139
  /** 99Food's catalogue capability, for the base URLs it was given. */
140
140
  declare function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue;
141
141
 
142
+ /**
143
+ * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
144
+ * software PUSHES the merchant's status to the Ordering Application.
145
+ *
146
+ * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)
147
+ * "sent with only the `merchantStatus` field ... will force the opening or
148
+ * closing of the merchant within the Ordering Application"; `merchantStatus`
149
+ * is `AVAILABLE | UNAVAILABLE`, "only use this type when you must close
150
+ * (disable) the merchant due to an unexpected event and you don't know when
151
+ * the service will be re-established"; 204 (200 "for compatibility"), 400,
152
+ * 401, 403, 404, 503 (openapi.yaml v1.7.1, README "Pausing a store").
153
+ *
154
+ * A SWITCH, with no id and no end, so offered only when the host opts in
155
+ * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path
156
+ * (the spec files this webhook under the key `/v1/menuUpdated` while its own
157
+ * description and route table say `POST /v1/merchantUpdate`; the latter is
158
+ * sent), that 99Food implements it at all, and that the token names the
159
+ * merchant (Open Delivery authenticates per merchant, so the body names none).
160
+ */
161
+ /** Set the merchant's status. */
162
+ declare function openDeliverySetMerchantStatus(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls, status: "AVAILABLE" | "UNAVAILABLE"): Promise<OutboundResult>;
163
+ /** 99Food's availability capability: Open Delivery's merchant status, a switch. */
164
+ declare function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability;
165
+
142
166
  /** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
143
167
  declare const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS: number;
144
168
  interface NinetyNineFoodAdapterConfig {
@@ -155,8 +179,15 @@ interface NinetyNineFoodAdapterConfig {
155
179
  * per-order deep link, so the link is the portal. Required; https only.
156
180
  */
157
181
  portalUrl: string;
182
+ /**
183
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open
184
+ * Delivery's `merchantStatus`, a store-wide switch with no id: a store the
185
+ * owner also closed by hand on 99Food during the kitchen's pause is opened
186
+ * with it. A host turns this on knowing that.
187
+ */
188
+ pauseByStoreSwitch?: boolean;
158
189
  }
159
190
  /** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
160
191
  declare function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter;
161
192
 
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 };
193
+ 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, openDeliveryAvailability, openDeliveryCatalogue, openDeliveryMenuDocument, openDeliverySetMerchantStatus, verifyOpenDeliverySignature };
@@ -13,7 +13,7 @@ import {
13
13
  import {
14
14
  answered,
15
15
  outboundResultOf
16
- } from "../chunk-RVBTARIY.js";
16
+ } from "../chunk-RGMSD7S7.js";
17
17
  import {
18
18
  __name
19
19
  } from "../chunk-7QVYU63E.js";
@@ -376,6 +376,35 @@ function openDeliveryCatalogue(bases) {
376
376
  }
377
377
  __name(openDeliveryCatalogue, "openDeliveryCatalogue");
378
378
 
379
+ // src/99food/pause.ts
380
+ function openDeliverySetMerchantStatus(ctx, bases, status) {
381
+ return answered(async () => {
382
+ const auth = await bearer(ctx, bases);
383
+ if (!("token" in auth)) return auth;
384
+ const response = await ctx.http({
385
+ method: "POST",
386
+ url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
387
+ headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
388
+ body: JSON.stringify({ merchantStatus: status })
389
+ });
390
+ if (response.status !== 401) return outboundResultOf(response);
391
+ ctx.tokens.delete(tokenKey(ctx));
392
+ return { kind: "retry", reason: "99Food refused the token" };
393
+ });
394
+ }
395
+ __name(openDeliverySetMerchantStatus, "openDeliverySetMerchantStatus");
396
+ function openDeliveryAvailability(bases) {
397
+ return {
398
+ kind: "switch",
399
+ pause: /* @__PURE__ */ __name(async (ctx, request) => {
400
+ const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
401
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
402
+ }, "pause"),
403
+ resume: /* @__PURE__ */ __name((ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"), "resume")
404
+ };
405
+ }
406
+ __name(openDeliveryAvailability, "openDeliveryAvailability");
407
+
379
408
  // src/99food/index.ts
380
409
  var NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 6e4;
381
410
  var ITEM_UNAVAILABLE = "UNAVAILABLE_ITEM";
@@ -426,7 +455,8 @@ function createNinetyNineFoodAdapter(config) {
426
455
  fetchOrder: /* @__PURE__ */ __name((ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions), "fetchOrder"),
427
456
  confirm: /* @__PURE__ */ __name((ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input), "confirm"),
428
457
  requestCancellation: /* @__PURE__ */ __name((ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input), "requestCancellation"),
429
- appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink")
458
+ appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink"),
459
+ ...config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}
430
460
  };
431
461
  }
432
462
  __name(createNinetyNineFoodAdapter, "createNinetyNineFoodAdapter");
@@ -437,8 +467,10 @@ export {
437
467
  createNinetyNineFoodAdapter,
438
468
  normalizeOpenDeliveryEvent,
439
469
  normalizeOpenDeliveryOrder,
470
+ openDeliveryAvailability,
440
471
  openDeliveryCatalogue,
441
472
  openDeliveryMenuDocument,
473
+ openDeliverySetMerchantStatus,
442
474
  verifyOpenDeliverySignature
443
475
  };
444
476
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/99food/copy.ts","../../src/99food/normalize.ts","../../src/99food/outbound.ts","../../src/99food/catalogue.ts","../../src/99food/index.ts"],"sourcesContent":["/**\n * The words the 99Food adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * The cancellation codes a merchant may send, verbatim from Open Delivery\n * v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two\n * codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,\n * `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.\n */\nexport const NINETY_NINE_FOOD_REASON_CODES = [\n \"SYSTEMIC_ISSUES\",\n \"DUPLICATE_APPLICATION\",\n \"UNAVAILABLE_ITEM\",\n \"RESTAURANT_WITHOUT_DELIVERY_PERSON\",\n \"OUTDATED_MENU\",\n \"ORDER_OUTSIDE_THE_DELIVERY_AREA\",\n \"BLOCKED_CUSTOMER\",\n \"OUTSIDE_DELIVERY_HOURS\",\n \"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT\",\n \"RISK_AREA\",\n \"DELIVERY_PROBLEM\",\n] as const;\n\nexport type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];\n\nexport interface NinetyNineFoodAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).\n *\n * Open Delivery splits what iFood sends at once: the webhook's `Event` names\n * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and\n * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So\n * there are two readers here: {@link normalizeOpenDeliveryEvent} for the\n * webhook (a `CREATED` becomes `orderToFetch`), and\n * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.\n *\n * Every shape below is the spec's (`components/schemas/Event`, `Order`,\n * `Price`, `Address`), and every fixture in the tests is the spec's own\n * example. Read defensively all the same: a missing field produces null, and\n * only a missing order id refuses an event (it is the idempotency key).\n */\n\n/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const NINETY_NINE_FOOD_PROVIDER = \"NINETY_NINE_FOOD\";\n\n/** The order exists and its body must be fetched. */\nconst CREATED = \"CREATED\";\n/** The order is cancelled: the store's request was granted, or a mandatory cancellation. */\nconst CANCELLED = \"CANCELLED\";\n/** The marketplace refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_DENIED = \"CANCELLATION_REQUEST_DENIED\";\n\n/**\n * Verify a delivery: Open Delivery's `X-App-Signature` is \"a lowercased\n * hexadecimal HMAC signature of the webhook HTTP request body, using the\n * client secret as a key and SHA256 as the hash function\". The key is the\n * merchant app's CLIENT SECRET, so a store's connection keeps that same value\n * as its webhook secret.\n *\n * Unlike iFood (whose secret is issued after certification), the key exists\n * from the moment the store connects, so an unset secret REFUSES: an unsigned\n * CANCELLED for a known order id would otherwise cancel it.\n */\nexport function verifyOpenDeliverySignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return false;\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/**\n * Normalize one webhook `Event`. Null only when it names no order.\n *\n * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.\n * - `CANCELLED` is a cancellation, whether the store asked for it or not.\n * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the\n * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and\n * recorded, and acts on nothing: an IGNORED inbox row.\n *\n * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the\n * engine attributes a delivery by its URL's store slug, so it reads none.\n */\nexport function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"]]);\n if (!externalOrderId) return null;\n const eventType = (firstString(payload, [[\"eventType\"]]) ?? \"UNKNOWN\").toUpperCase();\n const cancelled = eventType === CANCELLED;\n const denied = eventType === CANCELLATION_REQUEST_DENIED;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n // The spec's own event id. The fallback is deterministic so a redelivery\n // still collides on the inbox's unique index.\n eventId: firstString(payload, [[\"eventId\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: null,\n externalOrderId,\n order: null,\n orderToFetch: eventType === CREATED,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : denied ? \"FAILED\" : null,\n };\n}\n\n/** A `Price` object (`{ value, currency }`) in cents. */\nfunction priceCents(source: unknown, ...path: string[]): number | null {\n return toCents(pick(source, ...path, \"value\"));\n}\n\n/**\n * The note a kitchen reads: the chosen options (a pizza's halves are options)\n * and the buyer's own instructions. The normalized line has no options of its\n * own, and a flavour dropped from the ticket is food made wrong.\n */\nfunction lineNote(item: unknown, fraction: string | null): string | null {\n const rawOptions = pick(item, \"options\");\n const options = (Array.isArray(rawOptions) ? rawOptions : [])\n .map((option) => {\n const name = asString(pick(option, \"name\"));\n const quantity = Number(pick(option, \"quantity\") ?? 1);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n const parts = [fraction, options.join(\", \") || null, firstString(item, [[\"specialInstructions\"]])];\n const note = parts.filter((part): part is string => part !== null).join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * What the buyer paid for the whole line, in cents. The spec's `totalPrice`\n * (\"quantity * (unitPrice + optionsPrice)\") is the figure the order's\n * `itemsPrice` is built from, and it wins whenever it is stated — its own\n * example does not add up otherwise (unit 43, options 50, total 50).\n *\n * Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls\n * `optionsPrice` \"the sum of the total prices of all options of the item\", a\n * LINE figure, so it is added once, never multiplied by the quantity or by a\n * weight.\n */\nfunction lineTotalCents(item: unknown, quantity: number): number {\n const total = priceCents(item, \"totalPrice\");\n if (total !== null) return total;\n const unit = priceCents(item, \"unitPrice\") ?? 0;\n return Math.round(unit * quantity) + (priceCents(item, \"optionsPrice\") ?? 0);\n}\n\n/** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */\nfunction quantityOf(item: unknown): number {\n const stated = Number(pick(item, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\n/**\n * Split a line total over a whole quantity so the lines add up to it EXACTLY:\n * one row at `total / quantity` when it divides; otherwise `quantity - 1`\n * units at the floor and one unit carrying the remainder, under the same SKU\n * (R$ 10.00 over 3 is 3.33 × 2 + 3.34).\n */\nfunction splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {\n const floor = Math.floor(total / quantity);\n const remainder = total - floor * quantity;\n if (remainder === 0) return [{ quantity, unitPriceCents: floor }];\n const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];\n return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];\n}\n\n/**\n * One `Order.items[]` entry → its lines, which always add up to the line's\n * total ({@link lineTotalCents}). A whole quantity is split by\n * {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its\n * total, the weight in the note.\n *\n * A line with no `externalCode` keys on the item id, then the name: an\n * unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the\n * item id is stable across orders is not pinned by the spec; if it is per\n * order, each such order adds an unmapped SKU row.\n */\nfunction readLines(item: unknown): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = quantityOf(item);\n const whole = Number.isInteger(quantity);\n const fraction = whole ? null : `${quantity} ${firstString(item, [[\"unit\"]]) ?? \"\"}`.trim();\n const total = lineTotalCents(item, quantity);\n const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];\n const note = lineNote(item, fraction);\n return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));\n}\n\n/** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"type\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n return stated === \"MERCHANT\" || stated === \"MARKETPLACE\" ? stated : null;\n}\n\n/**\n * `delivery.deliveryAddress`. The spec's schema says `street`, `number`,\n * `district`; its own (commented) order example says `streetName`,\n * `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by\n * recommendation (`BR-SP`), so the country prefix is dropped.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"street\"], [\"streetName\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"number\"], [\"streetNumber\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"district\"], [\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]])?.replace(/^[A-Z]{2}-/u, \"\") ?? null,\n };\n}\n\n/**\n * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when\n * it carries no id or no line.\n *\n * The total is `total.orderAmount`, \"the final value of the order (itemsPrice\n * + otherFees - discounts)\": the buyer's receipt, gross. Open Delivery's\n * `Order` states NO commission field, so `commissionCents` is null (\"did not\n * say\"), never 0; the marketplace's cut arrives with its statement.\n */\nexport function normalizeOpenDeliveryOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n const externalOrderId = firstString(order, [[\"id\"]]);\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .flatMap(readLines);\n if (!externalOrderId || lines.length === 0) return null;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]),\n externalMerchantId: firstString(order, [[\"merchant\", \"id\"]]),\n buyer: {\n externalId: firstString(order, [[\"customer\", \"id\"]]),\n name: firstString(order, [[\"customer\", \"name\"]]),\n phone: firstString(order, [[\"customer\", \"phone\", \"number\"]]),\n },\n lines,\n // The line sum is the FALLBACK: the stated total carries the fees and\n // discounts the lines do not, and it is the number on the receipt.\n totalCents:\n firstCents(order, [[\"total\", \"orderAmount\", \"value\"]]) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n deliveryDueAt: firstDate(order, [\n [\"delivery\", \"estimatedDeliveryDateTime\"],\n [\"takeout\", \"takeoutDateTime\"],\n [\"schedule\", \"scheduledDateTimeEnd\"],\n ]),\n placedAt: firstDate(order, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from \"./normalize\";\n\n/**\n * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth\n * grant, the order fetch, confirm and requestCancellation. Paths, verbs,\n * bodies and answers are the spec's; the job that calls these, its retries\n * and what a failure shows are the engine's.\n *\n * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the\n * paths under each Ordering Application's own base URL, and 99Food gives its\n * base URLs to a partner at onboarding. So the base URL per environment is\n * the adapter's REQUIRED config, never a guessed default. Tests never reach\n * 99Food: the HTTP client is the host's port, answered by a fake.\n */\n\n/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */\nexport type NinetyNineFoodApiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/** `expires_in` is optional in the spec's `TokenResponse`; an hour when absent. ESTIMATED. */\nconst DEFAULT_TOKEN_SECONDS = 3600;\n\n/** The base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nexport function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {\n const base = bases[ctx.environment];\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\nexport const tokenKey = (ctx: AdapterCallContext): string =>\n `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token from the per-process cache, or a fresh `client_credentials`\n * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,\n * `grant_type`). Keyed by environment and client id; memory only.\n */\nexport async function bearer(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/oauth/token`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"client_credentials\",\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"99Food answered the token grant without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated call to an order's resource, the raw answer or the result that ends it. */\nasync function callOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n request: { method: \"GET\" | \"POST\"; externalOrderId: string; action: string | null; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const suffix = request.action === null ? \"\" : `/${request.action}`;\n const response = await ctx.http({\n method: request.method,\n url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */\nfunction alreadyCancelled(response: MarketplaceHttpResponse): boolean {\n if (response.status !== 422) return false;\n try {\n return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === \"CANCELLED\";\n } catch {\n return false;\n }\n}\n\n/** {@link answered} for a fetch: a call that never got an answer is a retry. */\nasync function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */\nexport function openDeliveryFetchOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: { externalOrderId: string },\n options: { missingStreetNumber: string },\n): Promise<FetchOrderResult> {\n return fetched(async () => {\n const response = await callOrder(ctx, bases, { method: \"GET\", externalOrderId: order.externalOrderId, action: null });\n if (\"kind\" in response) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown;\n try {\n body = JSON.parse(response.body);\n } catch {\n return { kind: \"refused\", status: response.status, message: \"the order is not JSON\" };\n }\n const normalized = normalizeOpenDeliveryOrder(body, options);\n return normalized\n ? { kind: \"order\", order: normalized }\n : { kind: \"refused\", status: response.status, message: \"the order carries no id or no line\" };\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:\n * `orderExternalCode` (the host's own order id) and `createdAt`, plus the\n * `preparationTime` in minutes when the store stated one. The spec describes\n * `createdAt` with the ORDER's creation text (a copy of another schema's), so\n * it is sent as the moment of the confirmation: ESTIMATED.\n *\n * Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`\n * (\"unable to process the contained instructions. (Check if the instruction\n * has not been sent before.)\"), and its body cannot tell a duplicate from a\n * cancelled order. So a retried confirm whose first answer was lost reads\n * \"não confirmou\" with the app link — a false alarm a person dismisses on\n * 99Food — and a confirm 99Food truly refused is never stamped confirmed.\n */\nexport function openDeliveryConfirm(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"confirm\",\n body: {\n orderExternalCode: order.hostOrderCode,\n createdAt: ctx.now.toISOString(),\n ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),\n },\n });\n if (\"kind\" in response) return response;\n return outboundResultOf(response);\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/requestCancellation` with the spec's\n * `RequestCancelled`: `reason` (free text: the store's, else the label),\n * `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means\n * taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`\n * event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is\n * cancelled already, which is what the request wanted.\n *\n * `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,\n * and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU\n * map is keyed on. The field is optional.\n */\nexport function openDeliveryRequestCancellation(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"requestCancellation\",\n body: { reason: input.text === \"\" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },\n });\n if (\"kind\" in response) return response;\n return alreadyCancelled(response) ? { kind: \"accepted\" } : outboundResultOf(response);\n });\n}\n","import { answered, outboundResultOf, type OutboundResult } from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type { CatalogueCallContext, CatalogueMenuEntry, CatalogueMenuOptions, PullCatalogue } from \"../core/catalogue-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).\n *\n * In Open Delivery the store's software does not write the menu to the\n * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a\n * `Merchant` document carrying `menus`, `categories`, `items` and\n * `itemOffers` (the price lives on the offer), and the ORDERING APPLICATION\n * (99Food) pulls it, again when its `TTL` runs out or when told the merchant\n * changed (`POST /v1/merchantUpdate`, sent with an empty body: \"pull\n * everything again\"). Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml\n *\n * So the adapter does two things: build the menu part of that document from\n * the items the store switched on (`menuDocument`, pure; the host merges it\n * into the rest of the `Merchant`, which is its own: `basicInfo`, `services`,\n * `lastUpdate`, `TTL`, `status`), and tell 99Food the menu changed\n * (`notifyMenuChanged`).\n *\n * ESTIMATED, to be checked once 99Food grants partner access:\n * - the path: the spec's route table and prose name `POST /merchantUpdate`\n * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this\n * sends the prose's;\n * - the `X-App-MerchantId` header on it: the operation lists none, and one\n * client app may serve many merchants, so it is sent to name which;\n * - that 99Food reads the whole `Merchant` on that notification (scenario 1\n * of the operation) rather than needing `entityType`/`updatedObjects`.\n *\n * Every id in the document is a UUID the software generates (the spec's\n * `format: uuid`), derived from the publication's stable reference, so the\n * same product keeps the same ids across pulls.\n */\n\n/** One category per host category name, in first-seen order. */\nfunction categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {\n const byName = new Map<string, { id: string; name: string; offers: string[] }>();\n for (const entry of entries) {\n const name = entry.categoryName.trim();\n const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };\n category.offers.push(stableUuid(`${entry.ref}:offer`));\n byName.set(name, category);\n }\n return [...byName.values()];\n}\n\n/** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */\nexport function openDeliveryMenuDocument(input: {\n externalMerchantId: string;\n entries: readonly CatalogueMenuEntry[];\n options: CatalogueMenuOptions;\n}) {\n const { externalMerchantId: merchantId, entries, options } = input;\n const categories = categoriesOf(merchantId, entries);\n return {\n menus: [\n {\n id: stableUuid(`${merchantId}:menu`),\n name: options.menuName,\n externalCode: \"menu\",\n categoryId: categories.map((category) => category.id),\n },\n ],\n categories: categories.map((category, index) => ({\n id: category.id,\n index,\n name: category.name,\n externalCode: category.name,\n status: \"AVAILABLE\",\n itemOfferId: category.offers,\n })),\n items: entries.map((entry) => ({\n id: stableUuid(`${entry.ref}:item`),\n name: entry.name,\n description: entry.description ?? \"\",\n externalCode: entry.productId,\n status: \"AVAILABLE\",\n unit: \"UN\",\n ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),\n })),\n itemOffers: entries.map((entry, index) => {\n const value = Math.round(entry.priceCents) / 100;\n return {\n id: stableUuid(`${entry.ref}:offer`),\n itemId: stableUuid(`${entry.ref}:item`),\n index,\n status: \"AVAILABLE\",\n price: { value, originalValue: value, currency: options.currency },\n };\n }),\n };\n}\n\n/** `POST /v1/merchantUpdate` with no body: 99Food pulls the whole `Merchant` again. 200 or 204. */\nasync function notify(ctx: CatalogueCallContext, bases: NinetyNineFoodApiBaseUrls): Promise<OutboundResult> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"X-App-MerchantId\": ctx.externalMerchantId },\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** 99Food's catalogue capability, for the base URLs it was given. */\nexport function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),\n };\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nimport { openDeliveryCatalogue } from \"./catalogue\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from \"./normalize\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n type NinetyNineFoodApiBaseUrls,\n} from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.\n *\n * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks\n * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,\n * confirm, requestCancellation with the spec's codes. Everything 99Food is\n * under this folder; the engine reaches it only through the\n * {@link MarketplaceAdapter} port, and registering it is the whole cost:\n *\n * ```ts\n * import { createNinetyNineFoodAdapter } from \"@12-apps/marketplace/99food\";\n * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/99food/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),\n * ],\n * });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.\n */\n\nexport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */\nexport const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = \"UNAVAILABLE_ITEM\";\n\nexport interface NinetyNineFoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: NinetyNineFoodAdapterCopy;\n /**\n * Where 99Food serves Open Delivery, per environment: the base the spec's\n * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at\n * onboarding and not public, so required and defaultless. https only.\n */\n apiBaseUrl: NinetyNineFoodApiBaseUrls;\n /**\n * Where \"open it on 99Food\" goes: the merchant portal. Open Delivery names no\n * per-order deep link, so the link is the portal. Required; https only.\n */\n portalUrl: string;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);\n}\n\n/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */\nexport function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {\n assertHttps(\"apiBaseUrl.SANDBOX\", config.apiBaseUrl.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", config.apiBaseUrl.PRODUCTION);\n assertHttps(\"portalUrl\", config.portalUrl);\n const bases = { ...config.apiBaseUrl };\n const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional in the spec (see `./outbound.ts`).\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // The spec lets a merchant request a cancellation before or after the\n // confirm (\"rules may vary depending on the timing\"); the answer says.\n cancelAfterAccept: true,\n // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: normalizeOpenDeliveryEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyOpenDeliverySignature,\n cancellationReasons: () => reasons,\n // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).\n catalogue: openDeliveryCatalogue(bases),\n fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),\n confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),\n requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),\n appLink: () => config.portalUrl,\n };\n}\n\nexport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nexport { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nexport type { NinetyNineFoodApiBaseUrls } from \"./outbound\";\nexport { openDeliveryCatalogue, openDeliveryMenuDocument } from \"./catalogue\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcO,IAAM,gCAAgC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACSO,IAAM,4BAA4B;AAGzC,IAAM,UAAU;AAEhB,IAAM,YAAY;AAElB,IAAM,8BAA8B;AAa7B,SAAS,4BACd,SACA,WACA,eACS;AACT,MAAI,CAAC,cAAe,QAAO;AAC3B,SAAO,oBAAoB,SAAS,WAAW,aAAa;AAC9D;AAPgB;AAsBT,SAAS,2BAA2B,SAA0C;AACnF,QAAM,kBAAkB,YAAY,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC;AAC1D,MAAI,CAAC,gBAAiB,QAAO;AAC7B,QAAM,aAAa,YAAY,SAAS,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,WAAW,YAAY;AACnF,QAAM,YAAY,cAAc;AAChC,QAAM,SAAS,cAAc;AAC7B,SAAO;AAAA,IACL,UAAU;AAAA;AAAA;AAAA,IAGV,SAAS,YAAY,SAAS,CAAC,CAAC,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AAU,gCAAgC,KAAK,OAAO,OAAO,KAAK,GAA/E;AAAA,IACrB,SAAS,6BAAM,OAAO,WAAb;AAAA,EACX;AACF;AAvCgB;","names":[]}
1
+ {"version":3,"sources":["../../src/99food/copy.ts","../../src/99food/normalize.ts","../../src/99food/outbound.ts","../../src/99food/catalogue.ts","../../src/99food/pause.ts","../../src/99food/index.ts"],"sourcesContent":["/**\n * The words the 99Food adapter needs from its host, and nothing else.\n *\n * Required and defaultless, like every copy port in this repo: the adapter\n * ships no language of its own. Two packs sit beside it (`./pt-BR`,\n * `./en-US`); a host passes one by hand, or its own.\n */\n\n/**\n * The cancellation codes a merchant may send, verbatim from Open Delivery\n * v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two\n * codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,\n * `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.\n */\nexport const NINETY_NINE_FOOD_REASON_CODES = [\n \"SYSTEMIC_ISSUES\",\n \"DUPLICATE_APPLICATION\",\n \"UNAVAILABLE_ITEM\",\n \"RESTAURANT_WITHOUT_DELIVERY_PERSON\",\n \"OUTDATED_MENU\",\n \"ORDER_OUTSIDE_THE_DELIVERY_AREA\",\n \"BLOCKED_CUSTOMER\",\n \"OUTSIDE_DELIVERY_HOURS\",\n \"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT\",\n \"RISK_AREA\",\n \"DELIVERY_PROBLEM\",\n] as const;\n\nexport type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];\n\nexport interface NinetyNineFoodAdapterCopy {\n /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */\n reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import {\n asString,\n firstCents,\n firstDate,\n firstString,\n pick,\n toCents,\n verifyHmacSha256Hex,\n} from \"../core/payload-read\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceOrderType,\n NormalizedAddress,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n NormalizedOrderLine,\n} from \"../core/types\";\n\n/**\n * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).\n *\n * Open Delivery splits what iFood sends at once: the webhook's `Event` names\n * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and\n * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So\n * there are two readers here: {@link normalizeOpenDeliveryEvent} for the\n * webhook (a `CREATED` becomes `orderToFetch`), and\n * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.\n *\n * Every shape below is the spec's (`components/schemas/Event`, `Order`,\n * `Price`, `Address`), and every fixture in the tests is the spec's own\n * example. Read defensively all the same: a missing field produces null, and\n * only a missing order id refuses an event (it is the idempotency key).\n */\n\n/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const NINETY_NINE_FOOD_PROVIDER = \"NINETY_NINE_FOOD\";\n\n/** The order exists and its body must be fetched. */\nconst CREATED = \"CREATED\";\n/** The order is cancelled: the store's request was granted, or a mandatory cancellation. */\nconst CANCELLED = \"CANCELLED\";\n/** The marketplace refused the store's own cancellation request. */\nconst CANCELLATION_REQUEST_DENIED = \"CANCELLATION_REQUEST_DENIED\";\n\n/**\n * Verify a delivery: Open Delivery's `X-App-Signature` is \"a lowercased\n * hexadecimal HMAC signature of the webhook HTTP request body, using the\n * client secret as a key and SHA256 as the hash function\". The key is the\n * merchant app's CLIENT SECRET, so a store's connection keeps that same value\n * as its webhook secret.\n *\n * Unlike iFood (whose secret is issued after certification), the key exists\n * from the moment the store connects, so an unset secret REFUSES: an unsigned\n * CANCELLED for a known order id would otherwise cancel it.\n */\nexport function verifyOpenDeliverySignature(\n rawBody: string,\n signature: string | null,\n webhookSecret: string | null,\n): boolean {\n if (!webhookSecret) return false;\n return verifyHmacSha256Hex(rawBody, signature, webhookSecret);\n}\n\n/**\n * Normalize one webhook `Event`. Null only when it names no order.\n *\n * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.\n * - `CANCELLED` is a cancellation, whether the store asked for it or not.\n * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the\n * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and\n * recorded, and acts on nothing: an IGNORED inbox row.\n *\n * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the\n * engine attributes a delivery by its URL's store slug, so it reads none.\n */\nexport function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {\n const externalOrderId = firstString(payload, [[\"orderId\"]]);\n if (!externalOrderId) return null;\n const eventType = (firstString(payload, [[\"eventType\"]]) ?? \"UNKNOWN\").toUpperCase();\n const cancelled = eventType === CANCELLED;\n const denied = eventType === CANCELLATION_REQUEST_DENIED;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n // The spec's own event id. The fallback is deterministic so a redelivery\n // still collides on the inbox's unique index.\n eventId: firstString(payload, [[\"eventId\"]]) ?? `${externalOrderId}:${eventType}`,\n eventType,\n externalMerchantId: null,\n externalOrderId,\n order: null,\n orderToFetch: eventType === CREATED,\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : denied ? \"FAILED\" : null,\n };\n}\n\n/** A `Price` object (`{ value, currency }`) in cents. */\nfunction priceCents(source: unknown, ...path: string[]): number | null {\n return toCents(pick(source, ...path, \"value\"));\n}\n\n/**\n * The note a kitchen reads: the chosen options (a pizza's halves are options)\n * and the buyer's own instructions. The normalized line has no options of its\n * own, and a flavour dropped from the ticket is food made wrong.\n */\nfunction lineNote(item: unknown, fraction: string | null): string | null {\n const rawOptions = pick(item, \"options\");\n const options = (Array.isArray(rawOptions) ? rawOptions : [])\n .map((option) => {\n const name = asString(pick(option, \"name\"));\n const quantity = Number(pick(option, \"quantity\") ?? 1);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n const parts = [fraction, options.join(\", \") || null, firstString(item, [[\"specialInstructions\"]])];\n const note = parts.filter((part): part is string => part !== null).join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * What the buyer paid for the whole line, in cents. The spec's `totalPrice`\n * (\"quantity * (unitPrice + optionsPrice)\") is the figure the order's\n * `itemsPrice` is built from, and it wins whenever it is stated — its own\n * example does not add up otherwise (unit 43, options 50, total 50).\n *\n * Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls\n * `optionsPrice` \"the sum of the total prices of all options of the item\", a\n * LINE figure, so it is added once, never multiplied by the quantity or by a\n * weight.\n */\nfunction lineTotalCents(item: unknown, quantity: number): number {\n const total = priceCents(item, \"totalPrice\");\n if (total !== null) return total;\n const unit = priceCents(item, \"unitPrice\") ?? 0;\n return Math.round(unit * quantity) + (priceCents(item, \"optionsPrice\") ?? 0);\n}\n\n/** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */\nfunction quantityOf(item: unknown): number {\n const stated = Number(pick(item, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\n/**\n * Split a line total over a whole quantity so the lines add up to it EXACTLY:\n * one row at `total / quantity` when it divides; otherwise `quantity - 1`\n * units at the floor and one unit carrying the remainder, under the same SKU\n * (R$ 10.00 over 3 is 3.33 × 2 + 3.34).\n */\nfunction splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {\n const floor = Math.floor(total / quantity);\n const remainder = total - floor * quantity;\n if (remainder === 0) return [{ quantity, unitPriceCents: floor }];\n const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];\n return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];\n}\n\n/**\n * One `Order.items[]` entry → its lines, which always add up to the line's\n * total ({@link lineTotalCents}). A whole quantity is split by\n * {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its\n * total, the weight in the note.\n *\n * A line with no `externalCode` keys on the item id, then the name: an\n * unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the\n * item id is stable across orders is not pinned by the spec; if it is per\n * order, each such order adds an unmapped SKU row.\n */\nfunction readLines(item: unknown): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"externalCode\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = quantityOf(item);\n const whole = Number.isInteger(quantity);\n const fraction = whole ? null : `${quantity} ${firstString(item, [[\"unit\"]]) ?? \"\"}`.trim();\n const total = lineTotalCents(item, quantity);\n const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];\n const note = lineNote(item, fraction);\n return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));\n}\n\n/** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */\nfunction readOrderType(order: unknown): MarketplaceOrderType | null {\n const stated = firstString(order, [[\"type\"]])?.toUpperCase();\n return stated === \"DELIVERY\" || stated === \"TAKEOUT\" ? stated : null;\n}\n\nfunction readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {\n const stated = firstString(order, [[\"delivery\", \"deliveredBy\"]])?.toUpperCase();\n return stated === \"MERCHANT\" || stated === \"MARKETPLACE\" ? stated : null;\n}\n\n/**\n * `delivery.deliveryAddress`. The spec's schema says `street`, `number`,\n * `district`; its own (commented) order example says `streetName`,\n * `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by\n * recommendation (`BR-SP`), so the country prefix is dropped.\n */\nfunction readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(order, \"delivery\", \"deliveryAddress\");\n const street = firstString(raw, [[\"street\"], [\"streetName\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"number\"], [\"streetNumber\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"district\"], [\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"reference\"]]),\n postalCode: firstString(raw, [[\"postalCode\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"state\"]])?.replace(/^[A-Z]{2}-/u, \"\") ?? null,\n };\n}\n\n/**\n * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when\n * it carries no id or no line.\n *\n * The total is `total.orderAmount`, \"the final value of the order (itemsPrice\n * + otherFees - discounts)\": the buyer's receipt, gross. Open Delivery's\n * `Order` states NO commission field, so `commissionCents` is null (\"did not\n * say\"), never 0; the marketplace's cut arrives with its statement.\n */\nexport function normalizeOpenDeliveryOrder(\n order: unknown,\n options: { missingStreetNumber: string },\n): NormalizedMarketplaceOrder | null {\n const externalOrderId = firstString(order, [[\"id\"]]);\n const rawItems = pick(order, \"items\");\n const lines = (Array.isArray(rawItems) ? rawItems : [])\n .flatMap(readLines);\n if (!externalOrderId || lines.length === 0) return null;\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n externalOrderId,\n externalDisplayId: firstString(order, [[\"displayId\"]]),\n externalMerchantId: firstString(order, [[\"merchant\", \"id\"]]),\n buyer: {\n externalId: firstString(order, [[\"customer\", \"id\"]]),\n name: firstString(order, [[\"customer\", \"name\"]]),\n phone: firstString(order, [[\"customer\", \"phone\", \"number\"]]),\n },\n lines,\n // The line sum is the FALLBACK: the stated total carries the fees and\n // discounts the lines do not, and it is the number on the receipt.\n totalCents:\n firstCents(order, [[\"total\", \"orderAmount\", \"value\"]]) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n deliveryDueAt: firstDate(order, [\n [\"delivery\", \"estimatedDeliveryDateTime\"],\n [\"takeout\", \"takeoutDateTime\"],\n [\"schedule\", \"scheduledDateTimeEnd\"],\n ]),\n placedAt: firstDate(order, [[\"createdAt\"]]) ?? new Date(),\n orderType: readOrderType(order),\n deliveredBy: readDeliveredBy(order),\n deliveryAddress: readAddress(order, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from \"./normalize\";\n\n/**\n * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth\n * grant, the order fetch, confirm and requestCancellation. Paths, verbs,\n * bodies and answers are the spec's; the job that calls these, its retries\n * and what a failure shows are the engine's.\n *\n * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the\n * paths under each Ordering Application's own base URL, and 99Food gives its\n * base URLs to a partner at onboarding. So the base URL per environment is\n * the adapter's REQUIRED config, never a guessed default. Tests never reach\n * 99Food: the HTTP client is the host's port, answered by a fake.\n */\n\n/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */\nexport type NinetyNineFoodApiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/** `expires_in` is optional in the spec's `TokenResponse`; an hour when absent. ESTIMATED. */\nconst DEFAULT_TOKEN_SECONDS = 3600;\n\n/** The base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nexport function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {\n const base = bases[ctx.environment];\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\nexport const tokenKey = (ctx: AdapterCallContext): string =>\n `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */\nfunction tokenOf(body: string): { token: string; expiresInSeconds: number } | null {\n try {\n const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };\n if (typeof parsed.access_token !== \"string\" || parsed.access_token === \"\") return null;\n const expires =\n typeof parsed.expires_in === \"number\" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;\n return { token: parsed.access_token, expiresInSeconds: expires };\n } catch {\n return null;\n }\n}\n\n/**\n * A bearer token from the per-process cache, or a fresh `client_credentials`\n * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,\n * `grant_type`). Keyed by environment and client id; memory only.\n */\nexport async function bearer(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n): Promise<{ token: string } | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const cached = ctx.tokens.get(tokenKey(ctx));\n if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/oauth/token`,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: ctx.credentials.clientId,\n client_secret: ctx.credentials.clientSecret,\n grant_type: \"client_credentials\",\n }).toString(),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"99Food answered the token grant without a token\" };\n ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });\n return { token: token.token };\n}\n\n/** One authenticated call to an order's resource, the raw answer or the result that ends it. */\nasync function callOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n request: { method: \"GET\" | \"POST\"; externalOrderId: string; action: string | null; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const suffix = request.action === null ? \"\" : `/${request.action}`;\n const response = await ctx.http({\n method: request.method,\n url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,\n headers: {\n Authorization: `Bearer ${auth.token}`,\n ...(request.body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),\n });\n // A 401 is a token that went stale under us: forget it, and the retry fetches another.\n if (response.status !== 401) return response;\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */\nfunction alreadyCancelled(response: MarketplaceHttpResponse): boolean {\n if (response.status !== 422) return false;\n try {\n return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === \"CANCELLED\";\n } catch {\n return false;\n }\n}\n\n/** {@link answered} for a fetch: a call that never got an answer is a retry. */\nasync function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n\n/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */\nexport function openDeliveryFetchOrder(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: { externalOrderId: string },\n options: { missingStreetNumber: string },\n): Promise<FetchOrderResult> {\n return fetched(async () => {\n const response = await callOrder(ctx, bases, { method: \"GET\", externalOrderId: order.externalOrderId, action: null });\n if (\"kind\" in response) return response;\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n let body: unknown;\n try {\n body = JSON.parse(response.body);\n } catch {\n return { kind: \"refused\", status: response.status, message: \"the order is not JSON\" };\n }\n const normalized = normalizeOpenDeliveryOrder(body, options);\n return normalized\n ? { kind: \"order\", order: normalized }\n : { kind: \"refused\", status: response.status, message: \"the order carries no id or no line\" };\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:\n * `orderExternalCode` (the host's own order id) and `createdAt`, plus the\n * `preparationTime` in minutes when the store stated one. The spec describes\n * `createdAt` with the ORDER's creation text (a copy of another schema's), so\n * it is sent as the moment of the confirmation: ESTIMATED.\n *\n * Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`\n * (\"unable to process the contained instructions. (Check if the instruction\n * has not been sent before.)\"), and its body cannot tell a duplicate from a\n * cancelled order. So a retried confirm whose first answer was lost reads\n * \"não confirmou\" with the app link — a false alarm a person dismisses on\n * 99Food — and a confirm 99Food truly refused is never stamped confirmed.\n */\nexport function openDeliveryConfirm(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"confirm\",\n body: {\n orderExternalCode: order.hostOrderCode,\n createdAt: ctx.now.toISOString(),\n ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),\n },\n });\n if (\"kind\" in response) return response;\n return outboundResultOf(response);\n });\n}\n\n/**\n * `POST /v1/orders/{orderId}/requestCancellation` with the spec's\n * `RequestCancelled`: `reason` (free text: the store's, else the label),\n * `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means\n * taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`\n * event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is\n * cancelled already, which is what the request wanted.\n *\n * `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,\n * and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU\n * map is keyed on. The field is optional.\n */\nexport function openDeliveryRequestCancellation(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: \"requestCancellation\",\n body: { reason: input.text === \"\" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },\n });\n if (\"kind\" in response) return response;\n return alreadyCancelled(response) ? { kind: \"accepted\" } : outboundResultOf(response);\n });\n}\n","import { answered, outboundResultOf, type OutboundResult } from \"../core/adapter\";\nimport { stableUuid } from \"../core/catalogue-ids\";\nimport type { CatalogueCallContext, CatalogueMenuEntry, CatalogueMenuOptions, PullCatalogue } from \"../core/catalogue-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).\n *\n * In Open Delivery the store's software does not write the menu to the\n * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a\n * `Merchant` document carrying `menus`, `categories`, `items` and\n * `itemOffers` (the price lives on the offer), and the ORDERING APPLICATION\n * (99Food) pulls it, again when its `TTL` runs out or when told the merchant\n * changed (`POST /v1/merchantUpdate`, sent with an empty body: \"pull\n * everything again\"). Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml\n *\n * So the adapter does two things: build the menu part of that document from\n * the items the store switched on (`menuDocument`, pure; the host merges it\n * into the rest of the `Merchant`, which is its own: `basicInfo`, `services`,\n * `lastUpdate`, `TTL`, `status`), and tell 99Food the menu changed\n * (`notifyMenuChanged`).\n *\n * ESTIMATED, to be checked once 99Food grants partner access:\n * - the path: the spec's route table and prose name `POST /merchantUpdate`\n * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this\n * sends the prose's;\n * - the `X-App-MerchantId` header on it: the operation lists none, and one\n * client app may serve many merchants, so it is sent to name which;\n * - that 99Food reads the whole `Merchant` on that notification (scenario 1\n * of the operation) rather than needing `entityType`/`updatedObjects`.\n *\n * Every id in the document is a UUID the software generates (the spec's\n * `format: uuid`), derived from the publication's stable reference, so the\n * same product keeps the same ids across pulls.\n */\n\n/** One category per host category name, in first-seen order. */\nfunction categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {\n const byName = new Map<string, { id: string; name: string; offers: string[] }>();\n for (const entry of entries) {\n const name = entry.categoryName.trim();\n const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };\n category.offers.push(stableUuid(`${entry.ref}:offer`));\n byName.set(name, category);\n }\n return [...byName.values()];\n}\n\n/** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */\nexport function openDeliveryMenuDocument(input: {\n externalMerchantId: string;\n entries: readonly CatalogueMenuEntry[];\n options: CatalogueMenuOptions;\n}) {\n const { externalMerchantId: merchantId, entries, options } = input;\n const categories = categoriesOf(merchantId, entries);\n return {\n menus: [\n {\n id: stableUuid(`${merchantId}:menu`),\n name: options.menuName,\n externalCode: \"menu\",\n categoryId: categories.map((category) => category.id),\n },\n ],\n categories: categories.map((category, index) => ({\n id: category.id,\n index,\n name: category.name,\n externalCode: category.name,\n status: \"AVAILABLE\",\n itemOfferId: category.offers,\n })),\n items: entries.map((entry) => ({\n id: stableUuid(`${entry.ref}:item`),\n name: entry.name,\n description: entry.description ?? \"\",\n externalCode: entry.productId,\n status: \"AVAILABLE\",\n unit: \"UN\",\n ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),\n })),\n itemOffers: entries.map((entry, index) => {\n const value = Math.round(entry.priceCents) / 100;\n return {\n id: stableUuid(`${entry.ref}:offer`),\n itemId: stableUuid(`${entry.ref}:item`),\n index,\n status: \"AVAILABLE\",\n price: { value, originalValue: value, currency: options.currency },\n };\n }),\n };\n}\n\n/** `POST /v1/merchantUpdate` with no body: 99Food pulls the whole `Merchant` again. 200 or 204. */\nasync function notify(ctx: CatalogueCallContext, bases: NinetyNineFoodApiBaseUrls): Promise<OutboundResult> {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"X-App-MerchantId\": ctx.externalMerchantId },\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n}\n\n/** 99Food's catalogue capability, for the base URLs it was given. */\nexport function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {\n return {\n mode: \"pull\",\n menuDocument: openDeliveryMenuDocument,\n notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),\n };\n}\n","import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from \"../core/adapter\";\nimport type { MarketplaceAvailability } from \"../core/pause-port\";\nimport { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from \"./outbound\";\n\n/**\n * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the\n * software PUSHES the merchant's status to the Ordering Application.\n *\n * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)\n * \"sent with only the `merchantStatus` field ... will force the opening or\n * closing of the merchant within the Ordering Application\"; `merchantStatus`\n * is `AVAILABLE | UNAVAILABLE`, \"only use this type when you must close\n * (disable) the merchant due to an unexpected event and you don't know when\n * the service will be re-established\"; 204 (200 \"for compatibility\"), 400,\n * 401, 403, 404, 503 (openapi.yaml v1.7.1, README \"Pausing a store\").\n *\n * A SWITCH, with no id and no end, so offered only when the host opts in\n * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path\n * (the spec files this webhook under the key `/v1/menuUpdated` while its own\n * description and route table say `POST /v1/merchantUpdate`; the latter is\n * sent), that 99Food implements it at all, and that the token names the\n * merchant (Open Delivery authenticates per merchant, so the body names none).\n */\n\n/** Set the merchant's status. */\nexport function openDeliverySetMerchantStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n status: \"AVAILABLE\" | \"UNAVAILABLE\",\n): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx, bases);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"POST\",\n url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,\n headers: { Authorization: `Bearer ${auth.token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ merchantStatus: status }),\n });\n if (response.status !== 401) return outboundResultOf(response);\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"99Food refused the token\" };\n });\n}\n\n/** 99Food's availability capability: Open Delivery's merchant status, a switch. */\nexport function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx, request) => {\n const result = await openDeliverySetMerchantStatus(ctx, bases, \"UNAVAILABLE\");\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, \"AVAILABLE\"),\n };\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nimport { openDeliveryCatalogue } from \"./catalogue\";\nimport { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from \"./normalize\";\nimport {\n openDeliveryConfirm,\n openDeliveryFetchOrder,\n openDeliveryRequestCancellation,\n type NinetyNineFoodApiBaseUrls,\n} from \"./outbound\";\nimport { openDeliveryAvailability } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.\n *\n * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks\n * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,\n * confirm, requestCancellation with the spec's codes. Everything 99Food is\n * under this folder; the engine reaches it only through the\n * {@link MarketplaceAdapter} port, and registering it is the whole cost:\n *\n * ```ts\n * import { createNinetyNineFoodAdapter } from \"@12-apps/marketplace/99food\";\n * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/99food/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),\n * ],\n * });\n * ```\n *\n * Its webhook is the engine's one route, `POST\n * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.\n */\n\nexport { NINETY_NINE_FOOD_PROVIDER } from \"./normalize\";\n\n/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */\nexport const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = \"UNAVAILABLE_ITEM\";\n\nexport interface NinetyNineFoodAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: NinetyNineFoodAdapterCopy;\n /**\n * Where 99Food serves Open Delivery, per environment: the base the spec's\n * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at\n * onboarding and not public, so required and defaultless. https only.\n */\n apiBaseUrl: NinetyNineFoodApiBaseUrls;\n /**\n * Where \"open it on 99Food\" goes: the merchant portal. Open Delivery names no\n * per-order deep link, so the link is the portal. Required; https only.\n */\n portalUrl: string;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open\n * Delivery's `merchantStatus`, a store-wide switch with no id: a store the\n * owner also closed by hand on 99Food during the kitchen's pause is opened\n * with it. A host turns this on knowing that.\n */\n pauseByStoreSwitch?: boolean;\n}\n\nfunction assertHttps(name: string, url: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);\n}\n\n/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */\nexport function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {\n assertHttps(\"apiBaseUrl.SANDBOX\", config.apiBaseUrl.SANDBOX);\n assertHttps(\"apiBaseUrl.PRODUCTION\", config.apiBaseUrl.PRODUCTION);\n assertHttps(\"portalUrl\", config.portalUrl);\n const bases = { ...config.apiBaseUrl };\n const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n // `outOfStockItems` is optional in the spec (see `./outbound.ts`).\n needsItems: false,\n }));\n const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: NINETY_NINE_FOOD_PROVIDER,\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // The spec lets a merchant request a cancellation before or after the\n // confirm (\"rules may vary depending on the timing\"); the answer says.\n cancelAfterAccept: true,\n // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.\n asyncCancellationOutcome: true,\n perOrderAppLink: false,\n // `OrderConfirmed.preparationTime`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: normalizeOpenDeliveryEvent,\n readSignature: (header) => header(\"x-app-signature\"),\n verifySignature: verifyOpenDeliverySignature,\n cancellationReasons: () => reasons,\n // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).\n catalogue: openDeliveryCatalogue(bases),\n fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),\n confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),\n requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),\n };\n}\n\nexport {\n NINETY_NINE_FOOD_REASON_CODES,\n type NinetyNineFoodAdapterCopy,\n type NinetyNineFoodReasonCode,\n} from \"./copy\";\nexport { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from \"./normalize\";\nexport type { NinetyNineFoodApiBaseUrls } from \"./outbound\";\nexport { openDeliveryCatalogue, openDeliveryMenuDocument } from \"./catalogue\";\nexport { openDeliveryAvailability, openDeliverySetMerchantStatus } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcO,IAAM,gCAAgC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACSO,IAAM,4BAA4B;AAGzC,IAAM,UAAU;AAEhB,IAAM,YAAY;AAElB,IAAM,8BAA8B;AAa7B,SAAS,4BACd,SACA,WACA,eACS;AACT,MAAI,CAAC,cAAe,QAAO;AAC3B,SAAO,oBAAoB,SAAS,WAAW,aAAa;AAC9D;AAPgB;AAsBT,SAAS,2BAA2B,SAA0C;AACnF,QAAM,kBAAkB,YAAY,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC;AAC1D,MAAI,CAAC,gBAAiB,QAAO;AAC7B,QAAM,aAAa,YAAY,SAAS,CAAC,CAAC,WAAW,CAAC,CAAC,KAAK,WAAW,YAAY;AACnF,QAAM,YAAY,cAAc;AAChC,QAAM,SAAS,cAAc;AAC7B,SAAO;AAAA,IACL,UAAU;AAAA;AAAA;AAAA,IAGV,SAAS,YAAY,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,GAAG,eAAe,IAAI,SAAS;AAAA,IAC/E;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA,OAAO;AAAA,IACP,cAAc,cAAc;AAAA,IAC5B;AAAA,IACA,qBAAqB,YAAY,cAAc,SAAS,WAAW;AAA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