@12-apps/marketplace 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/ADOPTING.md +9 -4
  2. package/README.md +147 -2
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-BggtVFf9.d.ts → adapter-_iuSxvVD.d.ts} +35 -1
  13. package/dist/{chunk-7BYVGNU5.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-NGNEL4HS.js → chunk-CRYFYDQ2.js} +26 -2
  18. package/dist/chunk-CRYFYDQ2.js.map +1 -0
  19. package/dist/{chunk-DVIRN42O.js → chunk-D2X7TOR6.js} +669 -136
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-KrgZ4pA4.d.ts → engine-D-a4mttc.d.ts} +58 -2
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +7 -11
  25. package/dist/ifood/index.js +10 -60
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +56 -352
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +5 -1
  45. package/src/99food/copy.ts +36 -0
  46. package/src/99food/en-US.ts +19 -0
  47. package/src/99food/index.ts +121 -0
  48. package/src/99food/normalize.ts +263 -0
  49. package/src/99food/outbound.ts +220 -0
  50. package/src/99food/pt-BR.ts +23 -0
  51. package/src/core/adapter.ts +17 -1
  52. package/src/core/decisions.ts +16 -4
  53. package/src/core/engine.ts +8 -0
  54. package/src/core/fetch-order.ts +253 -0
  55. package/src/core/inbox.ts +8 -2
  56. package/src/core/ingest.ts +10 -2
  57. package/src/core/integration.ts +30 -1
  58. package/src/core/order-fetch-marks.ts +63 -0
  59. package/src/core/outbound.ts +22 -2
  60. package/src/core/payload-read.ts +101 -0
  61. package/src/core/pipeline.ts +64 -15
  62. package/src/core/types.ts +14 -0
  63. package/src/ifood/normalize.ts +15 -88
  64. package/src/index.ts +9 -1
  65. package/src/rappi/copy.ts +39 -0
  66. package/src/rappi/en-US.ts +14 -0
  67. package/src/rappi/index.ts +155 -0
  68. package/src/rappi/normalize.ts +314 -0
  69. package/src/rappi/outbound.ts +182 -0
  70. package/src/rappi/pt-BR.ts +18 -0
  71. package/src/server/index.ts +1 -0
  72. package/src/server/jobs.ts +35 -2
  73. package/dist/chunk-7BYVGNU5.js.map +0 -1
  74. package/dist/chunk-DVIRN42O.js.map +0 -1
  75. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The Rappi adapter's pt-BR pack: Rappi's reject types in the words a store
3
+ * reads. A host passes this pack by hand: choosing the language is a line in
4
+ * the host's diff.
5
+ */
6
+ declare const RAPPI_ADAPTER_COPY_PT_BR: {
7
+ readonly reasonLabels: {
8
+ readonly ITEM_OUT_OF_STOCK: "Item indisponível";
9
+ readonly ITEM_NOT_FOUND: "Item não encontrado";
10
+ readonly ITEM_WRONG_PRICE: "Preço do item errado";
11
+ readonly ORDER_MISSING_INFORMATION: "Faltam informações no pedido";
12
+ readonly ORDER_MISSING_ADDRESS_INFORMATION: "Faltam informações do endereço";
13
+ readonly ORDER_TOTAL_INCORRECT: "Total do pedido incorreto";
14
+ };
15
+ readonly missingStreetNumber: "s/n";
16
+ };
17
+
18
+ export { RAPPI_ADAPTER_COPY_PT_BR };
@@ -0,0 +1,18 @@
1
+ import "../chunk-7QVYU63E.js";
2
+
3
+ // src/rappi/pt-BR.ts
4
+ var RAPPI_ADAPTER_COPY_PT_BR = {
5
+ reasonLabels: {
6
+ ITEM_OUT_OF_STOCK: "Item indispon\xEDvel",
7
+ ITEM_NOT_FOUND: "Item n\xE3o encontrado",
8
+ ITEM_WRONG_PRICE: "Pre\xE7o do item errado",
9
+ ORDER_MISSING_INFORMATION: "Faltam informa\xE7\xF5es no pedido",
10
+ ORDER_MISSING_ADDRESS_INFORMATION: "Faltam informa\xE7\xF5es do endere\xE7o",
11
+ ORDER_TOTAL_INCORRECT: "Total do pedido incorreto"
12
+ },
13
+ missingStreetNumber: "s/n"
14
+ };
15
+ export {
16
+ RAPPI_ADAPTER_COPY_PT_BR
17
+ };
18
+ //# sourceMappingURL=pt-BR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rappi/pt-BR.ts"],"sourcesContent":["import type { RappiAdapterCopy } from \"./copy\";\n\n/**\n * The Rappi adapter's pt-BR pack: Rappi's reject types in the words a store\n * reads. A host passes this pack by hand: choosing the language is a line in\n * the host's diff.\n */\nexport const RAPPI_ADAPTER_COPY_PT_BR = {\n reasonLabels: {\n ITEM_OUT_OF_STOCK: \"Item indisponível\",\n ITEM_NOT_FOUND: \"Item não encontrado\",\n ITEM_WRONG_PRICE: \"Preço do item errado\",\n ORDER_MISSING_INFORMATION: \"Faltam informações no pedido\",\n ORDER_MISSING_ADDRESS_INFORMATION: \"Faltam informações do endereço\",\n ORDER_TOTAL_INCORRECT: \"Total do pedido incorreto\",\n },\n missingStreetNumber: \"s/n\",\n} as const satisfies RappiAdapterCopy;\n"],"mappings":";;;AAOO,IAAM,2BAA2B;AAAA,EACtC,cAAc;AAAA,IACZ,mBAAmB;AAAA,IACnB,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,2BAA2B;AAAA,IAC3B,mCAAmC;AAAA,IACnC,uBAAuB;AAAA,EACzB;AAAA,EACA,qBAAqB;AACvB;","names":[]}
@@ -1,7 +1,7 @@
1
- import { h as DecisionProblemCode, b as BulkProblemCode, u as MarketplaceEngine, y as MarketplaceLogger, S as OutboundJobPayload } from '../engine-KrgZ4pA4.js';
1
+ import { h as DecisionProblemCode, b as BulkProblemCode, x as MarketplaceEngine, H as MarketplaceLogger, W as OutboundJobPayload, F as FetchOrderJobPayload } from '../engine-D-a4mttc.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-BggtVFf9.js';
4
+ import '../adapter-_iuSxvVD.js';
5
5
 
