@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.
- package/ADOPTING.md +76 -4
- package/README.md +163 -3
- package/dist/99food/index.d.ts +79 -2
- package/dist/99food/index.js +117 -2
- package/dist/99food/index.js.map +1 -1
- package/dist/adapter-B8QtQ2RA.d.ts +612 -0
- package/dist/{chunk-CRYFYDQ2.js → chunk-DPCZVN2C.js} +69 -5
- package/dist/chunk-DPCZVN2C.js.map +1 -0
- package/dist/{chunk-D2X7TOR6.js → chunk-EBAIZQPB.js} +841 -86
- package/dist/chunk-EBAIZQPB.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-24RQZPSV.js → chunk-SZRZTLVU.js} +1 -1
- package/dist/chunk-SZRZTLVU.js.map +1 -0
- package/dist/{engine-D-a4mttc.d.ts → engine-o5cm54vC.d.ts} +462 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +22 -2
- package/dist/ifood/index.js +396 -56
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +445 -9
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +5 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +15 -2
- package/dist/rappi/index.js +62 -2
- package/dist/rappi/index.js.map +1 -1
- package/dist/server/index.d.ts +25 -10
- package/dist/server/index.js +4 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +158 -1
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/index.ts +14 -0
- package/src/99food/outbound.ts +3 -3
- package/src/99food/pause.ts +56 -0
- package/src/core/adapter.ts +20 -1
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/engine.ts +83 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/pause-job.ts +381 -0
- package/src/core/pause-port.ts +110 -0
- package/src/core/pause-retired.ts +139 -0
- package/src/core/pause-store.ts +151 -0
- package/src/core/pause-sweep.ts +148 -0
- package/src/core/pause.ts +316 -0
- package/src/core/ports.ts +47 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +8 -0
- package/src/ifood/outbound.ts +9 -6
- package/src/ifood/pause.ts +257 -0
- package/src/index.ts +64 -0
- package/src/rappi/index.ts +17 -0
- package/src/rappi/outbound.ts +2 -2
- package/src/rappi/pause.ts +98 -0
- package/src/server/index.ts +1 -0
- package/src/server/jobs.ts +100 -10
- package/dist/adapter-_iuSxvVD.d.ts +0 -319
- package/dist/chunk-24RQZPSV.js.map +0 -1
- package/dist/chunk-CRYFYDQ2.js.map +0 -1
- package/dist/chunk-D2X7TOR6.js.map +0 -1
package/ADOPTING.md
CHANGED
|
@@ -11,7 +11,7 @@ error at mount, never a default that quietly adopts another host's policy.
|
|
|
11
11
|
|
|
12
12
|
| port | type | what the host answers |
|
|
13
13
|
|---|---|---|
|
|
14
|
-
| `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance
|
|
14
|
+
| `db` | `() => Promise<MarketplaceDb>` | The Prisma client generated from a schema that includes `prisma/marketplace.prisma`. Structural: the four delegates `marketplaceIntegration`, `marketplaceMenuLink`, `marketplaceInboxEvent`, `marketplaceAcceptance`, and the catalogue's `marketplaceCataloguePublication` (optional in the type; the catalogue calls need it). |
|
|
15
15
|
| `transaction` | `<T>(fn: (db: MarketplaceDb) => Promise<T>) => Promise<T>` | Prisma's interactive `$transaction`: run `fn` with the transaction's client; a throw rolls back. Every bulk write and every decision (admission + claim) is one transaction. |
|
|
16
16
|
| `order.admit` | `(request: { clientId; orderId; decision: "ACCEPT" \| "REJECT"; admission: MarketplaceAdmission; db: MarketplaceDb }) => Promise<{ admitted: true } \| { admitted: false; code: string; message: string; details?: unknown }>` | Judge each decision BEFORE its claim commits, inside the claim's transaction (`request.db` is the transaction's client: draw the stock there, and a refusal anywhere in the call rolls the draw back). `admission` is `{ admitStockPastZero?: boolean }` as the person stated it. Refuse with your own code: the route answers 409 with it (`MARKETPLACE_STOCK_ASK` and the short lines in `details`). Never called for an ingest or `recordStoreCancellation`. |
|
|
17
17
|
| `order.create` | `(clientId, order: NormalizedMarketplaceOrder, lines: readonly ResolvedOrderLine[], db: MarketplaceDb) => Promise<string>` | Create the host's own order from a normalized one; return its id. `lines[i].subjectRef` is the mapped catalog id or null (never refuse the order for a null). `db` is the ingest's transaction client: write the order through it, so the order and the acceptance row commit together (a lost race rolls the host's order back instead of leaving an orphan a redelivery would duplicate). |
|
|
@@ -22,15 +22,16 @@ error at mount, never a default that quietly adopts another host's policy.
|
|
|
22
22
|
| `order.onCancellationFailed` | OPTIONAL. `(clientId, orderId, reason: "REFUSED" \| "TIMEOUT") => Promise<void>` | The store's request FAILED: REFUSED (the marketplace's refusal event, the job's 4xx, its last attempt dying, or — request first — a marketplace whose API cannot take it, at once) or TIMEOUT (the outbound sweep, past the marketplace's answer window, or the 24-hour give-up). Called once, by the path that moved the row. Request first: the order stays as it was (AWAITING or ACCEPTED) and may be accepted again; show the adapter's app link and tell the person. A throw is logged. |
|
|
23
23
|
| `order.summarize` | `(clientId, orderIds: readonly string[]) => Promise<Map<string, MarketplaceOrderSummary>>` | The queue's host facts in one read: `{ buyerName, totalCents, unmappedLines, createdAt }`. |
|
|
24
24
|
| `secrets` | `{ seal(plaintext): string; open(sealed): string }` | Seal and open the credential blob with the host's key. `open` THROWS on a blob that will not open. |
|
|
25
|
-
| `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. |
|
|
25
|
+
| `http` | `(req: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>` | The only way the engine reaches a marketplace. Answer any status; throw only when no answer arrived (timeout, network). The host owns the timeout, proxy and CA. `method` is `GET`, `POST`, `PUT` or, since the catalogue (1.2), `PATCH`. |
|
|
26
26
|
| `audit` | `{ record(entry: { clientId; actorId: string \| null; action: "marketplace.integration.archive" \| "marketplace.integration.unarchive"; provider; reason: string \| null; at: Date }, db: MarketplaceDb): Promise<void> }` | Every archive and unarchive of a connection, INSIDE the same transaction: write the line through `db`, so an archive never lands without its line and a failing audit rolls the archive back. `actorId` is `MarketplaceActor.userId`. |
|
|
27
|
-
| `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) => Promise<{ enqueued: boolean; reason?: string }> }` | The wiring `JobsEnqueuePort`. The engine queues only `marketplace.outbound`
|
|
27
|
+
| `enqueue` | `{ enqueue(name, payload, { dedupeKey? }) => Promise<{ enqueued: boolean; reason?: string }> }` | The wiring `JobsEnqueuePort`. Never throws. The engine queues only its own three on-demand jobs: `marketplace.outbound` (`{ clientId, orderId, action }`, dedupe key `marketplace.outbound:<action>:<orderId>`), `marketplace.fetch-order` (`{ clientId, inboxId }`, dedupe key `marketplace.fetch-order:<inboxId>`) and `marketplace.catalogue` (`{ clientId, publicationId, action }`, dedupe key `marketplace.catalogue:<action>:<publicationId>:<asked at, ms>`); the sweeps re-queue each under a key of their own. |
|
|
28
28
|
| `clock` | `{ now(): Date }` | What time it is. |
|
|
29
29
|
| `logger` | `{ info, warn, error }` | The wiring `LoggerPort`; bind `assembled.loggers["@12-apps/marketplace"]`. |
|
|
30
30
|
| `publishChanged` | `(clientId) => void` | Tell the staff surfaces something moved. Fire-and-forget. |
|
|
31
31
|
| `defaultAckSlaSeconds` | `number` | The acceptance window a new connection gets (the origin host: 300). |
|
|
32
32
|
| `reconcileBatchSize` | `number` | Stored deliveries one reconciliation pass re-runs (origin: 50). |
|
|
33
33
|
| `maxInboxAttempts` | `number` | Re-runs before a stored delivery is retired (origin: 5). |
|
|
34
|
+
| `catalogue` | OPTIONAL. `{ items(clientId, productIds) => Promise<Map<string, CatalogueItem>>; image(url) => Promise<{ contentType; base64 } \| null> }` | Catalogue publishing (1.2, FUT-4768). `items` maps the host's products into `{ name, description, imageUrl, categoryName, priceCents }` (the store's price, smallest unit; the photo an absolute https URL that CHANGES when the photo changes, such as a content hash or upload id in it: a marketplace's uploaded copy is reused while the URL is the same), keyed by product id; a missing id is a product that no longer exists. Called at publish (to check it exists) and by the job when it sends, so what goes out is the product as it is then. `image` reads a photo's bytes for a marketplace that takes an upload (iFood); null publishes without a photo. Absent: every catalogue call answers `UNSUPPORTED`. |
|
|
34
35
|
| `cancellationWindowMs` | OPTIONAL. `number` | For a host that requests first (binds `onCancellationConfirmed`): how long a store's cancellation request may wait (PENDING: not yet delivered, or REQUESTED: delivered and unanswered) before the outbound sweep fails it as TIMEOUT, for every adapter; a PENDING request's retries stop with it. A 1.0.0 host has no window: its requests are re-queued and given up after 24 hours, as before. Absent: each adapter's `capabilities.cancellationAnswerWindowMs` (iFood: 5 minutes, estimated); an adapter with none is given up on only after 24 hours. |
|
|
35
36
|
|
|
36
37
|
Plus `adapters: readonly MarketplaceAdapter[]` — one per marketplace the host
|
|
@@ -68,6 +69,11 @@ export const engine = createMarketplaceEngine({
|
|
|
68
69
|
| `suggestReason(provider, { itemUnavailable })` | To preselect a reason in the refusal dialog. The host judges the shortage. |
|
|
69
70
|
| `orderStates(clientId, orderIds)` | The order reads: `{ status, confirmedAt, confirmFailedAt, cancellation, cancellationReasonCode, cancellationFailure, appUrl }` per marketplace order, one query. `cancellation` PENDING or REQUESTED is a request still waiting: draw it as such. `cancellationFailure` is REFUSED or TIMEOUT when `cancellation` is FAILED. |
|
|
70
71
|
| `adapter(provider)`, `reasons(provider)`, `appLink(provider, ref)` | The marketplace's capabilities, reasons and link, without naming it. |
|
|
72
|
+
| `catalogueMode(provider)` | `"push"`, `"pull"` or null: whether the product page can offer this marketplace's switch at all (null: say it cannot be published to). Null also while the host binds no `catalogue` port. |
|
|
73
|
+
| `publish({ clientId, provider, productId, priceCents? })` | The switch turned ON, a new marketplace price, or "try again" after FAILED. `priceCents` absent keeps the stored price, `null` goes back to the store's, a positive integer sets this marketplace's (never the store's own). Answers `queued` with the row (PUBLISHING), or `refused` with `UNSUPPORTED`, `NOT_CONNECTED` (no live connection with credentials and a merchant id), `UNKNOWN_PRODUCT` or `INVALID_PRICE`. Gate it with `marketplace:manage`. |
|
|
74
|
+
| `withdraw({ clientId, provider, productId })` | The switch turned OFF (and the undo of an ON). `queued` (WITHDRAWING), or `unchanged` when the product was never switched on, or is WITHDRAWN at once because its connection was archived or removed since. |
|
|
75
|
+
| `catalogueState({ clientId, productIds, providers? })` | The product page's read: one row per marketplace the product was ever switched on for, in one query. Draw PUBLISHED as "in the catalogue" (with your sentence for a `warningCode`, IMAGE_TOO_LARGE or IMAGE_REFUSED: it went out without its photo), PUBLISHING / WITHDRAWING as "sending…" (switch disabled), FAILED with your own sentence for its `failureCode` (REFUSED, UNAVAILABLE, TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL), the marketplace's own words from `failureReason` beside a REFUSED, and a retry (`publish` or `withdraw` again, per `failedAction`). The engine writes no sentence a person reads. No row is OFF. |
|
|
76
|
+
| `catalogueDocument({ clientId, provider, options: { menuName, currency } })` | PULL marketplaces only (99Food): the menu part of the document the marketplace reads. Serve it from the route the marketplace pulls (Open Delivery's `GET /v1/merchant`), merged into the rest of that document, which is the host's (`id`, `status`, `lastUpdate`, `TTL`, `basicInfo`, `services`). The menu's name and the currency are the host's words. |
|
|
71
77
|
| `ingest(...)`, `deliver(...)` | A producer that hands over an order directly; the webhook does `deliver` for you. |
|
|
72
78
|
|
|
73
79
|
A host never writes `provider === "IFOOD"`. A capability is asked of
|
|
@@ -91,7 +97,7 @@ host.adoptServer({
|
|
|
91
97
|
| capability | what it is |
|
|
92
98
|
|---|---|
|
|
93
99
|
| `http` | `POST /webhooks/marketplace/:tenantSlug/:provider` (`kind: "webhook"`, needs the raw `request`), and per entity one read and one bulk write under `/admin/:tenantSlug/marketplace`: `GET`/`PUT` (connections), `GET`/`PUT /menu-links`, `GET`/`POST /acceptances` (decisions). `@12-apps/marketplace/hono`'s `marketplaceRouter({ ...config, resolveActor })` mounts them in one line. |
|
|
94
|
-
| `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.fetch-order` (on demand, 3 attempts, exponential backoff 5 s: the order body an event only announced; a host that holds it through its `enqueue` port holds every fetch), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h). Bind `{ engine }`. |
|
|
100
|
+
| `jobs` | `marketplace.expire-acceptances` (every minute, lease 5 min), `marketplace.reconcile-inbox` (every 5 min, lease 5 min), `marketplace.outbound` (3 attempts, exponential backoff 30 s), `marketplace.fetch-order` (on demand, 3 attempts, exponential backoff 5 s: the order body an event only announced; a host that holds it through its `enqueue` port holds every fetch), `marketplace.catalogue` (on demand, 3 attempts, exponential backoff 10 s: one publish or withdraw; the last attempt ends FAILED with a `failureCode`, or leaves a publish that only waited for another's category PUBLISHING for the sweep), `marketplace.outbound-sweep` (every 5 min, lease 5 min: re-queues every call still owed after 10 min, gives a PENDING request up as FAILED after 24 h, re-queues a catalogue row still PUBLISHING or WITHDRAWING after 10 min, and FAILS one as TIMEOUT after 24 h). Bind `{ engine }`. |
|
|
95
101
|
| `mcp` | Six tools, the bulk-upsert protocol: `listMarketplaceIntegrations` / `upsertMarketplaceIntegrations` (operations `upsert`, `archive`, `unarchive`), `listMarketplaceMenuLinks` / `upsertMarketplaceMenuLinks`, `listMarketplaceAcceptances` / `decideMarketplaceOrders`. Every write takes a list, is all-or-nothing in one transaction, supports `validateOnly`, answers every problem with its path; reads take `ids`. Descriptions are English. |
|
|
96
102
|
| `permissions` | `marketplace:manage` (connect, map) and `marketplace:decide` (read and answer the queue). The host decides which roles hold them; each route declares its own. |
|
|
97
103
|
| `db` | `prisma/marketplace.prisma` + `prisma/migrations` (composed). |
|
|
@@ -170,6 +176,19 @@ country); see the README's Rappi section for what is still ESTIMATED.
|
|
|
170
176
|
- run migration `20261112120000_marketplace_cancellation_failure` (one nullable column,
|
|
171
177
|
its CHECK and an index), through the host's plugin-migration sync like the first.
|
|
172
178
|
|
|
179
|
+
14. **Catalogue publishing (1.2, FUT-4768) — opt in by binding `catalogue`.** Nothing
|
|
180
|
+
changes for a host that does not. To offer the product page's marketplace switches:
|
|
181
|
+
- run migration `20261113120000_marketplace_catalogue` (one new table, additive) and
|
|
182
|
+
re-sync the partial (`prisma:sync-marketplace`), so `db` has the
|
|
183
|
+
`marketplaceCataloguePublication` and `marketplaceCatalogueCategory` delegates;
|
|
184
|
+
- bind `catalogue.items` (the product → item mapping) and `catalogue.image`;
|
|
185
|
+
- let the `http` port send `PATCH`;
|
|
186
|
+
- run the `marketplace.catalogue` job (it arrives with the jobs capability);
|
|
187
|
+
- gate `publish`/`withdraw` with `marketplace:manage`, and show a marketplace whose
|
|
188
|
+
`catalogueMode` is null as not publishable (Rappi, today);
|
|
189
|
+
- for 99Food, serve `catalogueDocument` inside Open Delivery's `GET /v1/merchant`
|
|
190
|
+
(the route 99Food pulls) and register that route with 99Food at onboarding.
|
|
191
|
+
|
|
173
192
|
## 5. The database
|
|
174
193
|
|
|
175
194
|
The partial names no host table: `client_id`, `order_id` and `menu_item_id`
|
|
@@ -180,6 +199,12 @@ migration:
|
|
|
180
199
|
- `marketplace_acceptances.order_id → <orders>(id) ON DELETE CASCADE`
|
|
181
200
|
- `marketplace_menu_links.menu_item_id → <catalog>(id) ON DELETE SET NULL`
|
|
182
201
|
|
|
202
|
+
`20261113120000_marketplace_catalogue` (1.2) adds `marketplace_catalogue_publications`:
|
|
203
|
+
one row per (store, marketplace, product), its five states, its failed action and its
|
|
204
|
+
prices CHECKed, `product_id` by value; and `marketplace_catalogue_categories`, a push
|
|
205
|
+
marketplace's category id per (store, marketplace, category name), created once. A host that wants it adds
|
|
206
|
+
`marketplace_catalogue_publications.product_id → <catalog>(id) ON DELETE CASCADE`.
|
|
207
|
+
|
|
183
208
|
The migrations are replay-safe. `20261112120000_marketplace_cancellation_failure`
|
|
184
209
|
(1.1) adds `marketplace_acceptances.cancellation_failure_reason` (REFUSED or
|
|
185
210
|
TIMEOUT, CHECKed), and a PARTIAL index the expiry of waiting requests reads
|
|
@@ -202,3 +227,50 @@ The stock draw at the acceptance, the settlement effects, the board's and the
|
|
|
202
227
|
order screen's UI, the cancel route itself, the HTTP client's timeout and CA,
|
|
203
228
|
the jobs runtime and its leases, which roles hold the two permissions, and
|
|
204
229
|
every sentence a person reads.
|
|
230
|
+
|
|
231
|
+
## 7. Pausing a store
|
|
232
|
+
|
|
233
|
+
The store pause (FUT-4851) closes the store on every connected marketplace
|
|
234
|
+
while the host's kitchen is paused. Everything the host owns about it:
|
|
235
|
+
|
|
236
|
+
**When to call.** The host decides when its kitchen is paused and runs the
|
|
237
|
+
debounce (a store setting beside the cap, 3 minutes by default: pause at once
|
|
238
|
+
when the cap is passed, reopen only after the queue stayed under it that long).
|
|
239
|
+
The engine never debounces.
|
|
240
|
+
|
|
241
|
+
| call | who calls it, and when |
|
|
242
|
+
|---|---|
|
|
243
|
+
| `pauseStore({ clientId, until, reason, timeZone })` | The kitchen enters its pause, and again on every renewal while it stays paused (each time its estimated reopening time moves, later OR earlier: an earlier end is honoured too, so the store is never closed longer than the kitchen's pause; a renewal every few minutes is fine). `until` is the kitchen's ESTIMATED reopening time and must be in the future (else `{ kind: "invalid", code: "UNTIL_NOT_FUTURE" }`). `reason` is the host's own words (its copy, in the store's language), sent where the marketplace shows one. `timeZone` is the store's IANA zone (one the runtime does not know answers `{ kind: "invalid", code: "TIME_ZONE_INVALID" }`). Answers per live connection: `queued`, `unchanged` (a pause with exactly this end already stands or is on its way), `unsupported` (the adapter has no `availability`), `not-connected` (no credentials or no merchant id). |
|
|
244
|
+
| `resumeStore({ clientId })` | The moment the kitchen's pause is over (after the host's debounce). Deletes only what the engine created; answers `queued`, `open` (nothing of ours stood there: nobody is called) or `unchanged`. |
|
|
245
|
+
| `availabilityState(clientId)` | The screen: per live connection `{ provider, supported, kind, connected, state, wanted, until, sentUntil, failureCode, failureDetail, pausedAt, resumedAt, updatedAt }`. `state` is `OPEN`, `PAUSING`, `PAUSED`, `RESUMING` or `FAILED`; draw `supported: false` as "this marketplace cannot be paused from here". `failureCode` is a code for the host's copy; `failureDetail` is the marketplace's own words, never copy. |
|
|
246
|
+
|
|
247
|
+
If the host stops renewing (it died, or never called `resumeStore`), the
|
|
248
|
+
availability sweep resumes the store on its own once `until` has passed: the
|
|
249
|
+
store is never closed on a marketplace longer than the kitchen's own pause.
|
|
250
|
+
|
|
251
|
+
**The jobs.** Bind the two new blueprints with the rest of `MARKETPLACE_JOBS`
|
|
252
|
+
(`{ engine }`): `marketplace.availability` (on demand, three attempts, short
|
|
253
|
+
backoff) and `marketplace.availability-sweep` (every five minutes, on the
|
|
254
|
+
single-flight `sweeps` queue). A host that adopts the wiring manifest gets
|
|
255
|
+
them with the others. A host that declines `jobs` gets no pause at all: every
|
|
256
|
+
ask stays `PAUSING`, so it must not call `pauseStore`.
|
|
257
|
+
|
|
258
|
+
**The outbound gate.** No path that answers a request calls a marketplace:
|
|
259
|
+
`pauseStore` and `resumeStore` record the ask and queue the job, and the job
|
|
260
|
+
calls the adapter through the host's `http` port, as `confirm` does. A host
|
|
261
|
+
that gates outbound calls (an environment where nothing may reach a real
|
|
262
|
+
marketplace) gates the `http` port, and every pause call goes through it.
|
|
263
|
+
|
|
264
|
+
**The switches.** Rappi and 99Food can only switch a whole store on or off,
|
|
265
|
+
with no id and no end, so the engine cannot tell its own closure from one the
|
|
266
|
+
owner ALSO made by hand on the marketplace during the kitchen's pause (that
|
|
267
|
+
one would be reopened with it). Their adapters offer the capability only with
|
|
268
|
+
`pauseByStoreSwitch: true`; leave it off to keep them `unsupported`.
|
|
269
|
+
|
|
270
|
+
**The database.** Migration `20261113230000_marketplace_store_pause` adds
|
|
271
|
+
`marketplace_store_pauses` (one row per store and marketplace, CHECKed
|
|
272
|
+
vocabularies, no foreign key; add `client_id → <tenants>(id) ON DELETE CASCADE`
|
|
273
|
+
if you want one). The `MarketplaceDb.marketplaceStorePause` delegate is
|
|
274
|
+
OPTIONAL in the type, so a 1.x host compiles before it migrates; `pauseStore`
|
|
275
|
+
and `resumeStore` throw naming the migration until it does, and
|
|
276
|
+
`availabilityState` reads every marketplace OPEN.
|
package/README.md
CHANGED
|
@@ -47,7 +47,8 @@ engine code (`src/__tests__/second-adapter.test.ts`).
|
|
|
47
47
|
| **Outbound engine** | The `marketplace.outbound` job: confirm after accept (with the preparation time where the marketplace takes one), cancellation request with the stored reason code and SKUs. 2xx done; a 4xx other than 408/425/429 refused and final; anything else retried until the last attempt, which ends FAILED whatever went wrong. Stamps `confirmed_at`, `confirm_failed_at`, `cancellation_status` (PENDING, REQUESTED, CONFIRMED, FAILED). Idempotent by the row. Queued BEFORE the host's half runs, and the `marketplace.outbound-sweep` job re-queues every call still owed, so nothing is lost. The same sweep fails a request still waiting (never delivered, or delivered and unanswered) as TIMEOUT once past its answer window, and its retries stop (the adapter's `cancellationAnswerWindowMs`, or the engine's `cancellationWindowMs`), so no request waits forever. |
|
|
48
48
|
| **Order fetch** | For a marketplace whose events name an order without carrying it (Open Delivery's `CREATED`), the adapter marks the event `orderToFetch`: the webhook records it PENDING and queues `marketplace.fetch-order`, which calls the adapter's `fetchOrder` and ingests through the same ingest path. No request calls out; the reconciliation sweep re-queues a row still owed, and a host that holds the job holds every fetch. |
|
|
49
49
|
| **Inbound outcomes** | A marketplace CANCELLED confirms a pending request; CANCELLATION_REQUEST_FAILED marks it FAILED; CONFIRMED is terminal. |
|
|
50
|
-
| **
|
|
50
|
+
| **Catalogue publishing** | A store turns a product ON or OFF per connected marketplace, with an optional price for that marketplace. One row per (store, marketplace, product): PUBLISHING → PUBLISHED, WITHDRAWING → WITHDRAWN, FAILED with a failure code (and the marketplace's own words for a refusal). The `marketplace.catalogue` job makes the call; the sweep re-queues what is owed. Push or pull is the adapter's. See [Catalogue publishing](#catalogue-publishing). |
|
|
51
|
+
| **Adapter port** | `MarketplaceAdapter`: `normalize`, `readSignature`, `verifySignature`, `cancellationReasons`, `confirm`, `requestCancellation`, `appLink`, `capabilities`, and the optional `fetchOrder` and `catalogue`. |
|
|
51
52
|
|
|
52
53
|
## Subpaths
|
|
53
54
|
|
|
@@ -66,10 +67,98 @@ engine code (`src/__tests__/second-adapter.test.ts`).
|
|
|
66
67
|
| `@12-apps/marketplace/manifest`, `/manifest/server` | the wiring manifests |
|
|
67
68
|
| `prisma/marketplace.prisma`, `prisma/migrations/*` | the partial (no host table named) and its replay-safe migration |
|
|
68
69
|
|
|
70
|
+
## Catalogue publishing
|
|
71
|
+
|
|
72
|
+
FUT-4768, approved by the owner on 2026-11-12: from a product's page the store
|
|
73
|
+
turns the product ON (in that marketplace's catalogue) or OFF (removed) per
|
|
74
|
+
connected marketplace, with an optional price for that marketplace that
|
|
75
|
+
defaults to the store's and never changes it. What goes out: name, photo,
|
|
76
|
+
description, category and the price. The states a host shows: in the
|
|
77
|
+
catalogue, "sending…", and refused with the marketplace's reason and a retry.
|
|
78
|
+
Why the engine now does this at all: the decision record
|
|
79
|
+
[`docs/marketplace/decisions/draft-the-engine-publishes-catalogues.md`](../../docs/marketplace/decisions/draft-the-engine-publishes-catalogues.md).
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
engine.catalogueMode(provider); // "push" | "pull" | null (cannot be published to)
|
|
83
|
+
await engine.publish({ clientId, provider, productId, priceCents }); // priceCents: absent keeps, null = the store's price
|
|
84
|
+
await engine.withdraw({ clientId, provider, productId });
|
|
85
|
+
await engine.catalogueState({ clientId, productIds: [productId] }); // every marketplace, one read
|
|
86
|
+
await engine.catalogueDocument({ clientId, provider, options: { menuName, currency } }); // pull only: what the host serves
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
| part | what it does |
|
|
90
|
+
|---|---|
|
|
91
|
+
| **The row** | `marketplace_catalogue_publications`, one per (store, marketplace, product): `status`, the marketplace price (`price_cents`, NULL = the store's), the price last sent, the marketplace's id for the item, the failed action, its code and the marketplace's own words, and when each thing happened. `product_id` is opaque: no host table is read. |
|
|
92
|
+
| **States** | `publish` → PUBLISHING → (job) PUBLISHED; `withdraw` → WITHDRAWING → (job) WITHDRAWN; a final refusal, or the last attempt, → FAILED with `failedAction` (PUBLISH / WITHDRAW) and a `failureCode` the host words (REFUSED, UNAVAILABLE, TIMEOUT, NOT_CONNECTED, CREDENTIALS, PRODUCT_GONE, UNSUPPORTED, INTERNAL); `failureReason` carries the marketplace's own words for a REFUSED only, never an engine or internal message. `publish` or `withdraw` again from FAILED is the retry. |
|
|
93
|
+
| **Idempotency** | A run acts only while the row still asks for its action at the instant it read (`requested_at`). A double tap while on its way keeps the same ask and the same dedupe key. The store's last tap wins: a withdraw while publishing makes the publish run call nobody, a publish that LANDS after the withdraw is withdrawn again, and a withdraw that lands after the product was switched back on is followed by the publish again. A withdraw is sent even after a failed publish (an answer lost after the item landed), and a marketplace answers a withdraw of an item it does not have as done; only a connection archived or removed since ends WITHDRAWN at once, with nobody to tell. |
|
|
94
|
+
| **The host's product** | Read through the host's `catalogue.items(clientId, productIds)` port when the job sends it, so what goes out is the product as it is then; `catalogue.image(url)` hands over a photo's bytes for a marketplace that takes an upload. |
|
|
95
|
+
| **SKU map** | A publish that succeeds maps the SKU the marketplace's orders will carry for the item (the adapter's `sku`, else the product id sent as its external code) to the product, so those orders arrive mapped rather than on the attention list; only when the SKU is not mapped yet, so a store's own mapping of it is never undone. A withdraw keeps the map: an order placed before it still maps. |
|
|
96
|
+
| **Categories** | A push marketplace's category id is found or created by name ONCE per (connection, name) and stored (`marketplace_catalogue_categories`). The first publish to need a new one claims its creation; a second one meanwhile is retried by the job and then reuses the stored id, so switching on several products of a new category at once creates it once. A claim is released whatever its publish met (a timeout included), and only by its own holder; one left by a dead publish is taken over after 3 minutes, well above three slow calls, so a live holder on a slow call keeps it. A publish that only waited stays PUBLISHING, and the sweep re-queues it after 10 minutes. |
|
|
97
|
+
| **Push** | `catalogue.publishItem` / `withdrawItem`: the adapter writes ONE item. The engine hands it a stable reference (the row's id), so an adapter that must invent the marketplace's id derives it (`stableUuid`) and a retry never creates a second item. |
|
|
98
|
+
| **Pull** | `catalogue.menuDocument` builds the marketplace's menu document from every item ON (PUBLISHING or PUBLISHED, and one published before, not withdrawn since, whose re-publish FAILED, kept at the price last sent until it is withdrawn); the host serves it. `notifyMenuChanged` tells the marketplace to read it again; PUBLISHED / WITHDRAWN once it took the notice. |
|
|
99
|
+
| **Sweep** | The `marketplace.outbound-sweep` pass re-queues a row still PUBLISHING or WITHDRAWING after 10 minutes, and FAILS one 24 hours old, so no switch says "sending" forever. |
|
|
100
|
+
|
|
101
|
+
### What each marketplace offers, from its public documentation
|
|
102
|
+
|
|
103
|
+
Read 2026-11-13. CONFIRMED: read on the page linked. ESTIMATED: not stated
|
|
104
|
+
there, chosen in the adapter's code and marked so beside it.
|
|
105
|
+
|
|
106
|
+
**iFood — push, Catalog API v2.0** (`src/ifood/catalogue.ts`)
|
|
107
|
+
|
|
108
|
+
| fact | status |
|
|
109
|
+
|---|---|
|
|
110
|
+
| Base `https://merchant-api.ifood.com.br/catalog/v2.0/merchants/{merchantId}/…`; bearer token from the same OAuth grant as orders | CONFIRMED — [Introduction](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/introduction) |
|
|
111
|
+
| Hierarchy catalog → context (DEFAULT delivery, WHITELABEL, INDOOR) → category → item → products / option groups / options; each level has its own status | CONFIRMED — [Fundamentals](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/fundamentals) |
|
|
112
|
+
| `GET /catalogs`; `GET /categories` (`?include_items=true`); `POST /categories` `{ name, status, template: "DEFAULT" }` → `{ id, … }` | CONFIRMED — [Endpoints](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/endpoints) |
|
|
113
|
+
| `PUT /items` with `item`, `products`, `optionGroups`, `options` (all four always sent) creates or REPLACES the whole item; the item appears at once (synchronous) | CONFIRMED — Introduction, Endpoints |
|
|
114
|
+
| `item.id` and `products[].id` are UUID v4 the software generates (another shape answers 404); `externalCode` is the software's code, unique per merchant (409 when reused); `status` AVAILABLE / UNAVAILABLE; `price` `{ value, originalValue? }` in the major unit | CONFIRMED — Fundamentals, Introduction |
|
|
115
|
+
| `PATCH /items/status` `{ itemId, status }` and `PATCH /items/price` `{ itemId, price }`, synchronous; the batch forms (`/products/status`, `/products/price`) answer a `batchId` and run asynchronously | CONFIRMED — Endpoints, [Errors](https://developer.ifood.com.br/en-US/docs/food/guides/modules/catalog/errors-and-troubleshooting) |
|
|
116
|
+
| `POST /image/upload` `{ image: "data:image/png;base64,…" }` → `{ imagePath }`, reusable across items; jpg/jpeg/png, at most 5 MB (413 above) | CONFIRMED — Endpoints, Errors |
|
|
117
|
+
| The photo is uploaded once per photo URL, so the host's `imageUrl` must change when the photo does (a versioned URL); new bytes at an old URL are never re-uploaded: its `imagePath` is kept on the row and reused while the URL is the same; a loader that reads nothing keeps it (the PUT replaces the whole item); a refused upload (413, another 4xx) publishes without a photo with the warning IMAGE_TOO_LARGE / IMAGE_REFUSED | choice |
|
|
118
|
+
| Errors: 400 malformed, 401 token, 403 module not contracted (the catalogue module must be enabled for the app), 404, 409 `externalCode` reused, 422 business rule, 429 rate limit, 500; do not retry 4xx but 429 | CONFIRMED — Errors |
|
|
119
|
+
| Rate limits: 3000 req/min for `PUT /items` and the category calls, 5000 req/min for the item status and price PATCHes | CONFIRMED — [Rate limit](https://developer.ifood.com.br/en-US/docs/getting-started/documentation/rate-limit/) (it spells the PATCH paths `/item/status`, singular, where Endpoints spells `/items/status`; the adapter uses Endpoints') |
|
|
120
|
+
| The category list answers an array of `{ id, name }`, oldest first: after a create the adapter reads it again and adopts the first of that name, so a create whose answer was lost is not repeated | ESTIMATED |
|
|
121
|
+
| `item.productId` names the item's product, and `products[].imagePath` carries the uploaded photo | ESTIMATED (the pages read show neither field on a full example; the Errors page names `imagePath` as what the item carries) |
|
|
122
|
+
| OFF is the item paused (`UNAVAILABLE`): no item delete is listed on the Endpoints page; a paused item is not shown in the app | ESTIMATED as the meaning of "removed"; the call is CONFIRMED |
|
|
123
|
+
| A 404 on the withdraw means the item is already out | ESTIMATED |
|
|
124
|
+
| A category the store deleted on iFood's portal makes `PUT /items` answer 400 or 404; then the list is read again, and a category of that name with another id (or none) means the stored id is stale: it is forgotten, found or created again, and the PUT sent once more | ESTIMATED (the Errors page does not say which id a 400/404 is about) |
|
|
125
|
+
| A publish lands in the DEFAULT (delivery) context only; no `contextModifiers` are sent | choice |
|
|
126
|
+
|
|
127
|
+
**99Food — pull, Open Delivery v1.7.1** (`src/99food/catalogue.ts`)
|
|
128
|
+
|
|
129
|
+
| fact | status |
|
|
130
|
+
|---|---|
|
|
131
|
+
| The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`; the ordering application (99Food) pulls it. `Merchant` requires `lastUpdate`, `TTL` (500–86400 s: pulled again when it runs out), `id`, `status`, `basicInfo`, `services`, `items`, `menus`, `categories`, `itemOffers` | CONFIRMED — [openapi.yaml](https://abrasel-nacional.github.io/opendelivery/openapi.yaml), `getMerchant`, `Merchant` |
|
|
132
|
+
| `Menu { id, name, externalCode, categoryId[] }`; `Category { id (uuid), index, name, externalCode, status, itemOfferId[] }`; `Item { id (uuid), name, description, externalCode, unit, status?, image? { URL } }`; `ItemOffer { id, itemId, index, price { value, originalValue, currency } }` — the price lives on the offer | CONFIRMED — same, the schemas |
|
|
133
|
+
| `POST /v1/merchantUpdate` on 99Food, sent with an EMPTY body, makes it read `GET /v1/merchant` again; 200 or 204 | CONFIRMED — same, operation `menuUpdated` |
|
|
134
|
+
| `GET /v1/merchantStatus?merchantId=` answers the last read's outcome (SUCCESS, PROCESSING, FAIL) | CONFIRMED — same; not called by this adapter (a later check) |
|
|
135
|
+
| The notification's path: the prose and the route table say `/v1/merchantUpdate`, the path key says `/v1/menuUpdated`; the adapter sends the former | ESTIMATED |
|
|
136
|
+
| `X-App-MerchantId` on the notification (the operation lists no header) | ESTIMATED |
|
|
137
|
+
| A product in the document is PUBLISHED once 99Food took the notification, not once it read the menu | choice |
|
|
138
|
+
|
|
139
|
+
**Rappi — not supported** (no `catalogue` on the adapter)
|
|
140
|
+
|
|
141
|
+
| fact | status |
|
|
142
|
+
|---|---|
|
|
143
|
+
| The menu is written whole: `POST https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/menu` with `{ storeId, items[] }` (`name`, `description`, `imageUrl`, `price`, `sku`, `category`, `children` toppings), parent stores only | CONFIRMED — [Managing Store Menus](https://dev-portal.rappi.com/en/managing-store-menus/) |
|
|
144
|
+
| A sent menu goes to approval ("Menu updated and ready to be validated"), its status at `GET …/menu/approved/{storeId}`; while one is in approval, every further menu of the store is IGNORED; a rejection is a 400 with each failed validation | CONFIRMED — same |
|
|
145
|
+
| Availability by SKU, `PUT …/availability/stores/items` `[{ store_integration_id, items: { turn_on, turn_off } }]`, only turns items Rappi already has on or off | CONFIRMED — [Managing Availability](https://dev-portal.rappi.com/en/managing-availability/) (the page's URL line says `/token`, its heading `availability/stores/items`) |
|
|
146
|
+
|
|
147
|
+
So a per-product switch cannot be built honestly on Rappi's public API: each
|
|
148
|
+
publish would REPLACE the store's whole Rappi menu with the products switched
|
|
149
|
+
on here (wiping what the store keeps on Rappi's portal), and a second switch
|
|
150
|
+
inside the approval window would be dropped while the row said "in the
|
|
151
|
+
catalogue". The capability is absent, `engine.catalogueMode("RAPPI")` is null,
|
|
152
|
+
and the host shows Rappi as not publishable. Supporting it later is a pull-like
|
|
153
|
+
whole-menu mode over the same rows, once a store accepts that its Rappi menu
|
|
154
|
+
is exactly what it switches on here.
|
|
155
|
+
|
|
69
156
|
## iFood is unverified
|
|
70
157
|
|
|
71
|
-
iFood's developer portal refused our reader, so the iFood adapter's URLs,
|
|
72
|
-
fields and reason codes come from the portal's search snippets
|
|
158
|
+
iFood's developer portal refused our reader, so the iFood adapter's ORDER URLs,
|
|
159
|
+
body fields and reason codes come from the portal's search snippets
|
|
160
|
+
(2026-11-11). (Its Catalog module's pages were read whole on 2026-11-13: see
|
|
161
|
+
[Catalogue publishing](#catalogue-publishing).)
|
|
73
162
|
They live only in `src/ifood/outbound.ts` and `src/ifood/copy.ts`, whose
|
|
74
163
|
headers say so, so the homologation run corrects two files. Tests never reach
|
|
75
164
|
iFood: the HTTP client is the host's port.
|
|
@@ -212,3 +301,74 @@ all. Its retry runs after the store's accept, finds no request and sends
|
|
|
212
301
|
nothing, so the order stays ACCEPTED here while cancelled on Rappi. The take
|
|
213
302
|
the accept queued is then answered 400, so the order shows "não confirmou"
|
|
214
303
|
with the portal link and a person settles it there.
|
|
304
|
+
|
|
305
|
+
## Pausing a store (FUT-4851)
|
|
306
|
+
|
|
307
|
+
When the store's kitchen passes its cap, the host closes the store on every
|
|
308
|
+
connected marketplace until the kitchen's ESTIMATED reopening time, renews the
|
|
309
|
+
closure while the kitchen stays paused, and opens the store the moment the
|
|
310
|
+
pause is over. The host owns the debounce (a store setting, 3 minutes by
|
|
311
|
+
default); the engine only receives `pauseStore({ clientId, until, reason,
|
|
312
|
+
timeZone })` and `resumeStore({ clientId })`, and the screen reads
|
|
313
|
+
`availabilityState(clientId)`. The owner's rules and why each part is shaped
|
|
314
|
+
this way: [the decision draft](../../docs/marketplace/decisions/draft-a-store-pause-closes-every-marketplace.md).
|
|
315
|
+
What the host wires: [ADOPTING.md](./ADOPTING.md#7-pausing-a-store).
|
|
316
|
+
|
|
317
|
+
A marketplace is paused through an OPTIONAL adapter capability,
|
|
318
|
+
`availability`, in one of two shapes:
|
|
319
|
+
|
|
320
|
+
- **`interruption`**: the marketplace keeps a closure with its own id and an
|
|
321
|
+
end. The engine stores the id and deletes that id and nothing else, so a
|
|
322
|
+
closure the owner made by hand is never touched; and if every call after
|
|
323
|
+
the pause is lost, the marketplace still opens the store at the end it was
|
|
324
|
+
given.
|
|
325
|
+
- **`switch`**: a store-wide on/off with no id and no end. The engine turns a
|
|
326
|
+
store on only if its own record says it turned it off, and turns it on by
|
|
327
|
+
itself once `until` has passed unrenewed. It cannot tell its own closure
|
|
328
|
+
from one the owner ALSO made by hand meanwhile, so a switch adapter offers
|
|
329
|
+
the capability only when the host opts in (`pauseByStoreSwitch: true`).
|
|
330
|
+
|
|
331
|
+
### What each marketplace offers, from public documentation only
|
|
332
|
+
|
|
333
|
+
CONFIRMED = read in the cited public document. ESTIMATED = not shown there;
|
|
334
|
+
assumed in code, confined to the adapter's `pause.ts`, to be checked in the
|
|
335
|
+
marketplace's sandbox.
|
|
336
|
+
|
|
337
|
+
| marketplace | fact | status | source |
|
|
338
|
+
|---|---|---|---|
|
|
339
|
+
| iFood | Interruptions: `GET`/`POST /merchant/v1.0/merchants/{merchantId}/interruptions`, `DELETE …/interruptions/{interruptionId}` on `https://merchant-api.ifood.com.br`; a temporary closure that does not change the opening hours | ESTIMATED (two independent public clients agree; iFood's portal, developer.ifood.com.br, answers our reader 403) | npm `@theyahia/ifood-mcp` (`dist/tools/*-interruption.js`), npm `n8n-nodes-ifood-completo`, npm `n8n-nodes-ifood` |
|
|
340
|
+
| iFood | Create body `{ description, start, end }`, 201 with the interruption; delete answers 204 | ESTIMATED (same clients) | as above |
|
|
341
|
+
| iFood | The client may send its own `id` in the create body (sent, as the idempotency key) | ESTIMATED, and not relied on: every create is preceded by a list, and an interruption is ours when it carries our id OR, where iFood assigned its own, exactly the end and the description the create sent (the end compared as the string sent, as an instant, or as the store's wall clock without offset). A retry after a lost answer reuses it, and a resume by key deletes it; a hand-made interruption matches neither. The key and the end it carried are written BEFORE the call, so a lost answer is never forgotten | none public |
|
|
342
|
+
| iFood | Times are read as the store's local clock, the payload's offset discarded | ESTIMATED (one client says so); the adapter sends the store's wall clock WITH its offset, which reads the same either way | `@theyahia/ifood-mcp` |
|
|
343
|
+
| iFood | No call moves an interruption's end | ESTIMATED; on a renewal (a later end OR an earlier one) the engine creates the new interruption first, then deletes the old, so the store is never open between them | none found |
|
|
344
|
+
| iFood | iFood ACCEPTS two overlapping interruptions for the moment of a renewal | ESTIMATED. If it refuses the overlap, the renewal is FAILED (`PAUSE_REFUSED`, iFood's words) and the old interruption still holds to its own end | none found |
|
|
345
|
+
| iFood | Auth: the merchant app's client-credentials token (`POST /authentication/v1.0/oauth/token`), as every other call of the adapter | ESTIMATED (as the rest of the iFood adapter, "iFood is unverified" above); no public scope list for the merchant module was readable | the adapter's existing outbound |
|
|
346
|
+
| iFood | Limits (rate, interruptions per merchant, maximum length, description length) | ESTIMATED: none published that we could read; a refusal is FAILED with iFood's own words | none |
|
|
347
|
+
| Rappi | `PUT https://{COUNTRY_DOMAIN}/api/v2/restaurants-integrations-public-api/availability/stores/enable`, synchronous, `{ stores: [{ store_id, is_enabled }] }`; 200 with `results[]` (`store_id`, `is_enabled`, `operation_result`, `operation_result_type`, `operation_result_message`, `suspended_reason`, `suspended_at`, `suspended_time`), 400, 403, 422 (over 300 stores), 502 | CONFIRMED | [dev-portal.rappi.com/en/api-reference/availability](https://dev-portal.rappi.com/en/api-reference/availability/) |
|
|
348
|
+
| Rappi | No end time or duration on the request: a switch; a store turned off stays off until turned on | CONFIRMED (no such parameter; the portal's FAQ: it stays off until enabled again) | same page; [dev-portal.rappi.com/en/frequently-asked-questions](https://dev-portal.rappi.com/en/frequently-asked-questions/) |
|
|
349
|
+
| Rappi | `store_id` is the connection's merchant id (Rappi's store id) | ESTIMATED (the page says "the one from your system" for this call and "the one in the rappi system" for the massive one) | same page |
|
|
350
|
+
| Rappi | A per-store failure reads as `operation_result: false` or an error-named `operation_result_type` | ESTIMATED (types not shown) | same page |
|
|
351
|
+
| 99Food | Open Delivery v1.7.1: the software PUSHES `POST /v1/merchantUpdate` with only `merchantStatus` (`AVAILABLE`/`UNAVAILABLE`) to open or close the merchant, OAuth2 `od.all`; 204 (200 for compatibility), 400, 401, 403, 404, 503 | CONFIRMED for the standard | [openapi.yaml v1.7.1](https://abrasel-nacional.github.io/opendelivery/openapi.yaml), "New Merchant Update Notification" |
|
|
352
|
+
| 99Food | `merchantStatus` has no end ("you don't know when the service will be re-established"): a switch | CONFIRMED for the standard | same |
|
|
353
|
+
| 99Food | The path is `/v1/merchantUpdate` (the spec files the webhook under the key `/v1/menuUpdated`, while its description and route table say `POST /v1/merchantUpdate`) | ESTIMATED | same |
|
|
354
|
+
| 99Food | 99Food implements `merchantUpdate`, and the token names the merchant (the body names none) | ESTIMATED | none public for 99Food |
|
|
355
|
+
| 99Food | The marketplace PULLING the status (`GET /v1/merchant/{id}/status`, host: the software) | Not used: the engine pushes, and serving the status is a host route this package does not ship | same spec |
|
|
356
|
+
|
|
357
|
+
### Failure codes
|
|
358
|
+
|
|
359
|
+
No sentence a host shows is the engine's. A FAILED record carries a
|
|
360
|
+
`failureCode` (`UNSUPPORTED`, `NOT_CONNECTED`, `PAUSE_REFUSED`,
|
|
361
|
+
`PAUSE_UNANSWERED`, `RESUME_REFUSED`, `RESUME_UNANSWERED`) for the host's copy,
|
|
362
|
+
and the marketplace's own words, verbatim and cut to 300 characters, in
|
|
363
|
+
`failureDetail` — only for a refusal; an unanswered call, a missing connection
|
|
364
|
+
or an engine error leaves it null and goes to the logger.
|
|
365
|
+
|
|
366
|
+
### Tests
|
|
367
|
+
|
|
368
|
+
- `src/__tests__/store-pause.test.ts`: the engine through fake marketplaces
|
|
369
|
+
(an interruption and a switch): fan-out, idempotency and renewal, the state
|
|
370
|
+
machine, deleting only what it created, the races (resume before and during
|
|
371
|
+
a pause, pause during a resume, a lost answer, two runs at once), the sweep.
|
|
372
|
+
- `src/ifood/__tests__/pause.test.ts`: the request shapes each adapter sends.
|
|
373
|
+
- `src/__tests__/store-pause-migration.test.ts`: the migration on PGlite,
|
|
374
|
+
index names against Prisma's, and a pause and resume on real Postgres.
|
package/dist/99food/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAdapter } from '../adapter-
|
|
1
|
+
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, P as PullCatalogue, C as CatalogueMenuEntry, b as CatalogueMenuOptions, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-B8QtQ2RA.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The words the 99Food adapter needs from its host, and nothing else.
|
|
@@ -93,6 +93,76 @@ declare function normalizeOpenDeliveryOrder(order: unknown, options: {
|
|
|
93
93
|
missingStreetNumber: string;
|
|
94
94
|
}): NormalizedMarketplaceOrder | null;
|
|
95
95
|
|
|
96
|
+
/** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */
|
|
97
|
+
declare function openDeliveryMenuDocument(input: {
|
|
98
|
+
externalMerchantId: string;
|
|
99
|
+
entries: readonly CatalogueMenuEntry[];
|
|
100
|
+
options: CatalogueMenuOptions;
|
|
101
|
+
}): {
|
|
102
|
+
menus: {
|
|
103
|
+
id: string;
|
|
104
|
+
name: string;
|
|
105
|
+
externalCode: string;
|
|
106
|
+
categoryId: string[];
|
|
107
|
+
}[];
|
|
108
|
+
categories: {
|
|
109
|
+
id: string;
|
|
110
|
+
index: number;
|
|
111
|
+
name: string;
|
|
112
|
+
externalCode: string;
|
|
113
|
+
status: string;
|
|
114
|
+
itemOfferId: string[];
|
|
115
|
+
}[];
|
|
116
|
+
items: {
|
|
117
|
+
image?: {
|
|
118
|
+
URL: string;
|
|
119
|
+
} | undefined;
|
|
120
|
+
id: string;
|
|
121
|
+
name: string;
|
|
122
|
+
description: string;
|
|
123
|
+
externalCode: string;
|
|
124
|
+
status: string;
|
|
125
|
+
unit: string;
|
|
126
|
+
}[];
|
|
127
|
+
itemOffers: {
|
|
128
|
+
id: string;
|
|
129
|
+
itemId: string;
|
|
130
|
+
index: number;
|
|
131
|
+
status: string;
|
|
132
|
+
price: {
|
|
133
|
+
value: number;
|
|
134
|
+
originalValue: number;
|
|
135
|
+
currency: string;
|
|
136
|
+
};
|
|
137
|
+
}[];
|
|
138
|
+
};
|
|
139
|
+
/** 99Food's catalogue capability, for the base URLs it was given. */
|
|
140
|
+
declare function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
|
|
144
|
+
* software PUSHES the merchant's status to the Ordering Application.
|
|
145
|
+
*
|
|
146
|
+
* `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)
|
|
147
|
+
* "sent with only the `merchantStatus` field ... will force the opening or
|
|
148
|
+
* closing of the merchant within the Ordering Application"; `merchantStatus`
|
|
149
|
+
* is `AVAILABLE | UNAVAILABLE`, "only use this type when you must close
|
|
150
|
+
* (disable) the merchant due to an unexpected event and you don't know when
|
|
151
|
+
* the service will be re-established"; 204 (200 "for compatibility"), 400,
|
|
152
|
+
* 401, 403, 404, 503 (openapi.yaml v1.7.1, README "Pausing a store").
|
|
153
|
+
*
|
|
154
|
+
* A SWITCH, with no id and no end, so offered only when the host opts in
|
|
155
|
+
* (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path
|
|
156
|
+
* (the spec files this webhook under the key `/v1/menuUpdated` while its own
|
|
157
|
+
* description and route table say `POST /v1/merchantUpdate`; the latter is
|
|
158
|
+
* sent), that 99Food implements it at all, and that the token names the
|
|
159
|
+
* merchant (Open Delivery authenticates per merchant, so the body names none).
|
|
160
|
+
*/
|
|
161
|
+
/** Set the merchant's status. */
|
|
162
|
+
declare function openDeliverySetMerchantStatus(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls, status: "AVAILABLE" | "UNAVAILABLE"): Promise<OutboundResult>;
|
|
163
|
+
/** 99Food's availability capability: Open Delivery's merchant status, a switch. */
|
|
164
|
+
declare function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability;
|
|
165
|
+
|
|
96
166
|
/** How long 99Food may take to answer a cancellation request. ESTIMATED: the spec names no deadline. */
|
|
97
167
|
declare const NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS: number;
|
|
98
168
|
interface NinetyNineFoodAdapterConfig {
|
|
@@ -109,8 +179,15 @@ interface NinetyNineFoodAdapterConfig {
|
|
|
109
179
|
* per-order deep link, so the link is the portal. Required; https only.
|
|
110
180
|
*/
|
|
111
181
|
portalUrl: string;
|
|
182
|
+
/**
|
|
183
|
+
* OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open
|
|
184
|
+
* Delivery's `merchantStatus`, a store-wide switch with no id: a store the
|
|
185
|
+
* owner also closed by hand on 99Food during the kitchen's pause is opened
|
|
186
|
+
* with it. A host turns this on knowing that.
|
|
187
|
+
*/
|
|
188
|
+
pauseByStoreSwitch?: boolean;
|
|
112
189
|
}
|
|
113
190
|
/** Build the 99Food adapter. Its reasons are static: a dialog never waits on 99Food. */
|
|
114
191
|
declare function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig): MarketplaceAdapter;
|
|
115
192
|
|
|
116
|
-
export { NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS, NINETY_NINE_FOOD_PROVIDER, NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterConfig, type NinetyNineFoodAdapterCopy, type NinetyNineFoodApiBaseUrls, type NinetyNineFoodReasonCode, createNinetyNineFoodAdapter, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature };
|
|
193
|
+
export { NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS, NINETY_NINE_FOOD_PROVIDER, NINETY_NINE_FOOD_REASON_CODES, type NinetyNineFoodAdapterConfig, type NinetyNineFoodAdapterCopy, type NinetyNineFoodApiBaseUrls, type NinetyNineFoodReasonCode, createNinetyNineFoodAdapter, normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, openDeliveryAvailability, openDeliveryCatalogue, openDeliveryMenuDocument, openDeliverySetMerchantStatus, verifyOpenDeliverySignature };
|
package/dist/99food/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
stableUuid
|
|
3
|
+
} from "../chunk-M2V4RFMA.js";
|
|
1
4
|
import {
|
|
2
5
|
asString,
|
|
3
6
|
firstCents,
|
|
@@ -10,7 +13,7 @@ import {
|
|
|
10
13
|
import {
|
|
11
14
|
answered,
|
|
12
15
|
outboundResultOf
|
|
13
|
-
} from "../chunk-
|
|
16
|
+
} from "../chunk-SZRZTLVU.js";
|
|
14
17
|
import {
|
|
15
18
|
__name
|
|
16
19
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -297,6 +300,111 @@ function openDeliveryRequestCancellation(ctx, bases, order, input) {
|
|
|
297
300
|
}
|
|
298
301
|
__name(openDeliveryRequestCancellation, "openDeliveryRequestCancellation");
|
|
299
302
|
|
|
303
|
+
// src/99food/catalogue.ts
|
|
304
|
+
function categoriesOf(merchantId, entries) {
|
|
305
|
+
const byName = /* @__PURE__ */ new Map();
|
|
306
|
+
for (const entry of entries) {
|
|
307
|
+
const name = entry.categoryName.trim();
|
|
308
|
+
const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };
|
|
309
|
+
category.offers.push(stableUuid(`${entry.ref}:offer`));
|
|
310
|
+
byName.set(name, category);
|
|
311
|
+
}
|
|
312
|
+
return [...byName.values()];
|
|
313
|
+
}
|
|
314
|
+
__name(categoriesOf, "categoriesOf");
|
|
315
|
+
function openDeliveryMenuDocument(input) {
|
|
316
|
+
const { externalMerchantId: merchantId, entries, options } = input;
|
|
317
|
+
const categories = categoriesOf(merchantId, entries);
|
|
318
|
+
return {
|
|
319
|
+
menus: [
|
|
320
|
+
{
|
|
321
|
+
id: stableUuid(`${merchantId}:menu`),
|
|
322
|
+
name: options.menuName,
|
|
323
|
+
externalCode: "menu",
|
|
324
|
+
categoryId: categories.map((category) => category.id)
|
|
325
|
+
}
|
|
326
|
+
],
|
|
327
|
+
categories: categories.map((category, index) => ({
|
|
328
|
+
id: category.id,
|
|
329
|
+
index,
|
|
330
|
+
name: category.name,
|
|
331
|
+
externalCode: category.name,
|
|
332
|
+
status: "AVAILABLE",
|
|
333
|
+
itemOfferId: category.offers
|
|
334
|
+
})),
|
|
335
|
+
items: entries.map((entry) => ({
|
|
336
|
+
id: stableUuid(`${entry.ref}:item`),
|
|
337
|
+
name: entry.name,
|
|
338
|
+
description: entry.description ?? "",
|
|
339
|
+
externalCode: entry.productId,
|
|
340
|
+
status: "AVAILABLE",
|
|
341
|
+
unit: "UN",
|
|
342
|
+
...entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }
|
|
343
|
+
})),
|
|
344
|
+
itemOffers: entries.map((entry, index) => {
|
|
345
|
+
const value = Math.round(entry.priceCents) / 100;
|
|
346
|
+
return {
|
|
347
|
+
id: stableUuid(`${entry.ref}:offer`),
|
|
348
|
+
itemId: stableUuid(`${entry.ref}:item`),
|
|
349
|
+
index,
|
|
350
|
+
status: "AVAILABLE",
|
|
351
|
+
price: { value, originalValue: value, currency: options.currency }
|
|
352
|
+
};
|
|
353
|
+
})
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
__name(openDeliveryMenuDocument, "openDeliveryMenuDocument");
|
|
357
|
+
async function notify(ctx, bases) {
|
|
358
|
+
const auth = await bearer(ctx, bases);
|
|
359
|
+
if (!("token" in auth)) return auth;
|
|
360
|
+
const response = await ctx.http({
|
|
361
|
+
method: "POST",
|
|
362
|
+
url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
|
|
363
|
+
headers: { Authorization: `Bearer ${auth.token}`, "X-App-MerchantId": ctx.externalMerchantId }
|
|
364
|
+
});
|
|
365
|
+
if (response.status !== 401) return outboundResultOf(response);
|
|
366
|
+
ctx.tokens.delete(tokenKey(ctx));
|
|
367
|
+
return { kind: "retry", reason: "99Food refused the token" };
|
|
368
|
+
}
|
|
369
|
+
__name(notify, "notify");
|
|
370
|
+
function openDeliveryCatalogue(bases) {
|
|
371
|
+
return {
|
|
372
|
+
mode: "pull",
|
|
373
|
+
menuDocument: openDeliveryMenuDocument,
|
|
374
|
+
notifyMenuChanged: /* @__PURE__ */ __name((ctx) => answered(() => notify(ctx, bases)), "notifyMenuChanged")
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
__name(openDeliveryCatalogue, "openDeliveryCatalogue");
|
|
378
|
+
|
|
379
|
+
// src/99food/pause.ts
|
|
380
|
+
function openDeliverySetMerchantStatus(ctx, bases, status) {
|
|
381
|
+
return answered(async () => {
|
|
382
|
+
const auth = await bearer(ctx, bases);
|
|
383
|
+
if (!("token" in auth)) return auth;
|
|
384
|
+
const response = await ctx.http({
|
|
385
|
+
method: "POST",
|
|
386
|
+
url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
|
|
387
|
+
headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
|
|
388
|
+
body: JSON.stringify({ merchantStatus: status })
|
|
389
|
+
});
|
|
390
|
+
if (response.status !== 401) return outboundResultOf(response);
|
|
391
|
+
ctx.tokens.delete(tokenKey(ctx));
|
|
392
|
+
return { kind: "retry", reason: "99Food refused the token" };
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
__name(openDeliverySetMerchantStatus, "openDeliverySetMerchantStatus");
|
|
396
|
+
function openDeliveryAvailability(bases) {
|
|
397
|
+
return {
|
|
398
|
+
kind: "switch",
|
|
399
|
+
pause: /* @__PURE__ */ __name(async (ctx, request) => {
|
|
400
|
+
const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
|
|
401
|
+
return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
|
|
402
|
+
}, "pause"),
|
|
403
|
+
resume: /* @__PURE__ */ __name((ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"), "resume")
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
__name(openDeliveryAvailability, "openDeliveryAvailability");
|
|
407
|
+
|
|
300
408
|
// src/99food/index.ts
|
|
301
409
|
var NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS = 5 * 6e4;
|
|
302
410
|
var ITEM_UNAVAILABLE = "UNAVAILABLE_ITEM";
|
|
@@ -342,10 +450,13 @@ function createNinetyNineFoodAdapter(config) {
|
|
|
342
450
|
readSignature: /* @__PURE__ */ __name((header) => header("x-app-signature"), "readSignature"),
|
|
343
451
|
verifySignature: verifyOpenDeliverySignature,
|
|
344
452
|
cancellationReasons: /* @__PURE__ */ __name(() => reasons, "cancellationReasons"),
|
|
453
|
+
// PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).
|
|
454
|
+
catalogue: openDeliveryCatalogue(bases),
|
|
345
455
|
fetchOrder: /* @__PURE__ */ __name((ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions), "fetchOrder"),
|
|
346
456
|
confirm: /* @__PURE__ */ __name((ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input), "confirm"),
|
|
347
457
|
requestCancellation: /* @__PURE__ */ __name((ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input), "requestCancellation"),
|
|
348
|
-
appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink")
|
|
458
|
+
appLink: /* @__PURE__ */ __name(() => config.portalUrl, "appLink"),
|
|
459
|
+
...config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}
|
|
349
460
|
};
|
|
350
461
|
}
|
|
351
462
|
__name(createNinetyNineFoodAdapter, "createNinetyNineFoodAdapter");
|
|
@@ -356,6 +467,10 @@ export {
|
|
|
356
467
|
createNinetyNineFoodAdapter,
|
|
357
468
|
normalizeOpenDeliveryEvent,
|
|
358
469
|
normalizeOpenDeliveryOrder,
|
|
470
|
+
openDeliveryAvailability,
|
|
471
|
+
openDeliveryCatalogue,
|
|
472
|
+
openDeliveryMenuDocument,
|
|
473
|
+
openDeliverySetMerchantStatus,
|
|
359
474
|
verifyOpenDeliverySignature
|
|
360
475
|
};
|
|
361
476
|
//# sourceMappingURL=index.js.map
|