@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,263 @@
1
+ import {
2
+ asString,
3
+ firstCents,
4
+ firstDate,
5
+ firstString,
6
+ pick,
7
+ toCents,
8
+ verifyHmacSha256Hex,
9
+ } from "../core/payload-read";
10
+ import type {
11
+ MarketplaceDeliveredBy,
12
+ MarketplaceOrderType,
13
+ NormalizedAddress,
14
+ NormalizedEvent,
15
+ NormalizedMarketplaceOrder,
16
+ NormalizedOrderLine,
17
+ } from "../core/types";
18
+
19
+ /**
20
+ * The 99Food adapter's INBOUND half, on Open Delivery v1.7.1 (Abrasel).
21
+ *
22
+ * Open Delivery splits what iFood sends at once: the webhook's `Event` names
23
+ * an order (`eventId`, `eventType`, `orderId`, `orderURL`, `createdAt`) and
24
+ * carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So
25
+ * there are two readers here: {@link normalizeOpenDeliveryEvent} for the
26
+ * webhook (a `CREATED` becomes `orderToFetch`), and
27
+ * {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.
28
+ *
29
+ * Every shape below is the spec's (`components/schemas/Event`, `Order`,
30
+ * `Price`, `Address`), and every fixture in the tests is the spec's own
31
+ * example. Read defensively all the same: a missing field produces null, and
32
+ * only a missing order id refuses an event (it is the idempotency key).
33
+ */
34
+
35
+ /** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */
36
+ export const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
37
+
38
+ /** The order exists and its body must be fetched. */
39
+ const CREATED = "CREATED";
40
+ /** The order is cancelled: the store's request was granted, or a mandatory cancellation. */
41
+ const CANCELLED = "CANCELLED";
42
+ /** The marketplace refused the store's own cancellation request. */
43
+ const CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
44
+
45
+ /**
46
+ * Verify a delivery: Open Delivery's `X-App-Signature` is "a lowercased
47
+ * hexadecimal HMAC signature of the webhook HTTP request body, using the
48
+ * client secret as a key and SHA256 as the hash function". The key is the
49
+ * merchant app's CLIENT SECRET, so a store's connection keeps that same value
50
+ * as its webhook secret.
51
+ *
52
+ * Unlike iFood (whose secret is issued after certification), the key exists
53
+ * from the moment the store connects, so an unset secret REFUSES: an unsigned
54
+ * CANCELLED for a known order id would otherwise cancel it.
55
+ */
56
+ export function verifyOpenDeliverySignature(
57
+ rawBody: string,
58
+ signature: string | null,
59
+ webhookSecret: string | null,
60
+ ): boolean {
61
+ if (!webhookSecret) return false;
62
+ return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
63
+ }
64
+
65
+ /**
66
+ * Normalize one webhook `Event`. Null only when it names no order.
67
+ *
68
+ * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
69
+ * - `CANCELLED` is a cancellation, whether the store asked for it or not.
70
+ * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
71
+ * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the
72
+ * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
73
+ * recorded, and acts on nothing: an IGNORED inbox row.
74
+ *
75
+ * The merchant is named by the `X-App-MerchantId` HEADER, not the body; the
76
+ * engine attributes a delivery by its URL's store slug, so it reads none.
77
+ */
78
+ export function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {
79
+ const externalOrderId = firstString(payload, [["orderId"]]);
80
+ if (!externalOrderId) return null;
81
+ const eventType = (firstString(payload, [["eventType"]]) ?? "UNKNOWN").toUpperCase();
82
+ const cancelled = eventType === CANCELLED;
83
+ const denied = eventType === CANCELLATION_REQUEST_DENIED;
84
+ return {
85
+ provider: NINETY_NINE_FOOD_PROVIDER,
86
+ // The spec's own event id. The fallback is deterministic so a redelivery
87
+ // still collides on the inbox's unique index.
88
+ eventId: firstString(payload, [["eventId"]]) ?? `${externalOrderId}:${eventType}`,
89
+ eventType,
90
+ externalMerchantId: null,
91
+ externalOrderId,
92
+ order: null,
93
+ orderToFetch: eventType === CREATED,
94
+ cancelled,
95
+ cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
96
+ };
97
+ }
98
+
99
+ /** A `Price` object (`{ value, currency }`) in cents. */
100
+ function priceCents(source: unknown, ...path: string[]): number | null {
101
+ return toCents(pick(source, ...path, "value"));
102
+ }
103
+
104
+ /**
105
+ * The note a kitchen reads: the chosen options (a pizza's halves are options)
106
+ * and the buyer's own instructions. The normalized line has no options of its
107
+ * own, and a flavour dropped from the ticket is food made wrong.
108
+ */
109
+ function lineNote(item: unknown, fraction: string | null): string | null {
110
+ const rawOptions = pick(item, "options");
111
+ const options = (Array.isArray(rawOptions) ? rawOptions : [])
112
+ .map((option) => {
113
+ const name = asString(pick(option, "name"));
114
+ const quantity = Number(pick(option, "quantity") ?? 1);
115
+ return name && quantity > 1 ? `${quantity}x ${name}` : name;
116
+ })
117
+ .filter((name): name is string => name !== null);
118
+ const parts = [fraction, options.join(", ") || null, firstString(item, [["specialInstructions"]])];
119
+ const note = parts.filter((part): part is string => part !== null).join(" · ");
120
+ return note === "" ? null : note;
121
+ }
122
+
123
+ /**
124
+ * What the buyer paid for the whole line, in cents. The spec's `totalPrice`
125
+ * ("quantity * (unitPrice + optionsPrice)") is the figure the order's
126
+ * `itemsPrice` is built from, and it wins whenever it is stated — its own
127
+ * example does not add up otherwise (unit 43, options 50, total 50).
128
+ *
129
+ * Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls
130
+ * `optionsPrice` "the sum of the total prices of all options of the item", a
131
+ * LINE figure, so it is added once, never multiplied by the quantity or by a
132
+ * weight.
133
+ */
134
+ function lineTotalCents(item: unknown, quantity: number): number {
135
+ const total = priceCents(item, "totalPrice");
136
+ if (total !== null) return total;
137
+ const unit = priceCents(item, "unitPrice") ?? 0;
138
+ return Math.round(unit * quantity) + (priceCents(item, "optionsPrice") ?? 0);
139
+ }
140
+
141
+ /** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */
142
+ function quantityOf(item: unknown): number {
143
+ const stated = Number(pick(item, "quantity") ?? 1);
144
+ return Number.isFinite(stated) && stated > 0 ? stated : 1;
145
+ }
146
+
147
+ /**
148
+ * Split a line total over a whole quantity so the lines add up to it EXACTLY:
149
+ * one row at `total / quantity` when it divides; otherwise `quantity - 1`
150
+ * units at the floor and one unit carrying the remainder, under the same SKU
151
+ * (R$ 10.00 over 3 is 3.33 × 2 + 3.34).
152
+ */
153
+ function splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {
154
+ const floor = Math.floor(total / quantity);
155
+ const remainder = total - floor * quantity;
156
+ if (remainder === 0) return [{ quantity, unitPriceCents: floor }];
157
+ const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];
158
+ return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];
159
+ }
160
+
161
+ /**
162
+ * One `Order.items[]` entry → its lines, which always add up to the line's
163
+ * total ({@link lineTotalCents}). A whole quantity is split by
164
+ * {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its
165
+ * total, the weight in the note.
166
+ *
167
+ * A line with no `externalCode` keys on the item id, then the name: an
168
+ * unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the
169
+ * item id is stable across orders is not pinned by the spec; if it is per
170
+ * order, each such order adds an unmapped SKU row.
171
+ */
172
+ function readLines(item: unknown): NormalizedOrderLine[] {
173
+ const name = firstString(item, [["name"]]);
174
+ const sku = firstString(item, [["externalCode"], ["id"]]) ?? name;
175
+ if (!sku) return [];
176
+ const quantity = quantityOf(item);
177
+ const whole = Number.isInteger(quantity);
178
+ const fraction = whole ? null : `${quantity} ${firstString(item, [["unit"]]) ?? ""}`.trim();
179
+ const total = lineTotalCents(item, quantity);
180
+ const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];
181
+ const note = lineNote(item, fraction);
182
+ return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));
183
+ }
184
+
185
+ /** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */
186
+ function readOrderType(order: unknown): MarketplaceOrderType | null {
187
+ const stated = firstString(order, [["type"]])?.toUpperCase();
188
+ return stated === "DELIVERY" || stated === "TAKEOUT" ? stated : null;
189
+ }
190
+
191
+ function readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {
192
+ const stated = firstString(order, [["delivery", "deliveredBy"]])?.toUpperCase();
193
+ return stated === "MERCHANT" || stated === "MARKETPLACE" ? stated : null;
194
+ }
195
+
196
+ /**
197
+ * `delivery.deliveryAddress`. The spec's schema says `street`, `number`,
198
+ * `district`; its own (commented) order example says `streetName`,
199
+ * `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by
200
+ * recommendation (`BR-SP`), so the country prefix is dropped.
201
+ */
202
+ function readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {
203
+ const raw = pick(order, "delivery", "deliveryAddress");
204
+ const street = firstString(raw, [["street"], ["streetName"]]);
205
+ if (street === null) return null;
206
+ return {
207
+ street,
208
+ number: firstString(raw, [["number"], ["streetNumber"]]) ?? missingStreetNumber,
209
+ neighborhood: firstString(raw, [["district"], ["neighborhood"]]) ?? "",
210
+ complement: firstString(raw, [["complement"]]),
211
+ reference: firstString(raw, [["reference"]]),
212
+ postalCode: firstString(raw, [["postalCode"]])?.replace(/\D/g, "") || null,
213
+ city: firstString(raw, [["city"]]),
214
+ state: firstString(raw, [["state"]])?.replace(/^[A-Z]{2}-/u, "") ?? null,
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when
220
+ * it carries no id or no line.
221
+ *
222
+ * The total is `total.orderAmount`, "the final value of the order (itemsPrice
223
+ * + otherFees - discounts)": the buyer's receipt, gross. Open Delivery's
224
+ * `Order` states NO commission field, so `commissionCents` is null ("did not
225
+ * say"), never 0; the marketplace's cut arrives with its statement.
226
+ */
227
+ export function normalizeOpenDeliveryOrder(
228
+ order: unknown,
229
+ options: { missingStreetNumber: string },
230
+ ): NormalizedMarketplaceOrder | null {
231
+ const externalOrderId = firstString(order, [["id"]]);
232
+ const rawItems = pick(order, "items");
233
+ const lines = (Array.isArray(rawItems) ? rawItems : [])
234
+ .flatMap(readLines);
235
+ if (!externalOrderId || lines.length === 0) return null;
236
+ return {
237
+ provider: NINETY_NINE_FOOD_PROVIDER,
238
+ externalOrderId,
239
+ externalDisplayId: firstString(order, [["displayId"]]),
240
+ externalMerchantId: firstString(order, [["merchant", "id"]]),
241
+ buyer: {
242
+ externalId: firstString(order, [["customer", "id"]]),
243
+ name: firstString(order, [["customer", "name"]]),
244
+ phone: firstString(order, [["customer", "phone", "number"]]),
245
+ },
246
+ lines,
247
+ // The line sum is the FALLBACK: the stated total carries the fees and
248
+ // discounts the lines do not, and it is the number on the receipt.
249
+ totalCents:
250
+ firstCents(order, [["total", "orderAmount", "value"]]) ??
251
+ lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),
252
+ commissionCents: null,
253
+ deliveryDueAt: firstDate(order, [
254
+ ["delivery", "estimatedDeliveryDateTime"],
255
+ ["takeout", "takeoutDateTime"],
256
+ ["schedule", "scheduledDateTimeEnd"],
257
+ ]),
258
+ placedAt: firstDate(order, [["createdAt"]]) ?? new Date(),
259
+ orderType: readOrderType(order),
260
+ deliveredBy: readDeliveredBy(order),
261
+ deliveryAddress: readAddress(order, options.missingStreetNumber),
262
+ };
263
+ }
@@ -0,0 +1,220 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type CancellationRequestInput,
6
+ type FetchOrderResult,
7
+ type MarketplaceHttpResponse,
8
+ type OutboundOrderRef,
9
+ type OutboundResult,
10
+ } from "../core/adapter";
11
+ import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from "./normalize";
12
+
13
+ /**
14
+ * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth
15
+ * grant, the order fetch, confirm and requestCancellation. Paths, verbs,
16
+ * bodies and answers are the spec's; the job that calls these, its retries
17
+ * and what a failure shows are the engine's.
18
+ *
19
+ * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the
20
+ * paths under each Ordering Application's own base URL, and 99Food gives its
21
+ * base URLs to a partner at onboarding. So the base URL per environment is
22
+ * the adapter's REQUIRED config, never a guessed default. Tests never reach
23
+ * 99Food: the HTTP client is the host's port, answered by a fake.
24
+ */
25
+
26
+ /** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */
27
+ export type NinetyNineFoodApiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
28
+
29
+ /** A token is renewed this long before it expires. */
30
+ const TOKEN_MARGIN_MS = 60_000;
31
+ /** `expires_in` is optional in the spec's `TokenResponse`; an hour when absent. ESTIMATED. */
32
+ const DEFAULT_TOKEN_SECONDS = 3600;
33
+
34
+ /** The base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
35
+ function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {
36
+ const base = bases[ctx.environment];
37
+ let end = base.length;
38
+ while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
39
+ return base.slice(0, end);
40
+ }
41
+ const tokenKey = (ctx: AdapterCallContext): string =>
42
+ `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;
43
+
44
+ /** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */
45
+ function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
46
+ try {
47
+ const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };
48
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
49
+ const expires =
50
+ typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
51
+ return { token: parsed.access_token, expiresInSeconds: expires };
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * A bearer token from the per-process cache, or a fresh `client_credentials`
59
+ * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,
60
+ * `grant_type`). Keyed by environment and client id; memory only.
61
+ */
62
+ async function bearer(
63
+ ctx: AdapterCallContext,
64
+ bases: NinetyNineFoodApiBaseUrls,
65
+ ): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
66
+ const cached = ctx.tokens.get(tokenKey(ctx));
67
+ if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
68
+ const response = await ctx.http({
69
+ method: "POST",
70
+ url: `${baseOf(ctx, bases)}/oauth/token`,
71
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
72
+ body: new URLSearchParams({
73
+ client_id: ctx.credentials.clientId,
74
+ client_secret: ctx.credentials.clientSecret,
75
+ grant_type: "client_credentials",
76
+ }).toString(),
77
+ });
78
+ if (response.status < 200 || response.status >= 300) {
79
+ const result = outboundResultOf(response);
80
+ return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
81
+ }
82
+ const token = tokenOf(response.body);
83
+ if (!token) return { kind: "retry", reason: "99Food answered the token grant without a token" };
84
+ ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
85
+ return { token: token.token };
86
+ }
87
+
88
+ /** One authenticated call to an order's resource, the raw answer or the result that ends it. */
89
+ async function callOrder(
90
+ ctx: AdapterCallContext,
91
+ bases: NinetyNineFoodApiBaseUrls,
92
+ request: { method: "GET" | "POST"; externalOrderId: string; action: string | null; body?: unknown },
93
+ ): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: "accepted" }>> {
94
+ const auth = await bearer(ctx, bases);
95
+ if (!("token" in auth)) return auth;
96
+ const suffix = request.action === null ? "" : `/${request.action}`;
97
+ const response = await ctx.http({
98
+ method: request.method,
99
+ url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,
100
+ headers: {
101
+ Authorization: `Bearer ${auth.token}`,
102
+ ...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
103
+ },
104
+ ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
105
+ });
106
+ // A 401 is a token that went stale under us: forget it, and the retry fetches another.
107
+ if (response.status !== 401) return response;
108
+ ctx.tokens.delete(tokenKey(ctx));
109
+ return { kind: "retry", reason: "99Food refused the token" };
110
+ }
111
+
112
+ /** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */
113
+ function alreadyCancelled(response: MarketplaceHttpResponse): boolean {
114
+ if (response.status !== 422) return false;
115
+ try {
116
+ return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === "CANCELLED";
117
+ } catch {
118
+ return false;
119
+ }
120
+ }
121
+
122
+ /** {@link answered} for a fetch: a call that never got an answer is a retry. */
123
+ async function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {
124
+ try {
125
+ return await call();
126
+ } catch (error) {
127
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
128
+ }
129
+ }
130
+
131
+ /** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */
132
+ export function openDeliveryFetchOrder(
133
+ ctx: AdapterCallContext,
134
+ bases: NinetyNineFoodApiBaseUrls,
135
+ order: { externalOrderId: string },
136
+ options: { missingStreetNumber: string },
137
+ ): Promise<FetchOrderResult> {
138
+ return fetched(async () => {
139
+ const response = await callOrder(ctx, bases, { method: "GET", externalOrderId: order.externalOrderId, action: null });
140
+ if ("kind" in response) return response;
141
+ const result = outboundResultOf(response);
142
+ if (result.kind !== "accepted") return result;
143
+ let body: unknown;
144
+ try {
145
+ body = JSON.parse(response.body);
146
+ } catch {
147
+ return { kind: "refused", status: response.status, message: "the order is not JSON" };
148
+ }
149
+ const normalized = normalizeOpenDeliveryOrder(body, options);
150
+ return normalized
151
+ ? { kind: "order", order: normalized }
152
+ : { kind: "refused", status: response.status, message: "the order carries no id or no line" };
153
+ });
154
+ }
155
+
156
+ /**
157
+ * `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:
158
+ * `orderExternalCode` (the host's own order id) and `createdAt`, plus the
159
+ * `preparationTime` in minutes when the store stated one. The spec describes
160
+ * `createdAt` with the ORDER's creation text (a copy of another schema's), so
161
+ * it is sent as the moment of the confirmation: ESTIMATED.
162
+ *
163
+ * Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`
164
+ * ("unable to process the contained instructions. (Check if the instruction
165
+ * has not been sent before.)"), and its body cannot tell a duplicate from a
166
+ * cancelled order. So a retried confirm whose first answer was lost reads
167
+ * "não confirmou" with the app link — a false alarm a person dismisses on
168
+ * 99Food — and a confirm 99Food truly refused is never stamped confirmed.
169
+ */
170
+ export function openDeliveryConfirm(
171
+ ctx: AdapterCallContext,
172
+ bases: NinetyNineFoodApiBaseUrls,
173
+ order: OutboundOrderRef,
174
+ input: { preparationMinutes: number | null },
175
+ ): Promise<OutboundResult> {
176
+ return answered(async () => {
177
+ const response = await callOrder(ctx, bases, {
178
+ method: "POST",
179
+ externalOrderId: order.externalOrderId,
180
+ action: "confirm",
181
+ body: {
182
+ orderExternalCode: order.hostOrderCode,
183
+ createdAt: ctx.now.toISOString(),
184
+ ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),
185
+ },
186
+ });
187
+ if ("kind" in response) return response;
188
+ return outboundResultOf(response);
189
+ });
190
+ }
191
+
192
+ /**
193
+ * `POST /v1/orders/{orderId}/requestCancellation` with the spec's
194
+ * `RequestCancelled`: `reason` (free text: the store's, else the label),
195
+ * `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means
196
+ * taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`
197
+ * event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is
198
+ * cancelled already, which is what the request wanted.
199
+ *
200
+ * `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,
201
+ * and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU
202
+ * map is keyed on. The field is optional.
203
+ */
204
+ export function openDeliveryRequestCancellation(
205
+ ctx: AdapterCallContext,
206
+ bases: NinetyNineFoodApiBaseUrls,
207
+ order: OutboundOrderRef,
208
+ input: CancellationRequestInput,
209
+ ): Promise<OutboundResult> {
210
+ return answered(async () => {
211
+ const response = await callOrder(ctx, bases, {
212
+ method: "POST",
213
+ externalOrderId: order.externalOrderId,
214
+ action: "requestCancellation",
215
+ body: { reason: input.text === "" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },
216
+ });
217
+ if ("kind" in response) return response;
218
+ return alreadyCancelled(response) ? { kind: "accepted" } : outboundResultOf(response);
219
+ });
220
+ }
@@ -0,0 +1,23 @@
1
+ import type { NinetyNineFoodAdapterCopy } from "./copy";
2
+
3
+ /**
4
+ * The 99Food adapter's pt-BR pack: Open Delivery's merchant cancellation codes
5
+ * in the words a store reads. A host passes this pack by hand: choosing the
6
+ * language is a line in the host's diff.
7
+ */
8
+ export const NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR = {
9
+ reasonLabels: {
10
+ SYSTEMIC_ISSUES: "Problemas de sistema",
11
+ DUPLICATE_APPLICATION: "Pedido em duplicidade",
12
+ UNAVAILABLE_ITEM: "Item indisponível",
13
+ RESTAURANT_WITHOUT_DELIVERY_PERSON: "Restaurante sem entregador",
14
+ OUTDATED_MENU: "Cardápio desatualizado",
15
+ ORDER_OUTSIDE_THE_DELIVERY_AREA: "Pedido fora da área de entrega",
16
+ BLOCKED_CUSTOMER: "Cliente bloqueado",
17
+ OUTSIDE_DELIVERY_HOURS: "Fora do horário de entrega",
18
+ INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Dificuldades internas do restaurante",
19
+ RISK_AREA: "Área de risco",
20
+ DELIVERY_PROBLEM: "Problema na entrega",
21
+ },
22
+ missingStreetNumber: "s/n",
23
+ } as const satisfies NinetyNineFoodAdapterCopy;
@@ -1,3 +1,5 @@
1
+ import { NO_STANDING_REQUEST } from "./cancellation";
2
+ import { rejectConfirmed, tellCancellationConfirmed } from "./cancellation-outcome";
1
3
  import type { EngineContext } from "./ports";
