@12-apps/marketplace 1.8.0 → 1.9.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/README.md +102 -8
- 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-PYHNM47K.js +478 -0
- package/dist/chunk-PYHNM47K.js.map +1 -0
- package/dist/client-B4EQCRD_.d.ts +20 -0
- 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/package.json +14 -2
- 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/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/99food/catalogue.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
1
|
+
import type { PullCatalogue } from "../core/catalogue-port";
|
|
2
|
+
import { openDeliveryMenuDocument, openDeliveryMerchantUpdate } from "../open-delivery/merchant";
|
|
3
|
+
import { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
5
4
|
|
|
6
5
|
/**
|
|
7
6
|
* The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).
|
|
@@ -9,16 +8,16 @@ import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outb
|
|
|
9
8
|
* In Open Delivery the store's software does not write the menu to the
|
|
10
9
|
* marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a
|
|
11
10
|
* `Merchant` document carrying `menus`, `categories`, `items` and
|
|
12
|
-
* `itemOffers
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
11
|
+
* `itemOffers`, and the ORDERING APPLICATION (99Food) pulls it, again when its
|
|
12
|
+
* `TTL` runs out or when told the merchant changed (`POST
|
|
13
|
+
* /v1/merchantUpdate`, sent with an empty body: "pull everything again").
|
|
14
|
+
* Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml
|
|
16
15
|
*
|
|
17
16
|
* So the adapter does two things: build the menu part of that document from
|
|
18
|
-
* the items the store switched on (`menuDocument`, pure
|
|
19
|
-
*
|
|
20
|
-
* `
|
|
21
|
-
* (`notifyMenuChanged`).
|
|
17
|
+
* the items the store switched on (`menuDocument`, pure, shared:
|
|
18
|
+
* `../open-delivery/merchant.ts`; the host merges it into the rest of the
|
|
19
|
+
* `Merchant`, which is its own: `basicInfo`, `services`, `lastUpdate`, `TTL`,
|
|
20
|
+
* `status`), and tell 99Food the menu changed (`notifyMenuChanged`).
|
|
22
21
|
*
|
|
23
22
|
* ESTIMATED, to be checked once 99Food grants partner access:
|
|
24
23
|
* - the path: the spec's route table and prose name `POST /merchantUpdate`
|
|
@@ -28,90 +27,21 @@ import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outb
|
|
|
28
27
|
* client app may serve many merchants, so it is sent to name which;
|
|
29
28
|
* - that 99Food reads the whole `Merchant` on that notification (scenario 1
|
|
30
29
|
* of the operation) rather than needing `entityType`/`updatedObjects`.
|
|
31
|
-
*
|
|
32
|
-
* Every id in the document is a UUID the software generates (the spec's
|
|
33
|
-
* `format: uuid`), derived from the publication's stable reference, so the
|
|
34
|
-
* same product keeps the same ids across pulls.
|
|
35
30
|
*/
|
|
36
31
|
|
|
37
|
-
|
|
38
|
-
function categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {
|
|
39
|
-
const byName = new Map<string, { id: string; name: string; offers: string[] }>();
|
|
40
|
-
for (const entry of entries) {
|
|
41
|
-
const name = entry.categoryName.trim();
|
|
42
|
-
const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };
|
|
43
|
-
category.offers.push(stableUuid(`${entry.ref}:offer`));
|
|
44
|
-
byName.set(name, category);
|
|
45
|
-
}
|
|
46
|
-
return [...byName.values()];
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */
|
|
50
|
-
export function openDeliveryMenuDocument(input: {
|
|
51
|
-
externalMerchantId: string;
|
|
52
|
-
entries: readonly CatalogueMenuEntry[];
|
|
53
|
-
options: CatalogueMenuOptions;
|
|
54
|
-
}) {
|
|
55
|
-
const { externalMerchantId: merchantId, entries, options } = input;
|
|
56
|
-
const categories = categoriesOf(merchantId, entries);
|
|
57
|
-
return {
|
|
58
|
-
menus: [
|
|
59
|
-
{
|
|
60
|
-
id: stableUuid(`${merchantId}:menu`),
|
|
61
|
-
name: options.menuName,
|
|
62
|
-
externalCode: "menu",
|
|
63
|
-
categoryId: categories.map((category) => category.id),
|
|
64
|
-
},
|
|
65
|
-
],
|
|
66
|
-
categories: categories.map((category, index) => ({
|
|
67
|
-
id: category.id,
|
|
68
|
-
index,
|
|
69
|
-
name: category.name,
|
|
70
|
-
externalCode: category.name,
|
|
71
|
-
status: "AVAILABLE",
|
|
72
|
-
itemOfferId: category.offers,
|
|
73
|
-
})),
|
|
74
|
-
items: entries.map((entry) => ({
|
|
75
|
-
id: stableUuid(`${entry.ref}:item`),
|
|
76
|
-
name: entry.name,
|
|
77
|
-
description: entry.description ?? "",
|
|
78
|
-
externalCode: entry.productId,
|
|
79
|
-
status: "AVAILABLE",
|
|
80
|
-
unit: "UN",
|
|
81
|
-
...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),
|
|
82
|
-
})),
|
|
83
|
-
itemOffers: entries.map((entry, index) => {
|
|
84
|
-
const value = Math.round(entry.priceCents) / 100;
|
|
85
|
-
return {
|
|
86
|
-
id: stableUuid(`${entry.ref}:offer`),
|
|
87
|
-
itemId: stableUuid(`${entry.ref}:item`),
|
|
88
|
-
index,
|
|
89
|
-
status: "AVAILABLE",
|
|
90
|
-
price: { value, originalValue: value, currency: options.currency },
|
|
91
|
-
};
|
|
92
|
-
}),
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/** `POST /v1/merchantUpdate` with no body: 99Food pulls the whole `Merchant` again. 200 or 204. */
|
|
97
|
-
async function notify(ctx: CatalogueCallContext, bases: NinetyNineFoodApiBaseUrls): Promise<OutboundResult> {
|
|
98
|
-
const auth = await bearer(ctx, bases);
|
|
99
|
-
if (!("token" in auth)) return auth;
|
|
100
|
-
const response = await ctx.http({
|
|
101
|
-
method: "POST",
|
|
102
|
-
url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
|
|
103
|
-
headers: { Authorization: `Bearer ${auth.token}`, "X-App-MerchantId": ctx.externalMerchantId },
|
|
104
|
-
});
|
|
105
|
-
if (response.status !== 401) return outboundResultOf(response);
|
|
106
|
-
ctx.tokens.delete(tokenKey(ctx));
|
|
107
|
-
return { kind: "retry", reason: "99Food refused the token" };
|
|
108
|
-
}
|
|
32
|
+
export { openDeliveryMenuDocument } from "../open-delivery/merchant";
|
|
109
33
|
|
|
110
34
|
/** 99Food's catalogue capability, for the base URLs it was given. */
|
|
111
35
|
export function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {
|
|
36
|
+
const dialect = ninetyNineFoodDialect(bases);
|
|
112
37
|
return {
|
|
113
38
|
mode: "pull",
|
|
114
39
|
menuDocument: openDeliveryMenuDocument,
|
|
115
|
-
|
|
40
|
+
// No body: 99Food pulls the whole `Merchant` again. 200 or 204.
|
|
41
|
+
notifyMenuChanged: (ctx) =>
|
|
42
|
+
openDeliveryMerchantUpdate(ctx, dialect, {
|
|
43
|
+
path: "/v1/merchantUpdate",
|
|
44
|
+
headers: { "X-App-MerchantId": ctx.externalMerchantId },
|
|
45
|
+
}),
|
|
116
46
|
};
|
|
117
47
|
}
|
package/src/99food/copy.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { OPEN_DELIVERY_MERCHANT_REASON_CODES } from "../open-delivery/reasons";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* The words the 99Food adapter needs from its host, and nothing else.
|
|
3
5
|
*
|
|
@@ -6,25 +8,8 @@
|
|
|
6
8
|
* `./en-US`); a host passes one by hand, or its own.
|
|
7
9
|
*/
|
|
8
10
|
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
* v1.7.1 (`RequestCancelled.code`). Pinned by the spec, not estimated. The two
|
|
12
|
-
* codes only the marketplace sends (`CONSUMER_CANCELLATION_REQUESTED`,
|
|
13
|
-
* `OTHER_CANCELLATION_REASON`) are not a store's to choose and are left out.
|
|
14
|
-
*/
|
|
15
|
-
export const NINETY_NINE_FOOD_REASON_CODES = [
|
|
16
|
-
"SYSTEMIC_ISSUES",
|
|
17
|
-
"DUPLICATE_APPLICATION",
|
|
18
|
-
"UNAVAILABLE_ITEM",
|
|
19
|
-
"RESTAURANT_WITHOUT_DELIVERY_PERSON",
|
|
20
|
-
"OUTDATED_MENU",
|
|
21
|
-
"ORDER_OUTSIDE_THE_DELIVERY_AREA",
|
|
22
|
-
"BLOCKED_CUSTOMER",
|
|
23
|
-
"OUTSIDE_DELIVERY_HOURS",
|
|
24
|
-
"INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT",
|
|
25
|
-
"RISK_AREA",
|
|
26
|
-
"DELIVERY_PROBLEM",
|
|
27
|
-
] as const;
|
|
11
|
+
/** The cancellation codes a merchant may send: Open Delivery v1.7.1's (`../open-delivery/reasons.ts`). */
|
|
12
|
+
export const NINETY_NINE_FOOD_REASON_CODES = OPEN_DELIVERY_MERCHANT_REASON_CODES;
|
|
28
13
|
|
|
29
14
|
export type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];
|
|
30
15
|
|
package/src/99food/index.ts
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
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
2
|
import {
|
|
10
3
|
openDeliveryConfirm,
|
|
11
4
|
openDeliveryFetchOrder,
|
|
12
|
-
openDeliveryInformStatus,
|
|
13
5
|
openDeliveryRequestCancellation,
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
} from "
|
|
6
|
+
openDeliveryStatus,
|
|
7
|
+
} from "../open-delivery/orders";
|
|
8
|
+
import { assertHttpsUrl } from "../open-delivery/client";
|
|
9
|
+
import { OPEN_DELIVERY_ITEM_UNAVAILABLE } from "../open-delivery/reasons";
|
|
10
|
+
import { NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterCopy } from "./copy";
|
|
11
|
+
import { openDeliveryCatalogue } from "./catalogue";
|
|
12
|
+
import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from "./normalize";
|
|
13
|
+
import { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from "./outbound";
|
|
17
14
|
import { openDeliveryAvailability } from "./pause";
|
|
18
15
|
|
|
19
16
|
/**
|
|
@@ -21,8 +18,9 @@ import { openDeliveryAvailability } from "./pause";
|
|
|
21
18
|
*
|
|
22
19
|
* 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks
|
|
23
20
|
* Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,
|
|
24
|
-
* confirm, requestCancellation with the spec's codes.
|
|
25
|
-
*
|
|
21
|
+
* confirm, requestCancellation with the spec's codes. The standard's calls
|
|
22
|
+
* and readers are `../open-delivery/`, shared with Keeta; what is 99Food's
|
|
23
|
+
* (its dialect, its copy, its ESTIMATED choices) is under this folder; the engine reaches it only through the
|
|
26
24
|
* {@link MarketplaceAdapter} port, and registering it is the whole cost:
|
|
27
25
|
*
|
|
28
26
|
* ```ts
|
|
@@ -47,8 +45,8 @@ export { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
|
|
|
47
45
|
/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
|
|
48
46
|
export const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
|
|
49
47
|
|
|
50
|
-
/**
|
|
51
|
-
const
|
|
48
|
+
/** 99Food serves `pickedUp` for a take-out (v1.7.1). */
|
|
49
|
+
const STATUS = openDeliveryStatus({ takeoutPickedUp: true });
|
|
52
50
|
|
|
53
51
|
export interface NinetyNineFoodAdapterConfig {
|
|
54
52
|
/** The words the adapter needs: reason labels and the missing-number text. Required. */
|
|
@@ -73,30 +71,26 @@ export interface NinetyNineFoodAdapterConfig {
|
|
|
73
71
|
pauseByStoreSwitch?: boolean;
|
|
74
72
|
}
|
|
75
73
|
|
|
76
|
-
|
|
77
|
-
let parsed: URL;
|
|
78
|
-
try {
|
|
79
|
-
parsed = new URL(url);
|
|
80
|
-
} catch {
|
|
81
|
-
throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);
|
|
82
|
-
}
|
|
83
|
-
if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);
|
|
84
|
-
}
|
|
74
|
+
const assertHttps = (name: string, url: string): void => assertHttpsUrl("@12-apps/marketplace/99food", name, url);
|
|
85
75
|
|
|
86
76
|
/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
|
|
87
77
|
export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {
|
|
88
78
|
assertHttps("apiBaseUrl.SANDBOX", config.apiBaseUrl.SANDBOX);
|
|
89
79
|
assertHttps("apiBaseUrl.PRODUCTION", config.apiBaseUrl.PRODUCTION);
|
|
90
80
|
assertHttps("portalUrl", config.portalUrl);
|
|
91
|
-
const
|
|
81
|
+
const dialect = ninetyNineFoodDialect({ ...config.apiBaseUrl });
|
|
82
|
+
const bases = dialect.bases;
|
|
92
83
|
const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({
|
|
93
84
|
code,
|
|
94
85
|
label: config.copy.reasonLabels[code],
|
|
95
|
-
itemUnavailable: code ===
|
|
96
|
-
// `outOfStockItems` is optional in the spec (see
|
|
86
|
+
itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,
|
|
87
|
+
// `outOfStockItems` is optional in the spec, and not sent (see `cancellation` below).
|
|
97
88
|
needsItems: false,
|
|
98
89
|
}));
|
|
99
90
|
const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };
|
|
91
|
+
const fetchOptions = { normalize: (order: unknown) => normalizeOpenDeliveryOrder(order, normalizeOptions) };
|
|
92
|
+
// `outOfStockItems` wants 99Food's item uuids; the engine keeps SKUs (`externalCode`). Not sent.
|
|
93
|
+
const cancellation = { outOfStockAsSkus: false };
|
|
100
94
|
return {
|
|
101
95
|
provider: NINETY_NINE_FOOD_PROVIDER,
|
|
102
96
|
capabilities: {
|
|
@@ -111,7 +105,7 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
|
|
|
111
105
|
// `OrderConfirmed.preparationTime`, in minutes.
|
|
112
106
|
confirmTakesPreparationTime: true,
|
|
113
107
|
cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
|
|
114
|
-
// Open Delivery's readyForPickup, dispatch and delivered / pickedUp (
|
|
108
|
+
// Open Delivery's readyForPickup, dispatch and delivered / pickedUp (`../open-delivery/orders.ts`).
|
|
115
109
|
statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"],
|
|
116
110
|
},
|
|
117
111
|
normalize: normalizeOpenDeliveryEvent,
|
|
@@ -120,11 +114,12 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
|
|
|
120
114
|
cancellationReasons: () => reasons,
|
|
121
115
|
// PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).
|
|
122
116
|
catalogue: openDeliveryCatalogue(bases),
|
|
123
|
-
fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx,
|
|
124
|
-
confirm: (ctx, order, input) => openDeliveryConfirm(ctx,
|
|
125
|
-
requestCancellation: (ctx, order, input) =>
|
|
126
|
-
|
|
127
|
-
|
|
117
|
+
fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, dialect, order, fetchOptions),
|
|
118
|
+
confirm: (ctx, order, input) => openDeliveryConfirm(ctx, dialect, order, input),
|
|
119
|
+
requestCancellation: (ctx, order, input) =>
|
|
120
|
+
openDeliveryRequestCancellation(ctx, dialect, order, input, cancellation),
|
|
121
|
+
statusSupported: STATUS.supported,
|
|
122
|
+
informStatus: (ctx, order, facts) => STATUS.inform(ctx, dialect, order, facts),
|
|
128
123
|
appLink: () => config.portalUrl,
|
|
129
124
|
...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),
|
|
130
125
|
};
|
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
|
}
|