@12-apps/marketplace 1.7.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.
Files changed (96) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +153 -3
  3. package/dist/99food/index.d.ts +30 -52
  4. package/dist/99food/index.js +62 -391
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/chunk-PYHNM47K.js +478 -0
  16. package/dist/chunk-PYHNM47K.js.map +1 -0
  17. package/dist/client-B4EQCRD_.d.ts +20 -0
  18. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  19. package/dist/hono/index.d.ts +2 -2
  20. package/dist/hono/index.js +3 -3
  21. package/dist/ifood/index.d.ts +1 -1
  22. package/dist/ifood/index.js +29 -3
  23. package/dist/ifood/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +104 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/keeta/en-US.d.ts +19 -0
  28. package/dist/keeta/en-US.js +23 -0
  29. package/dist/keeta/en-US.js.map +1 -0
  30. package/dist/keeta/index.d.ts +253 -0
  31. package/dist/keeta/index.js +388 -0
  32. package/dist/keeta/index.js.map +1 -0
  33. package/dist/keeta/pt-BR.d.ts +23 -0
  34. package/dist/keeta/pt-BR.js +23 -0
  35. package/dist/keeta/pt-BR.js.map +1 -0
  36. package/dist/manifest/index.d.ts +3 -0
  37. package/dist/manifest/index.js +1 -1
  38. package/dist/manifest/server.d.ts +2 -2
  39. package/dist/manifest/server.js +3 -3
  40. package/dist/rappi/index.d.ts +7 -1
  41. package/dist/rappi/index.js +20 -3
  42. package/dist/rappi/index.js.map +1 -1
  43. package/dist/server/index.d.ts +6 -2
  44. package/dist/server/index.js +3 -3
  45. package/package.json +14 -2
  46. package/prisma/marketplace.prisma +45 -1
  47. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  48. package/src/99food/catalogue.ts +19 -89
  49. package/src/99food/copy.ts +4 -19
  50. package/src/99food/index.ts +29 -28
  51. package/src/99food/normalize.ts +11 -247
  52. package/src/99food/outbound.ts +29 -215
  53. package/src/99food/pause.ts +7 -22
  54. package/src/core/adapter.ts +41 -1
  55. package/src/core/bulk.ts +1 -1
  56. package/src/core/engine.ts +9 -0
  57. package/src/core/ingest.ts +6 -0
  58. package/src/core/integration.ts +17 -0
  59. package/src/core/lifecycle-port.ts +16 -0
  60. package/src/core/lifecycle.ts +133 -0
  61. package/src/core/outbound-queue.ts +24 -4
  62. package/src/core/outbound-sweep.ts +49 -5
  63. package/src/core/outbound.ts +11 -0
  64. package/src/core/pipeline.ts +22 -2
  65. package/src/core/ports.ts +39 -3
  66. package/src/core/status-inform.ts +51 -0
  67. package/src/core/status-job.ts +207 -0
  68. package/src/core/status-store.ts +85 -0
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +7 -1
  71. package/src/ifood/normalize.ts +17 -0
  72. package/src/ifood/outbound.ts +35 -0
  73. package/src/index.ts +8 -1
  74. package/src/keeta/authorization.ts +226 -0
  75. package/src/keeta/copy.ts +27 -0
  76. package/src/keeta/en-US.ts +19 -0
  77. package/src/keeta/index.ts +162 -0
  78. package/src/keeta/merchant.ts +70 -0
  79. package/src/keeta/normalize.ts +131 -0
  80. package/src/keeta/outbound.ts +55 -0
  81. package/src/keeta/pt-BR.ts +23 -0
  82. package/src/keeta/signature.ts +85 -0
  83. package/src/open-delivery/client.ts +185 -0
  84. package/src/open-delivery/merchant.ts +126 -0
  85. package/src/open-delivery/normalize.ts +269 -0
  86. package/src/open-delivery/orders.ts +241 -0
  87. package/src/open-delivery/reasons.ts +26 -0
  88. package/src/rappi/index.ts +6 -1
  89. package/src/rappi/normalize.ts +6 -0
  90. package/src/rappi/outbound.ts +31 -2
  91. package/src/server/mcp.ts +2 -0
  92. package/src/server/webhook.ts +3 -1
  93. package/dist/chunk-L3DCOZUU.js.map +0 -1
  94. package/dist/chunk-SJUKBCVO.js.map +0 -1
  95. package/dist/chunk-UYFYGGCS.js.map +0 -1
  96. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -1,7 +1,6 @@
