@12-apps/marketplace 1.1.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 (75) hide show
  1. package/ADOPTING.md +9 -4
  2. package/README.md +147 -2
  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-BggtVFf9.d.ts → adapter-_iuSxvVD.d.ts} +35 -1
  13. package/dist/{chunk-7BYVGNU5.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-NGNEL4HS.js → chunk-CRYFYDQ2.js} +26 -2
  18. package/dist/chunk-CRYFYDQ2.js.map +1 -0
  19. package/dist/{chunk-DVIRN42O.js → chunk-D2X7TOR6.js} +669 -136
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-KrgZ4pA4.d.ts → engine-D-a4mttc.d.ts} +58 -2
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +7 -11
  25. package/dist/ifood/index.js +10 -60
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +56 -352
  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 +5 -1
  45. package/src/99food/copy.ts +36 -0
  46. package/src/99food/en-US.ts +19 -0
  47. package/src/99food/index.ts +121 -0
  48. package/src/99food/normalize.ts +263 -0
  49. package/src/99food/outbound.ts +220 -0
  50. package/src/99food/pt-BR.ts +23 -0
  51. package/src/core/adapter.ts +17 -1
  52. package/src/core/decisions.ts +16 -4
  53. package/src/core/engine.ts +8 -0
  54. package/src/core/fetch-order.ts +253 -0
  55. package/src/core/inbox.ts +8 -2
  56. package/src/core/ingest.ts +10 -2
  57. package/src/core/integration.ts +30 -1
  58. package/src/core/order-fetch-marks.ts +63 -0
  59. package/src/core/outbound.ts +22 -2
  60. package/src/core/payload-read.ts +101 -0
  61. package/src/core/pipeline.ts +64 -15
  62. package/src/core/types.ts +14 -0
  63. package/src/ifood/normalize.ts +15 -88
  64. package/src/index.ts +9 -1
  65. package/src/rappi/copy.ts +39 -0
  66. package/src/rappi/en-US.ts +14 -0
  67. package/src/rappi/index.ts +155 -0
  68. package/src/rappi/normalize.ts +314 -0
  69. package/src/rappi/outbound.ts +182 -0
  70. package/src/rappi/pt-BR.ts +18 -0
  71. package/src/server/index.ts +1 -0
  72. package/src/server/jobs.ts +35 -2
  73. package/dist/chunk-7BYVGNU5.js.map +0 -1
  74. package/dist/chunk-DVIRN42O.js.map +0 -1
  75. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -97,6 +97,394 @@ async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedup
97
97
  }
98
98
  __name(enqueueOutbound, "enqueueOutbound");
99
99
 
