@12-apps/marketplace 1.0.0 → 1.2.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 (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,198 +1,57 @@
1
1
  import {
2
- answered,
3
- outboundResultOf
4
- } from "./chunk-OEKTWUQH.js";
5
- import {
2
+ CLAIM_SELECT,
3
+ FetchOrderRetryError,
4
+ MARKETPLACE_FETCH_ORDER_JOB,
5
+ MARKETPLACE_OUTBOUND_JOB,
6
6
  MarketplaceAdapterRegistrationError,
7
+ NO_STANDING_REQUEST,
8
+ OUTBOUND_GIVE_UP_MS,
9
+ OUTBOUND_STALE_MS,
7
10
  OutboundRetryError,
8
11
  PROVIDER_ID_PATTERN,
12
+ awaitOrderBody,
13
+ cancelAcceptance,
14
+ connectionMerchantId,
9
15
  createAdapterRegistry,
16
+ deferInboxEvent,
17
+ enqueueOutbound,
18
+ expireLapsedAcceptances,
19
+ failCancellationRequest,
20
+ ingestMarketplaceOrder,
10
21
  listMarketplaceIntegrations,
11
- markMarketplaceEventSeen,
22
+ listMarketplaceMenuLinks,
23
+ listPendingAcceptances,
24
+ listRetryableInboxEvents,
25
+ markCancelledBeforeIngest,
26
+ merchantMismatch,
27
+ notPendingProblem,
28
+ outboundDedupeKey,
29
+ planCancellation,
30
+ recordInboxEvent,
31
+ refusalData,
32
+ requestData,
33
+ requestsFirst,
34
+ requeueOwedFetch,
12
35
  resolveIngestionTarget,
13
36
  resolveReason,
14
37
  resolveTenantByMerchant,
38
+ runFetchOrder,
15
39
  runOutbound,
16
40
  saveMarketplaceIntegration,
17
- suggestReason
18
- } from "./chunk-6OODIO3E.js";
41
+ settleInboxEvent,
42
+ suggestReason,
43
+ sweepOutbound,
44
+ tellCancellationFailed,
45
+ upsertLink
46
+ } from "./chunk-D2X7TOR6.js";
47
+ import {
48
+ answered,
49
+ outboundResultOf
50
+ } from "./chunk-24RQZPSV.js";
19
51
  import {
20
52
  __name
21
53
  } from "./chunk-7QVYU63E.js";
22
54
 
