@12-apps/marketplace 1.8.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +27 -1
- package/README.md +103 -9
- package/dist/99food/index.d.ts +30 -54
- package/dist/99food/index.js +60 -418
- package/dist/99food/index.js.map +1 -1
- package/dist/{chunk-BMCERPQX.js → chunk-2BA2EHNF.js} +16 -6
- package/dist/chunk-2BA2EHNF.js.map +1 -0
- package/dist/chunk-PYHNM47K.js +478 -0
- package/dist/chunk-PYHNM47K.js.map +1 -0
- package/dist/{chunk-6N2HEV3U.js → chunk-WVZ2IXFH.js} +3 -3
- package/dist/{chunk-NP4EYKPO.js → chunk-ZO4S3LF4.js} +5 -3
- package/dist/chunk-ZO4S3LF4.js.map +1 -0
- package/dist/client-B4EQCRD_.d.ts +20 -0
- package/dist/{engine-wmW-VuBL.d.ts → engine-DK3iV_Kk.d.ts} +91 -60
- package/dist/hono/index.d.ts +1 -1
- package/dist/hono/index.js +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +17 -6
- package/dist/index.js.map +1 -1
- package/dist/keeta/en-US.d.ts +19 -0
- package/dist/keeta/en-US.js +23 -0
- package/dist/keeta/en-US.js.map +1 -0
- package/dist/keeta/index.d.ts +253 -0
- package/dist/keeta/index.js +388 -0
- package/dist/keeta/index.js.map +1 -0
- package/dist/keeta/pt-BR.d.ts +23 -0
- package/dist/keeta/pt-BR.js +23 -0
- package/dist/keeta/pt-BR.js.map +1 -0
- package/dist/manifest/index.d.ts +4 -1
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +1 -1
- package/dist/manifest/server.js +3 -3
- package/dist/server/index.d.ts +6 -2
- package/dist/server/index.js +3 -3
- package/package.json +14 -2
- package/prisma/marketplace.prisma +6 -0
- package/prisma/migrations/20261126230000_marketplace_menu_link_variation/migration.sql +11 -0
- package/src/99food/catalogue.ts +19 -89
- package/src/99food/copy.ts +4 -19
- package/src/99food/index.ts +28 -33
- package/src/99food/normalize.ts +11 -253
- package/src/99food/outbound.ts +29 -270
- package/src/99food/pause.ts +7 -22
- package/src/core/bulk.ts +34 -7
- package/src/core/ingest.ts +2 -1
- package/src/core/menu-links.ts +36 -6
- package/src/core/order-types.ts +74 -0
- package/src/core/ports.ts +23 -65
- package/src/index.ts +2 -1
- package/src/keeta/authorization.ts +226 -0
- package/src/keeta/copy.ts +27 -0
- package/src/keeta/en-US.ts +19 -0
- package/src/keeta/index.ts +162 -0
- package/src/keeta/merchant.ts +70 -0
- package/src/keeta/normalize.ts +131 -0
- package/src/keeta/outbound.ts +55 -0
- package/src/keeta/pt-BR.ts +23 -0
- package/src/keeta/signature.ts +85 -0
- package/src/open-delivery/client.ts +185 -0
- package/src/open-delivery/merchant.ts +126 -0
- package/src/open-delivery/normalize.ts +269 -0
- package/src/open-delivery/orders.ts +241 -0
- package/src/open-delivery/reasons.ts +26 -0
- package/src/server/mcp.ts +7 -2
- package/dist/chunk-BMCERPQX.js.map +0 -1
- package/dist/chunk-NP4EYKPO.js.map +0 -1
- /package/dist/{chunk-6N2HEV3U.js.map → chunk-WVZ2IXFH.js.map} +0 -0
package/src/99food/normalize.ts
CHANGED
|
@@ -1,269 +1,27 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
firstCents,
|
|
4
|
-
firstDate,
|
|
5
|
-
firstString,
|
|
6
|
-
pick,
|
|
7
|
-
toCents,
|
|
8
|
-
verifyHmacSha256Hex,
|
|
9
|
-
} from "../core/payload-read";
|
|
10
|
-
import type {
|
|
11
|
-
MarketplaceLifecycle,
|
|
12
|
-
MarketplaceDeliveredBy,
|
|
13
|
-
MarketplaceOrderType,
|
|
14
|
-
NormalizedAddress,
|
|
15
|
-
NormalizedEvent,
|
|
16
|
-
NormalizedMarketplaceOrder,
|
|
17
|
-
NormalizedOrderLine,
|
|
18
|
-
} from "../core/types";
|
|
1
|
+
import type { NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
|
|
2
|
+
import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../open-delivery/normalize";
|
|
19
3
|
|
|
20
4
|
/**
|
|
21
|
-
* The 99Food adapter's INBOUND half
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* carries no body, and `GET /v1/orders/{orderId}` answers the `Order`. So
|
|
26
|
-
* there are two readers here: {@link normalizeOpenDeliveryEvent} for the
|
|
27
|
-
* webhook (a `CREATED` becomes `orderToFetch`), and
|
|
28
|
-
* {@link normalizeOpenDeliveryOrder} for what the engine's fetch job reads.
|
|
29
|
-
*
|
|
30
|
-
* Every shape below is the spec's (`components/schemas/Event`, `Order`,
|
|
31
|
-
* `Price`, `Address`), and every fixture in the tests is the spec's own
|
|
32
|
-
* example. Read defensively all the same: a missing field produces null, and
|
|
33
|
-
* only a missing order id refuses an event (it is the idempotency key).
|
|
5
|
+
* The 99Food adapter's INBOUND half: Open Delivery v1.7.1's readers
|
|
6
|
+
* (`../open-delivery/normalize.ts`), stamped with 99Food's provider id. 99Food
|
|
7
|
+
* departs from the standard in nothing inbound: the `X-App-Signature` is the
|
|
8
|
+
* standard's lowercase-hex HMAC-SHA256 of the body.
|
|
34
9
|
*/
|
|
35
10
|
|
|
36
11
|
/** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */
|
|
37
12
|
export const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
|
|
38
13
|
|
|
39
|
-
|
|
40
|
-
const CREATED = "CREATED";
|
|
41
|
-
/** The order is cancelled: the store's request was granted, or a mandatory cancellation. */
|
|
42
|
-
const CANCELLED = "CANCELLED";
|
|
43
|
-
/** The order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */
|
|
44
|
-
const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: "DISPATCHED", CONCLUDED: "CONCLUDED" };
|
|
45
|
-
/** The marketplace refused the store's own cancellation request. */
|
|
46
|
-
const CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
|
|
14
|
+
export { verifyOpenDeliverySignature } from "../open-delivery/normalize";
|
|
47
15
|
|
|
48
|
-
/**
|
|
49
|
-
* Verify a delivery: Open Delivery's `X-App-Signature` is "a lowercased
|
|
50
|
-
* hexadecimal HMAC signature of the webhook HTTP request body, using the
|
|
51
|
-
* client secret as a key and SHA256 as the hash function". The key is the
|
|
52
|
-
* merchant app's CLIENT SECRET, so a store's connection keeps that same value
|
|
53
|
-
* as its webhook secret.
|
|
54
|
-
*
|
|
55
|
-
* Unlike iFood (whose secret is issued after certification), the key exists
|
|
56
|
-
* from the moment the store connects, so an unset secret REFUSES: an unsigned
|
|
57
|
-
* CANCELLED for a known order id would otherwise cancel it.
|
|
58
|
-
*/
|
|
59
|
-
export function verifyOpenDeliverySignature(
|
|
60
|
-
rawBody: string,
|
|
61
|
-
signature: string | null,
|
|
62
|
-
webhookSecret: string | null,
|
|
63
|
-
): boolean {
|
|
64
|
-
if (!webhookSecret) return false;
|
|
65
|
-
return verifyHmacSha256Hex(rawBody, signature, webhookSecret);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Normalize one webhook `Event`. Null only when it names no order.
|
|
70
|
-
*
|
|
71
|
-
* - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
|
|
72
|
-
* - `CANCELLED` is a cancellation, whether the store asked for it or not.
|
|
73
|
-
* - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
|
|
74
|
-
* - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine
|
|
75
|
-
* asks the host to move the order forward, when the store follows them.
|
|
76
|
-
* - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, the
|
|
77
|
-
* consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
|
|
78
|
-
* recorded, and acts on nothing: an IGNORED inbox row.
|
|
79
|
-
*
|
|
80
|
-
* The merchant is named by the `X-App-MerchantId` HEADER, not the body; the
|
|
81
|
-
* engine attributes a delivery by its URL's store slug, so it reads none.
|
|
82
|
-
*/
|
|
16
|
+
/** Normalize one webhook `Event` (see `normalizeOpenDeliveryEventAs`). Null only when it names no order. */
|
|
83
17
|
export function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent | null {
|
|
84
|
-
|
|
85
|
-
if (!externalOrderId) return null;
|
|
86
|
-
const eventType = (firstString(payload, [["eventType"]]) ?? "UNKNOWN").toUpperCase();
|
|
87
|
-
const cancelled = eventType === CANCELLED;
|
|
88
|
-
const denied = eventType === CANCELLATION_REQUEST_DENIED;
|
|
89
|
-
return {
|
|
90
|
-
provider: NINETY_NINE_FOOD_PROVIDER,
|
|
91
|
-
// The spec's own event id. The fallback is deterministic so a redelivery
|
|
92
|
-
// still collides on the inbox's unique index.
|
|
93
|
-
eventId: firstString(payload, [["eventId"]]) ?? `${externalOrderId}:${eventType}`,
|
|
94
|
-
eventType,
|
|
95
|
-
externalMerchantId: null,
|
|
96
|
-
externalOrderId,
|
|
97
|
-
order: null,
|
|
98
|
-
orderToFetch: eventType === CREATED,
|
|
99
|
-
cancelled,
|
|
100
|
-
cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
|
|
101
|
-
...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** A `Price` object (`{ value, currency }`) in cents. */
|
|
106
|
-
function priceCents(source: unknown, ...path: string[]): number | null {
|
|
107
|
-
return toCents(pick(source, ...path, "value"));
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* The note a kitchen reads: the chosen options (a pizza's halves are options)
|
|
112
|
-
* and the buyer's own instructions. The normalized line has no options of its
|
|
113
|
-
* own, and a flavour dropped from the ticket is food made wrong.
|
|
114
|
-
*/
|
|
115
|
-
function lineNote(item: unknown, fraction: string | null): string | null {
|
|
116
|
-
const rawOptions = pick(item, "options");
|
|
117
|
-
const options = (Array.isArray(rawOptions) ? rawOptions : [])
|
|
118
|
-
.map((option) => {
|
|
119
|
-
const name = asString(pick(option, "name"));
|
|
120
|
-
const quantity = Number(pick(option, "quantity") ?? 1);
|
|
121
|
-
return name && quantity > 1 ? `${quantity}x ${name}` : name;
|
|
122
|
-
})
|
|
123
|
-
.filter((name): name is string => name !== null);
|
|
124
|
-
const parts = [fraction, options.join(", ") || null, firstString(item, [["specialInstructions"]])];
|
|
125
|
-
const note = parts.filter((part): part is string => part !== null).join(" · ");
|
|
126
|
-
return note === "" ? null : note;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* What the buyer paid for the whole line, in cents. The spec's `totalPrice`
|
|
131
|
-
* ("quantity * (unitPrice + optionsPrice)") is the figure the order's
|
|
132
|
-
* `itemsPrice` is built from, and it wins whenever it is stated — its own
|
|
133
|
-
* example does not add up otherwise (unit 43, options 50, total 50).
|
|
134
|
-
*
|
|
135
|
-
* Without it: `unitPrice × quantity + optionsPrice`. ESTIMATED: the spec calls
|
|
136
|
-
* `optionsPrice` "the sum of the total prices of all options of the item", a
|
|
137
|
-
* LINE figure, so it is added once, never multiplied by the quantity or by a
|
|
138
|
-
* weight.
|
|
139
|
-
*/
|
|
140
|
-
function lineTotalCents(item: unknown, quantity: number): number {
|
|
141
|
-
const total = priceCents(item, "totalPrice");
|
|
142
|
-
if (total !== null) return total;
|
|
143
|
-
const unit = priceCents(item, "unitPrice") ?? 0;
|
|
144
|
-
return Math.round(unit * quantity) + (priceCents(item, "optionsPrice") ?? 0);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/** The stated quantity (decimal for weighed units), 1 when absent or nonsense. */
|
|
148
|
-
function quantityOf(item: unknown): number {
|
|
149
|
-
const stated = Number(pick(item, "quantity") ?? 1);
|
|
150
|
-
return Number.isFinite(stated) && stated > 0 ? stated : 1;
|
|
18
|
+
return normalizeOpenDeliveryEventAs(NINETY_NINE_FOOD_PROVIDER, payload);
|
|
151
19
|
}
|
|
152
20
|
|
|
153
|
-
/**
|
|
154
|
-
* Split a line total over a whole quantity so the lines add up to it EXACTLY:
|
|
155
|
-
* one row at `total / quantity` when it divides; otherwise `quantity - 1`
|
|
156
|
-
* units at the floor and one unit carrying the remainder, under the same SKU
|
|
157
|
-
* (R$ 10.00 over 3 is 3.33 × 2 + 3.34).
|
|
158
|
-
*/
|
|
159
|
-
function splitWhole(total: number, quantity: number): { quantity: number; unitPriceCents: number }[] {
|
|
160
|
-
const floor = Math.floor(total / quantity);
|
|
161
|
-
const remainder = total - floor * quantity;
|
|
162
|
-
if (remainder === 0) return [{ quantity, unitPriceCents: floor }];
|
|
163
|
-
const rest = quantity === 1 ? [] : [{ quantity: quantity - 1, unitPriceCents: floor }];
|
|
164
|
-
return [...rest, { quantity: 1, unitPriceCents: floor + remainder }];
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* One `Order.items[]` entry → its lines, which always add up to the line's
|
|
169
|
-
* total ({@link lineTotalCents}). A whole quantity is split by
|
|
170
|
-
* {@link splitWhole}; a fractional one (500 g as `0.5 KG`) is one line at its
|
|
171
|
-
* total, the weight in the note.
|
|
172
|
-
*
|
|
173
|
-
* A line with no `externalCode` keys on the item id, then the name: an
|
|
174
|
-
* unmapped line is recoverable, a dropped one is not. ESTIMATED: whether the
|
|
175
|
-
* item id is stable across orders is not pinned by the spec; if it is per
|
|
176
|
-
* order, each such order adds an unmapped SKU row.
|
|
177
|
-
*/
|
|
178
|
-
function readLines(item: unknown): NormalizedOrderLine[] {
|
|
179
|
-
const name = firstString(item, [["name"]]);
|
|
180
|
-
const sku = firstString(item, [["externalCode"], ["id"]]) ?? name;
|
|
181
|
-
if (!sku) return [];
|
|
182
|
-
const quantity = quantityOf(item);
|
|
183
|
-
const whole = Number.isInteger(quantity);
|
|
184
|
-
const fraction = whole ? null : `${quantity} ${firstString(item, [["unit"]]) ?? ""}`.trim();
|
|
185
|
-
const total = lineTotalCents(item, quantity);
|
|
186
|
-
const parts = whole ? splitWhole(total, quantity) : [{ quantity: 1, unitPriceCents: total }];
|
|
187
|
-
const note = lineNote(item, fraction);
|
|
188
|
-
return parts.map((part) => ({ externalSku: sku, name: name ?? sku, ...part, note }));
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/** `DELIVERY` or `TAKEOUT`; `INDOOR` (eaten at the store) is neither, so unstated. */
|
|
192
|
-
function readOrderType(order: unknown): MarketplaceOrderType | null {
|
|
193
|
-
const stated = firstString(order, [["type"]])?.toUpperCase();
|
|
194
|
-
return stated === "DELIVERY" || stated === "TAKEOUT" ? stated : null;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function readDeliveredBy(order: unknown): MarketplaceDeliveredBy | null {
|
|
198
|
-
const stated = firstString(order, [["delivery", "deliveredBy"]])?.toUpperCase();
|
|
199
|
-
return stated === "MERCHANT" || stated === "MARKETPLACE" ? stated : null;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* `delivery.deliveryAddress`. The spec's schema says `street`, `number`,
|
|
204
|
-
* `district`; its own (commented) order example says `streetName`,
|
|
205
|
-
* `streetNumber`, `neighborhood`. Both are read. The state is ISO 3166-2 by
|
|
206
|
-
* recommendation (`BR-SP`), so the country prefix is dropped.
|
|
207
|
-
*/
|
|
208
|
-
function readAddress(order: unknown, missingStreetNumber: string): NormalizedAddress | null {
|
|
209
|
-
const raw = pick(order, "delivery", "deliveryAddress");
|
|
210
|
-
const street = firstString(raw, [["street"], ["streetName"]]);
|
|
211
|
-
if (street === null) return null;
|
|
212
|
-
return {
|
|
213
|
-
street,
|
|
214
|
-
number: firstString(raw, [["number"], ["streetNumber"]]) ?? missingStreetNumber,
|
|
215
|
-
neighborhood: firstString(raw, [["district"], ["neighborhood"]]) ?? "",
|
|
216
|
-
complement: firstString(raw, [["complement"]]),
|
|
217
|
-
reference: firstString(raw, [["reference"]]),
|
|
218
|
-
postalCode: firstString(raw, [["postalCode"]])?.replace(/\D/g, "") || null,
|
|
219
|
-
city: firstString(raw, [["city"]]),
|
|
220
|
-
state: firstString(raw, [["state"]])?.replace(/^[A-Z]{2}-/u, "") ?? null,
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when
|
|
226
|
-
* it carries no id or no line.
|
|
227
|
-
*
|
|
228
|
-
* The total is `total.orderAmount`, "the final value of the order (itemsPrice
|
|
229
|
-
* + otherFees - discounts)": the buyer's receipt, gross. Open Delivery's
|
|
230
|
-
* `Order` states NO commission field, so `commissionCents` is null ("did not
|
|
231
|
-
* say"), never 0; the marketplace's cut arrives with its statement.
|
|
232
|
-
*/
|
|
21
|
+
/** Normalize one `Order` (see `normalizeOpenDeliveryOrderAs`). Null when it carries no id or no line. */
|
|
233
22
|
export function normalizeOpenDeliveryOrder(
|
|
234
23
|
order: unknown,
|
|
235
24
|
options: { missingStreetNumber: string },
|
|
236
25
|
): NormalizedMarketplaceOrder | null {
|
|
237
|
-
|
|
238
|
-
const rawItems = pick(order, "items");
|
|
239
|
-
const lines = (Array.isArray(rawItems) ? rawItems : [])
|
|
240
|
-
.flatMap(readLines);
|
|
241
|
-
if (!externalOrderId || lines.length === 0) return null;
|
|
242
|
-
return {
|
|
243
|
-
provider: NINETY_NINE_FOOD_PROVIDER,
|
|
244
|
-
externalOrderId,
|
|
245
|
-
externalDisplayId: firstString(order, [["displayId"]]),
|
|
246
|
-
externalMerchantId: firstString(order, [["merchant", "id"]]),
|
|
247
|
-
buyer: {
|
|
248
|
-
externalId: firstString(order, [["customer", "id"]]),
|
|
249
|
-
name: firstString(order, [["customer", "name"]]),
|
|
250
|
-
phone: firstString(order, [["customer", "phone", "number"]]),
|
|
251
|
-
},
|
|
252
|
-
lines,
|
|
253
|
-
// The line sum is the FALLBACK: the stated total carries the fees and
|
|
254
|
-
// discounts the lines do not, and it is the number on the receipt.
|
|
255
|
-
totalCents:
|
|
256
|
-
firstCents(order, [["total", "orderAmount", "value"]]) ??
|
|
257
|
-
lines.reduce((sum, line) => sum + line.unitPriceCents * line.quantity, 0),
|
|
258
|
-
commissionCents: null,
|
|
259
|
-
deliveryDueAt: firstDate(order, [
|
|
260
|
-
["delivery", "estimatedDeliveryDateTime"],
|
|
261
|
-
["takeout", "takeoutDateTime"],
|
|
262
|
-
["schedule", "scheduledDateTimeEnd"],
|
|
263
|
-
]),
|
|
264
|
-
placedAt: firstDate(order, [["createdAt"]]) ?? new Date(),
|
|
265
|
-
orderType: readOrderType(order),
|
|
266
|
-
deliveredBy: readDeliveredBy(order),
|
|
267
|
-
deliveryAddress: readAddress(order, options.missingStreetNumber),
|
|
268
|
-
};
|
|
26
|
+
return normalizeOpenDeliveryOrderAs(NINETY_NINE_FOOD_PROVIDER, order, options);
|
|
269
27
|
}
|
package/src/99food/outbound.ts
CHANGED
|
@@ -1,280 +1,39 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
outboundResultOf,
|
|
4
|
-
tokenGrantResultOf,
|
|
5
|
-
type AdapterCallContext,
|
|
6
|
-
type CancellationRequestInput,
|
|
7
|
-
type FetchOrderResult,
|
|
8
|
-
type MarketplaceHttpResponse,
|
|
9
|
-
type OutboundOrderRef,
|
|
10
|
-
type OutboundResult,
|
|
11
|
-
type StatusFacts,
|
|
12
|
-
} from "../core/adapter";
|
|
13
|
-
import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from "./normalize";
|
|
1
|
+
import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from "../open-delivery/client";
|
|
2
|
+
import { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
|
|
14
3
|
|
|
15
4
|
/**
|
|
16
|
-
*
|
|
17
|
-
* grant, the order fetch, confirm
|
|
18
|
-
*
|
|
19
|
-
*
|
|
5
|
+
* 99Food's Open Delivery DIALECT: v1.7.1 as the standard writes it. The calls
|
|
6
|
+
* themselves (the grant, the order fetch, confirm, requestCancellation, the
|
|
7
|
+
* status steps) are `../open-delivery/`'s; this file only says where and how
|
|
8
|
+
* 99Food takes them.
|
|
9
|
+
*
|
|
10
|
+
* - Token: `POST /oauth/token`, form-encoded `client_id`, `client_secret`,
|
|
11
|
+
* `grant_type=client_credentials`.
|
|
12
|
+
* - Bodies: plain JSON; no request signature.
|
|
20
13
|
*
|
|
21
14
|
* The one thing the spec cannot pin is WHERE: Open Delivery standardizes the
|
|
22
15
|
* paths under each Ordering Application's own base URL, and 99Food gives its
|
|
23
16
|
* base URLs to a partner at onboarding. So the base URL per environment is
|
|
24
|
-
* the adapter's REQUIRED config, never a guessed default.
|
|
25
|
-
* 99Food: the HTTP client is the host's port, answered by a fake.
|
|
17
|
+
* the adapter's REQUIRED config, never a guessed default.
|
|
26
18
|
*/
|
|
27
19
|
|
|
28
20
|
/** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */
|
|
29
|
-
export type NinetyNineFoodApiBaseUrls =
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
|
|
48
|
-
try {
|
|
49
|
-
const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };
|
|
50
|
-
if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
|
|
51
|
-
const expires =
|
|
52
|
-
typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
|
|
53
|
-
return { token: parsed.access_token, expiresInSeconds: expires };
|
|
54
|
-
} catch {
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* A bearer token from the per-process cache, or a fresh `client_credentials`
|
|
61
|
-
* grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,
|
|
62
|
-
* `grant_type`). Keyed by environment and client id; memory only.
|
|
63
|
-
*/
|
|
64
|
-
export async function bearer(
|
|
65
|
-
ctx: AdapterCallContext,
|
|
66
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
67
|
-
): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
|
|
68
|
-
const cached = ctx.tokens.get(tokenKey(ctx));
|
|
69
|
-
if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
|
|
70
|
-
const response = await ctx.http({
|
|
71
|
-
method: "POST",
|
|
72
|
-
url: `${baseOf(ctx, bases)}/oauth/token`,
|
|
73
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
74
|
-
body: new URLSearchParams({
|
|
75
|
-
client_id: ctx.credentials.clientId,
|
|
76
|
-
client_secret: ctx.credentials.clientSecret,
|
|
77
|
-
grant_type: "client_credentials",
|
|
78
|
-
}).toString(),
|
|
79
|
-
});
|
|
80
|
-
if (response.status < 200 || response.status >= 300) {
|
|
81
|
-
const result = tokenGrantResultOf(response);
|
|
82
|
-
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
|
|
83
|
-
}
|
|
84
|
-
const token = tokenOf(response.body);
|
|
85
|
-
if (!token) return { kind: "retry", reason: "99Food answered the token grant without a token" };
|
|
86
|
-
ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
|
|
87
|
-
return { token: token.token };
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** One authenticated call to an order's resource, the raw answer or the result that ends it. */
|
|
91
|
-
async function callOrder(
|
|
92
|
-
ctx: AdapterCallContext,
|
|
93
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
94
|
-
request: { method: "GET" | "POST"; externalOrderId: string; action: string | null; body?: unknown },
|
|
95
|
-
): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: "accepted" }>> {
|
|
96
|
-
const auth = await bearer(ctx, bases);
|
|
97
|
-
if (!("token" in auth)) return auth;
|
|
98
|
-
const suffix = request.action === null ? "" : `/${request.action}`;
|
|
99
|
-
const response = await ctx.http({
|
|
100
|
-
method: request.method,
|
|
101
|
-
url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,
|
|
102
|
-
headers: {
|
|
103
|
-
Authorization: `Bearer ${auth.token}`,
|
|
104
|
-
...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
105
|
-
},
|
|
106
|
-
...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
|
|
107
|
-
});
|
|
108
|
-
// A 401 is a token that went stale under us: forget it, and the retry fetches another.
|
|
109
|
-
if (response.status !== 401) return response;
|
|
110
|
-
ctx.tokens.delete(tokenKey(ctx));
|
|
111
|
-
return { kind: "retry", reason: "99Food refused the token" };
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */
|
|
115
|
-
function alreadyCancelled(response: MarketplaceHttpResponse): boolean {
|
|
116
|
-
if (response.status !== 422) return false;
|
|
117
|
-
try {
|
|
118
|
-
return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === "CANCELLED";
|
|
119
|
-
} catch {
|
|
120
|
-
return false;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** {@link answered} for a fetch: a call that never got an answer is a retry. */
|
|
125
|
-
async function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {
|
|
126
|
-
try {
|
|
127
|
-
return await call();
|
|
128
|
-
} catch (error) {
|
|
129
|
-
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */
|
|
134
|
-
export function openDeliveryFetchOrder(
|
|
135
|
-
ctx: AdapterCallContext,
|
|
136
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
137
|
-
order: { externalOrderId: string },
|
|
138
|
-
options: { missingStreetNumber: string },
|
|
139
|
-
): Promise<FetchOrderResult> {
|
|
140
|
-
return fetched(async () => {
|
|
141
|
-
const response = await callOrder(ctx, bases, { method: "GET", externalOrderId: order.externalOrderId, action: null });
|
|
142
|
-
if ("kind" in response) return response;
|
|
143
|
-
const result = outboundResultOf(response);
|
|
144
|
-
if (result.kind !== "accepted") return result;
|
|
145
|
-
let body: unknown;
|
|
146
|
-
try {
|
|
147
|
-
body = JSON.parse(response.body);
|
|
148
|
-
} catch {
|
|
149
|
-
return { kind: "refused", status: response.status, message: "the order is not JSON" };
|
|
150
|
-
}
|
|
151
|
-
const normalized = normalizeOpenDeliveryOrder(body, options);
|
|
152
|
-
return normalized
|
|
153
|
-
? { kind: "order", order: normalized }
|
|
154
|
-
: { kind: "refused", status: response.status, message: "the order carries no id or no line" };
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:
|
|
160
|
-
* `orderExternalCode` (the host's own order id) and `createdAt`, plus the
|
|
161
|
-
* `preparationTime` in minutes when the store stated one. The spec describes
|
|
162
|
-
* `createdAt` with the ORDER's creation text (a copy of another schema's), so
|
|
163
|
-
* it is sent as the moment of the confirmation: ESTIMATED.
|
|
164
|
-
*
|
|
165
|
-
* Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`
|
|
166
|
-
* ("unable to process the contained instructions. (Check if the instruction
|
|
167
|
-
* has not been sent before.)"), and its body cannot tell a duplicate from a
|
|
168
|
-
* cancelled order. So a retried confirm whose first answer was lost reads
|
|
169
|
-
* "não confirmou" with the app link — a false alarm a person dismisses on
|
|
170
|
-
* 99Food — and a confirm 99Food truly refused is never stamped confirmed.
|
|
171
|
-
*/
|
|
172
|
-
export function openDeliveryConfirm(
|
|
173
|
-
ctx: AdapterCallContext,
|
|
174
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
175
|
-
order: OutboundOrderRef,
|
|
176
|
-
input: { preparationMinutes: number | null },
|
|
177
|
-
): Promise<OutboundResult> {
|
|
178
|
-
return answered(async () => {
|
|
179
|
-
const response = await callOrder(ctx, bases, {
|
|
180
|
-
method: "POST",
|
|
181
|
-
externalOrderId: order.externalOrderId,
|
|
182
|
-
action: "confirm",
|
|
183
|
-
body: {
|
|
184
|
-
orderExternalCode: order.hostOrderCode,
|
|
185
|
-
createdAt: ctx.now.toISOString(),
|
|
186
|
-
...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),
|
|
187
|
-
},
|
|
188
|
-
});
|
|
189
|
-
if ("kind" in response) return response;
|
|
190
|
-
return outboundResultOf(response);
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* `POST /v1/orders/{orderId}/requestCancellation` with the spec's
|
|
196
|
-
* `RequestCancelled`: `reason` (free text: the store's, else the label),
|
|
197
|
-
* `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means
|
|
198
|
-
* taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`
|
|
199
|
-
* event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is
|
|
200
|
-
* cancelled already, which is what the request wanted.
|
|
201
|
-
*
|
|
202
|
-
* `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,
|
|
203
|
-
* and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU
|
|
204
|
-
* map is keyed on. The field is optional.
|
|
205
|
-
*/
|
|
206
|
-
export function openDeliveryRequestCancellation(
|
|
207
|
-
ctx: AdapterCallContext,
|
|
208
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
209
|
-
order: OutboundOrderRef,
|
|
210
|
-
input: CancellationRequestInput,
|
|
211
|
-
): Promise<OutboundResult> {
|
|
212
|
-
return answered(async () => {
|
|
213
|
-
const response = await callOrder(ctx, bases, {
|
|
214
|
-
method: "POST",
|
|
215
|
-
externalOrderId: order.externalOrderId,
|
|
216
|
-
action: "requestCancellation",
|
|
217
|
-
body: { reason: input.text === "" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },
|
|
218
|
-
});
|
|
219
|
-
if ("kind" in response) return response;
|
|
220
|
-
if (alreadyCancelled(response)) return { kind: "accepted" };
|
|
221
|
-
const result = outboundResultOf(response);
|
|
222
|
-
// Open Delivery's 400 is a malformed request (a bad id or body: ours);
|
|
223
|
-
// its 422 is the business answer and stays a refusal.
|
|
224
|
-
return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* What 99Food is told per step (FUT-4653), from Open Delivery v1.7.1's
|
|
230
|
-
* `openapi.yaml` (https://abrasel-nacional.github.io/opendelivery/openapi.yaml,
|
|
231
|
-
* read 2026-11-25, paths at lines 1605-1890):
|
|
232
|
-
*
|
|
233
|
-
* - READY: `POST /v1/orders/{id}/readyForPickup`, "ready for pickup by the
|
|
234
|
-
* customer or delivery person"; 202. Every kind of order.
|
|
235
|
-
* - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`
|
|
236
|
-
* (`deliveryTrackingInfo` optional, sent empty), and "a DISPATCHED event is
|
|
237
|
-
* expected after this action". Only where the logistics is the merchant's.
|
|
238
|
-
* - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a
|
|
239
|
-
* take-out `POST /v1/orders/{id}/pickedUp`. Both optional in the spec. The
|
|
240
|
-
* marketplace's own fleet: none.
|
|
241
|
-
*
|
|
242
|
-
* The kind of order is `deliveredBy` (null: a take-out). That a take-out's
|
|
243
|
-
* order states no `deliveredBy` is how 99Food's order reads (ESTIMATED: an
|
|
244
|
-
* order that merely omits it reads as a take-out here).
|
|
245
|
-
*/
|
|
246
|
-
const STATUS_PATH: Readonly<Record<string, (facts: StatusFacts) => { action: string; body?: unknown } | null>> = {
|
|
247
|
-
READY: () => ({ action: "readyForPickup" }),
|
|
248
|
-
DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null),
|
|
249
|
-
HANDED_OVER: (facts) =>
|
|
250
|
-
facts.deliveredBy === "MERCHANT"
|
|
251
|
-
? { action: "delivered", body: {} }
|
|
252
|
-
: facts.deliveredBy === null
|
|
253
|
-
? { action: "pickedUp", body: {} }
|
|
254
|
-
: null,
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
/** Whether 99Food takes this step for this kind of order: answered offline. */
|
|
258
|
-
export function openDeliveryStatusSupported(facts: StatusFacts): boolean {
|
|
259
|
-
return STATUS_PATH[facts.step]?.(facts) != null;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
/** Tell 99Food a step happened. `unsupported` when the spec has no call for it. */
|
|
263
|
-
export function openDeliveryInformStatus(
|
|
264
|
-
ctx: AdapterCallContext,
|
|
265
|
-
bases: NinetyNineFoodApiBaseUrls,
|
|
266
|
-
order: OutboundOrderRef,
|
|
267
|
-
facts: StatusFacts,
|
|
268
|
-
): Promise<OutboundResult | { kind: "unsupported" }> {
|
|
269
|
-
const path = STATUS_PATH[facts.step]?.(facts) ?? null;
|
|
270
|
-
if (path === null) return Promise.resolve({ kind: "unsupported" });
|
|
271
|
-
return answered(async () => {
|
|
272
|
-
const response = await callOrder(ctx, bases, {
|
|
273
|
-
method: "POST",
|
|
274
|
-
externalOrderId: order.externalOrderId,
|
|
275
|
-
action: path.action,
|
|
276
|
-
...(path.body === undefined ? {} : { body: path.body }),
|
|
277
|
-
});
|
|
278
|
-
return "kind" in response ? response : outboundResultOf(response);
|
|
279
|
-
});
|
|
21
|
+
export type NinetyNineFoodApiBaseUrls = OpenDeliveryApiBaseUrls;
|
|
22
|
+
|
|
23
|
+
/** 99Food's dialect, for the base URLs it was given. */
|
|
24
|
+
export function ninetyNineFoodDialect(bases: NinetyNineFoodApiBaseUrls): OpenDeliveryDialect {
|
|
25
|
+
return {
|
|
26
|
+
provider: NINETY_NINE_FOOD_PROVIDER,
|
|
27
|
+
name: "99Food",
|
|
28
|
+
bases,
|
|
29
|
+
tokenGrant: (ctx) => ({
|
|
30
|
+
contentType: "application/x-www-form-urlencoded",
|
|
31
|
+
body: new URLSearchParams({
|
|
32
|
+
client_id: ctx.credentials.clientId,
|
|
33
|
+
client_secret: ctx.credentials.clientSecret,
|
|
34
|
+
grant_type: "client_credentials",
|
|
35
|
+
}).toString(),
|
|
36
|
+
}),
|
|
37
|
+
serialize: (body) => JSON.stringify(body),
|
|
38
|
+
};
|
|
280
39
|
}
|
package/src/99food/pause.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { AdapterCallContext, OutboundResult } from "../core/adapter";
|
|
2
2
|
import type { MarketplaceAvailability } from "../core/pause-port";
|
|
3
|
-
import {
|
|
3
|
+
import { openDeliveryMerchantUpdate, openDeliverySwitchAvailability } from "../open-delivery/merchant";
|
|
4
|
+
import { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
|
|
@@ -28,29 +29,13 @@ export function openDeliverySetMerchantStatus(
|
|
|
28
29
|
bases: NinetyNineFoodApiBaseUrls,
|
|
29
30
|
status: "AVAILABLE" | "UNAVAILABLE",
|
|
30
31
|
): Promise<OutboundResult> {
|
|
31
|
-
return
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const response = await ctx.http({
|
|
35
|
-
method: "POST",
|
|
36
|
-
url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
|
|
37
|
-
headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
|
|
38
|
-
body: JSON.stringify({ merchantStatus: status }),
|
|
39
|
-
});
|
|
40
|
-
if (response.status !== 401) return outboundResultOf(response);
|
|
41
|
-
ctx.tokens.delete(tokenKey(ctx));
|
|
42
|
-
return { kind: "retry", reason: "99Food refused the token" };
|
|
32
|
+
return openDeliveryMerchantUpdate(ctx, ninetyNineFoodDialect(bases), {
|
|
33
|
+
path: "/v1/merchantUpdate",
|
|
34
|
+
body: { merchantStatus: status },
|
|
43
35
|
});
|
|
44
36
|
}
|
|
45
37
|
|
|
46
38
|
/** 99Food's availability capability: Open Delivery's merchant status, a switch. */
|
|
47
39
|
export function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {
|
|
48
|
-
return
|
|
49
|
-
kind: "switch",
|
|
50
|
-
pause: async (ctx, request) => {
|
|
51
|
-
const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
|
|
52
|
-
return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
|
|
53
|
-
},
|
|
54
|
-
resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"),
|
|
55
|
-
};
|
|
40
|
+
return openDeliverySwitchAvailability((ctx, _merchantId, status) => openDeliverySetMerchantStatus(ctx, bases, status));
|
|
56
41
|
}
|