@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
@@ -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();
@@ -484,21 +883,26 @@ async function markMarketplaceEventSeen(db, clientId, provider, at) {
484
883
  }
485
884
  __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
486
885
  async function readOutboundConnection(ctx, clientId, provider) {
886
+ return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
887
+ }
888
+ __name(readOutboundConnection, "readOutboundConnection");
889
+ async function readSealedOutboundConnection(ctx, clientId, provider) {
487
890
  const db = await ctx.ports.db();
488
891
  const row = await db.marketplaceIntegration.findUnique({
489
892
  where: { clientId_provider: { clientId, provider } },
490
893
  select: { environment: true, credentials: true, authMode: true }
491
894
  });
492
895
  if (!row || row.credentials === "") return null;
896
+ const sealed = row.credentials;
493
897
  const environment = environmentOf(row.environment);
494
- if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
898
+ if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
495
899
  const app = await appCredentialsOf(ctx, provider, environment);
496
900
  if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
497
- const refreshToken = openLinkRefreshToken(ctx, row.credentials);
498
- const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
499
- return { environment, credentials: app, grant: linkGrant(ctx, link) };
901
+ const refreshToken = openLinkRefreshToken(ctx, sealed);
902
+ const link = { clientId, provider, environment, refreshToken, app, sealed };
903
+ return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
500
904
  }
501
- __name(readOutboundConnection, "readOutboundConnection");
905
+ __name(readSealedOutboundConnection, "readSealedOutboundConnection");
502
906
 
503
907
  // src/core/catalogue-store.ts
504
908
  var CATALOGUE_ROW_SELECT = {
@@ -764,87 +1168,188 @@ async function runCatalogue(ctx, payload, attempt) {
764
1168
  }
765
1169
  __name(runCatalogue, "runCatalogue");
766
1170
 
767
- // src/core/inbox.ts
768
- async function recordInboxEvent(ctx, input) {
769
- const db = await ctx.ports.db();
770
- const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
771
- const existing = await db.marketplaceInboxEvent.findUnique({
772
- where: key,
773
- select: { id: true }
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}`
774
1196
  });
775
- if (existing) return { id: existing.id, fresh: false };
776
- try {
777
- const row = await db.marketplaceInboxEvent.create({
778
- data: {
779
- clientId: input.clientId,
780
- provider: input.event.provider,
781
- eventId: input.event.eventId,
782
- eventType: input.event.eventType,
783
- externalOrderId: input.event.externalOrderId,
784
- payload: input.payload,
785
- // The engine's clock, not the database's: an announced order's
786
- // acceptance window counts from here (`./fetch-order.ts`).
787
- receivedAt: ctx.ports.clock.now()
788
- },
789
- select: { id: true }
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) {
1257
+ const db = await ctx.ports.db();
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 }
790
1268
  });
791
- return { id: row.id, fresh: true };
792
- } catch (error) {
793
- if (error.code !== "P2002") throw error;
794
- const raced = await db.marketplaceInboxEvent.findUnique({
795
- where: key,
796
- 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}`
797
1280
  });
798
- return { id: raced?.id ?? "", fresh: false };
1281
+ if (outcome.enqueued) queued += 1;
799
1282
  }
1283
+ return queued;
800
1284
  }
