@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
@@ -0,0 +1,63 @@
1
+ import type { CancellationReason, PresenceProbe } from "./adapter";
2
+ import { runAcknowledge, sweepAcknowledgements, type AcknowledgeJobPayload, type AcknowledgeOutcome } from "./acknowledge";
3
+ import { appCredentialsOf } from "./link-store";
4
+ import {
5
+ readOrderReasons,
6
+ runCancellationReasons,
7
+ type CancellationReasonsJobPayload,
8
+ type CancellationReasonsOutcome,
9
+ } from "./order-reasons";
10
+ import type { EngineContext } from "./ports";
11
+
12
+ /** A job run's attempt, as the runner says. */
13
+ interface Attempt {
14
+ attempt: number;
15
+ maxAttempts: number;
16
+ }
17
+
18
+ /**
19
+ * The engine calls of the iFood homologation conformity (FUT-5984): the
20
+ * webhook's answer status and presence heartbeat, the events'
21
+ * acknowledgment, and each order's own cancellation reasons. Provider-neutral:
22
+ * every answer is the adapter's.
23
+ */
24
+ export interface MarketplaceConformityEngine {
25
+ /** The status a recorded delivery is answered with: the adapter's, else 200. */
26
+ answerStatus(provider: string): number;
27
+ /** The delivery is the marketplace's presence heartbeat, not an event, or null. */
28
+ presence(provider: string, payload: unknown): PresenceProbe | null;
29
+ /**
30
+ * Is this delivery signed by the software's own app on this marketplace, in
31
+ * either environment (`appCredentials`)? No statement: what proves a
32
+ * heartbeat that names no store.
33
+ */
34
+ signedByApp(provider: string, rawBody: string, signature: string | null): Promise<boolean>;
35
+ /** One order's reasons for the refusal dialog: its own, read from the marketplace, else the static list. */
36
+ orderReasons(clientId: string, orderId: string): Promise<readonly CancellationReason[]>;
37
+ /** Run one acknowledgment (the `marketplace.acknowledge` job's body). */
38
+ runAcknowledge(payload: AcknowledgeJobPayload, attempt: Attempt): Promise<AcknowledgeOutcome>;
39
+ /** Re-queue the stores still owing an acknowledgment (run by the reconcile pass). */
40
+ sweepAcknowledgements(): Promise<{ requeued: number }>;
41
+ /** Read one order's reasons (the `marketplace.cancellation-reasons` job's body). */
42
+ runCancellationReasons(payload: CancellationReasonsJobPayload, attempt: Attempt): Promise<CancellationReasonsOutcome>;
43
+ }
44
+
45
+ export function conformityEngine(ctx: EngineContext): MarketplaceConformityEngine {
46
+ return {
47
+ answerStatus: (provider) => ctx.registry.get(provider)?.capabilities.webhookAnswerStatus ?? 200,
48
+ presence: (provider, payload) => ctx.registry.get(provider)?.presence?.(payload) ?? null,
49
+ signedByApp: async (provider, rawBody, signature) => {
50
+ const adapter = ctx.registry.has(provider) ? ctx.registry.get(provider) : null;
51
+ if (!adapter || signature === null) return false;
52
+ for (const environment of ["PRODUCTION", "SANDBOX"] as const) {
53
+ const app = await appCredentialsOf(ctx, provider, environment);
54
+ if (app && adapter.verifySignature(rawBody, signature, app.webhookSecret || app.clientSecret)) return true;
55
+ }
56
+ return false;
57
+ },
58
+ orderReasons: (clientId, orderId) => readOrderReasons(ctx, clientId, orderId),
59
+ runAcknowledge: (payload, attempt) => runAcknowledge(ctx, payload, attempt),
60
+ sweepAcknowledgements: () => sweepAcknowledgements(ctx),
61
+ runCancellationReasons: (payload, attempt) => runCancellationReasons(ctx, payload, attempt),
62
+ };
63
+ }
@@ -37,6 +37,7 @@ import type { CatalogueReadResult } from "./catalogue-read-port";
37
37
  import type { CataloguePublicationView } from "./catalogue-store";
38
38
  import { courierEngine } from "./courier";
39
39
  import type { MarketplaceCourierEngine } from "./courier-port";
