@12-apps/marketplace 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/ADOPTING.md +143 -3
  2. package/README.md +27 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CQ4QiZPi.d.ts → adapter-szxo9ohc.d.ts} +82 -2
  6. package/dist/{chunk-NFJQQWG4.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-CEWTV2TC.js → chunk-MDXSVE7Q.js} +652 -246
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-W57TITU4.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-CCSnylou.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-1KlJ_8jK.d.ts → engine-CgKBbk9J.d.ts} +127 -3
  15. package/dist/hono/index.d.ts +2 -2
  16. package/dist/hono/index.js +2 -2
  17. package/dist/ifood/index.d.ts +13 -3
  18. package/dist/ifood/index.js +114 -23
  19. package/dist/ifood/index.js.map +1 -1
  20. package/dist/index.d.ts +29 -5
  21. package/dist/index.js +54 -6
  22. package/dist/index.js.map +1 -1
  23. package/dist/keeta/index.d.ts +2 -2
  24. package/dist/keeta/index.js +2 -2
  25. package/dist/manifest/server.d.ts +4 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +14 -5
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +17 -3
  33. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  34. package/src/core/acceptance.ts +12 -6
  35. package/src/core/acknowledge.ts +189 -0
  36. package/src/core/adapter.ts +74 -1
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/engine.ts +3 -2
  40. package/src/core/ingest.ts +6 -0
  41. package/src/core/link-store.ts +2 -4
  42. package/src/core/marketplace-confirmed.ts +229 -0
  43. package/src/core/order-reasons.ts +119 -0
  44. package/src/core/outbound.ts +5 -1
  45. package/src/core/pipeline.ts +27 -1
  46. package/src/core/ports.ts +2 -0
  47. package/src/core/registry.ts +28 -2
  48. package/src/core/state.ts +10 -0
  49. package/src/core/status-job.ts +86 -3
  50. package/src/core/types.ts +6 -0
  51. package/src/ifood/index.ts +27 -4
  52. package/src/ifood/normalize.ts +16 -0
  53. package/src/ifood/outbound.ts +131 -27
  54. package/src/index.ts +18 -0
  55. package/src/server/jobs.ts +57 -4
  56. package/src/server/webhook.ts +27 -4
  57. package/dist/chunk-4J2KJ3ZW.js.map +0 -1
  58. package/dist/chunk-CEWTV2TC.js.map +0 -1
  59. package/dist/chunk-W57TITU4.js.map +0 -1
  60. /package/dist/{chunk-NFJQQWG4.js.map → chunk-BNWRIR5J.js.map} +0 -0
@@ -1,5 +1,5 @@
1
- import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
2
- import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CCSnylou.js';
1
+ import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-szxo9ohc.js';
2
+ import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CaZiG7Lw.js';
3
3
 
