@12-apps/marketplace 1.12.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 (64) hide show
  1. package/ADOPTING.md +184 -0
  2. package/README.md +39 -4
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-nUyZpLzz.d.ts → adapter-szxo9ohc.d.ts} +84 -3
  6. package/dist/{chunk-L6FG6T4S.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-LACBT6NC.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-45ZVN5XI.js → chunk-MDXSVE7Q.js} +707 -255
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-MIPNQ7X5.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-Ctas7WCS.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-CIy9P7Cq.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 +26 -3
  18. package/dist/ifood/index.js +301 -140
  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 +76 -2
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/connection-stamp.ts +61 -0
  40. package/src/core/engine.ts +3 -2
  41. package/src/core/fetch-order.ts +54 -12
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +19 -4
  44. package/src/core/link-store.ts +2 -4
  45. package/src/core/marketplace-confirmed.ts +229 -0
  46. package/src/core/order-reasons.ts +119 -0
  47. package/src/core/outbound.ts +5 -1
  48. package/src/core/pipeline.ts +27 -1
  49. package/src/core/ports.ts +2 -0
  50. package/src/core/registry.ts +28 -2
  51. package/src/core/state.ts +10 -0
  52. package/src/core/status-job.ts +86 -3
  53. package/src/core/types.ts +6 -0
  54. package/src/ifood/fetch-order.ts +103 -0
  55. package/src/ifood/index.ts +31 -4
  56. package/src/ifood/normalize.ts +39 -3
  57. package/src/ifood/outbound.ts +131 -27
  58. package/src/index.ts +18 -0
  59. package/src/server/jobs.ts +57 -4
  60. package/src/server/webhook.ts +27 -4
  61. package/dist/chunk-45ZVN5XI.js.map +0 -1
  62. package/dist/chunk-LACBT6NC.js.map +0 -1
  63. package/dist/chunk-MIPNQ7X5.js.map +0 -1
  64. /package/dist/{chunk-L6FG6T4S.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
+ }
@@ -0,0 +1,61 @@
1
+ import type { EngineContext } from "./ports";
2
+ import type { MarketplaceProvider } from "./types";
3
+
4
+ /**
5
+ * What a call no person made says about a connection's credentials (the order
6
+ * fetch, FUT-5800): refused, or working again. Each stamp is guarded on the
7
+ * sealed credentials the call was made with, as `./link-store.ts`'s
8
+ * `markLinkFailed` is, so a call made with credentials since replaced never
9
+ * judges the new ones.
10
+ */
11
+
12
+ /**
13
+ * The marketplace refused this connection's credentials on a call no person
14
+ * made (the order fetch, FUT-5800): the connection reads FAILED, which is what
15
+ * the connections screen shows, and the staff surfaces are told. Only the
16
+ * credentials the call was made with (`sealed`) are judged: a store that
17
+ * entered new ones meanwhile is left alone. Re-entering the credentials resets
18
+ * it to UNVERIFIED; the next fetch that succeeds, to VERIFIED
19
+ * ({@link markCredentialsAccepted}). Best-effort: never throws.
20
+ */
21
+ export async function markCredentialsRefused(
22
+ ctx: EngineContext,
23
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
24
+ ): Promise<void> {
25
+ await stampConnection(ctx, input, { archivedAt: null }, { status: "FAILED" });
26
+ }
27
+
28
+ /**
29
+ * A call with these credentials (`sealed`) succeeded: a connection that read
30
+ * FAILED for them reads VERIFIED again. Any other status is left as it is.
31
+ * Best-effort: never throws.
32
+ */
33
+ export async function markCredentialsAccepted(
34
+ ctx: EngineContext,
35
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
36
+ ): Promise<void> {
37
+ await stampConnection(ctx, input, { status: "FAILED" }, { status: "VERIFIED", lastVerifiedAt: ctx.ports.clock.now() });
38
+ }
39
+
40
+ /** One guarded status write on the connection the call was made with; tells the staff surfaces when it moved. */
41
+ async function stampConnection(
42
+ ctx: EngineContext,
43
+ input: { clientId: string; provider: MarketplaceProvider; sealed: string },
44
+ where: Record<string, unknown>,
45
+ data: Record<string, unknown>,
46
+ ): Promise<void> {
47
+ const { clientId, provider, sealed } = input;
48
+ try {
49
+ const db = await ctx.ports.db();
50
+ const { count } = await db.marketplaceIntegration.updateMany({
51
+ where: { clientId, provider, credentials: sealed, ...where },
52
+ data,
53
+ });
54
+ if (count > 0) ctx.ports.publishChanged(clientId);
55
+ } catch (error) {
56
+ ctx.ports.logger.error(
57
+ `marketplace: ${provider} connection of ${clientId} not stamped ${String(data.status)}: ` +
58
+ (error instanceof Error ? error.message : String(error)),
59
+ );
60
+ }
61
+ }
@@ -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,6 +1,7 @@
1
1
  import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