801
- __name(recordInboxEvent, "recordInboxEvent");
802
- async function settleInboxEvent(ctx, id, outcome, error) {
803
- if (!id) return;
804
- const db = await ctx.ports.db();
805
- await db.marketplaceInboxEvent.update({
806
- where: { id },
807
- data: {
808
- status: outcome,
809
- // Truncated: a provider's error body can be a page of HTML, and the
810
- // column exists to be read by a human in a list.
811
- error: error ? error.slice(0, 500) : null,
812
- processedAt: ctx.ports.clock.now(),
813
- attempts: { increment: 1 }
814
- }
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}`
815
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
+ }
816
1309
  }
817
- __name(settleInboxEvent, "settleInboxEvent");
818
- async function deferInboxEvent(ctx, id, reason) {
819
- 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) {
820
1322
  const db = await ctx.ports.db();
821
- await db.marketplaceInboxEvent.update({
822
- where: { id },
823
- 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 }
824
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 };
825
1341
  }
826
- __name(deferInboxEvent, "deferInboxEvent");
827
- async function listRetryableInboxEvents(ctx) {
1342
+ __name(runCancellationReasons, "runCancellationReasons");
1343
+ async function readOrderReasons(ctx, clientId, orderId) {
828
1344
  const db = await ctx.ports.db();
829
- const rows = await db.marketplaceInboxEvent.findMany({
830
- where: {
831
- status: { in: ["PENDING", "FAILED"] },
832
- clientId: { not: null },
833
- attempts: { lt: ctx.ports.maxInboxAttempts }
834
- },
835
- orderBy: { receivedAt: "asc" },
836
- take: ctx.ports.reconcileBatchSize,
837
- 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 }
838
1348
  });
839
- return rows.map((row) => ({
840
- id: row.id,
841
- clientId: row.clientId,
842
- provider: row.provider,
843
- payload: row.payload,
844
- receivedAt: row.receivedAt
845
- }));
1349
+ const adapter = row ? ctx.registry.get(row.provider) : null;
1350
+ return adapter ? reasonsForOrder(adapter, row?.cancellationReasons) : [];
846
1351
  }
847
- __name(listRetryableInboxEvents, "listRetryableInboxEvents");
1352
+ __name(readOrderReasons, "readOrderReasons");
848
1353
 
849
1354
  // src/core/menu-links.ts
850
1355
  var LINK_SELECT = {
@@ -1023,161 +1528,37 @@ async function ingestMarketplaceOrder(ctx, input) {
1023
1528
  await ctx.ports.order.onAccepted(clientId, orderId);
1024
1529
  }
1025
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 });
1026
1533
  return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
1027
1534
  }
1028
1535
  __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
1029
1536
 
1030
- // src/core/cancellation-outcome.ts
1031
- async function tell(ctx, what, orderId, call2) {
1537
+ // src/core/connection-stamp.ts
1538
+ async function markCredentialsRefused(ctx, input) {
1539
+ await stampConnection(ctx, input, { archivedAt: null }, { status: "FAILED" });
1540
+ }
1541
+ __name(markCredentialsRefused, "markCredentialsRefused");
1542
+ async function markCredentialsAccepted(ctx, input) {
1543
+ await stampConnection(ctx, input, { status: "FAILED" }, { status: "VERIFIED", lastVerifiedAt: ctx.ports.clock.now() });
1544
+ }
1545
+ __name(markCredentialsAccepted, "markCredentialsAccepted");
1546
+ async function stampConnection(ctx, input, where, data) {
1547
+ const { clientId, provider, sealed } = input;
1032
1548
  try {
1033
- await call2();
1549
+ const db = await ctx.ports.db();
1550
+ const { count } = await db.marketplaceIntegration.updateMany({
1551
+ where: { clientId, provider, credentials: sealed, ...where },
1552
+ data
1553
+ });
1554
+ if (count > 0) ctx.ports.publishChanged(clientId);
1034
1555
  } catch (error) {
1035
1556
  ctx.ports.logger.error(
1036
- `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
1557
+ `marketplace: ${provider} connection of ${clientId} not stamped ${String(data.status)}: ` + (error instanceof Error ? error.message : String(error))
1037
1558
  );
1038
1559
  }
1039
1560
  }