4
4
  /**
5
5
  * Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
@@ -13,7 +13,7 @@ import {
13
13
  openDeliveryRequestCancellation,
14
14
  openDeliveryStatus,
15
15
  openDeliverySwitchAvailability
16
- } from "../chunk-NFJQQWG4.js";
16
+ } from "../chunk-BNWRIR5J.js";
17
17
  import "../chunk-M2V4RFMA.js";
18
18
  import {
19
19
  asString,
@@ -23,7 +23,7 @@ import {
23
23
  } from "../chunk-BD7DS3XM.js";
24
24
  import {
25
25
  outboundResultOf
26
- } from "../chunk-4J2KJ3ZW.js";
26
+ } from "../chunk-BTKVZAJI.js";
27
27
  import {
28
28
  __name
29
29
  } from "../chunk-7QVYU63E.js";
@@ -1,7 +1,7 @@
1
- import { am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-1KlJ_8jK.js';
1
+ import { av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-CgKBbk9J.js';
2
2
  import * as _12_apps_wiring from '@12-apps/wiring';
3
3
  import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
4
- import '../adapter-CQ4QiZPi.js';
4
+ import '../adapter-szxo9ohc.js';
5
5
  import 'zod';
6
6
 
7
7
  declare const marketplaceServerManifest: {
@@ -16,6 +16,8 @@ declare const marketplaceServerManifest: {
16
16
  readonly "reconcile-inbox": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
17
17
  readonly outbound: _12_apps_wiring.WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
18
18
  readonly "fetch-order": _12_apps_wiring.WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
19
+ readonly acknowledge: _12_apps_wiring.WireJobBlueprint<AcknowledgeJobPayload, MarketplaceJobDeps>;
20
+ readonly "cancellation-reasons": _12_apps_wiring.WireJobBlueprint<CancellationReasonsJobPayload, MarketplaceJobDeps>;
19
21
  readonly catalogue: _12_apps_wiring.WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
20
22
  readonly "outbound-sweep": _12_apps_wiring.WireJobBlueprint<void, MarketplaceJobDeps>;
21
23
  readonly availability: _12_apps_wiring.WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps>;
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MARKETPLACE_JOBS,
3
3
  createApiMarketplace
4
- } from "../chunk-W57TITU4.js";
4
+ } from "../chunk-R3BUW5PX.js";
5
5
  import "../chunk-SGOTN5PX.js";
6
- import "../chunk-CEWTV2TC.js";
6
+ import "../chunk-MDXSVE7Q.js";
7
7
  import "../chunk-7QVYU63E.js";
8
8
 
9
9
  // src/manifest/server.ts
@@ -1,4 +1,4 @@
1
- import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-CQ4QiZPi.js';
1
+ import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-szxo9ohc.js';
2
2
 
3
3
  /**
4
4
  * The words the Rappi adapter needs from its host, and nothing else.
@@ -9,7 +9,7 @@ import {
9
9
  answered,
10
10
  outboundResultOf,
11
11
  tokenGrantResultOf
12
- } from "../chunk-4J2KJ3ZW.js";
12
+ } from "../chunk-BTKVZAJI.js";
13
13
  import {
14
14
  __name
15
15
  } from "../chunk-7QVYU63E.js";
@@ -1,7 +1,7 @@
1
- import { y as DecisionProblemCode, f as BulkProblemCode, R as LinkRefusalCode, a3 as MarketplaceEngine, a9 as MarketplaceLogger, am as OutboundJobPayload, G as FetchOrderJobPayload, n as CatalogueJobPayload, b as AvailabilityJobPayload } from '../engine-1KlJ_8jK.js';
1
+ import { I as DecisionProblemCode, i as BulkProblemCode, X as LinkRefusalCode, ac as MarketplaceEngine, ai as MarketplaceLogger, av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-CgKBbk9J.js';
2
2
  import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
3
3
  import { z } from 'zod';
4
- import '../adapter-CQ4QiZPi.js';
4
+ import '../adapter-szxo9ohc.js';
5
5
 
6
6
  /**
7
7
  * Every problem code a route words from `problems`, decisions and bulk writes
@@ -118,7 +118,7 @@ declare const MARKETPLACE_MANAGE = "marketplace:manage";
118
118
  declare const MARKETPLACE_DECIDE = "marketplace:decide";
119
119
 
120
120
  /**
121
- * The engine's eight jobs, declared here because every number in them is the
121
+ * The engine's ten jobs, declared here because every number in them is the
122
122
  * engine's knowledge, not a host's:
123
123
  *
124
124
  * - `expire-acceptances`, every minute: the unit being measured is minutes (a
@@ -133,6 +133,12 @@ declare const MARKETPLACE_DECIDE = "marketplace:decide";
133
133
  * - `fetch-order`, on demand: one GET of an order a marketplace's event only
134
134
  * announced (`orderToFetch`), then the one ingest path. Three attempts with
135
135
  * backoff; the reconciliation sweep re-queues a row still owed.
136
+ * - `acknowledge`, on demand: tells the marketplace a store's recorded events
137
+ * were received (FUT-5984, iFood). Three attempts with backoff; the
138
+ * reconcile pass re-queues a store still owing some.
139
+ * - `cancellation-reasons`, on demand: reads one order's own cancellation
140
+ * reasons once, after its ingest (FUT-5984, iFood). Three attempts; the
141
+ * static list stays the fallback.
136
142
  * - `catalogue`, on demand: one publish or withdraw of one product on one
137
143
  * marketplace's catalogue (FUT-4768). Three attempts with backoff; the
138
144
  * last one stamps FAILED with a failure code.
@@ -152,13 +158,14 @@ declare const MARKETPLACE_DECIDE = "marketplace:decide";
152
158
  *
153
159
  * Bound with `{ engine }`, these arrive at a runner as
154
160
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
155
- * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,
161
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,
162
+ * `marketplace.cancellation-reasons`, `marketplace.catalogue`,
156
163
  * `marketplace.outbound-sweep`, `marketplace.availability` and
157
164
  * `marketplace.availability-sweep`.
158
165
  */
159
166
  /** What the host closes over at bind time: the mounted engine. */
160
167
  interface MarketplaceJobDeps {
161
- engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runCatalogue" | "sweepOutbound" | "runAvailability" | "sweepAvailability">;
168
+ engine: Pick<MarketplaceEngine, "expireLapsed" | "retryable" | "reprocess" | "runOutbound" | "runFetchOrder" | "runAcknowledge" | "sweepAcknowledgements" | "runCancellationReasons" | "runCatalogue" | "sweepOutbound" | "runAvailability" | "sweepAvailability">;
162
169
  }