23
- // src/core/acceptance.ts
24
- async function listPendingAcceptances(ctx, clientId, orderIds) {
25
- const db = await ctx.ports.db();
26
- const rows = await db.marketplaceAcceptance.findMany({
27
- where: { clientId, status: "AWAITING", ...orderIds ? { orderId: { in: [...orderIds] } } : {} },
28
- orderBy: { acknowledgeBy: "asc" },
29
- select: {
30
- id: true,
31
- orderId: true,
32
- provider: true,
33
- externalOrderId: true,
34
- externalDisplayId: true,
35
- acknowledgeBy: true,
36
- externalDueAt: true,
37
- commissionCents: true
38
- }
39
- });
40
- if (rows.length === 0) return [];
41
- const summaries = await ctx.ports.order.summarize(
42
- clientId,
43
- rows.map((row) => row.orderId)
44
- );
45
- return rows.map((row) => {
46
- const summary = summaries.get(row.orderId);
47
- return {
48
- ...row,
49
- buyerName: summary?.buyerName ?? null,
50
- totalCents: summary?.totalCents ?? 0,
51
- unmappedLines: summary?.unmappedLines ?? 0,
52
- createdAt: summary?.createdAt ?? null
53
- };
54
- });
55
- }
56
- __name(listPendingAcceptances, "listPendingAcceptances");
57
- async function expireLapsedAcceptances(ctx, now) {
58
- const db = await ctx.ports.db();
59
- const lapsed = await db.marketplaceAcceptance.findMany({
60
- where: { status: "AWAITING", acknowledgeBy: { lt: now } },
61
- select: { id: true, clientId: true, orderId: true }
62
- });
63
- if (lapsed.length === 0) return { expired: 0, tenants: 0 };
64
- const result = await db.marketplaceAcceptance.updateMany({
65
- where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING" },
66
- data: { status: "EXPIRED", acknowledgedAt: now }
67
- });
68
- for (const row of lapsed) {
69
- try {
70
- await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
71
- } catch (error) {
72
- ctx.ports.logger.error(
73
- `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` + (error instanceof Error ? error.message : String(error))
74
- );
75
- }
76
- }
77
- const tenants = new Set(lapsed.map((row) => row.clientId));
78
- for (const clientId of tenants) ctx.ports.publishChanged(clientId);
79
- return { expired: result.count, tenants: tenants.size };
80
- }
81
- __name(expireLapsedAcceptances, "expireLapsedAcceptances");
82
- async function cancelAcceptance(ctx, input) {
83
- const db = await ctx.ports.db();
84
- const row = await db.marketplaceAcceptance.findFirst({
85
- where: {
86
- clientId: input.clientId,
87
- provider: input.provider,
88
- externalOrderId: input.externalOrderId
89
- },
90
- select: { orderId: true }
91
- });
92
- if (!row) return false;
93
- await ctx.ports.transaction(async (tx) => {
94
- await tx.marketplaceAcceptance.updateMany({
95
- where: { orderId: row.orderId, status: { not: "REJECTED" } },
96
- data: { status: "REJECTED", acknowledgedAt: input.now ?? ctx.ports.clock.now() }
97
- });
98
- await tx.marketplaceAcceptance.updateMany({
99
- where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
100
- data: { cancellationStatus: "CONFIRMED" }
101
- });
102
- });
103
- await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
104
- ctx.ports.publishChanged(input.clientId);
105
- return true;
106
- }
107
- __name(cancelAcceptance, "cancelAcceptance");
108
-
109
- // src/core/menu-links.ts
110
- var LINK_SELECT = {
111
- id: true,
112
- provider: true,
113
- externalSku: true,
114
- externalName: true,
115
- menuItemId: true,
116
- lastSeenAt: true
117
- };
118
- function toView(row) {
119
- return {
120
- id: row.id,
121
- provider: row.provider,
122
- externalSku: row.externalSku,
123
- externalName: row.externalName ?? row.externalSku,
124
- menuItemId: row.menuItemId,
125
- lastSeenAt: row.lastSeenAt
126
- };
127
- }
128
- __name(toView, "toView");
129
- async function listMarketplaceMenuLinks(ctx, input) {
130
- const db = await ctx.ports.db();
131
- const rows = await db.marketplaceMenuLink.findMany({
132
- where: {
133
- clientId: input.clientId,
134
- ...input.ids ? { id: { in: [...input.ids] } } : {},
135
- ...input.provider ? { provider: input.provider } : {},
136
- ...input.unmappedOnly ? { menuItemId: null } : {}
137
- },
138
- select: LINK_SELECT,
139
- orderBy: { lastSeenAt: "desc" }
140
- });
141
- return rows.map(toView);
142
- }
143
- __name(listMarketplaceMenuLinks, "listMarketplaceMenuLinks");
144
- async function upsertLink(db, input) {
145
- const row = await db.marketplaceMenuLink.upsert({
146
- where: {
147
- clientId_provider_externalSku: {
148
- clientId: input.clientId,
149
- provider: input.provider,
150
- externalSku: input.externalSku
151
- }
152
- },
153
- create: {
154
- clientId: input.clientId,
155
- provider: input.provider,
156
- externalSku: input.externalSku,
157
- externalName: input.externalName ?? input.externalSku,
158
- menuItemId: input.menuItemId
159
- },
160
- // `externalName` is NOT rewritten here. It is the marketplace's snapshot of
161
- // what it called the item, and an operator's typing is not a better record
162
- // of that than the marketplace's own text.
163
- update: { menuItemId: input.menuItemId },
164
- select: LINK_SELECT
165
- });
166
- return toView(row);
167
- }
168
- __name(upsertLink, "upsertLink");
169
- async function resolveSkus(db, input) {
170
- const resolved = /* @__PURE__ */ new Map();
171
- for (const sku of input.skus) {
172
- const row = await db.marketplaceMenuLink.upsert({
173
- where: {
174
- clientId_provider_externalSku: {
175
- clientId: input.clientId,
176
- provider: input.provider,
177
- externalSku: sku.externalSku
178
- }
179
- },
180
- create: {
181
- clientId: input.clientId,
182
- provider: input.provider,
183
- externalSku: sku.externalSku,
184
- externalName: sku.name,
185
- lastSeenAt: input.seenAt
186
- },
187
- update: { lastSeenAt: input.seenAt },
188
- select: { menuItemId: true }
189
- });
190
- resolved.set(sku.externalSku, row.menuItemId);
191
- }
192
- return resolved;
193
- }
194
- __name(resolveSkus, "resolveSkus");
195
-
196
55
  // src/core/bulk.ts