1040
- __name(tell, "tell");
1041
- function requestsFirst(ctx) {
1042
- return ctx.ports.order.onCancellationConfirmed !== void 0;
1043
- }
1044
- __name(requestsFirst, "requestsFirst");
1045
- async function rejectConfirmed(db, orderId, now) {
1046
- await db.marketplaceAcceptance.updateMany({
1047
- where: { orderId, status: "AWAITING" },
1048
- data: { status: "REJECTED", acknowledgedAt: now }
1049
- });
1050
- await db.marketplaceAcceptance.updateMany({
1051
- where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
1052
- data: { status: "REJECTED" }
1053
- });
1054
- }
1055
- __name(rejectConfirmed, "rejectConfirmed");
1056
- async function confirmedToHost(ctx, clientId, orderId) {
1057
- if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
1058
- await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
1059
- }
1060
- __name(confirmedToHost, "confirmedToHost");
1061
- async function tellCancellationConfirmed(ctx, clientId, orderId) {
1062
- const hook = ctx.ports.order.onCancellationConfirmed;
1063
- if (!hook) return false;
1064
- await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
1065
- return true;
1066
- }
1067
- __name(tellCancellationConfirmed, "tellCancellationConfirmed");
1068
- async function tellCancellationFailed(ctx, clientId, orderId, reason) {
1069
- const hook = ctx.ports.order.onCancellationFailed;
1070
- if (!hook) return;
1071
- await tell(
1072
- ctx,
1073
- `had its cancellation request fail (${reason})`,
1074
- orderId,
1075
- () => hook.call(ctx.ports.order, clientId, orderId, reason)
1076
- );
1077
- }
1078
- __name(tellCancellationFailed, "tellCancellationFailed");
1079
- function cancellationWindowMs(ctx, adapter) {
1080
- return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
1081
- }
1082
- __name(cancellationWindowMs, "cancellationWindowMs");
1083
- function failedRequestData(reason) {
1084
- return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
1085
- }
1086
- __name(failedRequestData, "failedRequestData");
1087
-
1088
- // src/core/cancellation.ts
1089
- function noStandingRequest(cancellationStatus) {
1090
- return cancellationStatus === null || cancellationStatus === "FAILED";
1091
- }
1092
- __name(noStandingRequest, "noStandingRequest");
1093
- var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
1094
- var CLAIM_SELECT = {
1095
- orderId: true,
1096
- provider: true,
1097
- status: true,
1098
- cancellationStatus: true,
1099
- lineSkus: true
1100
- };
1101
- function notPendingProblem(row, path, allowed = ["AWAITING"]) {
1102
- if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
1103
- if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
1104
- const status = row.status;
1105
- return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
1106
- }
1107
- __name(notPendingProblem, "notPendingProblem");
1108
- function lineSkusOf(row) {
1109
- return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
1110
- }
1111
- __name(lineSkusOf, "lineSkusOf");
1112
- function skuProblems(reason, skus, row, path) {
1113
- if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
1114
- const known = lineSkusOf(row);
1115
- if (!known) return [];
1116
- return skus.flatMap(
1117
- (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
1118
- );
1119
- }
1120
- __name(skuProblems, "skuProblems");
1121
- function invalidReasonProblem(adapter, reason, code, path) {
1122
- if (code === null || code === void 0 || reason) return null;
1123
- const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
1124
- return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
1125
- }
1126
- __name(invalidReasonProblem, "invalidReasonProblem");
1127
- function planCancellation(adapter, input, row, path) {
1128
- if (!adapter) return { status: null, reason: null, skus: [] };
1129
- const reason = resolveReason(adapter, input.reasonCode);
1130
- const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
1131
- if (invalid) return [invalid];
1132
- const skus = [...new Set(input.offendingSkus ?? [])];
1133
- const problems = skuProblems(reason, skus, row, path);
1134
- if (problems.length > 0) return problems;
1135
- const { apiCancel, cancelAfterAccept } = adapter.capabilities;
1136
- const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
1137
- return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
1138
- }
1139
- __name(planCancellation, "planCancellation");
1140
- function refusalData(plan, fromStatus, now) {
1141
- return {
1142
- status: "REJECTED",
1143
- // An accepted row keeps the instant it was accepted; a row leaving the
1144
- // clock is acknowledged now (the table's CHECK pairs the two).
1145
- ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
1146
- cancellationStatus: plan.status,
1147
- cancellationReasonCode: plan.reason?.code ?? null,
1148
- cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
1149
- cancellationRequestedAt: plan.status === "PENDING" ? now : null,
1150
- // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
1151
- cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
1152
- };
1153
- }
1154
- __name(refusalData, "refusalData");
1155
- function requestData(plan, now) {
1156
- return {
1157
- cancellationStatus: plan.status,
1158
- cancellationReasonCode: plan.reason?.code ?? null,
1159
- cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
1160
- cancellationRequestedAt: plan.status === "PENDING" ? now : null,
1161
- // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
1162
- cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
1163
- };
1164
- }
1165
- __name(requestData, "requestData");
1166
- async function failCancellationRequest(ctx, input) {
1167
- const db = await ctx.ports.db();
1168
- const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
1169
- const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
1170
- if (!row) return false;
1171
- const moved = await db.marketplaceAcceptance.updateMany({
1172
- where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
1173
- data: failedRequestData("REFUSED")
1174
- });
1175
- if (moved.count === 0) return false;
1176
- ctx.ports.publishChanged(input.clientId);
1177
- await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
1178
- return true;
1179
- }
1180
- __name(failCancellationRequest, "failCancellationRequest");
1561
+ __name(stampConnection, "stampConnection");
1181
1562
 
1182
1563
  // src/core/acceptance.ts
1183
1564
  async function listPendingAcceptances(ctx, clientId, orderIds) {
@@ -1219,15 +1600,19 @@ async function expireLapsedAcceptances(ctx, now) {
1219
1600
  // An order whose cancellation request waits is left to that request: its
1220
1601
  // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
1221
1602
  // never hears EXPIRED and then the confirmation for one order.
1222
- where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
1223
- 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 }
1224
1606
  });