1
- import { answered, outboundResultOf, type OutboundResult } from "../core/adapter";
2
- import { stableUuid } from "../core/catalogue-ids";
3
- import type { CatalogueCallContext, CatalogueMenuEntry, CatalogueMenuOptions, PullCatalogue } from "../core/catalogue-port";
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` (the price lives on the offer), and the ORDERING APPLICATION
13
- * (99Food) pulls it, again when its `TTL` runs out or when told the merchant
14
- * changed (`POST /v1/merchantUpdate`, sent with an empty body: "pull
15
- * everything again"). Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml
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; the host merges it
19
- * into the rest of the `Merchant`, which is its own: `basicInfo`, `services`,
20
- * `lastUpdate`, `TTL`, `status`), and tell 99Food the menu changed
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
- /** One category per host category name, in first-seen order. */
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
- notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),
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
  }
@@ -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
- * The cancellation codes a merchant may send, verbatim from Open Delivery
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
 
@@ -1,17 +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
5
  openDeliveryRequestCancellation,
13
- type NinetyNineFoodApiBaseUrls,
14
- } from "./outbound";
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";
15
14
  import { openDeliveryAvailability } from "./pause";
16
15
 
17
16
  /**
@@ -19,8 +18,9 @@ import { openDeliveryAvailability } from "./pause";
19
18
  *
20
19
  * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks
21
20
  * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,
22
- * confirm, requestCancellation with the spec's codes. Everything 99Food is
23
- * under this folder; the engine reaches it only through the
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
24
24
  * {@link MarketplaceAdapter} port, and registering it is the whole cost:
25
25
  *
26
26
  * ```ts
@@ -45,8 +45,8 @@ export { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
45
45
  /** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
46
46
  export const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
47
47
 
48
- /** The one reason that means "an item is unavailable". */
49
- const ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = "UNAVAILABLE_ITEM";
48
+ /** 99Food serves `pickedUp` for a take-out (v1.7.1). */
49
+ const STATUS = openDeliveryStatus({ takeoutPickedUp: true });
50
50
 
51
51
  export interface NinetyNineFoodAdapterConfig {
52
52
  /** The words the adapter needs: reason labels and the missing-number text. Required. */
@@ -71,30 +71,26 @@ export interface NinetyNineFoodAdapterConfig {
71
71
  pauseByStoreSwitch?: boolean;
72
72
  }
73
73
 
74
- function assertHttps(name: string, url: string): void {
75
- let parsed: URL;
76
- try {
77
- parsed = new URL(url);
78
- } catch {
79
- throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);
80
- }
81
- if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);
82
- }
74
+ const assertHttps = (name: string, url: string): void => assertHttpsUrl("@12-apps/marketplace/99food", name, url);
83
75
 
84
76
  /** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
85
77
  export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {
86
78
  assertHttps("apiBaseUrl.SANDBOX", config.apiBaseUrl.SANDBOX);
87
79
  assertHttps("apiBaseUrl.PRODUCTION", config.apiBaseUrl.PRODUCTION);
88
80
  assertHttps("portalUrl", config.portalUrl);
89
- const bases = { ...config.apiBaseUrl };
81
+ const dialect = ninetyNineFoodDialect({ ...config.apiBaseUrl });
82
+ const bases = dialect.bases;
90
83
  const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({
91
84
  code,
92
85
  label: config.copy.reasonLabels[code],
93
- itemUnavailable: code === ITEM_UNAVAILABLE,
94
- // `outOfStockItems` is optional in the spec (see `./outbound.ts`).
86
+ itemUnavailable: code === OPEN_DELIVERY_ITEM_UNAVAILABLE,
87
+ // `outOfStockItems` is optional in the spec, and not sent (see `cancellation` below).
95
88
  needsItems: false,
96
89
  }));
97
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 };
98
94
  return {
99
95
  provider: NINETY_NINE_FOOD_PROVIDER,
100
96
  capabilities: {
@@ -109,6 +105,8 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
109
105
  // `OrderConfirmed.preparationTime`, in minutes.
110
106
  confirmTakesPreparationTime: true,
111
107
  cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
108
+ // Open Delivery's readyForPickup, dispatch and delivered / pickedUp (`../open-delivery/orders.ts`).
109
+ statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"],
112
110
  },
113
111
  normalize: normalizeOpenDeliveryEvent,
114
112
  readSignature: (header) => header("x-app-signature"),
@@ -116,9 +114,12 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
116
114
  cancellationReasons: () => reasons,
117
115
  // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).
118
116
  catalogue: openDeliveryCatalogue(bases),
119
- fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
120
- confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
121
- requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
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),
122
123
  appLink: () => config.portalUrl,
123
124
  ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),
124
125
  };
@@ -1,263 +1,27 @@
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";
1
+ import type { NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
2
+ import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../open-delivery/normalize";
18
3
 
19
4
  /**
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).
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.
33
9
  */
34
10
 
35
11
  /** The provider id 99Food is registered under. Uppercase: the column's CHECK holds that shape. */
36
12
  export const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
37
13
 
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";
14
+ export { verifyOpenDeliverySignature } from "../open-delivery/normalize";
44
15
 
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
- */
16
+ /** Normalize one webhook `Event` (see `normalizeOpenDeliveryEventAs`). Null only when it names no order. */
78
17
  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;
18
+ return normalizeOpenDeliveryEventAs(NINETY_NINE_FOOD_PROVIDER, payload);
145
19
  }
146
20
 
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
- */
21
+ /** Normalize one `Order` (see `normalizeOpenDeliveryOrderAs`). Null when it carries no id or no line. */
227
22
  export function normalizeOpenDeliveryOrder(
228
23
  order: unknown,
229
24
  options: { missingStreetNumber: string },
230
25
  ): 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
- };
26
+ return normalizeOpenDeliveryOrderAs(NINETY_NINE_FOOD_PROVIDER, order, options);
263
27
  }