@12-apps/marketplace 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -0,0 +1,314 @@
1
+ import { asString, firstDate, firstString, pick, verifyHmacSha256Hex } from "../core/payload-read";
2
+ import type {
3
+ MarketplaceDeliveredBy,
4
+ MarketplaceOrderType,
5
+ NormalizedAddress,
6
+ NormalizedEvent,
7
+ NormalizedMarketplaceOrder,
8
+ NormalizedOrderLine,
9
+ } from "../core/types";
10
+
11
+ /**
12
+ * The Rappi adapter's INBOUND half, from Rappi's public developer portal
13
+ * (dev-portal.rappi.com: webhook-events, api-reference/orders), read
14
+ * 2026-11-13.
15
+ *
16
+ * Rappi registers one webhook URL PER EVENT, and its payloads do not name the
17
+ * event they are. So the event is read from the body's shape, as the portal
18
+ * documents each one:
19
+ *
20
+ * - `NEW_ORDER` is "the same information that we can get from the getOrders
21
+ * endpoint": one element of `GET orders`, an `order_detail` (with `items`,
22
+ * `totals`, `delivery_information`) beside `customer` and `store`.
23
+ * - `NEW_ORDER_SCHEDULED` is that shape plus `"action": "scheduled"`, every
24
+ * price zero (the real order follows as `NEW_ORDER`); recorded, ignored.
25
+ * - `NEW_ORDER_SCHEDULED_CANCELLED` is `"action": "cancelled"` with an
26
+ * `order_detail.order_id`: an order never released to the store; ignored.
27
+ * - `ORDER_EVENT_CANCEL` is `{ event, order_id, store_id }`, `event` naming the
28
+ * cancellation (`canceled_with_charge`).
29
+ * - `ORDER_OTHER_EVENT` is `{ event, order_id, store_id, event_time,
30
+ * additional_information }`; recorded, ignored.
31
+ *
32
+ * ESTIMATED, until the Rappi sandbox confirms it: telling ORDER_EVENT_CANCEL
33
+ * from ORDER_OTHER_EVENT. The portal shows one example of each and names no
34
+ * list of `event` values, so a payload is a cancellation only when it has
35
+ * neither `event_time` nor `additional_information` AND its `event` names a
36
+ * cancellation (`cancel` in it, which `canceled_with_charge` has). Anything
37
+ * else is recorded and IGNORED: a missed cancellation is visible in the inbox,
38
+ * a false one would cancel a live order.
39
+ *
40
+ * Rappi payloads carry no event id, so the inbox key is derived from the
41
+ * order and the event, deterministic so a redelivery collides on the inbox's
42
+ * unique index.
43
+ */
44
+
45
+ /** The provider id Rappi is registered under. Uppercase: the column's CHECK holds that shape. */
46
+ export const RAPPI_PROVIDER = "RAPPI";
47
+
48
+ /** The header Rappi signs every webhook in (the portal: "Rappi-Signature"; headers are case-insensitive). */
49
+ export const RAPPI_SIGNATURE_HEADER = "rappi-signature";
50
+
51
+ /**
52
+ * How Rappi states money. The portal types every amount as an `integer` and
53
+ * names no unit (its examples are Colombian and Mexican pesos). Whether a
54
+ * Brazilian store's `price: 2890` is R$ 28,90 or R$ 2.890 is not public, so
55
+ * it is the adapter's REQUIRED config: `MINOR_UNITS` (cents) or `MAJOR_UNITS`
56
+ * (whole reais). ESTIMATED until the sandbox shows a Brazilian order.
57
+ */
58
+ export type RappiAmountUnit = "MINOR_UNITS" | "MAJOR_UNITS";
59
+
60
+ export interface RappiNormalizeOptions {
61
+ amountUnit: RappiAmountUnit;
62
+ missingStreetNumber: string;
63
+ }
64
+
65
+ /**
66
+ * Verify a delivery, as the portal's "Validating Your Signature" says:
67
+ * `Rappi-Signature: t=<timestamp>,sign=<signature>`; the signed payload is
68
+ * the timestamp, `.`, and the raw body as it arrived; HMAC-SHA256 keyed by
69
+ * the webhook's secret. The digest's encoding is not stated: the portal's
70
+ * example `sign` is 64 hex characters, so it is read as lowercase hex
71
+ * (ESTIMATED). Compared in constant time.
72
+ *
73
+ * The secret is REQUIRED: Rappi gives it when the webhook is registered, so a
74
+ * connection without one refuses every delivery (an unsigned
75
+ * ORDER_EVENT_CANCEL for a known order id would otherwise cancel it). No
76
+ * timestamp tolerance is applied: the portal states none, and a replayed
77
+ * delivery is a duplicate in the inbox.
78
+ */
79
+ export function verifyRappiSignature(rawBody: string, header: string | null, webhookSecret: string | null): boolean {
80
+ if (!webhookSecret || !header) return false;
81
+ const parts = signatureParts(header);
82
+ if (parts.t === null || parts.sign === null) return false;
83
+ return verifyHmacSha256Hex(`${parts.t}.${rawBody}`, parts.sign, webhookSecret);
84
+ }
85
+
86
+ /** `t=…,sign=…` split on "," then on the first "=", as the portal describes. No regex. */
87
+ function signatureParts(header: string): { t: string | null; sign: string | null } {
88
+ const found: { t: string | null; sign: string | null } = { t: null, sign: null };
89
+ for (const element of header.split(",")) {
90
+ const at = element.indexOf("=");
91
+ if (at < 0) continue;
92
+ const key = element.slice(0, at).trim().toLowerCase();
93
+ const value = element.slice(at + 1).trim();
94
+ if (value === "") continue;
95
+ if (key === "t") found.t = value;
96
+ if (key === "sign") found.sign = value;
97
+ }
98
+ return found;
99
+ }
100
+
101
+ /** Rappi's store id, from wherever this event shape keeps it. */
102
+ function storeIdOf(payload: unknown): string | null {
103
+ return firstString(payload, [["store", "internal_id"], ["order_detail", "store", "internal_id"], ["order_detail", "store_id"], ["store_id"]]);
104
+ }
105
+
106
+ /** One event's frame; the order is filled by the caller. */
107
+ function eventOf(
108
+ orderId: string,
109
+ eventType: string,
110
+ payload: unknown,
111
+ extra: Partial<NormalizedEvent> & { eventId?: string } = {},
112
+ ): NormalizedEvent {
113
+ return {
114
+ provider: RAPPI_PROVIDER,
115
+ eventId: `${orderId}:${eventType}`,
116
+ eventType,
117
+ externalMerchantId: storeIdOf(payload),
118
+ externalOrderId: orderId,
119
+ order: null,
120
+ cancelled: false,
121
+ cancellationOutcome: null,
122
+ ...extra,
123
+ };
124
+ }
125
+
126
+ /** A shape with an `order_detail`: NEW_ORDER, or one of the scheduled notices. */
127
+ function orderDetailEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {
128
+ const orderId = firstString(payload, [["order_detail", "order_id"]]);
129
+ if (!orderId) return null;
130
+ const action = firstString(payload, [["action"]])?.toLowerCase() ?? null;
131
+ if (action === "scheduled") return eventOf(orderId, "NEW_ORDER_SCHEDULED", payload);
132
+ if (action === "cancelled") return eventOf(orderId, "NEW_ORDER_SCHEDULED_CANCELLED", payload);
133
+ return eventOf(orderId, "NEW_ORDER", payload, { order: normalizeRappiOrder(payload, options) });
134
+ }
135
+
136
+ /** Whether `event` names a cancellation: "cancel" in it, case-insensitive. ESTIMATED (see the file header). */
137
+ function namesCancellation(event: string): boolean {
138
+ return event.toLowerCase().includes("cancel");
139
+ }
140
+
141
+ /** A shape with a top-level `order_id`: ORDER_EVENT_CANCEL or ORDER_OTHER_EVENT (and the tracking stream). */
142
+ function orderEvent(payload: unknown): NormalizedEvent | null {
143
+ const orderId = firstString(payload, [["order_id"]]);
144
+ if (!orderId) return null;
145
+ const event = firstString(payload, [["event"]]) ?? "UNKNOWN";
146
+ const other = pick(payload, "event_time") !== undefined || pick(payload, "additional_information") !== undefined;
147
+ const cancelled = !other && namesCancellation(event);
148
+ const eventType = cancelled ? "ORDER_EVENT_CANCEL" : "ORDER_OTHER_EVENT";
149
+ const at = asString(pick(payload, "event_time"));
150
+ return eventOf(orderId, eventType, payload, {
151
+ eventId: [orderId, eventType, event, ...(at ? [at] : [])].join(":"),
152
+ cancelled,
153
+ cancellationOutcome: cancelled ? "CONFIRMED" : null,
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Normalize one webhook delivery. Null only when it names no order (PING,
159
+ * MENU_*, STORE_CONNECTIVITY, STORE_PROVISIONING_STATUS): nothing to key on.
160
+ */
161
+ export function normalizeRappiEvent(payload: unknown, options: RappiNormalizeOptions): NormalizedEvent | null {
162
+ const detail = pick(payload, "order_detail");
163
+ if (typeof detail === "object" && detail !== null) return orderDetailEvent(payload, options);
164
+ return orderEvent(payload);
165
+ }
166
+
167
+ /** An amount as Rappi states it, in cents; null when absent or not a number. */
168
+ function amountCents(value: unknown, unit: RappiAmountUnit): number | null {
169
+ const numeric = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
170
+ if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
171
+ return Math.round(unit === "MAJOR_UNITS" ? numeric * 100 : numeric);
172
+ }
173
+
174
+ /** A stated count, 1 when absent or nonsense. */
175
+ function countOf(source: unknown): number {
176
+ const stated = Number(pick(source, "quantity") ?? 1);
177
+ return Number.isFinite(stated) && stated > 0 ? stated : 1;
178
+ }
179
+
180
+ function arrayAt(source: unknown, ...path: string[]): unknown[] {
181
+ const found = pick(source, ...path);
182
+ return Array.isArray(found) ? found : [];
183
+ }
184
+
185
+ /**
186
+ * One unit's price: the item's `price` ("Unit price for the item without the
187
+ * discount") plus each subitem's `price × quantity`. ESTIMATED: the portal
188
+ * does not say whether a subitem's quantity is per unit of its item or for the
189
+ * whole line; it is read per unit (a topping on each salad of three).
190
+ */
191
+ function unitCents(item: unknown, unit: RappiAmountUnit): number {
192
+ const base = amountCents(pick(item, "price"), unit) ?? 0;
193
+ return arrayAt(item, "subitems").reduce<number>(
194
+ (sum, sub) => sum + (amountCents(pick(sub, "price"), unit) ?? 0) * countOf(sub),
195
+ base,
196
+ );
197
+ }
198
+
199
+ /** The ticket's note: the subitems (a topping, a dressing) and the buyer's comments. */
200
+ function lineNote(item: unknown): string | null {
201
+ const subitems = arrayAt(item, "subitems")
202
+ .map((sub) => {
203
+ const name = asString(pick(sub, "name"));
204
+ const quantity = countOf(sub);
205
+ return name && quantity > 1 ? `${quantity}x ${name}` : name;
206
+ })
207
+ .filter((name): name is string => name !== null);
208
+ // `comments` is typed an array and shown as a string in the same reference.
209
+ const rawComments = pick(item, "comments");
210
+ const comments = (Array.isArray(rawComments) ? rawComments : [rawComments])
211
+ .map(asString)
212
+ .filter((comment): comment is string => comment !== null);
213
+ const note = [subitems.join(", "), ...comments].filter((part) => part !== "").join(" · ");
214
+ return note === "" ? null : note;
215
+ }
216
+
217
+ /**
218
+ * One `order_detail.items[]` entry → its lines, which add up EXACTLY to the
219
+ * item's total. A whole quantity is one row at the unit price (`unit × q` is
220
+ * the total, nothing to divide); a fractional one (the portal types quantity
221
+ * an integer, so this is defensive) is one row at its rounded total.
222
+ *
223
+ * The key is the item's `sku` (the store's own, "the ally grants their own
224
+ * SKU"), then Rappi's `id`, then the name: an unmapped line is recoverable, a
225
+ * dropped one is not.
226
+ */
227
+ function readLines(item: unknown, unit: RappiAmountUnit): NormalizedOrderLine[] {
228
+ const name = firstString(item, [["name"]]);
229
+ const sku = firstString(item, [["sku"], ["id"]]) ?? name;
230
+ if (!sku) return [];
231
+ const quantity = countOf(item);
232
+ const each = unitCents(item, unit);
233
+ const row = Number.isInteger(quantity)
234
+ ? { quantity, unitPriceCents: each }
235
+ : { quantity: 1, unitPriceCents: Math.round(each * quantity) };
236
+ return [{ externalSku: sku, name: name ?? sku, ...row, note: lineNote(item) }];
237
+ }
238
+
239
+ /**
240
+ * `delivery_method`: `delivery` (Rappi's courier), `marketplace` (the store's
241
+ * own: the portal sends the customer's data "only when delivery method is
242
+ * marketplace"), `pickup`.
243
+ */
244
+ function readMethod(detail: unknown): { orderType: MarketplaceOrderType | null; deliveredBy: MarketplaceDeliveredBy | null } {
245
+ const method = firstString(detail, [["delivery_method"]])?.toLowerCase();
246
+ if (method === "delivery") return { orderType: "DELIVERY", deliveredBy: "MARKETPLACE" };
247
+ if (method === "marketplace") return { orderType: "DELIVERY", deliveredBy: "MERCHANT" };
248
+ if (method === "pickup") return { orderType: "TAKEOUT", deliveredBy: null };
249
+ return { orderType: null, deliveredBy: null };
250
+ }
251
+
252
+ /** `order_detail.delivery_information`, the Brazilian fields included (`federal_unit`). */
253
+ function readAddress(detail: unknown, missingStreetNumber: string): NormalizedAddress | null {
254
+ const raw = pick(detail, "delivery_information");
255
+ const street = firstString(raw, [["street_name"], ["complete_address"]]);
256
+ if (street === null) return null;
257
+ return {
258
+ street,
259
+ number: firstString(raw, [["street_number"]]) ?? missingStreetNumber,
260
+ neighborhood: firstString(raw, [["neighborhood"]]) ?? "",
261
+ complement: firstString(raw, [["complement"]]),
262
+ reference: firstString(raw, [["description"]]),
263
+ postalCode: firstString(raw, [["postal_code"]])?.replace(/\D/g, "") || null,
264
+ city: firstString(raw, [["city"]]),
265
+ state: firstString(raw, [["federal_unit"]]),
266
+ };
267
+ }
268
+
269
+ /** The buyer, top-level `customer` as the example has it, or under `order_detail` as the table names it. */
270
+ function readBuyer(payload: unknown): NormalizedMarketplaceOrder["buyer"] {
271
+ const customer = pick(payload, "customer") ?? pick(payload, "order_detail", "customer");
272
+ const name = [firstString(customer, [["first_name"]]), firstString(customer, [["last_name"]])]
273
+ .filter((part): part is string => part !== null)
274
+ .join(" ");
275
+ return { externalId: null, name: name === "" ? null : name, phone: firstString(customer, [["phone_number"]]) };
276
+ }
277
+
278
+ /**
279
+ * Normalize one getOrders element (the NEW_ORDER body). Null when it carries
280
+ * no order id or no line.
281
+ *
282
+ * The total is `totals.total_order`, "the total amount that the restaurant
283
+ * receives" (with tip and delivery fee when the store delivers): the figure
284
+ * the store's receipt is reconciled against. Rappi states no commission, so
285
+ * `commissionCents` is null ("did not say"), never 0. The merchant the order
286
+ * names is Rappi's store id (`store.internal_id`), the id every other event
287
+ * carries as `store_id`; the engine refuses it for another connection.
288
+ */
289
+ export function normalizeRappiOrder(payload: unknown, options: RappiNormalizeOptions): NormalizedMarketplaceOrder | null {
290
+ const detail = pick(payload, "order_detail");
291
+ const externalOrderId = firstString(detail, [["order_id"]]);
292
+ const lines = arrayAt(detail, "items").flatMap((item) => readLines(item, options.amountUnit));
293
+ if (!externalOrderId || lines.length === 0) return null;
294
+ const method = readMethod(detail);
295
+ return {
296
+ provider: RAPPI_PROVIDER,
297
+ externalOrderId,
298
+ // Rappi's order id is the number its app and courier show.
299
+ externalDisplayId: externalOrderId,
300
+ externalMerchantId: storeIdOf(payload),
301
+ buyer: readBuyer(payload),
302
+ lines,
303
+ totalCents:
304
+ amountCents(pick(detail, "totals", "total_order"), options.amountUnit) ??
305
+ lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),
306
+ commissionCents: null,
307
+ // Rappi states no delivery promise on the order.
308
+ deliveryDueAt: null,
309
+ placedAt: firstDate(detail, [["created_at"]]) ?? new Date(),
310
+ orderType: method.orderType,
311
+ deliveredBy: method.deliveredBy,
312
+ deliveryAddress: method.orderType === "TAKEOUT" ? null : readAddress(detail, options.missingStreetNumber),
313
+ };
314
+ }
@@ -0,0 +1,182 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type CancellationRequestInput,
6
+ type MarketplaceHttpResponse,
7
+ type OutboundOrderRef,
8
+ type OutboundResult,
9
+ } from "../core/adapter";
10
+ import { RAPPI_PROVIDER } from "./normalize";
11
+
12
+ /**
13
+ * The Rappi adapter's OUTBOUND half, from Rappi's public developer portal
14
+ * (dev-portal.rappi.com: authentication-process, api-reference/orders), read
15
+ * 2026-11-13: the token, take and reject. The job that calls these, its
16
+ * retries and what a failure shows are the engine's.
17
+ *
18
+ * - Token: `POST https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`,
19
+ * JSON `{ client_id, client_secret }`; "the system responds with your
20
+ * access_token", valid "1 week"; sent as `x-authorization: Bearer <token>`.
21
+ * - Take: `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/orders/{orderId}/take/{cookingTime}`,
22
+ * the cooking time optional ("leave this field empty to keep the default");
23
+ * 200 taken, 400 "Invalid state transition", 404 not found.
24
+ * - Reject: `PUT …/orders/{orderId}/reject` with `{ reason, cancel_type,
25
+ * items_skus }`, only from SENT; 200 rejected, 400, 404.
26
+ *
27
+ * WHERE is not public per partner: the portal names its domains by country
28
+ * (`{COUNTRY_DOMAIN}`, and a "new" one for the token), and Rappi's account
29
+ * manager opens the sandbox. So the orders API's base and the token URL, per
30
+ * environment, are the adapter's REQUIRED config, never a guessed default. Tests never reach
31
+ * Rappi: the HTTP client is the host's port, answered by a fake.
32
+ */
33
+
34
+ /** One https URL per environment. */
35
+ export type RappiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
36
+
37
+ /**
38
+ * The two places the adapter calls, both host config (the portal's paths
39
+ * carry the origin application's own noun, so they are the host's to state):
40
+ * - `api`: the orders API's base, the portal's
41
+ * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api`, to
42
+ * which the adapter appends `/orders/{orderId}/…`;
43
+ * - `token`: the token endpoint itself, the portal's
44
+ * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`.
45
+ */
46
+ export interface RappiHosts {
47
+ api: RappiBaseUrls;
48
+ token: RappiBaseUrls;
49
+ }
50
+ /** A token is renewed this long before it expires. */
51
+ const TOKEN_MARGIN_MS = 60_000;
52
+ /**
53
+ * The portal: "Your access token has a validity of 1 week". Used when the
54
+ * answer states no `expires_in` (the answer's shape beyond `access_token` is
55
+ * not shown: ESTIMATED).
56
+ */
57
+ const DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;
58
+
59
+ /** A base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
60
+ function trimmed(base: string): string {
61
+ let end = base.length;
62
+ while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
63
+ return base.slice(0, end);
64
+ }
65
+
66
+ const tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;
67
+
68
+ /** The token answer, read defensively: `access_token`, and `expires_in` when present. */
69
+ function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
70
+ try {
71
+ const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };
72
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
73
+ const expires =
74
+ typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
75
+ return { token: parsed.access_token, expiresInSeconds: expires };
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * A token from the per-process cache, or a fresh one from the token endpoint
83
+ * (the M2M client credentials). Keyed by environment and client id; memory
84
+ * only, written to no row or log.
85
+ */
86
+ async function bearer(
87
+ ctx: AdapterCallContext,
88
+ hosts: RappiHosts,
89
+ ): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
90
+ const cached = ctx.tokens.get(tokenKey(ctx));
91
+ if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
92
+ const response = await ctx.http({
93
+ method: "POST",
94
+ url: hosts.token[ctx.environment],
95
+ headers: { "Content-Type": "application/json" },
96
+ body: JSON.stringify({ client_id: ctx.credentials.clientId, client_secret: ctx.credentials.clientSecret }),
97
+ });
98
+ if (response.status < 200 || response.status >= 300) {
99
+ const result = outboundResultOf(response);
100
+ return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
101
+ }
102
+ const token = tokenOf(response.body);
103
+ if (!token) return { kind: "retry", reason: "Rappi answered the token request without a token" };
104
+ ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
105
+ return { token: token.token };
106
+ }
107
+
108
+ /** One authenticated PUT to an order's resource: the raw answer, or the result that ends it. */
109
+ async function putOrder(
110
+ ctx: AdapterCallContext,
111
+ hosts: RappiHosts,
112
+ request: { externalOrderId: string; action: string; body?: unknown },
113
+ ): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: "accepted" }>> {
114
+ const auth = await bearer(ctx, hosts);
115
+ if (!("token" in auth)) return auth;
116
+ const response = await ctx.http({
117
+ method: "PUT",
118
+ url: `${trimmed(hosts.api[ctx.environment])}/orders/${encodeURIComponent(request.externalOrderId)}/${request.action}`,
119
+ headers: {
120
+ "x-authorization": `Bearer ${auth.token}`,
121
+ ...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
122
+ },
123
+ ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
124
+ });
125
+ // A 401 is a token that went stale under us: forget it, and the retry fetches another.
126
+ if (response.status !== 401) return response;
127
+ ctx.tokens.delete(tokenKey(ctx));
128
+ return { kind: "retry", reason: "Rappi refused the token" };
129
+ }
130
+
131
+ /**
132
+ * Take the order: `PUT …/orders/{orderId}/take/{cookingTime}`, the store's
133
+ * preparation minutes as the cooking time, or `…/take/` to keep the order's
134
+ * own (the portal: outside the order's range, Rappi uses the nearest bound).
135
+ * The empty segment is how the portal's guide spells it
136
+ * (`PUT /orders/{orderId}/take/`); ESTIMATED that Rappi's router serves it
137
+ * (a 404 there would read as a refusal and show the portal link).
138
+ * Every refused answer (400 "Invalid state transition", 404) is a refusal: the
139
+ * store sees "não confirmou" and the app link.
140
+ */
141
+ export function rappiTake(
142
+ ctx: AdapterCallContext,
143
+ hosts: RappiHosts,
144
+ order: OutboundOrderRef,
145
+ input: { preparationMinutes: number | null },
146
+ ): Promise<OutboundResult> {
147
+ const minutes = input.preparationMinutes === null ? "" : String(Math.round(input.preparationMinutes));
148
+ return answered(async () => {
149
+ const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: `take/${minutes}` });
150
+ return "kind" in response ? response : outboundResultOf(response);
151
+ });
152
+ }
153
+
154
+ /**
155
+ * Reject the order: `PUT …/orders/{orderId}/reject` with `reason` (required
156
+ * free text: the store's, else the reason's label), `cancel_type` (one of the
157
+ * portal's six) and `items_skus` (the offending SKUs, required by the three
158
+ * item reasons). The answer IS the outcome: 200 rejected (the engine stamps
159
+ * CONFIRMED), any refusal FAILED with the app link.
160
+ *
161
+ * `items_skus` carries the engine's SKUs, which are the store's own `sku`
162
+ * where the order states one. A line Rappi sent with no `sku` keys on Rappi's
163
+ * item id, which the portal wants under `items_ids` instead; it is sent under
164
+ * `items_skus` all the same (ESTIMATED: Rappi may refuse it, which reads as a
165
+ * refusal and puts the app link in front of a person).
166
+ */
167
+ export function rappiReject(
168
+ ctx: AdapterCallContext,
169
+ hosts: RappiHosts,
170
+ order: OutboundOrderRef,
171
+ input: CancellationRequestInput,
172
+ ): Promise<OutboundResult> {
173
+ const body = {
174
+ reason: input.text === "" ? input.reason.label : input.text,
175
+ cancel_type: input.reason.code,
176
+ ...(input.offendingSkus.length > 0 ? { items_skus: [...input.offendingSkus] } : {}),
177
+ };
178
+ return answered(async () => {
179
+ const response = await putOrder(ctx, hosts, { externalOrderId: order.externalOrderId, action: "reject", body });
180
+ return "kind" in response ? response : outboundResultOf(response);
181
+ });
182
+ }
@@ -0,0 +1,18 @@
1
+ import type { RappiAdapterCopy } from "./copy";
2
+
3
+ /**
4
+ * The Rappi adapter's pt-BR pack: Rappi's reject types in the words a store
5
+ * reads. A host passes this pack by hand: choosing the language is a line in
6
+ * the host's diff.
7
+ */
8
+ export const RAPPI_ADAPTER_COPY_PT_BR = {
9
+ reasonLabels: {
10
+ ITEM_OUT_OF_STOCK: "Item indisponível",
11
+ ITEM_NOT_FOUND: "Item não encontrado",
12
+ ITEM_WRONG_PRICE: "Preço do item errado",
13
+ ORDER_MISSING_INFORMATION: "Faltam informações no pedido",
14
+ ORDER_MISSING_ADDRESS_INFORMATION: "Faltam informações do endereço",
15
+ ORDER_TOTAL_INCORRECT: "Total do pedido incorreto",
16
+ },
17
+ missingStreetNumber: "s/n",
18
+ } as const satisfies RappiAdapterCopy;
@@ -36,6 +36,7 @@ export {
36
36
  MARKETPLACE_PERMISSIONS,
37
37
  } from "./contribution";