197
56
  function duplicates(rows, keyOf, list, field) {
198
57
  const seen = /* @__PURE__ */ new Set();
@@ -313,103 +172,6 @@ async function upsertMenuLinks(ctx, input) {
313
172
  }
314
173
  __name(upsertMenuLinks, "upsertMenuLinks");
315
174
 
316
- // src/core/cancellation.ts
317
- var CLAIM_SELECT = {
318
- orderId: true,
319
- provider: true,
320
- status: true,
321
- cancellationStatus: true,
322
- lineSkus: true
323
- };
324
- function notPendingProblem(row, path, allowed = ["AWAITING"]) {
325
- if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
326
- if (allowed.includes(row.status) && row.cancellationStatus === null) return null;
327
- const status = row.status;
328
- return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
329
- }
330
- __name(notPendingProblem, "notPendingProblem");
331
- function lineSkusOf(row) {
332
- return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
333
- }
334
- __name(lineSkusOf, "lineSkusOf");
335
- function skuProblems(reason, skus, row, path) {
336
- if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
337
- const known = lineSkusOf(row);
338
- if (!known) return [];
339
- return skus.flatMap(
340
- (sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
341
- );
342
- }
343
- __name(skuProblems, "skuProblems");
344
- function invalidReasonProblem(adapter, reason, code, path) {
345
- if (code === null || code === void 0 || reason) return null;
346
- const validCodes = adapter.cancellationReasons().map((candidate) => candidate.code);
347
- return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
348
- }
349
- __name(invalidReasonProblem, "invalidReasonProblem");
350
- function planCancellation(adapter, input, row, path) {
351
- if (!adapter) return { status: null, reason: null, skus: [] };
352
- const reason = resolveReason(adapter, input.reasonCode);
353
- const invalid = invalidReasonProblem(adapter, reason, input.reasonCode, path);
354
- if (invalid) return [invalid];
355
- const skus = [...new Set(input.offendingSkus ?? [])];
356
- const problems = skuProblems(reason, skus, row, path);
357
- if (problems.length > 0) return problems;
358
- const { apiCancel, cancelAfterAccept } = adapter.capabilities;
359
- const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
360
- return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
361
- }
362
- __name(planCancellation, "planCancellation");
363
- function refusalData(plan, fromStatus, now) {
364
- return {
365
- status: "REJECTED",
366
- // An accepted row keeps the instant it was accepted; a row leaving the
367
- // clock is acknowledged now (the table's CHECK pairs the two).
368
- ...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
369
- cancellationStatus: plan.status,
370
- cancellationReasonCode: plan.reason?.code ?? null,
371
- cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
372
- cancellationRequestedAt: plan.status === "PENDING" ? now : null
373
- };
374
- }
375
- __name(refusalData, "refusalData");
376
- async function failCancellationRequest(ctx, input) {
377
- const db = await ctx.ports.db();
378
- const moved = await db.marketplaceAcceptance.updateMany({
379
- where: {
380
- clientId: input.clientId,
381
- provider: input.provider,
382
- externalOrderId: input.externalOrderId,
383
- cancellationStatus: { in: ["PENDING", "REQUESTED"] }
384
- },
385
- data: { cancellationStatus: "FAILED" }
386
- });
387
- if (moved.count > 0) ctx.ports.publishChanged(input.clientId);
388
- return moved.count > 0;
389
- }
390
- __name(failCancellationRequest, "failCancellationRequest");
391
-
392
- // src/core/outbound-queue.ts
393
- var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
394
- function outboundDedupeKey(payload) {
395
- return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.orderId}`;
396
- }
397
- __name(outboundDedupeKey, "outboundDedupeKey");
398
- async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
399
- const adapter = ctx.registry.get(provider);
400
- if (!adapter) return false;
401
- const able = payload.action === "confirm" ? adapter.capabilities.apiConfirm : adapter.capabilities.apiCancel;
402
- if (!able) return false;
403
- const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
404
- if (!outcome.enqueued) {
405
- ctx.ports.logger.warn(
406
- `${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
407
- );
408
- }
409
- return outcome.enqueued;
410
- }
411
- __name(enqueueOutbound, "enqueueOutbound");
412
-
413
175
  // src/core/decisions.ts