100
+ // src/core/inbox.ts
101
+ async function recordInboxEvent(ctx, input) {
102
+ const db = await ctx.ports.db();
103
+ const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
104
+ const existing = await db.marketplaceInboxEvent.findUnique({
105
+ where: key,
106
+ select: { id: true }
107
+ });
108
+ if (existing) return { id: existing.id, fresh: false };
109
+ try {
110
+ const row = await db.marketplaceInboxEvent.create({
111
+ data: {
112
+ clientId: input.clientId,
113
+ provider: input.event.provider,
114
+ eventId: input.event.eventId,
115
+ eventType: input.event.eventType,
116
+ externalOrderId: input.event.externalOrderId,
117
+ payload: input.payload,
118
+ // The engine's clock, not the database's: an announced order's
119
+ // acceptance window counts from here (`./fetch-order.ts`).
120
+ receivedAt: ctx.ports.clock.now()
121
+ },
122
+ select: { id: true }
123
+ });
124
+ return { id: row.id, fresh: true };
125
+ } catch (error) {
126
+ if (error.code !== "P2002") throw error;
127
+ const raced = await db.marketplaceInboxEvent.findUnique({
128
+ where: key,
129
+ select: { id: true }
130
+ });
131
+ return { id: raced?.id ?? "", fresh: false };
132
+ }
133
+ }
134
+ __name(recordInboxEvent, "recordInboxEvent");
135
+ async function settleInboxEvent(ctx, id, outcome, error) {
136
+ if (!id) return;
137
+ const db = await ctx.ports.db();
138
+ await db.marketplaceInboxEvent.update({
139
+ where: { id },
140
+ data: {
141
+ status: outcome,
142
+ // Truncated: a provider's error body can be a page of HTML, and the
143
+ // column exists to be read by a human in a list.
144
+ error: error ? error.slice(0, 500) : null,
145
+ processedAt: ctx.ports.clock.now(),
146
+ attempts: { increment: 1 }
147
+ }
148
+ });
149
+ }
150
+ __name(settleInboxEvent, "settleInboxEvent");
151
+ async function deferInboxEvent(ctx, id, reason) {
152
+ if (!id) return;
153
+ const db = await ctx.ports.db();
154
+ await db.marketplaceInboxEvent.update({
155
+ where: { id },
156
+ data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
157
+ });
158
+ }
159
+ __name(deferInboxEvent, "deferInboxEvent");
160
+ async function listRetryableInboxEvents(ctx) {
161
+ const db = await ctx.ports.db();
162
+ const rows = await db.marketplaceInboxEvent.findMany({
163
+ where: {
164
+ status: { in: ["PENDING", "FAILED"] },
165
+ clientId: { not: null },
166
+ attempts: { lt: ctx.ports.maxInboxAttempts }
167
+ },
168
+ orderBy: { receivedAt: "asc" },
169
+ take: ctx.ports.reconcileBatchSize,
170
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
171
+ });
172
+ return rows.map((row) => ({
173
+ id: row.id,
174
+ clientId: row.clientId,
175
+ provider: row.provider,
176
+ payload: row.payload,
177
+ receivedAt: row.receivedAt
178
+ }));
179
+ }
180
+ __name(listRetryableInboxEvents, "listRetryableInboxEvents");
181
+
182
+ // src/core/integration.ts
183
+ var VIEW_SELECT = {
184
+ provider: true,
185
+ enabled: true,
186
+ environment: true,
187
+ status: true,
188
+ externalMerchantId: true,
189
+ autoAccept: true,
190
+ ackSlaSeconds: true,
191
+ credentials: true,
192
+ lastEventAt: true,
193
+ lastVerifiedAt: true,
194
+ archivedAt: true
195
+ };
196
+ function toView(row) {
197
+ return {
198
+ provider: row.provider,
199
+ enabled: row.enabled,
200
+ environment: row.environment,
201
+ status: row.status,
202
+ externalMerchantId: row.externalMerchantId,
203
+ autoAccept: row.autoAccept,
204
+ ackSlaSeconds: row.ackSlaSeconds,
205
+ connected: row.credentials !== "",
206
+ lastEventAt: row.lastEventAt,
207
+ lastVerifiedAt: row.lastVerifiedAt,
208
+ archivedAt: row.archivedAt ?? null
209
+ };
210
+ }
211
+ __name(toView, "toView");
212
+ async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
213
+ const db = await ctx.ports.db();
214
+ const rows = await db.marketplaceIntegration.findMany({
215
+ where: {
216
+ clientId,
217
+ ...options.providers ? { provider: { in: [...options.providers] } } : {},
218
+ ...options.includeArchived ? {} : { archivedAt: null }
219
+ },
220
+ select: VIEW_SELECT,
221
+ orderBy: { provider: "asc" }
222
+ });
223
+ return rows.map(toView);
224
+ }
225
+ __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
226
+ async function saveMarketplaceIntegration(ctx, input, db) {
227
+ const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
228
+ const mutable = {
229
+ ...input.enabled === void 0 ? {} : { enabled: input.enabled },
230
+ ...input.environment === void 0 ? {} : { environment: input.environment },
231
+ ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
232
+ ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
233
+ ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
234
+ ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
235
+ };
236
+ const row = await db.marketplaceIntegration.upsert({
237
+ where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
238
+ create: {
239
+ clientId: input.clientId,
240
+ provider: input.provider,
241
+ credentials: sealed ?? "",
242
+ ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
243
+ ...mutable
244
+ },
245
+ update: mutable,
246
+ select: VIEW_SELECT
247
+ });
248
+ return toView(row);
249
+ }
250
+ __name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
251
+ async function connectionMerchantId(ctx, clientId, provider) {
252
+ const db = await ctx.ports.db();
253
+ const row = await db.marketplaceIntegration.findUnique({
254
+ where: { clientId_provider: { clientId, provider } },
255
+ select: { externalMerchantId: true, archivedAt: true }
256
+ });
257
+ return row && !row.archivedAt ? row.externalMerchantId ?? null : null;
258
+ }
259
+ __name(connectionMerchantId, "connectionMerchantId");
260
+ async function resolveIngestionTarget(ctx, clientId, provider) {
261
+ const db = await ctx.ports.db();
262
+ const row = await db.marketplaceIntegration.findUnique({
263
+ where: { clientId_provider: { clientId, provider } },
264
+ select: {
265
+ enabled: true,
266
+ autoAccept: true,
267
+ ackSlaSeconds: true,
268
+ credentials: true,
269
+ archivedAt: true,
270
+ externalMerchantId: true
271
+ }
272
+ });
273
+ if (!row || row.archivedAt) return null;
274
+ return {
275
+ enabled: row.enabled,
276
+ autoAccept: row.autoAccept,
277
+ ackSlaSeconds: row.ackSlaSeconds,
278
+ externalMerchantId: row.externalMerchantId ?? null,
279
+ // An unopenable blob must not read as "no secret configured" — that would
280
+ // turn a key-rotation problem into an endpoint that accepts unsigned
281
+ // deliveries. The secrets port throws instead, and the caller answers 401.
282
+ webhookSecret: row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret
283
+ };
284
+ }
285
+ __name(resolveIngestionTarget, "resolveIngestionTarget");
286
+ function openCredentials(ctx, sealed) {
287
+ const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
288
+ if (typeof parsed !== "object" || parsed === null) {
289
+ throw new Error("Stored marketplace credentials are not an object.");
290
+ }
291
+ const record = parsed;
292
+ return {
293
+ clientId: String(record.clientId ?? ""),
294
+ clientSecret: String(record.clientSecret ?? ""),
295
+ webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
296
+ };
297
+ }
298
+ __name(openCredentials, "openCredentials");
299
+ async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
300
+ const db = await ctx.ports.db();
301
+ const rows = await db.marketplaceIntegration.findMany({
302
+ where: { provider, externalMerchantId, archivedAt: null },
303
+ select: { clientId: true },
304
+ take: 1
305
+ });
306
+ return rows[0]?.clientId ?? null;
307
+ }
308
+ __name(resolveTenantByMerchant, "resolveTenantByMerchant");
309
+ async function markMarketplaceEventSeen(db, clientId, provider, at) {
310
+ await db.marketplaceIntegration.updateMany({
311
+ where: { clientId, provider },
312
+ data: { lastEventAt: at }
313
+ });
314
+ }
315
+ __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
316
+ async function readOutboundConnection(ctx, clientId, provider) {
317
+ const db = await ctx.ports.db();
318
+ const row = await db.marketplaceIntegration.findUnique({
319
+ where: { clientId_provider: { clientId, provider } },
320
+ select: { environment: true, credentials: true }
321
+ });
322
+ if (!row || row.credentials === "") return null;
323
+ return {
324
+ environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
325
+ credentials: openCredentials(ctx, row.credentials)
326
+ };
327
+ }
328
+ __name(readOutboundConnection, "readOutboundConnection");
329
+
330
+ // src/core/menu-links.ts
331
+ var LINK_SELECT = {
332
+ id: true,
333
+ provider: true,
334
+ externalSku: true,
335
+ externalName: true,
336
+ menuItemId: true,
337
+ lastSeenAt: true
338
+ };
339
+ function toView2(row) {
340
+ return {
341
+ id: row.id,
342
+ provider: row.provider,
343
+ externalSku: row.externalSku,
344
+ externalName: row.externalName ?? row.externalSku,
345
+ menuItemId: row.menuItemId,
346
+ lastSeenAt: row.lastSeenAt
347
+ };
348
+ }
349
+ __name(toView2, "toView");
350
+ async function listMarketplaceMenuLinks(ctx, input) {
351
+ const db = await ctx.ports.db();
352
+ const rows = await db.marketplaceMenuLink.findMany({
353
+ where: {
354
+ clientId: input.clientId,
355
+ ...input.ids ? { id: { in: [...input.ids] } } : {},
356
+ ...input.provider ? { provider: input.provider } : {},
357
+ ...input.unmappedOnly ? { menuItemId: null } : {}
358
+ },
359
+ select: LINK_SELECT,
360
+ orderBy: { lastSeenAt: "desc" }
361
+ });
362
+ return rows.map(toView2);
363
+ }
364
+ __name(listMarketplaceMenuLinks, "listMarketplaceMenuLinks");
365
+ async function upsertLink(db, input) {
366
+ const row = await db.marketplaceMenuLink.upsert({
367
+ where: {
368
+ clientId_provider_externalSku: {
369
+ clientId: input.clientId,
370
+ provider: input.provider,
371
+ externalSku: input.externalSku
372
+ }
373
+ },
374
+ create: {
375
+ clientId: input.clientId,
376
+ provider: input.provider,
377
+ externalSku: input.externalSku,
378
+ externalName: input.externalName ?? input.externalSku,
379
+ menuItemId: input.menuItemId
380
+ },
381
+ // `externalName` is NOT rewritten here. It is the marketplace's snapshot of
382
+ // what it called the item, and an operator's typing is not a better record
383
+ // of that than the marketplace's own text.
384
+ update: { menuItemId: input.menuItemId },
385
+ select: LINK_SELECT
386
+ });
387
+ return toView2(row);
388
+ }
389
+ __name(upsertLink, "upsertLink");
390
+ async function resolveSkus(db, input) {
391
+ const resolved = /* @__PURE__ */ new Map();
392
+ for (const sku of input.skus) {
393
+ const row = await db.marketplaceMenuLink.upsert({
394
+ where: {
395
+ clientId_provider_externalSku: {
396
+ clientId: input.clientId,
397
+ provider: input.provider,
398
+ externalSku: sku.externalSku
399
+ }
400
+ },
401
+ create: {
402
+ clientId: input.clientId,
403
+ provider: input.provider,
404
+ externalSku: sku.externalSku,
405
+ externalName: sku.name,
406
+ lastSeenAt: input.seenAt
407
+ },
408
+ update: { lastSeenAt: input.seenAt },
409
+ select: { menuItemId: true }
410
+ });
411
+ resolved.set(sku.externalSku, row.menuItemId);
412
+ }
413
+ return resolved;
414
+ }
415
+ __name(resolveSkus, "resolveSkus");
416
+
417
+ // src/core/ingest.ts
418
+ async function composeLines(db, clientId, order, seenAt) {
419
+ const mapping = await resolveSkus(db, {
420
+ clientId,
421
+ provider: order.provider,
422
+ skus: order.lines.map((line) => ({ externalSku: line.externalSku, name: line.name })),
423
+ seenAt
424
+ });
425
+ return order.lines.map((line) => ({
426
+ externalSku: line.externalSku,
427
+ // The MARKETPLACE's text, never the catalog's, even for a mapped line.
428
+ // Every other order snapshots what the buyer was shown, and what this buyer
429
+ // was shown is the marketplace's menu — a mapped line renamed to the host's
430
+ // own product name would quietly disagree with the receipt in the bag.
431
+ name: line.name,
432
+ quantity: line.quantity,
433
+ unitPriceCents: line.unitPriceCents,
434
+ note: line.note,
435
+ subjectRef: mapping.get(line.externalSku) ?? null
436
+ }));
437
+ }
438
+ __name(composeLines, "composeLines");
439
+ function acceptanceData(clientId, orderId, order, settings, now, clockStartsAt) {
440
+ const accepted = settings.autoAccept;
441
+ return {
442
+ clientId,
443
+ orderId,
444
+ provider: order.provider,
445
+ externalOrderId: order.externalOrderId,
446
+ externalDisplayId: order.externalDisplayId,
447
+ // Who carries a delivery: the merchant's courier or the marketplace's fleet.
448
+ deliveredBy: order.deliveredBy ?? null,
449
+ status: accepted ? "ACCEPTED" : "AWAITING",
450
+ acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1e3),
451
+ acknowledgedAt: accepted ? now : null,
452
+ externalDueAt: order.deliveryDueAt,
453
+ commissionCents: order.commissionCents,
454
+ // The order's SKUs: what a cancellation's offending SKUs are checked against.
455
+ lineSkus: [...new Set(order.lines.map((line) => line.externalSku))]
456
+ };
457
+ }
458
+ __name(acceptanceData, "acceptanceData");
459
+ async function ingestMarketplaceOrder(ctx, input) {
460
+ const { clientId, order, settings } = input;
461
+ const now = input.now ?? ctx.ports.clock.now();
462
+ const clockStartsAt = input.clockStartsAt ?? now;
463
+ const db = await ctx.ports.db();
464
+ const existing = await db.marketplaceAcceptance.findFirst({
465
+ where: { provider: order.provider, externalOrderId: order.externalOrderId },
466
+ select: { orderId: true }
467
+ });
468
+ if (existing) {
469
+ return { orderId: existing.orderId, created: false, unmappedSkus: [], autoAccepted: false };
470
+ }
471
+ const accepted = settings.autoAccept;
472
+ const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
473
+ const lines = await composeLines(tx, clientId, order, now);
474
+ const created = await ctx.ports.order.create(clientId, order, lines, tx);
475
+ await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
476
+ await markMarketplaceEventSeen(tx, clientId, order.provider, now);
477
+ return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
478
+ });
479
+ if (accepted) {
480
+ await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, order.provider);
481
+ await ctx.ports.order.onAccepted(clientId, orderId);
482
+ }
483
+ ctx.ports.publishChanged(clientId);
484
+ return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
485
+ }
486
+ __name(ingestMarketplaceOrder, "ingestMarketplaceOrder");
487
+
100
488
  // src/core/cancellation-outcome.ts
