@12-apps/marketplace 1.15.1 → 1.17.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 +146 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CjVdMhZ2.d.ts → adapter-CxzF-qGx.d.ts} +185 -2
- package/dist/{chunk-TRUK5ZBE.js → chunk-7IYUO2KC.js} +2 -2
- package/dist/{chunk-BTKVZAJI.js → chunk-CF5BSXE5.js} +1 -1
- package/dist/chunk-CF5BSXE5.js.map +1 -0
- package/dist/{chunk-DJIMUEHT.js → chunk-EABVLQKK.js} +79 -7
- package/dist/chunk-EABVLQKK.js.map +1 -0
- package/dist/{chunk-H2VQRD3B.js → chunk-KKFMDV5K.js} +1 -1
- package/dist/chunk-KKFMDV5K.js.map +1 -0
- package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
- package/dist/chunk-LO7OKO6V.js.map +1 -0
- package/dist/{chunk-TICWLBSA.js → chunk-UZO2NILN.js} +365 -6
- package/dist/chunk-UZO2NILN.js.map +1 -0
- package/dist/{client-DgzCkl8u.d.ts → client-C-4QvVq3.d.ts} +1 -1
- package/dist/{engine-DSRj7qnC.d.ts → engine-Y6Rpf5p7.d.ts} +430 -185
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +4 -4
- package/dist/ifood/index.d.ts +65 -2
- package/dist/ifood/index.js +374 -23
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +21 -4
- package/dist/index.js +381 -42
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/index.d.ts +78 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +6 -2
- package/dist/manifest/server.js +4 -4
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +93 -7
- package/dist/server/index.js +4 -4
- package/package.json +1 -1
- package/prisma/marketplace.prisma +69 -1
- package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
- package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
- package/src/core/adapter.ts +12 -1
- package/src/core/app-linking.ts +396 -0
- package/src/core/dispute-engine.ts +32 -0
- package/src/core/dispute-job.ts +142 -0
- package/src/core/dispute-port.ts +133 -0
- package/src/core/dispute-store.ts +203 -0
- package/src/core/disputes.ts +263 -0
- package/src/core/engine.ts +4 -55
- package/src/core/integration.ts +3 -1
- package/src/core/link-engine.ts +176 -0
- package/src/core/link-store.ts +15 -0
- package/src/core/linking-port.ts +35 -1
- package/src/core/linking.ts +8 -0
- package/src/core/outbound-sweep.ts +9 -1
- package/src/core/pipeline.ts +8 -3
- package/src/core/ports.ts +15 -0
- package/src/core/types.ts +8 -0
- package/src/ifood/app-linking.ts +119 -0
- package/src/ifood/disputes.ts +209 -0
- package/src/ifood/index.ts +25 -1
- package/src/ifood/logistics.ts +195 -0
- package/src/ifood/normalize.ts +3 -0
- package/src/ifood/outbound.ts +1 -1
- package/src/index.ts +34 -0
- package/src/server/jobs.ts +51 -3
- package/src/server/link-routes.ts +56 -4
- package/src/server/mcp-link.ts +44 -2
- package/src/server/mcp.ts +2 -1
- package/dist/chunk-BTKVZAJI.js.map +0 -1
- package/dist/chunk-DJIMUEHT.js.map +0 -1
- package/dist/chunk-H2VQRD3B.js.map +0 -1
- package/dist/chunk-SGOTN5PX.js.map +0 -1
- package/dist/chunk-TICWLBSA.js.map +0 -1
- /package/dist/{chunk-TRUK5ZBE.js.map → chunk-7IYUO2KC.js.map} +0 -0
package/ADOPTING.md
CHANGED
|
@@ -359,6 +359,46 @@ software's own app"). What the host binds and decides:
|
|
|
359
359
|
- **A view** gains `authMode`; a host that switches on it treats an absent
|
|
360
360
|
value as `CREDENTIALS`.
|
|
361
361
|
|
|
362
|
+
### 9.1 iFood links through the CENTRALIZED app (FUT-5798)
|
|
363
|
+
|
|
364
|
+
iFood offers its webhook only to centralized apps, so the iFood adapter now
|
|
365
|
+
declares `appLinking` beside `linking`, and `appLinking` wins at every entry
|
|
366
|
+
point: every new link is centralized. `linking` (`IFOOD_LINKING`) stays
|
|
367
|
+
declared so a store linked through the code flow keeps refreshing its own
|
|
368
|
+
token until it links again. Nothing
|
|
369
|
+
is typed or pasted: the store authorizes the software's app on the Portal do
|
|
370
|
+
Parceiro, the app's own `client_credentials` token lists every store that
|
|
371
|
+
authorized it, and the store picks its own. Additive for a host:
|
|
372
|
+
|
|
373
|
+
- **Routes.** `POST …/link/start` opens an attempt (30 minutes, renewed by
|
|
374
|
+
each read) and asks iFood nothing; its `pending` has `mode: "app"`, an empty
|
|
375
|
+
`userCode`, the portal as `verificationUrl`, and `seenAt` / `checkedAt`.
|
|
376
|
+
`POST …/link/check` asks the list now (`merchants`, each with `taken` and
|
|
377
|
+
`address`; `pending.seenAt` is when a store to pick first appeared).
|
|
378
|
+
`GET …/link/merchants` is the same list. `PUT …/link/merchant` writes the
|
|
379
|
+
LINKED connection (refused `UNKNOWN_MERCHANT`, `MERCHANT_TAKEN`).
|
|
380
|
+
`POST …/link/cancel` is Cancelar. `POST …/link/finish` answers 409
|
|
381
|
+
`UNAVAILABLE` for a centralized adapter.
|
|
382
|
+
- **No ownership proof beyond the portal.** iFood exposes no CNPJ in the list
|
|
383
|
+
or the detail; the authorization is the proof. Only a store another
|
|
384
|
+
account's live connection holds is refused (the claim guard).
|
|
385
|
+
- **The job.** `marketplace.link-check` ticks each minute and queues one
|
|
386
|
+
half-minute pass while a store waits (`enqueue` with `delayMs`), so a
|
|
387
|
+
waiting attempt is asked every 30 seconds without a sub-minute scheduler.
|
|
388
|
+
`GET …/link` also asks once when its last check is 30 s old (on every
|
|
389
|
+
driver: at most one list call per 30 s per attempt), which is what a host
|
|
390
|
+
with no worker relies on. Every read of a live attempt renews it.
|
|
391
|
+
- **The hint.** Bind the optional port `publishLinkSeen(clientId, provider)`
|
|
392
|
+
to tell that store's open screen to read again; payload-free. The screen
|
|
393
|
+
should not poll.
|
|
394
|
+
- **Outbound.** A centralized link's blob holds no token (`{ app: true }`):
|
|
395
|
+
its calls use the app's client-credentials token, from the same cache key
|
|
396
|
+
as every other call of that app. A LINKED row from the distributed flow
|
|
397
|
+
keeps its refresh-token path.
|
|
398
|
+
- **Migration** `20261203180000_marketplace_app_link_check` adds
|
|
399
|
+
`marketplace_link_attempts.seen_at`, `.checked_at` and an index on
|
|
400
|
+
`expires_at`: additive.
|
|
401
|
+
|
|
362
402
|
## 10. The marketplace's own courier and the pickup code (FUT-5665)
|
|
363
403
|
|
|
364
404
|
When the marketplace's fleet carries a bag (`deliveredBy: "MARKETPLACE"`;
|
|
@@ -745,3 +785,109 @@ host), the mapping is:
|
|
|
745
785
|
exports `normalizedLineTotalCents`, `NormalizedLineOption`,
|
|
746
786
|
`NormalizedPayments`, `NormalizedPaymentMethod`, `MarketplacePaymentMethod`,
|
|
747
787
|
`NormalizedOrderFee`.
|
|
788
|
+
|
|
789
|
+
## 14. iFood Logistics: the store's own motoboy reported to iFood (FUT-5988)
|
|
790
|
+
|
|
791
|
+
When the store's own motoboy carries an iFood order (`deliveredBy: MERCHANT`),
|
|
792
|
+
iFood's **Logistics** module lets the software report the delivery, so the
|
|
793
|
+
customer follows it in the iFood app. `@12-apps/marketplace/ifood` exports the
|
|
794
|
+
wire client (`src/ifood/logistics.ts`); which step is sent when, and the job
|
|
795
|
+
that sends it, are the host's.
|
|
796
|
+
|
|
797
|
+
- **A second app.** Logistics is its own iFood app (category Logística,
|
|
798
|
+
centralized), so the call context carries THAT app's client id and secret,
|
|
799
|
+
never the store's PDV credentials and never a linked store's grant. Its token
|
|
800
|
+
is cached under its own client id, apart from the PDV app's.
|
|
801
|
+
- **`ifoodLogisticsAssignDriver(ctx, orderId, driver)`**: name, phone (sent as
|
|
802
|
+
digits, 10 to 13 of them) and one of `IFOOD_LOGISTICS_VEHICLES`. An invalid
|
|
803
|
+
driver answers `{ kind: "invalid" }` and nothing is sent. A second
|
|
804
|
+
assignment is iFood's 409, a `refused`.
|
|
805
|
+
- **`ifoodLogisticsStep(ctx, orderId, step)`**: `GOING_TO_ORIGIN`,
|
|
806
|
+
`ARRIVED_AT_ORIGIN`, `DISPATCHED`, `ARRIVED_AT_DESTINATION`. iFood takes them
|
|
807
|
+
asynchronously (202) and only in that order: out of order is 409.
|
|
808
|
+
`ifoodLogisticsStepsTo(lastSent, target)` names the steps still owed, in
|
|
809
|
+
order, so a host that reaches `DISPATCHED` straight from the assignment sends
|
|
810
|
+
the two origin steps first.
|
|
811
|
+
- **`ifoodLogisticsVerifyDeliveryCode(ctx, orderId, code)`**: `verified`,
|
|
812
|
+
`wrong-code` (iFood's `success: false` or 422: the motoboy may type it
|
|
813
|
+
again), `not-requested` (412: the order never asked for a code), or the
|
|
814
|
+
usual `refused` / `retry`. The code is never logged.
|
|
815
|
+
- **No live location.** iFood's guides have no endpoint for the motoboy's
|
|
816
|
+
position or route (read 2026-12-01).
|
|
817
|
+
- Every result is an `OutboundResult` shape: 429, 408 and 5xx are retries, a
|
|
818
|
+
401 renews the token once inside the call.
|
|
819
|
+
|
|
820
|
+
## 15. Buyer disputes: iFood's Negotiation Platform (FUT-6099)
|
|
821
|
+
|
|
822
|
+
A buyer asks the marketplace, after ordering, for a refund or a change (iFood's
|
|
823
|
+
"Plataforma de Negociação", handshake disputes), and the store answers:
|
|
824
|
+
accept, reject with one of the marketplace's reasons, or offer one of the
|
|
825
|
+
alternatives the marketplace sent for THAT dispute. The engine keeps each
|
|
826
|
+
dispute per order, sends the answer from a job and closes the dispute on the
|
|
827
|
+
marketplace's settlement. Everything is additive and optional: a host that
|
|
828
|
+
composes no table keeps its orders as before: a dispute event fails its inbox
|
|
829
|
+
row (FAILED), is retried by the reconcile pass, then retired by the attempt
|
|
830
|
+
bound.
|
|
831
|
+
|
|
832
|
+
### 15.1 The cases
|
|
833
|
+
|
|
834
|
+
Every case is a test in `src/__tests__/disputes.test.ts` (and the PGlite case
|
|
835
|
+
in `migration.test.ts`); on `main` (`7dc036c3`) the file did not import: no
|
|
836
|
+
dispute module existed.
|
|
837
|
+
|
|
838
|
+
| id | event / call | this release |
|
|
839
|
+
|---|---|---|
|
|
840
|
+
| D1 | iFood `HANDSHAKE_DISPUTE` (HSD) on an order the engine holds | one `marketplace_disputes` row, OPEN, with what iFood sent: `action`, `handshakeType`, `reason`, `message`, the https photos (`evidences`, other schemes dropped), the disputed lines (`garnishItems`), the asked amount, `expiresAt`, `timeoutAction`, `alternatives` (REFUND / BENEFIT with `maxAmount`, ADDITIONAL_TIME with its allowed minutes), the rejection reasons (`negotiationReasons`) and the accept reasons (`acceptCancellationReasons`); inbox PROCESSED; `publishChanged` and `order.onDispute(…, { kind: "opened" })` after the commit; the acceptance row and the order untouched; no call to iFood; outcome `{ kind: "dispute", change: "opened" }` |
|
|
841
|
+
| D2 | the same HSD redelivered / another event id for the same dispute | `duplicate` / `change: "unchanged"`, still one row (unique `(provider, dispute_id)`) |
|
|
842
|
+
| D3 | HSD before its order | deferred PENDING (`dispute before its order`); the reconcile pass applies it once the order is ingested |
|
|
843
|
+
| D4 | `HANDSHAKE_SETTLEMENT` (HSS) | SETTLED with `settlement` ACCEPTED / REJECTED / EXPIRED / ALTERNATIVE_REPLIED (OTHER for an unknown word), `settledAt`, the amount; `onDispute(…, { kind: "settled" })` |
|
|
844
|
+
| D5 | HSS before its HSD | deferred PENDING (`settlement before its dispute`) |
|
|
845
|
+
| D15 | HSD whatever the acceptance's status (delivered, cancelled, in preparation) | kept: a dispute never reads or moves the acceptance |
|
|
846
|
+
| D6 | `answerDispute` ACCEPT | judged, claimed OPEN → SENDING (`updateMany … status: "OPEN"`, so two tablets never both answer), `marketplace.dispute-answer` `{ clientId, disputeId }` queued (key `…:<disputeId>:<answered at ms>`), no call; the job `POST /order/v1.0/disputes/{id}/accept` with no body → ANSWERED |
|
|
847
|
+
| D6b | ACCEPT when iFood listed accept reasons | the FIRST listed is sent (`{ reason }`); a person gives none (owner, 2026-12-03: no PIN, no reason) |
|
|
848
|
+
| D7 | REJECT | only a code iFood sent for THIS dispute (`INVALID_REASON` otherwise); `POST …/reject` `{ reason }` |
|
|
849
|
+
| D8 | ALTERNATIVE refund / benefit (an alternative whose stated `maxAmount` is not whole cents is not offered at all) | a positive whole number of cents, at most the alternative's `maxAmount` (`INVALID_AMOUNT`); an id iFood did not send is `INVALID_ALTERNATIVE`; `POST …/alternatives/{alternativeId}` `{ type, metadata: { amount: { value: "<cents>", currency: "BRL" } } }` |
|
|
850
|
+
| D9 | ALTERNATIVE more time | positive minutes, one of those iFood allows when it lists some (`INVALID_MINUTES`); `{ type: "ADDITIONAL_TIME", metadata: { additionalTimeInMinutes } }` |
|
|
851
|
+
| D10 | an unknown dispute (or one of another order than the `orderId` given) / past `expiresAt` / already answered | `NOT_FOUND` / `EXPIRED` / `ALREADY_ANSWERED`, refused locally, nothing claimed, nothing queued |
|
|
852
|
+
| D11 | the job's answer | 2xx → ANSWERED; `422 DISPUTE_ALREADY_ANSWERED` → ANSWERED with `failure: ALREADY_ANSWERED` (another device or iFood's portal answered first); `404`, `400 INVALID_REASON` / `INVALID_AMOUNT`, any other final 4xx → back to OPEN with that code and the answer cleared, so a person answers again; 408/429/5xx/timeout retried (3 attempts from 10 s), the last → OPEN, UNREACHABLE; a row no longer SENDING → skipped, no call |
|
|
853
|
+
| D12 | `disputes({ clientId, settledSince })` | one statement: every dispute OPEN, SENDING or ANSWERED, plus those settled since then (the board's shift); `disputes({ clientId, orderIds })` the orders' own ; a host that folds the read into one of its own statements maps each `marketplace_disputes` row with the exported `disputeView(row: DisputeRow)` |
|
|
854
|
+
| D13 | a marketplace without disputes (99Food, Keeta, Rappi) | `capabilities.disputes` and `adapter.disputes` absent; an answer on its row is `UNSUPPORTED` |
|
|
855
|
+
| D14 | an answer still SENDING | the `marketplace.outbound-sweep` re-queues it after 10 minutes (counted in `requeued`), and gives it back OPEN, UNREACHABLE after a day (counted in `givenUp`) |
|
|
856
|
+
|
|
857
|
+
### 15.2 Invariants
|
|
858
|
+
|
|
859
|
+
- **No call to the marketplace in a request.** The webhook records and applies
|
|
860
|
+
the event; `answerDispute` claims and queues. Only the
|
|
861
|
+
`marketplace.dispute-answer` job calls iFood, through the host's `http` port.
|
|
862
|
+
- **One answer per dispute.** The claim is predicated on OPEN; the job sends
|
|
863
|
+
only from SENDING; a failure gives the dispute back OPEN with its code.
|
|
864
|
+
- **Only what the marketplace offers.** Reasons, alternatives, amounts and
|
|
865
|
+
minutes are judged against the dispute's own row, never a static list.
|
|
866
|
+
- **A dispute moves no order.** No admit, no claim, no `onRefused`, no stock.
|
|
867
|
+
- **The engine writes no sentence.** `MarketplaceDisputeView` carries codes,
|
|
868
|
+
numbers and the marketplace's own words; every sentence is the host's.
|
|
869
|
+
|
|
870
|
+
### 15.3 What is still ESTIMATED
|
|
871
|
+
|
|
872
|
+
iFood's developer portal answered 403 (Cloudflare) to curl and WebFetch on
|
|
873
|
+
2026-12-02, so `src/ifood/disputes.ts` follows four independent public
|
|
874
|
+
write-ups of iFood's handshake guide, not iFood's page. Not verified live:
|
|
875
|
+
|
|
876
|
+
- U1, the proposal endpoint: `POST …/disputes/{id}/alternatives/{alternativeId}`
|
|
877
|
+
with `{ type, metadata }`; the other reading is `POST …/disputes/{id}/alternative`
|
|
878
|
+
with the type in the body;
|
|
879
|
+
- U2, whether accept takes a reason: sent only when iFood lists accept reasons;
|
|
880
|
+
- the field names inside `metadata` (`garnishItems`, `negotiationReasons`,
|
|
881
|
+
`allowedsAdditionalTimeInMinutes`, `selectedDisputeAlternative`), money as
|
|
882
|
+
cents in `{ value }`, and the success code (201 or 202: any 2xx is taken).
|
|
883
|
+
|
|
884
|
+
### 15.4 What the host binds
|
|
885
|
+
|
|
886
|
+
| | |
|
|
887
|
+
|---|---|
|
|
888
|
+
| **Database** | Compose the partial (`MarketplaceDispute`) and run `20261203190000_marketplace_disputes` (one new table, additive) with the bump: sync the partial, `prisma generate`, migrate. `MarketplaceDb.marketplaceDispute` is OPTIONAL in the type: without it `disputes` answers `[]`, `answerDispute` `NOT_FOUND`, and a dispute event fails its inbox row (retried by the reconcile pass, then retired). A host that wants it adds `marketplace_disputes.order_id → <orders>(id) ON DELETE CASCADE`. |
|
|
889
|
+
| **Job** | `marketplace.dispute-answer` arrives with `MARKETPLACE_JOBS` (bind `{ engine }`); allow it through any job allow-list in front of the queue. |
|
|
890
|
+
| **Hook** | OPTIONAL `order.onDispute(clientId, orderId, { kind: "opened" \| "settled", disputeId })`, after the commit: refresh the board, tell a person. A throw is logged. `publishChanged` is called either way. |
|
|
891
|
+
| **Read** | `engine.disputes({ clientId, settledSince })` for the board (the host's own shift start), `{ orderIds }` for an order. Draw `status` OPEN (with `expiresAt`'s countdown; past it, the host's "deadline gone" line and no answer), SENDING / ANSWERED (what was sent, `answer`, and "waiting on the marketplace"; `failure: ALREADY_ANSWERED` means another answer stood), SETTLED (`settlement.outcome`). A `failure` on an OPEN dispute is the last answer's refusal: say so beside the answer controls. |
|
|
892
|
+
| **Answer** | `engine.answerDispute({ clientId, disputeId, orderId, answer })` (pass the order the person acted on: a dispute of another order is NOT_FOUND before anything is claimed) with `{ kind: "ACCEPT" }`, `{ kind: "REJECT", reasonCode }` or `{ kind: "ALTERNATIVE", alternativeId, amountCents? , minutes? }`. Answers `queued` with the view, or `refused` with `NOT_FOUND`, `ALREADY_ANSWERED`, `EXPIRED`, `UNSUPPORTED`, `INVALID_REASON`, `INVALID_ALTERNATIVE`, `INVALID_AMOUNT` or `INVALID_MINUTES`. Gate it with `marketplace:decide`. |
|
|
893
|
+
| **Capability** | `engine.adapter(provider)?.capabilities.disputes` (iFood only). Offer Recusar only when `rejectReasons` is not empty, and Propor only when `alternatives` is not empty. |
|
package/dist/99food/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-
|
|
2
|
-
import { O as OpenDeliveryApiBaseUrls } from '../client-
|
|
1
|
+
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, C as CatalogueMenuEntry, b as CatalogueMenuOptions, P as PullCatalogue, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CxzF-qGx.js';
|
|
2
|
+
import { O as OpenDeliveryApiBaseUrls } from '../client-C-4QvVq3.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* The words the 99Food adapter needs from its host, and nothing else.
|
package/dist/99food/index.js
CHANGED
|
@@ -12,10 +12,10 @@ import {
|
|
|
12
12
|
openDeliveryStatus,
|
|
13
13
|
openDeliverySwitchAvailability,
|
|
14
14
|
verifyOpenDeliverySignature
|
|
15
|
-
} from "../chunk-
|
|
15
|
+
} from "../chunk-7IYUO2KC.js";
|
|
16
16
|
import "../chunk-M2V4RFMA.js";
|
|
17
17
|
import "../chunk-E4XJXHUK.js";
|
|
18
|
-
import "../chunk-
|
|
18
|
+
import "../chunk-CF5BSXE5.js";
|
|
19
19
|
import {
|
|
20
20
|
__name
|
|
21
21
|
} from "../chunk-7QVYU63E.js";
|
|
@@ -160,6 +160,136 @@ interface PullCatalogue {
|
|
|
160
160
|
/** The catalogue capability an adapter states, or leaves out. */
|
|
161
161
|
type MarketplaceCatalogue = PushCatalogue | PullCatalogue;
|
|
162
162
|
|
|
163
|
+
/**
|
|
164
|
+
* A marketplace's disputes (FUT-6099): the buyer asks the marketplace for a
|
|
165
|
+
* refund or a change AFTER the order was placed (iFood's Negotiation Platform,
|
|
166
|
+
* "Plataforma de Negociação"), and the store answers: accept, reject with one
|
|
167
|
+
* of the marketplace's reasons, or offer one of the alternatives the
|
|
168
|
+
* marketplace sent. Provider-neutral: what a dispute carries is read by the
|
|
169
|
+
* adapter, kept by the engine, drawn and worded by the host.
|
|
170
|
+
*/
|
|
171
|
+
/** The kinds of alternative a store may offer instead of what the buyer asked. */
|
|
172
|
+
type DisputeAlternativeType = "REFUND" | "BENEFIT" | "ADDITIONAL_TIME";
|
|
173
|
+
/** One alternative the marketplace allows for THIS dispute. */
|
|
174
|
+
interface DisputeAlternative {
|
|
175
|
+
/** The marketplace's id for it; sent back with the proposal. */
|
|
176
|
+
id: string;
|
|
177
|
+
type: DisputeAlternativeType;
|
|
178
|
+
/** A refund or a benefit: the most the store may offer, in cents; null when the marketplace states none. */
|
|
179
|
+
maxAmountCents: number | null;
|
|
180
|
+
/** More time: the minutes the marketplace allows, when it lists them; empty when it states none. */
|
|
181
|
+
allowedMinutes: number[];
|
|
182
|
+
}
|
|
183
|
+
/** One reason the marketplace accepts with an answer: its code and its own words. */
|
|
184
|
+
interface DisputeReason {
|
|
185
|
+
code: string;
|
|
186
|
+
description: string;
|
|
187
|
+
}
|
|
188
|
+
/** One line the buyer disputes, as the marketplace lists it. */
|
|
189
|
+
interface DisputeItem {
|
|
190
|
+
name: string;
|
|
191
|
+
quantity: number;
|
|
192
|
+
/** What the line cost, in cents; null when unstated. */
|
|
193
|
+
amountCents: number | null;
|
|
194
|
+
}
|
|
195
|
+
/** A dispute the marketplace opened, normalized. */
|
|
196
|
+
interface NormalizedDisputeOpened {
|
|
197
|
+
/** The marketplace's id for the dispute: the key of every answer. */
|
|
198
|
+
disputeId: string;
|
|
199
|
+
/** What the buyer asks, the marketplace's own code (iFood: CANCELLATION, PARTIAL_CANCELLATION, …). */
|
|
200
|
+
action: string;
|
|
201
|
+
/** When in the order's life it was opened (iFood: AFTER_DELIVERY, PREPARATION_TIME, DELAY, …); null unstated. */
|
|
202
|
+
handshakeType: string | null;
|
|
203
|
+
/** Why, in the marketplace's words ("Faltou item"); null unstated. */
|
|
204
|
+
reason: string | null;
|
|
205
|
+
/** The buyer's own words; null unstated. */
|
|
206
|
+
message: string | null;
|
|
207
|
+
/** The buyer's photos: https URLs only. */
|
|
208
|
+
evidenceUrls: string[];
|
|
209
|
+
items: DisputeItem[];
|
|
210
|
+
/** What the buyer asks back, in cents; null unstated. */
|
|
211
|
+
requestedAmountCents: number | null;
|
|
212
|
+
/** The store's deadline; null unstated. */
|
|
213
|
+
expiresAt: Date | null;
|
|
214
|
+
/** When the buyer opened it; null unstated (the engine then keeps its clock). */
|
|
215
|
+
openedAt: Date | null;
|
|
216
|
+
/** What the marketplace does when the store does not answer (iFood: ACCEPT_CANCELLATION, …); null unstated. */
|
|
217
|
+
timeoutAction: string | null;
|
|
218
|
+
alternatives: DisputeAlternative[];
|
|
219
|
+
/** The reasons a rejection may carry, as the marketplace sent them for this dispute. */
|
|
220
|
+
rejectReasons: DisputeReason[];
|
|
221
|
+
/** The reasons an acceptance may carry; sent only when the marketplace lists some. */
|
|
222
|
+
acceptReasons: DisputeReason[];
|
|
223
|
+
}
|
|
224
|
+
/** How the marketplace closed a dispute. `OTHER`: closed, with a word the engine does not know. */
|
|
225
|
+
type DisputeOutcome = "ACCEPTED" | "REJECTED" | "EXPIRED" | "ALTERNATIVE_REPLIED" | "OTHER";
|
|
226
|
+
/** A dispute the marketplace closed, normalized. */
|
|
227
|
+
interface NormalizedDisputeSettled {
|
|
228
|
+
disputeId: string;
|
|
229
|
+
outcome: DisputeOutcome;
|
|
230
|
+
/** When it closed; null unstated. */
|
|
231
|
+
at: Date | null;
|
|
232
|
+
/** What was refunded or granted, in cents; null unstated. */
|
|
233
|
+
amountCents: number | null;
|
|
234
|
+
}
|
|
235
|
+
/** What a delivery says about a dispute, when it says one. */
|
|
236
|
+
type NormalizedDisputeEvent = {
|
|
237
|
+
kind: "opened";
|
|
238
|
+
dispute: NormalizedDisputeOpened;
|
|
239
|
+
} | {
|
|
240
|
+
kind: "settled";
|
|
241
|
+
settlement: NormalizedDisputeSettled;
|
|
242
|
+
};
|
|
243
|
+
/** The store's answer, as it is sent. */
|
|
244
|
+
type DisputeAnswer = {
|
|
245
|
+
kind: "ACCEPT";
|
|
246
|
+
reasonCode: string | null;
|
|
247
|
+
} | {
|
|
248
|
+
kind: "REJECT";
|
|
249
|
+
reasonCode: string;
|
|
250
|
+
} | {
|
|
251
|
+
kind: "ALTERNATIVE";
|
|
252
|
+
alternative: DisputeAlternative;
|
|
253
|
+
amountCents: number | null;
|
|
254
|
+
minutes: number | null;
|
|
255
|
+
};
|
|
256
|
+
/** Why an answer did not land. */
|
|
257
|
+
type DisputeFailureCode = "ALREADY_ANSWERED" | "NOT_FOUND" | "INVALID_REASON" | "INVALID_AMOUNT" | "REFUSED" | "UNREACHABLE" | "NOT_CONNECTED" | "UNSUPPORTED";
|
|
258
|
+
/** One answer call's result: the outbound shapes, a refusal carrying the engine's code. */
|
|
259
|
+
type DisputeAnswerResult = {
|
|
260
|
+
kind: "accepted";
|
|
261
|
+
} | {
|
|
262
|
+
kind: "refused";
|
|
263
|
+
status: number;
|
|
264
|
+
message: string;
|
|
265
|
+
code: DisputeFailureCode;
|
|
266
|
+
} | {
|
|
267
|
+
kind: "retry";
|
|
268
|
+
reason: string;
|
|
269
|
+
};
|
|
270
|
+
/** The adapter's disputes API. Present only on a marketplace with disputes (`capabilities.disputes`). */
|
|
271
|
+
interface MarketplaceDisputeApi {
|
|
272
|
+
/** Send the store's answer to one dispute. Called only from the `marketplace.dispute-answer` job. */
|
|
273
|
+
answer(ctx: AdapterCallContext, target: {
|
|
274
|
+
externalOrderId: string;
|
|
275
|
+
disputeId: string;
|
|
276
|
+
}, answer: DisputeAnswer): Promise<DisputeAnswerResult>;
|
|
277
|
+
}
|
|
278
|
+
/** What the host hears after a dispute's commit (`order.onDispute`). */
|
|
279
|
+
interface MarketplaceDisputeChange {
|
|
280
|
+
kind: "opened" | "settled";
|
|
281
|
+
disputeId: string;
|
|
282
|
+
}
|
|
283
|
+
/** The dispute table's delegate. OPTIONAL in `MarketplaceDb`: a host that has not composed it gets no disputes. */
|
|
284
|
+
interface MarketplaceDisputeDelegate {
|
|
285
|
+
findFirst(args: unknown): Promise<unknown>;
|
|
286
|
+
findMany(args: unknown): Promise<unknown[]>;
|
|
287
|
+
create(args: unknown): Promise<unknown>;
|
|
288
|
+
updateMany(args: unknown): Promise<{
|
|
289
|
+
count: number;
|
|
290
|
+
}>;
|
|
291
|
+
}
|
|
292
|
+
|
|
163
293
|
/**
|
|
164
294
|
* The canonical shape every marketplace adapter normalizes INTO.
|
|
165
295
|
*
|
|
@@ -471,6 +601,12 @@ interface NormalizedEvent {
|
|
|
471
601
|
* host's admit, with no confirm sent back. Carries no order body.
|
|
472
602
|
*/
|
|
473
603
|
marketplaceConfirmed?: boolean;
|
|
604
|
+
/**
|
|
605
|
+
* OPTIONAL (FUT-6099). A dispute the marketplace opened or closed on this
|
|
606
|
+
* order (iFood's HSD / HSS). Carries no order body, and never moves the
|
|
607
|
+
* order or its acceptance.
|
|
608
|
+
*/
|
|
609
|
+
dispute?: NormalizedDisputeEvent | null;
|
|
474
610
|
}
|
|
475
611
|
|
|
476
612
|
/**
|
|
@@ -775,11 +911,15 @@ interface LinkGrant {
|
|
|
775
911
|
*/
|
|
776
912
|
refreshToken: string | null;
|
|
777
913
|
}
|
|
778
|
-
/** One marketplace store the grant covers. */
|
|
914
|
+
/** One marketplace store the grant (or, centralized, the app's authorization) covers. */
|
|
779
915
|
interface LinkedMerchant {
|
|
780
916
|
id: string;
|
|
781
917
|
name: string | null;
|
|
782
918
|
corporateName: string | null;
|
|
919
|
+
/** One line of the store's address, read off its detail (centralized linking, FUT-5798); absent when not asked. */
|
|
920
|
+
address?: string | null;
|
|
921
|
+
/** Another store's live connection already holds it (centralized linking, FUT-5798); absent when not judged. */
|
|
922
|
+
taken?: boolean;
|
|
783
923
|
}
|
|
784
924
|
/**
|
|
785
925
|
* A linking call's answer: the value, or why there is none. `refused` is
|
|
@@ -814,6 +954,33 @@ interface MarketplaceLinking {
|
|
|
814
954
|
* working unchanged either way.
|
|
815
955
|
*/
|
|
816
956
|
type MarketplaceAppCredentialsPort = (provider: string, environment: "SANDBOX" | "PRODUCTION") => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
|
|
957
|
+
/**
|
|
958
|
+
* LINKING through the software's CENTRALIZED app (FUT-5798): the store
|
|
959
|
+
* authorizes the app on the marketplace's portal, and that is all. No code is
|
|
960
|
+
* typed, nothing is pasted, no token is the store's: the app's own
|
|
961
|
+
* client-credentials token sees every store that authorized it, and the store
|
|
962
|
+
* picks its own from that list. A linked connection then talks to the
|
|
963
|
+
* marketplace with the app's token, and the app's webhook brings its orders.
|
|
964
|
+
*
|
|
965
|
+
* The adapter's half is the wire format of the list and nothing else; the
|
|
966
|
+
* attempt, the claim and the rows are the engine's (`./app-linking.ts`).
|
|
967
|
+
*/
|
|
968
|
+
interface MarketplaceAppLinking {
|
|
969
|
+
/** The portal page where the store authorizes the app. Always https. */
|
|
970
|
+
readonly portalUrl: string;
|
|
971
|
+
/** Every store the app is authorized for, through the app's own token. */
|
|
972
|
+
merchants(ctx: AppLinkCallContext): Promise<LinkResult<LinkedMerchant[]>>;
|
|
973
|
+
/** One line of a store's address, for the person to recognise it; null when the detail carries none. */
|
|
974
|
+
address(ctx: AppLinkCallContext, merchantId: string): Promise<LinkResult<string | null>>;
|
|
975
|
+
}
|
|
976
|
+
/** What a centralized linking call is handed: the APP's credentials and the engine's token cache. */
|
|
977
|
+
interface AppLinkCallContext extends LinkCallContext {
|
|
978
|
+
/** The engine's per-process token cache: the app's token is shared with its outbound calls, never bought early. */
|
|
979
|
+
tokens: Map<string, {
|
|
980
|
+
token: string;
|
|
981
|
+
expiresAt: number;
|
|
982
|
+
}>;
|
|
983
|
+
}
|
|
817
984
|
/** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
|
|
818
985
|
interface MarketplaceLinkAttemptDelegate {
|
|
819
986
|
findUnique(args: unknown): Promise<unknown>;
|
|
@@ -821,6 +988,12 @@ interface MarketplaceLinkAttemptDelegate {
|
|
|
821
988
|
deleteMany(args: unknown): Promise<{
|
|
822
989
|
count: number;
|
|
823
990
|
}>;
|
|
991
|
+
/** The live attempts the periodic check walks (FUT-5798). Absent: the check finds none. */
|
|
992
|
+
findMany?(args: unknown): Promise<unknown[]>;
|
|
993
|
+
/** Stamp a check on an attempt (FUT-5798). */
|
|
994
|
+
updateMany?(args: unknown): Promise<{
|
|
995
|
+
count: number;
|
|
996
|
+
}>;
|
|
824
997
|
}
|
|
825
998
|
|
|
826
999
|
/**
|
|
@@ -1034,6 +1207,8 @@ interface MarketplaceCapabilities {
|
|
|
1034
1207
|
* it has not confirmed). Absent: steps never wait on the confirm.
|
|
1035
1208
|
*/
|
|
1036
1209
|
statusAfterConfirm?: boolean;
|
|
1210
|
+
/** OPTIONAL (FUT-6099). The buyer's disputes arrive as events and are answered through `disputes`. */
|
|
1211
|
+
disputes?: boolean;
|
|
1037
1212
|
}
|
|
1038
1213
|
/**
|
|
1039
1214
|
* A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off
|
|
@@ -1262,11 +1437,19 @@ interface MarketplaceAdapter {
|
|
|
1262
1437
|
* marketplace (FUT-5613). Absent: a store connects with its own credentials only.
|
|
1263
1438
|
*/
|
|
1264
1439
|
readonly linking?: MarketplaceLinking;
|
|
1440
|
+
/**
|
|
1441
|
+
* OPTIONAL. Linking a store through the software's CENTRALIZED app (FUT-5798):
|
|
1442
|
+
* the store authorizes the app on the portal and picks its store from the
|
|
1443
|
+
* app's list; no code, no token of its own. Wins over `linking` when both are set.
|
|
1444
|
+
*/
|
|
1445
|
+
readonly appLinking?: MarketplaceAppLinking;
|
|
1265
1446
|
/**
|
|
1266
1447
|
* OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check
|
|
1267
1448
|
* and the tracking read. Absent: neither is offered, and the host says so.
|
|
1268
1449
|
*/
|
|
1269
1450
|
readonly courier?: MarketplaceCourierApi;
|
|
1451
|
+
/** OPTIONAL (FUT-6099). Answering the buyer's disputes; present with `capabilities.disputes`. */
|
|
1452
|
+
readonly disputes?: MarketplaceDisputeApi;
|
|
1270
1453
|
/** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
|
|
1271
1454
|
appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
|
|
1272
1455
|
}
|
|
@@ -1286,4 +1469,4 @@ declare function tokenGrantResultOf(response: MarketplaceHttpResponse): Outbound
|
|
|
1286
1469
|
/** A call that never got an answer is a retry, with the reason a log can read. */
|
|
1287
1470
|
declare function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult>;
|
|
1288
1471
|
|
|
1289
|
-
export { type
|
|
1472
|
+
export { type DisputeItem as $, type AdapterCallContext as A, type CatalogueReadNotice as B, type CatalogueMenuEntry as C, type CatalogueReadRefusalCode as D, type CatalogueReadResult as E, type FetchOrderResult as F, type CatalogueReadWarning as G, type CatalogueReadWarningCode as H, type CatalogueSnapshot as I, type CatalogueSnapshotCategory as J, type CatalogueSnapshotItem as K, type CatalogueSnapshotOption as L, type MarketplaceAvailability as M, type NormalizedEvent as N, type OutboundResult as O, type PullCatalogue as P, type CatalogueSnapshotOptionGroup as Q, type CatalogueStoredImage as R, type StorePauseRequest as S, type CatalogueWarningCode as T, type CourierTrackingCallResult as U, type CourierTrackingResult as V, type DisputeAlternative as W, type DisputeAlternativeType as X, type DisputeAnswer as Y, type DisputeAnswerResult as Z, type DisputeFailureCode as _, type NormalizedMarketplaceOrder as a, type DisputeOutcome as a0, type DisputeReason as a1, type LinkCallContext as a2, type LinkCode as a3, type LinkGrant as a4, type LinkResult as a5, type LinkedMerchant as a6, type MarketplaceAcknowledgement as a7, type MarketplaceAppCredentialsPort as a8, type MarketplaceCapabilities as a9, type NormalizedLineOption as aA, type NormalizedOrderDiscount as aB, type NormalizedOrderFee as aC, type NormalizedOrderLine as aD, type NormalizedPaymentMethod as aE, type NormalizedPayments as aF, type OrderCancellationReason as aG, type OrderCancellationReasonsResult as aH, type OutboundOrderRef as aI, PROVIDER_ID_PATTERN as aJ, type PickupCodeCallResult as aK, type PickupCodeValidation as aL, type PresenceProbe as aM, type StatusFacts as aN, type StatusStep as aO, type ValidatePickupCodeInput as aP, answered as aQ, centsFromMajor as aR, normalizedLineTotalCents as aS, outboundResultOf as aT, tokenGrantResultOf as aU, type MarketplaceCatalogue as aa, type MarketplaceCourier as ab, type MarketplaceCourierAnswer as ac, type MarketplaceCourierEngine as ad, type MarketplaceCourierFacts as ae, type MarketplaceCourierStep as af, type MarketplaceCourierTracking as ag, type MarketplaceCourierVehicle as ah, type MarketplaceCredentials as ai, type MarketplaceDeliveredBy as aj, type MarketplaceDiscountSponsor as ak, type MarketplaceDisputeApi as al, type MarketplaceDisputeChange as am, type MarketplaceDisputeDelegate as an, type MarketplaceHttp as ao, type MarketplaceHttpRequest as ap, type MarketplaceHttpResponse as aq, type MarketplaceLifecycle as ar, type MarketplaceLinkAttemptDelegate as as, type MarketplaceOrderType as at, type MarketplacePaymentMethod as au, type NormalizedAddress as av, type NormalizedBuyer as aw, type NormalizedDisputeEvent as ax, type NormalizedDisputeOpened as ay, type NormalizedDisputeSettled as az, type CatalogueMenuOptions as b, type MarketplaceAdapter as c, type PushCatalogue as d, type CatalogueItemOut as e, type CatalogueReader as f, type MarketplaceLinking as g, type MarketplaceAppLinking as h, type MarketplaceCourierApi as i, type NormalizedCourierEvent as j, type StorePauseResult as k, type StorePauseRef as l, type MarketplaceProvider as m, type CancellationReason as n, type AdapterGrant as o, type AdapterTokenCache as p, type AppLinkCallContext as q, type CancellationOutcome as r, type CancellationRequestInput as s, type CatalogueCallContext as t, type CatalogueFailure as u, type CatalogueImage as v, type CatalogueItem as w, type CatalogueItemRef as x, type CataloguePublishResult as y, type CatalogueReadContext as z };
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
answered,
|
|
16
16
|
outboundResultOf,
|
|
17
17
|
tokenGrantResultOf
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-CF5BSXE5.js";
|
|
19
19
|
import {
|
|
20
20
|
__name
|
|
21
21
|
} from "./chunk-7QVYU63E.js";
|
|
@@ -483,4 +483,4 @@ export {
|
|
|
483
483
|
normalizeOpenDeliveryEventAs,
|
|
484
484
|
normalizeOpenDeliveryOrderAs
|
|
485
485
|
};
|
|
486
|
-
//# sourceMappingURL=chunk-
|
|
486
|
+
//# sourceMappingURL=chunk-7IYUO2KC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { MarketplaceDisputeApi } from \"./dispute-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceAppLinking, MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n /**\n * OPTIONAL. The HTTP status a recorded delivery is answered with (FUT-5984:\n * iFood wants `202 Accepted`). Absent: 200. Refusals and failures keep theirs.\n */\n webhookAnswerStatus?: 200 | 202;\n /**\n * OPTIONAL. The marketplace announces that the store accepted an order in the\n * marketplace's own app (`NormalizedEvent.marketplaceConfirmed`, FUT-5653).\n * Its ingest then applies a confirmation that arrived before the order.\n */\n marketplaceConfirms?: boolean;\n /**\n * OPTIONAL. A status step is told only after the marketplace took the\n * store's confirm (`confirmedAt`, FUT-5673: iFood refuses a step of an order\n * it has not confirmed). Absent: steps never wait on the confirm.\n */\n statusAfterConfirm?: boolean;\n /** OPTIONAL (FUT-6099). The buyer's disputes arrive as events and are answered through `disputes`. */\n disputes?: boolean;\n}\n\n/**\n * A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off\n * a delivery: `merchantIds` when it asks about named merchants (its\n * per-merchant mode), null when it asks about the whole app.\n */\nexport interface PresenceProbe {\n merchantIds: readonly string[] | null;\n}\n\n/** Acknowledging recorded events to the marketplace (FUT-5984: iFood's `events/acknowledgment`). */\nexport interface MarketplaceAcknowledgement {\n /** At most this many event ids per call. */\n batchSize: number;\n /** How long the marketplace keeps an event: an older one is never acknowledged. */\n retentionMs: number;\n /** Acknowledge these event ids, in one call. */\n send(ctx: AdapterCallContext, eventIds: readonly string[]): Promise<OutboundResult>;\n}\n\n/** One cancellation reason the marketplace lists for one order: its code and its own words. */\nexport interface OrderCancellationReason {\n code: string;\n description: string;\n}\n\n/** One order's reasons read from the marketplace, or the refusal / retry of the read. */\nexport type OrderCancellationReasonsResult =\n | { kind: \"reasons\"; reasons: OrderCancellationReason[] }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /**\n * The marketplace's documented reasons, static and offline: a dialog never\n * waits on the network. With `orderCancellationReasons`, the fallback of an\n * order whose own list could not be read.\n */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. The step that must be told before this one for this kind of\n * order (FUT-5984: iFood's dispatch of a merchant bag follows its\n * `readyToPickup`), or null. The status job sends it first when it is not\n * told yet.\n */\n statusPrerequisite?(facts: StatusFacts): StatusStep | null;\n /**\n * OPTIONAL. A delivery that is the marketplace's presence heartbeat, not an\n * event (FUT-5984: iFood's `KEEPALIVE`), or null. Answered 202 once its\n * signature is proved, with nothing recorded.\n */\n presence?(payload: unknown): PresenceProbe | null;\n /** OPTIONAL. Acknowledging recorded events (FUT-5984). Absent: nothing is acknowledged. */\n readonly acknowledgement?: MarketplaceAcknowledgement;\n /**\n * OPTIONAL. Read the reasons the marketplace accepts for cancelling THIS\n * order (FUT-5984: iFood's `GET /orders/{id}/cancellationReasons`). Called\n * only from the `marketplace.cancellation-reasons` job. Absent: the static\n * `cancellationReasons()` are every order's.\n */\n orderCancellationReasons?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<OrderCancellationReasonsResult>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order leaves it out. A final `refused` marked `own` with a 4xx status is\n * our credentials refused: the engine stamps the connection FAILED.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /**\n * OPTIONAL. Linking a store through the software's CENTRALIZED app (FUT-5798):\n * the store authorizes the app on the portal and picks its store from the\n * app's list; no code, no token of its own. Wins over `linking` when both are set.\n */\n readonly appLinking?: MarketplaceAppLinking;\n /**\n * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check\n * and the tracking read. Absent: neither is offered, and the host says so.\n */\n readonly courier?: MarketplaceCourierApi;\n /** OPTIONAL (FUT-6099). Answering the buyer's disputes; present with `capabilities.disputes`. */\n readonly disputes?: MarketplaceDisputeApi;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AA6WA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
|