2
  import { ingestMarketplaceOrder } from "./ingest";
3
- import { readOutboundConnection, resolveIngestionTarget } from "./integration";
3
+ import { markCredentialsAccepted, markCredentialsRefused } from "./connection-stamp";
4
+ import { readSealedOutboundConnection, resolveIngestionTarget } from "./integration";
4
5
  import type { FetchOrderResult } from "./adapter";
5
6
  import { cancelAcceptance } from "./acceptance";
6
7
  import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest } from "./order-fetch-marks";
@@ -131,30 +132,37 @@ async function owedFetch(
131
132
  return { row, event };
132
133
  }
133
134
 
135
+ /** What one call to the adapter answered, and the sealed credentials it was made with (null: no call). */
136
+ interface AdapterFetch {
137
+ result: FetchOrderResult;
138
+ sealed: string | null;
139
+ }
140
+
134
141
  /** One call to the adapter, or the refusal that stands in for it. */
135
142
  async function fetchThroughAdapter(
136
143
  ctx: EngineContext,
137
144
  clientId: string,
138
145
  provider: MarketplaceProvider,
139
146
  externalOrderId: string,
140
- ): Promise<FetchOrderResult> {
147
+ ): Promise<AdapterFetch> {
141
148
  const adapter = ctx.registry.get(provider);
142
- if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
143
- let connection;
149
+ if (!adapter?.fetchOrder) return { result: { kind: "refused", status: 0, message: `${provider} cannot fetch an order` }, sealed: null };
150
+ let opened;
144
151
  try {
145
- connection = await readOutboundConnection(ctx, clientId, provider);
152
+ opened = await readSealedOutboundConnection(ctx, clientId, provider);
146
153
  } catch (error) {
147
154
  const reason = error instanceof Error ? error.message : String(error);
148
- return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
155
+ return { result: { kind: "refused", status: 0, message: `credentials do not open: ${reason}` }, sealed: null };
149
156
  }
150
- if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
157
+ if (!opened) return { result: { kind: "refused", status: 0, message: "no credentials on file" }, sealed: null };
151
158
  try {
152
- return await adapter.fetchOrder(
153
- { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
159
+ const result = await adapter.fetchOrder(
160
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...opened.connection },
154
161
  { externalOrderId },
155
162
  );
163
+ return { result, sealed: opened.sealed };
156
164
  } catch (error) {
157
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
165
+ return { result: { kind: "retry", reason: error instanceof Error ? error.message : String(error) }, sealed: opened.sealed };
158
166
  }
159
167
  }
160
168
 
@@ -222,6 +230,11 @@ async function ingestFetched(
222
230
  return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
223
231
  }
224
232
 
233
+ /** A final refusal of our own credentials by the marketplace (a 4xx, not a local "no credentials"). */
234
+ function credentialsRefused(result: FetchOrderResult): boolean {
235
+ return result.kind === "refused" && result.own === true && result.status >= 400 && result.status < 500;
236
+ }
237
+
225
238
  /**
226
239
  * Run one queued fetch. Returns what it did; throws {@link FetchOrderRetryError}
227
240
  * for an answer worth retrying before the last attempt. A refusal, or the last
@@ -241,12 +254,41 @@ export async function runFetchOrder(
241
254
  await deferInboxEvent(ctx, row.id, "integration is not enabled");
242
255
  return { kind: "skipped", reason: "integration is not enabled" };
243
256
  }
244
- const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
245
- if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
257
+ const { result, sealed } = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
258
+ const stamp = sealed === null ? null : { clientId: payload.clientId, provider: event.provider, sealed };
259
+ if (result.kind === "order") {
260
+ // The credentials worked: a FAILED stamp left by an earlier refusal of these same ones is lifted.
261
+ if (stamp) await markCredentialsAccepted(ctx, stamp);
262
+ return ingestFetched(ctx, row, payload.clientId, result.order, target);
263
+ }
264
+ return endUnfetched(ctx, { row, event, result, attempt, stamp });
265
+ }
266
+
267
+ /**
268
+ * A fetch that brought no order: rethrown for the queue while a retry is worth
269
+ * it, else the row settles FAILED. Our credentials refused (a 401 that a fresh
270
+ * token did not cure, a refused token grant) are never retried by the queue:
271
+ * the connection reads FAILED, and the reconciliation sweep's next pass,
272
+ * minutes away and within the row's attempt bound, is the only re-try, so a
273
+ * revoked app never loops.
274
+ */
275
+ async function endUnfetched(
276
+ ctx: EngineContext,
277
+ input: {
278
+ row: InboxRow;
279
+ event: NormalizedEvent;
280
+ result: Exclude<FetchOrderResult, { kind: "order" }>;
281
+ attempt: { attempt: number; maxAttempts: number };
282
+ /** The connection and the sealed credentials the call was made with; null when no call was made. */
283
+ stamp: { clientId: string; provider: MarketplaceProvider; sealed: string } | null;
284
+ },
285
+ ): Promise<FetchOrderOutcome> {
286
+ const { row, event, result, attempt } = input;
246
287
  const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
247
288
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
248
289
  throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
249
290
  }
291
+ if (input.stamp && credentialsRefused(result)) await markCredentialsRefused(ctx, input.stamp);
250
292
  await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
251
293
  ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
252
294
  return { kind: "failed", reason };
@@ -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
  }