40
+ import { conformityEngine, type MarketplaceConformityEngine } from "./conformity";
40
41
  import {
41
42
  runFetchOrder,
42
43
  type FetchOrderJobPayload,
@@ -99,7 +100,7 @@ import { readOrderStates, type MarketplaceOrderState } from "./state";
99
100
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
100
101
 
101
102
  /** Everything the mounted engine can do, with the ports and adapters bound in. */
102
- export interface MarketplaceEngine extends MarketplaceCourierEngine {
103
+ export interface MarketplaceEngine extends MarketplaceCourierEngine, MarketplaceConformityEngine {
103
104
  /** Every registered marketplace, in registration order. */
104
105
  providers(): readonly MarketplaceProvider[];
105
106
  /** Whether a provider id (a URL segment, a body field) names a registered adapter. */
@@ -377,7 +378,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
377
378
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
378
379
  runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
379
380
  informStatus: (input) => informStatus(ctx, input),
380
- ...courierEngine(ctx),
381
+ ...{ ...courierEngine(ctx), ...conformityEngine(ctx) },
381
382
 
382
383
  // Null too when the host bound no catalogue port: nothing could be published.
383
384
  catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
@@ -1,3 +1,5 @@
1
+ import { applyDeferredConfirmations } from "./marketplace-confirmed";
2
+ import { enqueueOrderReasons } from "./order-reasons";
1
3
  import { markMarketplaceEventSeen } from "./integration";
2
4
  import { resolveSkus } from "./menu-links";
3
5
  import { enqueueOutbound } from "./outbound-queue";
@@ -206,6 +208,10 @@ export async function ingestMarketplaceOrder(
206
208
  }
207
209
 
208
210
  ctx.ports.publishChanged(clientId);
211
+ // After the commit: the order's own cancellation reasons are read by a job, and a
212
+ // confirmation on the marketplace that outran this order is applied (FUT-5984, FUT-5653).
213
+ await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider });
214
+ if (!accepted) await applyDeferredConfirmations(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId });
209
215
 
210
216
  return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
211
217
  }
@@ -16,9 +16,6 @@ import type { MarketplaceProvider } from "./types";
16
16
  /** How a connection authenticates. */
17
17
  export type MarketplaceAuthMode = "CREDENTIALS" | "LINKED";
18
18
 
19
- /** A token is renewed this long before the marketplace says it expires. */
20
- const TOKEN_MARGIN_MS = 60_000;
21
-
22
19
  /** The blob a linked connection stores, sealed. The empty app fields keep 1.x readers' shape. */