414
176
  var Rollback = class extends Error {
415
177
  constructor(problems) {
@@ -432,29 +194,48 @@ function duplicateProblems(decisions) {
432
194
  });
433
195
  }
434
196
  __name(duplicateProblems, "duplicateProblems");
435
- function decidedOf(input, plan) {
197
+ function decidedOf(input, plan, keptStatus) {
198
+ const decided = input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED";
436
199
  return {
437
200
  orderId: input.orderId,
438
- status: input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED",
201
+ status: keptStatus ?? decided,
439
202
  cancellation: plan?.status ?? null,
440
203
  reasonCode: plan?.reason?.code ?? null,
441
204
  offendingSkus: plan?.skus ?? []
442
205
  };
443
206
  }
444
207
  __name(decidedOf, "decidedOf");
208
+ var CLEARED_REQUEST = {
209
+ cancellationStatus: null,
210
+ cancellationReasonCode: null,
211
+ cancellationOffendingSkus: null,
212
+ cancellationFailureReason: null
213
+ };
445
214
  function planOne(ctx, input, index, row, now) {
446
215
  const path = ["decisions", index];
447
216
  const stale = notPendingProblem(row, path);
448
217
  if (stale || !row) return stale ? [stale] : [];
449
218
  if (input.decision === "ACCEPT") {
450
- const data = { status: "ACCEPTED", acknowledgedAt: now, preparationMinutes: input.preparationMinutes ?? null };
451
- return { input, index, row, data, decided: decidedOf(input, null) };
219
+ const data = {
220
+ status: "ACCEPTED",
221
+ acknowledgedAt: now,
222
+ preparationMinutes: input.preparationMinutes ?? null,
223
+ ...row.cancellationStatus === null ? {} : CLEARED_REQUEST
224
+ };
225
+ return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };
452
226
  }
453
227
  const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);
454
228
  if (Array.isArray(plan)) return plan;
455
- return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan) };
229
+ if (requestOnly(ctx, plan)) {
230
+ return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };
231
+ }
232
+ return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };
456
233
  }
457
234
  __name(planOne, "planOne");
