@12-apps/marketplace 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +1 -0
- package/README.md +1 -1
- package/dist/99food/index.d.ts +1 -1
- package/dist/99food/index.js +7 -4
- package/dist/99food/index.js.map +1 -1
- package/dist/{adapter-CCWMqt2g.d.ts → adapter-DOjTak1H.d.ts} +37 -2
- package/dist/{chunk-RGMSD7S7.js → chunk-L3DCOZUU.js} +7 -1
- package/dist/chunk-L3DCOZUU.js.map +1 -0
- package/dist/{chunk-FKUEFVVA.js → chunk-SJUKBCVO.js} +34 -17
- package/dist/chunk-SJUKBCVO.js.map +1 -0
- package/dist/{chunk-UONWZIBO.js → chunk-YVUZHXUF.js} +2 -2
- package/dist/{engine-C3uq_BJd.d.ts → engine-DG1fg43Y.d.ts} +32 -7
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +1 -1
- package/dist/ifood/index.js +38 -4
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +17 -7
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +4 -3
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +3 -3
- package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql +16 -0
- package/src/99food/outbound.ts +7 -2
- package/src/core/adapter.ts +17 -2
- package/src/core/cancellation.ts +4 -1
- package/src/core/catalogue.ts +4 -3
- package/src/core/decisions.ts +3 -2
- package/src/core/fetch-order.ts +2 -2
- package/src/core/ingest.ts +32 -4
- package/src/core/order-fetch-marks.ts +13 -8
- package/src/core/outbound.ts +15 -11
- package/src/core/pipeline.ts +13 -1
- package/src/core/ports.ts +26 -4
- package/src/core/state.ts +1 -1
- package/src/core/types.ts +25 -0
- package/src/ifood/normalize.ts +53 -0
- package/src/ifood/outbound.ts +2 -1
- package/src/index.ts +3 -0
- package/src/rappi/outbound.ts +2 -1
- package/dist/chunk-FKUEFVVA.js.map +0 -1
- package/dist/chunk-RGMSD7S7.js.map +0 -1
- /package/dist/{chunk-UONWZIBO.js.map → chunk-YVUZHXUF.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { ae as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-
|
|
1
|
+
import { ae as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-DG1fg43Y.js';
|
|
2
2
|
import * as _12_apps_wiring from '@12-apps/wiring';
|
|
3
3
|
import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-DOjTak1H.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
|
|
7
7
|
declare const marketplaceServerManifest: {
|
package/dist/manifest/server.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MARKETPLACE_JOBS,
|
|
3
3
|
createApiMarketplace
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-YVUZHXUF.js";
|
|
5
5
|
import "../chunk-UYFYGGCS.js";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-SJUKBCVO.js";
|
|
7
7
|
import "../chunk-7QVYU63E.js";
|
|
8
8
|
|
|
9
9
|
// src/manifest/server.ts
|
package/dist/rappi/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-
|
|
1
|
+
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-DOjTak1H.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The words the Rappi adapter needs from its host, and nothing else.
|
package/dist/rappi/index.js
CHANGED
|
@@ -7,8 +7,9 @@ import {
|
|
|
7
7
|
} from "../chunk-BD7DS3XM.js";
|
|
8
8
|
import {
|
|
9
9
|
answered,
|
|
10
|
-
outboundResultOf
|
|
11
|
-
|
|
10
|
+
outboundResultOf,
|
|
11
|
+
tokenGrantResultOf
|
|
12
|
+
} from "../chunk-L3DCOZUU.js";
|
|
12
13
|
import {
|
|
13
14
|
__name
|
|
14
15
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -233,7 +234,7 @@ async function bearer(ctx, hosts) {
|
|
|
233
234
|
body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret })
|
|
234
235
|
});
|
|
235
236
|
if (response.status < 200 || response.status >= 300) {
|
|
236
|
-
const result =
|
|
237
|
+
const result = tokenGrantResultOf(response);
|
|
237
238
|
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
|
|
238
239
|
}
|
|
239
240
|
const token = tokenOf(response.body);
|
package/dist/rappi/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/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,E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ACjF,eAAa,MAAM;AACnB,QAAM,QAAQ,EAAE,KAAK,EAAE,GAAG,OAAO,WAAW,GAAG,OAAO,EAAE,GAAG,OAAO,SAAS,EAAE;AAC7E,QAAM,UAAyC,mBAAmB,IAAI,CAAC,UAAU;AAAA,IAC/E;AAAA,IACA,OAAO,OAAO,KAAK,aAAa,IAAI;AAAA,IACpC,iBAAiB,SAAS;AAAA,IAC1B,YAAY,wBAAwB,SAAS,IAAI;AAAA,EACnD,EAAE;AACF,QAAM,mBAAmB,EAAE,YAAY,OAAO,YAAY,qBAAqB,OAAO,KAAK,oBAAoB;AAC/G,SAAO;AAAA,IACL,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOV,cAAc;AAAA,MACZ,YAAY;AAAA,MACZ,WAAW;AAAA;AAAA,MAEX,mBAAmB;AAAA;AAAA,MAEnB,0BAA0B;AAAA,MAC1B,iBAAiB;AAAA;AAAA,MAEjB,6BAA6B;AAAA,MAC7B,4BAA4B;AAAA,IAC9B;AAAA,IACA,WAAW,wBAAC,YAAY,oBAAoB,SAAS,gBAAgB,GAA1D;AAAA,IACX,eAAe,wBAAC,WAAW,OAAO,sBAAsB,GAAzC;AAAA,IACf,iBAAiB;AAAA,IACjB,qBAAqB,6BAAM,SAAN;AAAA,IACrB,SAAS,wBAAC,KAAK,OAAO,UAAU,UAAU,KAAK,OAAO,OAAO,KAAK,GAAzD;AAAA,IACT,qBAAqB,wBAAC,KAAK,OAAO,UAAU,YAAY,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
|
+
{"version":3,"sources":["../../src/rappi/copy.ts","../../src/rappi/normalize.ts","../../src/rappi/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 tokenGrantResultOf,\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 = tokenGrantResultOf(response);\n return result.kind === \"accepted\" ? { kind: \"retry\", reason: \"unexpected token answer\" } : result;\n }\n const token = tokenOf(response.body);\n if (!token) return { kind: \"retry\", reason: \"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,CAAC,gBAAgB,UAAU,GAAG,CAA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AA3D;AAAA,IACrB,SAAS,6BAAM,OAAO,WAAb;AAAA,IACT,GAAI,OAAO,qBAAqB,EAAE,cAAc,kBAAkB,KAAK,EAAE,IAAI,CAAC;AAAA,EAChF;AACF;AAvCgB;","names":["tokenKey"]}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-
|
|
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-DG1fg43Y.js';
|
|
2
2
|
import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-DOjTak1H.js';
|
|
5
5
|
|
|
6
6
|
/** Every problem code a route can answer, decisions and bulk writes alike. */
|
|
7
7
|
type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
|
package/dist/server/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
MARKETPLACE_SWEEP_QUEUE,
|
|
7
7
|
ORDER_NOT_PENDING_CODE,
|
|
8
8
|
createApiMarketplace
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-YVUZHXUF.js";
|
|
10
10
|
import {
|
|
11
11
|
MARKETPLACE_DECIDE,
|
|
12
12
|
MARKETPLACE_MANAGE,
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
upsertMarketplaceIntegrationsBody,
|
|
21
21
|
upsertMarketplaceMenuLinksBody
|
|
22
22
|
} from "../chunk-UYFYGGCS.js";
|
|
23
|
-
import "../chunk-
|
|
23
|
+
import "../chunk-SJUKBCVO.js";
|
|
24
24
|
import "../chunk-7QVYU63E.js";
|
|
25
25
|
export {
|
|
26
26
|
MARKETPLACE_AVAILABILITY_ATTEMPTS,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/marketplace",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.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.",
|
|
@@ -228,9 +228,9 @@ model MarketplaceAcceptance {
|
|
|
228
228
|
/// With a NULL status it is a TOMBSTONE: the request an accept cleared,
|
|
229
229
|
/// which a synchronous marketplace's late "cancelled" can still match.
|
|
230
230
|
cancellationRequestedAt DateTime? @map("cancellation_requested_at")
|
|
231
|
-
/// Why the request FAILED: REFUSED (the marketplace
|
|
232
|
-
///
|
|
233
|
-
///
|
|
231
|
+
/// Why the request FAILED: REFUSED (the marketplace denied it), UNREACHABLE
|
|
232
|
+
/// (our own request never got a judgement) or TIMEOUT (no answer inside its
|
|
233
|
+
/// window). CHECK in the migrations; NULL unless `cancellationStatus` is FAILED.
|
|
234
234
|
cancellationFailureReason String? @map("cancellation_failure_reason")
|
|
235
235
|
/// The preparation time the accept stated, for a confirm that takes one.
|
|
236
236
|
preparationMinutes Int? @map("preparation_minutes")
|
package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
-- @domains: marketplace
|
|
2
|
+
-- @12-apps/marketplace: a third reason a store's cancellation request FAILED
|
|
3
|
+
-- (FUT-4917). UNREACHABLE is "our own request never got a judgement" (no
|
|
4
|
+
-- credentials, a token not granted, a malformed request, retries that ran
|
|
5
|
+
-- out); REFUSED stays "the marketplace denied it" and TIMEOUT "no answer in
|
|
6
|
+
-- its window".
|
|
7
|
+
--
|
|
8
|
+
-- Widening a CHECK only accepts more, so the previous release, which never
|
|
9
|
+
-- writes the new value, keeps working against the new constraint. Replay-safe:
|
|
10
|
+
-- the drop is IF EXISTS and the add follows it.
|
|
11
|
+
|
|
12
|
+
ALTER TABLE "marketplace_acceptances" DROP CONSTRAINT IF EXISTS "marketplace_acceptances_cancellation_failure_reason_check";
|
|
13
|
+
|
|
14
|
+
ALTER TABLE "marketplace_acceptances" ADD CONSTRAINT "marketplace_acceptances_cancellation_failure_reason_check"
|
|
15
|
+
CHECK ("cancellation_failure_reason" IS NULL
|
|
16
|
+
OR "cancellation_failure_reason" IN ('REFUSED', 'UNREACHABLE', 'TIMEOUT'));
|
package/src/99food/outbound.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
answered,
|
|
3
3
|
outboundResultOf,
|
|
4
|
+
tokenGrantResultOf,
|
|
4
5
|
type AdapterCallContext,
|
|
5
6
|
type CancellationRequestInput,
|
|
6
7
|
type FetchOrderResult,
|
|
@@ -76,7 +77,7 @@ export async function bearer(
|
|
|
76
77
|
}).toString(),
|
|
77
78
|
});
|
|
78
79
|
if (response.status < 200 || response.status >= 300) {
|
|
79
|
-
const result =
|
|
80
|
+
const result = tokenGrantResultOf(response);
|
|
80
81
|
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
|
|
81
82
|
}
|
|
82
83
|
const token = tokenOf(response.body);
|
|
@@ -215,6 +216,10 @@ export function openDeliveryRequestCancellation(
|
|
|
215
216
|
body: { reason: input.text === "" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },
|
|
216
217
|
});
|
|
217
218
|
if ("kind" in response) return response;
|
|
218
|
-
|
|
219
|
+
if (alreadyCancelled(response)) return { kind: "accepted" };
|
|
220
|
+
const result = outboundResultOf(response);
|
|
221
|
+
// Open Delivery's 400 is a malformed request (a bad id or body: ours);
|
|
222
|
+
// its 422 is the business answer and stays a refusal.
|
|
223
|
+
return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
|
|
219
224
|
});
|
|
220
225
|
}
|
package/src/core/adapter.ts
CHANGED
|
@@ -124,8 +124,13 @@ export interface AdapterCallContext {
|
|
|
124
124
|
export type OutboundResult =
|
|
125
125
|
/** 2xx. For a marketplace whose outcome is asynchronous, "the request was taken". */
|
|
126
126
|
| { kind: "accepted" }
|
|
127
|
-
/**
|
|
128
|
-
|
|
127
|
+
/**
|
|
128
|
+
* A final 4xx (not 408/425/429): never retried. `own` marks a refusal that
|
|
129
|
+
* is not the marketplace's judgement of the order: our credentials were not
|
|
130
|
+
* accepted, or our request was malformed. A cancellation request that ends
|
|
131
|
+
* so fails as UNREACHABLE, not REFUSED.
|
|
132
|
+
*/
|
|
133
|
+
| { kind: "refused"; status: number; message: string; own?: true }
|
|
129
134
|
/** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */
|
|
130
135
|
| { kind: "retry"; reason: string };
|
|
131
136
|
|
|
@@ -222,6 +227,16 @@ export function outboundResultOf(response: MarketplaceHttpResponse): OutboundRes
|
|
|
222
227
|
return { kind: "retry", reason: `status ${response.status}: ${message}` };
|
|
223
228
|
}
|
|
224
229
|
|
|
230
|
+
/**
|
|
231
|
+
* {@link outboundResultOf} for a token grant: a final 4xx there says our
|
|
232
|
+
* credentials were not accepted, never a judgement of any order, so it is an
|
|
233
|
+
* `own` refusal.
|
|
234
|
+
*/
|
|
235
|
+
export function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {
|
|
236
|
+
const result = outboundResultOf(response);
|
|
237
|
+
return result.kind === "refused" ? { ...result, own: true } : result;
|
|
238
|
+
}
|
|
239
|
+
|
|
225
240
|
/** A call that never got an answer is a retry, with the reason a log can read. */
|
|
226
241
|
export async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {
|
|
227
242
|
try {
|
package/src/core/cancellation.ts
CHANGED
|
@@ -160,6 +160,7 @@ export function refusalData(plan: CancellationPlan, fromStatus: string, now: Dat
|
|
|
160
160
|
cancellationReasonCode: plan.reason?.code ?? null,
|
|
161
161
|
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
162
162
|
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
163
|
+
// FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
|
|
163
164
|
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
|
|
164
165
|
};
|
|
165
166
|
}
|
|
@@ -177,12 +178,14 @@ export function requestData(plan: CancellationPlan, now: Date): Record<string, u
|
|
|
177
178
|
cancellationReasonCode: plan.reason?.code ?? null,
|
|
178
179
|
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
179
180
|
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
181
|
+
// FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
|
|
180
182
|
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
|
|
181
183
|
};
|
|
182
184
|
}
|
|
183
185
|
|
|
184
186
|
/**
|
|
185
|
-
* The marketplace refused the store's cancellation request
|
|
187
|
+
* The marketplace refused the store's cancellation request: its denial event.
|
|
188
|
+
* FAILED (REFUSED),
|
|
186
189
|
* from PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving
|
|
187
190
|
* after the cancellation changes nothing. The host hears it once, from the
|
|
188
191
|
* call that moved the row. Returns whether a row moved.
|
package/src/core/catalogue.ts
CHANGED
|
@@ -207,8 +207,9 @@ export async function readCatalogueDocument(
|
|
|
207
207
|
const catalogue = ctx.registry.get(input.provider)?.catalogue;
|
|
208
208
|
const table = await usableTable(ctx, input.provider);
|
|
209
209
|
if (!table || catalogue?.mode !== "pull") return { kind: "refused", code: "UNSUPPORTED" };
|
|
210
|
-
|
|
211
|
-
|
|
210
|
+
// The document needs only the merchant id: no credentials are opened to serve it.
|
|
211
|
+
const externalMerchantId = await connectionMerchantId(ctx, input.clientId, input.provider);
|
|
212
|
+
if (externalMerchantId === null) return { kind: "refused", code: "NOT_CONNECTED" };
|
|
212
213
|
const rows = (await table.findMany({
|
|
213
214
|
where: { clientId: input.clientId, provider: input.provider, status: { in: IN_MENU } },
|
|
214
215
|
select: CATALOGUE_ROW_SELECT,
|
|
@@ -221,6 +222,6 @@ export async function readCatalogueDocument(
|
|
|
221
222
|
if (!item || priceCents === null) return [];
|
|
222
223
|
return [{ ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage: null }];
|
|
223
224
|
});
|
|
224
|
-
const document = catalogue.menuDocument({ externalMerchantId
|
|
225
|
+
const document = catalogue.menuDocument({ externalMerchantId, entries, options: input.options });
|
|
225
226
|
return { kind: "document", document };
|
|
226
227
|
}
|
package/src/core/decisions.ts
CHANGED
|
@@ -237,8 +237,9 @@ async function afterCommit(ctx: EngineContext, clientId: string, planned: readon
|
|
|
237
237
|
try {
|
|
238
238
|
if (one.decided.status === "ACCEPTED" && one.input.decision === "ACCEPT") await ctx.ports.order.onAccepted(clientId, orderId);
|
|
239
239
|
else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
|
|
240
|
-
// A request the marketplace cannot take through its API failed at once
|
|
241
|
-
// the order stays, and a person cancels it in
|
|
240
|
+
// A request the marketplace cannot take through its API failed at once
|
|
241
|
+
// (REFUSED: its own limit): the order stays, and a person cancels it in
|
|
242
|
+
// the marketplace's app.
|
|
242
243
|
else if (one.decided.cancellation === "FAILED") await tellCancellationFailed(ctx, clientId, orderId, "REFUSED");
|
|
243
244
|
} catch (error) {
|
|
244
245
|
ctx.ports.logger.error(
|
package/src/core/fetch-order.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ingestMarketplaceOrder } from "./ingest";
|
|
|
3
3
|
import { readOutboundConnection, resolveIngestionTarget } from "./integration";
|
|
4
4
|
import type { FetchOrderResult } from "./adapter";
|
|
5
5
|
import { cancelAcceptance } from "./acceptance";
|
|
6
|
-
import { cancelledBeforeIngest } from "./order-fetch-marks";
|
|
6
|
+
import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest } from "./order-fetch-marks";
|
|
7
7
|
import type { EngineContext } from "./ports";
|
|
8
8
|
import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
9
9
|
|
|
@@ -171,7 +171,7 @@ async function refusalOf(
|
|
|
171
171
|
connectionMerchantId: string | null,
|
|
172
172
|
): Promise<{ settle: "IGNORED" | "FAILED"; reason: string; failed: boolean } | null> {
|
|
173
173
|
if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
|
|
174
|
-
return { settle: "IGNORED", reason:
|
|
174
|
+
return { settle: "IGNORED", reason: CANCELLED_BEFORE_INGEST_REASON, failed: false };
|
|
175
175
|
}
|
|
176
176
|
const mismatch = merchantMismatch(order, connectionMerchantId);
|
|
177
177
|
// FAILED, not IGNORED: a connection whose merchant id was entered wrong is
|
package/src/core/ingest.ts
CHANGED
|
@@ -30,7 +30,10 @@ export interface IngestResult {
|
|
|
30
30
|
created: boolean;
|
|
31
31
|
/** SKUs that arrived with nothing behind them, in this order. */
|
|
32
32
|
unmappedSkus: string[];
|
|
33
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Whether this order was born accepted: the connection auto-accepts AND the
|
|
35
|
+
* host's `mayAutoAccept`, when bound, allowed it.
|
|
36
|
+
*/
|
|
34
37
|
autoAccepted: boolean;
|
|
35
38
|
}
|
|
36
39
|
|
|
@@ -79,10 +82,10 @@ function acceptanceData(
|
|
|
79
82
|
orderId: string,
|
|
80
83
|
order: NormalizedMarketplaceOrder,
|
|
81
84
|
settings: IngestSettings,
|
|
85
|
+
accepted: boolean,
|
|
82
86
|
now: Date,
|
|
83
87
|
clockStartsAt: Date,
|
|
84
88
|
): Record<string, unknown> {
|
|
85
|
-
const accepted = settings.autoAccept;
|
|
86
89
|
return {
|
|
87
90
|
clientId,
|
|
88
91
|
orderId,
|
|
@@ -101,6 +104,31 @@ function acceptanceData(
|
|
|
101
104
|
};
|
|
102
105
|
}
|
|
103
106
|
|
|
107
|
+
/**
|
|
108
|
+
* The host's say on an automatic acceptance (`order.mayAutoAccept`), asked
|
|
109
|
+
* only when the connection auto-accepts. Absent, it allows. A declined
|
|
110
|
+
* auto-accept is never a refused order: the order lands on the clock and a
|
|
111
|
+
* person decides it — so a host half that throws declines rather than failing
|
|
112
|
+
* the ingest, which would hold a paid order back until the sweep.
|
|
113
|
+
*/
|
|
114
|
+
async function hostAllowsAutoAccept(
|
|
115
|
+
ctx: EngineContext,
|
|
116
|
+
clientId: string,
|
|
117
|
+
order: NormalizedMarketplaceOrder,
|
|
118
|
+
): Promise<boolean> {
|
|
119
|
+
const ask = ctx.ports.order.mayAutoAccept;
|
|
120
|
+
if (!ask) return true;
|
|
121
|
+
try {
|
|
122
|
+
return await ask.call(ctx.ports.order, clientId);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
ctx.ports.logger.warn(
|
|
125
|
+
`marketplace: mayAutoAccept threw for ${order.provider} order ${order.externalOrderId}; it lands awaiting a decision`,
|
|
126
|
+
error,
|
|
127
|
+
);
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
104
132
|
/**
|
|
105
133
|
* Ingest one order.
|
|
106
134
|
*
|
|
@@ -147,7 +175,7 @@ export async function ingestMarketplaceOrder(
|
|
|
147
175
|
return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };
|
|
148
176
|
}
|
|
149
177
|
|
|
150
|
-
const accepted = settings.autoAccept;
|
|
178
|
+
const accepted = settings.autoAccept && (await hostAllowsAutoAccept(ctx, clientId, order));
|
|
151
179
|
// ONE transaction for the host's order, the SKU rows, the acceptance row and
|
|
152
180
|
// the liveness stamp: the host's `create` is handed the transaction's client,
|
|
153
181
|
// so an acceptance that cannot be written (a concurrent ingest won the
|
|
@@ -156,7 +184,7 @@ export async function ingestMarketplaceOrder(
|
|
|
156
184
|
const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
|
|
157
185
|
const lines = await composeLines(tx, clientId, order, now);
|
|
158
186
|
const created = await ctx.ports.order.create(clientId, order, lines, tx);
|
|
159
|
-
await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
|
|
187
|
+
await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, accepted, now, clockStartsAt) });
|
|
160
188
|
await markMarketplaceEventSeen(tx, clientId, order.provider, now);
|
|
161
189
|
return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
|
|
162
190
|
});
|