1225
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 };
1226
1611
  const result = await db.marketplaceAcceptance.updateMany({
1227
- 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 },
1228
1613
  data: { status: "EXPIRED", acknowledgedAt: now }
1229
1614
  });
1230
- for (const row of lapsed) {
1615
+ for (const row of expiring) {
1231
1616
  try {
1232
1617
  await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
1233
1618
  } catch (error) {
@@ -1236,7 +1621,7 @@ async function expireLapsedAcceptances(ctx, now) {
1236
1621
  );
1237
1622
  }
1238
1623
  }
1239
- const tenants = new Set(lapsed.map((row) => row.clientId));
1624
+ const tenants = new Set(expiring.map((row) => row.clientId));
1240
1625
  for (const clientId of tenants) ctx.ports.publishChanged(clientId);
1241
1626
  return { expired: result.count, tenants: tenants.size };
1242
1627
  }
@@ -1357,22 +1742,23 @@ async function owedFetch(ctx, payload) {
1357
1742
  __name(owedFetch, "owedFetch");
1358
1743
  async function fetchThroughAdapter(ctx, clientId, provider, externalOrderId) {
1359
1744
  const adapter = ctx.registry.get(provider);
1360
- if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
1361
- let connection;
1745
+ if (!adapter?.fetchOrder) return { result: { kind: "refused", status: 0, message: `${provider} cannot fetch an order` }, sealed: null };
1746
+ let opened;
1362
1747
  try {
1363
- connection = await readOutboundConnection(ctx, clientId, provider);
1748
+ opened = await readSealedOutboundConnection(ctx, clientId, provider);
1364
1749
  } catch (error) {
1365
1750
  const reason = error instanceof Error ? error.message : String(error);
1366
- return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
1751
+ return { result: { kind: "refused", status: 0, message: `credentials do not open: ${reason}` }, sealed: null };
1367
1752
  }
1368
- if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
1753
+ if (!opened) return { result: { kind: "refused", status: 0, message: "no credentials on file" }, sealed: null };
1369
1754
  try {
1370
- return await adapter.fetchOrder(
1371
- { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
1755
+ const result = await adapter.fetchOrder(
1756
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...opened.connection },
1372
1757
  { externalOrderId }
1373
1758
  );
1759
+ return { result, sealed: opened.sealed };
1374
1760
  } catch (error) {
1375
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
1761
+ return { result: { kind: "retry", reason: error instanceof Error ? error.message : String(error) }, sealed: opened.sealed };
1376
1762
  }
1377
1763
  }
1378
1764
  __name(fetchThroughAdapter, "fetchThroughAdapter");
@@ -1412,6 +1798,10 @@ async function ingestFetched(ctx, row, clientId, order, target) {
1412
1798
  return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
1413
1799
  }
1414
1800
  __name(ingestFetched, "ingestFetched");
1801
+ function credentialsRefused(result) {
1802
+ return result.kind === "refused" && result.own === true && result.status >= 400 && result.status < 500;
1803
+ }
1804
+ __name(credentialsRefused, "credentialsRefused");
1415
1805
  async function runFetchOrder(ctx, payload, attempt) {
1416
1806
  const owed = await owedFetch(ctx, payload);
1417
1807
  if (typeof owed === "string") return { kind: "skipped", reason: owed };
@@ -1421,17 +1811,27 @@ async function runFetchOrder(ctx, payload, attempt) {
1421
1811
  await deferInboxEvent(ctx, row.id, "integration is not enabled");
1422
1812
  return { kind: "skipped", reason: "integration is not enabled" };
1423
1813
  }
1424
- const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
1425
- if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
1814
+ const { result, sealed } = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
1815
+ const stamp = sealed === null ? null : { clientId: payload.clientId, provider: event.provider, sealed };
1816
+ if (result.kind === "order") {
1817
+ if (stamp) await markCredentialsAccepted(ctx, stamp);
1818
+ return ingestFetched(ctx, row, payload.clientId, result.order, target);
1819
+ }
1820
+ return endUnfetched(ctx, { row, event, result, attempt, stamp });
1821
+ }
1822
+ __name(runFetchOrder, "runFetchOrder");
1823
+ async function endUnfetched(ctx, input) {
1824
+ const { row, event, result, attempt } = input;
1426
1825
  const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
1427
1826
  if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
1428
1827
  throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
1429
1828
  }
1829
+ if (input.stamp && credentialsRefused(result)) await markCredentialsRefused(ctx, input.stamp);
1430
1830
  await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
1431
1831
  ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
1432
1832
  return { kind: "failed", reason };
1433
1833
  }
1434
- __name(runFetchOrder, "runFetchOrder");
1834
+ __name(endUnfetched, "endUnfetched");
1435
1835
 
1436
1836
  // src/core/catalogue-sweep.ts
1437
1837
  var CATALOGUE_STALE_MS = 10 * 6e4;
@@ -1695,6 +2095,15 @@ function acceptanceSkip(row) {
1695
2095
  return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
1696
2096
  }
1697
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");
1698
2107
  async function adapterAndHostSkip(ctx, payload, step, row, adapter) {
1699
2108
  const takes = adapter.informStatus !== void 0 && adapter.capabilities.statusSteps?.includes(step) === true && adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
1700
2109
  if (!takes) return `the marketplace does not take ${step} for this order`;
@@ -1719,7 +2128,7 @@ function callAdapter(ctx, connection, adapter, row, step, ref) {
1719
2128
  });
1720
2129
  }