163
170
  /** The single-flight queue name (`@12-apps/jobs`' `SWEEP_QUEUE`), as a literal. */
164
171
  declare const MARKETPLACE_SWEEP_QUEUE = "sweeps";
@@ -176,6 +183,8 @@ declare const MARKETPLACE_JOBS: {
176
183
  readonly "reconcile-inbox": WireJobBlueprint<void, MarketplaceJobDeps>;
177
184
  readonly outbound: WireJobBlueprint<OutboundJobPayload, MarketplaceJobDeps>;
178
185
  readonly "fetch-order": WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps>;
186
+ readonly acknowledge: WireJobBlueprint<AcknowledgeJobPayload, MarketplaceJobDeps>;
187
+ readonly "cancellation-reasons": WireJobBlueprint<CancellationReasonsJobPayload, MarketplaceJobDeps>;
179
188
  readonly catalogue: WireJobBlueprint<CatalogueJobPayload, MarketplaceJobDeps>;
180
189
  readonly "outbound-sweep": WireJobBlueprint<void, MarketplaceJobDeps>;
181
190
  readonly availability: WireJobBlueprint<AvailabilityJobPayload, MarketplaceJobDeps>;
@@ -6,7 +6,7 @@ import {
6
6
  MARKETPLACE_SWEEP_QUEUE,
7
7
  ORDER_NOT_PENDING_CODE,
8
8
  createApiMarketplace
9
- } from "../chunk-W57TITU4.js";
9
+ } from "../chunk-R3BUW5PX.js";
10
10
  import {
11
11
  MARKETPLACE_DECIDE,
12
12
  MARKETPLACE_MANAGE,
@@ -20,7 +20,7 @@ import {
20
20
  upsertMarketplaceIntegrationsBody,
21
21
  upsertMarketplaceMenuLinksBody
22
22
  } from "../chunk-SGOTN5PX.js";
23
- import "../chunk-CEWTV2TC.js";
23
+ import "../chunk-MDXSVE7Q.js";
24
24
  import "../chunk-7QVYU63E.js";
25
25
  export {
26
26
  MARKETPLACE_AVAILABILITY_ATTEMPTS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/marketplace",
3
- "version": "1.13.0",
3
+ "version": "1.14.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food and ./keeta on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
@@ -53,9 +53,10 @@ model MarketplaceIntegration {
53
53
  /// learning it does.
54
54
  autoAccept Boolean @default(false) @map("auto_accept")
55
55
 
56
- /// Whether the marketplace's DISPATCHED and CONCLUDED events move the pedido
57
- /// forward here (FUT-4653). Governs the INBOUND move only: telling the
58
- /// marketplace what the store did is always on where it has an endpoint.
56
+ /// Whether the store and the marketplace follow each other's status
57
+ /// (FUT-4653). On: the marketplace's DISPATCHED and CONCLUDED events move the
58
+ /// pedido forward here, and the store's steps are told to the marketplace
59
+ /// where it has an endpoint. Off: neither side moves the other (FUT-5673).
59
60
  followStatus Boolean @default(true) @map("follow_status")
60
61
 
61
62
  /// How long this store may take to answer, in seconds. Per-connection because
@@ -172,6 +173,14 @@ model MarketplaceInboxEvent {
172
173
 
173
174
  receivedAt DateTime @default(now()) @map("received_at")
174
175
  processedAt DateTime? @map("processed_at")
176
+ /// When the marketplace was told this event was received (FUT-5984: iFood's
177
+ /// `events/acknowledgment`), by the `marketplace.acknowledge` job. NULL: owed,
178
+ /// for a marketplace that takes acknowledgments, inside its retention.
179
+ /// Two PARTIAL indexes WHERE acknowledged_at IS NULL, on (client_id,
180
+ /// received_at) for the job and (provider, received_at) for the reconcile
181
+ /// pass: SQL-only (migration 20261202120000). Set also when the marketplace
182
+ /// refused the event's acknowledgment for good (a final 4xx): never resent.
183
+ acknowledgedAt DateTime? @map("acknowledged_at")
175
184
 
176
185
  @@unique([provider, eventId])
177
186
  @@index([status, receivedAt])
@@ -257,6 +266,11 @@ model MarketplaceAcceptance {
257
266
  /// The order's SKUs as the marketplace sent them (a JSON array): what
258
267
  /// offending SKUs are validated against. NULL on rows from before it.
259
268
  lineSkus Json? @map("line_skus")
269
+ /// The reasons the marketplace accepts for cancelling THIS order, as it listed
270
+ /// them (a JSON array of `{ code, description }`, FUT-5984: iFood's
271
+ /// `GET /orders/{id}/cancellationReasons`), read once after the ingest. NULL:
272
+ /// not read (yet, or the read failed): the adapter's static list applies.
273
+ cancellationReasons Json? @map("cancellation_reasons")
260
274
 
261
275
  createdAt DateTime @default(now()) @map("created_at")
262
276
  updatedAt DateTime @updatedAt @map("updated_at")
@@ -0,0 +1,25 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: iFood homologation conformity (FUT-5984).
3
+ -- Additive and replay-safe, like the engine's earlier migrations: two nullable
4
+ -- columns and one partial index. Nothing the previous release reads changes.
5
+ --
6
+ -- `acknowledged_at`: when the marketplace was told an inbox event was received
7
+ -- (iFood's `events/acknowledgment`), stamped by the `marketplace.acknowledge`
8
+ -- job. Existing rows stay NULL; the job only reads rows inside the
9
+ -- marketplace's retention (8 hours for iFood), so history is never sent.
10
+ --
11
+ -- `cancellation_reasons`: the reasons the marketplace lists for cancelling one
12
+ -- order (`GET /orders/{id}/cancellationReasons`), read once after its ingest.
13
+ -- NULL: the adapter's static list applies.
14
+
15
+ ALTER TABLE "marketplace_inbox_events" ADD COLUMN IF NOT EXISTS "acknowledged_at" TIMESTAMP(3);
16
+ ALTER TABLE "marketplace_acceptances" ADD COLUMN IF NOT EXISTS "cancellation_reasons" JSONB;
17
+
18
+ CREATE INDEX IF NOT EXISTS "marketplace_inbox_events_unacknowledged_idx"
19
+ ON "marketplace_inbox_events" ("client_id", "received_at")
20
+ WHERE "acknowledged_at" IS NULL;
21
+
22
+ -- The reconcile pass's read: by marketplace and retention window, every store.
23
+ CREATE INDEX IF NOT EXISTS "marketplace_inbox_events_unacknowledged_provider_idx"
24
+ ON "marketplace_inbox_events" ("provider", "received_at")
25
+ WHERE "acknowledged_at" IS NULL;
@@ -1,5 +1,6 @@
1
1
  import { NO_STANDING_REQUEST } from "./cancellation";
2
2
  import { rejectConfirmed, tellCancellationConfirmed } from "./cancellation-outcome";
3
+ import { applyOwedConfirmations } from "./marketplace-confirmed";
3
4
  import type { EngineContext } from "./ports";
4
5
  import type { MarketplaceProvider } from "./types";
5
6
 
@@ -130,19 +131,24 @@ export async function expireLapsedAcceptances(
130
131
  // An order whose cancellation request waits is left to that request: its
131
132
  // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
132
133
  // never hears EXPIRED and then the confirmation for one order.
133
- where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
134
- select: { id: true, clientId: true, orderId: true },
135
- })) as { id: string; clientId: string; orderId: string }[];
134
+ // An order the marketplace confirmed (`confirmed_at`, FUT-5653: accepted in its own app) is never expired.
135
+ where: { status: "AWAITING", confirmedAt: null, acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
136
+ select: { id: true, clientId: true, orderId: true, provider: true, externalOrderId: true },
137
+ })) as { id: string; clientId: string; orderId: string; provider: string; externalOrderId: string }[];
136
138
  if (lapsed.length === 0) return { expired: 0, tenants: 0 };
139
+ // A confirmation that outran its order and still waits is applied first: that order is not expired.
140
+ const confirmed = await applyOwedConfirmations(ctx, lapsed);
141
+ const expiring = lapsed.filter((row) => !confirmed.has(row.orderId));
142
+ if (expiring.length === 0) return { expired: 0, tenants: 0 };
137
143
 
138
144
  const result = await db.marketplaceAcceptance.updateMany({
139
- where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
145
+ where: { id: { in: expiring.map((row) => row.id) }, status: "AWAITING", confirmedAt: null, ...NO_STANDING_REQUEST },
140
146
  data: { status: "EXPIRED", acknowledgedAt: now },
141
147
  });
142
148
 
143
149
  // The host's half must not be able to fail the sweep: one tenant's broken
144
150
  // cancellation cannot leave every other tenant's lapsed orders on the clock.
145
- for (const row of lapsed) {
151
+ for (const row of expiring) {
146
152
  try {
147
153
  await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
148
154
  } catch (error) {
@@ -153,7 +159,7 @@ export async function expireLapsedAcceptances(
153
159
  }
154
160
  }
155
161
 
156
- const tenants = new Set(lapsed.map((row) => row.clientId));
162
+ const tenants = new Set(expiring.map((row) => row.clientId));
157
163
  for (const clientId of tenants) ctx.ports.publishChanged(clientId);
158
164
  return { expired: result.count, tenants: tenants.size };
159
165
  }
@@ -0,0 +1,189 @@
1
+ import type { MarketplaceAdapter, OutboundResult } from "./adapter";
2
+ import { readOutboundConnection } from "./integration";
3
+ import type { EngineContext } from "./ports";
4
+ import type { MarketplaceProvider } from "./types";
5
+
6
+ /**
7
+ * Acknowledging recorded events to the marketplace (FUT-5984, iFood's
8
+ * `POST /events/v1.0/events/acknowledgment`).
9
+ *
10
+ * The webhook request only QUEUES it, after the inbox row is written: one
11
+ * `marketplace.acknowledge` job per fresh delivery, keyed by its row. The job
12
+ * sends every event of that store still owed (recorded inside the
13
+ * marketplace's retention, `acknowledged_at` null) in one call, up to the
14
+ * adapter's batch size, and stamps exactly those rows. The stamp is the
15
+ * marker: a second run finds nothing and calls nobody; a failed call leaves
16
+ * the rows owed, and the reconcile pass re-queues a job per store that still
17
+ * owes some. Nothing here ever holds or fails an ingest.
18
+ */
19
+
20
+ /** The wire name, `<namespace>.<blueprint>`. */
21
+ export const MARKETPLACE_ACKNOWLEDGE_JOB = "marketplace.acknowledge";
22
+
23
+ /** The job's payload: whose events, on which marketplace. Identifiers only. */
24
+ export interface AcknowledgeJobPayload {
25
+ clientId: string;
26
+ provider: string;
27
+ }
28
+
29
+ /** What one run did. */
30
+ export type AcknowledgeOutcome =
31
+ | { kind: "skipped"; reason: string }
32
+ | { kind: "done"; acknowledged: number }
33
+ | { kind: "failed"; reason: string };
34
+
35
+ /** Thrown so the queue retries. */
36
+ export class AcknowledgeRetryError extends Error {
37
+ constructor(message: string) {
38
+ super(message);
39
+ this.name = "AcknowledgeRetryError";
40
+ }
41
+ }
42
+
43
+ /** The adapter's acknowledgment, or null when it has none. */
44
+ function acknowledgementOf(ctx: EngineContext, provider: string): NonNullable<MarketplaceAdapter["acknowledgement"]> | null {
45
+ return ctx.registry.get(provider)?.acknowledgement ?? null;
46
+ }
47
+
48
+ /** How many stores one pass re-queues, per marketplace. */
49
+ const SWEEP_STORES = 500;
50
+
51
+ /** The oldest instant a still-acknowledgeable event may have been recorded at. */
52
+ function windowStart(ctx: EngineContext, retentionMs: number): Date {
53
+ return new Date(ctx.ports.clock.now().getTime() - retentionMs);
54
+ }
55
+
56
+ /**
57
+ * Queue the acknowledgment of a delivery just recorded. A queue call, never a
58
+ * statement; never throws. A lost enqueue is re-queued by the sweep.
59
+ */
60
+ export async function enqueueAcknowledge(
61
+ ctx: EngineContext,
62
+ input: { clientId: string | null; provider: MarketplaceProvider; inboxId: string },
63
+ ): Promise<void> {
64
+ if (!input.clientId || !input.inboxId || !acknowledgementOf(ctx, input.provider)) return;
65
+ const payload: AcknowledgeJobPayload = { clientId: input.clientId, provider: input.provider };
66
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_ACKNOWLEDGE_JOB, payload, {
67
+ dedupeKey: `${MARKETPLACE_ACKNOWLEDGE_JOB}:${input.inboxId}`,
68
+ });
69
+ if (!outcome.enqueued) {
70
+ ctx.ports.logger.warn(
71
+ `${MARKETPLACE_ACKNOWLEDGE_JOB}: event ${input.inboxId} was not queued; the reconcile pass re-queues it` +
72
+ (outcome.reason ? ` (${outcome.reason})` : ""),
73
+ );
74
+ }
75
+ }
76
+
77
+ interface OwedRow {
78
+ id: string;
79
+ eventId: string;
80
+ }
81
+
82
+ /** Run one acknowledgment job. Throws {@link AcknowledgeRetryError} for a retryable answer before the last attempt. */
83
+ export async function runAcknowledge(
84
+ ctx: EngineContext,
85
+ payload: AcknowledgeJobPayload,
86
+ attempt: { attempt: number; maxAttempts: number },
87
+ ): Promise<AcknowledgeOutcome> {
88
+ const acknowledgement = acknowledgementOf(ctx, payload.provider);
89
+ if (!acknowledgement) return { kind: "skipped", reason: `${payload.provider} takes no acknowledgment` };
90
+ const db = await ctx.ports.db();
91
+ const owed = (await db.marketplaceInboxEvent.findMany({
92
+ where: {
93
+ clientId: payload.clientId,
94
+ provider: payload.provider,
95
+ acknowledgedAt: null,
96
+ receivedAt: { gte: windowStart(ctx, acknowledgement.retentionMs) },
97
+ },
98
+ orderBy: { receivedAt: "asc" },
99
+ take: acknowledgement.batchSize,
100
+ select: { id: true, eventId: true },
101
+ })) as OwedRow[];
102
+ if (owed.length === 0) return { kind: "skipped", reason: "no event is owed an acknowledgment" };
103
+ const connection = await readOutboundConnection(ctx, payload.clientId, payload.provider).catch(() => null);
104
+ if (!connection) return { kind: "skipped", reason: "no credentials on file" };
105
+
106
+ const now = ctx.ports.clock.now();
107
+ const result = await acknowledgement.send(
108
+ { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
109
+ [...new Set(owed.map((row) => row.eventId))],
110
+ );
111
+ return settle(ctx, payload, owed, result, attempt);
112
+ }
113
+
114
+ /** Settle rows: acknowledged, or refused for good by the marketplace. Either way never sent again. */
115
+ async function stampSettled(ctx: EngineContext, owed: readonly OwedRow[]): Promise<void> {
116
+ const db = await ctx.ports.db();
117
+ await db.marketplaceInboxEvent.updateMany({
118
+ where: { id: { in: owed.map((row) => row.id) }, acknowledgedAt: null },
119
+ data: { acknowledgedAt: ctx.ports.clock.now() },
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Stamp the rows a 2xx acknowledged, or a final 4xx refused for good; retry,
125
+ * or leave them owed for the reconcile pass, otherwise (our own credentials
126
+ * refused included: fixing them sends the rows).
127
+ */
128
+ async function settle(
129
+ ctx: EngineContext,
130
+ payload: AcknowledgeJobPayload,
131
+ owed: readonly OwedRow[],
132
+ result: OutboundResult,
133
+ attempt: { attempt: number; maxAttempts: number },
134
+ ): Promise<AcknowledgeOutcome> {
135
+ if (result.kind === "accepted") {
136
+ await stampSettled(ctx, owed);
137
+ return { kind: "done", acknowledged: owed.length };
138
+ }
139
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
140
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
141
+ throw new AcknowledgeRetryError(`${payload.provider} events of ${payload.clientId}: ${reason}`);
142
+ }
143
+ if (result.kind === "refused" && !result.own) {
144
+ // The marketplace refused this batch for good (a final 4xx): given up on, stamped, never resent,
145
+ // so one bad id cannot make every reconcile pass resend the store's events for the whole retention.
146
+ await stampSettled(ctx, owed);
147
+ ctx.ports.logger.error(`${MARKETPLACE_ACKNOWLEDGE_JOB}: ${payload.provider} refused ${owed.length} event(s) of ${payload.clientId}; given up: ${reason}`);
148
+ return { kind: "failed", reason };
149
+ }
150
+ // Left owed: the reconcile pass re-queues it, inside the marketplace's retention.
151
+ ctx.ports.logger.error(`${MARKETPLACE_ACKNOWLEDGE_JOB}: ${payload.provider} events of ${payload.clientId} not acknowledged: ${reason}`);
152
+ return { kind: "failed", reason };
153
+ }
154
+
155
+ /**
156
+ * The reconcile pass's half: one job per (store, marketplace) that still owes
157
+ * an acknowledgment inside the retention. One read per marketplace that takes
158
+ * acknowledgments.
159
+ */
160
+ export async function sweepAcknowledgements(ctx: EngineContext): Promise<{ requeued: number }> {
161
+ const db = await ctx.ports.db();
162
+ let requeued = 0;
163
+ for (const provider of ctx.registry.providers()) {
164
+ const acknowledgement = acknowledgementOf(ctx, provider);
165
+ if (!acknowledgement) continue;
166
+ const rows = (await db.marketplaceInboxEvent.findMany({
167
+ where: { provider, acknowledgedAt: null, clientId: { not: null }, receivedAt: { gte: windowStart(ctx, acknowledgement.retentionMs) } },
168
+ // One row per store, bounded: the next pass takes the rest.
169
+ distinct: ["clientId"],
170
+ take: SWEEP_STORES,
171
+ select: { clientId: true },
172
+ })) as { clientId: string }[];
173
+ requeued += await requeueStores(ctx, provider, new Set(rows.map((row) => row.clientId)));
174
+ }
175
+ return { requeued };
176
+ }
177
+
178
+ /** Queue one job per store, under a key of the sweep's own (a queue keeps a finished job's id). */
179
+ async function requeueStores(ctx: EngineContext, provider: string, clientIds: ReadonlySet<string>): Promise<number> {
180
+ const at = ctx.ports.clock.now().getTime();
181
+ let queued = 0;
182
+ for (const clientId of clientIds) {
183
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_ACKNOWLEDGE_JOB, { clientId, provider } satisfies AcknowledgeJobPayload, {
184
+ dedupeKey: `${MARKETPLACE_ACKNOWLEDGE_JOB}:sweep:${provider}:${clientId}:${at}`,
185
+ });
186
+ if (outcome.enqueued) queued += 1;
187
+ }
188
+ return queued;
189
+ }
@@ -95,8 +95,55 @@ export interface MarketplaceCapabilities {
95
95
  * Absent or empty: the engine tells it nothing.
96
96
  */
97
97
  statusSteps?: readonly StatusStep[];
98
+ /**
99
+ * OPTIONAL. The HTTP status a recorded delivery is answered with (FUT-5984:
100
+ * iFood wants `202 Accepted`). Absent: 200. Refusals and failures keep theirs.
101
+ */
102
+ webhookAnswerStatus?: 200 | 202;
103
+ /**
104
+ * OPTIONAL. The marketplace announces that the store accepted an order in the
105
+ * marketplace's own app (`NormalizedEvent.marketplaceConfirmed`, FUT-5653).
106
+ * Its ingest then applies a confirmation that arrived before the order.
107
+ */
108
+ marketplaceConfirms?: boolean;
109
+ /**
110
+ * OPTIONAL. A status step is told only after the marketplace took the
111
+ * store's confirm (`confirmedAt`, FUT-5673: iFood refuses a step of an order
112
+ * it has not confirmed). Absent: steps never wait on the confirm.
113
+ */
114
+ statusAfterConfirm?: boolean;
98
115
  }
99
116
 
117
+ /**
118
+ * A marketplace's presence heartbeat (FUT-5984: iFood's `KEEPALIVE`), read off
119
+ * a delivery: `merchantIds` when it asks about named merchants (its
120
+ * per-merchant mode), null when it asks about the whole app.
121
+ */
122
+ export interface PresenceProbe {
123
+ merchantIds: readonly string[] | null;
124
+ }
125
+
126
+ /** Acknowledging recorded events to the marketplace (FUT-5984: iFood's `events/acknowledgment`). */
127
+ export interface MarketplaceAcknowledgement {
128
+ /** At most this many event ids per call. */
129
+ batchSize: number;
130
+ /** How long the marketplace keeps an event: an older one is never acknowledged. */
131
+ retentionMs: number;
132
+ /** Acknowledge these event ids, in one call. */
133
+ send(ctx: AdapterCallContext, eventIds: readonly string[]): Promise<OutboundResult>;
134
+ }
135
+
136
+ /** One cancellation reason the marketplace lists for one order: its code and its own words. */
137
+ export interface OrderCancellationReason {
138
+ code: string;
139
+ description: string;
140
+ }
141
+
142
+ /** One order's reasons read from the marketplace, or the refusal / retry of the read. */
143
+ export type OrderCancellationReasonsResult =
144
+ | { kind: "reasons"; reasons: OrderCancellationReason[] }
145
+ | Exclude<OutboundResult, { kind: "accepted" }>;
146
+
100
147
  /**
101
148
  * A step of the order the store tells the marketplace about (FUT-4653): the
102
149
  * order is ready for pickup, the courier left, the order was handed over.
@@ -201,7 +248,11 @@ export interface MarketplaceAdapter {
201
248
  readSignature(header: (name: string) => string | null): string | null;
202
249
  /** Is this delivery's signature the one this store's secret would produce? */
203
250
  verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;
204
- /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */
251
+ /**
252
+ * The marketplace's documented reasons, static and offline: a dialog never
253
+ * waits on the network. With `orderCancellationReasons`, the fallback of an
254
+ * order whose own list could not be read.
255
+ */
205
256
  cancellationReasons(): readonly CancellationReason[];
206
257
  /** Tell the marketplace the store accepted the order. */
207
258
  confirm(
@@ -233,6 +284,28 @@ export interface MarketplaceAdapter {
233
284
  order: OutboundOrderRef,
234
285
  facts: StatusFacts,
235
286
  ): Promise<OutboundResult | { kind: "unsupported" }>;
287
+ /**
288
+ * OPTIONAL. The step that must be told before this one for this kind of
289
+ * order (FUT-5984: iFood's dispatch of a merchant bag follows its
290
+ * `readyToPickup`), or null. The status job sends it first when it is not
291
+ * told yet.
292
+ */
293
+ statusPrerequisite?(facts: StatusFacts): StatusStep | null;
294
+ /**
295
+ * OPTIONAL. A delivery that is the marketplace's presence heartbeat, not an
296
+ * event (FUT-5984: iFood's `KEEPALIVE`), or null. Answered 202 once its
297
+ * signature is proved, with nothing recorded.
298
+ */
299
+ presence?(payload: unknown): PresenceProbe | null;
300
+ /** OPTIONAL. Acknowledging recorded events (FUT-5984). Absent: nothing is acknowledged. */
301
+ readonly acknowledgement?: MarketplaceAcknowledgement;
302
+ /**
303
+ * OPTIONAL. Read the reasons the marketplace accepts for cancelling THIS
304
+ * order (FUT-5984: iFood's `GET /orders/{id}/cancellationReasons`). Called
305
+ * only from the `marketplace.cancellation-reasons` job. Absent: the static
306
+ * `cancellationReasons()` are every order's.
307
+ */
308
+ orderCancellationReasons?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<OrderCancellationReasonsResult>;
236
309
  /**
237
310
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
238
311
  * marketplace whose events carry no order body). Called only from the
@@ -2,7 +2,7 @@ import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
2
  import type { CancellationReason, MarketplaceAdapter } from "./adapter";
3
3
  import { failedRequestData, tellCancellationFailed } from "./cancellation-outcome";
4
4
  import type { EngineContext } from "./ports";
5
- import { resolveReason } from "./registry";
5
+ import { reasonsForOrder, resolveReason } from "./registry";
6
6
  import type { MarketplaceProvider } from "./types";
7
7
 
8
8
  /**
@@ -59,6 +59,8 @@ export interface ClaimRow {
59
59
  status: string;
60
60
  cancellationStatus: string | null;
61
61
  lineSkus: unknown;
62
+ /** The order's own reasons, when the marketplace lists them per order (FUT-5984). */
63
+ cancellationReasons?: unknown;
62
64
  }
63
65
 
64
66
  export const CLAIM_SELECT = {
@@ -67,6 +69,7 @@ export const CLAIM_SELECT = {
67
69
  status: true,
68
70
  cancellationStatus: true,
69
71
  lineSkus: true,
72
+ cancellationReasons: true,
70
73
  } as const;
71
74
 
72
75
  /** The refusal a row that is no longer on the clock earns, or null. */
@@ -112,11 +115,11 @@ function skuProblems(
112
115
  function invalidReasonProblem(
113
116
  adapter: MarketplaceAdapter,
114
117
  reason: CancellationReason | null,
115
- code: string | null | undefined,
118
+ input: { code: string | null | undefined; stored: unknown },
116
119
  path: (string | number)[],
117
120
  ): DecisionProblem | null {
118
- if (code === null || code === undefined || reason) return null;
119
- const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
121
+ if (input.code === null || input.code === undefined || reason) return null;
122
+ const validCodes = reasonsForOrder(adapter, input.stored).map((candidate) => candidate.code);
120
123
  return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
121
124
  }
122
125
 
@@ -138,8 +141,9 @@ export function planCancellation(
138
141
  path: (string | number)[],
139
142
  ): CancellationPlan | DecisionProblem[] {
140
143
  if (!adapter) return { status: null, reason: null, skus: [] };
141
- const reason = resolveReason(adapter, input.reasonCode);
142
- const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
144
+ // The order's own reasons when the marketplace listed them, else the static list (FUT-5984).
145
+ const reason = resolveReason(adapter, input.reasonCode, row.cancellationReasons);
146
+ const invalid = invalidReasonProblem(adapter, reason, { code: input.reasonCode, stored: row.cancellationReasons }, path);
143
147
  if (invalid) return [invalid];
144
148
  const skus = [...new Set(input.offendingSkus ?? [])];
145
149
  const problems = skuProblems(reason, skus, row, path);