@12-apps/marketplace 1.2.0 → 1.4.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 (69) hide show
  1. package/ADOPTING.md +76 -4
  2. package/README.md +163 -3
  3. package/dist/99food/index.d.ts +79 -2
  4. package/dist/99food/index.js +117 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/adapter-B8QtQ2RA.d.ts +612 -0
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-DPCZVN2C.js} +69 -5
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-D2X7TOR6.js → chunk-EBAIZQPB.js} +841 -86
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/chunk-M2V4RFMA.js +23 -0
  12. package/dist/chunk-M2V4RFMA.js.map +1 -0
  13. package/dist/{chunk-24RQZPSV.js → chunk-SZRZTLVU.js} +1 -1
  14. package/dist/chunk-SZRZTLVU.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-o5cm54vC.d.ts} +462 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +22 -2
  19. package/dist/ifood/index.js +396 -56
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +445 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +5 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +62 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +25 -10
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +158 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  35. package/src/99food/catalogue.ts +117 -0
  36. package/src/99food/index.ts +14 -0
  37. package/src/99food/outbound.ts +3 -3
  38. package/src/99food/pause.ts +56 -0
  39. package/src/core/adapter.ts +20 -1
  40. package/src/core/catalogue-category.ts +119 -0
  41. package/src/core/catalogue-ids.ts +23 -0
  42. package/src/core/catalogue-job.ts +332 -0
  43. package/src/core/catalogue-port.ts +173 -0
  44. package/src/core/catalogue-store.ts +172 -0
  45. package/src/core/catalogue-sweep.ts +43 -0
  46. package/src/core/catalogue.ts +226 -0
  47. package/src/core/engine.ts +83 -0
  48. package/src/core/outbound-sweep.ts +7 -2
  49. package/src/core/pause-job.ts +381 -0
  50. package/src/core/pause-port.ts +110 -0
  51. package/src/core/pause-retired.ts +139 -0
  52. package/src/core/pause-store.ts +151 -0
  53. package/src/core/pause-sweep.ts +148 -0
  54. package/src/core/pause.ts +316 -0
  55. package/src/core/ports.ts +47 -0
  56. package/src/ifood/catalogue.ts +273 -0
  57. package/src/ifood/index.ts +8 -0
  58. package/src/ifood/outbound.ts +9 -6
  59. package/src/ifood/pause.ts +257 -0
  60. package/src/index.ts +64 -0
  61. package/src/rappi/index.ts +17 -0
  62. package/src/rappi/outbound.ts +2 -2
  63. package/src/rappi/pause.ts +98 -0
  64. package/src/server/index.ts +1 -0
  65. package/src/server/jobs.ts +100 -10
  66. package/dist/adapter-_iuSxvVD.d.ts +0 -319
  67. package/dist/chunk-24RQZPSV.js.map +0 -1
  68. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  69. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -8,6 +8,7 @@ import {
8
8
  type RappiAmountUnit,
9
9
  } from "./normalize";
10
10
  import { rappiReject, rappiTake, type RappiBaseUrls } from "./outbound";
11
+ import { rappiAvailability } from "./pause";
11
12
 
12
13
  /**
13
14
  * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.
@@ -86,6 +87,14 @@ export interface RappiAdapterConfig {
86
87
  portalUrl: string;
87
88
  /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */
88
89
  amountUnit: RappiAmountUnit;
90
+ /**
91
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Rappi's
92
+ * store on/off switch. A switch has no id, so the engine cannot tell its own
93
+ * closure from one the owner made by hand meanwhile: a store the owner also
94
+ * turned off on Rappi during the kitchen's pause is turned on with it. A
95
+ * host turns this on knowing that.
96
+ */
97
+ pauseByStoreSwitch?: boolean;
89
98
  }
90
99
 
91
100
  function assertHttps(name: string, url: string): void {
@@ -122,6 +131,12 @@ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapt
122
131
  const normalizeOptions = { amountUnit: config.amountUnit, missingStreetNumber: config.copy.missingStreetNumber };
123
132
  return {
124
133
  provider: RAPPI_PROVIDER,
134
+ // No `catalogue` (FUT-4768). Rappi's public menu write, `POST …/menu`,
135
+ // replaces the store's WHOLE menu, goes to an approval, and ignores every
136
+ // further menu while one is in approval: a per-product switch on it would
137
+ // wipe what the store keeps on Rappi's portal and report "in the catalogue"
138
+ // for a menu Rappi may have dropped. Its availability endpoints only turn
139
+ // items Rappi already has on and off. See the README, "Catalogue publishing".
125
140
  capabilities: {
126
141
  apiConfirm: true,
127
142
  apiCancel: true,
@@ -141,6 +156,7 @@ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapt
141
156
  confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),
142
157
  requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),
143
158
  appLink: () => config.portalUrl,
159
+ ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),
144
160
  };