6
6
  /** Every problem code a route can answer, decisions and bulk writes alike. */
7
7
  type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
@@ -114,6 +114,9 @@ declare const MARKETPLACE_DECIDE = "marketplace:decide";
114
114
  * - `outbound`, on demand: one call to a marketplace, three attempts with
115
115
  * backoff. Its idempotency is the ROW's (the engine re-reads it), never the
116
116
  * queue's dedupe alone.
117
+ * - `fetch-order`, on demand: one GET of an order a marketplace's event only
118
+ * announced (`orderToFetch`), then the one ingest path. Three attempts with
119
+ * backoff; the reconciliation sweep re-queues a row still owed.
117
120
  * - `outbound-sweep`, every five minutes: re-queues every call a row still
118
121
  * owes (a PENDING request, an accept with no confirm stamp) once it is older
119
122
  * than the job's own retry span, so a refused enqueue or a dead process
@@ -124,16 +127,19 @@ declare const MARKETPLACE_DECIDE = "marketplace:decide";
124
127
  *
125
128
  * Bound with `{ engine }`, these arrive at a runner as
126
129
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
127
- * `marketplace.outbound` and `marketplace.outbound-sweep`.
130
+ * `marketplace.outbound`, `marketplace.fetch-order` and
131
+ * `marketplace.outbound-sweep`.
128
132
  */
129
133
  /** What the host closes over at bind time: the mounted engine. */
130
134
  interface MarketplaceJobDeps {
131
- engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "sweepOutbound">;
135
+ engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "sweepOutbound">;
132
136
  }
133
137
  /** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
134
138
  declare const MARKETPLACE_SWEEP_QUEUE = "sweeps";
135
139
  /** The outbound job's attempts: the last one stamps the failure. */
136
140
  declare const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;
141
+ /** The fetch job's attempts: the last one settles the inbox row FAILED. */
142
+ declare const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;
137
143
  /** The jobs contribution. */
138
144
  declare const MARKETPLACE_JOBS: {
139
145
  readonly namespace: "marketplace";
@@ -141,6 +147,7 @@ declare const MARKETPLACE_JOBS: {
141
147
  readonly "expire-acceptances": WireJobBlueprint<void, MarketplaceJobDeps>;
142
148
  readonly "reconcile-inbox": WireJobBlueprint<void, MarketplaceJobDeps>;
143
149
  readonly outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
150
+ readonly "fetch-order": WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
144
151
  readonly "outbound-sweep": WireJobBlueprint<void, MarketplaceJobDeps>;
145
152
  };
146
153
  };
