@12-apps/marketplace 1.7.0 → 1.8.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.
- package/ADOPTING.md +17 -0
- package/README.md +56 -0
- package/dist/99food/index.d.ts +4 -2
- package/dist/99food/index.js +32 -3
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
- package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
- package/dist/chunk-6N2HEV3U.js.map +1 -0
- package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
- package/dist/chunk-BMCERPQX.js.map +1 -0
- package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
- package/dist/chunk-HEXLCTOG.js.map +1 -0
- package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
- package/dist/chunk-NP4EYKPO.js.map +1 -0
- package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +1 -1
- package/dist/ifood/index.js +29 -3
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +104 -7
- package/dist/index.js.map +1 -1
- package/dist/manifest/index.d.ts +3 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +7 -1
- package/dist/rappi/index.js +20 -3
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +6 -2
- package/dist/server/index.js +3 -3
- package/package.json +1 -1
- package/prisma/marketplace.prisma +45 -1
- package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
- package/src/99food/index.ts +6 -0
- package/src/99food/normalize.ts +7 -1
- package/src/99food/outbound.ts +55 -0
- package/src/core/adapter.ts +41 -1
- package/src/core/bulk.ts +1 -1
- package/src/core/engine.ts +9 -0
- package/src/core/ingest.ts +6 -0
- package/src/core/integration.ts +17 -0
- package/src/core/lifecycle-port.ts +16 -0
- package/src/core/lifecycle.ts +133 -0
- package/src/core/outbound-queue.ts +24 -4
- package/src/core/outbound-sweep.ts +49 -5
- package/src/core/outbound.ts +11 -0
- package/src/core/pipeline.ts +22 -2
- package/src/core/ports.ts +39 -3
- package/src/core/status-inform.ts +51 -0
- package/src/core/status-job.ts +207 -0
- package/src/core/status-store.ts +85 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/index.ts +7 -1
- package/src/ifood/normalize.ts +17 -0
- package/src/ifood/outbound.ts +35 -0
- package/src/index.ts +6 -0
- package/src/rappi/index.ts +6 -1
- package/src/rappi/normalize.ts +6 -0
- package/src/rappi/outbound.ts +31 -2
- package/src/server/mcp.ts +2 -0
- package/src/server/webhook.ts +3 -1
- package/dist/chunk-L3DCOZUU.js.map +0 -1
- package/dist/chunk-SJUKBCVO.js.map +0 -1
- package/dist/chunk-UYFYGGCS.js.map +0 -1
- package/dist/chunk-YVUZHXUF.js.map +0 -1
package/ADOPTING.md
CHANGED
|
@@ -75,6 +75,7 @@ export const engine = createMarketplaceEngine({
|
|
|
75
75
|
| `withdraw({ clientId, provider, productId })` | The switch turned OFF (and the undo of an ON). `queued` (WITHDRAWING), or `unchanged` when the product was never switched on, or is WITHDRAWN at once because its connection was archived or removed since. |
|
|
76
76
|
| `catalogueState({ clientId, productIds, providers? })` | The product page's read: one row per marketplace the product was ever switched on for, in one query. Draw PUBLISHED as "in the catalogue" (with your sentence for a `warningCode`, IMAGE_TOO_LARGE or IMAGE_REFUSED: it went out without its photo), PUBLISHING / WITHDRAWING as "sending…" (switch disabled), FAILED with your own sentence for its `failureCode` (REFUSED, UNAVAILABLE, TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL), the marketplace's own words from `failureReason` beside a REFUSED, and a retry (`publish` or `withdraw` again, per `failedAction`). The engine writes no sentence a person reads. No row is OFF. |
|
|
77
77
|
| `catalogueDocument({ clientId, provider, options: { menuName, currency } })` | PULL marketplaces only (99Food): the menu part of the document the marketplace reads. Serve it from the route the marketplace pulls (Open Delivery's `GET /v1/merchant`), merged into the rest of that document, which is the host's (`id`, `status`, `lastUpdate`, `TTL`, `basicInfo`, `services`). The menu's name and the currency are the host's words. |
|
|
78
|
+
| `informStatus({ clientId, orderId, step, at, delayMs? })` | An order reached `READY`, `DISPATCHED` or `HANDED_OVER` (FUT-4653). One enqueue, no statement, never throws: call it after the move's commit, from the one place every writer of that step passes, gated on the order being a marketplace's. `at` is the move's own timestamp (it makes the job's dedupe key, so a re-dispatch after an undo is a new job); `delayMs` is the board's undo window for a dispatch. Your `enqueue` port must pass `options.delayMs` on. The job decides everything else (see the README). |
|
|
78
79
|
| `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
|
|
79
80
|
|
|
80
81
|
A host never writes `provider === "IFOOD"`. A capability is asked of
|
|
@@ -222,6 +223,22 @@ connection's `archived_at`, keeps the host's foreign keys, and replaces the
|
|
|
222
223
|
closed provider lists (`*_provider_valid`) with a shape check, so a new
|
|
223
224
|
adapter is never a migration.
|
|
224
225
|
|
|
226
|
+
`20261126120000_marketplace_status_updates` (1.8, FUT-4653) adds
|
|
227
|
+
`marketplace_integrations.follow_status` (NOT NULL DEFAULT true: every existing
|
|
228
|
+
connection follows the marketplace's status once the hook is bound) and
|
|
229
|
+
`marketplace_status_updates`, one row per (order, step) with its step, source and
|
|
230
|
+
state CHECKed and a partial index the outbound sweep reads. Additive; `order_id`
|
|
231
|
+
is by value. Compose it with the schema in the same change as the engine bump: the
|
|
232
|
+
engine selects `follow_status`. To follow the marketplace's status a host binds
|
|
233
|
+
`order.onLifecycle`; to tell it, `order.statusHolds` and calls `informStatus`.
|
|
234
|
+
Both are optional: a host that binds neither behaves as before.
|
|
235
|
+
`MarketplaceDb.marketplaceStatusUpdate` is optional in the type, so a host that has
|
|
236
|
+
not composed the model still compiles, and the two paths then do nothing.
|
|
237
|
+
`DeliveryOutcome` gains `{ kind: "moved", orderId, lifecycle }`, and
|
|
238
|
+
`OutboundAction` gains `"status"` (the payload an optional `step`): a host that
|
|
239
|
+
switches over either exhaustively adds the case; allow `"status"` in any
|
|
240
|
+
action allow-list in front of the outbound job.
|
|
241
|
+
|
|
225
242
|
## 6. What stays the host's
|
|
226
243
|
|
|
227
244
|
The stock draw at the acceptance, the settlement effects, the board's and the
|
package/README.md
CHANGED
|
@@ -352,6 +352,62 @@ nothing, so the order stays ACCEPTED here while cancelled on Rappi. The take
|
|
|
352
352
|
the accept queued is then answered 400, so the order shows "não confirmou"
|
|
353
353
|
with the portal link and a person settles it there.
|
|
354
354
|
|
|
355
|
+
## Following and informing an order's status (FUT-4653)
|
|
356
|
+
|
|
357
|
+
Two directions, both forward-only and neither ever refused, reverted or waited on.
|
|
358
|
+
|
|
359
|
+
**Inbound.** An iFood `DSP`/`CON` and an Open Delivery `DISPATCHED`/`CONCLUDED`
|
|
360
|
+
normalize to `NormalizedEvent.lifecycle` (`"DISPATCHED"` or `"CONCLUDED"`).
|
|
361
|
+
iFood's codes are ESTIMATED (its portal refused our reader, 2026-11-25); Rappi
|
|
362
|
+
maps none (its `event` values are undocumented). With the connection's
|
|
363
|
+
`followStatus` ON (default; `marketplace_integrations.follow_status`) and a host
|
|
364
|
+
that binds `order.onLifecycle`, the engine asks the host to move the order
|
|
365
|
+
forward, after four rules of its own, each ending the delivery IGNORED with a
|
|
366
|
+
reason:
|
|
367
|
+
|
|
368
|
+
1. no acceptance yet: DEFERRED (PENDING, one attempt counted,
|
|
369
|
+
`lifecycle before its order`), so the reconcile pass applies it after the
|
|
370
|
+
order's own event ingests; retired after `maxInboxAttempts`;
|
|
371
|
+
2. the acceptance is not ACCEPTED (`the order is AWAITING, not ACCEPTED`);
|
|
372
|
+
3. a cancellation request is PENDING or REQUESTED;
|
|
373
|
+
4. the event echoes a step we informed (`echo of our DISPATCHED`; a CONCLUDED
|
|
374
|
+
after our HANDED_OVER): without this, a store that dispatched, told iFood and
|
|
375
|
+
dragged the bag back would have it dispatched again by iFood's own echo.
|
|
376
|
+
|
|
377
|
+
Whatever the host answers, the marketplace's word is NOTED (a
|
|
378
|
+
`marketplace_status_updates` row) so our own job never informs it back. The
|
|
379
|
+
host answers `"moved"`, `"unchanged"` or `{ kind: "unchanged", reason }` (its
|
|
380
|
+
reason becomes the inbox's; a bag whose store never named a courier is the
|
|
381
|
+
host's rule, not the engine's). The facts it gets are `{ deliveredBy }`
|
|
382
|
+
(`MERCHANT`, `MARKETPLACE`, null for a take-out). Switch OFF, no hook, or
|
|
383
|
+
settings built by hand without `followStatus`: byte-for-byte the old answer
|
|
384
|
+
(`no order body on <type>`).
|
|
385
|
+
|
|
386
|
+
**Outbound.** The host calls `engine.informStatus({ clientId, orderId, step,
|
|
387
|
+
at, delayMs? })` when an order reaches `READY`, `DISPATCHED` or `HANDED_OVER`:
|
|
388
|
+
one enqueue of `marketplace.outbound` (action `status`), no statement, never
|
|
389
|
+
throws. The job asks, in order, stopping at the first no, with no row and no
|
|
390
|
+
call: acceptance ACCEPTED and no cancellation request standing; the adapter
|
|
391
|
+
states the step (`capabilities.statusSteps`) and takes it for this order
|
|
392
|
+
(`statusSupported`); `order.statusHolds` says the order still holds it; no
|
|
393
|
+
status row exists for (order, step) and the marketplace has not CONCLUDED;
|
|
394
|
+
then it claims the row (STORE, SENDING, unique per (order, step)) and calls
|
|
395
|
+
`informStatus`. 2xx is SENT; a final 4xx FAILED (error log, never retried); a
|
|
396
|
+
5xx or timeout is retried (3 attempts, exponential from 30 s) and the last is
|
|
397
|
+
FAILED. A SENDING row left by a dead job is re-queued by the outbound sweep
|
|
398
|
+
after 10 minutes and failed after 24 hours.
|
|
399
|
+
|
|
400
|
+
| step | iFood (ESTIMATED) | 99Food (Open Delivery v1.7.1) | Rappi |
|
|
401
|
+
|---|---|---|---|
|
|
402
|
+
| READY | `POST /orders/{id}/readyToPickup`, not for a merchant bag | `POST /v1/orders/{id}/readyForPickup` | `POST /orders/{id}/ready-for-pickup` (ESTIMATED verb; MANUAL-notification stores only) |
|
|
403
|
+
| DISPATCHED | `POST /orders/{id}/dispatch`, merchant bag only | `POST /v1/orders/{id}/dispatch`, merchant bag only | none |
|
|
404
|
+
| HANDED_OVER | none | merchant bag `delivered`, take-out `pickedUp`, fleet none | none |
|
|
405
|
+
|
|
406
|
+
Sources: Open Delivery `openapi.yaml` (read 2026-11-25), Rappi's portal
|
|
407
|
+
"Managing User Orders" (read 2026-11-25); iFood's developer portal answered 403,
|
|
408
|
+
so every iFood row but confirm and requestCancellation is ESTIMATED, in
|
|
409
|
+
`src/ifood/outbound.ts` and `src/ifood/normalize.ts` only.
|
|
410
|
+
|
|
355
411
|
## Pausing a store (FUT-4851)
|
|
356
412
|
|
|
357
413
|
When the store's kitchen passes its cap, the host closes the store on every
|
package/dist/99food/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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-CYJzu1c9.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The words the 99Food adapter needs from its host, and nothing else.
|
|
@@ -72,7 +72,9 @@ declare function verifyOpenDeliverySignature(rawBody: string, signature: string
|
|
|
72
72
|
* - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
|
|
73
73
|
* - `CANCELLED` is a cancellation, whether the store asked for it or not.
|
|
74
74
|
* - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
|
|
75
|
-
* -
|
|
75
|
+
* - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine
|
|
76
|
+
* asks the host to move the order forward, when the store follows them.
|
|
77
|
+
* - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, the
|
|
76
78
|
* consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
|
|
77
79
|
* recorded, and acts on nothing: an IGNORED inbox row.
|
|
78
80
|
*
|
package/dist/99food/index.js
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
answered,
|
|
15
15
|
outboundResultOf,
|
|
16
16
|
tokenGrantResultOf
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-HEXLCTOG.js";
|
|
18
18
|
import {
|
|
19
19
|
__name
|
|
20
20
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -38,6 +38,7 @@ var NINETY_NINE_FOOD_REASON_CODES = [
|
|
|
38
38
|
var NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
|
|
39
39
|
var CREATED = "CREATED";
|
|
40
40
|
var CANCELLED = "CANCELLED";
|
|
41
|
+
var LIFECYCLE_OF = { DISPATCHED: "DISPATCHED", CONCLUDED: "CONCLUDED" };
|
|
41
42
|
var CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
|
|
42
43
|
function verifyOpenDeliverySignature(rawBody, signature, webhookSecret) {
|
|
43
44
|
if (!webhookSecret) return false;
|
|
@@ -61,7 +62,8 @@ function normalizeOpenDeliveryEvent(payload) {
|
|
|
61
62
|
order: null,
|
|
62
63
|
orderToFetch: eventType === CREATED,
|
|
63
64
|
cancelled,
|
|
64
|
-
cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null
|
|
65
|
+
cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
|
|
66
|
+
...LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}
|
|
65
67
|
};
|
|
66
68
|
}
|
|
67
69
|
__name(normalizeOpenDeliveryEvent, "normalizeOpenDeliveryEvent");
|
|
@@ -302,6 +304,29 @@ function openDeliveryRequestCancellation(ctx, bases, order, input) {
|
|
|
302
304
|
});
|
|
303
305
|
}
|
|
304
306
|
__name(openDeliveryRequestCancellation, "openDeliveryRequestCancellation");
|
|
307
|
+
var STATUS_PATH = {
|
|
308
|
+
READY: /* @__PURE__ */ __name(() => ({ action: "readyForPickup" }), "READY"),
|
|
309
|
+
DISPATCHED: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null, "DISPATCHED"),
|
|
310
|
+
HANDED_OVER: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? { action: "delivered", body: {} } : facts.deliveredBy === null ? { action: "pickedUp", body: {} } : null, "HANDED_OVER")
|
|
311
|
+
};
|
|
312
|
+
function openDeliveryStatusSupported(facts) {
|
|
313
|
+
return STATUS_PATH[facts.step]?.(facts) != null;
|
|
314
|
+
}
|
|
315
|
+
__name(openDeliveryStatusSupported, "openDeliveryStatusSupported");
|
|
316
|
+
function openDeliveryInformStatus(ctx, bases, order, facts) {
|
|
317
|
+
const path = STATUS_PATH[facts.step]?.(facts) ?? null;
|
|
318
|
+
if (path === null) return Promise.resolve({ kind: "unsupported" });
|
|
319
|
+
return answered(async () => {
|
|
320
|
+
const response = await callOrder(ctx, bases, {
|
|
321
|
+
method: "POST",
|
|
322
|
+
externalOrderId: order.externalOrderId,
|
|
323
|
+
action: path.action,
|
|
324
|
+
...path.body === void 0 ? {} : { body: path.body }
|
|
325
|
+
});
|
|
326
|
+
return "kind" in response ? response : outboundResultOf(response);
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
__name(openDeliveryInformStatus, "openDeliveryInformStatus");
|
|
305
330
|
|
|
306
331
|
// src/99food/catalogue.ts
|
|
307
332
|
function categoriesOf(merchantId, entries) {
|
|
@@ -447,7 +472,9 @@ function createNinetyNineFoodAdapter(config) {
|
|
|
447
472
|
perOrderAppLink: false,
|
|
448
473
|
// `OrderConfirmed.preparationTime`, in minutes.
|
|
449
474
|
confirmTakesPreparationTime: true,
|
|
450
|
-
cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS
|
|
475
|
+
cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
|
|
476
|
+
// Open Delivery's readyForPickup, dispatch and delivered / pickedUp (see `./outbound.ts`).
|
|
477
|
+
statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"]
|
|
451
478
|
},
|
|
452
479
|
normalize: normalizeOpenDeliveryEvent,
|
|
453
480
|
readSignature: /* @__PURE__ */ __name((header) => header("x-app-signature"), "readSignature"),
|
|
@@ -458,6 +485,8 @@ function createNinetyNineFoodAdapter(config) {
|
|
|
458
485
|
fetchOrder: /* @__PURE__ */ __name((ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions), "fetchOrder"),
|
|
459
486
|
confirm: /* @__PURE__ */ __name((ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input), "confirm"),
|
|
460
487
|
requestCancellation: /* @__PURE__ */ __name((ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input), "requestCancellation"),
|
|
488
|
+
statusSupported: openDeliveryStatusSupported,
|
|
489
|
+
informStatus: /* @__PURE__ */ __name((ctx, order, facts) => openDeliveryInformStatus(ctx, bases, order, facts), "informStatus"),
|
|
461
490
|
appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink"),
|
|
462
491
|
...config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}
|
|
463
492
|
};
|
package/dist/99food/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 tokenGrantResultOf,\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 = tokenGrantResultOf(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 if (alreadyCancelled(response)) return { kind: \"accepted\" };\n const result = outboundResultOf(response);\n // Open Delivery's 400 is a malformed request (a bad id or body: ours);\n // its 422 is the business answer and stays a refusal.\n return result.kind === \"refused\" && result.status === 400 ? { ...result, own: true } : result;\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;AAAA,EACrE;AACF;AAnBgB;AAsBhB,SAAS,WAAW,WAAoB,MAA+B;AACrE,SAAO,QAAQ,KAAK,QA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,OAAO,KAAK,aAAa,IAAI;AAAA,IACpC,iBAAiB,SAAS;AAAA;AAAA,IAE1B,YAAY;AAAA,EACd,EAAE;AACF,QAAM,mBAAmB,EAAE,qBAAqB,OAAO,KAAK,oBAAoB;AAChF,SAAO;AAAA,IACL,UAAU;AAAA,IACV,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ,WAAW;AAAA;AAAA;AAAA,MAGX,mBAAmB;AAAA;AAAA,MAEnB,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA;AAAA,MAEjB,6BAA6B;AAAA,MAC7B,4BAA4B;AAAA,IAC9B;AAAA,IACA,WAAW;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,iBAAiB,GAApC;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA;AAAA,IAErB,WAAW,sBAAsB,KAAK;AAAA,IACtC,YAAY,wBAAC,KAAK,UAAU,uBAAuB,KAAK,OAAO,OAAO,gBAAgB,GAA1E;AAAA,IACZ,SAAS,wBAAC,KAAK,OAAO,UAAU,oBAAoB,KAAK,OAAO,OAAO,KAAK,GAAnE;AAAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAAU,gCAAgC,KAAK,OAAO,OAAO,KAAK,GAA/E;AAAA,IACrB,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,yBAAyB,KAAK,EAAE,IAAI,CAAC;AAAA,EACvF;AACF;AAxCgB;","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 MarketplaceLifecycle,\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 order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */\nconst LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: \"DISPATCHED\", CONCLUDED: \"CONCLUDED\" };\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 * - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine\n * asks the host to move the order forward, when the store follows them.\n * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, 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 ...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),\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 tokenGrantResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type FetchOrderResult,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n type StatusFacts,\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 = tokenGrantResultOf(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 if (alreadyCancelled(response)) return { kind: \"accepted\" };\n const result = outboundResultOf(response);\n // Open Delivery's 400 is a malformed request (a bad id or body: ours);\n // its 422 is the business answer and stays a refusal.\n return result.kind === \"refused\" && result.status === 400 ? { ...result, own: true } : result;\n });\n}\n\n/**\n * What 99Food is told per step (FUT-4653), from Open Delivery v1.7.1's\n * `openapi.yaml` (https://abrasel-nacional.github.io/opendelivery/openapi.yaml,\n * read 2026-11-25, paths at lines 1605-1890):\n *\n * - READY: `POST /v1/orders/{id}/readyForPickup`, \"ready for pickup by the\n * customer or delivery person\"; 202. Every kind of order.\n * - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`\n * (`deliveryTrackingInfo` optional, sent empty), and \"a DISPATCHED event is\n * expected after this action\". Only where the logistics is the merchant's.\n * - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a\n * take-out `POST /v1/orders/{id}/pickedUp`. Both optional in the spec. The\n * marketplace's own fleet: none.\n *\n * The kind of order is `deliveredBy` (null: a take-out). That a take-out's\n * order states no `deliveredBy` is how 99Food's order reads (ESTIMATED: an\n * order that merely omits it reads as a take-out here).\n */\nconst STATUS_PATH: Readonly<Record<string, (facts: StatusFacts) => { action: string; body?: unknown } | null>> = {\n READY: () => ({ action: \"readyForPickup\" }),\n DISPATCHED: (facts) => (facts.deliveredBy === \"MERCHANT\" ? { action: \"dispatch\", body: {} } : null),\n HANDED_OVER: (facts) =>\n facts.deliveredBy === \"MERCHANT\"\n ? { action: \"delivered\", body: {} }\n : facts.deliveredBy === null\n ? { action: \"pickedUp\", body: {} }\n : null,\n};\n\n/** Whether 99Food takes this step for this kind of order: answered offline. */\nexport function openDeliveryStatusSupported(facts: StatusFacts): boolean {\n return STATUS_PATH[facts.step]?.(facts) != null;\n}\n\n/** Tell 99Food a step happened. `unsupported` when the spec has no call for it. */\nexport function openDeliveryInformStatus(\n ctx: AdapterCallContext,\n bases: NinetyNineFoodApiBaseUrls,\n order: OutboundOrderRef,\n facts: StatusFacts,\n): Promise<OutboundResult | { kind: \"unsupported\" }> {\n const path = STATUS_PATH[facts.step]?.(facts) ?? null;\n if (path === null) return Promise.resolve({ kind: \"unsupported\" });\n return answered(async () => {\n const response = await callOrder(ctx, bases, {\n method: \"POST\",\n externalOrderId: order.externalOrderId,\n action: path.action,\n ...(path.body === undefined ? {} : { body: path.body }),\n });\n return \"kind\" in response ? response : 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 openDeliveryInformStatus,\n openDeliveryRequestCancellation,\n openDeliveryStatusSupported,\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 // Open Delivery's readyForPickup, dispatch and delivered / pickedUp (see `./outbound.ts`).\n statusSteps: [\"READY\", \"DISPATCHED\", \"HANDED_OVER\"],\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 statusSupported: openDeliveryStatusSupported,\n informStatus: (ctx, order, facts) => openDeliveryInformStatus(ctx, bases, order, facts),\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;;;ACUO,IAAM,4BAA4B;AAGzC,IAAM,UAAU;AAEhB,IAAM,YAAY;AAElB,IAAM,eAA+D,EAAE,YAAY,cAAc,WAAW,YAAY;AAExH,IAAM,8BAA8B;AAa7B,SAAS,4BACd,SACA,WACA,eACS;AACT,MAAI,CAAC,cAAe,QAAO;AAC3B,SAAO,oBAAoB,SAAS,WAAW,aAAa;AAC9D;AAPgB;AAwBT,SAAS,2BAA2B,SAA0C;AACnF,QAAM,kBAAkB,YAAY,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC;AAC1D,MAAI,CAAC,gBAAiB,QAAO;AAC7B,QAAM,aAA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BAAyB,KAAK,EAAE,IAAI,CAAC;AAAA,EACvF;AACF;AA5CgB;","names":[]}
|
|
@@ -543,6 +543,13 @@ interface NormalizedMarketplaceOrder {
|
|
|
543
543
|
* `FAILED` when it refused the request.
|
|
544
544
|
*/
|
|
545
545
|
type CancellationOutcome = "CONFIRMED" | "FAILED";
|
|
546
|
+
/**
|
|
547
|
+
* A step of the order's life a marketplace announces about an order it
|
|
548
|
+
* already has (FUT-4653): the courier left (`DISPATCHED`) or the order is
|
|
549
|
+
* finished (`CONCLUDED`). An event that names one moves nothing by itself; the
|
|
550
|
+
* engine asks the host to move the order forward (`onLifecycle`).
|
|
551
|
+
*/
|
|
552
|
+
type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
|
|
546
553
|
/** What an adapter makes of one inbound delivery. */
|
|
547
554
|
interface NormalizedEvent {
|
|
548
555
|
provider: MarketplaceProvider;
|
|
@@ -574,6 +581,12 @@ interface NormalizedEvent {
|
|
|
574
581
|
* the event. Ignored when `order` is present.
|
|
575
582
|
*/
|
|
576
583
|
orderToFetch?: boolean;
|
|
584
|
+
/**
|
|
585
|
+
* OPTIONAL. The lifecycle step this event announces about an order the
|
|
586
|
+
* engine already has. Absent or null: the event names none. An event that
|
|
587
|
+
* names one carries no order body.
|
|
588
|
+
*/
|
|
589
|
+
lifecycle?: MarketplaceLifecycle | null;
|
|
577
590
|
}
|
|
578
591
|
|
|
579
592
|
/**
|
|
@@ -651,6 +664,21 @@ interface MarketplaceCapabilities {
|
|
|
651
664
|
* the request as TIMEOUT. Absent: only the 24-hour give-up applies.
|
|
652
665
|
*/
|
|
653
666
|
cancellationAnswerWindowMs?: number;
|
|
667
|
+
/**
|
|
668
|
+
* OPTIONAL. The steps this marketplace can be told about (`informStatus`).
|
|
669
|
+
* Absent or empty: the engine tells it nothing.
|
|
670
|
+
*/
|
|
671
|
+
statusSteps?: readonly StatusStep[];
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* A step of the order the store tells the marketplace about (FUT-4653): the
|
|
675
|
+
* order is ready for pickup, the courier left, the order was handed over.
|
|
676
|
+
*/
|
|
677
|
+
type StatusStep = "READY" | "DISPATCHED" | "HANDED_OVER";
|
|
678
|
+
/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */
|
|
679
|
+
interface StatusFacts {
|
|
680
|
+
step: StatusStep;
|
|
681
|
+
deliveredBy: MarketplaceDeliveredBy | null;
|
|
654
682
|
}
|
|
655
683
|
/** One reason a store may give for refusing or cancelling an order. */
|
|
656
684
|
interface CancellationReason {
|
|
@@ -746,6 +774,22 @@ interface MarketplaceAdapter {
|
|
|
746
774
|
}): Promise<OutboundResult>;
|
|
747
775
|
/** Ask the marketplace to cancel the order, with one of its own reasons. */
|
|
748
776
|
requestCancellation(ctx: AdapterCallContext, order: OutboundOrderRef, input: CancellationRequestInput): Promise<OutboundResult>;
|
|
777
|
+
/**
|
|
778
|
+
* OPTIONAL. Whether this marketplace takes this step for this kind of order,
|
|
779
|
+
* answered offline, with no call: the job asks it BEFORE it claims anything
|
|
780
|
+
* (an unsupported step leaves no row). Absent: every step in
|
|
781
|
+
* `capabilities.statusSteps` is taken for every order.
|
|
782
|
+
*/
|
|
783
|
+
statusSupported?(facts: StatusFacts): boolean;
|
|
784
|
+
/**
|
|
785
|
+
* OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called
|
|
786
|
+
* only from the `marketplace.outbound` job, action `status`. `unsupported`
|
|
787
|
+
* (no endpoint for this step and this kind of order) ends the job with no
|
|
788
|
+
* row. Absent: the marketplace is told nothing.
|
|
789
|
+
*/
|
|
790
|
+
informStatus?(ctx: AdapterCallContext, order: OutboundOrderRef, facts: StatusFacts): Promise<OutboundResult | {
|
|
791
|
+
kind: "unsupported";
|
|
792
|
+
}>;
|
|
749
793
|
/**
|
|
750
794
|
* OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
|
|
751
795
|
* marketplace whose events carry no order body). Called only from the
|
|
@@ -793,4 +837,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
|
|
|
793
837
|
/** A call that never got an answer is a retry, with the reason a log can read. */
|
|
794
838
|
declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
|
|
795
839
|
|
|
796
|
-
export { type
|
|
840
|
+
export { type NormalizedOrderLine as $, type AdapterCallContext as A, type CatalogueSnapshotCategory as B, type CatalogueMenuEntry as C, type CatalogueSnapshotItem as D, type CatalogueSnapshotOption as E, type CatalogueSnapshotOptionGroup as F, type CatalogueStoredImage as G, type CatalogueWarningCode as H, type FetchOrderResult as I, type MarketplaceCapabilities as J, type MarketplaceCatalogue as K, type MarketplaceCredentials as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type MarketplaceDeliveredBy as Q, type MarketplaceDiscountSponsor as R, type StorePauseRequest as S, type MarketplaceHttp as T, type MarketplaceHttpRequest as U, type MarketplaceHttpResponse as V, type MarketplaceLifecycle as W, type MarketplaceOrderType as X, type NormalizedAddress as Y, type NormalizedBuyer as Z, type NormalizedOrderDiscount as _, type NormalizedMarketplaceOrder as a, type OutboundOrderRef as a0, PROVIDER_ID_PATTERN as a1, type StatusFacts as a2, type StatusStep as a3, answered as a4, centsFromMajor as a5, outboundResultOf as a6, tokenGrantResultOf as a7, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type StorePauseResult as g, type StorePauseRef as h, type MarketplaceProvider as i, type CancellationReason as j, type AdapterTokenCache as k, type CancellationOutcome as l, type CancellationRequestInput as m, type CatalogueCallContext as n, type CatalogueFailure as o, type CatalogueImage as p, type CatalogueItem as q, type CatalogueItemRef as r, type CataloguePublishResult as s, type CatalogueReadContext as t, type CatalogueReadNotice as u, type CatalogueReadRefusalCode as v, type CatalogueReadResult as w, type CatalogueReadWarning as x, type CatalogueReadWarningCode as y, type CatalogueSnapshot as z };
|
|
@@ -7,13 +7,13 @@ import {
|
|
|
7
7
|
listMarketplaceMenuLinksQuery,
|
|
8
8
|
upsertMarketplaceIntegrationsBody,
|
|
9
9
|
upsertMarketplaceMenuLinksBody
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-NP4EYKPO.js";
|
|
11
11
|
import {
|
|
12
12
|
AvailabilityRetryError,
|
|
13
13
|
CatalogueRetryError,
|
|
14
14
|
FetchOrderRetryError,
|
|
15
15
|
OutboundRetryError
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-BMCERPQX.js";
|
|
17
17
|
import {
|
|
18
18
|
__name
|
|
19
19
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -99,7 +99,7 @@ async function handleWebhook(config, request) {
|
|
|
99
99
|
payload,
|
|
100
100
|
// A DISABLED connection still stores its deliveries and ingests nothing;
|
|
101
101
|
// the retry sweep ingests them if the store turns it back on.
|
|
102
|
-
settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds } : null
|
|
102
|
+
settings: target.enabled ? { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds, followStatus: target.followStatus } : null
|
|
103
103
|
});
|
|
104
104
|
if (outcome.kind === "failed") {
|
|
105
105
|
return { status: 500, body: { received: true, error: outcome.reason } };
|
|
@@ -473,4 +473,4 @@ export {
|
|
|
473
473
|
MARKETPLACE_JOBS,
|
|
474
474
|
createApiMarketplace
|
|
475
475
|
};
|
|
476
|
-
//# sourceMappingURL=chunk-
|
|
476
|
+
//# sourceMappingURL=chunk-6N2HEV3U.js.map
|