@@ -357,18 +357,33 @@ export async function readOutboundConnection(
357
357
  clientId: string,
358
358
  provider: MarketplaceProvider,
359
359
  ): Promise<OutboundConnection | null> {
360
+ return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
361
+ }
362
+
363
+ /**
364
+ * {@link readOutboundConnection}, with the sealed blob it was opened from: a
365
+ * caller that stamps the connection afterwards (`./fetch-order.ts`) guards
366
+ * the stamp on it, so a call made with credentials since replaced never
367
+ * judges the new ones. The blob never reaches an adapter.
368
+ */
369
+ export async function readSealedOutboundConnection(
370
+ ctx: EngineContext,
371
+ clientId: string,
372
+ provider: MarketplaceProvider,
373
+ ): Promise<{ connection: OutboundConnection; sealed: string } | null> {
360
374
  const db = await ctx.ports.db();
361
375
  const row = (await db.marketplaceIntegration.findUnique({
362
376
  where: { clientId_provider: { clientId, provider } },
363
377
  select: { environment: true, credentials: true, authMode: true },
364
378
  })) as { environment: string; credentials: string; authMode?: string } | null;
365
379
  if (!row || row.credentials === "") return null;
380
+ const sealed = row.credentials;
366
381
  const environment = environmentOf(row.environment);
367
- if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
382
+ if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
368
383
  // Linked: the software's app speaks for the store, with the store's refresh token.
369
384
  const app = await appCredentialsOf(ctx, provider, environment);
370
385
  if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
371
- const refreshToken = openLinkRefreshToken(ctx, row.credentials);
372
- const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
373
- return { environment, credentials: app, grant: linkGrant(ctx, link) };
386
+ const refreshToken = openLinkRefreshToken(ctx, sealed);
387
+ const link = { clientId, provider, environment, refreshToken, app, sealed };
388
+ return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
374
389
  }
@@ -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
+ }