@@ -526,4 +533,4 @@ interface ApiMarketplace {
526
533
  /** Build the route table over a mounted engine. */
527
534
  declare function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace;
528
535
 
529
- export { type ApiMarketplace, MARKETPLACE_DECIDE, MARKETPLACE_JOBS, MARKETPLACE_MANAGE, MARKETPLACE_MCP_TOOLS, MARKETPLACE_OUTBOUND_ATTEMPTS, MARKETPLACE_PERMISSIONS, MARKETPLACE_SWEEP_QUEUE, type MarketplaceActor, type MarketplaceApiConfig, type MarketplaceJobDeps, type MarketplaceProblemCode, type MarketplaceRoute, type MarketplaceServerCopy, ORDER_NOT_PENDING_CODE, createApiMarketplace, decideMarketplaceOrdersBody, listMarketplaceAcceptancesQuery, listMarketplaceIntegrationsQuery, listMarketplaceMenuLinksQuery, marketplaceParams, upsertMarketplaceIntegrationsBody, upsertMarketplaceMenuLinksBody };
536
+ export { type ApiMarketplace, MARKETPLACE_DECIDE, MARKETPLACE_FETCH_ORDER_ATTEMPTS, MARKETPLACE_JOBS, MARKETPLACE_MANAGE, MARKETPLACE_MCP_TOOLS, MARKETPLACE_OUTBOUND_ATTEMPTS, MARKETPLACE_PERMISSIONS, MARKETPLACE_SWEEP_QUEUE, type MarketplaceActor, type MarketplaceApiConfig, type MarketplaceJobDeps, type MarketplaceProblemCode, type MarketplaceRoute, type MarketplaceServerCopy, ORDER_NOT_PENDING_CODE, createApiMarketplace, decideMarketplaceOrdersBody, listMarketplaceAcceptancesQuery, listMarketplaceIntegrationsQuery, listMarketplaceMenuLinksQuery, marketplaceParams, upsertMarketplaceIntegrationsBody, upsertMarketplaceMenuLinksBody };
@@ -1,10 +1,11 @@
1
1
  import {
2
+ MARKETPLACE_FETCH_ORDER_ATTEMPTS,
2
3
  MARKETPLACE_JOBS,
3
4
  MARKETPLACE_OUTBOUND_ATTEMPTS,
4
5
  MARKETPLACE_SWEEP_QUEUE,
5
6
  ORDER_NOT_PENDING_CODE,
6
7
  createApiMarketplace
7
- } from "../chunk-NGNEL4HS.js";
8
+ } from "../chunk-CRYFYDQ2.js";
8
9
  import {
9
10
  MARKETPLACE_DECIDE,
10
11
  MARKETPLACE_MANAGE,
@@ -18,10 +19,11 @@ import {
18
19
  upsertMarketplaceIntegrationsBody,
19
20
  upsertMarketplaceMenuLinksBody
20
21
  } from "../chunk-UYFYGGCS.js";
21
- import "../chunk-DVIRN42O.js";
22
+ import "../chunk-D2X7TOR6.js";
22
23
  import "../chunk-7QVYU63E.js";
23
24
  export {
24
25
  MARKETPLACE_DECIDE,
26
+ MARKETPLACE_FETCH_ORDER_ATTEMPTS,
25
27
  MARKETPLACE_JOBS,
26
28
  MARKETPLACE_MANAGE,
27
29
  MARKETPLACE_MCP_TOOLS,
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
- "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
6
+ "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
7
7
  "exports": {
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
@@ -21,6 +21,30 @@
21
21
  "types": "./dist/ifood/en-US.d.ts",
22
22
  "default": "./dist/ifood/en-US.js"
23
23
  },
24
+ "./99food": {
25
+ "types": "./dist/99food/index.d.ts",
26
+ "default": "./dist/99food/index.js"
27
+ },
28
+ "./99food/pt-BR": {
29
+ "types": "./dist/99food/pt-BR.d.ts",
30
+ "default": "./dist/99food/pt-BR.js"
31
+ },
32
+ "./99food/en-US": {
33
+ "types": "./dist/99food/en-US.d.ts",
34
+ "default": "./dist/99food/en-US.js"
35
+ },
36
+ "./rappi": {
37
+ "types": "./dist/rappi/index.d.ts",
38
+ "default": "./dist/rappi/index.js"
39
+ },
40
+ "./rappi/pt-BR": {
41
+ "types": "./dist/rappi/pt-BR.d.ts",
42
+ "default": "./dist/rappi/pt-BR.js"
43
+ },
44
+ "./rappi/en-US": {
45
+ "types": "./dist/rappi/en-US.d.ts",
46
+ "default": "./dist/rappi/en-US.js"
47
+ },
24
48
  "./server": {
25
49
  "types": "./dist/server/index.d.ts",
26
50
  "default": "./dist/server/index.js"
@@ -216,13 +216,17 @@ model MarketplaceAcceptance {
216
216
  /// The store's own cancellation request: PENDING (asked here, not
217
217
  /// yet sent) → REQUESTED (the marketplace took the request) → CONFIRMED (it
218
218
  /// cancelled) | FAILED (it refused, or every attempt failed). CHECK in the
219
- /// migration; NULL when the store never asked. CONFIRMED is terminal.
219
+ /// migration; NULL when the store never asked, or when an accept cleared a
220
+ /// FAILED request (`cancellationRequestedAt` then stays as its tombstone).
221
+ /// CONFIRMED is terminal.
220
222
  cancellationStatus String? @map("cancellation_status")
221
223
  /// The marketplace's own reason code the request carries, sent verbatim. Lives on the row, never in a job payload.
222
224
  cancellationReasonCode String? @map("cancellation_reason_code")
223
225
  /// The SKUs the request names, for a reason that needs them (a JSON array).
224
226
  cancellationOffendingSkus Json? @map("cancellation_offending_skus")
225
227
  /// When the request was stamped PENDING: what the outbound sweep ages it by.
228
+ /// With a NULL status it is a TOMBSTONE: the request an accept cleared,
229
+ /// which a synchronous marketplace's late "cancelled" can still match.
226
230
  cancellationRequestedAt DateTime? @map("cancellation_requested_at")
227
231
  /// Why the request FAILED: REFUSED (the marketplace said no, or every
228
232
  /// attempt failed) or TIMEOUT (no answer inside its window). CHECK in the
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The words the 99Food adapter needs from its host, and nothing else.
3
+ *
4
+ * Required and defaultless, like every copy port in this repo: the adapter
5
+ * ships no language of its own. Two packs sit beside it (`./pt-BR`,
6
+ * `./en-US`); a host passes one by hand, or its own.
7
+ */
8
+
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;
28
+
29
+ export type NinetyNineFoodReasonCode = (typeof NINETY_NINE_FOOD_REASON_CODES)[number];
30
+
31
+ export interface NinetyNineFoodAdapterCopy {
32
+ /** One label per reason code. Sent as the request's `reason` text when the store wrote none. */
33
+ reasonLabels: Readonly<Record<NinetyNineFoodReasonCode, string>>;
34
+ /** What an address with no street number says instead. */
35
+ missingStreetNumber: string;
36
+ }
@@ -0,0 +1,19 @@
1
+ import type { NinetyNineFoodAdapterCopy } from "./copy";
2
+
3
+ /** The 99Food adapter's en-US pack: the same reasons, in English. */
4
+ export const NINETY_NINE_FOOD_ADAPTER_COPY_EN_US = {
5
+ reasonLabels: {
6
+ SYSTEMIC_ISSUES: "System problems",
7
+ DUPLICATE_APPLICATION: "Duplicate order",
8
+ UNAVAILABLE_ITEM: "Item unavailable",
9
+ RESTAURANT_WITHOUT_DELIVERY_PERSON: "No courier available",
10
+ OUTDATED_MENU: "Menu out of date",
11
+ ORDER_OUTSIDE_THE_DELIVERY_AREA: "Address outside the delivery area",
12
+ BLOCKED_CUSTOMER: "Blocked customer",
13
+ OUTSIDE_DELIVERY_HOURS: "Outside delivery hours",
14
+ INTERNAL_DIFFICULTIES_OF_THE_RESTAURANT: "Internal difficulties",
15
+ RISK_AREA: "Risk area",
16
+ DELIVERY_PROBLEM: "Delivery problem",
17
+ },
18
+ missingStreetNumber: "no number",
19
+ } as const satisfies NinetyNineFoodAdapterCopy;
@@ -0,0 +1,121 @@
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 { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from "./normalize";
8
+ import {
9
+ openDeliveryConfirm,
10
+ openDeliveryFetchOrder,
11
+ openDeliveryRequestCancellation,
12
+ type NinetyNineFoodApiBaseUrls,
13
+ } from "./outbound";
14
+
15
+ /**
16
+ * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.
17
+ *
18
+ * 99Food completed Open Delivery (Abrasel) adherence, so this adapter speaks
19
+ * Open Delivery v1.7.1: the signed webhook, `CREATED` → fetch the order,
20
+ * confirm, requestCancellation with the spec's codes. Everything 99Food is
21
+ * under this folder; the engine reaches it only through the
22
+ * {@link MarketplaceAdapter} port, and registering it is the whole cost:
23
+ *
24
+ * ```ts
25
+ * import { createNinetyNineFoodAdapter } from "@12-apps/marketplace/99food";
26
+ * import { NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR } from "@12-apps/marketplace/99food/pt-BR";
27
+ *
28
+ * createMarketplaceEngine({
29
+ * …ports,
30
+ * adapters: [
31
+ * createIfoodAdapter({ copy: IFOOD_ADAPTER_COPY_PT_BR }),
32
+ * createNinetyNineFoodAdapter({ copy: NINETY_NINE_FOOD_ADAPTER_COPY_PT_BR, apiBaseUrl, portalUrl }),
33
+ * ],
34
+ * });
35
+ * ```
36
+ *
37
+ * Its webhook is the engine's one route, `POST
38
+ * /webhooks/marketplace/:tenantSlug/NINETY_NINE_FOOD`.
39
+ */
40
+
41
+ export { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
42
+
43
+ /** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
44
+ export const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 60_000;
45
+
46
+ /** The one reason that means "an item is unavailable". */
47
+ const ITEM_UNAVAILABLE: NinetyNineFoodReasonCode = "UNAVAILABLE_ITEM";
48
+
49
+ export interface NinetyNineFoodAdapterConfig {
50
+ /** The words the adapter needs: reason labels and the missing-number text. Required. */
51
+ copy: NinetyNineFoodAdapterCopy;
52
+ /**
53
+ * Where 99Food serves Open Delivery, per environment: the base the spec's
54
+ * paths (`/oauth/token`, `/v1/orders/…`) hang from. Given to a partner at
55
+ * onboarding and not public, so required and defaultless. https only.
56
+ */
57
+ apiBaseUrl: NinetyNineFoodApiBaseUrls;
58
+ /**
59
+ * Where "open it on 99Food" goes: the merchant portal. Open Delivery names no
60
+ * per-order deep link, so the link is the portal. Required; https only.
61
+ */
62
+ portalUrl: string;
63
+ }
64
+
65
+ function assertHttps(name: string, url: string): void {
66
+ let parsed: URL;
67
+ try {
68
+ parsed = new URL(url);
69
+ } catch {
70
+ throw new Error(`@12-apps/marketplace/99food: ${name} is not a URL.`);
71
+ }
72
+ if (parsed.protocol !== "https:") throw new Error(`@12-apps/marketplace/99food: ${name} must be https.`);
73
+ }
74
+
75
+ /** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
76
+ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter {
77
+ assertHttps("apiBaseUrl.SANDBOX", config.apiBaseUrl.SANDBOX);
78
+ assertHttps("apiBaseUrl.PRODUCTION", config.apiBaseUrl.PRODUCTION);
79
+ assertHttps("portalUrl", config.portalUrl);
80
+ const bases = { ...config.apiBaseUrl };
81
+ const reasons: readonly CancellationReason[] = NINETY_NINE_FOOD_REASON_CODES.map((code) => ({
82
+ code,
83
+ label: config.copy.reasonLabels[code],
84
+ itemUnavailable: code === ITEM_UNAVAILABLE,
85
+ // `outOfStockItems` is optional in the spec (see `./outbound.ts`).
86
+ needsItems: false,
87
+ }));
88
+ const normalizeOptions = { missingStreetNumber: config.copy.missingStreetNumber };
89
+ return {
90
+ provider: NINETY_NINE_FOOD_PROVIDER,
91
+ capabilities: {
92
+ apiConfirm: true,
93
+ apiCancel: true,
94
+ // The spec lets a merchant request a cancellation before or after the
95
+ // confirm ("rules may vary depending on the timing"); the answer says.
96
+ cancelAfterAccept: true,
97
+ // 202, then a CANCELLED or CANCELLATION_REQUEST_DENIED event.
98
+ asyncCancellationOutcome: true,
99
+ perOrderAppLink: false,
100
+ // `OrderConfirmed.preparationTime`, in minutes.
101
+ confirmTakesPreparationTime: true,
102
+ cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
103
+ },
104
+ normalize: normalizeOpenDeliveryEvent,
105
+ readSignature: (header) => header("x-app-signature"),
106
+ verifySignature: verifyOpenDeliverySignature,
107
+ cancellationReasons: () => reasons,
108
+ fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
109
+ confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
110
+ requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
111
+ appLink: () => config.portalUrl,
112
+ };
113
+ }
114
+
115
+ export {
116
+ NINETY_NINE_FOOD_REASON_CODES,
117
+ type NinetyNineFoodAdapterCopy,
118
+ type NinetyNineFoodReasonCode,
119
+ } from "./copy";
120
+ export { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from "./normalize";
121
+ export type { NinetyNineFoodApiBaseUrls } from "./outbound";
@@ -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
+ }