38
38
  export {
39
+ MARKETPLACE_FETCH_ORDER_ATTEMPTS,
39
40
  MARKETPLACE_JOBS,
40
41
  MARKETPLACE_OUTBOUND_ATTEMPTS,
41
42
  MARKETPLACE_SWEEP_QUEUE,
@@ -1,6 +1,7 @@
1
1
  import type { JobsContribution, WireJobBlueprint } from "@12-apps/wiring";
2
2
 
3
3
  import type { MarketplaceEngine } from "../core/engine";
4
+ import { FetchOrderRetryError, type FetchOrderJobPayload } from "../core/fetch-order";
4
5
  import { OutboundRetryError } from "../core/outbound";
5
6
  import type { OutboundJobPayload } from "../core/outbound-queue";
6
7
 
@@ -17,6 +18,9 @@ import type { OutboundJobPayload } from "../core/outbound-queue";
17
18
  * - `outbound`, on demand: one call to a marketplace, three attempts with
18
19
  * backoff. Its idempotency is the ROW's (the engine re-reads it), never the
19
20
  * queue's dedupe alone.
21
+ * - `fetch-order`, on demand: one GET of an order a marketplace's event only
22
+ * announced (`orderToFetch`), then the one ingest path. Three attempts with
23
+ * backoff; the reconciliation sweep re-queues a row still owed.
20
24
  * - `outbound-sweep`, every five minutes: re-queues every call a row still
21
25
  * owes (a PENDING request, an accept with no confirm stamp) once it is older
22
26
  * than the job's own retry span, so a refused enqueue or a dead process
@@ -27,12 +31,16 @@ import type { OutboundJobPayload } from "../core/outbound-queue";
27
31
  *
28
32
  * Bound with `{ engine }`, these arrive at a runner as
29
33
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
30
- * `marketplace.outbound` and `marketplace.outbound-sweep`.
34
+ * `marketplace.outbound`, `marketplace.fetch-order` and
35
+ * `marketplace.outbound-sweep`.
31
36
  */
32
37
 
33
38
  /** What the host closes over at bind time: the mounted engine. */
34
39
  export interface MarketplaceJobDeps {
35
- engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "sweepOutbound">;
40
+ engine: Pick<
41
+ MarketplaceEngine,
42
+ "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "sweepOutbound"
43
+ >;
36
44
  }
37
45
 
38
46
  /** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
@@ -103,6 +111,30 @@ const outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps> = {
103
111
  },
104
112
  };
105
113
 
114
+ /** The fetch job's attempts: the last one settles the inbox row FAILED. */
115
+ export const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;
116
+
117
+ const fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {
118
+ name: "fetch-order",
119
+ attempts: MARKETPLACE_FETCH_ORDER_ATTEMPTS,
120
+ // Short: an order waiting for its body is on the store's acceptance clock.
121
+ backoff: { type: "exponential", delayMs: 5_000 },
122
+ handle: async (payload, deps, context) => {
123
+ try {
124
+ const outcome = await deps.engine.runFetchOrder(payload, {
125
+ attempt: context.attempt,
126
+ maxAttempts: context.maxAttempts,
127
+ });
128
+ if (outcome.kind === "skipped") {
129
+ context.logger.info(`marketplace.fetch-order: inbox ${payload.inboxId} skipped: ${outcome.reason}`);
130
+ }
131
+ } catch (error) {
132
+ if (error instanceof FetchOrderRetryError) context.logger.warn(`marketplace.fetch-order: ${error.message}`);
133
+ throw error;
134
+ }
135
+ },
136
+ };
137
+
106
138
  const outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
107
139
  name: "outbound-sweep",
108
140
  queue: MARKETPLACE_SWEEP_QUEUE,
@@ -112,9 +144,10 @@ const outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
112
144
  lease: { ttlMs: SWEEP_LEASE_MS },
113
145
  handle: async (_payload, deps, context) => {
114
146
  const result = await deps.engine.sweepOutbound();
115
- if (result.requeued === 0 && result.givenUp === 0) return;
147
+ if (result.requeued === 0 && result.givenUp === 0 && result.timedOut === 0) return;
116
148
  context.logger.info(
117
- `marketplace.outbound-sweep: re-queued ${result.requeued} call(s), gave up on ${result.givenUp} request(s).`,
149
+ `marketplace.outbound-sweep: re-queued ${result.requeued} call(s), timed out ${result.timedOut} ` +
150
+ `cancellation request(s), gave up on ${result.givenUp}.`,
118
151
  );
119
152
  },
120
153
  };
@@ -126,6 +159,7 @@ export const MARKETPLACE_JOBS = {
126
159
  "expire-acceptances": expireAcceptances,
127
160
  "reconcile-inbox": reconcileInbox,
128
161
  outbound,
162
+ "fetch-order": fetchOrder,
129
163
  "outbound-sweep": outboundSweep,
130
164
  },
131
165
  } as const satisfies JobsContribution<MarketplaceJobDeps>;