2
4
  import type { MarketplaceProvider } from "./types";
3
5
 
@@ -125,13 +127,16 @@ export async function expireLapsedAcceptances(
125
127
  ): Promise<ExpirySweepResult> {
126
128
  const db = await ctx.ports.db();
127
129
  const lapsed = (await db.marketplaceAcceptance.findMany({
128
- where: { status: "AWAITING", acknowledgeBy: { lt: now } },
130
+ // An order whose cancellation request waits is left to that request: its
131
+ // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
132
+ // never hears EXPIRED and then the confirmation for one order.
133
+ where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
129
134
  select: { id: true, clientId: true, orderId: true },
130
135
  })) as { id: string; clientId: string; orderId: string }[];
131
136
  if (lapsed.length === 0) return { expired: 0, tenants: 0 };
132
137
 
133
138
  const result = await db.marketplaceAcceptance.updateMany({
134
- where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING" },
139
+ where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
135
140
  data: { status: "EXPIRED", acknowledgedAt: now },
136
141
  });
137
142
 
@@ -158,10 +163,17 @@ export async function expireLapsedAcceptances(
158
163
  *
159
164
  * Terminal on the acceptance side whatever state it was in. A cancellation
160
165
  * request the store made is answered: CONFIRMED, from PENDING, REQUESTED or
161
- * FAILED (a refusal followed by a cancellation is still a cancellation).
162
- * Returns false when no acceptance stands for this external order — a
166
+ * FAILED (a refusal followed by a cancellation is still a cancellation), and
167
+ * the host hears it through `onCancellationConfirmed` when it has one;
168
+ * otherwise, and for a cancellation the store never asked for,
169
+ * `onRefused(…, "CANCELLED")`. Returns false when no acceptance stands for this external order — a
163
170
  * cancellation can outrun the placement it refers to.
164
171
  */
172
+ /** Whether the host takes a confirmed request through `onCancellationConfirmed` (FUT-4758). */
173
+ function hasConfirmHook(ctx: EngineContext): boolean {
174
+ return ctx.ports.order.onCancellationConfirmed !== undefined;
175
+ }
176
+
165
177
  export async function cancelAcceptance(
166
178
  ctx: EngineContext,
167
179
  input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string; now?: Date },
@@ -173,24 +185,28 @@ export async function cancelAcceptance(
173
185
  provider: input.provider,
174
186
  externalOrderId: input.externalOrderId,
175
187
  },
176
- select: { orderId: true },
177
- })) as { orderId: string } | null;
188
+ select: { orderId: true, cancellationStatus: true },
189
+ })) as { orderId: string; cancellationStatus: string | null } | null;
178
190
  if (!row) return false;
