@12-apps/marketplace 1.1.0 → 1.3.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 (92) hide show
  1. package/ADOPTING.md +37 -7
  2. package/README.md +238 -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 +162 -0
  7. package/dist/99food/index.js +444 -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-0l_EmuJA.d.ts} +206 -2
  13. package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
  14. package/dist/chunk-AYYBRQJV.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-M2V4RFMA.js +23 -0
  18. package/dist/chunk-M2V4RFMA.js.map +1 -0
  19. package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
  20. package/dist/chunk-RVBTARIY.js.map +1 -0
  21. package/dist/chunk-XUAFXNOH.js +1604 -0
  22. package/dist/chunk-XUAFXNOH.js.map +1 -0
  23. package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
  24. package/dist/hono/index.d.ts +2 -2
  25. package/dist/hono/index.js +2 -2
  26. package/dist/ifood/index.d.ts +16 -12
  27. package/dist/ifood/index.js +248 -121
  28. package/dist/ifood/index.js.map +1 -1
  29. package/dist/index.d.ts +30 -4
  30. package/dist/index.js +189 -346
  31. package/dist/index.js.map +1 -1
  32. package/dist/manifest/server.d.ts +4 -2
  33. package/dist/manifest/server.js +2 -2
  34. package/dist/rappi/en-US.d.ts +14 -0
  35. package/dist/rappi/en-US.js +18 -0
  36. package/dist/rappi/en-US.js.map +1 -0
  37. package/dist/rappi/index.d.ts +190 -0
  38. package/dist/rappi/index.js +359 -0
  39. package/dist/rappi/index.js.map +1 -0
  40. package/dist/rappi/pt-BR.d.ts +18 -0
  41. package/dist/rappi/pt-BR.js +18 -0
  42. package/dist/rappi/pt-BR.js.map +1 -0
  43. package/dist/server/index.d.ts +19 -8
  44. package/dist/server/index.js +4 -2
  45. package/package.json +26 -2
  46. package/prisma/marketplace.prisma +97 -2
  47. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  48. package/src/99food/catalogue.ts +117 -0
  49. package/src/99food/copy.ts +36 -0
  50. package/src/99food/en-US.ts +19 -0
  51. package/src/99food/index.ts +125 -0
  52. package/src/99food/normalize.ts +263 -0
  53. package/src/99food/outbound.ts +220 -0
  54. package/src/99food/pt-BR.ts +23 -0
  55. package/src/core/adapter.ts +27 -2
  56. package/src/core/catalogue-category.ts +119 -0
  57. package/src/core/catalogue-ids.ts +23 -0
  58. package/src/core/catalogue-job.ts +332 -0
  59. package/src/core/catalogue-port.ts +173 -0
  60. package/src/core/catalogue-store.ts +172 -0
  61. package/src/core/catalogue-sweep.ts +43 -0
  62. package/src/core/catalogue.ts +226 -0
  63. package/src/core/decisions.ts +16 -4
  64. package/src/core/engine.ts +54 -0
  65. package/src/core/fetch-order.ts +253 -0
  66. package/src/core/inbox.ts +8 -2
  67. package/src/core/ingest.ts +10 -2
  68. package/src/core/integration.ts +30 -1
  69. package/src/core/order-fetch-marks.ts +63 -0
  70. package/src/core/outbound-sweep.ts +7 -2
  71. package/src/core/outbound.ts +22 -2
  72. package/src/core/payload-read.ts +101 -0
  73. package/src/core/pipeline.ts +64 -15
  74. package/src/core/ports.ts +36 -0
  75. package/src/core/types.ts +14 -0
  76. package/src/ifood/catalogue.ts +273 -0
  77. package/src/ifood/index.ts +4 -0
  78. package/src/ifood/normalize.ts +15 -88
  79. package/src/ifood/outbound.ts +9 -6
  80. package/src/index.ts +49 -1
  81. package/src/rappi/copy.ts +39 -0
  82. package/src/rappi/en-US.ts +14 -0
  83. package/src/rappi/index.ts +161 -0
  84. package/src/rappi/normalize.ts +314 -0
  85. package/src/rappi/outbound.ts +182 -0
  86. package/src/rappi/pt-BR.ts +18 -0
  87. package/src/server/index.ts +1 -0
  88. package/src/server/jobs.ts +71 -8
  89. package/dist/chunk-7BYVGNU5.js.map +0 -1
  90. package/dist/chunk-DVIRN42O.js +0 -707
  91. package/dist/chunk-DVIRN42O.js.map +0 -1
  92. package/dist/chunk-NGNEL4HS.js.map +0 -1
