@12-apps/marketplace 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/ADOPTING.md +47 -0
  2. package/README.md +122 -1
  3. package/dist/99food/index.d.ts +33 -2
  4. package/dist/99food/index.js +34 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-0l_EmuJA.d.ts → adapter-CCWMqt2g.d.ts} +275 -3
  7. package/dist/{chunk-XUAFXNOH.js → chunk-FKUEFVVA.js} +396 -4
  8. package/dist/chunk-FKUEFVVA.js.map +1 -0
  9. package/dist/{chunk-RVBTARIY.js → chunk-RGMSD7S7.js} +1 -1
  10. package/dist/chunk-RGMSD7S7.js.map +1 -0
  11. package/dist/{chunk-AYYBRQJV.js → chunk-UONWZIBO.js} +43 -3
  12. package/dist/chunk-UONWZIBO.js.map +1 -0
  13. package/dist/chunk-WN2EK4KX.js +15 -0
  14. package/dist/chunk-WN2EK4KX.js.map +1 -0
  15. package/dist/{engine-CZsP8KWd.d.ts → engine-C3uq_BJd.d.ts} +252 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +44 -2
  19. package/dist/ifood/index.js +441 -1
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +342 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +4 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +56 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +18 -7
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +67 -1
  33. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  34. package/src/99food/index.ts +10 -0
  35. package/src/99food/pause.ts +56 -0
  36. package/src/core/adapter.ts +19 -2
  37. package/src/core/catalogue-read-port.ts +151 -0
  38. package/src/core/catalogue-read.ts +51 -0
  39. package/src/core/engine.ts +46 -0
  40. package/src/core/pause-job.ts +381 -0
  41. package/src/core/pause-port.ts +110 -0
  42. package/src/core/pause-retired.ts +139 -0
  43. package/src/core/pause-store.ts +151 -0
  44. package/src/core/pause-sweep.ts +148 -0
  45. package/src/core/pause.ts +316 -0
  46. package/src/core/ports.ts +11 -0
  47. package/src/ifood/catalogue-read.ts +187 -0
  48. package/src/ifood/catalogue-snapshot.ts +246 -0
  49. package/src/ifood/index.ts +9 -0
  50. package/src/ifood/pause.ts +257 -0
  51. package/src/index.ts +39 -0
  52. package/src/rappi/index.ts +11 -0
  53. package/src/rappi/outbound.ts +2 -2
  54. package/src/rappi/pause.ts +98 -0
  55. package/src/server/index.ts +1 -0
  56. package/src/server/jobs.ts +64 -4
  57. package/dist/chunk-AYYBRQJV.js.map +0 -1
  58. package/dist/chunk-RVBTARIY.js.map +0 -1
  59. package/dist/chunk-XUAFXNOH.js.map +0 -1
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  answered,
10
10
  outboundResultOf
11
- } from "../chunk-RVBTARIY.js";
11
+ } from "../chunk-RGMSD7S7.js";
12
12
  import {
13
13
  __name
14
14
  } from "../chunk-7QVYU63E.js";
@@ -280,6 +280,57 @@ function rappiReject(ctx, hosts, order, input) {
280
280
  }
281
281
  __name(rappiReject, "rappiReject");
282
282
 
