@12-apps/marketplace 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/ADOPTING.md +37 -7
  2. package/README.md +238 -4
  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 +162 -0
  7. package/dist/99food/index.js +444 -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-0l_EmuJA.d.ts} +206 -2
  13. package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
  14. package/dist/chunk-AYYBRQJV.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-M2V4RFMA.js +23 -0
  18. package/dist/chunk-M2V4RFMA.js.map +1 -0
  19. package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
  20. package/dist/chunk-RVBTARIY.js.map +1 -0
  21. package/dist/chunk-XUAFXNOH.js +1604 -0
  22. package/dist/chunk-XUAFXNOH.js.map +1 -0
  23. package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
  24. package/dist/hono/index.d.ts +2 -2
  25. package/dist/hono/index.js +2 -2
  26. package/dist/ifood/index.d.ts +16 -12
  27. package/dist/ifood/index.js +248 -121
  28. package/dist/ifood/index.js.map +1 -1
  29. package/dist/index.d.ts +30 -4
  30. package/dist/index.js +189 -346
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +4 -2
  33. package/dist/manifest/server.js +2 -2
  34. package/dist/rappi/en-US.d.ts +14 -0
  35. package/dist/rappi/en-US.js +18 -0
  36. package/dist/rappi/en-US.js.map +1 -0
  37. package/dist/rappi/index.d.ts +190 -0
  38. package/dist/rappi/index.js +359 -0
  39. package/dist/rappi/index.js.map +1 -0
  40. package/dist/rappi/pt-BR.d.ts +18 -0
  41. package/dist/rappi/pt-BR.js +18 -0
  42. package/dist/rappi/pt-BR.js.map +1 -0
  43. package/dist/server/index.d.ts +19 -8
  44. package/dist/server/index.js +4 -2
  45. package/package.json +26 -2
  46. package/prisma/marketplace.prisma +97 -2
  47. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  48. package/src/99food/catalogue.ts +117 -0
  49. package/src/99food/copy.ts +36 -0
  50. package/src/99food/en-US.ts +19 -0
  51. package/src/99food/index.ts +125 -0
  52. package/src/99food/normalize.ts +263 -0
  53. package/src/99food/outbound.ts +220 -0
  54. package/src/99food/pt-BR.ts +23 -0
  55. package/src/core/adapter.ts +27 -2
  56. package/src/core/catalogue-category.ts +119 -0
  57. package/src/core/catalogue-ids.ts +23 -0
  58. package/src/core/catalogue-job.ts +332 -0
  59. package/src/core/catalogue-port.ts +173 -0
  60. package/src/core/catalogue-store.ts +172 -0
  61. package/src/core/catalogue-sweep.ts +43 -0
  62. package/src/core/catalogue.ts +226 -0
  63. package/src/core/decisions.ts +16 -4
  64. package/src/core/engine.ts +54 -0
  65. package/src/core/fetch-order.ts +253 -0
  66. package/src/core/inbox.ts +8 -2
  67. package/src/core/ingest.ts +10 -2
  68. package/src/core/integration.ts +30 -1
  69. package/src/core/order-fetch-marks.ts +63 -0
  70. package/src/core/outbound-sweep.ts +7 -2
  71. package/src/core/outbound.ts +22 -2
  72. package/src/core/payload-read.ts +101 -0
  73. package/src/core/pipeline.ts +64 -15
  74. package/src/core/ports.ts +36 -0
  75. package/src/core/types.ts +14 -0
  76. package/src/ifood/catalogue.ts +273 -0
  77. package/src/ifood/index.ts +4 -0
  78. package/src/ifood/normalize.ts +15 -88
  79. package/src/ifood/outbound.ts +9 -6
  80. package/src/index.ts +49 -1
  81. package/src/rappi/copy.ts +39 -0
  82. package/src/rappi/en-US.ts +14 -0
  83. package/src/rappi/index.ts +161 -0
  84. package/src/rappi/normalize.ts +314 -0
  85. package/src/rappi/outbound.ts +182 -0
  86. package/src/rappi/pt-BR.ts +18 -0
  87. package/src/server/index.ts +1 -0
  88. package/src/server/jobs.ts +71 -8
  89. package/dist/chunk-7BYVGNU5.js.map +0 -1
  90. package/dist/chunk-DVIRN42O.js +0 -707
  91. package/dist/chunk-DVIRN42O.js.map +0 -1
  92. 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 { u as DecisionProblemCode, b as BulkProblemCode, U as MarketplaceEngine, Y as MarketplaceLogger, a9 as OutboundJobPayload, F as FetchOrderJobPayload, j as CatalogueJobPayload } from '../engine-CZsP8KWd.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-BggtVFf9.js';