@@ -20,6 +20,24 @@ import {
20
20
  type DecisionInput,
21
21
  type DecisionResult,
22
22
  } from "./decisions";
23
+ import {
24
+ publishToCatalogue,
25
+ readCatalogueDocument,
26
+ readCatalogueState,
27
+ withdrawFromCatalogue,
28
+ type CatalogueActionResult,
29
+ type CatalogueDocumentResult,
30
+ type CataloguePublishInput,
31
+ type CatalogueTarget,
32
+ } from "./catalogue";
33
+ import { runCatalogue, type CatalogueJobPayload, type CatalogueOutcome } from "./catalogue-job";
34
+ import type { CatalogueMenuOptions } from "./catalogue-port";
35
+ import type { CataloguePublicationView } from "./catalogue-store";
36
+ import {
37
+ runFetchOrder,
38
+ type FetchOrderJobPayload,
39
+ type FetchOrderOutcome,
40
+ } from "./fetch-order";
23
41
  import { sweepOutbound, type OutboundSweepResult } from "./outbound-sweep";
24
42
  import type {
25
43
  AdapterTokenCache,
@@ -163,6 +181,33 @@ export interface MarketplaceEngine {
163
181
  sweepOutbound(now?: Date): Promise<OutboundSweepResult>;
164
182
  /** Run one queued outbound call (the `marketplace.outbound` job's body). */
165
183
  runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;
184
+ /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */
185
+ runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;
186
+
187
+ /**
188
+ * How this marketplace's catalogue is published (`push`, `pull`), or null
189
+ * when it cannot be: the adapter states no catalogue, or the host bound no
190
+ * catalogue port (FUT-4768).
191
+ */
192
+ catalogueMode(provider: string): "push" | "pull" | null;
193
+ /** Put a product in a marketplace's catalogue (or send it again), with an optional price for it. Queued. */
194
+ publish(input: CataloguePublishInput): Promise<CatalogueActionResult>;
195
+ /** Take a product out of a marketplace's catalogue. Queued. */
196
+ withdraw(input: CatalogueTarget): Promise<CatalogueActionResult>;
197
+ /** Where these products stand on these marketplaces, in one read. */
198
+ catalogueState(input: {
199
+ clientId: string;
200
+ productIds: readonly string[];
201
+ providers?: readonly string[];
202
+ }): Promise<CataloguePublicationView[]>;
203
+ /** The menu part of the document a PULL marketplace reads, for the host to serve. */
204
+ catalogueDocument(input: {
205
+ clientId: string;
206
+ provider: MarketplaceProvider;
207
+ options: CatalogueMenuOptions;
208
+ }): Promise<CatalogueDocumentResult>;
209
+ /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
210
+ runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
166
211
  }
167
212
 
168
213
  /**
@@ -225,5 +270,14 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
225
270
  reprocess: (event) => reprocessStoredDelivery(ctx, event),
226
271
  sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),
227
272
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
273
+ runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
274
+
275
+ // Null too when the host bound no catalogue port: nothing could be published.
276
+ catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
277
+ publish: (input) => publishToCatalogue(ctx, input),
278
+ withdraw: (input) => withdrawFromCatalogue(ctx, input),
279
+ catalogueState: (input) => readCatalogueState(ctx, input),
280
+ catalogueDocument: (input) => readCatalogueDocument(ctx, input),
281
+ runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),
228
282
  };
229
283
  }
@@ -0,0 +1,253 @@
1
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
+ import { ingestMarketplaceOrder } from "./ingest";
3
+ import { readOutboundConnection, resolveIngestionTarget } from "./integration";
4
+ import type { FetchOrderResult } from "./adapter";
5
+ import { cancelAcceptance } from "./acceptance";
6
+ import { cancelledBeforeIngest } from "./order-fetch-marks";
7
+ import type { EngineContext } from "./ports";
8
+ import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
9
+
10
+ /**
11
+ * Fetching an order the event only announced — the engine's half of a
12
+ * marketplace whose events carry no order body (Open Delivery's `CREATED`).
13
+ *
14
+ * The rule this keeps: no path that answers a request calls a marketplace. So
15
+ * the webhook only RECORDS the delivery (PENDING, "order details to fetch")
16
+ * and queues `marketplace.fetch-order`; the job reads the row, asks the
17
+ * adapter's `fetchOrder` through the host's HTTP port with the store's own
18
+ * credentials, and ingests what comes back through the one ingest path. The
19
+ * inbox reconciliation sweep re-queues the job for a row that is still owed
20
+ * once it is older than the job's own retry span ({@link FETCH_REQUEUE_AGE_MS}),
21
+ * so a refused enqueue or a dead worker loses nothing — and it never fetches
22
+ * itself, so a host that holds the job (its enqueue port answers "held")
23
+ * holds every fetch.
24
+ *
25
+ * Two things are judged before a fetched order is ingested: a cancellation
26
+ * that outran the fetch (`./order-fetch-marks.ts`) wins, and an order naming a
27
+ * merchant other than the connection's is refused.
28
+ *
29
+ * Nothing here knows a marketplace: which events need a fetch is the adapter's
30
+ * `orderToFetch`, and how to fetch is its `fetchOrder`.
31
+ */
32
+
33
+ /** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */
34
+ export const MARKETPLACE_FETCH_ORDER_JOB = "marketplace.fetch-order";
35
+
36
+ /** The job's payload. Identifiers only: the event itself is the inbox row's. */
37
+ export interface FetchOrderJobPayload {
38
+ clientId: string;
39
+ inboxId: string;
40
+ }
41
+
42
+ /** What one run did. */
43
+ export type FetchOrderOutcome =
44
+ | { kind: "skipped"; reason: string }
45
+ | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
46
+ | { kind: "failed"; reason: string };
47
+
48
+ /** Thrown so the queue retries the fetch. Its message is what the job log reads. */
49
+ export class FetchOrderRetryError extends Error {
50
+ constructor(message: string) {
51
+ super(message);
52
+ this.name = "FetchOrderRetryError";
53
+ }
54
+ }
55
+
56
+ /** The reason a recorded row waits for its fetch. */
57
+ const AWAITING_ORDER_REASON = "order details to fetch";
58
+
59
+ /**
60
+ * A row waiting for its fetch is left alone by the reconciliation sweep this
61
+ * long: the job's own three attempts (5 s, then 10 s apart) finish well inside
62
+ * it. Past it the sweep re-queues, and only then counts an attempt, so a slow
63
+ * queue never spends the row's attempts while its first job still waits.
64
+ */
65
+ export const FETCH_REQUEUE_AGE_MS = 2 * 60_000;
66
+
67
+ /**
68
+ * Leave the row PENDING for its fetch and queue the job. The queue port never
69
+ * throws; a refusal is logged and recovered by the reconciliation sweep.
70
+ * `dedupeKey` defaults to the row's own; a re-queue passes a fresh one, since
71
+ * a queue may keep a finished job's id and swallow a re-queue under it.
72
+ */
73
+ export async function awaitOrderBody(
74
+ ctx: EngineContext,
75
+ clientId: string,
76
+ inboxId: string,
77
+ dedupeKey: string = `${MARKETPLACE_FETCH_ORDER_JOB}:${inboxId}`,
78
+ ): Promise<void> {
79
+ await deferInboxEvent(ctx, inboxId, AWAITING_ORDER_REASON);
80
+ const payload: FetchOrderJobPayload = { clientId, inboxId };
81
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_FETCH_ORDER_JOB, payload, { dedupeKey });
82
+ if (!outcome.enqueued) {
83
+ ctx.ports.logger.warn(
84
+ `${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${inboxId} was not queued; the reconciliation sweep will re-queue it` +
85
+ (outcome.reason ? ` (${outcome.reason})` : ""),
86
+ );
87
+ }
88
+ }
89
+
90
+ /**
91
+ * The reconciliation sweep's answer to a row still waiting for its order body:
92
+ * untouched while younger than {@link FETCH_REQUEUE_AGE_MS} (no attempt
93
+ * counted, nothing queued), else re-queued under a fresh key with a warning,
94
+ * so a hold or a dead worker is visible rather than silent.
95
+ */
96
+ export async function requeueOwedFetch(
97
+ ctx: EngineContext,
98
+ input: { id: string; clientId: string; receivedAt?: Date | null },
99
+ ): Promise<{ kind: "awaitingOrder" }> {
100
+ const now = ctx.ports.clock.now();
101
+ const age = input.receivedAt ? now.getTime() - input.receivedAt.getTime() : Number.POSITIVE_INFINITY;
102
+ if (age < FETCH_REQUEUE_AGE_MS) return { kind: "awaitingOrder" };
103
+ ctx.ports.logger.warn(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${input.id} still waits for its order body; re-queued`);
104
+ await awaitOrderBody(ctx, input.clientId, input.id, `${MARKETPLACE_FETCH_ORDER_JOB}:${input.id}:${now.getTime()}`);
105
+ return { kind: "awaitingOrder" };
106
+ }
107
+
108
+ interface InboxRow {
109
+ id: string;
110
+ clientId: string | null;
111
+ provider: string;
112
+ payload: unknown;
113
+ status: string;
114
+ receivedAt: Date | null;
115
+ }
116
+
117
+ /** The recorded row and its event, or why there is nothing to fetch. */
118
+ async function owedFetch(
119
+ ctx: EngineContext,
120
+ payload: FetchOrderJobPayload,
121
+ ): Promise<{ row: InboxRow; event: NormalizedEvent } | string> {
122
+ const db = await ctx.ports.db();
123
+ const row = (await db.marketplaceInboxEvent.findUnique({
124
+ where: { id: payload.inboxId },
125
+ select: { id: true, clientId: true, provider: true, payload: true, status: true, receivedAt: true },
126
+ })) as InboxRow | null;
127
+ if (!row || row.clientId !== payload.clientId) return "no such inbox row for this tenant";
128
+ if (row.status !== "PENDING" && row.status !== "FAILED") return `the row is already ${row.status}`;
129
+ const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
130
+ if (!event?.orderToFetch || event.order) return "the event announces no order to fetch";
131
+ return { row, event };
132
+ }
133
+
134
+ /** One call to the adapter, or the refusal that stands in for it. */
135
+ async function fetchThroughAdapter(
136
+ ctx: EngineContext,
137
+ clientId: string,
138
+ provider: MarketplaceProvider,
139
+ externalOrderId: string,
140
+ ): Promise<FetchOrderResult> {
141
+ const adapter = ctx.registry.get(provider);
142
+ if (!adapter?.fetchOrder) return { kind: "refused", status: 0, message: `${provider} cannot fetch an order` };
143
+ let connection;
144
+ try {
145
+ connection = await readOutboundConnection(ctx, clientId, provider);
146
+ } catch (error) {
147
+ const reason = error instanceof Error ? error.message : String(error);
148
+ return { kind: "refused", status: 0, message: `credentials do not open: ${reason}` };
149
+ }
150
+ if (!connection) return { kind: "refused", status: 0, message: "no credentials on file" };
151
+ try {
152
+ return await adapter.fetchOrder(
153
+ { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection },
154
+ { externalOrderId },
155
+ );
156
+ } catch (error) {
157
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Why a fetched order must not be ingested, or null. A cancellation recorded
163
+ * before the body arrived wins: the order is cancelled, so no pedido and no
164
+ * confirm. An order naming another merchant than the connection's is someone
165
+ * else's order delivered to this store's URL (a wrong webhook URL, a replay).
166
+ */
167
+ async function refusalOf(
168
+ ctx: EngineContext,
169
+ clientId: string,
170
+ order: NormalizedMarketplaceOrder,
171
+ connectionMerchantId: string | null,
172
+ ): Promise<{ settle: "IGNORED" | "FAILED"; reason: string; failed: boolean } | null> {
173
+ if (await cancelledBeforeIngest(ctx, { clientId, provider: order.provider, externalOrderId: order.externalOrderId })) {
174
+ return { settle: "IGNORED", reason: "cancelled before its order body arrived", failed: false };
175
+ }
176
+ const mismatch = merchantMismatch(order, connectionMerchantId);
177
+ // FAILED, not IGNORED: a connection whose merchant id was entered wrong is
178
+ // corrected, and the reconciliation sweep then retries within its bound.
179
+ return mismatch ? { settle: "FAILED", reason: mismatch, failed: true } : null;
180
+ }
181
+
182
+ /**
183
+ * Why an order naming a merchant cannot be this connection's, or null. An
184
+ * order that names none, or a connection that states none, is not judged.
185
+ * Shared by the fetched path and an order the event carries (`./pipeline.ts`).
186
+ */
187
+ export function merchantMismatch(order: NormalizedMarketplaceOrder, connectionMerchantId: string | null): string | null {
188
+ const named = order.externalMerchantId ?? null;
189
+ if (named === null || connectionMerchantId === null || named === connectionMerchantId) return null;
190
+ return `the order names merchant ${named}, not this connection's`;
191
+ }
192
+
193
+ /** Ingest a fetched order, unless {@link refusalOf} says otherwise. */
194
+ async function ingestFetched(
195
+ ctx: EngineContext,
196
+ row: InboxRow,
197
+ clientId: string,
198
+ order: NormalizedMarketplaceOrder,
199
+ target: { autoAccept: boolean; ackSlaSeconds: number; externalMerchantId: string | null },
200
+ ): Promise<FetchOrderOutcome> {
201
+ const refusal = await refusalOf(ctx, clientId, order, target.externalMerchantId);
202
+ if (refusal) {
203
+ await settleInboxEvent(ctx, row.id, refusal.settle, refusal.reason);
204
+ if (!refusal.failed) return { kind: "skipped", reason: refusal.reason };
205
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} refused: ${refusal.reason}`);
206
+ return { kind: "failed", reason: refusal.reason };
207
+ }
208
+ const ingested = await ingestMarketplaceOrder(ctx, {
209
+ clientId,
210
+ order,
211
+ settings: { autoAccept: target.autoAccept, ackSlaSeconds: target.ackSlaSeconds },
212
+ // The store's acceptance window starts when the event arrived, not when a
213
+ // delayed fetch finished: the marketplace's own clock started then.
214
+ clockStartsAt: row.receivedAt ?? undefined,
215
+ });
216
+ // A CANCELLED that read the acceptances while this ingest's transaction was
217
+ // still open found none and left its marker: honour it now, through the
218
+ // ordinary cancel path (the order is cancelled; no confirm is owed).
219
+ const ref = { clientId, provider: order.provider, externalOrderId: order.externalOrderId };
220
+ if (await cancelledBeforeIngest(ctx, ref)) await cancelAcceptance(ctx, ref);
221
+ await settleInboxEvent(ctx, row.id, "PROCESSED");
222
+ return { kind: "ingested", orderId: ingested.orderId, unmappedSkus: ingested.unmappedSkus };
223
+ }
224
+
225
+ /**
226
+ * Run one queued fetch. Returns what it did; throws {@link FetchOrderRetryError}
227
+ * for an answer worth retrying before the last attempt. A refusal, or the last
228
+ * attempt's retry, settles the row FAILED: the reconciliation sweep re-queues
229
+ * it within the inbox's attempt bound.
230
+ */
231
+ export async function runFetchOrder(
232
+ ctx: EngineContext,
233
+ payload: FetchOrderJobPayload,
234
+ attempt: { attempt: number; maxAttempts: number },
235
+ ): Promise<FetchOrderOutcome> {
236
+ const owed = await owedFetch(ctx, payload);
237
+ if (typeof owed === "string") return { kind: "skipped", reason: owed };
238
+ const { row, event } = owed;
239
+ const target = await resolveIngestionTarget(ctx, payload.clientId, event.provider);
240
+ if (!target?.enabled) {
241
+ await deferInboxEvent(ctx, row.id, "integration is not enabled");
242
+ return { kind: "skipped", reason: "integration is not enabled" };
243
+ }
244
+ const result = await fetchThroughAdapter(ctx, payload.clientId, event.provider, event.externalOrderId ?? "");
245
+ if (result.kind === "order") return ingestFetched(ctx, row, payload.clientId, result.order, target);
246
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
247
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
248
+ throw new FetchOrderRetryError(`fetch of ${event.externalOrderId ?? "?"} (inbox ${row.id}): ${reason}`);
249
+ }
250
+ await settleInboxEvent(ctx, row.id, "FAILED", `order fetch failed: ${reason}`);
251
+ ctx.ports.logger.error(`${MARKETPLACE_FETCH_ORDER_JOB}: inbox row ${row.id} failed: ${reason}`);
252
+ return { kind: "failed", reason };
253
+ }
package/src/core/inbox.ts CHANGED
@@ -53,6 +53,9 @@ export async function recordInboxEvent(
53
53
  eventType: input.event.eventType,
54
54
  externalOrderId: input.event.externalOrderId,
55
55
  payload: input.payload,
56
+ // The engine's clock, not the database's: an announced order's
57
+ // acceptance window counts from here (`./fetch-order.ts`).
58
+ receivedAt: ctx.ports.clock.now(),
56
59
  },
57
60
  select: { id: true },
58
61
  })) as { id: string };
@@ -136,6 +139,8 @@ export interface PendingInboxEvent {
136
139
  clientId: string;
137
140
  provider: MarketplaceProvider;
138
141
  payload: unknown;
142
+ /** When the delivery was recorded. */
143
+ receivedAt?: Date | null;
139
144
  }
140
145
 
141
146
  /**
@@ -161,12 +166,13 @@ export async function listRetryableInboxEvents(
161
166
  },
162
167
  orderBy: { receivedAt: "asc" },
163
168
  take: ctx.ports.reconcileBatchSize,
164
- select: { id: true, clientId: true, provider: true, payload: true },
165
- })) as { id: string; clientId: string; provider: string; payload: unknown }[];
169
+ select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true },
170
+ })) as { id: string; clientId: string; provider: string; payload: unknown; receivedAt: Date | null }[];
166
171
  return rows.map((row) => ({
167
172
  id: row.id,
168
173
  clientId: row.clientId,
169
174
  provider: row.provider as MarketplaceProvider,
170
175
  payload: row.payload,
176
+ receivedAt: row.receivedAt,
171
177
  }));
172
178
  }
@@ -80,6 +80,7 @@ function acceptanceData(
80
80
  order: NormalizedMarketplaceOrder,
81
81
  settings: IngestSettings,
82
82
  now: Date,
83
+ clockStartsAt: Date,
83
84
  ): Record<string, unknown> {
84
85
  const accepted = settings.autoAccept;
85
86
  return {
@@ -91,7 +92,7 @@ function acceptanceData(
91
92
  // Who carries a delivery: the merchant's courier or the marketplace's fleet.
92
93
  deliveredBy: order.deliveredBy ?? null,
93
94
  status: accepted ? "ACCEPTED" : "AWAITING",
94
- acknowledgeBy: new Date(now.getTime() + settings.ackSlaSeconds * 1000),
95
+ acknowledgeBy: new Date(clockStartsAt.getTime() + settings.ackSlaSeconds * 1000),
95
96
  acknowledgedAt: accepted ? now : null,
96
97
  externalDueAt: order.deliveryDueAt,
97
98
  commissionCents: order.commissionCents,
@@ -122,10 +123,17 @@ export async function ingestMarketplaceOrder(
122
123
  order: NormalizedMarketplaceOrder;
123
124
  settings: IngestSettings;
124
125
  now?: Date;
126
+ /**
127
+ * When the acceptance window started, if not `now`: the arrival of the
128
+ * event that announced an order fetched later. Moves ONLY the deadline;
129
+ * the liveness stamp and an auto-accept's time stay `now`.
130
+ */
131
+ clockStartsAt?: Date;
125
132
  },
126
133
  ): Promise<IngestResult> {
127
134
  const { clientId, order, settings } = input;
128
135
  const now = input.now ?? ctx.ports.clock.now();
136
+ const clockStartsAt = input.clockStartsAt ?? now;
129
137
 
130
138
  const db = await ctx.ports.db();
131
139
  // Answered from this package's OWN table rather than through a port: the
@@ -148,7 +156,7 @@ export async function ingestMarketplaceOrder(
148
156
  const { orderId, unmappedSkus } = await ctx.ports.transaction(async (tx) => {
149
157
  const lines = await composeLines(tx, clientId, order, now);
150
158
  const created = await ctx.ports.order.create(clientId, order, lines, tx);
151
- await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now) });
159
+ await tx.marketplaceAcceptance.create({ data: acceptanceData(clientId, created, order, settings, now, clockStartsAt) });
152
160
  await markMarketplaceEventSeen(tx, clientId, order.provider, now);
153
161
  return { orderId: created, unmappedSkus: lines.filter((l) => l.subjectRef === null).map((l) => l.externalSku) };
154
162
  });
@@ -168,6 +168,26 @@ export interface IngestionTarget {
168
168
  autoAccept: boolean;
169
169
  ackSlaSeconds: number;
170
170
  webhookSecret: string | null;
171
+ /** The merchant the store connected; a fetched order naming another is refused. */
172
+ externalMerchantId: string | null;
173
+ }
174
+
175
+ /**
176
+ * The merchant id a store's live connection states, read alone: no
177
+ * credentials are opened. Null when it states none, or when there is no live
178
+ * connection (archived or absent).
179
+ */
180
+ export async function connectionMerchantId(
181
+ ctx: EngineContext,
182
+ clientId: string,
183
+ provider: MarketplaceProvider,
184
+ ): Promise<string | null> {
185
+ const db = await ctx.ports.db();
186
+ const row = (await db.marketplaceIntegration.findUnique({
187
+ where: { clientId_provider: { clientId, provider } },
188
+ select: { externalMerchantId: true, archivedAt: true },
189
+ })) as { externalMerchantId: string | null; archivedAt: Date | null } | null;
190
+ return row && !row.archivedAt ? (row.externalMerchantId ?? null) : null;
171
191
  }
172
192
 
173
193
  /**
@@ -188,8 +208,16 @@ export async function resolveIngestionTarget(
188
208
  const db = await ctx.ports.db();
189
209
  const row = (await db.marketplaceIntegration.findUnique({
190
210
  where: { clientId_provider: { clientId, provider } },
191
- select: { enabled: true, autoAccept: true, ackSlaSeconds: true, credentials: true, archivedAt: true },
211
+ select: {
212
+ enabled: true,
213
+ autoAccept: true,
214
+ ackSlaSeconds: true,
215
+ credentials: true,
216
+ archivedAt: true,
217
+ externalMerchantId: true,
218
+ },
192
219
  })) as {
220
+ externalMerchantId: string | null;
193
221
  enabled: boolean;
194
222
  autoAccept: boolean;
195
223
  ackSlaSeconds: number;
@@ -202,6 +230,7 @@ export async function resolveIngestionTarget(
202
230
  enabled: row.enabled,
203
231
  autoAccept: row.autoAccept,
204
232
  ackSlaSeconds: row.ackSlaSeconds,
233
+ externalMerchantId: row.externalMerchantId ?? null,
205
234
  // An unopenable blob must not read as "no secret configured" — that would
206
235
  // turn a key-rotation problem into an endpoint that accepts unsigned
207
236
  // deliveries. The secrets port throws instead, and the caller answers 401.
@@ -0,0 +1,63 @@
1
+ import type { EngineContext } from "./ports";
2
+ import type { MarketplaceProvider } from "./types";
3
+
4
+ /**
5
+ * A cancellation that outran its order's body.
6
+ *
7
+ * For a marketplace whose events only announce an order (`fetchOrder`), the
8
+ * marketplace's CANCELLED can arrive while the fetch is still queued, held or
9
+ * retrying, and the fetched body (Open Delivery's `Order` has no status) cannot
10
+ * say the order was cancelled. Without a trace the fetch would then ingest a
11
+ * cancelled order, send it to the kitchen and confirm it.
12
+ *
13
+ * So when a cancellation finds no acceptance to cancel, it leaves a MARKER: an
14
+ * IGNORED inbox row under a key derived from the order (`engine:cancelled:<id>`),
15
+ * found again through the inbox's own unique `(provider, eventId)` index, with
16
+ * no new column or table. The fetch reads it before it ingests.
17
+ */
18
+
19
+ const MARKER_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
20
+
21
+ const markerId = (externalOrderId: string): string => `engine:cancelled:${externalOrderId}`;
22
+
23
+ /** Leave the marker, for an adapter that fetches its orders. Idempotent. */
24
+ export async function markCancelledBeforeIngest(
25
+ ctx: EngineContext,
26
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
27
+ ): Promise<void> {
28
+ if (!ctx.registry.get(input.provider)?.fetchOrder) return;
29
+ const db = await ctx.ports.db();
30
+ try {
31
+ await db.marketplaceInboxEvent.create({
32
+ data: {
33
+ clientId: input.clientId,
34
+ provider: input.provider,
35
+ eventId: markerId(input.externalOrderId),
36
+ eventType: MARKER_TYPE,
37
+ externalOrderId: input.externalOrderId,
38
+ payload: {},
39
+ status: "IGNORED",
40
+ error: "cancelled before the order was ingested",
41
+ receivedAt: ctx.ports.clock.now(),
42
+ processedAt: ctx.ports.clock.now(),
43
+ },
44
+ select: { id: true },
45
+ });
46
+ } catch (error) {
47
+ // A redelivered cancellation: the marker is already there.
48
+ if ((error as { code?: string }).code !== "P2002") throw error;
49
+ }
50
+ }
51
+
52
+ /** Whether this store's order was cancelled before it was ingested. */
53
+ export async function cancelledBeforeIngest(
54
+ ctx: EngineContext,
55
+ input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
56
+ ): Promise<boolean> {
57
+ const db = await ctx.ports.db();
58
+ const row = (await db.marketplaceInboxEvent.findUnique({
59
+ where: { provider_eventId: { provider: input.provider, eventId: markerId(input.externalOrderId) } },
60
+ select: { clientId: true },
61
+ })) as { clientId: string | null } | null;
62
+ return row !== null && row.clientId === input.clientId;
63
+ }
@@ -1,4 +1,5 @@
1
1
  import { NO_STANDING_REQUEST } from "./cancellation";
2
+ import { sweepCatalogue } from "./catalogue-sweep";
2
3
  import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
3
4
  import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
4
5
  import type { EngineContext } from "./ports";
@@ -55,6 +56,8 @@ export interface OutboundSweepResult {
55
56
  givenUp: number;
56
57
  /** Requests failed as TIMEOUT past their marketplace's answer window. */
57
58
  timedOut: number;
59
+ /** Catalogue publishes and withdraws still owed, re-queued (FUT-4768). */
60
+ catalogueRequeued: number;
58
61
  }
59
62
 
60
63
  /** A store's cancellation request still waiting on the marketplace. */
@@ -136,7 +139,8 @@ async function expireUnanswered(ctx: EngineContext, now: Date): Promise<number>
136
139
 
137
140
  /**
138
141
  * One sweep pass: expire the requests nobody answered, give up on the very old,
139
- * and re-queue what is still owed.
142
+ * and re-queue what is still owed, the catalogue's publishes and withdraws
143
+ * included (`./catalogue-sweep.ts`).
140
144
  */
141
145
  export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<OutboundSweepResult> {
142
146
  const db = await ctx.ports.db();
@@ -165,5 +169,6 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
165
169
  const requeued =
166
170
  (await requeue(ctx, cancellations, "requestCancellation", now)) + (await requeue(ctx, confirms, "confirm", now));
167
171
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
168
- return { requeued, givenUp, timedOut };
172
+ const catalogueRequeued = await sweepCatalogue(ctx, now);
173
+ return { requeued, givenUp, timedOut, catalogueRequeued };
169
174
  }
@@ -144,6 +144,22 @@ async function stampCancellation(
144
144
  if (moved.count > 0 && status === "FAILED") await tellCancellationFailed(ctx, clientId, row.orderId, "REFUSED");
145
145
  }
146
146
 
147
+ /**
148
+ * Which rows a synchronous "cancelled" answers: the request still waiting or
149
+ * FAILED, or the tombstone an accept left of THIS request (no status, the
150
+ * same `cancellation_requested_at` the job read) on an order STILL ACCEPTED.
151
+ * A later request of the store carries a new instant and a status of its own,
152
+ * so it is never mistaken for it; and once the marketplace's own cancel event
153
+ * has moved the order to REJECTED (and told the host), the tombstone answers
154
+ * nothing more, so the host is never told twice.
155
+ */
156
+ function answerableRequest(row: OutboundRow): Record<string, unknown>[] {
157
+ const waiting = { cancellationStatus: { in: ["PENDING", "FAILED"] } };
158
+ if (row.cancellationRequestedAt === null) return [waiting];
159
+ const tombstone = { status: "ACCEPTED", cancellationStatus: null, cancellationRequestedAt: row.cancellationRequestedAt };
160
+ return [waiting, tombstone];
161
+ }
162
+
147
163
  /**
148
164
  * A marketplace that confirms in its answer: the same stamps as its
149
165
  * CANCELLED event (`cancelAcceptance`) — CONFIRMED and REJECTED in one
@@ -157,9 +173,13 @@ async function stampConfirmedCancellation(ctx: EngineContext, row: OutboundRow,
157
173
  // From FAILED too: the sweep may have timed the request out while this
158
174
  // call was in flight, and a marketplace that answers in the response sends
159
175
  // no event — its "cancelled" is the only word that it did (the event path's
160
- // own rule: a confirmation after a TIMEOUT still confirms).
176
+ // own rule: a confirmation after a TIMEOUT still confirms). And from the
177
+ // TOMBSTONE of this same request (FUT-4765, R3-N2): the store may have
178
+ // accepted the order once the request timed out, which clears the request
179
+ // but keeps its `cancellation_requested_at`. The order is cancelled on the
180
+ // marketplace, so it is cancelled here too, and the host hears it.
161
181
  const confirmed = await tx.marketplaceAcceptance.updateMany({
162
- where: { orderId: row.orderId, cancellationStatus: { in: ["PENDING", "FAILED"] } },
182
+ where: { orderId: row.orderId, OR: answerableRequest(row) },
163
183
  data: { cancellationStatus: "CONFIRMED", cancellationFailureReason: null },
164
184
  });
165
185
  if (confirmed.count === 0) return false;