283
+ // src/rappi/pause.ts
284
+ function refusalIn(body, storeId) {
285
+ let results;
286
+ try {
287
+ const parsed = JSON.parse(body === "" ? "{}" : body);
288
+ results = Array.isArray(parsed.results) ? parsed.results : [];
289
+ } catch {
290
+ return null;
291
+ }
292
+ const entry = results.find((result) => String(result.store_id) === storeId);
293
+ if (!entry) return null;
294
+ const type = typeof entry.operation_result_type === "string" ? entry.operation_result_type : "";
295
+ const failed = entry.operation_result === false || /error|fail/iu.test(type);
296
+ if (!failed) return null;
297
+ const message = typeof entry.operation_result_message === "string" ? entry.operation_result_message : type;
298
+ return { kind: "refused", status: 200, message: message.slice(0, 300) };
299
+ }
300
+ __name(refusalIn, "refusalIn");
301
+ var tokenKey2 = /* @__PURE__ */ __name((ctx) => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`, "tokenKey");
302
+ function rappiSetStoreEnabled(ctx, hosts, storeId, enabled) {
303
+ return answered(async () => {
304
+ const auth = await bearer(ctx, hosts);
305
+ if (!("token" in auth)) return auth;
306
+ const response = await ctx.http({
307
+ method: "PUT",
308
+ url: `${trimmed(hosts.api[ctx.environment])}/availability/stores/enable`,
309
+ headers: { "x-authorization": `Bearer ${auth.token}`, "Content-Type": "application/json" },
310
+ body: JSON.stringify({ stores: [{ store_id: storeId, is_enabled: enabled }] })
311
+ });
312
+ if (response.status === 401) {
313
+ ctx.tokens.delete(tokenKey2(ctx));
314
+ return { kind: "retry", reason: "Rappi refused the token" };
315
+ }
316
+ const result = outboundResultOf(response);
317
+ if (result.kind !== "accepted") return result;
318
+ return refusalIn(response.body, storeId) ?? result;
319
+ });
320
+ }
321
+ __name(rappiSetStoreEnabled, "rappiSetStoreEnabled");
322
+ function rappiAvailability(hosts) {
323
+ return {
324
+ kind: "switch",
325
+ pause: /* @__PURE__ */ __name(async (ctx, request) => {
326
+ const result = await rappiSetStoreEnabled(ctx, hosts, request.merchantId, false);
327
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
328
+ }, "pause"),
329
+ resume: /* @__PURE__ */ __name((ctx, ref) => rappiSetStoreEnabled(ctx, hosts, ref.merchantId, true), "resume")
330
+ };
331
+ }
332
+ __name(rappiAvailability, "rappiAvailability");
333
+
283
334
  // src/rappi/index.ts
284
335
  var RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 6e4;
285
336
  var ITEM_UNAVAILABLE = "ITEM_OUT_OF_STOCK";
@@ -341,7 +392,8 @@ function createRappiAdapter(config) {
341
392
  cancellationReasons: /* @__PURE__ */ __name(() => reasons, "cancellationReasons"),
342
393
  confirm: /* @__PURE__ */ __name((ctx, order, input) => rappiTake(ctx, hosts, order, input), "confirm"),
343
394
  requestCancellation: /* @__PURE__ */ __name((ctx, order, input) => rappiReject(ctx, hosts, order, input), "requestCancellation"),
344
- appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink")
395
+ appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink"),
396
+ ...config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}
345
397
  };
346
398
  }
347
399
  __name(createRappiAdapter, "createRappiAdapter");
@@ -354,6 +406,8 @@ export {
354
406
  createRappiAdapter,
355
407
  normalizeRappiEvent,
356
408
  normalizeRappiOrder,
409
+ rappiAvailability,
410
+ rappiSetStoreEnabled,
357
411
  verifyRappiSignature
358
412
  };
359
413
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/outbound.ts","../../src/rappi/index.ts"],"sourcesContent":["/**\n * The words the Rappi 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 `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,\n * verbatim from Rappi's public API reference (dev-portal.rappi.com,\n * api-reference/orders, \"PUT orders/{orderId}/reject\"). Pinned by the portal,\n * not estimated.\n */\nexport const RAPPI_REASON_CODES = [\n \"ITEM_OUT_OF_STOCK\",\n \"ITEM_NOT_FOUND\",\n \"ITEM_WRONG_PRICE\",\n \"ORDER_MISSING_INFORMATION\",\n \"ORDER_MISSING_ADDRESS_INFORMATION\",\n \"ORDER_TOTAL_INCORRECT\",\n] as const;\n\nexport type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];\n\n/**\n * The codes with which the portal REQUIRES the offending items (\"If the value\n * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,\n * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the\n * offending items\").\n */\nexport const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = [\"ITEM_OUT_OF_STOCK\", \"ITEM_NOT_FOUND\", \"ITEM_WRONG_PRICE\"];\n\nexport interface RappiAdapterCopy {\n /** One label per reason code. Sent as the reject's required `reason` text. */\n reasonLabels: Readonly<Record<RappiReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { asString, firstDate, firstString, pick, verifyHmacSha256Hex } 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 Rappi adapter's INBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: webhook-events, api-reference/orders), read\n * 2026-11-13.\n *\n * Rappi registers one webhook URL PER EVENT, and its payloads do not name the\n * event they are. So the event is read from the body's shape, as the portal\n * documents each one:\n *\n * - `NEW_ORDER` is \"the same information that we can get from the getOrders\n * endpoint\": one element of `GET orders`, an `order_detail` (with `items`,\n * `totals`, `delivery_information`) beside `customer` and `store`.\n * - `NEW_ORDER_SCHEDULED` is that shape plus `\"action\": \"scheduled\"`, every\n * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.\n * - `NEW_ORDER_SCHEDULED_CANCELLED` is `\"action\": \"cancelled\"` with an\n * `order_detail.order_id`: an order never released to the store; ignored.\n * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the\n * cancellation (`canceled_with_charge`).\n * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,\n * additional_information }`; recorded, ignored.\n *\n * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL\n * from ORDER_OTHER_EVENT. The portal shows one example of each and names no\n * list of `event` values, so a payload is a cancellation only when it has\n * neither `event_time` nor `additional_information` AND its `event` names a\n * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything\n * else is recorded and IGNORED: a missed cancellation is visible in the inbox,\n * a false one would cancel a live order.\n *\n * Rappi payloads carry no event id, so the inbox key is derived from the\n * order and the event, deterministic so a redelivery collides on the inbox's\n * unique index.\n */\n\n/** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const RAPPI_PROVIDER = \"RAPPI\";\n\n/** The header Rappi signs every webhook in (the portal: \"Rappi-Signature\"; headers are case-insensitive). */\nexport const RAPPI_SIGNATURE_HEADER = \"rappi-signature\";\n\n/**\n * How Rappi states money. The portal types every amount as an `integer` and\n * names no unit (its examples are Colombian and Mexican pesos). Whether a\n * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so\n * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`\n * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.\n */\nexport type RappiAmountUnit = \"MINOR_UNITS\" | \"MAJOR_UNITS\";\n\nexport interface RappiNormalizeOptions {\n amountUnit: RappiAmountUnit;\n missingStreetNumber: string;\n}\n\n/**\n * Verify a delivery, as the portal's \"Validating Your Signature\" says:\n * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is\n * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by\n * the webhook's secret. The digest's encoding is not stated: the portal's\n * example `sign` is 64 hex characters, so it is read as lowercase hex\n * (ESTIMATED). Compared in constant time.\n *\n * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a\n * connection without one refuses every delivery (an unsigned\n * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No\n * timestamp tolerance is applied: the portal states none, and a replayed\n * delivery is a duplicate in the inbox.\n */\nexport function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !header) return false;\n const parts = signatureParts(header);\n if (parts.t === null || parts.sign === null) return false;\n return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);\n}\n\n/** `t=…,sign=…` split on \",\" then on the first \"=\", as the portal describes. No regex. */\nfunction signatureParts(header: string): { t: string | null; sign: string | null } {\n const found: { t: string | null; sign: string | null } = { t: null, sign: null };\n for (const element of header.split(\",\")) {\n const at = element.indexOf(\"=\");\n if (at < 0) continue;\n const key = element.slice(0, at).trim().toLowerCase();\n const value = element.slice(at + 1).trim();\n if (value === \"\") continue;\n if (key === \"t\") found.t = value;\n if (key === \"sign\") found.sign = value;\n }\n return found;\n}\n\n/** Rappi's store id, from wherever this event shape keeps it. */\nfunction storeIdOf(payload: unknown): string | null {\n return firstString(payload, [[\"store\", \"internal_id\"], [\"order_detail\", \"store\", \"internal_id\"], [\"order_detail\", \"store_id\"], [\"store_id\"]]);\n}\n\n/** One event's frame; the order is filled by the caller. */\nfunction eventOf(\n orderId: string,\n eventType: string,\n payload: unknown,\n extra: Partial<NormalizedEvent> & { eventId?: string } = {},\n): NormalizedEvent {\n return {\n provider: RAPPI_PROVIDER,\n eventId: `${orderId}:${eventType}`,\n eventType,\n externalMerchantId: storeIdOf(payload),\n externalOrderId: orderId,\n order: null,\n cancelled: false,\n cancellationOutcome: null,\n ...extra,\n };\n}\n\n/** A shape with an `order_detail`: NEW_ORDER, or one of the scheduled notices. */\nfunction orderDetailEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_detail\", \"order_id\"]]);\n if (!orderId) return null;\n const action = firstString(payload, [[\"action\"]])?.toLowerCase() ?? null;\n if (action === \"scheduled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED\", payload);\n if (action === \"cancelled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED_CANCELLED\", payload);\n return eventOf(orderId, \"NEW_ORDER\", payload, { order: normalizeRappiOrder(payload, options) });\n}\n\n/** Whether `event` names a cancellation: \"cancel\" in it, case-insensitive. ESTIMATED (see the file header). */\nfunction namesCancellation(event: string): boolean {\n return event.toLowerCase().includes(\"cancel\");\n}\n\n/** A shape with a top-level `order_id`: ORDER_EVENT_CANCEL or ORDER_OTHER_EVENT (and the tracking stream). */\nfunction orderEvent(payload: unknown): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_id\"]]);\n if (!orderId) return null;\n const event = firstString(payload, [[\"event\"]]) ?? \"UNKNOWN\";\n const other = pick(payload, \"event_time\") !== undefined || pick(payload, \"additional_information\") !== undefined;\n const cancelled = !other && namesCancellation(event);\n const eventType = cancelled ? \"ORDER_EVENT_CANCEL\" : \"ORDER_OTHER_EVENT\";\n const at = asString(pick(payload, \"event_time\"));\n return eventOf(orderId, eventType, payload, {\n eventId: [orderId, eventType, event, ...(at ? [at] : [])].join(\":\"),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : null,\n });\n}\n\n/**\n * Normalize one webhook delivery. Null only when it names no order (PING,\n * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.\n */\nexport function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const detail = pick(payload, \"order_detail\");\n if (typeof detail === \"object\" && detail !== null) return orderDetailEvent(payload, options);\n return orderEvent(payload);\n}\n\n/** An amount as Rappi states it, in cents; null when absent or not a number. */\nfunction amountCents(value: unknown, unit: RappiAmountUnit): number | null {\n const numeric = typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(unit === \"MAJOR_UNITS\" ? numeric * 100 : numeric);\n}\n\n/** A stated count, 1 when absent or nonsense. */\nfunction countOf(source: unknown): number {\n const stated = Number(pick(source, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\nfunction arrayAt(source: unknown, ...path: string[]): unknown[] {\n const found = pick(source, ...path);\n return Array.isArray(found) ? found : [];\n}\n\n/**\n * One unit's price: the item's `price` (\"Unit price for the item without the\n * discount\") plus each subitem's `price × quantity`. ESTIMATED: the portal\n * does not say whether a subitem's quantity is per unit of its item or for the\n * whole line; it is read per unit (a topping on each salad of three).\n */\nfunction unitCents(item: unknown, unit: RappiAmountUnit): number {\n const base = amountCents(pick(item, \"price\"), unit) ?? 0;\n return arrayAt(item, \"subitems\").reduce<number>(\n (sum, sub) => sum + (amountCents(pick(sub, \"price\"), unit) ?? 0) * countOf(sub),\n base,\n );\n}\n\n/** The ticket's note: the subitems (a topping, a dressing) and the buyer's comments. */\nfunction lineNote(item: unknown): string | null {\n const subitems = arrayAt(item, \"subitems\")\n .map((sub) => {\n const name = asString(pick(sub, \"name\"));\n const quantity = countOf(sub);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n // `comments` is typed an array and shown as a string in the same reference.\n const rawComments = pick(item, \"comments\");\n const comments = (Array.isArray(rawComments) ? rawComments : [rawComments])\n .map(asString)\n .filter((comment): comment is string => comment !== null);\n const note = [subitems.join(\", \"), ...comments].filter((part) => part !== \"\").join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * One `order_detail.items[]` entry → its lines, which add up EXACTLY to the\n * item's total. A whole quantity is one row at the unit price (`unit × q` is\n * the total, nothing to divide); a fractional one (the portal types quantity\n * an integer, so this is defensive) is one row at its rounded total.\n *\n * The key is the item's `sku` (the store's own, \"the ally grants their own\n * SKU\"), then Rappi's `id`, then the name: an unmapped line is recoverable, a\n * dropped one is not.\n */\nfunction readLines(item: unknown, unit: RappiAmountUnit): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = countOf(item);\n const each = unitCents(item, unit);\n const row = Number.isInteger(quantity)\n ? { quantity, unitPriceCents: each }\n : { quantity: 1, unitPriceCents: Math.round(each * quantity) };\n return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];\n}\n\n/**\n * `delivery_method`: `delivery` (Rappi's courier), `marketplace` (the store's\n * own: the portal sends the customer's data \"only when delivery method is\n * marketplace\"), `pickup`.\n */\nfunction readMethod(detail: unknown): { orderType: MarketplaceOrderType | null; deliveredBy: MarketplaceDeliveredBy | null } {\n const method = firstString(detail, [[\"delivery_method\"]])?.toLowerCase();\n if (method === \"delivery\") return { orderType: \"DELIVERY\", deliveredBy: \"MARKETPLACE\" };\n if (method === \"marketplace\") return { orderType: \"DELIVERY\", deliveredBy: \"MERCHANT\" };\n if (method === \"pickup\") return { orderType: \"TAKEOUT\", deliveredBy: null };\n return { orderType: null, deliveredBy: null };\n}\n\n/** `order_detail.delivery_information`, the Brazilian fields included (`federal_unit`). */\nfunction readAddress(detail: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(detail, \"delivery_information\");\n const street = firstString(raw, [[\"street_name\"], [\"complete_address\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"street_number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"description\"]]),\n postalCode: firstString(raw, [[\"postal_code\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"federal_unit\"]]),\n };\n}\n\n/** The buyer, top-level `customer` as the example has it, or under `order_detail` as the table names it. */\nfunction readBuyer(payload: unknown): NormalizedMarketplaceOrder[\"buyer\"] {\n const customer = pick(payload, \"customer\") ?? pick(payload, \"order_detail\", \"customer\");\n const name = [firstString(customer, [[\"first_name\"]]), firstString(customer, [[\"last_name\"]])]\n .filter((part): part is string => part !== null)\n .join(\" \");\n return { externalId: null, name: name === \"\" ? null : name, phone: firstString(customer, [[\"phone_number\"]]) };\n}\n\n/**\n * Normalize one getOrders element (the NEW_ORDER body). Null when it carries\n * no order id or no line.\n *\n * The total is `totals.total_order`, \"the total amount that the restaurant\n * receives\" (with tip and delivery fee when the store delivers): the figure\n * the store's receipt is reconciled against. Rappi states no commission, so\n * `commissionCents` is null (\"did not say\"), never 0. The merchant the order\n * names is Rappi's store id (`store.internal_id`), the id every other event\n * carries as `store_id`; the engine refuses it for another connection.\n */\nexport function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null {\n const detail = pick(payload, \"order_detail\");\n const externalOrderId = firstString(detail, [[\"order_id\"]]);\n const lines = arrayAt(detail, \"items\").flatMap((item) => readLines(item, options.amountUnit));\n if (!externalOrderId || lines.length === 0) return null;\n const method = readMethod(detail);\n return {\n provider: RAPPI_PROVIDER,\n externalOrderId,\n // Rappi's order id is the number its app and courier show.\n externalDisplayId: externalOrderId,\n externalMerchantId: storeIdOf(payload),\n buyer: readBuyer(payload),\n lines,\n totalCents:\n amountCents(pick(detail, \"totals\", \"total_order\"), options.amountUnit) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n // Rappi states no delivery promise on the order.\n deliveryDueAt: null,\n placedAt: firstDate(detail, [[\"created_at\"]]) ?? new Date(),\n orderType: method.orderType,\n deliveredBy: method.deliveredBy,\n deliveryAddress: method.orderType === \"TAKEOUT\" ? null : readAddress(detail, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\n\n/**\n * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: authentication-process, api-reference/orders), read\n * 2026-11-13: the token, take and reject. The job that calls these, its\n * retries and what a failure shows are the engine's.\n *\n * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,\n * JSON `{ client_id, client_secret }`; \"the system responds with your\n * access_token\", valid \"1 week\"; sent as `x-authorization: Bearer <token>`.\n * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,\n * the cooking time optional (\"leave this field empty to keep the default\");\n * 200 taken, 400 \"Invalid state transition\", 404 not found.\n * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,\n * items_skus }`, only from SENT; 200 rejected, 400, 404.\n *\n * WHERE is not public per partner: the portal names its domains by country\n * (`{COUNTRY_DOMAIN}`, and a \"new\" one for the token), and Rappi's account\n * manager opens the sandbox. So the orders API's base and the token URL, per\n * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach\n * Rappi: the HTTP client is the host's port, answered by a fake.\n */\n\n/** One https URL per environment. */\nexport type RappiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/**\n * The two places the adapter calls, both host config (the portal's paths\n * carry the origin application's own noun, so they are the host's to state):\n * - `api`: the orders API's base, the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to\n * which the adapter appends `/orders/{orderId}/…`;\n * - `token`: the token endpoint itself, the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.\n */\nexport interface RappiHosts {\n api: RappiBaseUrls;\n token: RappiBaseUrls;\n}\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/**\n * The portal: \"Your access token has a validity of 1 week\". Used when the\n * answer states no `expires_in` (the answer's shape beyond `access_token` is\n * not shown: ESTIMATED).\n */\nconst DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;\n\n/** A base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nfunction trimmed(base: string): string {\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The token answer, read defensively: `access_token`, and `expires_in` when present. */\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 token from the per-process cache, or a fresh one from the token endpoint\n * (the M2M client credentials). Keyed by environment and client id; memory\n * only, written to no row or log.\n */\nasync function bearer(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\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: hosts.token[ctx.environment],\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"Rappi answered the token request 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 PUT to an order's resource: the raw answer, or the result that ends it. */\nasync function putOrder(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n request: { externalOrderId: string; action: string; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, hosts);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"PUT\",\n url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,\n headers: {\n \"x-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: \"Rappi refused the token\" };\n}\n\n/**\n * Take the order: `PUT …/orders/{orderId}/take/{cookingTime}`, the store's\n * preparation minutes as the cooking time, or `…/take/` to keep the order's\n * own (the portal: outside the order's range, Rappi uses the nearest bound).\n * The empty segment is how the portal's guide spells it\n * (`PUT /orders/{orderId}/take/`); ESTIMATED that Rappi's router serves it\n * (a 404 there would read as a refusal and show the portal link).\n * Every refused answer (400 \"Invalid state transition\", 404) is a refusal: the\n * store sees \"não confirmou\" and the app link.\n */\nexport function rappiTake(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n const minutes = input.preparationMinutes === null ? \"\" : String(Math.round(input.preparationMinutes));\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n\n/**\n * Reject the order: `PUT …/orders/{orderId}/reject` with `reason` (required\n * free text: the store's, else the reason's label), `cancel_type` (one of the\n * portal's six) and `items_skus` (the offending SKUs, required by the three\n * item reasons). The answer IS the outcome: 200 rejected (the engine stamps\n * CONFIRMED), any refusal FAILED with the app link.\n *\n * `items_skus` carries the engine's SKUs, which are the store's own `sku`\n * where the order states one. A line Rappi sent with no `sku` keys on Rappi's\n * item id, which the portal wants under `items_ids` instead; it is sent under\n * `items_skus` all the same (ESTIMATED: Rappi may refuse it, which reads as a\n * refusal and puts the app link in front of a person).\n */\nexport function rappiReject(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n const body = {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancel_type: input.reason.code,\n ...(input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}),\n };\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: \"reject\", body });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nimport {\n RAPPI_PROVIDER,\n RAPPI_SIGNATURE_HEADER,\n normalizeRappiEvent,\n verifyRappiSignature,\n type RappiAmountUnit,\n} from \"./normalize\";\nimport { rappiReject, rappiTake, type RappiBaseUrls } from \"./outbound\";\n\n/**\n * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.\n *\n * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's\n * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client\n * credentials. Everything Rappi is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port, and registering it is the\n * whole cost:\n *\n * ```ts\n * import { createRappiAdapter } from \"@12-apps/marketplace/rappi\";\n * import { RAPPI_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/rappi/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),\n * ],\n * });\n * ```\n *\n * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi\n * as its own subscription, all pointing at the same URL) are the engine's one\n * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.\n *\n * What Rappi CANNOT do through its public API is stated, never inferred: a\n * reject is only accepted while the order is SENT (before it is taken), and\n * there is no public endpoint to cancel a taken order. So\n * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is\n * FAILED at once and opens Rappi's portal (the app link) — and the reject's\n * answer is the outcome (`asyncCancellationOutcome: false`).\n */\n\nexport { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from \"./normalize\";\n\n/**\n * How long a reject may wait to be delivered. From the portal: an order in\n * SENT has \"a time limit of 6 minutes to take or reject the order, otherwise\n * it will transition to TIMEOUT status\", so a reject that has not reached Rappi\n * six minutes after it was asked can no longer be one. The request is failed\n * as TIMEOUT and a person finishes it on Rappi.\n *\n * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine\n * counts this window from the request. A reject asked late in Rappi's window\n * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads\n * as a refusal (FAILED, the portal link): slower than needed, never wrong.\n */\nexport const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: RappiReasonCode = \"ITEM_OUT_OF_STOCK\";\n\nconst AMOUNT_UNITS: readonly RappiAmountUnit[] = [\"MINOR_UNITS\", \"MAJOR_UNITS\"];\n\nexport interface RappiAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: RappiAdapterCopy;\n /**\n * The orders API's base per environment, https: the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its\n * samples use the `https://microservices.dev.rappi.com` domain). The adapter\n * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.\n * Required and defaultless: Rappi's account manager confirms the partner's\n * country domain.\n */\n apiBaseUrl: RappiBaseUrls;\n /**\n * The token endpoint per environment, https, whole: the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`\n * (\"for integrations services\"). Required and defaultless.\n */\n tokenUrl: RappiBaseUrls;\n /** Where \"open it on Rappi\" goes: the partner portal (Rappi names no per-order link). Required; https only. */\n portalUrl: string;\n /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */\n amountUnit: RappiAmountUnit;\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/rappi: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);\n}\n\nfunction assertConfig(config: RappiAdapterConfig): void {\n for (const env of [\"SANDBOX\", \"PRODUCTION\"] as const) {\n assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);\n assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);\n }\n assertHttps(\"portalUrl\", config.portalUrl);\n if (!AMOUNT_UNITS.includes(config.amountUnit)) {\n throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(\", \")}.`);\n }\n}\n\n/** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */\nexport function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {\n assertConfig(config);\n const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };\n const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: RAPPI_ITEM_REASON_CODES.includes(code),\n }));\n const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: RAPPI_PROVIDER,\n // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,\n // replaces the store's WHOLE menu, goes to an approval, and ignores every\n // further menu while one is in approval: a per-product switch on it would\n // wipe what the store keeps on Rappi's portal and report \"in the catalogue\"\n // for a menu Rappi may have dropped. Its availability endpoints only turn\n // items Rappi already has on and off. See the README, \"Catalogue publishing\".\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // Reject only from SENT; no public endpoint cancels a TAKEN order.\n cancelAfterAccept: false,\n // 200 is \"Order successfully rejected\": the answer is the outcome.\n asyncCancellationOutcome: false,\n perOrderAppLink: false,\n // `take/{cookingTime}`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),\n readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),\n verifySignature: verifyRappiSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),\n requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),\n appLink: () => config.portalUrl,\n };\n}\n\nexport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nexport {\n normalizeRappiEvent,\n normalizeRappiOrder,\n verifyRappiSignature,\n type RappiAmountUnit,\n type RappiNormalizeOptions,\n} from \"./normalize\";\nexport type { RappiBaseUrls, RappiHosts } from \"./outbound\";\n"],"mappings":";;;;;;;;;;;;;;;;AAcO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,0BAAsD,CAAC,qBAAqB,kBAAkB,kBAAkB;;;ACctH,IAAM,iBAAiB;AAGvB,IAAM,yBAAyB;AA8B/B,SAAS,qBAAqB,SAAiB,QAAuB,eAAuC;AAClH,MAAI,CAAC,iBAAiB,CAAC,OAAQ,QAAO;AACtC,QAAM,QAAQ,eAAe,MAAM;AACnC,MAAI,MAAM,MAAM,QAAQ,MAAM,SAAS,KAAM,QAAO;AACpD,SAAO,oBAAoB,GAAG,MAAM,CAAC,IAAI,OAAO,IAAI,MAAM,MAAM,aAAa;AAC/E;AALgB;AAQhB,SAAS,eAAe,QAA2D;AACjF,QAAM,QAAmD,EAAE,GAAG,MAAM,MAAM,KAAK;AAC/E,aAAW,WAAW,OAAO,MAAM,GAAG,GA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outbound.ts","../../src/rappi/pause.ts","../../src/rappi/index.ts"],"sourcesContent":["/**\n * The words the Rappi 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 `cancel_type` values a store may send with `PUT orders/{orderId}/reject`,\n * verbatim from Rappi's public API reference (dev-portal.rappi.com,\n * api-reference/orders, \"PUT orders/{orderId}/reject\"). Pinned by the portal,\n * not estimated.\n */\nexport const RAPPI_REASON_CODES = [\n \"ITEM_OUT_OF_STOCK\",\n \"ITEM_NOT_FOUND\",\n \"ITEM_WRONG_PRICE\",\n \"ORDER_MISSING_INFORMATION\",\n \"ORDER_MISSING_ADDRESS_INFORMATION\",\n \"ORDER_TOTAL_INCORRECT\",\n] as const;\n\nexport type RappiReasonCode = (typeof RAPPI_REASON_CODES)[number];\n\n/**\n * The codes with which the portal REQUIRES the offending items (\"If the value\n * informed for cancel_type is one of the following: ITEM_WRONG_PRICE,\n * ITEM_NOT_FOUND, ITEM_OUT_OF_STOCK. It would be required to include the\n * offending items\").\n */\nexport const RAPPI_ITEM_REASON_CODES: readonly RappiReasonCode[] = [\"ITEM_OUT_OF_STOCK\", \"ITEM_NOT_FOUND\", \"ITEM_WRONG_PRICE\"];\n\nexport interface RappiAdapterCopy {\n /** One label per reason code. Sent as the reject's required `reason` text. */\n reasonLabels: Readonly<Record<RappiReasonCode, string>>;\n /** What an address with no street number says instead. */\n missingStreetNumber: string;\n}\n","import { asString, firstDate, firstString, pick, verifyHmacSha256Hex } 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 Rappi adapter's INBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: webhook-events, api-reference/orders), read\n * 2026-11-13.\n *\n * Rappi registers one webhook URL PER EVENT, and its payloads do not name the\n * event they are. So the event is read from the body's shape, as the portal\n * documents each one:\n *\n * - `NEW_ORDER` is \"the same information that we can get from the getOrders\n * endpoint\": one element of `GET orders`, an `order_detail` (with `items`,\n * `totals`, `delivery_information`) beside `customer` and `store`.\n * - `NEW_ORDER_SCHEDULED` is that shape plus `\"action\": \"scheduled\"`, every\n * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.\n * - `NEW_ORDER_SCHEDULED_CANCELLED` is `\"action\": \"cancelled\"` with an\n * `order_detail.order_id`: an order never released to the store; ignored.\n * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the\n * cancellation (`canceled_with_charge`).\n * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,\n * additional_information }`; recorded, ignored.\n *\n * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL\n * from ORDER_OTHER_EVENT. The portal shows one example of each and names no\n * list of `event` values, so a payload is a cancellation only when it has\n * neither `event_time` nor `additional_information` AND its `event` names a\n * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything\n * else is recorded and IGNORED: a missed cancellation is visible in the inbox,\n * a false one would cancel a live order.\n *\n * Rappi payloads carry no event id, so the inbox key is derived from the\n * order and the event, deterministic so a redelivery collides on the inbox's\n * unique index.\n */\n\n/** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */\nexport const RAPPI_PROVIDER = \"RAPPI\";\n\n/** The header Rappi signs every webhook in (the portal: \"Rappi-Signature\"; headers are case-insensitive). */\nexport const RAPPI_SIGNATURE_HEADER = \"rappi-signature\";\n\n/**\n * How Rappi states money. The portal types every amount as an `integer` and\n * names no unit (its examples are Colombian and Mexican pesos). Whether a\n * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so\n * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`\n * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.\n */\nexport type RappiAmountUnit = \"MINOR_UNITS\" | \"MAJOR_UNITS\";\n\nexport interface RappiNormalizeOptions {\n amountUnit: RappiAmountUnit;\n missingStreetNumber: string;\n}\n\n/**\n * Verify a delivery, as the portal's \"Validating Your Signature\" says:\n * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is\n * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by\n * the webhook's secret. The digest's encoding is not stated: the portal's\n * example `sign` is 64 hex characters, so it is read as lowercase hex\n * (ESTIMATED). Compared in constant time.\n *\n * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a\n * connection without one refuses every delivery (an unsigned\n * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No\n * timestamp tolerance is applied: the portal states none, and a replayed\n * delivery is a duplicate in the inbox.\n */\nexport function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean {\n if (!webhookSecret || !header) return false;\n const parts = signatureParts(header);\n if (parts.t === null || parts.sign === null) return false;\n return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);\n}\n\n/** `t=…,sign=…` split on \",\" then on the first \"=\", as the portal describes. No regex. */\nfunction signatureParts(header: string): { t: string | null; sign: string | null } {\n const found: { t: string | null; sign: string | null } = { t: null, sign: null };\n for (const element of header.split(\",\")) {\n const at = element.indexOf(\"=\");\n if (at < 0) continue;\n const key = element.slice(0, at).trim().toLowerCase();\n const value = element.slice(at + 1).trim();\n if (value === \"\") continue;\n if (key === \"t\") found.t = value;\n if (key === \"sign\") found.sign = value;\n }\n return found;\n}\n\n/** Rappi's store id, from wherever this event shape keeps it. */\nfunction storeIdOf(payload: unknown): string | null {\n return firstString(payload, [[\"store\", \"internal_id\"], [\"order_detail\", \"store\", \"internal_id\"], [\"order_detail\", \"store_id\"], [\"store_id\"]]);\n}\n\n/** One event's frame; the order is filled by the caller. */\nfunction eventOf(\n orderId: string,\n eventType: string,\n payload: unknown,\n extra: Partial<NormalizedEvent> & { eventId?: string } = {},\n): NormalizedEvent {\n return {\n provider: RAPPI_PROVIDER,\n eventId: `${orderId}:${eventType}`,\n eventType,\n externalMerchantId: storeIdOf(payload),\n externalOrderId: orderId,\n order: null,\n cancelled: false,\n cancellationOutcome: null,\n ...extra,\n };\n}\n\n/** A shape with an `order_detail`: NEW_ORDER, or one of the scheduled notices. */\nfunction orderDetailEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_detail\", \"order_id\"]]);\n if (!orderId) return null;\n const action = firstString(payload, [[\"action\"]])?.toLowerCase() ?? null;\n if (action === \"scheduled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED\", payload);\n if (action === \"cancelled\") return eventOf(orderId, \"NEW_ORDER_SCHEDULED_CANCELLED\", payload);\n return eventOf(orderId, \"NEW_ORDER\", payload, { order: normalizeRappiOrder(payload, options) });\n}\n\n/** Whether `event` names a cancellation: \"cancel\" in it, case-insensitive. ESTIMATED (see the file header). */\nfunction namesCancellation(event: string): boolean {\n return event.toLowerCase().includes(\"cancel\");\n}\n\n/** A shape with a top-level `order_id`: ORDER_EVENT_CANCEL or ORDER_OTHER_EVENT (and the tracking stream). */\nfunction orderEvent(payload: unknown): NormalizedEvent | null {\n const orderId = firstString(payload, [[\"order_id\"]]);\n if (!orderId) return null;\n const event = firstString(payload, [[\"event\"]]) ?? \"UNKNOWN\";\n const other = pick(payload, \"event_time\") !== undefined || pick(payload, \"additional_information\") !== undefined;\n const cancelled = !other && namesCancellation(event);\n const eventType = cancelled ? \"ORDER_EVENT_CANCEL\" : \"ORDER_OTHER_EVENT\";\n const at = asString(pick(payload, \"event_time\"));\n return eventOf(orderId, eventType, payload, {\n eventId: [orderId, eventType, event, ...(at ? [at] : [])].join(\":\"),\n cancelled,\n cancellationOutcome: cancelled ? \"CONFIRMED\" : null,\n });\n}\n\n/**\n * Normalize one webhook delivery. Null only when it names no order (PING,\n * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.\n */\nexport function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {\n const detail = pick(payload, \"order_detail\");\n if (typeof detail === \"object\" && detail !== null) return orderDetailEvent(payload, options);\n return orderEvent(payload);\n}\n\n/** An amount as Rappi states it, in cents; null when absent or not a number. */\nfunction amountCents(value: unknown, unit: RappiAmountUnit): number | null {\n const numeric = typeof value === \"string\" && value.trim() !== \"\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isFinite(numeric)) return null;\n return Math.round(unit === \"MAJOR_UNITS\" ? numeric * 100 : numeric);\n}\n\n/** A stated count, 1 when absent or nonsense. */\nfunction countOf(source: unknown): number {\n const stated = Number(pick(source, \"quantity\") ?? 1);\n return Number.isFinite(stated) && stated > 0 ? stated : 1;\n}\n\nfunction arrayAt(source: unknown, ...path: string[]): unknown[] {\n const found = pick(source, ...path);\n return Array.isArray(found) ? found : [];\n}\n\n/**\n * One unit's price: the item's `price` (\"Unit price for the item without the\n * discount\") plus each subitem's `price × quantity`. ESTIMATED: the portal\n * does not say whether a subitem's quantity is per unit of its item or for the\n * whole line; it is read per unit (a topping on each salad of three).\n */\nfunction unitCents(item: unknown, unit: RappiAmountUnit): number {\n const base = amountCents(pick(item, \"price\"), unit) ?? 0;\n return arrayAt(item, \"subitems\").reduce<number>(\n (sum, sub) => sum + (amountCents(pick(sub, \"price\"), unit) ?? 0) * countOf(sub),\n base,\n );\n}\n\n/** The ticket's note: the subitems (a topping, a dressing) and the buyer's comments. */\nfunction lineNote(item: unknown): string | null {\n const subitems = arrayAt(item, \"subitems\")\n .map((sub) => {\n const name = asString(pick(sub, \"name\"));\n const quantity = countOf(sub);\n return name && quantity > 1 ? `${quantity}x ${name}` : name;\n })\n .filter((name): name is string => name !== null);\n // `comments` is typed an array and shown as a string in the same reference.\n const rawComments = pick(item, \"comments\");\n const comments = (Array.isArray(rawComments) ? rawComments : [rawComments])\n .map(asString)\n .filter((comment): comment is string => comment !== null);\n const note = [subitems.join(\", \"), ...comments].filter((part) => part !== \"\").join(\" · \");\n return note === \"\" ? null : note;\n}\n\n/**\n * One `order_detail.items[]` entry → its lines, which add up EXACTLY to the\n * item's total. A whole quantity is one row at the unit price (`unit × q` is\n * the total, nothing to divide); a fractional one (the portal types quantity\n * an integer, so this is defensive) is one row at its rounded total.\n *\n * The key is the item's `sku` (the store's own, \"the ally grants their own\n * SKU\"), then Rappi's `id`, then the name: an unmapped line is recoverable, a\n * dropped one is not.\n */\nfunction readLines(item: unknown, unit: RappiAmountUnit): NormalizedOrderLine[] {\n const name = firstString(item, [[\"name\"]]);\n const sku = firstString(item, [[\"sku\"], [\"id\"]]) ?? name;\n if (!sku) return [];\n const quantity = countOf(item);\n const each = unitCents(item, unit);\n const row = Number.isInteger(quantity)\n ? { quantity, unitPriceCents: each }\n : { quantity: 1, unitPriceCents: Math.round(each * quantity) };\n return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];\n}\n\n/**\n * `delivery_method`: `delivery` (Rappi's courier), `marketplace` (the store's\n * own: the portal sends the customer's data \"only when delivery method is\n * marketplace\"), `pickup`.\n */\nfunction readMethod(detail: unknown): { orderType: MarketplaceOrderType | null; deliveredBy: MarketplaceDeliveredBy | null } {\n const method = firstString(detail, [[\"delivery_method\"]])?.toLowerCase();\n if (method === \"delivery\") return { orderType: \"DELIVERY\", deliveredBy: \"MARKETPLACE\" };\n if (method === \"marketplace\") return { orderType: \"DELIVERY\", deliveredBy: \"MERCHANT\" };\n if (method === \"pickup\") return { orderType: \"TAKEOUT\", deliveredBy: null };\n return { orderType: null, deliveredBy: null };\n}\n\n/** `order_detail.delivery_information`, the Brazilian fields included (`federal_unit`). */\nfunction readAddress(detail: unknown, missingStreetNumber: string): NormalizedAddress | null {\n const raw = pick(detail, \"delivery_information\");\n const street = firstString(raw, [[\"street_name\"], [\"complete_address\"]]);\n if (street === null) return null;\n return {\n street,\n number: firstString(raw, [[\"street_number\"]]) ?? missingStreetNumber,\n neighborhood: firstString(raw, [[\"neighborhood\"]]) ?? \"\",\n complement: firstString(raw, [[\"complement\"]]),\n reference: firstString(raw, [[\"description\"]]),\n postalCode: firstString(raw, [[\"postal_code\"]])?.replace(/\\D/g, \"\") || null,\n city: firstString(raw, [[\"city\"]]),\n state: firstString(raw, [[\"federal_unit\"]]),\n };\n}\n\n/** The buyer, top-level `customer` as the example has it, or under `order_detail` as the table names it. */\nfunction readBuyer(payload: unknown): NormalizedMarketplaceOrder[\"buyer\"] {\n const customer = pick(payload, \"customer\") ?? pick(payload, \"order_detail\", \"customer\");\n const name = [firstString(customer, [[\"first_name\"]]), firstString(customer, [[\"last_name\"]])]\n .filter((part): part is string => part !== null)\n .join(\" \");\n return { externalId: null, name: name === \"\" ? null : name, phone: firstString(customer, [[\"phone_number\"]]) };\n}\n\n/**\n * Normalize one getOrders element (the NEW_ORDER body). Null when it carries\n * no order id or no line.\n *\n * The total is `totals.total_order`, \"the total amount that the restaurant\n * receives\" (with tip and delivery fee when the store delivers): the figure\n * the store's receipt is reconciled against. Rappi states no commission, so\n * `commissionCents` is null (\"did not say\"), never 0. The merchant the order\n * names is Rappi's store id (`store.internal_id`), the id every other event\n * carries as `store_id`; the engine refuses it for another connection.\n */\nexport function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null {\n const detail = pick(payload, \"order_detail\");\n const externalOrderId = firstString(detail, [[\"order_id\"]]);\n const lines = arrayAt(detail, \"items\").flatMap((item) => readLines(item, options.amountUnit));\n if (!externalOrderId || lines.length === 0) return null;\n const method = readMethod(detail);\n return {\n provider: RAPPI_PROVIDER,\n externalOrderId,\n // Rappi's order id is the number its app and courier show.\n externalDisplayId: externalOrderId,\n externalMerchantId: storeIdOf(payload),\n buyer: readBuyer(payload),\n lines,\n totalCents:\n amountCents(pick(detail, \"totals\", \"total_order\"), options.amountUnit) ??\n lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),\n commissionCents: null,\n // Rappi states no delivery promise on the order.\n deliveryDueAt: null,\n placedAt: firstDate(detail, [[\"created_at\"]]) ?? new Date(),\n orderType: method.orderType,\n deliveredBy: method.deliveredBy,\n deliveryAddress: method.orderType === \"TAKEOUT\" ? null : readAddress(detail, options.missingStreetNumber),\n };\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type CancellationRequestInput,\n type MarketplaceHttpResponse,\n type OutboundOrderRef,\n type OutboundResult,\n} from \"../core/adapter\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\n\n/**\n * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal\n * (dev-portal.rappi.com: authentication-process, api-reference/orders), read\n * 2026-11-13: the token, take and reject. The job that calls these, its\n * retries and what a failure shows are the engine's.\n *\n * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,\n * JSON `{ client_id, client_secret }`; \"the system responds with your\n * access_token\", valid \"1 week\"; sent as `x-authorization: Bearer <token>`.\n * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,\n * the cooking time optional (\"leave this field empty to keep the default\");\n * 200 taken, 400 \"Invalid state transition\", 404 not found.\n * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,\n * items_skus }`, only from SENT; 200 rejected, 400, 404.\n *\n * WHERE is not public per partner: the portal names its domains by country\n * (`{COUNTRY_DOMAIN}`, and a \"new\" one for the token), and Rappi's account\n * manager opens the sandbox. So the orders API's base and the token URL, per\n * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach\n * Rappi: the HTTP client is the host's port, answered by a fake.\n */\n\n/** One https URL per environment. */\nexport type RappiBaseUrls = Readonly<Record<\"SANDBOX\" | \"PRODUCTION\", string>>;\n\n/**\n * The two places the adapter calls, both host config (the portal's paths\n * carry the origin application's own noun, so they are the host's to state):\n * - `api`: the orders API's base, the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to\n * which the adapter appends `/orders/{orderId}/…`;\n * - `token`: the token endpoint itself, the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.\n */\nexport interface RappiHosts {\n api: RappiBaseUrls;\n token: RappiBaseUrls;\n}\n/** A token is renewed this long before it expires. */\nconst TOKEN_MARGIN_MS = 60_000;\n/**\n * The portal: \"Your access token has a validity of 1 week\". Used when the\n * answer states no `expires_in` (the answer's shape beyond `access_token` is\n * not shown: ESTIMATED).\n */\nconst DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;\n\n/** A base URL with its trailing slashes cut, by a loop: a `/\\/+$/` regex backtracks polynomially on many slashes. */\nexport function trimmed(base: string): string {\n let end = base.length;\n while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;\n return base.slice(0, end);\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** The token answer, read defensively: `access_token`, and `expires_in` when present. */\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 token from the per-process cache, or a fresh one from the token endpoint\n * (the M2M client credentials). Keyed by environment and client id; memory\n * only, written to no row or log.\n */\nexport async function bearer(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\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: hosts.token[ctx.environment],\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),\n });\n if (response.status < 200 || response.status >= 300) {\n const result = outboundResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"Rappi answered the token request 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 PUT to an order's resource: the raw answer, or the result that ends it. */\nasync function putOrder(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n request: { externalOrderId: string; action: string; body?: unknown },\n): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: \"accepted\" }>> {\n const auth = await bearer(ctx, hosts);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"PUT\",\n url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,\n headers: {\n \"x-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: \"Rappi refused the token\" };\n}\n\n/**\n * Take the order: `PUT …/orders/{orderId}/take/{cookingTime}`, the store's\n * preparation minutes as the cooking time, or `…/take/` to keep the order's\n * own (the portal: outside the order's range, Rappi uses the nearest bound).\n * The empty segment is how the portal's guide spells it\n * (`PUT /orders/{orderId}/take/`); ESTIMATED that Rappi's router serves it\n * (a 404 there would read as a refusal and show the portal link).\n * Every refused answer (400 \"Invalid state transition\", 404) is a refusal: the\n * store sees \"não confirmou\" and the app link.\n */\nexport function rappiTake(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n): Promise<OutboundResult> {\n const minutes = input.preparationMinutes === null ? \"\" : String(Math.round(input.preparationMinutes));\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n\n/**\n * Reject the order: `PUT …/orders/{orderId}/reject` with `reason` (required\n * free text: the store's, else the reason's label), `cancel_type` (one of the\n * portal's six) and `items_skus` (the offending SKUs, required by the three\n * item reasons). The answer IS the outcome: 200 rejected (the engine stamps\n * CONFIRMED), any refusal FAILED with the app link.\n *\n * `items_skus` carries the engine's SKUs, which are the store's own `sku`\n * where the order states one. A line Rappi sent with no `sku` keys on Rappi's\n * item id, which the portal wants under `items_ids` instead; it is sent under\n * `items_skus` all the same (ESTIMATED: Rappi may refuse it, which reads as a\n * refusal and puts the app link in front of a person).\n */\nexport function rappiReject(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n): Promise<OutboundResult> {\n const body = {\n reason: input.text === \"\" ? input.reason.label : input.text,\n cancel_type: input.reason.code,\n ...(input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}),\n };\n return answered(async () => {\n const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: \"reject\", body });\n return \"kind\" in response ? response : outboundResultOf(response);\n });\n}\n","import {\n answered,\n outboundResultOf,\n type AdapterCallContext,\n type OutboundResult,\n} from \"../core/adapter\";\nimport type { MarketplaceAvailability, StorePauseRequest, StorePauseResult } from \"../core/pause-port\";\nimport { RAPPI_PROVIDER } from \"./normalize\";\nimport { bearer, trimmed, type RappiHosts } from \"./outbound\";\n\n/**\n * Rappi's half of the store pause (FUT-4851): a store-wide SWITCH, from\n * Rappi's public developer portal (dev-portal.rappi.com, api-reference\n * \"availability\", read 2026-11-13):\n *\n * `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`,\n * synchronous, with `{ stores: [{ store_id, is_enabled }] }`; 200 with a\n * `results` array (`store_id`, `is_enabled`, `operation_result`,\n * `operation_result_type`, `operation_result_message`, `suspended_reason`, …),\n * 400, 403 \"not allowed to update those stores\", 422 too many stores, 502.\n *\n * A switch has no id and no end: the engine turns a store on only when its\n * own record says it turned it off, and turns it on by itself once the\n * kitchen's `until` has passed unrenewed. What it cannot tell apart is a store\n * the owner ALSO closed by hand during the kitchen's pause, which is why the\n * adapter offers this only when the host opts in (`pauseByStoreSwitch`).\n *\n * ESTIMATED: which id `store_id` is (the portal says \"the one from your\n * system\" for this call; the engine sends the connection's merchant id, the\n * store id Rappi's own events carry), and how a per-store failure reads in\n * `results` (an `operation_result` of `false`, or a `operation_result_type`\n * naming an error, is taken as a refusal with `operation_result_message`).\n */\n\ninterface RappiStoreResult {\n store_id?: unknown;\n operation_result?: unknown;\n operation_result_type?: unknown;\n operation_result_message?: unknown;\n}\n\n/** This store's entry in the answer's `results`, judged; null when the answer names it as done. */\nfunction refusalIn(body: string, storeId: string): Exclude<OutboundResult, { kind: \"accepted\" }> | null {\n let results: RappiStoreResult[];\n try {\n const parsed = JSON.parse(body === \"\" ? \"{}\" : body) as { results?: unknown };\n results = Array.isArray(parsed.results) ? (parsed.results as RappiStoreResult[]) : [];\n } catch {\n return null;\n }\n const entry = results.find((result) => String(result.store_id) === storeId);\n if (!entry) return null;\n const type = typeof entry.operation_result_type === \"string\" ? entry.operation_result_type : \"\";\n const failed = entry.operation_result === false || /error|fail/iu.test(type);\n if (!failed) return null;\n const message = typeof entry.operation_result_message === \"string\" ? entry.operation_result_message : type;\n return { kind: \"refused\", status: 200, message: message.slice(0, 300) };\n}\n\nconst tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;\n\n/** Turn the store on or off; the answer judged for THIS store. */\nexport function rappiSetStoreEnabled(\n ctx: AdapterCallContext,\n hosts: RappiHosts,\n storeId: string,\n enabled: boolean,\n): Promise<OutboundResult> {\n return answered(async () => {\n const auth = await bearer(ctx, hosts);\n if (!(\"token\" in auth)) return auth;\n const response = await ctx.http({\n method: \"PUT\",\n url: `${trimmed(hosts.api[ctx.environment])}/availability/stores/enable`,\n headers: { \"x-authorization\": `Bearer ${auth.token}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ stores: [{ store_id: storeId, is_enabled: enabled }] }),\n });\n if (response.status === 401) {\n ctx.tokens.delete(tokenKey(ctx));\n return { kind: \"retry\", reason: \"Rappi refused the token\" };\n }\n const result = outboundResultOf(response);\n if (result.kind !== \"accepted\") return result;\n return refusalIn(response.body, storeId) ?? result;\n });\n}\n\n/** Rappi's availability capability: a switch, offered only when the host opts in. */\nexport function rappiAvailability(hosts: RappiHosts): MarketplaceAvailability {\n return {\n kind: \"switch\",\n pause: async (ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> => {\n const result = await rappiSetStoreEnabled(ctx, hosts, request.merchantId, false);\n return result.kind === \"accepted\" ? { kind: \"paused\", externalId: null, until: request.until } : result;\n },\n resume: (ctx, ref) => rappiSetStoreEnabled(ctx, hosts, ref.merchantId, true),\n };\n}\n","import type { CancellationReason, MarketplaceAdapter } from \"../core/adapter\";\nimport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nimport {\n RAPPI_PROVIDER,\n RAPPI_SIGNATURE_HEADER,\n normalizeRappiEvent,\n verifyRappiSignature,\n type RappiAmountUnit,\n} from \"./normalize\";\nimport { rappiReject, rappiTake, type RappiBaseUrls } from \"./outbound\";\nimport { rappiAvailability } from \"./pause\";\n\n/**\n * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.\n *\n * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's\n * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client\n * credentials. Everything Rappi is under this folder; the engine reaches it\n * only through the {@link MarketplaceAdapter} port, and registering it is the\n * whole cost:\n *\n * ```ts\n * import { createRappiAdapter } from \"@12-apps/marketplace/rappi\";\n * import { RAPPI_ADAPTER_COPY_PT_BR } from \"@12-apps/marketplace/rappi/pt-BR\";\n *\n * createMarketplaceEngine({\n * …ports,\n * adapters: [\n * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),\n * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),\n * ],\n * });\n * ```\n *\n * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi\n * as its own subscription, all pointing at the same URL) are the engine's one\n * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.\n *\n * What Rappi CANNOT do through its public API is stated, never inferred: a\n * reject is only accepted while the order is SENT (before it is taken), and\n * there is no public endpoint to cancel a taken order. So\n * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is\n * FAILED at once and opens Rappi's portal (the app link) — and the reject's\n * answer is the outcome (`asyncCancellationOutcome: false`).\n */\n\nexport { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from \"./normalize\";\n\n/**\n * How long a reject may wait to be delivered. From the portal: an order in\n * SENT has \"a time limit of 6 minutes to take or reject the order, otherwise\n * it will transition to TIMEOUT status\", so a reject that has not reached Rappi\n * six minutes after it was asked can no longer be one. The request is failed\n * as TIMEOUT and a person finishes it on Rappi.\n *\n * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine\n * counts this window from the request. A reject asked late in Rappi's window\n * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads\n * as a refusal (FAILED, the portal link): slower than needed, never wrong.\n */\nexport const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;\n\n/** The one reason that means \"an item is unavailable\". */\nconst ITEM_UNAVAILABLE: RappiReasonCode = \"ITEM_OUT_OF_STOCK\";\n\nconst AMOUNT_UNITS: readonly RappiAmountUnit[] = [\"MINOR_UNITS\", \"MAJOR_UNITS\"];\n\nexport interface RappiAdapterConfig {\n /** The words the adapter needs: reason labels and the missing-number text. Required. */\n copy: RappiAdapterCopy;\n /**\n * The orders API's base per environment, https: the portal's\n * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its\n * samples use the `https://microservices.dev.rappi.com` domain). The adapter\n * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.\n * Required and defaultless: Rappi's account manager confirms the partner's\n * country domain.\n */\n apiBaseUrl: RappiBaseUrls;\n /**\n * The token endpoint per environment, https, whole: the portal's\n * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`\n * (\"for integrations services\"). Required and defaultless.\n */\n tokenUrl: RappiBaseUrls;\n /** Where \"open it on Rappi\" goes: the partner portal (Rappi names no per-order link). Required; https only. */\n portalUrl: string;\n /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */\n amountUnit: RappiAmountUnit;\n /**\n * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Rappi's\n * store on/off switch. A switch has no id, so the engine cannot tell its own\n * closure from one the owner made by hand meanwhile: a store the owner also\n * turned off on Rappi during the kitchen's pause is turned on with it. A\n * 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/rappi: ${name} is not a URL.`);\n }\n if (parsed.protocol !== \"https:\") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);\n}\n\nfunction assertConfig(config: RappiAdapterConfig): void {\n for (const env of [\"SANDBOX\", \"PRODUCTION\"] as const) {\n assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);\n assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);\n }\n assertHttps(\"portalUrl\", config.portalUrl);\n if (!AMOUNT_UNITS.includes(config.amountUnit)) {\n throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(\", \")}.`);\n }\n}\n\n/** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */\nexport function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {\n assertConfig(config);\n const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };\n const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({\n code,\n label: config.copy.reasonLabels[code],\n itemUnavailable: code === ITEM_UNAVAILABLE,\n needsItems: RAPPI_ITEM_REASON_CODES.includes(code),\n }));\n const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };\n return {\n provider: RAPPI_PROVIDER,\n // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,\n // replaces the store's WHOLE menu, goes to an approval, and ignores every\n // further menu while one is in approval: a per-product switch on it would\n // wipe what the store keeps on Rappi's portal and report \"in the catalogue\"\n // for a menu Rappi may have dropped. Its availability endpoints only turn\n // items Rappi already has on and off. See the README, \"Catalogue publishing\".\n capabilities: {\n apiConfirm: true,\n apiCancel: true,\n // Reject only from SENT; no public endpoint cancels a TAKEN order.\n cancelAfterAccept: false,\n // 200 is \"Order successfully rejected\": the answer is the outcome.\n asyncCancellationOutcome: false,\n perOrderAppLink: false,\n // `take/{cookingTime}`, in minutes.\n confirmTakesPreparationTime: true,\n cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,\n },\n normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),\n readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),\n verifySignature: verifyRappiSignature,\n cancellationReasons: () => reasons,\n confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),\n requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),\n appLink: () => config.portalUrl,\n ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),\n };\n}\n\nexport { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from \"./copy\";\nexport {\n normalizeRappiEvent,\n normalizeRappiOrder,\n verifyRappiSignature,\n type RappiAmountUnit,\n type RappiNormalizeOptions,\n} from \"./normalize\";\nexport type { RappiBaseUrls, RappiHosts } from \"./outbound\";\nexport { rappiAvailability, rappiSetStoreEnabled } from \"./pause\";\n"],"mappings":";;;;;;;;;;;;;;;;AAcO,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAUO,IAAM,0BAAsD,CAAC,qBAAqB,kBAAkB,kBAAkB;;;ACctH,IAAM,iBAAiB;AAGvB,IAAM,yBAAyB;AA8B/B,SAAS,qBAAqB,SAAiB,QAAuB,eAAuC;AAClH,MAAI,CAAC,iBAAiB,CAAC,OAAQ,QAAO;AACtC,QAAM,QAAQ,eAAe,MAAM;AACnC,MAAI,MAAM,MAAM,QAAQ,MAAM,SAAS,KAAM,QAAO;AACpD,SAAO,oBAAoB,GAAG,MAAM,CAAC,IAAI,OAAO,IAAI,MAAM,MAAM,aAAa;AAC/E;AALgB;AAQhB,SAAS,eAAe,QAA2D;AACjF,QAAM,QAAmD,EAAE,GAAG,MAAM,MAAM,KAAK;AAC/E,aAAW,WAAW,OAAO,MAAM,GAAG,GAAG;AACvC,UAAM,KAAK,QAAQ,QAAQ,GAAG;AAC9B,QAAI,KAAK,EAAG;AACZ,UAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,YAAY;AACpD,UAAM,QAAQ,QAAQ,MAAM,KAAK,CAAC,EAAE,KAAK;AACzC,QAAI,UAAU,GAAI;AAClB,QAAI,QAAQ,IAAK,OAAM,IAAI;AAC3B,QAAI,QAAQ,OAAQ,OAAM,OAAO;AAAA,EACnC;AACA,SAAO;AACT;AAZS;AAeT,SAAS,UAAU,SAAiC;AAClD,SAAO,YAAY,SAAS,CAAC,CAAC,SAAS,aAAa,GAAG,CAAC,gBAAgB,SAAS,aAAa,GAAG,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AY,KAAK,OAAO,OAAO,KAAK,GAA3D;AAAA,IACrB,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,kBAAkB,KAAK,EAAE,IAAI,CAAC;AAAA,EAChF;AACF;AAvCgB;","names":["tokenKey"]}
@@ -1,7 +1,7 @@
1
- import { u as DecisionProblemCode, b as BulkProblemCode, U as MarketplaceEngine, Y as MarketplaceLogger, a9 as OutboundJobPayload, F as FetchOrderJobPayload, j as CatalogueJobPayload } from '../engine-CZsP8KWd.js';
1
+ import { y as DecisionProblemCode, f as BulkProblemCode, Z as MarketplaceEngine, a1 as MarketplaceLogger, ae as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-C3uq_BJd.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-0l_EmuJA.js';
4
+ import '../adapter-CCWMqt2g.js';
5
5
 
6
6
  /** Every problem code a route can answer, decisions and bulk writes alike. */
7
7
  type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
@@ -102,7 +102,7 @@ declare const MARKETPLACE_MANAGE = "marketplace:manage";
102
102
  declare const MARKETPLACE_DECIDE = "marketplace:decide";
103
103
 
104
104
  /**
105
- * The engine's three jobs, declared here because every number in them is the
105
+ * The engine's eight jobs, declared here because every number in them is the
106
106
  * engine's knowledge, not a host's:
107
107
  *
108
108
  * - `expire-acceptances`, every minute: the unit being measured is minutes (a
@@ -124,18 +124,25 @@ declare const MARKETPLACE_DECIDE = "marketplace:decide";
124
124
  * owes (a PENDING request, an accept with no confirm stamp, a catalogue
125
125
  * publish or withdraw on its way) once it is older than the job's own retry
126
126
  * span, so a refused enqueue or a dead process loses nothing.
127
+ * - `availability`, on demand: brings one marketplace in line with the host's
128
+ * last pause or resume ask for one store (FUT-4851). Three attempts with
129
+ * backoff; the last one stamps FAILED with a failure code.
130
+ * - `availability-sweep`, every five minutes: resumes a pause past its
131
+ * `until` (the host stopped renewing it), re-queues an ask still owed, and
132
+ * gives up on one older than a day.
127
133
  *
128
134
  * What stays the host's: whether to run them at all, on which runtime, and the
129
135
  * lease implementation. A host with no worker declines `jobs` in writing.
130
136
  *
131
137
  * Bound with `{ engine }`, these arrive at a runner as
132
138
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
133
- * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`
134
- * and `marketplace.outbound-sweep`.
139
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,
140
+ * `marketplace.outbound-sweep`, `marketplace.availability` and
141
+ * `marketplace.availability-sweep`.
135
142
  */
136
143
  /** What the host closes over at bind time: the mounted engine. */
137
144
  interface MarketplaceJobDeps {
138
- engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runCatalogue" | "sweepOutbound">;
145
+ engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runCatalogue" | "sweepOutbound" | "runAvailability" | "sweepAvailability">;
139
146
  }
140
147
  /** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
141
148
  declare const MARKETPLACE_SWEEP_QUEUE = "sweeps";
@@ -143,6 +150,8 @@ declare const MARKETPLACE_SWEEP_QUEUE = "sweeps";
143
150
  declare const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;
144
151
  /** The fetch job's attempts: the last one settles the inbox row FAILED. */
145
152
  declare const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;
153
+ /** The availability job's attempts: the last one stamps FAILED. */
154
+ declare const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;
146
155
  /** The jobs contribution. */
147
156
  declare const MARKETPLACE_JOBS: {
148
157
  readonly namespace: "marketplace";
@@ -153,6 +162,8 @@ declare const MARKETPLACE_JOBS: {
153
162
  readonly "fetch-order": WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
154
163
  readonly catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
155
164
  readonly "outbound-sweep": WireJobBlueprint<void, MarketplaceJobDeps>;
165
+ readonly availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps>;
166
+ readonly "availability-sweep": WireJobBlueprint<void, MarketplaceJobDeps>;
156
167
  };
157
168
  };
158
169
 
@@ -537,4 +548,4 @@ interface ApiMarketplace {
537
548
  /** Build the route table over a mounted engine. */
538
549
  declare function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace;
539
550
 
540
- export { type ApiMarketplace, MARKETPLACE_DECIDE, MARKETPLACE_FETCH_ORDER_ATTEMPTS, MARKETPLACE_JOBS, MARKETPLACE_MANAGE, MARKETPLACE_MCP_TOOLS, MARKETPLACE_OUTBOUND_ATTEMPTS, MARKETPLACE_PERMISSIONS, MARKETPLACE_SWEEP_QUEUE, type MarketplaceActor, type MarketplaceApiConfig, type MarketplaceJobDeps, type MarketplaceProblemCode, type MarketplaceRoute, type MarketplaceServerCopy, ORDER_NOT_PENDING_CODE, createApiMarketplace, decideMarketplaceOrdersBody, listMarketplaceAcceptancesQuery, listMarketplaceIntegrationsQuery, listMarketplaceMenuLinksQuery, marketplaceParams, upsertMarketplaceIntegrationsBody, upsertMarketplaceMenuLinksBody };
551
+ export { type ApiMarketplace, MARKETPLACE_AVAILABILITY_ATTEMPTS, MARKETPLACE_DECIDE, MARKETPLACE_FETCH_ORDER_ATTEMPTS, MARKETPLACE_JOBS, MARKETPLACE_MANAGE, MARKETPLACE_MCP_TOOLS, MARKETPLACE_OUTBOUND_ATTEMPTS, MARKETPLACE_PERMISSIONS, MARKETPLACE_SWEEP_QUEUE, type MarketplaceActor, type MarketplaceApiConfig, type MarketplaceJobDeps, type MarketplaceProblemCode, type MarketplaceRoute, type MarketplaceServerCopy, ORDER_NOT_PENDING_CODE, createApiMarketplace, decideMarketplaceOrdersBody, listMarketplaceAcceptancesQuery, listMarketplaceIntegrationsQuery, listMarketplaceMenuLinksQuery, marketplaceParams, upsertMarketplaceIntegrationsBody, upsertMarketplaceMenuLinksBody };
@@ -1,11 +1,12 @@
1
1
  import {
2
+ MARKETPLACE_AVAILABILITY_ATTEMPTS,
2
3
  MARKETPLACE_FETCH_ORDER_ATTEMPTS,
3
4
  MARKETPLACE_JOBS,
4
5
  MARKETPLACE_OUTBOUND_ATTEMPTS,
5
6
  MARKETPLACE_SWEEP_QUEUE,
6
7
  ORDER_NOT_PENDING_CODE,
7
8
  createApiMarketplace
8
- } from "../chunk-AYYBRQJV.js";
9
+ } from "../chunk-UONWZIBO.js";
9
10
  import {
10
11
  MARKETPLACE_DECIDE,
11
12
  MARKETPLACE_MANAGE,
@@ -19,9 +20,10 @@ import {
19
20
  upsertMarketplaceIntegrationsBody,
20
21
  upsertMarketplaceMenuLinksBody
21
22
  } from "../chunk-UYFYGGCS.js";
22
- import "../chunk-XUAFXNOH.js";
23
+ import "../chunk-FKUEFVVA.js";
23
24
  import "../chunk-7QVYU63E.js";
24
25
  export {
26
+ MARKETPLACE_AVAILABILITY_ATTEMPTS,
25
27
  MARKETPLACE_DECIDE,
26
28
  MARKETPLACE_FETCH_ORDER_ATTEMPTS,
27
29
  MARKETPLACE_JOBS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -1,7 +1,7 @@
1
1
  // ---------------------------------------------------------------------------
2
2
  // @12-apps/marketplace — CANONICAL Prisma model partial.
3
3
  //
4
- // The six tables the marketplace engine owns. A host does NOT copy these
4
+ // The seven tables the marketplace engine owns. A host does NOT copy these
5
5
  // models by hand: it composes this file into its multi-file schema folder from
6
6
  // the `db` capability (`package.json` "wiring.db"), and discovers the
7
7
  // migrations beside it.
@@ -341,3 +341,69 @@ model MarketplaceCatalogueCategory {
341
341
  @@unique([clientId, provider, name])
342
342
  @@map("marketplace_catalogue_categories")
343
343
  }
344
+
345
+ /// One store's pause on one marketplace (FUT-4851): the engine's memory of
346
+ /// what it asked the marketplace to close, and of what it holds there.
347
+ ///
348
+ /// The owner's rule this row exists to keep: "never reopen a store the owner
349
+ /// closed by hand on the marketplace, and never close one beyond what the
350
+ /// kitchen's pause asked". The engine deletes only what it recorded here
351
+ /// (`externalId`, `retiredExternalIds`, or a closure found under `attemptKey`);
352
+ /// a closure the owner made by hand is in none of them.
353
+ ///
354
+ /// `wanted` is the host's LAST ask (PAUSED | OPEN), and the last ask wins;
355
+ /// `state` is where the marketplace stands as far as the engine knows
356
+ /// (OPEN | PAUSING | PAUSED | RESUMING | FAILED), with `failureCode` a machine
357
+ /// code and `failureDetail` the marketplace's own words. CHECKs in the
358
+ /// migration. By-value `clientId`, no foreign key, as every table here.
359
+ model MarketplaceStorePause {
360
+ id String @id @default(uuid())
361
+ clientId String @map("client_id")
362
+ provider String
363
+
364
+ state String @default("OPEN")
365
+ wanted String @default("OPEN")
366
+
367
+ /// The end the host asked for: the kitchen's estimated reopening time.
368
+ until DateTime?
369
+ /// The host's words for the closure, sent where the marketplace shows one.
370
+ reason String?
371
+ /// The store's IANA time zone, for a marketplace that reads its clock.
372
+ timeZone String? @map("time_zone")
373
+
374
+ /// The marketplace's id for the closure the engine holds (an interruption).
375
+ externalId String? @map("external_id")
376
+ /// The end the marketplace was given and took. For a switch, the only proof
377
+ /// the engine turned the store off.
378
+ sentUntil DateTime? @map("sent_until")
379
+ /// The key a create went out under, written BEFORE the call and kept while
380
+ /// its answer is in doubt.
381
+ attemptKey String? @map("attempt_key")
382
+ /// The end that create carried: how a closure the marketplace named with
383
+ /// its own id is still recognised as ours.
384
+ attemptUntil DateTime? @map("attempt_until")
385
+ /// The closures a renewal replaced, still to be deleted, oldest first, each
386
+ /// with its end (`id:<id>@<end>` or `key:<key>@<end>`, space-separated). One
387
+ /// leaves once its delete answers, its delete is refused for good, or its
388
+ /// own end passes; at most ten are kept (`src/core/pause-retired.ts`).
389
+ retiredExternalIds String? @map("retired_external_ids")
390
+
391
+ failureCode String? @map("failure_code")
392
+ failureDetail String? @map("failure_detail")
393
+
394
+ /// When the last ask was recorded: what the sweep ages it by.
395
+ requestedAt DateTime @default(now()) @map("requested_at")
396
+ /// A run's hold on the row, so two runs never call one marketplace at once.
397
+ leaseUntil DateTime? @map("lease_until")
398
+ pausedAt DateTime? @map("paused_at")
399
+ resumedAt DateTime? @map("resumed_at")
400
+ failedAt DateTime? @map("failed_at")
401
+
402
+ createdAt DateTime @default(now()) @map("created_at")
403
+ updatedAt DateTime @updatedAt @map("updated_at")
404
+
405
+ @@unique([clientId, provider])
406
+ @@index([state, requestedAt])
407
+ @@index([wanted, until])
408
+ @@map("marketplace_store_pauses")
409
+ }
@@ -0,0 +1,70 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: a store's pause on each marketplace (FUT-4851).
3
+ -- Additive and replay-safe, like the engine's earlier migrations: one new
4
+ -- table, its CHECKs and indexes. No foreign key into a host table.
5
+ --
6
+ -- One row per (store, marketplace). `wanted` is the host's last ask (PAUSED
7
+ -- or OPEN); `state` is where the marketplace stands (OPEN, PAUSING, PAUSED,
8
+ -- RESUMING, FAILED). The engine deletes on a marketplace only what a row
9
+ -- records: `external_id`, `retired_external_ids` (space-separated), or a
10
+ -- closure created under `attempt_key` (recognised by `attempt_until`).
11
+
12
+ CREATE TABLE IF NOT EXISTS "marketplace_store_pauses" (
13
+ "id" TEXT NOT NULL,
14
+ "client_id" TEXT NOT NULL,
15
+ "provider" TEXT NOT NULL,
16
+ "state" TEXT NOT NULL DEFAULT 'OPEN',
17
+ "wanted" TEXT NOT NULL DEFAULT 'OPEN',
18
+ "until" TIMESTAMP(3),
19
+ "reason" TEXT,
20
+ "time_zone" TEXT,
21
+ "external_id" TEXT,
22
+ "sent_until" TIMESTAMP(3),
23
+ "attempt_key" TEXT,
24
+ "attempt_until" TIMESTAMP(3),
25
+ "retired_external_ids" TEXT,
26
+ "failure_code" TEXT,
27
+ "failure_detail" TEXT,
28
+ "requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
29
+ "lease_until" TIMESTAMP(3),
30
+ "paused_at" TIMESTAMP(3),
31
+ "resumed_at" TIMESTAMP(3),
32
+ "failed_at" TIMESTAMP(3),
33
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
34
+ "updated_at" TIMESTAMP(3) NOT NULL,
35
+
36
+ CONSTRAINT "marketplace_store_pauses_pkey" PRIMARY KEY ("id")
37
+ );
38
+
39
+ DO $$ BEGIN
40
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_provider_shape"
41
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
42
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
43
+
44
+ DO $$ BEGIN
45
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_state_check"
46
+ CHECK ("state" IN ('OPEN', 'PAUSING', 'PAUSED', 'RESUMING', 'FAILED'));
47
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
48
+
49
+ DO $$ BEGIN
50
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_wanted_check"
51
+ CHECK ("wanted" IN ('PAUSED', 'OPEN'));
52
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
53
+
54
+ DO $$ BEGIN
55
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_failure_code_check"
56
+ CHECK ("failure_code" IS NULL OR "failure_code" IN (
57
+ 'UNSUPPORTED', 'NOT_CONNECTED', 'PAUSE_REFUSED', 'PAUSE_UNANSWERED', 'RESUME_REFUSED', 'RESUME_UNANSWERED'));
58
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
59
+
60
+ -- One pause per store and marketplace: the upsert's key.
61
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_store_pauses_client_id_provider_key"
62
+ ON "marketplace_store_pauses"("client_id", "provider");
63
+
64
+ -- The sweep: asks still owed, by age.
65
+ CREATE INDEX IF NOT EXISTS "marketplace_store_pauses_state_requested_at_idx"
66
+ ON "marketplace_store_pauses"("state", "requested_at");
67
+
68
+ -- The sweep: pauses past their end.
69
+ CREATE INDEX IF NOT EXISTS "marketplace_store_pauses_wanted_until_idx"
70
+ ON "marketplace_store_pauses"("wanted", "until");
@@ -12,6 +12,7 @@ import {
12
12
  openDeliveryRequestCancellation,
13
13
  type NinetyNineFoodApiBaseUrls,
14
14
  } from "./outbound";
15
+ import { openDeliveryAvailability } from "./pause";
15
16
 
16
17
  /**
17
18
  * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.
@@ -61,6 +62,13 @@ export interface NinetyNineFoodAdapterConfig {
61
62
  * per-order deep link, so the link is the portal. Required; https only.
62
63
  */
63
64
  portalUrl: string;
65
+ /**
66
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open
67
+ * Delivery's `merchantStatus`, a store-wide switch with no id: a store the
68
+ * owner also closed by hand on 99Food during the kitchen's pause is opened
69
+ * with it. A host turns this on knowing that.
70
+ */
71
+ pauseByStoreSwitch?: boolean;
64
72
  }
65
73
 
66
74
  function assertHttps(name: string, url: string): void {
@@ -112,6 +120,7 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
112
120
  confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
113
121
  requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
114
122
  appLink: () => config.portalUrl,
123
+ ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),
115
124
  };
116
125
  }
117
126
 
@@ -123,3 +132,4 @@ export {
123
132
  export { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from "./normalize";
124
133
  export type { NinetyNineFoodApiBaseUrls } from "./outbound";
125
134
  export { openDeliveryCatalogue, openDeliveryMenuDocument } from "./catalogue";
135
+ export { openDeliveryAvailability, openDeliverySetMerchantStatus } from "./pause";