101
489
  async function tell(ctx, what, orderId, call) {
102
490
  try {
@@ -247,6 +635,260 @@ async function failCancellationRequest(ctx, input) {
247
635
  }
248
636
  __name(failCancellationRequest, "failCancellationRequest");
249
637
 
638
+ // src/core/acceptance.ts
639
+ async function listPendingAcceptances(ctx, clientId, orderIds) {
640
+ const db = await ctx.ports.db();
641
+ const rows = await db.marketplaceAcceptance.findMany({
642
+ where: { clientId, status: "AWAITING", ...orderIds ? { orderId: { in: [...orderIds] } } : {} },
643
+ orderBy: { acknowledgeBy: "asc" },
644
+ select: {
645
+ id: true,
646
+ orderId: true,
647
+ provider: true,
648
+ externalOrderId: true,
649
+ externalDisplayId: true,
650
+ acknowledgeBy: true,
651
+ externalDueAt: true,
652
+ commissionCents: true
653
+ }
654
+ });
655
+ if (rows.length === 0) return [];
656
+ const summaries = await ctx.ports.order.summarize(
657
+ clientId,
658
+ rows.map((row) => row.orderId)
659
+ );
660
+ return rows.map((row) => {
661
+ const summary = summaries.get(row.orderId);
662
+ return {
663
+ ...row,
664
+ buyerName: summary?.buyerName ?? null,
665
+ totalCents: summary?.totalCents ?? 0,
666
+ unmappedLines: summary?.unmappedLines ?? 0,
667
+ createdAt: summary?.createdAt ?? null
668
+ };
669
+ });
670
+ }
671
+ __name(listPendingAcceptances, "listPendingAcceptances");
672
+ async function expireLapsedAcceptances(ctx, now) {
673
+ const db = await ctx.ports.db();
674
+ const lapsed = await db.marketplaceAcceptance.findMany({
675
+ // An order whose cancellation request waits is left to that request: its
676
+ // answer, or its window's TIMEOUT, ends it first (FUT-4758), so the host
677
+ // never hears EXPIRED and then the confirmation for one order.
678
+ where: { status: "AWAITING", acknowledgeBy: { lt: now }, ...NO_STANDING_REQUEST },
679
+ select: { id: true, clientId: true, orderId: true }
680
+ });
681
+ if (lapsed.length === 0) return { expired: 0, tenants: 0 };
682
+ const result = await db.marketplaceAcceptance.updateMany({
683
+ where: { id: { in: lapsed.map((row) => row.id) }, status: "AWAITING", ...NO_STANDING_REQUEST },
684
+ data: { status: "EXPIRED", acknowledgedAt: now }
685
+ });
686
+ for (const row of lapsed) {
687
+ try {
688
+ await ctx.ports.order.onRefused(row.clientId, row.orderId, "EXPIRED");
689
+ } catch (error) {
690
+ ctx.ports.logger.error(
691
+ `marketplace.expire-acceptances: order ${row.orderId} expired but the host's refusal failed: ` + (error instanceof Error ? error.message : String(error))
692
+ );
693
+ }
694
+ }
695
+ const tenants = new Set(lapsed.map((row) => row.clientId));
696
+ for (const clientId of tenants) ctx.ports.publishChanged(clientId);
697
+ return { expired: result.count, tenants: tenants.size };
698
+ }
699
+ __name(expireLapsedAcceptances, "expireLapsedAcceptances");
700
+ function hasConfirmHook(ctx) {
701
+ return ctx.ports.order.onCancellationConfirmed !== void 0;
702
+ }
703
+ __name(hasConfirmHook, "hasConfirmHook");
704
+ async function cancelAcceptance(ctx, input) {
705
+ const db = await ctx.ports.db();
706
+ const row = await db.marketplaceAcceptance.findFirst({
707
+ where: {
708
+ clientId: input.clientId,
709
+ provider: input.provider,
710
+ externalOrderId: input.externalOrderId
711
+ },
712
+ select: { orderId: true, cancellationStatus: true }
713
+ });
714
+ if (!row) return false;
715
+ const answered = await ctx.ports.transaction(async (tx) => {
716
+ await rejectConfirmed(tx, row.orderId, input.now ?? ctx.ports.clock.now());
717
+ const confirmed = await tx.marketplaceAcceptance.updateMany({
718
+ where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "REQUESTED", "FAILED"] } },
719
+ data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
720
+ });
721
+ return confirmed.count > 0;
722
+ });
723
+ const storeAsked = answered || row.cancellationStatus === "CONFIRMED";
724
+ const told = storeAsked && (answered ? await tellCancellationConfirmed(ctx, input.clientId, row.orderId) : hasConfirmHook(ctx));
725
+ if (!told) await ctx.ports.order.onRefused(input.clientId, row.orderId, "CANCELLED");
726
+ ctx.ports.publishChanged(input.clientId);
727
+ return true;
728
+ }
729
+ __name(cancelAcceptance, "cancelAcceptance");
730
+
731
+ // src/core/order-fetch-marks.ts
732
+ var MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
733
+ var markerId = /* @__PURE__ */ __name((externalOrderId) => `engine:cancelled:${externalOrderId}`, "markerId");
734
+ async function markCancelledBeforeIngest(ctx, input) {
735
+ if (!ctx.registry.get(input.provider)?.fetchOrder) return;
736
+ const db = await ctx.ports.db();
737
+ try {
738
+ await db.marketplaceInboxEvent.create({
739
+ data: {
740
+ clientId: input.clientId,
741
+ provider: input.provider,
742
+ eventId: markerId(input.externalOrderId),
743
+ eventType: MARKER_TYPE,
744
+ externalOrderId: input.externalOrderId,
745
+ payload: {},
746
+ status: "IGNORED",
747
+ error: "cancelled before the order was ingested",
748
+ receivedAt: ctx.ports.clock.now(),
749
+ processedAt: ctx.ports.clock.now()
750
+ },
751
+ select: { id: true }
752
+ });
753
+ } catch (error) {
754
+ if (error.code !== "P2002") throw error;
755
+ }
756
+ }
757
+ __name(markCancelledBeforeIngest, "markCancelledBeforeIngest");
758
+ async function cancelledBeforeIngest(ctx, input) {
759
+ const db = await ctx.ports.db();
760
+ const row = await db.marketplaceInboxEvent.findUnique({
761
+ where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },
762
+ select: { clientId: true }
763
+ });
764
+ return row !== null && row.clientId === input.clientId;
765
+ }
766
+ __name(cancelledBeforeIngest, "cancelledBeforeIngest");
767
+
768
+ // src/core/fetch-order.ts
769
+ var MARKETPLACE_FETCH_ORDER_JOB = "marketplace.fetch-order";
770
+ var FetchOrderRetryError = class extends Error {
771
+ static {
772
+ __name(this, "FetchOrderRetryError");
773
+ }
774
+ constructor(message) {
775
+ super(message);
776
+ this.name = "FetchOrderRetryError";
777
+ }
778
+ };
779
+ var AWAITING_ORDER_REASON = "order details to fetch";
780
+ var FETCH_REQUEUE_AGE_MS = 2 * 6e4;
781
+ async function awaitOrderBody(ctx, clientId, inboxId, dedupeKey = `${MARKETPLACE_FETCH_ORDER_JOB}:${inboxId}`) {
782
+ await deferInboxEvent(ctx, inboxId, AWAITING_ORDER_REASON);
783
+ const payload = { clientId, inboxId };
784
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_FETCH_ORDER_JOB, payload, { dedupeKey });
785
+ if (!outcome.enqueued) {
786
+ ctx.ports.logger.warn(
787
+ `${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${inboxId} was not queued; the reconciliation sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
788
+ );
789
+ }
790
+ }
791
+ __name(awaitOrderBody, "awaitOrderBody");
792
+ async function requeueOwedFetch(ctx, input) {
793
+ const now = ctx.ports.clock.now();
794
+ const age = input.receivedAt ? now.getTime() - input.receivedAt.getTime() : Number.POSITIVE_INFINITY;
795
+ if (age < FETCH_REQUEUE_AGE_MS) return { kind: "awaitingOrder" };
796
+ ctx.ports.logger.warn(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${input.id} still waits for its order body; re-queued`);
797
+ await awaitOrderBody(ctx, input.clientId, input.id, `${MARKETPLACE_FETCH_ORDER_JOB}:${input.id}:${now.getTime()}`);
798
+ return { kind: "awaitingOrder" };
799
+ }
800
+ __name(requeueOwedFetch, "requeueOwedFetch");
801
+ async function owedFetch(ctx, payload) {
802
+ const db = await ctx.ports.db();
803
+ const row = await db.marketplaceInboxEvent.findUnique({
804
+ where: { id: payload.inboxId },
805
+ select: { id: true, clientId: true, provider: true, payload: true, status: true, receivedAt: true }
806
+ });
807
+ if (!row || row.clientId !== payload.clientId) return "no such inbox row for this tenant";
808
+ if (row.status !== "PENDING" && row.status !== "FAILED") return `the row is already ${row.status}`;
809
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
810
+ if (!event?.orderToFetch || event.order) return "the event announces no order to fetch";
811
+ return { row, event };
812
+ }
813
+ __name(owedFetch, "owedFetch");
814
+ async function fetchThroughAdapter(ctx, clientId, provider, externalOrderId) {
815
+ const adapter = ctx.registry.get(provider);
816
+ if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
817
+ let connection;
818
+ try {
819
+ connection = await readOutboundConnection(ctx, clientId, provider);
820
+ } catch (error) {
821
+ const reason = error instanceof Error ? error.message : String(error);
822
+ return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
823
+ }
824
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
825
+ try {
826
+ return await adapter.fetchOrder(
827
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
828
+ { externalOrderId }
829
+ );
830
+ } catch (error) {
831
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
832
+ }
833
+ }
834
+ __name(fetchThroughAdapter, "fetchThroughAdapter");
835
+ async function refusalOf(ctx, clientId, order, connectionMerchantId2) {
836
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
837
+ return { settle: "IGNORED", reason: "cancelled before its order body arrived", failed: false };
838
+ }
839
+ const mismatch = merchantMismatch(order, connectionMerchantId2);
840
+ return mismatch ? { settle: "FAILED", reason: mismatch, failed: true } : null;
841
+ }
842
+ __name(refusalOf, "refusalOf");
843
+ function merchantMismatch(order, connectionMerchantId2) {
844
+ const named = order.externalMerchantId ?? null;
845
+ if (named === null || connectionMerchantId2 === null || named === connectionMerchantId2) return null;
846
+ return `the order names merchant ${named}, not this connection's`;
847
+ }
848
+ __name(merchantMismatch, "merchantMismatch");
849
+ async function ingestFetched(ctx, row, clientId, order, target) {
850
+ const refusal = await refusalOf(ctx, clientId, order, target.externalMerchantId);
851
+ if (refusal) {
852
+ await settleInboxEvent(ctx, row.id, refusal.settle, refusal.reason);
853
+ if (!refusal.failed) return { kind: "skipped", reason: refusal.reason };
854
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} refused: ${refusal.reason}`);
855
+ return { kind: "failed", reason: refusal.reason };
856
+ }
857
+ const ingested = await ingestMarketplaceOrder(ctx, {
858
+ clientId,
859
+ order,
860
+ settings: { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
861
+ // The store's acceptance window starts when the event arrived, not when a
862
+ // delayed fetch finished: the marketplace's own clock started then.
863
+ clockStartsAt: row.receivedAt ?? void 0
864
+ });
865
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
866
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
867
+ await settleInboxEvent(ctx, row.id, "PROCESSED");
868
+ return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
869
+ }
870
+ __name(ingestFetched, "ingestFetched");
871
+ async function runFetchOrder(ctx, payload, attempt) {
872
+ const owed = await owedFetch(ctx, payload);
873
+ if (typeof owed === "string") return { kind: "skipped", reason: owed };
874
+ const { row, event } = owed;
875
+ const target = await resolveIngestionTarget(ctx, payload.clientId, event.provider);
876
+ if (!target?.enabled) {
877
+ await deferInboxEvent(ctx, row.id, "integration is not enabled");
878
+ return { kind: "skipped", reason: "integration is not enabled" };
879
+ }
880
+ const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
881
+ if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
882
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
883
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
884
+ throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
885
+ }
886
+ await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
887
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
888
+ return { kind: "failed", reason };
889
+ }
890
+ __name(runFetchOrder, "runFetchOrder");
891
+
250
892
  // src/core/outbound-sweep.ts
251
893
  var OUTBOUND_STALE_MS = 10 * 6e4;
252
894
  var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
@@ -329,137 +971,6 @@ async function sweepOutbound(ctx, now) {
329
971
  }
330
972
  __name(sweepOutbound, "sweepOutbound");
331
973
 
332
- // src/core/integration.ts
333
- var VIEW_SELECT = {
334
- provider: true,
335
- enabled: true,
336
- environment: true,
337
- status: true,
338
- externalMerchantId: true,
339
- autoAccept: true,
340
- ackSlaSeconds: true,
341
- credentials: true,
342
- lastEventAt: true,
343
- lastVerifiedAt: true,
344
- archivedAt: true
345
- };
346
- function toView(row) {
347
- return {
348
- provider: row.provider,
349
- enabled: row.enabled,
350
- environment: row.environment,
351
- status: row.status,
352
- externalMerchantId: row.externalMerchantId,
353
- autoAccept: row.autoAccept,
354
- ackSlaSeconds: row.ackSlaSeconds,
355
- connected: row.credentials !== "",
356
- lastEventAt: row.lastEventAt,
357
- lastVerifiedAt: row.lastVerifiedAt,
358
- archivedAt: row.archivedAt ?? null
359
- };
360
- }
361
- __name(toView, "toView");
362
- async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
363
- const db = await ctx.ports.db();
364
- const rows = await db.marketplaceIntegration.findMany({
365
- where: {
366
- clientId,
367
- ...options.providers ? { provider: { in: [...options.providers] } } : {},
368
- ...options.includeArchived ? {} : { archivedAt: null }
369
- },
370
- select: VIEW_SELECT,
371
- orderBy: { provider: "asc" }
372
- });
373
- return rows.map(toView);
374
- }
375
- __name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
376
- async function saveMarketplaceIntegration(ctx, input, db) {
377
- const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
378
- const mutable = {
379
- ...input.enabled === void 0 ? {} : { enabled: input.enabled },
380
- ...input.environment === void 0 ? {} : { environment: input.environment },
381
- ...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
382
- ...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
383
- ...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
384
- ...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED" }
385
- };
386
- const row = await db.marketplaceIntegration.upsert({
387
- where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
388
- create: {
389
- clientId: input.clientId,
390
- provider: input.provider,
391
- credentials: sealed ?? "",
392
- ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
393
- ...mutable
394
- },
395
- update: mutable,
396
- select: VIEW_SELECT
397
- });
398
- return toView(row);
399
- }
400
- __name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
401
- async function resolveIngestionTarget(ctx, clientId, provider) {
402
- const db = await ctx.ports.db();
403
- const row = await db.marketplaceIntegration.findUnique({
404
- where: { clientId_provider: { clientId, provider } },
405
- select: { enabled: true, autoAccept: true, ackSlaSeconds: true, credentials: true, archivedAt: true }
406
- });
407
- if (!row || row.archivedAt) return null;
408
- return {
409
- enabled: row.enabled,
410
- autoAccept: row.autoAccept,
411
- ackSlaSeconds: row.ackSlaSeconds,
412
- // An unopenable blob must not read as "no secret configured" — that would
413
- // turn a key-rotation problem into an endpoint that accepts unsigned
414
- // deliveries. The secrets port throws instead, and the caller answers 401.
415
- webhookSecret: row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret
416
- };
417
- }
418
- __name(resolveIngestionTarget, "resolveIngestionTarget");
419
- function openCredentials(ctx, sealed) {
420
- const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
421
- if (typeof parsed !== "object" || parsed === null) {
422
- throw new Error("Stored marketplace credentials are not an object.");
423
- }
424
- const record = parsed;
425
- return {
426
- clientId: String(record.clientId ?? ""),
427
- clientSecret: String(record.clientSecret ?? ""),
428
- webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
429
- };
430
- }
431
- __name(openCredentials, "openCredentials");
432
- async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
433
- const db = await ctx.ports.db();
434
- const rows = await db.marketplaceIntegration.findMany({
435
- where: { provider, externalMerchantId, archivedAt: null },
436
- select: { clientId: true },
437
- take: 1
438
- });
439
- return rows[0]?.clientId ?? null;
440
- }
441
- __name(resolveTenantByMerchant, "resolveTenantByMerchant");
442
- async function markMarketplaceEventSeen(db, clientId, provider, at) {
443
- await db.marketplaceIntegration.updateMany({
444
- where: { clientId, provider },
445
- data: { lastEventAt: at }
446
- });
447
- }
448
- __name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
449
- async function readOutboundConnection(ctx, clientId, provider) {
450
- const db = await ctx.ports.db();
451
- const row = await db.marketplaceIntegration.findUnique({
452
- where: { clientId_provider: { clientId, provider } },
453
- select: { environment: true, credentials: true }
454
- });
455
- if (!row || row.credentials === "") return null;
456
- return {
457
- environment: row.environment === "PRODUCTION" ? "PRODUCTION" : "SANDBOX",
458
- credentials: openCredentials(ctx, row.credentials)
459
- };
460
- }
461
- __name(readOutboundConnection, "readOutboundConnection");
462
-
463
974
  // src/core/outbound.ts
464
975
  var OutboundRetryError = class extends Error {
465
976
  static {
@@ -523,11 +1034,18 @@ async function stampCancellation(ctx, row, status, clientId) {
523
1034
  if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
524
1035
  }
525
1036
  __name(stampCancellation, "stampCancellation");
1037
+ function answerableRequest(row) {
1038
+ const waiting = { cancellationStatus: { in: ["PENDING", "FAILED"] } };
1039
+ if (row.cancellationRequestedAt === null) return [waiting];
1040
+ const tombstone = { status: "ACCEPTED", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };
1041
+ return [waiting, tombstone];
1042
+ }
1043
+ __name(answerableRequest, "answerableRequest");
526
1044
  async function stampConfirmedCancellation(ctx, row, clientId) {
527
1045
  const now = ctx.ports.clock.now();
528
1046
  const moved = await ctx.ports.transaction(async (tx) => {
529
1047
  const confirmed = await tx.marketplaceAcceptance.updateMany({
530
- where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "FAILED"] } },
1048
+ where: { orderId: row.orderId, OR: answerableRequest(row) },
531
1049
  data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null }
532
1050
  });
533
1051
  if (confirmed.count === 0) return false;
@@ -675,8 +1193,6 @@ __name(runOutbound, "runOutbound");
675
1193
 
676
1194
  export {
677
1195
  requestsFirst,
678
- rejectConfirmed,
679
- tellCancellationConfirmed,
680
1196
  tellCancellationFailed,
681
1197
  PROVIDER_ID_PATTERN,
682
1198
  MarketplaceAdapterRegistrationError,
@@ -690,18 +1206,35 @@ export {
690
1206
  refusalData,
691
1207
  requestData,
692
1208
  failCancellationRequest,
1209
+ listPendingAcceptances,
1210
+ expireLapsedAcceptances,
1211
+ cancelAcceptance,
693
1212
  listMarketplaceIntegrations,
694
1213
  saveMarketplaceIntegration,
1214
+ connectionMerchantId,
695
1215
  resolveIngestionTarget,
696
1216
  resolveTenantByMerchant,
697
- markMarketplaceEventSeen,
1217
+ listMarketplaceMenuLinks,
1218
+ upsertLink,
698
1219
  MARKETPLACE_OUTBOUND_JOB,
699
1220
  outboundDedupeKey,
700
1221
  enqueueOutbound,
1222
+ recordInboxEvent,
1223
+ settleInboxEvent,
1224
+ deferInboxEvent,
1225
+ listRetryableInboxEvents,
1226
+ ingestMarketplaceOrder,
1227
+ markCancelledBeforeIngest,
1228
+ MARKETPLACE_FETCH_ORDER_JOB,
1229
+ FetchOrderRetryError,
1230
+ awaitOrderBody,
1231
+ requeueOwedFetch,
1232
+ merchantMismatch,
1233
+ runFetchOrder,
701
1234
  OUTBOUND_STALE_MS,
702
1235
  OUTBOUND_GIVE_UP_MS,
703
1236
  sweepOutbound,
704
1237
  OutboundRetryError,
705
1238
  runOutbound
706
1239
  };
707
- //# sourceMappingURL=chunk-DVIRN42O.js.map
1240
+ //# sourceMappingURL=chunk-D2X7TOR6.js.map