4
+ import '../adapter-0l_EmuJA.js';
5
5
 
6
6
  /** Every problem code a route can answer, decisions and bulk writes alike. */
7
7
  type MarketplaceProblemCode = DecisionProblemCode | BulkProblemCode;
@@ -114,26 +114,35 @@ 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.
120
+ * - `catalogue`, on demand: one publish or withdraw of one product on one
121
+ * marketplace's catalogue (FUT-4768). Three attempts with backoff; the
122
+ * last one stamps FAILED with a failure code.
117
123
  * - `outbound-sweep`, every five minutes: re-queues every call a row still
118
- * owes (a PENDING request, an accept with no confirm stamp) once it is older
119
- * than the job's own retry span, so a refused enqueue or a dead process
120
- * loses nothing.
124
+ * owes (a PENDING request, an accept with no confirm stamp, a catalogue
125
+ * publish or withdraw on its way) once it is older than the job's own retry
126
+ * span, so a refused enqueue or a dead process loses nothing.
121
127
  *
122
128
  * What stays the host's: whether to run them at all, on which runtime, and the
123
129
  * lease implementation. A host with no worker declines `jobs` in writing.
124
130
  *
125
131
  * Bound with `{ engine }`, these arrive at a runner as
126
132
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
127
- * `marketplace.outbound` and `marketplace.outbound-sweep`.
133
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`
134
+ * and `marketplace.outbound-sweep`.
128
135
  */
129
136
  /** What the host closes over at bind time: the mounted engine. */
130
137
  interface MarketplaceJobDeps {
131
- engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "sweepOutbound">;
138
+ engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runCatalogue" | "sweepOutbound">;
132
139
  }
133
140
  /** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
134
141
  declare const MARKETPLACE_SWEEP_QUEUE = "sweeps";
135
142
  /** The outbound job's attempts: the last one stamps the failure. */
136
143
  declare const MARKETPLACE_OUTBOUND_ATTEMPTS = 3;
144
+ /** The fetch job's attempts: the last one settles the inbox row FAILED. */
145
+ declare const MARKETPLACE_FETCH_ORDER_ATTEMPTS = 3;
137
146
  /** The jobs contribution. */
138
147
  declare const MARKETPLACE_JOBS: {
139
148
  readonly namespace: "marketplace";
@@ -141,6 +150,8 @@ declare const MARKETPLACE_JOBS: {
141
150
  readonly "expire-acceptances": WireJobBlueprint<void, MarketplaceJobDeps>;
142
151
  readonly "reconcile-inbox": WireJobBlueprint<void, MarketplaceJobDeps>;
143
152
  readonly outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
153
+ readonly "fetch-order": WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
154
+ readonly catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
144
155
  readonly "outbound-sweep": WireJobBlueprint<void, MarketplaceJobDeps>;
145
156
  };
146
157
  };
@@ -526,4 +537,4 @@ interface ApiMarketplace {
526
537
  /** Build the route table over a mounted engine. */
527
538
  declare function createApiMarketplace(config: MarketplaceApiConfig): ApiMarketplace;
528
539
 
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 };
540
+ 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-AYYBRQJV.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-XUAFXNOH.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.3.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"
@@ -1,7 +1,7 @@
1
1
  // ---------------------------------------------------------------------------
2
2
  // @12-apps/marketplace — CANONICAL Prisma model partial.
3
3
  //
4
- // The four tables the marketplace engine owns. A host does NOT copy these
4
+ // The six tables the marketplace engine owns. A host does NOT copy these
5
5
  // models by hand: it composes this file into its multi-file schema folder from
6
6
  // the `db` capability (`package.json` "wiring.db"), and discovers the
7
7
  // migrations beside it.
@@ -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
@@ -246,3 +250,94 @@ model MarketplaceAcceptance {
246
250
  // SQL-only (migration 20261112120000), since Prisma cannot express the WHERE.
247
251
  @@map("marketplace_acceptances")
248
252
  }
253
+
254
+ /// One host product's place in one marketplace's catalogue (FUT-4768).
255
+ ///
256
+ /// One row per (store, marketplace, product): the store's switch for that
257
+ /// marketplace, and what the marketplace made of it. `productId` is an OPAQUE
258
+ /// host catalog id, like `menuItemId` above; the engine never reads the
259
+ /// product, the host maps it at send time.
260
+ ///
261
+ /// `status` is the MECHANISM's vocabulary (CHECK in the migration):
262
+ /// PUBLISHING (asked, not yet in the catalogue) → PUBLISHED, WITHDRAWING (asked
263
+ /// out) → WITHDRAWN, and FAILED with the marketplace's own reason. A FAILED row
264
+ /// is asked again by the same publish or withdraw.
265
+ model MarketplaceCataloguePublication {
266
+ id String @id @default(uuid())
267
+ clientId String @map("client_id")
268
+ provider String
269
+ /// The host product this row publishes. Opaque here.
270
+ productId String @map("product_id")
271
+
272
+ status String @default("PUBLISHING")
273
+
274
+ /// The store's price for THIS marketplace, in the smallest currency unit.
275
+ /// NULL is "the store's own price"; it never changes the store's price.
276
+ priceCents Int? @map("price_cents")
277
+ /// The price the last successful publish sent, whichever rule chose it.
278
+ sentPriceCents Int? @map("sent_price_cents")
279
+
280
+ /// The marketplace's id for the item, from the last successful publish.
281
+ externalId String? @map("external_id")
282
+
283
+ /// The photo the marketplace holds for the item: the adapter's reference to
284
+ /// it (iFood's uploaded `imagePath`) and the photo URL it was made from, so a
285
+ /// re-publish of the same photo does not upload it again.
286
+ imageRef String? @map("image_ref")
287
+ imageSourceUrl String? @map("image_source_url")
288
+ /// What the last successful publish could not do: IMAGE_TOO_LARGE |
289
+ /// IMAGE_REFUSED (CHECK); NULL when it did everything.
290
+ warningCode String? @map("warning_code")
291
+
292
+ /// Which action FAILED: PUBLISH | WITHDRAW (CHECK); NULL unless FAILED.
293
+ failedAction String? @map("failed_action")
294
+ /// Why it FAILED, a code the host words (CHECK): REFUSED, UNAVAILABLE,
295
+ /// TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL.
296
+ failureCode String? @map("failure_code")
297
+ /// The marketplace's OWN words for a REFUSED (truncated by the writer);
298
+ /// NULL for every other code. Never an engine message.
299
+ failureReason String? @map("failure_reason")
300
+
301
+ /// When the current action was asked: what the job matches its run to, and
302
+ /// what the outbound sweep ages a row still owed by.
303
+ requestedAt DateTime @map("requested_at")
304
+ publishedAt DateTime? @map("published_at")
305
+ withdrawnAt DateTime? @map("withdrawn_at")
306
+ failedAt DateTime? @map("failed_at")
307
+
308
+ createdAt DateTime @default(now()) @map("created_at")
309
+ updatedAt DateTime @updatedAt @map("updated_at")
310
+
311
+ // Named: Prisma's default (68 characters) is past Postgres's 63, which
312
+ // truncates it, and the database and the schema would then disagree.
313
+ @@unique([clientId, provider, productId], map: "marketplace_catalogue_publications_client_provider_product_key")
314
+ @@index([clientId, productId])
315
+ @@index([status, requestedAt])
316
+ @@map("marketplace_catalogue_publications")
317
+ }
318
+
319
+ /// The marketplace's id for one host category on one connection (FUT-4768).
320
+ ///
321
+ /// A marketplace that is written to (push) groups items in categories it
322
+ /// issues ids for, found or created by name. Stored so every publish into
323
+ /// the same category reuses one id, and CLAIMED while it is being created
324
+ /// (`claimedAt` set, `externalId` still NULL), so two products switched on at
325
+ /// once into a new category create it once, not twice.
326
+ model MarketplaceCatalogueCategory {
327
+ id String @id @default(uuid())
328
+ clientId String @map("client_id")
329
+ provider String
330
+ /// The host category's name, as the item carried it.
331
+ name String
332
+
333
+ /// The marketplace's id for it; NULL while it is being found or created.
334
+ externalId String? @map("external_id")
335
+ /// When a publish claimed the creation; a claim past its staleness is taken over.
336
+ claimedAt DateTime? @map("claimed_at")
337
+
338
+ createdAt DateTime @default(now()) @map("created_at")
339
+ updatedAt DateTime @updatedAt @map("updated_at")
340
+
341
+ @@unique([clientId, provider, name])
342
+ @@map("marketplace_catalogue_categories")
343
+ }
@@ -0,0 +1,97 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: the catalogue publication (FUT-4768). Additive and
3
+ -- replay-safe, like the engine's other migrations: two new tables, their
4
+ -- indexes and their CHECKs. No column of an existing table changes.
5
+ --
6
+ -- One row per (store, marketplace, host product): whether the store wants the
7
+ -- product in that marketplace's catalogue, the price it set for that
8
+ -- marketplace (NULL: the store's own), and what the marketplace made of it.
9
+ -- `product_id` is a by-value scalar, like `menu_item_id`: no foreign key into
10
+ -- a host table.
11
+
12
+ CREATE TABLE IF NOT EXISTS "marketplace_catalogue_publications" (
13
+ "id" TEXT NOT NULL,
14
+ "client_id" TEXT NOT NULL,
15
+ "provider" TEXT NOT NULL,
16
+ "product_id" TEXT NOT NULL,
17
+ "status" TEXT NOT NULL DEFAULT 'PUBLISHING',
18
+ "price_cents" INTEGER,
19
+ "sent_price_cents" INTEGER,
20
+ "external_id" TEXT,
21
+ "image_ref" TEXT,
22
+ "image_source_url" TEXT,
23
+ "warning_code" TEXT,
24
+ "failed_action" TEXT,
25
+ "failure_code" TEXT,
26
+ "failure_reason" TEXT,
27
+ "requested_at" TIMESTAMP(3) NOT NULL,
28
+ "published_at" TIMESTAMP(3),
29
+ "withdrawn_at" TIMESTAMP(3),
30
+ "failed_at" TIMESTAMP(3),
31
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
32
+ "updated_at" TIMESTAMP(3) NOT NULL,
33
+
34
+ CONSTRAINT "marketplace_catalogue_publications_pkey" PRIMARY KEY ("id")
35
+ );
36
+
37
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_catalogue_publications_client_provider_product_key"
38
+ ON "marketplace_catalogue_publications"("client_id", "provider", "product_id");
39
+ CREATE INDEX IF NOT EXISTS "marketplace_catalogue_publications_client_id_product_id_idx"
40
+ ON "marketplace_catalogue_publications"("client_id", "product_id");
41
+ CREATE INDEX IF NOT EXISTS "marketplace_catalogue_publications_status_requested_at_idx"
42
+ ON "marketplace_catalogue_publications"("status", "requested_at");
43
+
44
+ DO $$ BEGIN
45
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_provider_shape"
46
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
47
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
48
+
49
+ DO $$ BEGIN
50
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_status_check"
51
+ CHECK ("status" IN ('PUBLISHING', 'PUBLISHED', 'WITHDRAWING', 'WITHDRAWN', 'FAILED'));
52
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
53
+
54
+ DO $$ BEGIN
55
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_failed_action_check"
56
+ CHECK ("failed_action" IS NULL OR "failed_action" IN ('PUBLISH', 'WITHDRAW'));
57
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
58
+
59
+ DO $$ BEGIN
60
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_failure_code_check"
61
+ CHECK ("failure_code" IS NULL OR "failure_code" IN ('REFUSED', 'UNAVAILABLE', 'TIMEOUT', 'NOT_CONNECTED',
62
+ 'CREDENTIALS', 'PRODUCT_GONE', 'UNSUPPORTED', 'INTERNAL'));
63
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
64
+
65
+ DO $$ BEGIN
66
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_warning_code_check"
67
+ CHECK ("warning_code" IS NULL OR "warning_code" IN ('IMAGE_TOO_LARGE', 'IMAGE_REFUSED'));
68
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
69
+
70
+ DO $$ BEGIN
71
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_price_check"
72
+ CHECK (("price_cents" IS NULL OR "price_cents" > 0)
73
+ AND ("sent_price_cents" IS NULL OR "sent_price_cents" > 0));
74
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
75
+
76
+ -- The marketplace's id for one host category on one connection, found or
77
+ -- created by name once and reused; claimed while it is being created.
78
+ CREATE TABLE IF NOT EXISTS "marketplace_catalogue_categories" (
79
+ "id" TEXT NOT NULL,
80
+ "client_id" TEXT NOT NULL,
81
+ "provider" TEXT NOT NULL,
82
+ "name" TEXT NOT NULL,
83
+ "external_id" TEXT,
84
+ "claimed_at" TIMESTAMP(3),
85
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
86
+ "updated_at" TIMESTAMP(3) NOT NULL,
87
+
88
+ CONSTRAINT "marketplace_catalogue_categories_pkey" PRIMARY KEY ("id")
89
+ );
90
+
91
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_catalogue_categories_client_id_provider_name_key"
92
+ ON "marketplace_catalogue_categories"("client_id", "provider", "name");
93
+
94
+ DO $$ BEGIN
95
+ ALTER TABLE "marketplace_catalogue_categories" ADD CONSTRAINT "marketplace_catalogue_categories_provider_shape"
96
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
97
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
@@ -0,0 +1,117 @@
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";
5
+
6
+ /**
7
+ * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).
8
+ *
9
+ * In Open Delivery the store's software does not write the menu to the
10
+ * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a
11
+ * `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
16
+ *
17
+ * 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`).
22
+ *
23
+ * ESTIMATED, to be checked once 99Food grants partner access:
24
+ * - the path: the spec's route table and prose name `POST /merchantUpdate`
25
+ * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this
26
+ * sends the prose's;
27
+ * - the `X-App-MerchantId` header on it: the operation lists none, and one
28
+ * client app may serve many merchants, so it is sent to name which;
29
+ * - that 99Food reads the whole `Merchant` on that notification (scenario 1
30
+ * 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
+ */
36
+
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
+ }
109
+
110
+ /** 99Food's catalogue capability, for the base URLs it was given. */
111
+ export function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {
112
+ return {
113
+ mode: "pull",
114
+ menuDocument: openDeliveryMenuDocument,
115
+ notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),
116
+ };
117
+ }
@@ -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;