145
161
  }
146
162
 
@@ -153,3 +169,4 @@ export {
153
169
  type RappiNormalizeOptions,
154
170
  } from "./normalize";
155
171
  export type { RappiBaseUrls, RappiHosts } from "./outbound";
172
+ export { rappiAvailability, rappiSetStoreEnabled } from "./pause";
@@ -57,7 +57,7 @@ const TOKEN_MARGIN_MS = 60_000;
57
57
  const DEFAULT_TOKEN_SECONDS = 7 * 24 * 60 * 60;
58
58
 
59
59
  /** A base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
60
- function trimmed(base: string): string {
60
+ export function trimmed(base: string): string {
61
61
  let end = base.length;
62
62
  while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
63
63
  return base.slice(0, end);
@@ -83,7 +83,7 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
83
83
  * (the M2M client credentials). Keyed by environment and client id; memory
84
84
  * only, written to no row or log.
85
85
  */
86
- async function bearer(
86
+ export async function bearer(
87
87
  ctx: AdapterCallContext,
88
88
  hosts: RappiHosts,
89
89
  ): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
@@ -0,0 +1,98 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type OutboundResult,
6
+ } from "../core/adapter";
7
+ import type { MarketplaceAvailability, StorePauseRequest, StorePauseResult } from "../core/pause-port";
8
+ import { RAPPI_PROVIDER } from "./normalize";
9
+ import { bearer, trimmed, type RappiHosts } from "./outbound";
10
+
11
+ /**
12
+ * Rappi's half of the store pause (FUT-4851): a store-wide SWITCH, from
13
+ * Rappi's public developer portal (dev-portal.rappi.com, api-reference
14
+ * "availability", read 2026-11-13):
15
+ *
16
+ * `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`,
17
+ * synchronous, with `{ stores: [{ store_id, is_enabled }] }`; 200 with a
18
+ * `results` array (`store_id`, `is_enabled`, `operation_result`,
19
+ * `operation_result_type`, `operation_result_message`, `suspended_reason`, …),
20
+ * 400, 403 "not allowed to update those stores", 422 too many stores, 502.
21
+ *
22
+ * A switch has no id and no end: the engine turns a store on only when its
23
+ * own record says it turned it off, and turns it on by itself once the
24
+ * kitchen's `until` has passed unrenewed. What it cannot tell apart is a store
25
+ * the owner ALSO closed by hand during the kitchen's pause, which is why the
26
+ * adapter offers this only when the host opts in (`pauseByStoreSwitch`).
27
+ *
28
+ * ESTIMATED: which id `store_id` is (the portal says "the one from your
29
+ * system" for this call; the engine sends the connection's merchant id, the
30
+ * store id Rappi's own events carry), and how a per-store failure reads in
31
+ * `results` (an `operation_result` of `false`, or a `operation_result_type`
32
+ * naming an error, is taken as a refusal with `operation_result_message`).
33
+ */
34
+
35
+ interface RappiStoreResult {
36
+ store_id?: unknown;
37
+ operation_result?: unknown;
38
+ operation_result_type?: unknown;
39
+ operation_result_message?: unknown;
40
+ }
41
+
42
+ /** This store's entry in the answer's `results`, judged; null when the answer names it as done. */
43
+ function refusalIn(body: string, storeId: string): Exclude<OutboundResult, { kind: "accepted" }> | null {
44
+ let results: RappiStoreResult[];
45
+ try {
46
+ const parsed = JSON.parse(body === "" ? "{}" : body) as { results?: unknown };
47
+ results = Array.isArray(parsed.results) ? (parsed.results as RappiStoreResult[]) : [];
48
+ } catch {
49
+ return null;
50
+ }
51
+ const entry = results.find((result) => String(result.store_id) === storeId);
52
+ if (!entry) return null;
53
+ const type = typeof entry.operation_result_type === "string" ? entry.operation_result_type : "";
54
+ const failed = entry.operation_result === false || /error|fail/iu.test(type);
55
+ if (!failed) return null;
56
+ const message = typeof entry.operation_result_message === "string" ? entry.operation_result_message : type;
57
+ return { kind: "refused", status: 200, message: message.slice(0, 300) };
58
+ }
59
+
60
+ const tokenKey = (ctx: AdapterCallContext): string => `${RAPPI_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;
61
+
62
+ /** Turn the store on or off; the answer judged for THIS store. */
63
+ export function rappiSetStoreEnabled(
64
+ ctx: AdapterCallContext,
65
+ hosts: RappiHosts,
66
+ storeId: string,
67
+ enabled: boolean,
68
+ ): Promise<OutboundResult> {
69
+ return answered(async () => {
70
+ const auth = await bearer(ctx, hosts);
71
+ if (!("token" in auth)) return auth;
72
+ const response = await ctx.http({
73
+ method: "PUT",
74
+ url: `${trimmed(hosts.api[ctx.environment])}/availability/stores/enable`,
75
+ headers: { "x-authorization": `Bearer ${auth.token}`, "Content-Type": "application/json" },
76
+ body: JSON.stringify({ stores: [{ store_id: storeId, is_enabled: enabled }] }),
77
+ });
78
+ if (response.status === 401) {
79
+ ctx.tokens.delete(tokenKey(ctx));
80
+ return { kind: "retry", reason: "Rappi refused the token" };
81
+ }
82
+ const result = outboundResultOf(response);
83
+ if (result.kind !== "accepted") return result;
84
+ return refusalIn(response.body, storeId) ?? result;
85
+ });
86
+ }
87
+
88
+ /** Rappi's availability capability: a switch, offered only when the host opts in. */
89
+ export function rappiAvailability(hosts: RappiHosts): MarketplaceAvailability {
90
+ return {
91
+ kind: "switch",
92
+ pause: async (ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> => {
93
+ const result = await rappiSetStoreEnabled(ctx, hosts, request.merchantId, false);
94
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
95
+ },
96
+ resume: (ctx, ref) => rappiSetStoreEnabled(ctx, hosts, ref.merchantId, true),
97
+ };
98
+ }
@@ -36,6 +36,7 @@ export {
36
36
  MARKETPLACE_PERMISSIONS,
37
37
  } from "./contribution";
38
38
  export {
39
+ MARKETPLACE_AVAILABILITY_ATTEMPTS,
39
40
  MARKETPLACE_FETCH_ORDER_ATTEMPTS,
40
41
  MARKETPLACE_JOBS,
41
42
  MARKETPLACE_OUTBOUND_ATTEMPTS,
@@ -1,12 +1,15 @@
1
1
  import type { JobsContribution, WireJobBlueprint } from "@12-apps/wiring";
2
2
 
3
3
  import type { MarketplaceEngine } from "../core/engine";
4
+ import { CatalogueRetryError, type CatalogueJobPayload } from "../core/catalogue-job";
4
5
  import { FetchOrderRetryError, type FetchOrderJobPayload } from "../core/fetch-order";
5
6
  import { OutboundRetryError } from "../core/outbound";
6
7
  import type { OutboundJobPayload } from "../core/outbound-queue";
8
+ import { AvailabilityRetryError } from "../core/pause-job";
9
+ import type { AvailabilityJobPayload } from "../core/pause-store";
7
10
 
8
11
  /**
9
- * The engine's three jobs, declared here because every number in them is the
12
+ * The engine's eight jobs, declared here because every number in them is the
10
13
  * engine's knowledge, not a host's:
11
14
  *
12
15
  * - `expire-acceptances`, every minute: the unit being measured is minutes (a
@@ -21,25 +24,43 @@ import type { OutboundJobPayload } from "../core/outbound-queue";
21
24
  * - `fetch-order`, on demand: one GET of an order a marketplace's event only
22
25
  * announced (`orderToFetch`), then the one ingest path. Three attempts with
23
26
  * backoff; the reconciliation sweep re-queues a row still owed.
27
+ * - `catalogue`, on demand: one publish or withdraw of one product on one
28
+ * marketplace's catalogue (FUT-4768). Three attempts with backoff; the
29
+ * last one stamps FAILED with a failure code.
24
30
  * - `outbound-sweep`, every five minutes: re-queues every call a row still
25
- * owes (a PENDING request, an accept with no confirm stamp) once it is older
26
- * than the job's own retry span, so a refused enqueue or a dead process
27
- * loses nothing.
31
+ * owes (a PENDING request, an accept with no confirm stamp, a catalogue
32
+ * publish or withdraw on its way) once it is older than the job's own retry
33
+ * span, so a refused enqueue or a dead process loses nothing.
34
+ * - `availability`, on demand: brings one marketplace in line with the host's
35
+ * last pause or resume ask for one store (FUT-4851). Three attempts with
36
+ * backoff; the last one stamps FAILED with a failure code.
37
+ * - `availability-sweep`, every five minutes: resumes a pause past its
38
+ * `until` (the host stopped renewing it), re-queues an ask still owed, and
39
+ * gives up on one older than a day.
28
40
  *
29
41
  * What stays the host's: whether to run them at all, on which runtime, and the
30
42
  * lease implementation. A host with no worker declines `jobs` in writing.
31
43
  *
32
44
  * Bound with `{ engine }`, these arrive at a runner as
33
45
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
34
- * `marketplace.outbound`, `marketplace.fetch-order` and
35
- * `marketplace.outbound-sweep`.
46
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,
47
+ * `marketplace.outbound-sweep`, `marketplace.availability` and
48
+ * `marketplace.availability-sweep`.
36
49
  */
37
50
 
38
51
  /** What the host closes over at bind time: the mounted engine. */
39
52
  export interface MarketplaceJobDeps {
40
53
  engine: Pick<
41
54
  MarketplaceEngine,
42
- "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "sweepOutbound"
55
+ | "expireLapsed"
56
+ | "retryable"
57
+ | "reprocess"
58
+ | "runOutbound"
59
+ | "runFetchOrder"
60
+ | "runCatalogue"
61
+ | "sweepOutbound"
62
+ | "runAvailability"
63
+ | "sweepAvailability"
43
64
  >;
44
65
  }
45
66
 
@@ -135,6 +156,30 @@ const fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {
135
156
  },
136
157
  };
137
158
 
159
+ /** The catalogue job's attempts: the last one stamps FAILED. */
160
+ const MARKETPLACE_CATALOGUE_ATTEMPTS = 3;
161
+
162
+ const catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps> = {
163
+ name: "catalogue",
164
+ attempts: MARKETPLACE_CATALOGUE_ATTEMPTS,
165
+ // Short: a person is watching the switch say "sending".
166
+ backoff: { type: "exponential", delayMs: 10_000 },
167
+ handle: async (payload, deps, context) => {
168
+ try {
169
+ const outcome = await deps.engine.runCatalogue(payload, {
170
+ attempt: context.attempt,
171
+ maxAttempts: context.maxAttempts,
172
+ });
173
+ if (outcome.kind === "skipped") {
174
+ context.logger.info(`marketplace.catalogue: ${payload.action} ${payload.publicationId} skipped: ${outcome.reason}`);
175
+ }
176
+ } catch (error) {
177
+ if (error instanceof CatalogueRetryError) context.logger.warn(`marketplace.catalogue: ${error.message}`);
178
+ throw error;
179
+ }
180
+ },
181
+ };
182
+
138
183
  const outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
139
184
  name: "outbound-sweep",
140
185
  queue: MARKETPLACE_SWEEP_QUEUE,
@@ -144,10 +189,52 @@ const outboundSweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
144
189
  lease: { ttlMs: SWEEP_LEASE_MS },
145
190
  handle: async (_payload, deps, context) => {
146
191
  const result = await deps.engine.sweepOutbound();
147
- if (result.requeued === 0 && result.givenUp === 0 && result.timedOut === 0) return;
192
+ const idle = result.requeued + result.givenUp + result.timedOut + result.catalogueRequeued === 0;
193
+ if (idle) return;
194
+ context.logger.info(
195
+ `marketplace.outbound-sweep: re-queued ${result.requeued} call(s) and ${result.catalogueRequeued} catalogue ` +
196
+ `call(s), timed out ${result.timedOut} cancellation request(s), gave up on ${result.givenUp}.`,
197
+ );
198
+ },
199
+ };
200
+
201
+ /** The availability job's attempts: the last one stamps FAILED. */
202
+ export const MARKETPLACE_AVAILABILITY_ATTEMPTS = 3;
203
+
204
+ const availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps> = {
205
+ name: "availability",
206
+ attempts: MARKETPLACE_AVAILABILITY_ATTEMPTS,
207
+ // Short: a store is open on the marketplace while the kitchen is paused.
208
+ backoff: { type: "exponential", delayMs: 10_000 },
209
+ handle: async (payload, deps, context) => {
210
+ try {
211
+ const outcome = await deps.engine.runAvailability(payload, {
212
+ attempt: context.attempt,
213
+ maxAttempts: context.maxAttempts,
214
+ });
215
+ if (outcome.kind === "skipped") {
216
+ context.logger.info(`marketplace.availability: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);
217
+ }
218
+ } catch (error) {
219
+ if (error instanceof AvailabilityRetryError) context.logger.warn(`marketplace.availability: ${error.message}`);
220
+ throw error;
221
+ }
222
+ },
223
+ };
224
+
225
+ const availabilitySweep: WireJobBlueprint<void, MarketplaceJobDeps> = {
226
+ name: "availability-sweep",
227
+ queue: MARKETPLACE_SWEEP_QUEUE,
228
+ concurrency: 1,
229
+ schedule: { pattern: "*/5 * * * *", timezone: "UTC" },
230
+ attempts: 1,
231
+ lease: { ttlMs: SWEEP_LEASE_MS },
232
+ handle: async (_payload, deps, context) => {
233
+ const result = await deps.engine.sweepAvailability();
234
+ if (result.expired + result.requeued + result.givenUp === 0) return;
148
235
  context.logger.info(
149
- `marketplace.outbound-sweep: re-queued ${result.requeued} call(s), timed out ${result.timedOut} ` +
150
- `cancellation request(s), gave up on ${result.givenUp}.`,
236
+ `marketplace.availability-sweep: resumed ${result.expired} expired pause(s), re-queued ${result.requeued}, ` +
237
+ `gave up on ${result.givenUp}.`,
151
238
  );
152
239
  },
153
240
  };
