@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
@@ -60,8 +60,25 @@ function createAdapterRegistry(adapters) {
60
60
  };
61
61
  }
62
62
  __name(createAdapterRegistry, "createAdapterRegistry");
63
- function resolveReason(adapter, code) {
64
- const reasons = adapter.cancellationReasons();
63
+ function storedReasons(value) {
64
+ if (!Array.isArray(value) || value.length === 0) return null;
65
+ return value.flatMap((entry) => {
66
+ const { code, description } = entry ?? {};
67
+ return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
68
+ });
69
+ }
70
+ __name(storedReasons, "storedReasons");
71
+ function reasonsForOrder(adapter, stored) {
72
+ const own = storedReasons(stored);
73
+ if (own === null) return adapter.cancellationReasons();
74
+ const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
75
+ return own.map(
76
+ (reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false }
77
+ );
78
+ }
79
+ __name(reasonsForOrder, "reasonsForOrder");
80
+ function resolveReason(adapter, code, stored) {
81
+ const reasons = reasonsForOrder(adapter, stored);
65
82
  if (code === null || code === void 0) return reasons[0] ?? null;
66
83
  return reasons.find((reason) => reason.code === code) ?? null;
67
84
  }
@@ -76,6 +93,389 @@ function suggestReason(adapter, input) {
76
93
  }
77
94
  __name(suggestReason, "suggestReason");
78
95
 
96
+ // src/core/cancellation-outcome.ts
97
+ async function tell(ctx, what, orderId, call2) {
98
+ try {
99
+ await call2();
100
+ } catch (error) {
101
+ ctx.ports.logger.error(
102
+ `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
103
+ );
104
+ }
105
+ }
106
+ __name(tell, "tell");
107
+ function requestsFirst(ctx) {
108
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
109
+ }
110
+ __name(requestsFirst, "requestsFirst");
111
+ async function rejectConfirmed(db, orderId, now) {
112
+ await db.marketplaceAcceptance.updateMany({
113
+ where: { orderId, status: "AWAITING" },
114
+ data: { status: "REJECTED", acknowledgedAt: now }
115
+ });
116
+ await db.marketplaceAcceptance.updateMany({
117
+ where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
118
+ data: { status: "REJECTED" }
119
+ });
120
+ }
121
+ __name(rejectConfirmed, "rejectConfirmed");
122
+ async function confirmedToHost(ctx, clientId, orderId) {
123
+ if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
124
+ await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
125
+ }
126
+ __name(confirmedToHost, "confirmedToHost");
127
+ async function tellCancellationConfirmed(ctx, clientId, orderId) {
128
+ const hook = ctx.ports.order.onCancellationConfirmed;
129
+ if (!hook) return false;
130
+ await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
131
+ return true;
132
+ }
133
+ __name(tellCancellationConfirmed, "tellCancellationConfirmed");
134
+ async function tellCancellationFailed(ctx, clientId, orderId, reason) {
135
+ const hook = ctx.ports.order.onCancellationFailed;
136
+ if (!hook) return;
137
+ await tell(
138
+ ctx,
139
+ `had its cancellation request fail (${reason})`,
140
+ orderId,
141
+ () => hook.call(ctx.ports.order, clientId, orderId, reason)
142
+ );
143
+ }
144
+ __name(tellCancellationFailed, "tellCancellationFailed");
145
+ function cancellationWindowMs(ctx, adapter) {
146
+ return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
147
+ }
148
+ __name(cancellationWindowMs, "cancellationWindowMs");
149
+ function failedRequestData(reason) {
150
+ return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
151
+ }
152
+ __name(failedRequestData, "failedRequestData");
153
+
154
+ // src/core/cancellation.ts
155
+ function noStandingRequest(cancellationStatus) {
156
+ return cancellationStatus === null || cancellationStatus === "FAILED";
157
+ }
158
+ __name(noStandingRequest, "noStandingRequest");
159
+ var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
160
+ var CLAIM_SELECT = {
161
+ orderId: true,
162
+ provider: true,
163
+ status: true,
164
+ cancellationStatus: true,
165
+ lineSkus: true,
166
+ cancellationReasons: true
167
+ };
168
+ function notPendingProblem(row, path, allowed = ["AWAITING"]) {
169
+ if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
170
+ if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
171
+ const status = row.status;
172
+ return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
173
+ }
174
+ __name(notPendingProblem, "notPendingProblem");
175
+ function lineSkusOf(row) {
176
+ return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
177
+ }
178
+ __name(lineSkusOf, "lineSkusOf");
179
+ function skuProblems(reason, skus, row, path) {
180
+ if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
181
+ const known = lineSkusOf(row);
182
+ if (!known) return [];
183
+ return skus.flatMap(
184
+ (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
185
+ );
186
+ }
187
+ __name(skuProblems, "skuProblems");
188
+ function invalidReasonProblem(adapter, reason, input, path) {
189
+ if (input.code === null || input.code === void 0 || reason) return null;
190
+ const validCodes = reasonsForOrder(adapter, input.stored).map((candidate) => candidate.code);
191
+ return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
192
+ }
193
+ __name(invalidReasonProblem, "invalidReasonProblem");
194
+ function planCancellation(adapter, input, row, path) {
195
+ if (!adapter) return { status: null, reason: null, skus: [] };
196
+ const reason = resolveReason(adapter, input.reasonCode, row.cancellationReasons);
197
+ const invalid = invalidReasonProblem(adapter, reason, { code: input.reasonCode, stored: row.cancellationReasons }, path);
198
+ if (invalid) return [invalid];
199
+ const skus = [...new Set(input.offendingSkus ?? [])];
200
+ const problems = skuProblems(reason, skus, row, path);
201
+ if (problems.length > 0) return problems;
202
+ const { apiCancel, cancelAfterAccept } = adapter.capabilities;
203
+ const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
204
+ return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
205
+ }
206
+ __name(planCancellation, "planCancellation");
207
+ function refusalData(plan, fromStatus, now) {
208
+ return {
209
+ status: "REJECTED",
210
+ // An accepted row keeps the instant it was accepted; a row leaving the
211
+ // clock is acknowledged now (the table's CHECK pairs the two).
212
+ ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
213
+ cancellationStatus: plan.status,
214
+ cancellationReasonCode: plan.reason?.code ?? null,
215
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
216
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
217
+ // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
218
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
219
+ };
220
+ }
221
+ __name(refusalData, "refusalData");
222
+ function requestData(plan, now) {
223
+ return {
224
+ cancellationStatus: plan.status,
225
+ cancellationReasonCode: plan.reason?.code ?? null,
226
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
227
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
228
+ // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
229
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
230
+ };
231
+ }
232
+ __name(requestData, "requestData");
233
+ async function failCancellationRequest(ctx, input) {
234
+ const db = await ctx.ports.db();
235
+ const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
236
+ const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
237
+ if (!row) return false;
238
+ const moved = await db.marketplaceAcceptance.updateMany({
239
+ where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
240
+ data: failedRequestData("REFUSED")
241
+ });
242
+ if (moved.count === 0) return false;
243
+ ctx.ports.publishChanged(input.clientId);
244
+ await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
245
+ return true;
246
+ }
247
+ __name(failCancellationRequest, "failCancellationRequest");
248
+
249
+ // src/core/inbox.ts
250
+ async function recordInboxEvent(ctx, input) {
251
+ const db = await ctx.ports.db();
252
+ const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
253
+ const existing = await db.marketplaceInboxEvent.findUnique({
254
+ where: key,
255
+ select: { id: true }
256
+ });
257
+ if (existing) return { id: existing.id, fresh: false };
258
+ try {
259
+ const row = await db.marketplaceInboxEvent.create({
260
+ data: {
261
+ clientId: input.clientId,
262
+ provider: input.event.provider,
263
+ eventId: input.event.eventId,
264
+ eventType: input.event.eventType,
265
+ externalOrderId: input.event.externalOrderId,
266
+ payload: input.payload,
267
+ // The engine's clock, not the database's: an announced order's
268
+ // acceptance window counts from here (`./fetch-order.ts`).
269
+ receivedAt: ctx.ports.clock.now()
270
+ },
271
+ select: { id: true }
272
+ });
273
+ return { id: row.id, fresh: true };
274
+ } catch (error) {
275
+ if (error.code !== "P2002") throw error;
276
+ const raced = await db.marketplaceInboxEvent.findUnique({
277
+ where: key,
278
+ select: { id: true }
279
+ });
280
+ return { id: raced?.id ?? "", fresh: false };
281
+ }
282
+ }
283
+ __name(recordInboxEvent, "recordInboxEvent");
284
+ async function settleInboxEvent(ctx, id, outcome, error) {
285
+ if (!id) return;
286
+ const db = await ctx.ports.db();
287
+ await db.marketplaceInboxEvent.update({
288
+ where: { id },
289
+ data: {
290
+ status: outcome,
291
+ // Truncated: a provider's error body can be a page of HTML, and the
292
+ // column exists to be read by a human in a list.
293
+ error: error ? error.slice(0, 500) : null,
294
+ processedAt: ctx.ports.clock.now(),
295
+ attempts: { increment: 1 }
296
+ }
297
+ });
298
+ }
299
+ __name(settleInboxEvent, "settleInboxEvent");
300
+ async function deferInboxEvent(ctx, id, reason) {
301
+ if (!id) return;
302
+ const db = await ctx.ports.db();
303
+ await db.marketplaceInboxEvent.update({
304
+ where: { id },
305
+ data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
306
+ });
307
+ }
308
+ __name(deferInboxEvent, "deferInboxEvent");
309
+ async function listRetryableInboxEvents(ctx) {
310
+ const db = await ctx.ports.db();
311
+ const rows = await db.marketplaceInboxEvent.findMany({
312
+ where: {
313
+ status: { in: ["PENDING", "FAILED"] },
314
+ clientId: { not: null },
315
+ attempts: { lt: ctx.ports.maxInboxAttempts }
316
+ },
317
+ orderBy: { receivedAt: "asc" },
318
+ take: ctx.ports.reconcileBatchSize,
319
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
320
+ });
321
+ return rows.map((row) => ({
322
+ id: row.id,
323
+ clientId: row.clientId,
324
+ provider: row.provider,
325
+ payload: row.payload,
326
+ receivedAt: row.receivedAt
327
+ }));
328
+ }
329
+ __name(listRetryableInboxEvents, "listRetryableInboxEvents");
330
+
331
+ // src/core/marketplace-confirmed.ts
332
+ var CONFIRMED_BEFORE_ORDER = "confirmed before its order";
333
+ var NotClaimed = class extends Error {
334
+ constructor(refusal) {
335
+ super("not claimed");
336
+ this.refusal = refusal;
337
+ }
338
+ refusal;
339
+ static {
340
+ __name(this, "NotClaimed");
341
+ }
342
+ };
343
+ var CLEARED_FAILED_REQUEST = {
344
+ cancellationStatus: null,
345
+ cancellationReasonCode: null,
346
+ cancellationOffendingSkus: null,
347
+ cancellationFailureReason: null
348
+ };
349
+ async function claimConfirmed(ctx, clientId, held, now) {
350
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") return { accepted: false };
351
+ try {
352
+ await ctx.ports.transaction(async (tx) => {
353
+ const answer = await ctx.ports.order.admit({
354
+ clientId,
355
+ orderId: held.orderId,
356
+ decision: "ACCEPT",
357
+ admission: {},
358
+ db: tx
359
+ });
360
+ if (!answer.admitted) throw new NotClaimed({ code: answer.code, message: answer.message });
361
+ const claimed = await tx.marketplaceAcceptance.updateMany({
362
+ where: { orderId: held.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
363
+ data: {
364
+ status: "ACCEPTED",
365
+ acknowledgedAt: now,
366
+ confirmedAt: now,
367
+ ...held.cancellationStatus === "FAILED" ? CLEARED_FAILED_REQUEST : {}
368
+ }
369
+ });
370
+ if (claimed.count === 0) throw new NotClaimed(null);
371
+ });
372
+ return { accepted: true };
373
+ } catch (error) {
374
+ if (!(error instanceof NotClaimed)) throw error;
375
+ return error.refusal ? { accepted: false, refusal: error.refusal } : { accepted: false };
376
+ }
377
+ }
378
+ __name(claimConfirmed, "claimConfirmed");
379
+ async function tellAccepted(ctx, clientId, orderId) {
380
+ try {
381
+ await ctx.ports.order.onAccepted(clientId, orderId);
382
+ } catch (error) {
383
+ ctx.ports.logger.error(
384
+ `marketplace.confirmed: order ${orderId} is ACCEPTED but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
385
+ );
386
+ }
387
+ }
388
+ __name(tellAccepted, "tellAccepted");
389
+ async function confirmHeld(ctx, inboxId, clientId, held) {
390
+ const now = ctx.ports.clock.now();
391
+ const db = await ctx.ports.db();
392
+ await db.marketplaceAcceptance.updateMany({
393
+ where: { orderId: held.orderId, clientId, status: "AWAITING", confirmedAt: null },
394
+ data: { confirmedAt: now }
395
+ });
396
+ const claim3 = await claimConfirmed(ctx, clientId, held, now);
397
+ const note = claim3.accepted ? void 0 : `accepted on the marketplace; waits for a person${claim3.refusal ? ` (${claim3.refusal.code})` : ""}`;
398
+ await settleInboxEvent(ctx, inboxId, "PROCESSED", note);
399
+ if (claim3.accepted) await tellAccepted(ctx, clientId, held.orderId);
400
+ ctx.ports.publishChanged(clientId);
401
+ return { kind: "confirmedByMarketplace", orderId: held.orderId, ...claim3 };
402
+ }
403
+ __name(confirmHeld, "confirmHeld");
404
+ async function applyMarketplaceConfirmation(ctx, inboxId, clientId, event) {
405
+ if (!event.marketplaceConfirmed || !event.externalOrderId) return null;
406
+ const db = await ctx.ports.db();
407
+ const held = await db.marketplaceAcceptance.findFirst({
408
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
409
+ select: { orderId: true, status: true, cancellationStatus: true }
410
+ });
411
+ if (!held) {
412
+ await deferInboxEvent(ctx, inboxId, CONFIRMED_BEFORE_ORDER);
413
+ return { kind: "ignored", reason: CONFIRMED_BEFORE_ORDER };
414
+ }
415
+ if (held.status === "ACCEPTED") return confirmAccepted(ctx, inboxId, clientId, held.orderId);
416
+ if (held.status !== "AWAITING") {
417
+ const reason = `the order is ${held.status}, not AWAITING`;
418
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
419
+ return { kind: "ignored", reason };
420
+ }
421
+ return confirmHeld(ctx, inboxId, clientId, held);
422
+ }
423
+ __name(applyMarketplaceConfirmation, "applyMarketplaceConfirmation");
424
+ async function confirmAccepted(ctx, inboxId, clientId, orderId) {
425
+ const db = await ctx.ports.db();
426
+ const stamped = await db.marketplaceAcceptance.updateMany({
427
+ where: { orderId, clientId, status: "ACCEPTED", confirmedAt: null },
428
+ data: { confirmedAt: ctx.ports.clock.now(), confirmFailedAt: null }
429
+ });
430
+ if (stamped.count === 0) {
431
+ const reason = "the order is ACCEPTED and its confirm already stamped";
432
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
433
+ return { kind: "ignored", reason };
434
+ }
435
+ await settleInboxEvent(ctx, inboxId, "PROCESSED", "accepted here first; the marketplace took the acceptance");
436
+ ctx.ports.publishChanged(clientId);
437
+ return { kind: "confirmedByMarketplace", orderId, accepted: true };
438
+ }
439
+ __name(confirmAccepted, "confirmAccepted");
440
+ async function applyRows(ctx, rows) {
441
+ const applied = /* @__PURE__ */ new Set();
442
+ for (const row of rows) {
443
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
444
+ if (!event?.marketplaceConfirmed) continue;
445
+ const outcome = await applyMarketplaceConfirmation(ctx, row.id, row.clientId, event);
446
+ if (outcome?.kind === "confirmedByMarketplace") applied.add(outcome.orderId);
447
+ }
448
+ return applied;
449
+ }
450
+ __name(applyRows, "applyRows");
451
+ var DEFERRED_SELECT = { id: true, clientId: true, provider: true, externalOrderId: true, payload: true };
452
+ async function applyDeferredConfirmations(ctx, input) {
453
+ if (!ctx.registry.get(input.provider)?.capabilities.marketplaceConfirms) return;
454
+ const db = await ctx.ports.db();
455
+ const rows = await db.marketplaceInboxEvent.findMany({
456
+ where: { ...input, status: "PENDING", error: CONFIRMED_BEFORE_ORDER },
457
+ select: DEFERRED_SELECT
458
+ });
459
+ await applyRows(ctx, rows);
460
+ }
461
+ __name(applyDeferredConfirmations, "applyDeferredConfirmations");
462
+ async function applyOwedConfirmations(ctx, lapsed) {
463
+ if (lapsed.length === 0) return /* @__PURE__ */ new Set();
464
+ const db = await ctx.ports.db();
465
+ const rows = await db.marketplaceInboxEvent.findMany({
466
+ where: {
467
+ status: "PENDING",
468
+ error: CONFIRMED_BEFORE_ORDER,
469
+ clientId: { not: null },
470
+ externalOrderId: { in: [...new Set(lapsed.map((row) => row.externalOrderId))] }
471
+ },
472
+ select: DEFERRED_SELECT
473
+ });
474
+ const named = new Set(lapsed.map((row) => `${row.provider}:${row.externalOrderId}`));
475
+ return applyRows(ctx, rows.filter((row) => named.has(`${row.provider}:${row.externalOrderId ?? ""}`)));
476
+ }
477
+ __name(applyOwedConfirmations, "applyOwedConfirmations");
478
+
79
479
  // src/core/merchant-claim.ts
80
480
  var MarketplaceMerchantTakenError = class extends Error {
81
481
  static {
@@ -230,7 +630,6 @@ async function forgetCategory(ctx, connection, name) {
230
630
  __name(forgetCategory, "forgetCategory");
231
631
 
232
632
  // src/core/link-store.ts
233
- var TOKEN_MARGIN_MS = 6e4;
234
633
  function sealLink(ctx, refreshToken) {
235
634
  return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
236
635
  }
@@ -317,7 +716,7 @@ function linkGrant(ctx, link) {
317
716
  key,
318
717
  accessToken: /* @__PURE__ */ __name(async () => {
319
718
  const cached = ctx.tokens.get(key);
320
- if (cached && cached.expiresAt > ctx.ports.clock.now().getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
719
+ if (cached && cached.expiresAt > ctx.ports.clock.now().getTime()) return { token: cached.token };
321
720
  let running = inflight.get(ctx.tokens);
322
721
  if (!running) {
323
722
  running = /* @__PURE__ */ new Map();
@@ -769,87 +1168,188 @@ async function runCatalogue(ctx, payload, attempt) {
769
1168
  }
770
1169
  __name(runCatalogue, "runCatalogue");
771
1170
 
772
- // src/core/inbox.ts
773
- async function recordInboxEvent(ctx, input) {
1171
+ // src/core/acknowledge.ts
1172
+ var MARKETPLACE_ACKNOWLEDGE_JOB = "marketplace.acknowledge";
1173
+ var AcknowledgeRetryError = class extends Error {
1174
+ static {
1175
+ __name(this, "AcknowledgeRetryError");
1176
+ }
1177
+ constructor(message) {
1178
+ super(message);
1179
+ this.name = "AcknowledgeRetryError";
1180
+ }
1181
+ };
1182
+ function acknowledgementOf(ctx, provider) {
1183
+ return ctx.registry.get(provider)?.acknowledgement ?? null;
1184
+ }
1185
+ __name(acknowledgementOf, "acknowledgementOf");
1186
+ var SWEEP_STORES = 500;
1187
+ function windowStart(ctx, retentionMs) {
1188
+ return new Date(ctx.ports.clock.now().getTime() - retentionMs);
1189
+ }
1190
+ __name(windowStart, "windowStart");
1191
+ async function enqueueAcknowledge(ctx, input) {
1192
+ if (!input.clientId || !input.inboxId || !acknowledgementOf(ctx, input.provider)) return;
1193
+ const payload = { clientId: input.clientId, provider: input.provider };
1194
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_ACKNOWLEDGE_JOB, payload, {
1195
+ dedupeKey: `${MARKETPLACE_ACKNOWLEDGE_JOB}:${input.inboxId}`
1196
+ });
1197
+ if (!outcome.enqueued) {
1198
+ ctx.ports.logger.warn(
1199
+ `${MARKETPLACE_ACKNOWLEDGE_JOB}: event ${input.inboxId} was not queued; the reconcile pass re-queues it` + (outcome.reason ? ` (${outcome.reason})` : "")
1200
+ );
1201
+ }
1202
+ }
1203
+ __name(enqueueAcknowledge, "enqueueAcknowledge");
1204
+ async function runAcknowledge(ctx, payload, attempt) {
1205
+ const acknowledgement = acknowledgementOf(ctx, payload.provider);
1206
+ if (!acknowledgement) return { kind: "skipped", reason: `${payload.provider} takes no acknowledgment` };
1207
+ const db = await ctx.ports.db();
1208
+ const owed = await db.marketplaceInboxEvent.findMany({
1209
+ where: {
1210
+ clientId: payload.clientId,
1211
+ provider: payload.provider,
1212
+ acknowledgedAt: null,
1213
+ receivedAt: { gte: windowStart(ctx, acknowledgement.retentionMs) }
1214
+ },
1215
+ orderBy: { receivedAt: "asc" },
1216
+ take: acknowledgement.batchSize,
1217
+ select: { id: true, eventId: true }
1218
+ });
1219
+ if (owed.length === 0) return { kind: "skipped", reason: "no event is owed an acknowledgment" };
1220
+ const connection = await readOutboundConnection(ctx, payload.clientId, payload.provider).catch(() => null);
1221
+ if (!connection) return { kind: "skipped", reason: "no credentials on file" };
1222
+ const now = ctx.ports.clock.now();
1223
+ const result = await acknowledgement.send(
1224
+ { http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
1225
+ [...new Set(owed.map((row) => row.eventId))]
1226
+ );
1227
+ return settle2(ctx, payload, owed, result, attempt);
1228
+ }
1229
+ __name(runAcknowledge, "runAcknowledge");
1230
+ async function stampSettled(ctx, owed) {
1231
+ const db = await ctx.ports.db();
1232
+ await db.marketplaceInboxEvent.updateMany({
1233
+ where: { id: { in: owed.map((row) => row.id) }, acknowledgedAt: null },
1234
+ data: { acknowledgedAt: ctx.ports.clock.now() }
1235
+ });
1236
+ }
1237
+ __name(stampSettled, "stampSettled");
1238
+ async function settle2(ctx, payload, owed, result, attempt) {
1239
+ if (result.kind === "accepted") {
1240
+ await stampSettled(ctx, owed);
1241
+ return { kind: "done", acknowledged: owed.length };
1242
+ }
1243
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1244
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1245
+ throw new AcknowledgeRetryError(`${payload.provider} events of ${payload.clientId}: ${reason}`);
1246
+ }
1247
+ if (result.kind === "refused" && !result.own) {
1248
+ await stampSettled(ctx, owed);
1249
+ ctx.ports.logger.error(`${MARKETPLACE_ACKNOWLEDGE_JOB}: ${payload.provider} refused ${owed.length} event(s) of ${payload.clientId}; given up: ${reason}`);
1250
+ return { kind: "failed", reason };
1251
+ }
1252
+ ctx.ports.logger.error(`${MARKETPLACE_ACKNOWLEDGE_JOB}: ${payload.provider} events of ${payload.clientId} not acknowledged: ${reason}`);
1253
+ return { kind: "failed", reason };
1254
+ }
1255
+ __name(settle2, "settle");
1256
+ async function sweepAcknowledgements(ctx) {
774
1257
  const db = await ctx.ports.db();
775
- const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
776
- const existing = await db.marketplaceInboxEvent.findUnique({
777
- where: key,
778
- select: { id: true }
779
- });
780
- if (existing) return { id: existing.id, fresh: false };
781
- try {
782
- const row = await db.marketplaceInboxEvent.create({
783
- data: {
784
- clientId: input.clientId,
785
- provider: input.event.provider,
786
- eventId: input.event.eventId,
787
- eventType: input.event.eventType,
788
- externalOrderId: input.event.externalOrderId,
789
- payload: input.payload,
790
- // The engine's clock, not the database's: an announced order's
791
- // acceptance window counts from here (`./fetch-order.ts`).
792
- receivedAt: ctx.ports.clock.now()
793
- },
794
- select: { id: true }
1258
+ let requeued = 0;
1259
+ for (const provider of ctx.registry.providers()) {
1260
+ const acknowledgement = acknowledgementOf(ctx, provider);
1261
+ if (!acknowledgement) continue;
1262
+ const rows = await db.marketplaceInboxEvent.findMany({
1263
+ where: { provider, acknowledgedAt: null, clientId: { not: null }, receivedAt: { gte: windowStart(ctx, acknowledgement.retentionMs) } },
1264
+ // One row per store, bounded: the next pass takes the rest.
1265
+ distinct: ["clientId"],
1266
+ take: SWEEP_STORES,
1267
+ select: { clientId: true }
795
1268
  });
796
- return { id: row.id, fresh: true };
797
- } catch (error) {
798
- if (error.code !== "P2002") throw error;
799
- const raced = await db.marketplaceInboxEvent.findUnique({
800
- where: key,
801
- select: { id: true }
1269
+ requeued += await requeueStores(ctx, provider, new Set(rows.map((row) => row.clientId)));
1270
+ }
1271
+ return { requeued };
1272
+ }
1273
+ __name(sweepAcknowledgements, "sweepAcknowledgements");
1274
+ async function requeueStores(ctx, provider, clientIds) {
1275
+ const at = ctx.ports.clock.now().getTime();
1276
+ let queued = 0;
1277
+ for (const clientId of clientIds) {
1278
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_ACKNOWLEDGE_JOB, { clientId, provider }, {
1279
+ dedupeKey: `${MARKETPLACE_ACKNOWLEDGE_JOB}:sweep:${provider}:${clientId}:${at}`
802
1280
  });
803
- return { id: raced?.id ?? "", fresh: false };
1281
+ if (outcome.enqueued) queued += 1;
804
1282
  }
1283
+ return queued;
805
1284
  }
806
- __name(recordInboxEvent, "recordInboxEvent");
807
- async function settleInboxEvent(ctx, id, outcome, error) {
808
- if (!id) return;
809
- const db = await ctx.ports.db();
810
- await db.marketplaceInboxEvent.update({
811
- where: { id },
812
- data: {
813
- status: outcome,
814
- // Truncated: a provider's error body can be a page of HTML, and the
815
- // column exists to be read by a human in a list.
816
- error: error ? error.slice(0, 500) : null,
817
- processedAt: ctx.ports.clock.now(),
818
- attempts: { increment: 1 }
819
- }
1285
+ __name(requeueStores, "requeueStores");
1286
+
1287
+ // src/core/order-reasons.ts
1288
+ var MARKETPLACE_CANCELLATION_REASONS_JOB = "marketplace.cancellation-reasons";
1289
+ var CancellationReasonsRetryError = class extends Error {
1290
+ static {
1291
+ __name(this, "CancellationReasonsRetryError");
1292
+ }
1293
+ constructor(message) {
1294
+ super(message);
1295
+ this.name = "CancellationReasonsRetryError";
1296
+ }
1297
+ };
1298
+ async function enqueueOrderReasons(ctx, input) {
1299
+ if (!ctx.registry.get(input.provider)?.orderCancellationReasons) return;
1300
+ const payload = { clientId: input.clientId, orderId: input.orderId };
1301
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
1302
+ dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`
820
1303
  });
1304
+ if (!outcome.enqueued) {
1305
+ ctx.ports.logger.warn(
1306
+ `${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${input.orderId} was not queued; its reasons stay the static list` + (outcome.reason ? ` (${outcome.reason})` : "")
1307
+ );
1308
+ }
821
1309
  }
822
- __name(settleInboxEvent, "settleInboxEvent");
823
- async function deferInboxEvent(ctx, id, reason) {
824
- if (!id) return;
1310
+ __name(enqueueOrderReasons, "enqueueOrderReasons");
1311
+ async function keep(ctx, db, clientId, orderId, reasons) {
1312
+ if (reasons.length === 0) {
1313
+ ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${orderId} got an empty list; it keeps the static reasons`);
1314
+ return { kind: "skipped", reason: "the marketplace listed no reason" };
1315
+ }
1316
+ await db.marketplaceAcceptance.updateMany({ where: { orderId }, data: { cancellationReasons: reasons } });
1317
+ ctx.ports.publishChanged(clientId);
1318
+ return { kind: "done", count: reasons.length };
1319
+ }
1320
+ __name(keep, "keep");
1321
+ async function runCancellationReasons(ctx, payload, attempt) {
825
1322
  const db = await ctx.ports.db();
826
- await db.marketplaceInboxEvent.update({
827
- where: { id },
828
- data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
1323
+ const row = await db.marketplaceAcceptance.findFirst({
1324
+ where: { orderId: payload.orderId, clientId: payload.clientId },
1325
+ select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true }
829
1326
  });
1327
+ if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
1328
+ if (storedReasons(row.cancellationReasons) !== null) return { kind: "skipped", reason: "the order's reasons are already kept" };
1329
+ const read = ctx.registry.get(row.provider)?.orderCancellationReasons;
1330
+ if (!read) return { kind: "skipped", reason: `${row.provider} lists no reasons per order` };
1331
+ const connection = await readOutboundConnection(ctx, payload.clientId, row.provider).catch(() => null);
1332
+ if (!connection) return { kind: "skipped", reason: "no credentials on file" };
1333
+ const result = await read({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, row);
1334
+ if (result.kind === "reasons") return keep(ctx, db, payload.clientId, row.orderId, result.reasons);
1335
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1336
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1337
+ throw new CancellationReasonsRetryError(`reasons of order ${row.orderId}: ${reason}`);
1338
+ }
1339
+ ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${row.orderId} keeps the static reasons: ${reason}`);
1340
+ return { kind: "failed", reason };
830
1341
  }
831
- __name(deferInboxEvent, "deferInboxEvent");
832
- async function listRetryableInboxEvents(ctx) {
1342
+ __name(runCancellationReasons, "runCancellationReasons");
1343
+ async function readOrderReasons(ctx, clientId, orderId) {
833
1344
  const db = await ctx.ports.db();
834
- const rows = await db.marketplaceInboxEvent.findMany({
835
- where: {
836
- status: { in: ["PENDING", "FAILED"] },
837
- clientId: { not: null },
838
- attempts: { lt: ctx.ports.maxInboxAttempts }
839
- },
840
- orderBy: { receivedAt: "asc" },
841
- take: ctx.ports.reconcileBatchSize,
842
- select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
1345
+ const row = await db.marketplaceAcceptance.findFirst({
1346
+ where: { orderId, clientId },
1347
+ select: { provider: true, cancellationReasons: true }
843
1348
  });
844
- return rows.map((row) => ({
845
- id: row.id,
846
- clientId: row.clientId,
847
- provider: row.provider,
848
- payload: row.payload,
849
- receivedAt: row.receivedAt
850
- }));
1349
+ const adapter = row ? ctx.registry.get(row.provider) : null;
1350
+ return adapter ? reasonsForOrder(adapter, row?.cancellationReasons) : [];
851
1351
  }
852
- __name(listRetryableInboxEvents, "listRetryableInboxEvents");
1352
+ __name(readOrderReasons, "readOrderReasons");
853
1353
 
854
1354
  // src/core/menu-links.ts
855
1355
  var LINK_SELECT = {
@@ -1028,6 +1528,8 @@ async function ingestMarketplaceOrder(ctx, input) {
1028
1528
  await ctx.ports.order.onAccepted(clientId, orderId);
1029
1529
  }
1030
1530
  ctx.ports.publishChanged(clientId);
1531
+ await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider });
1532
+ if (!accepted) await applyDeferredConfirmations(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId });
1031
1533
  return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
1032
1534
  }
1033
1535
  __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
@@ -1058,158 +1560,6 @@ async function stampConnection(ctx, input, where, data) {
1058
1560
  }
1059
1561
  __name(stampConnection, "stampConnection");
1060
1562
 
1061
- // src/core/cancellation-outcome.ts
1062
- async function tell(ctx, what, orderId, call2) {
1063
- try {
1064
- await call2();
1065
- } catch (error) {
1066
- ctx.ports.logger.error(
1067
- `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
1068
- );
1069
- }
1070
- }
1071
- __name(tell, "tell");
1072
- function requestsFirst(ctx) {
1073
- return ctx.ports.order.onCancellationConfirmed !== void 0;
1074
- }
1075
- __name(requestsFirst, "requestsFirst");
1076
- async function rejectConfirmed(db, orderId, now) {
1077
- await db.marketplaceAcceptance.updateMany({
1078
- where: { orderId, status: "AWAITING" },
1079
- data: { status: "REJECTED", acknowledgedAt: now }
1080
- });
1081
- await db.marketplaceAcceptance.updateMany({
1082
- where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
1083
- data: { status: "REJECTED" }
1084
- });
1085
- }
1086
- __name(rejectConfirmed, "rejectConfirmed");
1087
- async function confirmedToHost(ctx, clientId, orderId) {
1088
- if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
1089
- await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
1090
- }
1091
- __name(confirmedToHost, "confirmedToHost");
1092
- async function tellCancellationConfirmed(ctx, clientId, orderId) {
1093
- const hook = ctx.ports.order.onCancellationConfirmed;
1094
- if (!hook) return false;
1095
- await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
1096
- return true;
1097
- }
1098
- __name(tellCancellationConfirmed, "tellCancellationConfirmed");
1099
- async function tellCancellationFailed(ctx, clientId, orderId, reason) {
1100
- const hook = ctx.ports.order.onCancellationFailed;
1101
- if (!hook) return;
1102
- await tell(
1103
- ctx,
1104
- `had its cancellation request fail (${reason})`,
1105
- orderId,
1106
- () => hook.call(ctx.ports.order, clientId, orderId, reason)
1107
- );
1108
- }
1109
- __name(tellCancellationFailed, "tellCancellationFailed");
1110
- function cancellationWindowMs(ctx, adapter) {
1111
- return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
1112
- }
1113
- __name(cancellationWindowMs, "cancellationWindowMs");
1114
- function failedRequestData(reason) {
1115
- return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
1116
- }
1117
- __name(failedRequestData, "failedRequestData");
1118
-
1119
- // src/core/cancellation.ts
1120
- function noStandingRequest(cancellationStatus) {
1121
- return cancellationStatus === null || cancellationStatus === "FAILED";
1122
- }
1123
- __name(noStandingRequest, "noStandingRequest");
1124
- var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
1125
- var CLAIM_SELECT = {
1126
- orderId: true,
1127
- provider: true,
1128
- status: true,
1129
- cancellationStatus: true,
1130
- lineSkus: true
1131
- };
1132
- function notPendingProblem(row, path, allowed = ["AWAITING"]) {
1133
- if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
1134
- if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
1135
- const status = row.status;
1136
- return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
1137
- }
1138
- __name(notPendingProblem, "notPendingProblem");
1139
- function lineSkusOf(row) {
1140
- return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
1141
- }
1142
- __name(lineSkusOf, "lineSkusOf");
1143
- function skuProblems(reason, skus, row, path) {
1144
- if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
1145
- const known = lineSkusOf(row);
1146
- if (!known) return [];
1147
- return skus.flatMap(
1148
- (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
1149
- );
1150
- }
1151
- __name(skuProblems, "skuProblems");
1152
- function invalidReasonProblem(adapter, reason, code, path) {
1153
- if (code === null || code === void 0 || reason) return null;
1154
- const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
1155
- return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
1156
- }
1157
- __name(invalidReasonProblem, "invalidReasonProblem");
1158
- function planCancellation(adapter, input, row, path) {
1159
- if (!adapter) return { status: null, reason: null, skus: [] };
1160
- const reason = resolveReason(adapter, input.reasonCode);
1161
- const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
1162
- if (invalid) return [invalid];
1163
- const skus = [...new Set(input.offendingSkus ?? [])];
1164
- const problems = skuProblems(reason, skus, row, path);
1165
- if (problems.length > 0) return problems;
1166
- const { apiCancel, cancelAfterAccept } = adapter.capabilities;
1167
- const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
1168
- return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
1169
- }
1170
- __name(planCancellation, "planCancellation");
1171
- function refusalData(plan, fromStatus, now) {
1172
- return {
1173
- status: "REJECTED",
1174
- // An accepted row keeps the instant it was accepted; a row leaving the
1175
- // clock is acknowledged now (the table's CHECK pairs the two).
1176
- ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
1177
- cancellationStatus: plan.status,
1178
- cancellationReasonCode: plan.reason?.code ?? null,
1179
- cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
1180
- cancellationRequestedAt: plan.status === "PENDING" ? now : null,
1181
- // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
1182
- cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
1183
- };
1184
- }
1185
- __name(refusalData, "refusalData");
1186
- function requestData(plan, now) {
1187
- return {
1188
- cancellationStatus: plan.status,
1189
- cancellationReasonCode: plan.reason?.code ?? null,
1190
- cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
1191
- cancellationRequestedAt: plan.status === "PENDING" ? now : null,
1192
- // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
1193
- cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
1194
- };
1195
- }
1196
- __name(requestData, "requestData");
1197
- async function failCancellationRequest(ctx, input) {
1198
- const db = await ctx.ports.db();
1199
- const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
1200
- const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
1201
- if (!row) return false;
1202
- const moved = await db.marketplaceAcceptance.updateMany({
1203
- where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
1204
- data: failedRequestData("REFUSED")
1205
- });
1206
- if (moved.count === 0) return false;
1207
- ctx.ports.publishChanged(input.clientId);
1208
- await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
1209
- return true;
1210
- }
1211
- __name(failCancellationRequest, "failCancellationRequest");
1212
-
1213
1563
  // src/core/acceptance.ts
1214
1564
  async function listPendingAcceptances(ctx, clientId, orderIds) {
1215
1565
  const db = await ctx.ports.db();
@@ -1250,15 +1600,19 @@ async function expireLapsedAcceptances(ctx, now) {
1250
1600
  // An order whose cancellation request waits is left to that request: its
1251
1601
  // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
1252
1602
  // never hears EXPIRED and then the confirmation for one order.
1253
- where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
1254
- select: { id: true, clientId: true, orderId: true }
1603
+ // An order the marketplace confirmed (`confirmed_at`, FUT-5653: accepted in its own app) is never expired.
1604
+ where: { status: "AWAITING", confirmedAt: null, acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
1605
+ select: { id: true, clientId: true, orderId: true, provider: true, externalOrderId: true }
1255
1606
  });
1256
1607
  if (lapsed.length === 0) return { expired: 0, tenants: 0 };
1608
+ const confirmed = await applyOwedConfirmations(ctx, lapsed);
1609
+ const expiring = lapsed.filter((row) => !confirmed.has(row.orderId));
1610
+ if (expiring.length === 0) return { expired: 0, tenants: 0 };
1257
1611
  const result = await db.marketplaceAcceptance.updateMany({
1258
- where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
1612
+ where: { id: { in: expiring.map((row) => row.id) }, status: "AWAITING", confirmedAt: null, ...NO_STANDING_REQUEST },
1259
1613
  data: { status: "EXPIRED", acknowledgedAt: now }
1260
1614
  });
1261
- for (const row of lapsed) {
1615
+ for (const row of expiring) {
1262
1616
  try {
1263
1617
  await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
1264
1618
  } catch (error) {
@@ -1267,7 +1621,7 @@ async function expireLapsedAcceptances(ctx, now) {
1267
1621
  );
1268
1622
  }
1269
1623
  }
1270
- const tenants = new Set(lapsed.map((row) => row.clientId));
1624
+ const tenants = new Set(expiring.map((row) => row.clientId));
1271
1625
  for (const clientId of tenants) ctx.ports.publishChanged(clientId);
1272
1626
  return { expired: result.count, tenants: tenants.size };
1273
1627
  }
@@ -1741,6 +2095,15 @@ function acceptanceSkip(row) {
1741
2095
  return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
1742
2096
  }
1743
2097
  __name(acceptanceSkip, "acceptanceSkip");
2098
+ function confirmSkip(row, adapter, deps) {
2099
+ if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
2100
+ if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
2101
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) {
2102
+ throw deps.retryError(`status for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
2103
+ }
2104
+ return "the store's confirm has not reached the marketplace";
2105
+ }
2106
+ __name(confirmSkip, "confirmSkip");
1744
2107
  async function adapterAndHostSkip(ctx, payload, step, row, adapter) {
1745
2108
  const takes = adapter.informStatus !== void 0 && adapter.capabilities.statusSteps?.includes(step) === true && adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
1746
2109
  if (!takes) return `the marketplace does not take ${step} for this order`;
@@ -1765,7 +2128,7 @@ function callAdapter(ctx, connection, adapter, row, step, ref) {
1765
2128
  });
1766
2129
  }
1767
2130
  __name(callAdapter, "callAdapter");
1768
- async function settle2(ctx, db, where, result, deps) {
2131
+ async function settle3(ctx, db, where, result, deps) {
1769
2132
  const table = statusTable(db);
1770
2133
  if (result.kind === "accepted") {
1771
2134
  await settleStatusRow(table, where, "SENT");
@@ -1779,7 +2142,7 @@ async function settle2(ctx, db, where, result, deps) {
1779
2142
  ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
1780
2143
  return { kind: "failed", action: "status", reason };
1781
2144
  }
1782
- __name(settle2, "settle");
2145
+ __name(settle3, "settle");
1783
2146
  function ownsClaim(found, key) {
1784
2147
  return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
1785
2148
  }
@@ -1806,7 +2169,7 @@ __name(claim2, "claim");
1806
2169
  async function runStatus(ctx, payload, row, adapter, deps) {
1807
2170
  const step = payload.step;
1808
2171
  if (!step) return skipped("a status call names no step");
1809
- const stopped = acceptanceSkip(row) ?? await adapterAndHostSkip(ctx, payload, step, row, adapter);
2172
+ const stopped = acceptanceSkip(row) ?? confirmSkip(row, adapter, deps) ?? await adapterAndHostSkip(ctx, payload, step, row, adapter);
1810
2173
  if (stopped) return skipped(stopped);
1811
2174
  const db = await ctx.ports.db();
1812
2175
  const table = statusTable(db);
@@ -1819,10 +2182,39 @@ async function runStatus(ctx, payload, row, adapter, deps) {
1819
2182
  const key = payload.claimKey ?? "";
1820
2183
  const unclaimed = await claim2(table, payload, row, step, key);
1821
2184
  if (unclaimed) return skipped(unclaimed);
2185
+ const before = await sendPrerequisite(ctx, { table, payload, row, step, key, connection, adapter }, deps);
2186
+ if (before) return before;
1822
2187
  const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
1823
- return settle2(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
2188
+ return settle3(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
1824
2189
  }
1825
2190
  __name(runStatus, "runStatus");
2191
+ function prerequisiteState(found, key, run, first, deps) {
2192
+ if (!found || ownsClaim(found, key)) return "send";
2193
+ if (found.state !== "SENDING") return "proceed";
2194
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) {
2195
+ throw deps.retryError(`status ${run.step} for order ${run.row.orderId}: waiting for ${first}, held by another run`);
2196
+ }
2197
+ return skipped(`${first} is still being sent by another run`);
2198
+ }
2199
+ __name(prerequisiteState, "prerequisiteState");
2200
+ async function sendPrerequisite(ctx, run, deps) {
2201
+ const first = run.adapter.statusPrerequisite?.({ step: run.step, deliveredBy: deliveredByOf(run.row) }) ?? null;
2202
+ if (first === null) return null;
2203
+ const key = `${run.key}:${first}`;
2204
+ const [found] = await readStatusRows(run.table, run.row.orderId, [first]);
2205
+ const state = prerequisiteState(found, key, run, first, deps);
2206
+ if (state === "proceed") return null;
2207
+ if (typeof state !== "string") return state;
2208
+ if (!found) {
2209
+ const row = { clientId: run.payload.clientId, orderId: run.row.orderId, provider: run.row.provider };
2210
+ const claimed = await insertStatusRow(run.table, { ...row, step: first, source: "STORE", state: "SENDING", claimKey: key });
2211
+ if (!claimed) return sendPrerequisite(ctx, run, deps);
2212
+ }
2213
+ const result = await callAdapter(ctx, run.connection, run.adapter, run.row, first, deps.ref);
2214
+ const outcome = await settle3(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
2215
+ return outcome.kind === "skipped" ? outcome : null;
2216
+ }
2217
+ __name(sendPrerequisite, "sendPrerequisite");
1826
2218
  async function failStatusRow(ctx, payload) {
1827
2219
  const table = statusTable(await ctx.ports.db());
1828
2220
  if (table && payload.step) {
@@ -1855,6 +2247,7 @@ var ROW_SELECT = {
1855
2247
  cancellationOffendingSkus: true,
1856
2248
  cancellationRequestedAt: true,
1857
2249
  preparationMinutes: true,
2250
+ cancellationReasons: true,
1858
2251
  createdAt: true
1859
2252
  };
1860
2253
  function refOf(row) {
@@ -1866,7 +2259,7 @@ function refOf(row) {
1866
2259
  };
1867
2260
  }
1868
2261
  __name(refOf, "refOf");
1869
- function confirmSkip(row, adapter) {
2262
+ function confirmSkip2(row, adapter) {
1870
2263
  if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
1871
2264
  if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
1872
2265
  return `a cancellation request is ${row.cancellationStatus}`;
@@ -1875,7 +2268,7 @@ function confirmSkip(row, adapter) {
1875
2268
  if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
1876
2269
  return null;
1877
2270
  }
1878
- __name(confirmSkip, "confirmSkip");
2271
+ __name(confirmSkip2, "confirmSkip");
1879
2272
  async function stampConfirm(ctx, row, succeeded, now) {
1880
2273
  const db = await ctx.ports.db();
1881
2274
  await db.marketplaceAcceptance.updateMany({
@@ -1931,7 +2324,7 @@ async function connectionFor(ctx, clientId, provider) {
1931
2324
  }
1932
2325
  }
1933
2326
  __name(connectionFor, "connectionFor");
1934
- async function settle3(ctx, payload, row, result, attempt, succeed, fail3) {
2327
+ async function settle4(ctx, payload, row, result, attempt, succeed, fail3) {
1935
2328
  if (result.kind === "accepted") {
1936
2329
  await succeed();
1937
2330
  ctx.ports.publishChanged(payload.clientId);
@@ -1946,9 +2339,9 @@ async function settle3(ctx, payload, row, result, attempt, succeed, fail3) {
1946
2339
  ctx.ports.publishChanged(payload.clientId);
1947
2340
  return { kind: "failed", action: payload.action, reason };
1948
2341
  }
1949
- __name(settle3, "settle");
2342
+ __name(settle4, "settle");
1950
2343
  async function runConfirm(ctx, payload, row, adapter, attempt) {
1951
- const skip = confirmSkip(row, adapter);
2344
+ const skip = confirmSkip2(row, adapter);
1952
2345
  if (skip) return { kind: "skipped", reason: skip };
1953
2346
  const now = ctx.ports.clock.now();
1954
2347
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
@@ -1958,7 +2351,7 @@ async function runConfirm(ctx, payload, row, adapter, attempt) {
1958
2351
  // The stated preparation time, for a marketplace whose confirm takes one.
1959
2352
  { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
1960
2353
  );
1961
- return settle3(
2354
+ return settle4(
1962
2355
  ctx,
1963
2356
  payload,
1964
2357
  row,
@@ -1988,7 +2381,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1988
2381
  await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
1989
2382
  return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
1990
2383
  }
1991
- const reason = resolveReason(adapter, row.cancellationReasonCode);
2384
+ const reason = resolveReason(adapter, row.cancellationReasonCode, row.cancellationReasons) ?? resolveReason(adapter, row.cancellationReasonCode);
1992
2385
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
1993
2386
  let result;
1994
2387
  if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's", own: true };
@@ -2001,7 +2394,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
2001
2394
  );
2002
2395
  }
2003
2396
  const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
2004
- return settle3(
2397
+ return settle4(
2005
2398
  ctx,
2006
2399
  payload,
2007
2400
  row,
@@ -2448,6 +2841,8 @@ export {
2448
2841
  PROVIDER_ID_PATTERN,
2449
2842
  MarketplaceAdapterRegistrationError,
2450
2843
  createAdapterRegistry,
2844
+ storedReasons,
2845
+ reasonsForOrder,
2451
2846
  resolveReason,
2452
2847
  suggestReason,
2453
2848
  NO_STANDING_REQUEST,
@@ -2457,6 +2852,12 @@ export {
2457
2852
  refusalData,
2458
2853
  requestData,
2459
2854
  failCancellationRequest,
2855
+ recordInboxEvent,
2856
+ settleInboxEvent,
2857
+ deferInboxEvent,
2858
+ listRetryableInboxEvents,
2859
+ CONFIRMED_BEFORE_ORDER,
2860
+ applyMarketplaceConfirmation,
2460
2861
  listPendingAcceptances,
2461
2862
  expireLapsedAcceptances,
2462
2863
  cancelAcceptance,
@@ -2490,14 +2891,19 @@ export {
2490
2891
  catalogueDedupeKey,
2491
2892
  enqueueCatalogue,
2492
2893
  runCatalogue,
2493
- recordInboxEvent,
2494
- settleInboxEvent,
2495
- deferInboxEvent,
2496
- listRetryableInboxEvents,
2497
2894
  statusTable,
2498
2895
  readStatusRows,
2499
2896
  noteMarketplaceStep,
2500
2897
  validatePickupCode,
2898
+ MARKETPLACE_ACKNOWLEDGE_JOB,
2899
+ AcknowledgeRetryError,
2900
+ enqueueAcknowledge,
2901
+ runAcknowledge,
2902
+ sweepAcknowledgements,
2903
+ MARKETPLACE_CANCELLATION_REASONS_JOB,
2904
+ CancellationReasonsRetryError,
2905
+ runCancellationReasons,
2906
+ readOrderReasons,
2501
2907
  ingestMarketplaceOrder,
2502
2908
  CANCELLED_BEFORE_INGEST_REASON,
2503
2909
  markCancelledBeforeIngest,
@@ -2526,4 +2932,4 @@ export {
2526
2932
  AvailabilityRetryError,
2527
2933
  runAvailability
2528
2934
  };
2529
- //# sourceMappingURL=chunk-CEWTV2TC.js.map
2935
+ //# sourceMappingURL=chunk-MDXSVE7Q.js.map