235
+ function requestOnly(ctx, plan) {
236
+ return requestsFirst(ctx) && plan.status !== null;
237
+ }
238
+ __name(requestOnly, "requestOnly");
458
239
  async function admitAndClaim(ctx, clientId, planned, validateOnly) {
459
240
  await ctx.ports.transaction(async (tx) => {
460
241
  const refused = [];
@@ -475,7 +256,7 @@ async function admitAndClaim(ctx, clientId, planned, validateOnly) {
475
256
  if (refused.length > 0) throw new Rollback(refused);
476
257
  for (const one of planned) {
477
258
  const claimed = await tx.marketplaceAcceptance.updateMany({
478
- where: { orderId: one.input.orderId, clientId, status: "AWAITING" },
259
+ where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
479
260
  data: one.data
480
261
  });
481
262
  if (claimed.count === 0) refused.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
@@ -488,14 +269,15 @@ __name(admitAndClaim, "admitAndClaim");
488
269
  async function afterCommit(ctx, clientId, planned) {
489
270
  for (const one of planned) {
490
271
  const { orderId } = one.input;
491
- if (one.decided.status === "ACCEPTED") {
272
+ if (one.input.decision === "ACCEPT") {
492
273
  await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, one.row.provider);
493
274
  } else if (one.decided.cancellation === "PENDING") {
494
275
  await enqueueOutbound(ctx, { clientId, orderId, action: "requestCancellation" }, one.row.provider);
495
276
  }
496
277
  try {
497
- if (one.decided.status === "ACCEPTED") await ctx.ports.order.onAccepted(clientId, orderId);
498
- else await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
278
+ if (one.decided.status === "ACCEPTED" && one.input.decision === "ACCEPT") await ctx.ports.order.onAccepted(clientId, orderId);
279
+ else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
280
+ else if (one.decided.cancellation === "FAILED") await tellCancellationFailed(ctx, clientId, orderId, "REFUSED");
499
281
  } catch (error) {
500
282
  ctx.ports.logger.error(
501
283
  `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
@@ -569,212 +351,26 @@ async function recordStoreCancellation(ctx, input) {
569
351
  if (stale || !row) return stale ? resultOfProblem(stale) : { kind: "stale", reason: "NOT_FOUND", status: null };
570
352
  const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);
571
353
  if (Array.isArray(plan)) return resultOfProblem(plan[0]);
354
+ return claimStoreCancellation(ctx, input, row, plan);
355
+ }
356
+ __name(recordStoreCancellation, "recordStoreCancellation");
357
+ async function claimStoreCancellation(ctx, input, row, plan) {
572
358
  const now = input.now ?? ctx.ports.clock.now();
573
359
  const db = await ctx.ports.db();
360
+ const only = requestOnly(ctx, plan);
574
361
  const claimed = await db.marketplaceAcceptance.updateMany({
575
- where: { orderId: input.orderId, clientId: input.clientId, status: row.status, cancellationStatus: null },
576
- data: refusalData(plan, row.status, now)
362
+ where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },
363
+ data: only ? requestData(plan, now) : refusalData(plan, row.status, now)
577
364
  });
578
365
  if (claimed.count === 0) return { kind: "stale", reason: "CONFLICT", status: null };
579
366
  if (plan.status === "PENDING") {
580
367
  await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: "requestCancellation" }, row.provider);
581
368
  }
582
369
  ctx.ports.publishChanged(input.clientId);
583
- return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan) };
584
- }
585
- __name(recordStoreCancellation, "recordStoreCancellation");
586
-
587
- // src/core/outbound-sweep.ts
588
- var OUTBOUND_STALE_MS = 10 * 6e4;
589
- var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
590
- var OWED_SELECT = { clientId: true, orderId: true, provider: true };
591
- function sweepDedupeKey(action, orderId, now) {
592
- return `${MARKETPLACE_OUTBOUND_JOB}:${action}:${orderId}:sweep:${now.getTime()}`;
593
- }
594
- __name(sweepDedupeKey, "sweepDedupeKey");
595
- async function requeue(ctx, rows, action, now) {
596
- let queued = 0;
597
- for (const row of rows) {
598
- const payload = { clientId: row.clientId, orderId: row.orderId, action };
599
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now))) queued += 1;
600
- }
601
- return queued;
602
- }
603
- __name(requeue, "requeue");
604
- async function sweepOutbound(ctx, now) {
605
- const db = await ctx.ports.db();
606
- const stale = new Date(now.getTime() - OUTBOUND_STALE_MS);
607
- const giveUp = new Date(now.getTime() - OUTBOUND_GIVE_UP_MS);
608
- const abandoned = await db.marketplaceAcceptance.updateMany({
609
- where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: giveUp } },
610
- data: { cancellationStatus: "FAILED" }
611
- });
612
- const cancellations = await db.marketplaceAcceptance.findMany({
613
- where: { cancellationStatus: "PENDING", cancellationRequestedAt: { lt: stale, gte: giveUp } },
614
- select: OWED_SELECT
615
- });
616
- const confirms = await db.marketplaceAcceptance.findMany({
617
- where: {
618
- status: "ACCEPTED",
619
- confirmedAt: null,
620
- confirmFailedAt: null,
621
- acknowledgedAt: { lt: stale, gte: giveUp }
622
- },
623
- select: OWED_SELECT
624
- });
625
- const requeued = await requeue(ctx, cancellations, "requestCancellation", now) + await requeue(ctx, confirms, "confirm", now);
626
- if (abandoned.count > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${abandoned.count} cancellation request(s).`);
627
- return { requeued, givenUp: abandoned.count };
370
+ if (only && plan.status === "FAILED") await tellCancellationFailed(ctx, input.clientId, input.orderId, "REFUSED");
371
+ return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan, only ? row.status : void 0) };
628
372
  }
629
- __name(sweepOutbound, "sweepOutbound");
630
-
631
- // src/core/inbox.ts
632
- async function recordInboxEvent(ctx, input) {
633
- const db = await ctx.ports.db();
634
- const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
635
- const existing = await db.marketplaceInboxEvent.findUnique({
636
- where: key,
637
- select: { id: true }
638
- });
639
- if (existing) return { id: existing.id, fresh: false };
640
- try {
641
- const row = await db.marketplaceInboxEvent.create({
642
- data: {
643
- clientId: input.clientId,
644
- provider: input.event.provider,
645
- eventId: input.event.eventId,
646
- eventType: input.event.eventType,
647
- externalOrderId: input.event.externalOrderId,
648
- payload: input.payload
649
- },
650
- select: { id: true }
651
- });
652
- return { id: row.id, fresh: true };
653
- } catch (error) {
654
- if (error.code !== "P2002") throw error;
655
- const raced = await db.marketplaceInboxEvent.findUnique({
656
- where: key,
657
- select: { id: true }
658
- });
659
- return { id: raced?.id ?? "", fresh: false };
660
- }
661
- }
662
- __name(recordInboxEvent, "recordInboxEvent");
663
- async function settleInboxEvent(ctx, id, outcome, error) {
664
- if (!id) return;
665
- const db = await ctx.ports.db();
666
- await db.marketplaceInboxEvent.update({
667
- where: { id },
668
- data: {
669
- status: outcome,
670
- // Truncated: a provider's error body can be a page of HTML, and the
671
- // column exists to be read by a human in a list.
672
- error: error ? error.slice(0, 500) : null,
673
- processedAt: ctx.ports.clock.now(),
674
- attempts: { increment: 1 }
675
- }
676
- });
677
- }
678
- __name(settleInboxEvent, "settleInboxEvent");
679
- async function deferInboxEvent(ctx, id, reason) {
680
- if (!id) return;
681
- const db = await ctx.ports.db();
682
- await db.marketplaceInboxEvent.update({
683
- where: { id },
684
- data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
685
- });
686
- }
687
- __name(deferInboxEvent, "deferInboxEvent");
688
- async function listRetryableInboxEvents(ctx) {
689
- const db = await ctx.ports.db();
690
- const rows = await db.marketplaceInboxEvent.findMany({
691
- where: {
692
- status: { in: ["PENDING", "FAILED"] },
693
- clientId: { not: null },
694
- attempts: { lt: ctx.ports.maxInboxAttempts }
695
- },
696
- orderBy: { receivedAt: "asc" },
697
- take: ctx.ports.reconcileBatchSize,
698
- select: { id: true, clientId: true, provider: true, payload: true }
699
- });
700
- return rows.map((row) => ({
701
- id: row.id,
702
- clientId: row.clientId,
703
- provider: row.provider,
704
- payload: row.payload
705
- }));
706
- }
707
- __name(listRetryableInboxEvents, "listRetryableInboxEvents");
708
-
709
- // src/core/ingest.ts
710
- async function composeLines(db, clientId, order, seenAt) {
711
- const mapping = await resolveSkus(db, {
712
- clientId,
713
- provider: order.provider,
714
- skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),
715
- seenAt
716
- });
717
- return order.lines.map((line) => ({
718
- externalSku: line.externalSku,
719
- // The MARKETPLACE's text, never the catalog's, even for a mapped line.
720
- // Every other order snapshots what the buyer was shown, and what this buyer
721
- // was shown is the marketplace's menu — a mapped line renamed to the host's
722
- // own product name would quietly disagree with the receipt in the bag.
723
- name: line.name,
724
- quantity: line.quantity,
725
- unitPriceCents: line.unitPriceCents,
726
- note: line.note,
727
- subjectRef: mapping.get(line.externalSku) ?? null
728
- }));
729
- }
730
- __name(composeLines, "composeLines");
731
- function acceptanceData(clientId, orderId, order, settings, now) {
732
- const accepted = settings.autoAccept;
733
- return {
734
- clientId,
735
- orderId,
736
- provider: order.provider,
737
- externalOrderId: order.externalOrderId,
738
- externalDisplayId: order.externalDisplayId,
739
- // Who carries a delivery: the merchant's courier or the marketplace's fleet.
740
- deliveredBy: order.deliveredBy ?? null,
741
- status: accepted ? "ACCEPTED" : "AWAITING",
742
- acknowledgeBy: new Date(now.getTime() + settings.ackSlaSeconds * 1e3),
743
- acknowledgedAt: accepted ? now : null,
744
- externalDueAt: order.deliveryDueAt,
745
- commissionCents: order.commissionCents,
746
- // The order's SKUs: what a cancellation's offending SKUs are checked against.
747
- lineSkus: [...new Set(order.lines.map((line) => line.externalSku))]
748
- };
749
- }
750
- __name(acceptanceData, "acceptanceData");
751
- async function ingestMarketplaceOrder(ctx, input) {
752
- const { clientId, order, settings } = input;
753
- const now = input.now ?? ctx.ports.clock.now();
754
- const db = await ctx.ports.db();
755
- const existing = await db.marketplaceAcceptance.findFirst({
756
- where: { provider: order.provider, externalOrderId: order.externalOrderId },
757
- select: { orderId: true }
758
- });
759
- if (existing) {
760
- return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };
761
- }
762
- const accepted = settings.autoAccept;
763
- const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
764
- const lines = await composeLines(tx, clientId, order, now);
765
- const created = await ctx.ports.order.create(clientId, order, lines, tx);
766
- await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now) });
767
- await markMarketplaceEventSeen(tx, clientId, order.provider, now);
768
- return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
769
- });
770
- if (accepted) {
771
- await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, order.provider);
772
- await ctx.ports.order.onAccepted(clientId, orderId);
773
- }
774
- ctx.ports.publishChanged(clientId);
775
- return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
776
- }
777
- __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
373
+ __name(claimStoreCancellation, "claimStoreCancellation");
778
374
 
