@12-apps/marketplace 1.1.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 (75) hide show
  1. package/ADOPTING.md +9 -4
  2. package/README.md +147 -2
  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-BggtVFf9.d.ts → adapter-_iuSxvVD.d.ts} +35 -1
  13. package/dist/{chunk-7BYVGNU5.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-NGNEL4HS.js → chunk-CRYFYDQ2.js} +26 -2
  18. package/dist/chunk-CRYFYDQ2.js.map +1 -0
  19. package/dist/{chunk-DVIRN42O.js → chunk-D2X7TOR6.js} +669 -136
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-KrgZ4pA4.d.ts → engine-D-a4mttc.d.ts} +58 -2
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +7 -11
  25. package/dist/ifood/index.js +10 -60
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +56 -352
  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 +5 -1
  45. package/src/99food/copy.ts +36 -0
  46. package/src/99food/en-US.ts +19 -0
  47. package/src/99food/index.ts +121 -0
  48. package/src/99food/normalize.ts +263 -0
  49. package/src/99food/outbound.ts +220 -0
  50. package/src/99food/pt-BR.ts +23 -0
  51. package/src/core/adapter.ts +17 -1
  52. package/src/core/decisions.ts +16 -4
  53. package/src/core/engine.ts +8 -0
  54. package/src/core/fetch-order.ts +253 -0
  55. package/src/core/inbox.ts +8 -2
  56. package/src/core/ingest.ts +10 -2
  57. package/src/core/integration.ts +30 -1
  58. package/src/core/order-fetch-marks.ts +63 -0
  59. package/src/core/outbound.ts +22 -2
  60. package/src/core/payload-read.ts +101 -0
  61. package/src/core/pipeline.ts +64 -15
  62. package/src/core/types.ts +14 -0
  63. package/src/ifood/normalize.ts +15 -88
  64. package/src/index.ts +9 -1
  65. package/src/rappi/copy.ts +39 -0
  66. package/src/rappi/en-US.ts +14 -0
  67. package/src/rappi/index.ts +155 -0
  68. package/src/rappi/normalize.ts +314 -0
  69. package/src/rappi/outbound.ts +182 -0
  70. package/src/rappi/pt-BR.ts +18 -0
  71. package/src/server/index.ts +1 -0
  72. package/src/server/jobs.ts +35 -2
  73. package/dist/chunk-7BYVGNU5.js.map +0 -1
  74. package/dist/chunk-DVIRN42O.js.map +0 -1
  75. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -0,0 +1,155 @@
