@12-apps/marketplace 1.1.0 → 1.3.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 +37 -7
- package/README.md +238 -4
- package/dist/99food/en-US.d.ts +19 -0
- package/dist/99food/en-US.js +23 -0
- package/dist/99food/en-US.js.map +1 -0
- package/dist/99food/index.d.ts +162 -0
- package/dist/99food/index.js +444 -0
- package/dist/99food/index.js.map +1 -0
- package/dist/99food/pt-BR.d.ts +23 -0
- package/dist/99food/pt-BR.js +23 -0
- package/dist/99food/pt-BR.js.map +1 -0
- package/dist/{adapter-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
- package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
- package/dist/chunk-AYYBRQJV.js.map +1 -0
- package/dist/chunk-BD7DS3XM.js +78 -0
- package/dist/chunk-BD7DS3XM.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
- package/dist/chunk-RVBTARIY.js.map +1 -0
- package/dist/chunk-XUAFXNOH.js +1604 -0
- package/dist/chunk-XUAFXNOH.js.map +1 -0
- package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +16 -12
- package/dist/ifood/index.js +248 -121
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +189 -346
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/en-US.d.ts +14 -0
- package/dist/rappi/en-US.js +18 -0
- package/dist/rappi/en-US.js.map +1 -0
- package/dist/rappi/index.d.ts +190 -0
- package/dist/rappi/index.js +359 -0
- package/dist/rappi/index.js.map +1 -0
- package/dist/rappi/pt-BR.d.ts +18 -0
- package/dist/rappi/pt-BR.js +18 -0
- package/dist/rappi/pt-BR.js.map +1 -0
- package/dist/server/index.d.ts +19 -8
- package/dist/server/index.js +4 -2
- package/package.json +26 -2
- package/prisma/marketplace.prisma +97 -2
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/copy.ts +36 -0
- package/src/99food/en-US.ts +19 -0
- package/src/99food/index.ts +125 -0
- package/src/99food/normalize.ts +263 -0
- package/src/99food/outbound.ts +220 -0
- package/src/99food/pt-BR.ts +23 -0
- package/src/core/adapter.ts +27 -2
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/decisions.ts +16 -4
- package/src/core/engine.ts +54 -0
- package/src/core/fetch-order.ts +253 -0
- package/src/core/inbox.ts +8 -2
- package/src/core/ingest.ts +10 -2
- package/src/core/integration.ts +30 -1
- package/src/core/order-fetch-marks.ts +63 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/outbound.ts +22 -2
- package/src/core/payload-read.ts +101 -0
- package/src/core/pipeline.ts +64 -15
- package/src/core/ports.ts +36 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/normalize.ts +15 -88
- package/src/ifood/outbound.ts +9 -6
- package/src/index.ts +49 -1
- package/src/rappi/copy.ts +39 -0
- package/src/rappi/en-US.ts +14 -0
- package/src/rappi/index.ts +161 -0
- package/src/rappi/normalize.ts +314 -0
- package/src/rappi/outbound.ts +182 -0
- package/src/rappi/pt-BR.ts +18 -0
- package/src/server/index.ts +1 -0
- package/src/server/jobs.ts +71 -8
- package/dist/chunk-7BYVGNU5.js.map +0 -1
- package/dist/chunk-DVIRN42O.js +0 -707
- package/dist/chunk-DVIRN42O.js.map +0 -1
- package/dist/chunk-NGNEL4HS.js.map +0 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
|
|
2
|
+
import {
|
|
3
|
+
NINETY_NINE_FOOD_REASON_CODES,
|
|
4
|
+
type NinetyNineFoodAdapterCopy,
|
|
5
|
+
type NinetyNineFoodReasonCode,
|
|
6
|
+
} from "./copy";
|
|
7
|
+
import { openDeliveryCatalogue } from "./catalogue";
|
|
8
|
+
import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from "./normalize";
|
|
9
|
+
import {
|
|
10
|
+
openDeliveryConfirm,
|
|
11
|
+
openDeliveryFetchOrder,
|
|
12
|
+
openDeliveryRequestCancellation,
|
|
13
|
+
type NinetyNineFoodApiBaseUrls,
|
|
14
|
+
} from "./outbound";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.
|
|
18
|
+
*
|
|
19
|
+
* 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks
|
|
20
|
+
* Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,
|
|
21
|
+
* confirm, requestCancellation with the spec's codes. Everything 99Food is
|
|
22
|
+
* under this folder; the engine reaches it only through the
|
|
23
|
+
* {@link MarketplaceAdapter} port, and registering it is the whole cost:
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { createNinetyNineFoodAdapter } from "@12-apps/marketplace/99food";
|
|
27
|
+
* import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/99food/pt-BR";
|
|
28
|
+
*
|
|
29
|
+
* createMarketplaceEngine({
|
|
30
|
+
* …ports,
|
|
31
|
+
* adapters: [
|
|
32
|
+
* createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),
|
|
33
|
+
* createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),
|
|
34
|
+
* ],
|
|
35
|
+
* });
|
|
36
|
+
* ```
|
|
37
|
+
*
|
|
38
|
+
* Its webhook is the engine's one route, `POST
|
|
39
|
+
* /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
export { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
|
|
43
|
+
|
|
44
|
+
/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
|
|
45
|
+
export const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
|
|
46
|
+
|
|
47
|
+
/** The one reason that means "an item is unavailable". */
|
|
48
|
+
const ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = "UNAVAILABLE_ITEM";
|
|
49
|
+
|
|
50
|
+
export interface NinetyNineFoodAdapterConfig {
|
|
51
|
+
/** The words the adapter needs: reason labels and the missing-number text. Required. */
|
|
52
|
+
copy: NinetyNineFoodAdapterCopy;
|
|
53
|
+
/**
|
|
54
|
+
* Where 99Food serves Open Delivery, per environment: the base the spec's
|
|
55
|
+
* paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at
|
|
56
|
+
* onboarding and not public, so required and defaultless. https only.
|
|
57
|
+
*/
|
|
58
|
+
apiBaseUrl: NinetyNineFoodApiBaseUrls;
|
|
59
|
+
/**
|
|
60
|
+
* Where "open it on 99Food" goes: the merchant portal. Open Delivery names no
|
|
61
|
+
* per-order deep link, so the link is the portal. Required; https only.
|
|
62
|
+
*/
|
|
63
|
+
portalUrl: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function assertHttps(name: string, url: string): void {
|
|
67
|
+
let parsed: URL;
|
|
68
|
+
try {
|
|
69
|
+
parsed = new URL(url);
|
|
70
|
+
} catch {
|
|
71
|
+
throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);
|
|
72
|
+
}
|
|
73
|
+
if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
|
|
77
|
+
export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {
|
|
78
|
+
assertHttps("apiBaseUrl.SANDBOX", config.apiBaseUrl.SANDBOX);
|
|
79
|
+
assertHttps("apiBaseUrl.PRODUCTION", config.apiBaseUrl.PRODUCTION);
|
|
80
|
+
assertHttps("portalUrl", config.portalUrl);
|
|
81
|
+
const bases = { ...config.apiBaseUrl };
|
|
82
|
+
const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({
|
|
83
|
+
code,
|
|
84
|
+
label: config.copy.reasonLabels[code],
|
|
85
|
+
itemUnavailable: code === ITEM_UNAVAILABLE,
|
|
86
|
+
// `outOfStockItems` is optional in the spec (see `./outbound.ts`).
|
|
87
|
+
needsItems: false,
|
|
88
|
+
}));
|
|
89
|
+
const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };
|
|
90
|
+
return {
|
|
91
|
+
provider: NINETY_NINE_FOOD_PROVIDER,
|
|
92
|
+
capabilities: {
|
|
93
|
+
apiConfirm: true,
|
|
94
|
+
apiCancel: true,
|
|
95
|
+
// The spec lets a merchant request a cancellation before or after the
|
|
96
|
+
// confirm ("rules may vary depending on the timing"); the answer says.
|
|
97
|
+
cancelAfterAccept: true,
|
|
98
|
+
// 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.
|
|
99
|
+
asyncCancellationOutcome: true,
|
|
100
|
+
perOrderAppLink: false,
|
|
101
|
+
// `OrderConfirmed.preparationTime`, in minutes.
|
|
102
|
+
confirmTakesPreparationTime: true,
|
|
103
|
+
cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
|
|
104
|
+
},
|
|
105
|
+
normalize: normalizeOpenDeliveryEvent,
|
|
106
|
+
readSignature: (header) => header("x-app-signature"),
|
|
107
|
+
verifySignature: verifyOpenDeliverySignature,
|
|
108
|
+
cancellationReasons: () => reasons,
|
|
109
|
+
// PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).
|
|
110
|
+
catalogue: openDeliveryCatalogue(bases),
|
|
111
|
+
fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
|
|
112
|
+
confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
|
|
113
|
+
requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
|
|
114
|
+
appLink: () => config.portalUrl,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export {
|
|
119
|
+
NINETY_NINE_FOOD_REASON_CODES,
|
|
120
|
+
type NinetyNineFoodAdapterCopy,
|
|
121
|
+
type NinetyNineFoodReasonCode,
|
|
122
|
+
} from "./copy";
|
|
123
|
+
export { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from "./normalize";
|
|
124
|
+
export type { NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
125
|
+
export { openDeliveryCatalogue, openDeliveryMenuDocument } from "./catalogue";
|
|
@@ -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
|
+
export 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
|
+
export 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
|
+
export 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;
|