1721
2130
  __name(callAdapter, "callAdapter");
1722
- async function settle2(ctx, db, where, result, deps) {
2131
+ async function settle3(ctx, db, where, result, deps) {
1723
2132
  const table = statusTable(db);
1724
2133
  if (result.kind === "accepted") {
1725
2134
  await settleStatusRow(table, where, "SENT");
@@ -1733,7 +2142,7 @@ async function settle2(ctx, db, where, result, deps) {
1733
2142
  ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
1734
2143
  return { kind: "failed", action: "status", reason };
1735
2144
  }
1736
- __name(settle2, "settle");
2145
+ __name(settle3, "settle");
1737
2146
  function ownsClaim(found, key) {
1738
2147
  return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
1739
2148
  }
@@ -1760,7 +2169,7 @@ __name(claim2, "claim");
1760
2169
  async function runStatus(ctx, payload, row, adapter, deps) {
1761
2170
  const step = payload.step;
1762
2171
  if (!step) return skipped("a status call names no step");
1763
- 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);
1764
2173
  if (stopped) return skipped(stopped);
1765
2174
  const db = await ctx.ports.db();
1766
2175
  const table = statusTable(db);
@@ -1773,10 +2182,39 @@ async function runStatus(ctx, payload, row, adapter, deps) {
1773
2182
  const key = payload.claimKey ?? "";
1774
2183
  const unclaimed = await claim2(table, payload, row, step, key);
1775
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;
1776
2187
  const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
1777
- 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);
1778
2189
  }
1779
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");
1780
2218
  async function failStatusRow(ctx, payload) {
1781
2219
  const table = statusTable(await ctx.ports.db());
1782
2220
  if (table && payload.step) {
@@ -1809,6 +2247,7 @@ var ROW_SELECT = {
1809
2247
  cancellationOffendingSkus: true,
1810
2248
  cancellationRequestedAt: true,
1811
2249
  preparationMinutes: true,
2250
+ cancellationReasons: true,
1812
2251
  createdAt: true
1813
2252
  };
1814
2253
  function refOf(row) {
@@ -1820,7 +2259,7 @@ function refOf(row) {
1820
2259
  };
1821
2260
  }
1822
2261
  __name(refOf, "refOf");
1823
- function confirmSkip(row, adapter) {
2262
+ function confirmSkip2(row, adapter) {
1824
2263
  if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
1825
2264
  if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
1826
2265
  return `a cancellation request is ${row.cancellationStatus}`;
@@ -1829,7 +2268,7 @@ function confirmSkip(row, adapter) {
1829
2268
  if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
1830
2269
  return null;
1831
2270
  }
1832
- __name(confirmSkip, "confirmSkip");
2271
+ __name(confirmSkip2, "confirmSkip");
1833
2272
  async function stampConfirm(ctx, row, succeeded, now) {
1834
2273
  const db = await ctx.ports.db();
1835
2274
  await db.marketplaceAcceptance.updateMany({
@@ -1885,7 +2324,7 @@ async function connectionFor(ctx, clientId, provider) {
1885
2324
  }
1886
2325
  }
1887
2326
  __name(connectionFor, "connectionFor");
1888
- async function settle3(ctx, payload, row, result, attempt, succeed, fail3) {
2327
+ async function settle4(ctx, payload, row, result, attempt, succeed, fail3) {
1889
2328
  if (result.kind === "accepted") {
1890
2329
  await succeed();
1891
2330
  ctx.ports.publishChanged(payload.clientId);
@@ -1900,9 +2339,9 @@ async function settle3(ctx, payload, row, result, attempt, succeed, fail3) {
1900
2339
  ctx.ports.publishChanged(payload.clientId);
1901
2340
  return { kind: "failed", action: payload.action, reason };
1902
2341
  }
1903
- __name(settle3, "settle");
2342
+ __name(settle4, "settle");
1904
2343
  async function runConfirm(ctx, payload, row, adapter, attempt) {
1905
- const skip = confirmSkip(row, adapter);
2344
+ const skip = confirmSkip2(row, adapter);
1906
2345
  if (skip) return { kind: "skipped", reason: skip };
1907
2346
  const now = ctx.ports.clock.now();
1908
2347
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
@@ -1912,7 +2351,7 @@ async function runConfirm(ctx, payload, row, adapter, attempt) {
1912
2351
  // The stated preparation time, for a marketplace whose confirm takes one.
1913
2352
  { preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
1914
2353
  );
1915
- return settle3(
2354
+ return settle4(
1916
2355
  ctx,
1917
2356
  payload,
1918
2357
  row,
@@ -1942,7 +2381,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1942
2381
  await failAsTimeout(ctx, [{ clientId: payload.clientId, orderId: row.orderId, provider: row.provider }]);
1943
2382
  return { kind: "failed", action: payload.action, reason: "past the marketplace's answer window" };
1944
2383
  }
1945
- const reason = resolveReason(adapter, row.cancellationReasonCode);
2384
+ const reason = resolveReason(adapter, row.cancellationReasonCode, row.cancellationReasons) ?? resolveReason(adapter, row.cancellationReasonCode);
1946
2385
  const connection = await connectionFor(ctx, payload.clientId, row.provider);
1947
2386
  let result;
1948
2387
  if (!reason) result = { kind: "refused", status: 0, message: "the stored reason is not the marketplace's", own: true };
@@ -1955,7 +2394,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
1955
2394
  );
1956
2395
  }
1957
2396
  const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
1958
- return settle3(
2397
+ return settle4(
1959
2398
  ctx,
1960
2399
  payload,
1961
2400
  row,
@@ -2402,6 +2841,8 @@ export {
2402
2841
  PROVIDER_ID_PATTERN,
2403
2842
  MarketplaceAdapterRegistrationError,
2404
2843
  createAdapterRegistry,
2844
+ storedReasons,
2845
+ reasonsForOrder,
2405
2846
  resolveReason,
2406
2847
  suggestReason,
2407
2848
  NO_STANDING_REQUEST,
@@ -2411,6 +2852,12 @@ export {
2411
2852
  refusalData,
2412
2853
  requestData,
2413
2854
  failCancellationRequest,
2855
+ recordInboxEvent,
2856
+ settleInboxEvent,
2857
+ deferInboxEvent,
2858
+ listRetryableInboxEvents,
2859
+ CONFIRMED_BEFORE_ORDER,
2860
+ applyMarketplaceConfirmation,
2414
2861
  listPendingAcceptances,
2415
2862
  expireLapsedAcceptances,
2416
2863
  cancelAcceptance,
@@ -2444,14 +2891,19 @@ export {
2444
2891
  catalogueDedupeKey,
2445
2892
  enqueueCatalogue,
2446
2893
  runCatalogue,
2447
- recordInboxEvent,
2448
- settleInboxEvent,
2449
- deferInboxEvent,
2450
- listRetryableInboxEvents,
2451
2894
  statusTable,
2452
2895
  readStatusRows,
2453
2896
  noteMarketplaceStep,
2454
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,
2455
2907
  ingestMarketplaceOrder,
2456
2908
  CANCELLED_BEFORE_INGEST_REASON,
2457
2909
  markCancelledBeforeIngest,
@@ -2480,4 +2932,4 @@ export {
2480
2932
  AvailabilityRetryError,
2481
2933
  runAvailability
2482
2934
  };
2483
- //# sourceMappingURL=chunk-45ZVN5XI.js.map
2935
+ //# sourceMappingURL=chunk-MDXSVE7Q.js.map