779
375
  // src/core/pipeline.ts
780
376
  function normalizeEvent(ctx, provider, payload) {
@@ -800,6 +396,15 @@ async function processDelivery(ctx, input) {
800
396
  }
801
397
  }
802
398
  __name(processDelivery, "processDelivery");
399
+ function announcesOrderToFetch(event) {
400
+ return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;
401
+ }
402
+ __name(announcesOrderToFetch, "announcesOrderToFetch");
403
+ async function carriedOrderMismatch(ctx, clientId, order) {
404
+ if (!order.externalMerchantId) return null;
405
+ return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));
406
+ }
407
+ __name(carriedOrderMismatch, "carriedOrderMismatch");
803
408
  async function applyEvent(ctx, inboxId, clientId, event, settings, now) {
804
409
  const outcome = event.cancellationOutcome ?? (event.cancelled ? "CONFIRMED" : null);
805
410
  if (outcome === "FAILED" && event.externalOrderId) {
@@ -812,30 +417,35 @@ async function applyEvent(ctx, inboxId, clientId, event, settings, now) {
812
417
  return { kind: "cancellationFailed" };
813
418
  }
814
419
  if (event.cancelled && event.externalOrderId) {
815
- await cancelAcceptance(ctx, {
816
- clientId,
817
- provider: event.provider,
818
- externalOrderId: event.externalOrderId,
819
- now
820
- });
420
+ const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };
421
+ if (!await cancelAcceptance(ctx, { ...order, now })) await markCancelledBeforeIngest(ctx, order);
821
422
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
822
423
  return { kind: "cancelled" };
823
424
  }
425
+ if (announcesOrderToFetch(event)) {
426
+ await awaitOrderBody(ctx, clientId, inboxId);
427
+ return { kind: "awaitingOrder" };
428
+ }
824
429
  if (!event.order) {
825
430
  const reason = `no order body on ${event.eventType}`;
826
431
  await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
827
432
  return { kind: "ignored", reason };
828
433
  }
829
- const result = await ingestMarketplaceOrder(ctx, {
830
- clientId,
831
- order: event.order,
832
- settings,
833
- now
834
- });
434
+ return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);
435
+ }
436
+ __name(applyEvent, "applyEvent");
437
+ async function ingestCarried(ctx, inboxId, clientId, order, settings, now) {
438
+ const mismatch = await carriedOrderMismatch(ctx, clientId, order);
439
+ if (mismatch) {
440
+ await settleInboxEvent(ctx, inboxId, "FAILED", mismatch);
441
+ ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);
442
+ return { kind: "failed", reason: mismatch };
443
+ }
444
+ const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });
835
445
  await settleInboxEvent(ctx, inboxId, "PROCESSED");