1
+ import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
+ import { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from "./copy";
3
+ import {
4
+ RAPPI_PROVIDER,
5
+ RAPPI_SIGNATURE_HEADER,
6
+ normalizeRappiEvent,
7
+ verifyRappiSignature,
8
+ type RappiAmountUnit,
9
+ } from "./normalize";
10
+ import { rappiReject, rappiTake, type RappiBaseUrls } from "./outbound";
11
+
12
+ /**
13
+ * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.
14
+ *
15
+ * Built from Rappi's public developer portal (dev-portal.rappi.com), owner's
16
+ * decision 2026-11-11: the NEW_ORDER webhook, take, reject and the M2M client
17
+ * credentials. Everything Rappi is under this folder; the engine reaches it
18
+ * only through the {@link MarketplaceAdapter} port, and registering it is the
19
+ * whole cost:
20
+ *
21
+ * ```ts
22
+ * import { createRappiAdapter } from "@12-apps/marketplace/rappi";
23
+ * import { RAPPI_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/rappi/pt-BR";
24
+ *
25
+ * createMarketplaceEngine({
26
+ * …ports,
27
+ * adapters: [
28
+ * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),
29
+ * createRappiAdapter({ copy: RAPPI_ADAPTER_COPY_PT_BR, apiBaseUrl, tokenUrl, portalUrl, amountUnit }),
30
+ * ],
31
+ * });
32
+ * ```
33
+ *
34
+ * Its webhooks (NEW_ORDER and ORDER_EVENT_CANCEL, each registered with Rappi
35
+ * as its own subscription, all pointing at the same URL) are the engine's one
36
+ * route, `POST /webhooks/marketplace/:tenantSlug/RAPPI`.
37
+ *
38
+ * What Rappi CANNOT do through its public API is stated, never inferred: a
39
+ * reject is only accepted while the order is SENT (before it is taken), and
40
+ * there is no public endpoint to cancel a taken order. So
41
+ * `cancelAfterAccept` is false — the store's cancel of a taken Rappi order is
42
+ * FAILED at once and opens Rappi's portal (the app link) — and the reject's
43
+ * answer is the outcome (`asyncCancellationOutcome: false`).
44
+ */
45
+
46
+ export { RAPPI_PROVIDER, RAPPI_SIGNATURE_HEADER } from "./normalize";
47
+
48
+ /**
49
+ * How long a reject may wait to be delivered. From the portal: an order in
50
+ * SENT has "a time limit of 6 minutes to take or reject the order, otherwise
51
+ * it will transition to TIMEOUT status", so a reject that has not reached Rappi
52
+ * six minutes after it was asked can no longer be one. The request is failed
53
+ * as TIMEOUT and a person finishes it on Rappi.
54
+ *
55
+ * ESTIMATED: Rappi counts its 6 minutes from the order's arrival, the engine
56
+ * counts this window from the request. A reject asked late in Rappi's window
57
+ * may still be sent after Rappi's TIMEOUT; Rappi then answers 400, which reads
58
+ * as a refusal (FAILED, the portal link): slower than needed, never wrong.
59
+ */
60
+ export const RAPPI_CANCELLATION_ANSWER_WINDOW_MS = 6 * 60_000;
61
+
62
+ /** The one reason that means "an item is unavailable". */
63
+ const ITEM_UNAVAILABLE: RappiReasonCode = "ITEM_OUT_OF_STOCK";
64
+
65
+ const AMOUNT_UNITS: readonly RappiAmountUnit[] = ["MINOR_UNITS", "MAJOR_UNITS"];
66
+
67
+ export interface RappiAdapterConfig {
68
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
69
+ copy: RappiAdapterCopy;
70
+ /**
71
+ * The orders API's base per environment, https: the portal's
72
+ * `https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api` (its
73
+ * samples use the `https://microservices.dev.rappi.com` domain). The adapter
74
+ * appends `/orders/{orderId}/take/…` and `/orders/{orderId}/reject`.
75
+ * Required and defaultless: Rappi's account manager confirms the partner's
76
+ * country domain.
77
+ */
78
+ apiBaseUrl: RappiBaseUrls;
79
+ /**
80
+ * The token endpoint per environment, https, whole: the portal's
81
+ * `https://{NEW_DOMAIN}/restaurants/auth/v1/token/login/integrations`
82
+ * ("for integrations services"). Required and defaultless.
83
+ */
84
+ tokenUrl: RappiBaseUrls;
85
+ /** Where "open it on Rappi" goes: the partner portal (Rappi names no per-order link). Required; https only. */
86
+ portalUrl: string;
87
+ /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */
88
+ amountUnit: RappiAmountUnit;
89
+ }
90
+
91
+ function assertHttps(name: string, url: string): void {
92
+ let parsed: URL;
93
+ try {
94
+ parsed = new URL(url);
95
+ } catch {
96
+ throw new Error(`@12-apps/marketplace/rappi: ${name} is not a URL.`);
97
+ }
98
+ if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/rappi: ${name} must be https.`);
99
+ }
100
+
101
+ function assertConfig(config: RappiAdapterConfig): void {
102
+ for (const env of ["SANDBOX", "PRODUCTION"] as const) {
103
+ assertHttps(`apiBaseUrl.${env}`, config.apiBaseUrl[env]);
104
+ assertHttps(`tokenUrl.${env}`, config.tokenUrl[env]);
105
+ }
106
+ assertHttps("portalUrl", config.portalUrl);
107
+ if (!AMOUNT_UNITS.includes(config.amountUnit)) {
108
+ throw new Error(`@12-apps/marketplace/rappi: amountUnit must be one of ${AMOUNT_UNITS.join(", ")}.`);
109
+ }
110
+ }
111
+
112
+ /** Build the Rappi adapter. Its reasons are static: a dialog never waits on Rappi. */
113
+ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapter {
114
+ assertConfig(config);
115
+ const hosts = { api: { ...config.apiBaseUrl }, token: { ...config.tokenUrl } };
116
+ const reasons: readonly CancellationReason[] = RAPPI_REASON_CODES.map((code) => ({
117
+ code,
118
+ label: config.copy.reasonLabels[code],
119
+ itemUnavailable: code === ITEM_UNAVAILABLE,
120
+ needsItems: RAPPI_ITEM_REASON_CODES.includes(code),
121
+ }));
122
+ const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };
123
+ return {
124
+ provider: RAPPI_PROVIDER,
125
+ capabilities: {
126
+ apiConfirm: true,
127
+ apiCancel: true,
128
+ // Reject only from SENT; no public endpoint cancels a TAKEN order.
129
+ cancelAfterAccept: false,
130
+ // 200 is "Order successfully rejected": the answer is the outcome.
131
+ asyncCancellationOutcome: false,
132
+ perOrderAppLink: false,
133
+ // `take/{cookingTime}`, in minutes.
134
+ confirmTakesPreparationTime: true,
135
+ cancellationAnswerWindowMs: RAPPI_CANCELLATION_ANSWER_WINDOW_MS,
136
+ },
137
+ normalize: (payload) => normalizeRappiEvent(payload, normalizeOptions),
138
+ readSignature: (header) => header(RAPPI_SIGNATURE_HEADER),
139
+ verifySignature: verifyRappiSignature,
140
+ cancellationReasons: () => reasons,
141
+ confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),
142
+ requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),
143
+ appLink: () => config.portalUrl,
144
+ };
145
+ }
146
+
147
+ export { RAPPI_ITEM_REASON_CODES, RAPPI_REASON_CODES, type RappiAdapterCopy, type RappiReasonCode } from "./copy";
148
+ export {
149
+ normalizeRappiEvent,
150
+ normalizeRappiOrder,
151
+ verifyRappiSignature,
152
+ type RappiAmountUnit,
153
+ type RappiNormalizeOptions,
154
+ } from "./normalize";
155
+ export type { RappiBaseUrls, RappiHosts } from "./outbound";
@@ -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,