179
191
 
180
192
  // The two stamps commit together: a cancelled order never shows a request
181
193
  // still PENDING. The host's cancel runs after; if it throws, the inbox row
182
194
  // is FAILED and the retry sweep re-runs this, whose stamps are idempotent.
183
- await ctx.ports.transaction(async (tx) => {
184
- await tx.marketplaceAcceptance.updateMany({
185
- where: { orderId: row.orderId, status: { not: "REJECTED" } },
186
- data: { status: "REJECTED", acknowledgedAt: input.now ?? ctx.ports.clock.now() },
187
- });
188
- await tx.marketplaceAcceptance.updateMany({
195
+ const answered = await ctx.ports.transaction(async (tx) => {
196
+ await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());
197
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
189
198
  where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
190
- data: { cancellationStatus: "CONFIRMED" },
199
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null },
191
200
  });
201
+ return confirmed.count > 0;
192
202
  });
193
- await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
203
+ // The store's own request, answered (FUT-4758): a host that cancels on the
204
+ // confirmation hears it as such; any other cancellation is the marketplace's.
205
+ // A redelivered confirmation of a request already answered tells a host
206
+ // with the callback nothing more (it heard the first one).
207
+ const storeAsked = answered || row.cancellationStatus === "CONFIRMED";
208
+ const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));
209
+ if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
194
210
  ctx.ports.publishChanged(input.clientId);