836
446
  return { kind: "ingested", orderId: result.orderId, unmappedSkus: result.unmappedSkus };
837
447
  }
838
- __name(applyEvent, "applyEvent");
448
+ __name(ingestCarried, "ingestCarried");
839
449
  async function reprocessStoredDelivery(ctx, input) {
840
450
  const event = normalizeEvent(ctx, input.provider, input.payload);
841
451
  if (!event) {
@@ -849,6 +459,7 @@ async function reprocessStoredDelivery(ctx, input) {
849
459
  await deferInboxEvent(ctx, input.id, reason);
850
460
  return { kind: "ignored", reason };
851
461
  }
462
+ if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);
852
463
  try {
853
464
  return await applyEvent(
854
465
  ctx,
@@ -881,7 +492,8 @@ async function readOrderStates(ctx, clientId, orderIds) {
881
492
  confirmedAt: true,
882
493
  confirmFailedAt: true,
883
494
  cancellationStatus: true,
884
- cancellationReasonCode: true
495
+ cancellationReasonCode: true,
496
+ cancellationFailureReason: true
885
497
  }
886
498
  });
887
499
  return new Map(
@@ -897,6 +509,7 @@ async function readOrderStates(ctx, clientId, orderIds) {
897
509
  confirmFailedAt: row.confirmFailedAt,
898
510
  cancellation: row.cancellationStatus,
899
511
  cancellationReasonCode: row.cancellationReasonCode,
512
+ cancellationFailure: row.cancellationFailureReason,
900
513
  appUrl: adapter ? adapter.appLink(row) : null
901
514
  };
902
515
  return [row.orderId, state];
@@ -949,11 +562,14 @@ function createMarketplaceEngine(config) {
949
562
  retryable: /* @__PURE__ */ __name(() => listRetryableInboxEvents(ctx), "retryable"),
950
563
  reprocess: /* @__PURE__ */ __name((event) => reprocessStoredDelivery(ctx, event), "reprocess"),
951
564
  sweepOutbound: /* @__PURE__ */ __name((now) => sweepOutbound(ctx, now ?? ports.clock.now()), "sweepOutbound"),
952
- runOutbound: /* @__PURE__ */ __name((payload, attempt) => runOutbound(ctx, payload, attempt), "runOutbound")
565
+ runOutbound: /* @__PURE__ */ __name((payload, attempt) => runOutbound(ctx, payload, attempt), "runOutbound"),
566
+ runFetchOrder: /* @__PURE__ */ __name((payload, attempt) => runFetchOrder(ctx, payload, attempt), "runFetchOrder")
953
567
  };
954
568
  }
955
569
  __name(createMarketplaceEngine, "createMarketplaceEngine");
956
570
  export {
571
+ FetchOrderRetryError,
572
+ MARKETPLACE_FETCH_ORDER_JOB,
957
573
  MARKETPLACE_OUTBOUND_JOB,
958
574
  MarketplaceAdapterRegistrationError,
959
575
  OUTBOUND_GIVE_UP_MS,