23
20
  export function sealLink(ctx: EngineContext, refreshToken: string): string {
24
21
  return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
@@ -149,7 +146,8 @@ export function linkGrant(ctx: EngineContext, link: LinkedConnection): AdapterGr
149
146
  key,
150
147
  accessToken: async () => {
151
148
  const cached = ctx.tokens.get(key);
152
- if (cached && cached.expiresAt > ctx.ports.clock.now().getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
149
+ // Refreshed only once expired, never early (iFood's homologation criteria, FUT-5984).
150
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime()) return { token: cached.token };
153
151
  let running = inflight.get(ctx.tokens);
154
152
  if (!running) {
155
153
  running = new Map();
@@ -0,0 +1,229 @@
1
+ import { NO_STANDING_REQUEST } from "./cancellation";
2
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
3
+ import type { DeliveryOutcome } from "./pipeline";
4
+ import type { EngineContext, MarketplaceAdmissionResult, MarketplaceDb } from "./ports";
5
+ import type { MarketplaceProvider, NormalizedEvent } from "./types";
6
+
7
+ /**
8
+ * The store accepted an order in the marketplace's own app (FUT-5653: iFood's
9
+ * CFM from its tablet or Gestor de Pedidos). The owner's decision (2026-12-02):
10
+ * the order is accepted here too, through the SAME admit as an aceite on the
11
+ * Quadro (`order.admit`: the stock ask), with no confirm sent back (the
12
+ * marketplace has it), and is never expired by our clock afterwards.
13
+ *
14
+ * In order:
15
+ * 1. no acceptance yet (the PLACED's fetch still running): DEFERRED, and
16
+ * applied right after that order's ingest, or by the expiry sweep before it
17
+ * would expire it;
18
+ * 2. not AWAITING (an ACCEPTED one is our own confirm's echo): IGNORED;
19
+ * 3. `confirmed_at` stamped on the AWAITING row: the marketplace has the
20
+ * acceptance, so the clock never expires it and no confirm is ever sent;
21
+ * 4. with no cancellation request standing, the host admits it and the row is
22
+ * claimed AWAITING → ACCEPTED in one transaction, then `onAccepted`. A
23
+ * refused admit leaves it AWAITING for a person, whose aceite then goes
24
+ * through `decide` as ever.
25
+ */
26
+
27
+ /** The reason a confirmation that outran its order waits under. */
28
+ export const CONFIRMED_BEFORE_ORDER = "confirmed before its order";
29
+
30
+ interface HeldRow {
31
+ orderId: string;
32
+ status: string;
33
+ cancellationStatus: string | null;
34
+ }
35
+
36
+ /** Thrown inside the claim's transaction to roll it back. */
37
+ class NotClaimed extends Error {
38
+ constructor(readonly refusal: { code: string; message: string } | null) {
39
+ super("not claimed");
40
+ }
41
+ }
42
+
43
+ /** What claiming a confirmed order came to. */
44
+ type Claim = { accepted: true } | { accepted: false; refusal?: { code: string; message: string } };
45
+
46
+ /** A FAILED request an accept clears, keeping its `cancellation_requested_at` tombstone (as `decide` does). */
47
+ const CLEARED_FAILED_REQUEST = {
48
+ cancellationStatus: null,
49
+ cancellationReasonCode: null,
50
+ cancellationOffendingSkus: null,
51
+ cancellationFailureReason: null,
52
+ } as const;
53
+
54
+ /** The host's admit, then the claim, in one transaction; a refusal or a lost claim rolls both back. */
55
+ async function claimConfirmed(ctx: EngineContext, clientId: string, held: HeldRow, now: Date): Promise<Claim> {
56
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") return { accepted: false };
57
+ try {
58
+ await ctx.ports.transaction(async (tx: MarketplaceDb) => {
59
+ const answer: MarketplaceAdmissionResult = await ctx.ports.order.admit({
60
+ clientId,
61
+ orderId: held.orderId,
62
+ decision: "ACCEPT",
63
+ admission: {},
64
+ db: tx,
65
+ });
66
+ if (!answer.admitted) throw new NotClaimed({ code: answer.code, message: answer.message });
67
+ const claimed = await tx.marketplaceAcceptance.updateMany({
68
+ where: { orderId: held.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
69
+ data: {
70
+ status: "ACCEPTED",
71
+ acknowledgedAt: now,
72
+ confirmedAt: now,
73
+ ...(held.cancellationStatus === "FAILED" ? CLEARED_FAILED_REQUEST : {}),
74
+ },
75
+ });
76
+ if (claimed.count === 0) throw new NotClaimed(null);
77
+ });
78
+ return { accepted: true };
79
+ } catch (error) {
80
+ if (!(error instanceof NotClaimed)) throw error;
81
+ return error.refusal ? { accepted: false, refusal: error.refusal } : { accepted: false };
82
+ }
83
+ }
84
+
85
+ /** Tell the host after the commit; its failure is logged and cannot un-accept. */
86
+ async function tellAccepted(ctx: EngineContext, clientId: string, orderId: string): Promise<void> {
87
+ try {
88
+ await ctx.ports.order.onAccepted(clientId, orderId);
89
+ } catch (error) {
90
+ ctx.ports.logger.error(
91
+ `marketplace.confirmed: order ${orderId} is ACCEPTED but the host's half failed: ` +
92
+ (error instanceof Error ? error.message : String(error)),
93
+ );
94
+ }
95
+ }
96
+
97
+ /** Apply one confirmation to the AWAITING order it names. */
98
+ async function confirmHeld(ctx: EngineContext, inboxId: string, clientId: string, held: HeldRow): Promise<DeliveryOutcome> {
99
+ const now = ctx.ports.clock.now();
100
+ const db = await ctx.ports.db();
101
+ await db.marketplaceAcceptance.updateMany({
102
+ where: { orderId: held.orderId, clientId, status: "AWAITING", confirmedAt: null },
103
+ data: { confirmedAt: now },
104
+ });
105
+ const claim = await claimConfirmed(ctx, clientId, held, now);
106
+ const note = claim.accepted ? undefined : `accepted on the marketplace; waits for a person${claim.refusal ? ` (${claim.refusal.code})` : ""}`;
107
+ await settleInboxEvent(ctx, inboxId, "PROCESSED", note);
108
+ if (claim.accepted) await tellAccepted(ctx, clientId, held.orderId);
109
+ ctx.ports.publishChanged(clientId);
110
+ return { kind: "confirmedByMarketplace", orderId: held.orderId, ...claim };
111
+ }
112
+
113
+ /**
114
+ * Apply a marketplace confirmation, or null when the event is none (the
115
+ * caller then does what it did before FUT-5653).
116
+ */
117
+ export async function applyMarketplaceConfirmation(
118
+ ctx: EngineContext,
119
+ inboxId: string,
120
+ clientId: string,
121
+ event: NormalizedEvent,
122
+ ): Promise<DeliveryOutcome | null> {
123
+ if (!event.marketplaceConfirmed || !event.externalOrderId) return null;
124
+ const db = await ctx.ports.db();
125
+ const held = (await db.marketplaceAcceptance.findFirst({
126
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
127
+ select: { orderId: true, status: true, cancellationStatus: true },
128
+ })) as HeldRow | null;
129
+ if (!held) {
130
+ await deferInboxEvent(ctx, inboxId, CONFIRMED_BEFORE_ORDER);
131
+ return { kind: "ignored", reason: CONFIRMED_BEFORE_ORDER };
132
+ }
133
+ if (held.status === "ACCEPTED") return confirmAccepted(ctx, inboxId, clientId, held.orderId);
134
+ if (held.status !== "AWAITING") {
135
+ const reason = `the order is ${held.status}, not AWAITING`;
136
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
137
+ return { kind: "ignored", reason };
138
+ }
139
+ return confirmHeld(ctx, inboxId, clientId, held);
140
+ }
141
+
142
+ /**
143
+ * A CFM of an order already ACCEPTED here whose confirm is not stamped: a
144
+ * person's aceite that raced the tablet's, or our confirm that timed out but
145
+ * reached iFood. iFood holds the acceptance, so `confirmed_at` is stamped and
146
+ * the queued confirm skips ("already stamped") instead of confirming twice.
147
+ * A `confirm_failed_at` our duplicate confirm earned (iFood refused it because
148
+ * the tablet had confirmed first) is cleared: iFood's word is that the order
149
+ * is confirmed, so the status steps go out and the host stops showing "não
150
+ * confirmou". Only an already stamped confirm (our own echo) is IGNORED.
151
+ */
152
+ async function confirmAccepted(ctx: EngineContext, inboxId: string, clientId: string, orderId: string): Promise<DeliveryOutcome> {
153
+ const db = await ctx.ports.db();
154
+ const stamped = await db.marketplaceAcceptance.updateMany({
155
+ where: { orderId, clientId, status: "ACCEPTED", confirmedAt: null },
156
+ data: { confirmedAt: ctx.ports.clock.now(), confirmFailedAt: null },
157
+ });
158
+ if (stamped.count === 0) {
159
+ const reason = "the order is ACCEPTED and its confirm already stamped";
160
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
161
+ return { kind: "ignored", reason };
162
+ }
163
+ await settleInboxEvent(ctx, inboxId, "PROCESSED", "accepted here first; the marketplace took the acceptance");
164
+ ctx.ports.publishChanged(clientId);
165
+ return { kind: "confirmedByMarketplace", orderId, accepted: true };
166
+ }
167
+
168
+ interface DeferredRow {
169
+ id: string;
170
+ clientId: string;
171
+ provider: string;
172
+ externalOrderId: string | null;
173
+ payload: unknown;
174
+ }
175
+
176
+ /** Re-run deferred confirmations; returns the orders they were for. */
177
+ async function applyRows(ctx: EngineContext, rows: readonly DeferredRow[]): Promise<Set<string>> {
178
+ const applied = new Set<string>();
179
+ for (const row of rows) {
180
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
181
+ if (!event?.marketplaceConfirmed) continue;
182
+ const outcome = await applyMarketplaceConfirmation(ctx, row.id, row.clientId, event);
183
+ if (outcome?.kind === "confirmedByMarketplace") applied.add(outcome.orderId);
184
+ }
185
+ return applied;
186
+ }
187
+
188
+ const DEFERRED_SELECT = { id: true, clientId: true, provider: true, externalOrderId: true, payload: true } as const;
189
+
190
+ /**
191
+ * After an order of a marketplace that `marketplaceConfirms` ingested: apply a
192
+ * confirmation that arrived before it. One read, only for such a marketplace.
193
+ */
194
+ export async function applyDeferredConfirmations(
195
+ ctx: EngineContext,
196
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
197
+ ): Promise<void> {
198
+ if (!ctx.registry.get(input.provider)?.capabilities.marketplaceConfirms) return;
199
+ const db = await ctx.ports.db();
200
+ const rows = (await db.marketplaceInboxEvent.findMany({
201
+ where: { ...input, status: "PENDING", error: CONFIRMED_BEFORE_ORDER },
202
+ select: DEFERRED_SELECT,
203
+ })) as DeferredRow[];
204
+ await applyRows(ctx, rows);
205
+ }
206
+
207
+ /**
208
+ * The expiry sweep's half: for orders about to expire, apply any confirmation
209
+ * still deferred for them first. Returns the orders it accepted or stamped,
210
+ * which the sweep must not expire. One read, only when rows lapsed.
211
+ */
212
+ export async function applyOwedConfirmations(
213
+ ctx: EngineContext,
214
+ lapsed: readonly { provider: string; externalOrderId: string }[],
215
+ ): Promise<Set<string>> {
216
+ if (lapsed.length === 0) return new Set();
217
+ const db = await ctx.ports.db();
218
+ const rows = (await db.marketplaceInboxEvent.findMany({
219
+ where: {
220
+ status: "PENDING",
221
+ error: CONFIRMED_BEFORE_ORDER,
222
+ clientId: { not: null },
223
+ externalOrderId: { in: [...new Set(lapsed.map((row) => row.externalOrderId))] },
224
+ },
225
+ select: DEFERRED_SELECT,
226
+ })) as DeferredRow[];
227
+ const named = new Set(lapsed.map((row) => `${row.provider}:${row.externalOrderId}`));
228
+ return applyRows(ctx, rows.filter((row) => named.has(`${row.provider}:${row.externalOrderId ?? ""}`)));
229
+ }
@@ -0,0 +1,119 @@
1
+ import type { CancellationReason, OrderCancellationReason } from "./adapter";
2
+ import { readOutboundConnection } from "./integration";
3
+ import type { EngineContext, MarketplaceDb } from "./ports";
4
+ import { reasonsForOrder, storedReasons } from "./registry";
5
+ import type { MarketplaceProvider } from "./types";
6
+
7
+ /**
8
+ * An order's own cancellation reasons (FUT-5984, iFood's
9
+ * `GET /order/v1.0/orders/{id}/cancellationReasons`): read once, in the
10
+ * `marketplace.cancellation-reasons` job queued after the ingest's commit, and
11
+ * kept on the acceptance row (`cancellation_reasons`) for the order's life.
12
+ * The adapter's static list is the fallback while, or when, that read did not
13
+ * land: a refusal is never held on the marketplace.
14
+ */
15
+
16
+ /** The wire name, `<namespace>.<blueprint>`. */
17
+ export const MARKETPLACE_CANCELLATION_REASONS_JOB = "marketplace.cancellation-reasons";
18
+
19
+ /** The job's payload: identifiers only. */
20
+ export interface CancellationReasonsJobPayload {
21
+ clientId: string;
22
+ orderId: string;
23
+ }
24
+
25
+ /** What one run did. */
26
+ export type CancellationReasonsOutcome =
27
+ | { kind: "skipped"; reason: string }
28
+ | { kind: "done"; count: number }
29
+ | { kind: "failed"; reason: string };
30
+
31
+ /** Thrown so the queue retries. */
32
+ export class CancellationReasonsRetryError extends Error {
33
+ constructor(message: string) {
34
+ super(message);
35
+ this.name = "CancellationReasonsRetryError";
36
+ }
37
+ }
38
+
39
+ /** Queue the read of a new order's reasons, when its marketplace lists them per order. Never throws. */
40
+ export async function enqueueOrderReasons(
41
+ ctx: EngineContext,
42
+ input: { clientId: string; orderId: string; provider: MarketplaceProvider },
43
+ ): Promise<void> {
44
+ if (!ctx.registry.get(input.provider)?.orderCancellationReasons) return;
45
+ const payload: CancellationReasonsJobPayload = { clientId: input.clientId, orderId: input.orderId };
46
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
47
+ dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`,
48
+ });
49
+ if (!outcome.enqueued) {
50
+ ctx.ports.logger.warn(
51
+ `${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${input.orderId} was not queued; its reasons stay the static list` +
52
+ (outcome.reason ? ` (${outcome.reason})` : ""),
53
+ );
54
+ }
55
+ }
56
+
57
+ interface ReasonsRow {
58
+ orderId: string;
59
+ provider: string;
60
+ externalOrderId: string;
61
+ cancellationReasons: unknown;
62
+ }
63
+
64
+ /** Keep a read list on the order; an empty one is not kept, so the static list stays (FUT-5984). */
65
+ async function keep(
66
+ ctx: EngineContext,
67
+ db: MarketplaceDb,
68
+ clientId: string,
69
+ orderId: string,
70
+ reasons: readonly OrderCancellationReason[],
71
+ ): Promise<CancellationReasonsOutcome> {
72
+ if (reasons.length === 0) {
73
+ ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${orderId} got an empty list; it keeps the static reasons`);
74
+ return { kind: "skipped", reason: "the marketplace listed no reason" };
75
+ }
76
+ await db.marketplaceAcceptance.updateMany({ where: { orderId }, data: { cancellationReasons: reasons } });
77
+ ctx.ports.publishChanged(clientId);
78
+ return { kind: "done", count: reasons.length };
79
+ }
80
+
81
+ /** Run one read. Throws {@link CancellationReasonsRetryError} for a retryable answer before the last attempt. */
82
+ export async function runCancellationReasons(
83
+ ctx: EngineContext,
84
+ payload: CancellationReasonsJobPayload,
85
+ attempt: { attempt: number; maxAttempts: number },
86
+ ): Promise<CancellationReasonsOutcome> {
87
+ const db = await ctx.ports.db();
88
+ const row = (await db.marketplaceAcceptance.findFirst({
89
+ where: { orderId: payload.orderId, clientId: payload.clientId },
90
+ select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true },
91
+ })) as ReasonsRow | null;
92
+ if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
93
+ if (storedReasons(row.cancellationReasons) !== null) return { kind: "skipped", reason: "the order's reasons are already kept" };
94
+ const read = ctx.registry.get(row.provider)?.orderCancellationReasons;
95
+ if (!read) return { kind: "skipped", reason: `${row.provider} lists no reasons per order` };
96
+ const connection = await readOutboundConnection(ctx, payload.clientId, row.provider).catch(() => null);
97
+ if (!connection) return { kind: "skipped", reason: "no credentials on file" };
98
+
99
+ const result = await read({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, row);
100
+ if (result.kind === "reasons") return keep(ctx, db, payload.clientId, row.orderId, result.reasons);
101
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
102
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
103
+ throw new CancellationReasonsRetryError(`reasons of order ${row.orderId}: ${reason}`);
104
+ }
105
+ // The static list stays this order's reasons: a refusal never waits on the marketplace.
106
+ ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${row.orderId} keeps the static reasons: ${reason}`);
107
+ return { kind: "failed", reason };
108
+ }
109
+
110
+ /** One order's reasons, for the refusal dialog: its own, else the static list. Empty for an unknown order. */
111
+ export async function readOrderReasons(ctx: EngineContext, clientId: string, orderId: string): Promise<readonly CancellationReason[]> {
112
+ const db = await ctx.ports.db();
113
+ const row = (await db.marketplaceAcceptance.findFirst({
114
+ where: { orderId, clientId },
115
+ select: { provider: true, cancellationReasons: true },
116
+ })) as { provider: string; cancellationReasons: unknown } | null;
117
+ const adapter = row ? ctx.registry.get(row.provider) : null;
118
+ return adapter ? reasonsForOrder(adapter, row?.cancellationReasons) : [];
119
+ }
@@ -70,6 +70,7 @@ interface OutboundRow {
70
70
  cancellationOffendingSkus: unknown;
71
71
  cancellationRequestedAt: Date | null;
72
72
  preparationMinutes: number | null;
73
+ cancellationReasons: unknown;
73
74
  createdAt: Date;
74
75
  }
75
76
 
@@ -87,6 +88,7 @@ const ROW_SELECT = {
87
88
  cancellationOffendingSkus: true,
88
89
  cancellationRequestedAt: true,
89
90
  preparationMinutes: true,
91
+ cancellationReasons: true,
90
92
  createdAt: true,
91
93
  } as const;
92
94
 
@@ -303,7 +305,9 @@ async function runCancellation(
303
305
  await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
304
306
  return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
305
307
  }
306
- const reason = resolveReason(adapter, row.cancellationReasonCode);
308
+ // The order's own list, else the static list the code was validated against when the order's
309
+ // was not read yet (FUT-5984): a list stored in between never turns a valid request into ours.
310
+ const reason = resolveReason(adapter, row.cancellationReasonCode, row.cancellationReasons) ?? resolveReason(adapter, row.cancellationReasonCode);
307
311
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
308
312
  let result: OutboundResult;
309
313
  // A stored reason that is not the marketplace's own was never sent: our side (UNREACHABLE).
@@ -14,6 +14,8 @@ import type {
14
14
  NormalizedMarketplaceOrder,
15
15
  } from "./types";
16
16
  import { followCourierAndLifecycle } from "./courier";
17
+ import { enqueueAcknowledge } from "./acknowledge";
18
+ import { applyMarketplaceConfirmation } from "./marketplace-confirmed";
17
19
 
18
20
  /**
19
21
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -45,6 +47,12 @@ export type DeliveryOutcome =
45
47
  | { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
46
48
  /** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
47
49
  | { kind: "courier"; orderId: string; step: MarketplaceCourierStep }
50
+ /**
51
+ * The store accepted it in the marketplace's own app (FUT-5653): `accepted`
52
+ * when the host admitted it here too, else it waits AWAITING for a person
53
+ * (with the host's `refusal`, when it refused), never expired.
54
+ */
55
+ | { kind: "confirmedByMarketplace"; orderId: string; accepted: boolean; refusal?: { code: string; message: string } }
48
56
  | { kind: "cancelled" }
49
57
  | { kind: "cancellationFailed" }
50
58
  /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
@@ -80,6 +88,8 @@ export async function processDelivery(
80
88
  const { clientId, event, settings } = input;
81
89
  const record = await recordInboxEvent(ctx, { clientId, event, payload: input.payload });
82
90
  if (!record.fresh) return { kind: "duplicate" };
91
+ // The marketplace hears it was recorded, from a job after this commit (FUT-5984); a queue call only.
92
+ await enqueueAcknowledge(ctx, { clientId, provider: event.provider, inboxId: record.id });
83
93
 
84
94
  if (!clientId || !settings) {
85
95
  // Stored, not dropped, and the two reasons are kept apart because only one
@@ -175,11 +185,27 @@ async function applyEvent(
175
185
  // lifecycle event (dispatched, collected, concluded) of an order we hold:
176
186
  // with the connection's switch ON and a host that binds the hook, the order
177
187
  // follows. Anything else falls through to "understood, nothing to do", as before.
178
- const followed = await followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
188
+ const followed = await followMarketplace(ctx, inboxId, clientId, event, settings);
179
189
  if (followed) return followed;
180
190
  return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
181
191
  }
182
192
 
193
+ /**
194
+ * What the marketplace says about an order it already gave us: the store
195
+ * accepted it in the marketplace's app (FUT-5653), or a courier or lifecycle
196
+ * step. Null for anything else.
197
+ */
198
+ async function followMarketplace(
199
+ ctx: EngineContext,
200
+ inboxId: string,
201
+ clientId: string,
202
+ event: NormalizedEvent,
203
+ settings: IngestSettings,
204
+ ): Promise<DeliveryOutcome | null> {
205
+ const confirmed = await applyMarketplaceConfirmation(ctx, inboxId, clientId, event);
206
+ return confirmed ?? followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
207
+ }
208
+
183
209
  /** An event with no order body is understood and ignored; one that carries an order is ingested. */
184
210
  async function ingestOrIgnore(
185
211
  ctx: EngineContext,
package/src/core/ports.ts CHANGED
@@ -67,6 +67,8 @@ export interface MarketplaceDb {
67
67
  findMany(args: unknown): Promise<unknown[]>;
68
68
  create(args: unknown): Promise<unknown>;
69
69
  update(args: unknown): Promise<unknown>;
70
+ /** The acknowledgment's stamp (FUT-5984). */
71
+ updateMany(args: unknown): Promise<{ count: number }>;
70
72
  };
71
73
  marketplaceAcceptance: {
72
74
  findFirst(args: unknown): Promise<unknown>;
@@ -1,4 +1,4 @@
1
- import type { CancellationReason, MarketplaceAdapter } from "./adapter";
1
+ import type { CancellationReason, MarketplaceAdapter, OrderCancellationReason } from "./adapter";
2
2
  import { PROVIDER_ID_PATTERN, type MarketplaceProvider } from "./types";
3
3
 
4
4
  /**
@@ -75,6 +75,30 @@ export function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]):
75
75
  };
76
76
  }
77
77
 
78
+ /** The stored list, read defensively: anything that is not a list of codes is "not read". */
79
+ export function storedReasons(value: unknown): OrderCancellationReason[] | null {
80
+ // An empty list is "not read": every refusal would be refused, so the static list applies.
81
+ if (!Array.isArray(value) || value.length === 0) return null;
82
+ return value.flatMap((entry: unknown) => {
83
+ const { code, description } = (entry ?? {}) as { code?: unknown; description?: unknown };
84
+ return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
85
+ });
86
+ }
87
+
88
+ /**
89
+ * The reasons an order may be refused or cancelled with: its own list when it
90
+ * was read (each labelled by the adapter's pack when the pack names the code,
91
+ * else by the marketplace's own words), else the adapter's static list.
92
+ */
93
+ export function reasonsForOrder(adapter: MarketplaceAdapter, stored: unknown): readonly CancellationReason[] {
94
+ const own = storedReasons(stored);
95
+ if (own === null) return adapter.cancellationReasons();
96
+ const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
97
+ return own.map(
98
+ (reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false },
99
+ );
100
+ }
101
+
78
102
  /**
79
103
  * The reason a refusal carries: the one named by `code`, or — when the store
80
104
  * named none — the adapter's first. `null` when the code is not one of the
@@ -83,8 +107,10 @@ export function createAdapterRegistry(adapters: readonly MarketplaceAdapter[]):
83
107
  export function resolveReason(
84
108
  adapter: MarketplaceAdapter,
85
109
  code: string | null | undefined,
110
+ /** The order's own list (`cancellation_reasons`, FUT-5984); absent or unread: the static one. */
111
+ stored?: unknown,
86
112
  ): CancellationReason | null {
87
- const reasons = adapter.cancellationReasons();
113
+ const reasons = reasonsForOrder(adapter, stored);
88
114
  if (code === null || code === undefined) return reasons[0] ?? null;
89
115
  return reasons.find((reason) => reason.code === code) ?? null;
90
116
  }
package/src/core/state.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
+ import type { CancellationReason } from "./adapter";
2
3
  import type { CancellationFailureReason, EngineContext } from "./ports";
4
+ import { reasonsForOrder, storedReasons } from "./registry";
3
5
  import type { MarketplaceProvider } from "./types";
4
6
 
5
7
  /**
@@ -21,6 +23,11 @@ export interface MarketplaceOrderState {
21
23
  cancellationFailure: CancellationFailureReason | null;
22
24
  /** The adapter's app link, or null when no adapter is registered for it. */
23
25
  appUrl: string | null;
26
+ /**
27
+ * This order's own reasons, read from the marketplace (FUT-5984); null while
28
+ * or when they were not read: the adapter's static `reasons(provider)` then.
29
+ */
30
+ cancellationReasons: readonly CancellationReason[] | null;
24
31
  }
25
32
 
26
33
  interface StateRow {
@@ -34,6 +41,7 @@ interface StateRow {
34
41
  cancellationStatus: string | null;
35
42
  cancellationReasonCode: string | null;
36
43
  cancellationFailureReason: string | null;
44
+ cancellationReasons: unknown;
37
45
  }
38
46
 
39
47
  /** The state of each of these orders that is a marketplace order, keyed by id. */
@@ -57,6 +65,7 @@ export async function readOrderStates(
57
65
  cancellationStatus: true,
58
66
  cancellationReasonCode: true,
59
67
  cancellationFailureReason: true,
68
+ cancellationReasons: true,
60
69
  },
61
70
  })) as StateRow[];
62
71
  return new Map(
@@ -74,6 +83,7 @@ export async function readOrderStates(
74
83
  cancellationReasonCode: row.cancellationReasonCode,
75
84
  cancellationFailure: row.cancellationFailureReason as CancellationFailureReason | null,
76
85
  appUrl: adapter ? adapter.appLink(row) : null,
86
+ cancellationReasons: adapter && storedReasons(row.cancellationReasons) !== null ? reasonsForOrder(adapter, row.cancellationReasons) : null,
77
87
  };
78
88
  return [row.orderId, state];
79
89
  }),