195
211
  return true;
196
212
  }
@@ -1,4 +1,4 @@
1
- import type { MarketplaceProvider, NormalizedEvent } from "./types";
1
+ import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
2
2
 
3
3
  /**
4
4
  * The adapter port: everything one marketplace is, behind one shape.
@@ -70,6 +70,12 @@ export interface MarketplaceCapabilities {
70
70
  perOrderAppLink: boolean;
71
71
  /** Confirming states a preparation time. */
72
72
  confirmTakesPreparationTime: boolean;
73
+ /**
74
+ * OPTIONAL. How long the marketplace takes, at most, to answer a store's
75
+ * cancellation request, in milliseconds: past it the outbound sweep fails
76
+ * the request as TIMEOUT. Absent: only the 24-hour give-up applies.
77
+ */
78
+ cancellationAnswerWindowMs?: number;
73
79
  }
74
80
 
75
81
  /** One reason a store may give for refusing or cancelling an order. */
@@ -116,6 +122,15 @@ export type OutboundResult =
116
122
  /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */
117
123
  | { kind: "retry"; reason: string };
118
124
 
125
+ /**
126
+ * One order-body fetch's answer: the order, normalized, or the same refusal and
127
+ * retry shapes an outbound call answers with (a 404 for an expired order is a
128
+ * refusal; a 5xx, a timeout or a 429 is a retry).
129
+ */
130
+ export type FetchOrderResult =
131
+ | { kind: "order"; order: NormalizedMarketplaceOrder }
132
+ | Exclude<OutboundResult, { kind: "accepted" }>;
133
+
119
134
  /** What a cancellation request carries. */
120
135
  export interface CancellationRequestInput {
121
136
  reason: CancellationReason;
@@ -149,6 +164,13 @@ export interface MarketplaceAdapter {
149
164
  order: OutboundOrderRef,
150
165
  input: CancellationRequestInput,
151
166
  ): Promise<OutboundResult>;
167
+ /**
168
+ * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
169
+ * marketplace whose events carry no order body). Called only from the
170
+ * `marketplace.fetch-order` job. An adapter whose events always carry the
171
+ * order (iFood) leaves it out.
172
+ */
173
+ fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;
152
174
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
153
175
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
154
176
  }