@@ -160,6 +247,9 @@ export const MARKETPLACE_JOBS = {
160
247
  "reconcile-inbox": reconcileInbox,
161
248
  outbound,
162
249
  "fetch-order": fetchOrder,
250
+ catalogue,
163
251
  "outbound-sweep": outboundSweep,
252
+ availability,
253
+ "availability-sweep": availabilitySweep,
164
254
  },
165
255
  } as const satisfies JobsContribution<MarketplaceJobDeps>;
@@ -1,319 +0,0 @@
1
- /**
2
- * The canonical shape every marketplace adapter normalizes INTO.
3
- *
4
- * This type is the seam. The engine below it knows no marketplace by name: a
5
- * marketplace is an adapter registered with the engine (`./adapter`), and the
6
- * provider id is whatever that adapter says it is. A second marketplace is a
7
- * second adapter, never a second pipeline, a second acceptance clock or a
8
- * second idea of what an order is.
9
- *
10
- * Deliberately POORER than any marketplace's own payload. Everything a store
11
- * operates on is here; everything else stays in the inbox row's raw `payload`,
12
- * which is where a normalization bug is reconstructed from.
13
- */
14
- /**
15
- * A marketplace's id, as its adapter declares it (`"IFOOD"`). Uppercase
16
- * letters, digits and underscores; the migration's CHECK holds the same shape.
17
- * A string rather than a closed union, because the set of marketplaces is the
18
- * set of registered adapters, and a union would make a new one a code change
19
- * in the engine.
20
- */
21
- type MarketplaceProvider = string;
22
- /** The shape a provider id must have. Shared by the registry and the CHECK. */
23
- declare const PROVIDER_ID_PATTERN: RegExp;
24
- /** One line of an incoming order, before it is resolved against the catalog. */
25
- interface NormalizedOrderLine {
26
- /** The marketplace's own SKU — the key the SKU map is matched on. */
27
- externalSku: string;
28
- /** What the marketplace called it. Snapshotted, and the fallback line text. */
29
- name: string;
30
- quantity: number;
31
- /**
32
- * Unit price in the smallest currency unit AS THE MARKETPLACE STATES IT. A
33
- * marketplace's menu carries its own prices, and the buyer's receipt is the
34
- * marketplace's one: re-pricing from the host's catalog would produce a
35
- * total nobody was charged.
36
- */
37
- unitPriceCents: number;
38
- /** The buyer's note on this line, when they left one. */
39
- note: string | null;
40
- }
41
- /** The buyer, as much of them as the marketplace discloses. */
42
- interface NormalizedBuyer {
43
- /** The marketplace's own stable id for this customer, when it gives one. */
44
- externalId: string | null;
45
- name: string | null;
46
- phone: string | null;
47
- }
48
- /** Where a delivery goes, as much of it as the marketplace states. */
49
- interface NormalizedAddress {
50
- street: string;
51
- number: string;
52
- neighborhood: string;
53
- complement: string | null;
54
- /** The sentence that finds the door. */
55
- reference: string | null;
56
- postalCode: string | null;
57
- city: string | null;
58
- state: string | null;
59
- }
60
- /** How the order reaches the buyer: brought to the door, or collected. */
61
- type MarketplaceOrderType = "DELIVERY" | "TAKEOUT";
62
- /** WHO carries a delivery: the merchant's own courier, or the marketplace's fleet. */
63
- type MarketplaceDeliveredBy = "MERCHANT" | "MARKETPLACE";
64
- /** An incoming marketplace order, normalized. */
65
- interface NormalizedMarketplaceOrder {
66
- provider: MarketplaceProvider;
67
- /** The marketplace's order id — THE idempotency key for the whole pipeline. */
68
- externalOrderId: string;
69
- /** The short code the courier and the buyer say out loud. */
70
- externalDisplayId: string | null;
71
- buyer: NormalizedBuyer;
72
- lines: NormalizedOrderLine[];
73
- /**
74
- * What the buyer paid, gross. NOT derived from the lines when the
75
- * marketplace states it: its total carries fees, promotions and rounding the
76
- * line sum does not, and the number that must match the receipt is this one.
77
- */
78
- totalCents: number;
79
- /** The marketplace's cut, when it states one. NULL is "did not say", not 0. */
80
- commissionCents: number | null;
81
- /** The marketplace's own promise to the buyer. */
82
- deliveryDueAt: Date | null;
83
- /** When the marketplace says the order was placed. */
84
- placedAt: Date;
85
- /** Null when the payload does not say. */
86
- orderType?: MarketplaceOrderType | null;
87
- /** Null on a take-out and when unstated. */
88
- deliveredBy?: MarketplaceDeliveredBy | null;
89
- /** Null on a take-out and when unstated. */
90
- deliveryAddress?: NormalizedAddress | null;
91
- /**
92
- * OPTIONAL. The merchant the order names, when its body says (Open
93
- * Delivery's `merchant.id`). A fetched order naming another merchant than
94
- * the connection's is refused.
95
- */
96
- externalMerchantId?: string | null;
97
- }
98
- /**
99
- * What an event says about the STORE's own cancellation request: `CONFIRMED`
100
- * when the marketplace cancelled the order (a pending request is answered),
101
- * `FAILED` when it refused the request.
102
- */
103
- type CancellationOutcome = "CONFIRMED" | "FAILED";
104
- /** What an adapter makes of one inbound delivery. */
105
- interface NormalizedEvent {
106
- provider: MarketplaceProvider;
107
- /** The delivery's own id — the inbox dedup key, paired with the provider. */
108
- eventId: string;
109
- /** The provider's event type verbatim, kept for the inbox row and the log. */
110
- eventType: string;
111
- /** The merchant this event names, used to attribute it to a tenant. */
112
- externalMerchantId: string | null;
113
- externalOrderId: string | null;
114
- /**
115
- * The order this event carries, or null when the event is one the engine
116
- * understands and does not ingest. A null here is an IGNORED inbox row (or a
117
- * cancellation, below), never a failure.
118
- */
119
- order: NormalizedMarketplaceOrder | null;
120
- /** The marketplace has CANCELLED the order. */
121
- cancelled: boolean;
122
- /**
123
- * The answer to the store's own cancellation request, when this event is
124
- * one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
125
- */
126
- cancellationOutcome?: CancellationOutcome | null;
127
- /**
128
- * OPTIONAL. This event announces an order whose body the marketplace serves
129
- * separately (Open Delivery's `CREATED` carries only the order's id): the
130
- * engine fetches it through the adapter's `fetchOrder`, in the
131
- * `marketplace.fetch-order` job, never inside the request that delivered
132
- * the event. Ignored when `order` is present.
133
- */
134
- orderToFetch?: boolean;
135
- }
136
-
137
- /**
138
- * The adapter port: everything one marketplace is, behind one shape.
139
- *
140
- * The owner's rule, which this file exists to make true: "the integration
141
- * engine must be the same for all integrations: iFood, Rappi, 99. Only an
142
- * adapter is made for each one, to connect to the base engine."
143
- *
144
- * A marketplace differs from the next in five ways that matter to a store:
145
- * how its deliveries look and are signed (`normalize`, `readSignature`,
146
- * `verifySignature`), what it lets a store answer through its API (`confirm`,
147
- * `requestCancellation`), which reasons a refusal may carry
148
- * (`cancellationReasons`), and where a person goes when the API cannot do it
149
- * (`appLink`). Everything else — the inbox, the clock, the SKU map, the
150
- * outbound bookkeeping and its retries — is the engine's and does not change
151
- * with the marketplace.
152
- *
153
- * What a marketplace CAN do is stated by its adapter as
154
- * {@link MarketplaceCapabilities} and read by the engine and the host. It is
155
- * never inferred from the provider's id: a branch on the id outside an adapter
156
- * would make the next marketplace a code change instead of an adapter.
157
- *
158
- * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every
159
- * outbound call. An adapter never reaches the network on its own, so tests
160
- * answer the seam and nothing else, and the host owns the timeout, the proxy
161
- * and the CA.
162
- */
163
- /** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */
164
- interface MarketplaceCredentials {
165
- clientId: string;
166
- clientSecret: string;
167
- /**
168
- * The shared secret a delivery's signature is verified against. Separate
169
- * from the OAuth pair: a merchant rotating their webhook secret has not
170
- * re-onboarded.
171
- */
172
- webhookSecret: string | null;
173
- }
174
- /** What the host's HTTP client takes. */
175
- interface MarketplaceHttpRequest {
176
- method: "GET" | "POST" | "PUT";
177
- url: string;
178
- headers: Record<string, string>;
179
- body?: string;
180
- }
181
- /** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */
182
- interface MarketplaceHttpResponse {
183
- status: number;
184
- body: string;
185
- }
186
- /** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */
187
- type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;
188
- /** What a marketplace can do, stated by its adapter. */
189
- interface MarketplaceCapabilities {
190
- /** Accepting is answered through the API. */
191
- apiConfirm: boolean;
192
- /** A cancellation can be requested through the API at all. */
193
- apiCancel: boolean;
194
- /** …and still once the order was accepted. */
195
- cancelAfterAccept: boolean;
196
- /** The cancellation's outcome arrives later as an event rather than in the answer. */
197
- asyncCancellationOutcome: boolean;
198
- /** `appLink` names this order, rather than only the marketplace's portal. */
199
- perOrderAppLink: boolean;
200
- /** Confirming states a preparation time. */
201
- confirmTakesPreparationTime: boolean;
202
- /**
203
- * OPTIONAL. How long the marketplace takes, at most, to answer a store's
204
- * cancellation request, in milliseconds: past it the outbound sweep fails
205
- * the request as TIMEOUT. Absent: only the 24-hour give-up applies.
206
- */
207
- cancellationAnswerWindowMs?: number;
208
- }
209
- /** One reason a store may give for refusing or cancelling an order. */
210
- interface CancellationReason {
211
- /** The marketplace's own code, sent verbatim. */
212
- code: string;
213
- /** The label the host was configured with for this code (a named pack). */
214
- label: string;
215
- /** This reason means "an item is unavailable": the host preselects it when stock is short. */
216
- itemUnavailable: boolean;
217
- /** The marketplace requires the offending SKUs with this reason. */
218
- needsItems: boolean;
219
- }
220
- /** The order an outbound call is about, as the engine knows it. */
221
- interface OutboundOrderRef {
222
- externalOrderId: string;
223
- externalDisplayId: string | null;
224
- /** The host's own id for the order. */
225
- hostOrderCode: string;
226
- /** When the engine recorded the order. */
227
- placedAt: Date;
228
- }
229
- /** A per-engine token cache an adapter reads and fills. Never persisted. */
230
- type AdapterTokenCache = Map<string, {
231
- token: string;
232
- expiresAt: number;
233
- }>;
234
- /** What one outbound call is handed. */
235
- interface AdapterCallContext {
236
- http: MarketplaceHttp;
237
- credentials: MarketplaceCredentials;
238
- environment: "SANDBOX" | "PRODUCTION";
239
- /** Written to no row, log or audit entry: memory only, per process. */
240
- tokens: AdapterTokenCache;
241
- now: Date;
242
- }
243
- /** One outbound call's answer, in the three shapes the engine acts on. */
244
- type OutboundResult =
245
- /** 2xx. For a marketplace whose outcome is asynchronous, "the request was taken". */
246
- {
247
- kind: "accepted";
248
- }
249
- /** A final 4xx (not 408/425/429): never retried. */
250
- | {
251
- kind: "refused";
252
- status: number;
253
- message: string;
254
- }
255
- /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */
256
- | {
257
- kind: "retry";
258
- reason: string;
259
- };
260
- /**
261
- * One order-body fetch's answer: the order, normalized, or the same refusal and
262
- * retry shapes an outbound call answers with (a 404 for an expired order is a
263
- * refusal; a 5xx, a timeout or a 429 is a retry).
264
- */
265
- type FetchOrderResult = {
266
- kind: "order";
267
- order: NormalizedMarketplaceOrder;
268
- } | Exclude<OutboundResult, {
269
- kind: "accepted";
270
- }>;
271
- /** What a cancellation request carries. */
272
- interface CancellationRequestInput {
273
- reason: CancellationReason;
274
- /** Free text from the store; empty means "the reason's own label". */
275
- text: string;
276
- mode: "MANUAL" | "AUTO";
277
- offendingSkus: readonly string[];
278
- }
279
- /** One marketplace, in and out. */
280
- interface MarketplaceAdapter {
281
- readonly provider: MarketplaceProvider;
282
- readonly capabilities: MarketplaceCapabilities;
283
- /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */
284
- normalize(payload: unknown): NormalizedEvent | null;
285
- /** Which header carries this marketplace's signature, read off the request. */
286
- readSignature(header: (name: string) => string | null): string | null;
287
- /** Is this delivery's signature the one this store's secret would produce? */
288
- verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;
289
- /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */
290
- cancellationReasons(): readonly CancellationReason[];
291
- /** Tell the marketplace the store accepted the order. */
292
- confirm(ctx: AdapterCallContext, order: OutboundOrderRef, input: {
293
- preparationMinutes: number | null;
294
- }): Promise<OutboundResult>;
295
- /** Ask the marketplace to cancel the order, with one of its own reasons. */
296
- requestCancellation(ctx: AdapterCallContext, order: OutboundOrderRef, input: CancellationRequestInput): Promise<OutboundResult>;
297
- /**
298
- * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
299
- * marketplace whose events carry no order body). Called only from the
300
- * `marketplace.fetch-order` job. An adapter whose events always carry the
301
- * order (iFood) leaves it out.
302
- */
303
- fetchOrder?(ctx: AdapterCallContext, order: {
304
- externalOrderId: string;
305
- }): Promise<FetchOrderResult>;
306
- /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
307
- appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
308
- }
309
- /**
310
- * Read one HTTP answer the way the engine acts on it. Shared by every adapter
311
- * whose API speaks plain status codes, so the rule is one rule rather than one
312
- * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and
313
- * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.
314
- */
315
- declare function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult;
316
- /** A call that never got an answer is a retry, with the reason a log can read. */
317
- declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
318
-
319
- export { type AdapterCallContext as A, type CancellationReason as C, type FetchOrderResult as F, type MarketplaceAdapter as M, type NormalizedEvent as N, type OutboundOrderRef as O, PROVIDER_ID_PATTERN as P, type NormalizedMarketplaceOrder as a, type MarketplaceProvider as b, type AdapterTokenCache as c, type CancellationOutcome as d, type CancellationRequestInput as e, type MarketplaceCapabilities as f, type MarketplaceCredentials as g, type MarketplaceDeliveredBy as h, type MarketplaceHttp as i, type MarketplaceHttpRequest as j, type MarketplaceHttpResponse as k, type MarketplaceOrderType as l, type NormalizedAddress as m, type NormalizedBuyer as n, type NormalizedOrderLine as o, type OutboundResult as p, answered as q, outboundResultOf as r };