@12-apps/marketplace 1.16.0 → 1.18.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 (79) hide show
  1. package/ADOPTING.md +185 -0
  2. package/dist/99food/index.d.ts +2 -2
  3. package/dist/99food/index.js +2 -2
  4. package/dist/{adapter-CjVdMhZ2.d.ts → adapter-ZpAWKoCk.d.ts} +300 -3
  5. package/dist/{chunk-TRUK5ZBE.js → chunk-3B5EULS6.js} +2 -2
  6. package/dist/{chunk-DJIMUEHT.js → chunk-BLHZ3MRB.js} +79 -7
  7. package/dist/chunk-BLHZ3MRB.js.map +1 -0
  8. package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
  9. package/dist/chunk-LO7OKO6V.js.map +1 -0
  10. package/dist/{chunk-TICWLBSA.js → chunk-MDEIRGNL.js} +1372 -823
  11. package/dist/chunk-MDEIRGNL.js.map +1 -0
  12. package/dist/{chunk-H2VQRD3B.js → chunk-Q5RMVNU5.js} +1 -1
  13. package/dist/chunk-Q5RMVNU5.js.map +1 -0
  14. package/dist/{chunk-BTKVZAJI.js → chunk-ZT6TZTLD.js} +1 -1
  15. package/dist/chunk-ZT6TZTLD.js.map +1 -0
  16. package/dist/{client-DgzCkl8u.d.ts → client-DpEq0yXb.d.ts} +1 -1
  17. package/dist/{engine-DSRj7qnC.d.ts → engine-DRRhAjZK.d.ts} +566 -293
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +4 -4
  20. package/dist/ifood/index.d.ts +14 -2
  21. package/dist/ifood/index.js +406 -120
  22. package/dist/ifood/index.js.map +1 -1
  23. package/dist/index.d.ts +21 -4
  24. package/dist/index.js +453 -43
  25. package/dist/index.js.map +1 -1
  26. package/dist/keeta/index.d.ts +2 -2
  27. package/dist/keeta/index.js +2 -2
  28. package/dist/manifest/index.d.ts +78 -0
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +6 -2
  31. package/dist/manifest/server.js +4 -4
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/index.d.ts +93 -7
  35. package/dist/server/index.js +4 -4
  36. package/package.json +1 -1
  37. package/prisma/marketplace.prisma +70 -2
  38. package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
  39. package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
  40. package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
  41. package/src/core/adapter.ts +14 -2
  42. package/src/core/app-linking.ts +396 -0
  43. package/src/core/delivery-code.ts +119 -0
  44. package/src/core/dispute-engine.ts +32 -0
  45. package/src/core/dispute-job.ts +142 -0
  46. package/src/core/dispute-port.ts +133 -0
  47. package/src/core/dispute-store.ts +203 -0
  48. package/src/core/disputes.ts +263 -0
  49. package/src/core/engine.ts +12 -55
  50. package/src/core/integration.ts +3 -1
  51. package/src/core/link-engine.ts +176 -0
  52. package/src/core/link-store.ts +15 -0
  53. package/src/core/linking-port.ts +35 -1
  54. package/src/core/linking.ts +8 -0
  55. package/src/core/logistics.ts +388 -0
  56. package/src/core/outbound-queue.ts +6 -1
  57. package/src/core/outbound-sweep.ts +19 -6
  58. package/src/core/outbound.ts +4 -5
  59. package/src/core/pipeline.ts +14 -4
  60. package/src/core/ports.ts +20 -2
  61. package/src/core/status-job.ts +3 -0
  62. package/src/core/status-store.ts +2 -1
  63. package/src/core/types.ts +10 -0
  64. package/src/ifood/app-linking.ts +119 -0
  65. package/src/ifood/disputes.ts +209 -0
  66. package/src/ifood/index.ts +15 -1
  67. package/src/ifood/logistics.ts +38 -0
  68. package/src/ifood/normalize.ts +14 -1
  69. package/src/index.ts +44 -0
  70. package/src/server/jobs.ts +51 -3
  71. package/src/server/link-routes.ts +56 -4
  72. package/src/server/mcp-link.ts +44 -2
  73. package/src/server/mcp.ts +2 -1
  74. package/dist/chunk-BTKVZAJI.js.map +0 -1
  75. package/dist/chunk-DJIMUEHT.js.map +0 -1
  76. package/dist/chunk-H2VQRD3B.js.map +0 -1
  77. package/dist/chunk-SGOTN5PX.js.map +0 -1
  78. package/dist/chunk-TICWLBSA.js.map +0 -1
  79. /package/dist/{chunk-TRUK5ZBE.js.map → chunk-3B5EULS6.js.map} +0 -0
@@ -0,0 +1,388 @@
1
+ import type { AdapterCallContext, MarketplaceAdapter, MarketplaceCredentials, OutboundOrderRef, OutboundResult } from "./adapter";
2
+ import type { OutboundConnection } from "./integration";
3
+ import { readOutboundConnection } from "./integration";
4
+ import { MARKETPLACE_OUTBOUND_JOB, type OutboundJobPayload } from "./outbound-queue";
5
+ import type { MarketplaceAppCredentialsPort } from "./linking-port";
6
+ import type { EngineContext } from "./ports";
7
+ import { insertStatusRow, readStatusRows, settleStatusRow, statusTable, type StatusRow, type StatusRowStep } from "./status-store";
8
+
9
+ /**
10
+ * The store's OWN courier carrying a marketplace order, reported to the
11
+ * marketplace (FUT-5988, FUT-6166): iFood's Logistics module, so the buyer
12
+ * follows the delivery in the marketplace's app.
13
+ *
14
+ * The host says the courier reached a step (`informLogistics`, one enqueue);
15
+ * the `marketplace.outbound` job, action `logistics`, sends every step still
16
+ * owed up to it, in the marketplace's one order, each under its own claim row
17
+ * in the status table (`LOGISTICS_<STEP>`, unique per order and step, so a
18
+ * step is never sent twice). Only for an ACCEPTED order the store carries
19
+ * itself (`deliveredBy: MERCHANT`), only when the adapter has a Logistics
20
+ * half and the host configured the Logistics app's credentials
21
+ * (`logisticsCredentials`, the software's own app, never the store's PDV
22
+ * credentials). The courier's name and phone are read from the host at send
23
+ * time (`order.logisticsDriver`), never carried in the job's payload.
24
+ *
25
+ * A step that fails (a final refusal, or the last attempt) is FAILED and the
26
+ * chain stops there: the marketplace refuses a later step out of order. A
27
+ * failure never touches the order.
28
+ */
29
+
30
+ /** The steps, in the one order a marketplace takes them. */
31
+ export const LOGISTICS_STEPS = ["ASSIGNED", "GOING_TO_ORIGIN", "ARRIVED_AT_ORIGIN", "DISPATCHED", "ARRIVED_AT_DESTINATION"] as const;
32
+
33
+ export type LogisticsStep = (typeof LOGISTICS_STEPS)[number];
34
+
35
+ /** How the courier travels, as the marketplace is told. */
36
+ export type LogisticsVehicle = "MOTORCYCLE" | "CAR" | "BICYCLE" | "ON_FOOT" | "SCOOTER";
37
+
38
+ /** Who carries the order, read from the host when ASSIGNED is sent. */
39
+ export interface LogisticsDriver {
40
+ name: string;
41
+ phone: string;
42
+ vehicle: LogisticsVehicle;
43
+ }
44
+
45
+ /** An adapter's Logistics half: the wire calls, nothing else. */
46
+ export interface MarketplaceLogistics {
47
+ assignDriver(ctx: AdapterCallContext, order: OutboundOrderRef, driver: LogisticsDriver): Promise<OutboundResult | { kind: "invalid"; reason: string }>;
48
+ step(ctx: AdapterCallContext, order: OutboundOrderRef, step: Exclude<LogisticsStep, "ASSIGNED">): Promise<OutboundResult>;
49
+ /** OPTIONAL (FUT-6167). The customer's delivery code, typed by the courier at the door. */
50
+ verifyDeliveryCode?(ctx: AdapterCallContext, order: OutboundOrderRef, code: string): Promise<DeliveryCodeAnswer>;
51
+ }
52
+
53
+ /**
54
+ * What the marketplace said of the customer's delivery code (FUT-6167).
55
+ * UNAVAILABLE is never a refusal of the close: the host closes and records it.
56
+ */
57
+ export type DeliveryCodeAnswer =
58
+ | { kind: "VERIFIED" }
59
+ /** Wrong, or not a code at all: the courier may type it again. */
60
+ | { kind: "WRONG_CODE" }
61
+ /** The marketplace never asked this order for a code. */
62
+ | { kind: "NOT_REQUESTED" }
63
+ | { kind: "UNAVAILABLE"; reason: string };
64
+
65
+ /** The adapter's Logistics half (`MarketplaceAdapter` extends it). */
66
+ export interface LogisticsAdapter {
67
+ /** OPTIONAL (FUT-6166). The store's own courier reported to the marketplace. */
68
+ readonly logistics?: MarketplaceLogistics;
69
+ }
70
+
71
+ /** The order port's Logistics half (`MarketplaceOrderPort` extends it). */
72
+ export interface LogisticsOrderPort {
73
+ /**
74
+ * OPTIONAL (FUT-6166). The store's courier carrying the order, read before a
75
+ * Logistics run claims anything while ASSIGNED is still owed, or null when none
76
+ * is. Null or absent: the run is skipped and claims nothing. Answer null after
77
+ * the host's undo of a dispatch (ADOPTING §16).
78
+ */
79
+ logisticsDriver?(clientId: string, orderId: string): Promise<LogisticsDriver | null>;
80
+ /**
81
+ * OPTIONAL (FUT-6167). The marketplace asked the customer's delivery code for
82
+ * an ACCEPTED order: store it, so the courier's close asks for the code.
83
+ * Idempotent: a redelivery calls it again. Absent: the event is ignored.
84
+ */
85
+ onDeliveryCodeRequested?(clientId: string, orderId: string): Promise<void>;
86
+ }
87
+
88
+ /** The host's Logistics ports (`MarketplacePorts` extends it). */
89
+ export interface LogisticsPorts {
90
+ /**
91
+ * OPTIONAL (FUT-6166). The software's Logistics app on this marketplace (a
92
+ * separate app from the one that links stores), or null. Absent or null: no
93
+ * Logistics step is ever sent.
94
+ */
95
+ logisticsCredentials?: MarketplaceAppCredentialsPort;
96
+ }
97
+
98
+ /** What the host says when its courier reaches a step. */
99
+ export interface InformLogisticsInput {
100
+ clientId: string;
101
+ orderId: string;
102
+ step: LogisticsStep;
103
+ /** The move's instant: it keys the job and owns the claims it makes. */
104
+ at: Date;
105
+ /**
106
+ * Hold the job this long (the host's undo window): a move undone inside it
107
+ * leaves the order with no courier, and the job then sends nothing.
108
+ */
109
+ delayMs?: number;
110
+ }
111
+
112
+ /** The status-table step a Logistics claim is stored under. */
113
+ export const LOGISTICS_ROW_PREFIX = "LOGISTICS_";
114
+
115
+ const rowStep = (step: LogisticsStep): StatusRowStep => `${LOGISTICS_ROW_PREFIX}${step}` as StatusRowStep;
116
+
117
+ /** The dedupe key of one move. */
118
+ function logisticsDedupeKey(step: LogisticsStep, orderId: string, at: Date): string {
119
+ return `${MARKETPLACE_OUTBOUND_JOB}:logistics:${step}:${orderId}:${at.getTime()}`;
120
+ }
121
+
122
+ /** One enqueue, never a statement, never thrown (as `informStatus`). */
123
+ async function informLogistics(ctx: EngineContext, input: InformLogisticsInput): Promise<boolean> {
124
+ const payload: OutboundJobPayload = {
125
+ clientId: input.clientId,
126
+ orderId: input.orderId,
127
+ action: "logistics",
128
+ logisticsStep: input.step,
129
+ // The step is in the key: two moves at one instant never share a claim.
130
+ claimKey: `${input.step}:${input.at.getTime()}`,
131
+ };
132
+ try {
133
+ const options = {
134
+ dedupeKey: logisticsDedupeKey(input.step, input.orderId, input.at),
135
+ ...(input.delayMs === undefined ? {} : { delayMs: input.delayMs }),
136
+ };
137
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);
138
+ if (!outcome.enqueued) ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued`);
139
+ return outcome.enqueued;
140
+ } catch (error) {
141
+ ctx.ports.logger.warn(
142
+ `${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued: ` +
143
+ (error instanceof Error ? error.message : String(error)),
144
+ );
145
+ return false;
146
+ }
147
+ }
148
+
149
+ /** The engine's Logistics half (`MarketplaceEngine` extends it). */
150
+ export interface MarketplaceLogisticsEngine {
151
+ /**
152
+ * The store's own courier reached a step (FUT-6166): ONE enqueue of the
153
+ * `marketplace.outbound` job, action `logistics`, which sends every step
154
+ * still owed up to it. Never throws. True when the queue took it.
155
+ */
156
+ informLogistics(input: InformLogisticsInput): Promise<boolean>;
157
+ }
158
+
159
+ export function logisticsEngine(ctx: EngineContext): MarketplaceLogisticsEngine {
160
+ return { informLogistics: (input) => informLogistics(ctx, input) };
161
+ }
162
+
163
+ /** What the job reads of the acceptance row. */
164
+ interface LogisticsJobRow {
165
+ confirmedAt?: Date | null;
166
+ confirmFailedAt?: Date | null;
167
+ orderId: string;
168
+ provider: string;
169
+ status: string;
170
+ cancellationStatus: string | null;
171
+ deliveredBy: string | null;
172
+ }
173
+
174
+ type LogisticsJobOutcome =
175
+ | { kind: "skipped"; reason: string }
176
+ | { kind: "done"; action: "logistics" }
177
+ | { kind: "failed"; action: "logistics"; reason: string };
178
+
179
+ interface LogisticsJobDeps {
180
+ attempt: { attempt: number; maxAttempts: number };
181
+ ref: OutboundOrderRef;
182
+ retryError: (message: string) => Error;
183
+ }
184
+
185
+ const skipped = (reason: string): LogisticsJobOutcome => ({ kind: "skipped", reason });
186
+
187
+ /** Why the order is not one to report, or null. */
188
+ function orderSkip(row: LogisticsJobRow, adapter: MarketplaceAdapter): string | null {
189
+ if (!adapter.logistics) return "the marketplace has no Logistics half";
190
+ if (row.deliveredBy !== "MERCHANT") return "the store does not carry this order";
191
+ if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
192
+ const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
193
+ return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
194
+ }
195
+
196
+ /**
197
+ * As the status job (FUT-5673): a marketplace that wants its steps after the
198
+ * store's confirm gets none before it. Still owed: retried while attempts are
199
+ * left; failed or the last attempt: skipped.
200
+ */
201
+ function confirmSkip(row: LogisticsJobRow, adapter: MarketplaceAdapter, deps: LogisticsJobDeps): string | null {
202
+ if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
203
+ if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
204
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) throw deps.retryError(`logistics for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
205
+ return "the store's confirm has not reached the marketplace";
206
+ }
207
+
208
+ /** The Logistics app's credentials, or null when the host configured none. */
209
+ async function logisticsAppOf(ctx: EngineContext, provider: string, environment: "SANDBOX" | "PRODUCTION"): Promise<MarketplaceCredentials | null> {
210
+ const port = ctx.ports.logisticsCredentials;
211
+ if (!port) return null;
212
+ const credentials = await port(provider, environment);
213
+ return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
214
+ }
215
+
216
+ /** The store's connection environment, or why there is none. */
217
+ async function environmentOf(
218
+ ctx: EngineContext,
219
+ clientId: string,
220
+ provider: string,
221
+ ): Promise<{ environment: OutboundConnection["environment"] } | { missing: string }> {
222
+ try {
223
+ const connection = await readOutboundConnection(ctx, clientId, provider);
224
+ return connection ? { environment: connection.environment } : { missing: "no credentials on file" };
225
+ } catch (error) {
226
+ return { missing: `credentials do not open: ${error instanceof Error ? error.message : String(error)}` };
227
+ }
228
+ }
229
+
230
+ /** The steps up to `target`, in order. */
231
+ function chainTo(target: LogisticsStep): LogisticsStep[] {
232
+ return LOGISTICS_STEPS.slice(0, LOGISTICS_STEPS.indexOf(target) + 1);
233
+ }
234
+
235
+ interface ChainRun {
236
+ ctx: EngineContext;
237
+ table: NonNullable<ReturnType<typeof statusTable>>;
238
+ payload: OutboundJobPayload;
239
+ row: LogisticsJobRow;
240
+ call: AdapterCallContext;
241
+ logistics: MarketplaceLogistics;
242
+ /** The courier, read before any claim; null once ASSIGNED was SENT (no later step needs him). */
243
+ driver: LogisticsDriver | null;
244
+ key: string;
245
+ deps: LogisticsJobDeps;
246
+ }
247
+
248
+ /**
249
+ * Wait for another run's claim: retried while attempts are left. On the last
250
+ * attempt this run's own target is left owed (SENDING under its key), so the
251
+ * outbound sweep re-queues it once the other run is done, and no move is lost.
252
+ */
253
+ async function waitOrSkip(run: ChainRun, target: LogisticsStep, reason: string): Promise<LogisticsJobOutcome> {
254
+ if (run.deps.attempt.attempt < run.deps.attempt.maxAttempts) throw run.deps.retryError(`logistics for order ${run.row.orderId}: ${reason}`);
255
+ await claimStep(run, target, undefined);
256
+ return skipped(reason);
257
+ }
258
+
259
+ /** Send one step under a claim this run holds. */
260
+ async function send(run: ChainRun, step: LogisticsStep): Promise<OutboundResult | { kind: "invalid"; reason: string }> {
261
+ if (step !== "ASSIGNED") return run.logistics.step(run.call, run.deps.ref, step);
262
+ if (!run.driver) return { kind: "invalid", reason: "the host names no courier for this order" };
263
+ return run.logistics.assignDriver(run.call, run.deps.ref, run.driver);
264
+ }
265
+
266
+ /** Stamp a step's answer: SENT, a thrown retry, or FAILED (which stops the chain). */
267
+ async function settle(run: ChainRun, step: LogisticsStep, result: OutboundResult | { kind: "invalid"; reason: string }): Promise<string | null> {
268
+ const where = { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key };
269
+ if (result.kind === "accepted") {
270
+ await settleStatusRow(run.table, where, "SENT");
271
+ return null;
272
+ }
273
+ const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
274
+ if (result.kind === "retry" && run.deps.attempt.attempt < run.deps.attempt.maxAttempts) {
275
+ throw run.deps.retryError(`logistics ${step} for order ${run.row.orderId}: ${reason}`);
276
+ }
277
+ await settleStatusRow(run.table, where, "FAILED");
278
+ run.ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${step} for order ${run.row.orderId} failed: ${reason}`);
279
+ return reason;
280
+ }
281
+
282
+ /** Claim one step, or say why this run does not send it ("sent": it already went). */
283
+ async function claimStep(run: ChainRun, step: LogisticsStep, found: StatusRow | undefined): Promise<"mine" | "sent" | { stop: string } | { wait: string }> {
284
+ if (found?.state === "SENT") return "sent";
285
+ if (found?.state === "FAILED") return { stop: `${step} failed earlier` };
286
+ if (found?.state === "SENDING") return found.claimKey === run.key ? "mine" : { wait: `${step} is being sent by another run` };
287
+ const claimed = await insertStatusRow(run.table, {
288
+ clientId: run.payload.clientId,
289
+ orderId: run.row.orderId,
290
+ provider: run.row.provider,
291
+ step: rowStep(step),
292
+ source: "STORE",
293
+ state: "SENDING",
294
+ claimKey: run.key,
295
+ });
296
+ return claimed ? "mine" : { wait: `another run holds the claim on ${step}` };
297
+ }
298
+
299
+ /** The Logistics app's call context for this order, or why nothing is sent. */
300
+ export async function logisticsCallContext(ctx: EngineContext, clientId: string, provider: string): Promise<AdapterCallContext | string> {
301
+ const connection = await environmentOf(ctx, clientId, provider);
302
+ if ("missing" in connection) return connection.missing;
303
+ const app = await logisticsAppOf(ctx, provider, connection.environment);
304
+ if (!app) return "no Logistics app credentials are configured";
305
+ return { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), environment: connection.environment, credentials: app };
306
+ }
307
+
308
+ /** An earlier step FAILED: fail what this run still holds of the chain, so the sweep stops re-queuing it. */
309
+ async function stopChain(run: ChainRun, chain: readonly LogisticsStep[], reason: string): Promise<LogisticsJobOutcome> {
310
+ for (const step of chain) await settleStatusRow(run.table, { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key }, "FAILED");
311
+ return { kind: "failed", action: "logistics", reason };
312
+ }
313
+
314
+ /**
315
+ * The courier, read before any claim while ASSIGNED is still owed: once it went,
316
+ * the later steps need nobody (a host may clear the courier on a later move).
317
+ * "none": the order has no courier now, a dispatch undone in the host's window.
318
+ */
319
+ async function courierWhileOwed(
320
+ ctx: EngineContext,
321
+ table: ChainRun["table"],
322
+ payload: OutboundJobPayload,
323
+ orderId: string,
324
+ ): Promise<LogisticsDriver | null | "none"> {
325
+ const [assigned] = await readStatusRows(table, orderId, [rowStep("ASSIGNED")]);
326
+ if (assigned?.state === "SENT") return null;
327
+ return (await ctx.ports.order.logisticsDriver?.call(ctx.ports.order, payload.clientId, orderId)) ?? "none";
328
+ }
329
+
330
+ /** No courier now: skipped, never failed, and this run lets go of its claims so a later dispatch sends. */
331
+ async function releaseHeld(ctx: EngineContext, table: ChainRun["table"], orderId: string, chain: readonly LogisticsStep[], key: string): Promise<LogisticsJobOutcome> {
332
+ await table.deleteMany?.({ where: { orderId, step: { in: chain.map(rowStep) }, state: "SENDING", claimKey: key } });
333
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics for order ${orderId} not sent: the host names no courier for it now`);
334
+ return skipped("the host names no courier for this order");
335
+ }
336
+
337
+ /** Claim and send each step of the chain in order; stops at the first failure or wait. */
338
+ async function runChain(run: ChainRun, chain: readonly LogisticsStep[]): Promise<LogisticsJobOutcome> {
339
+ const rows = await readStatusRows(run.table, run.row.orderId, chain.map(rowStep));
340
+ for (const step of chain) {
341
+ const claim = await claimStep(run, step, rows.find((found) => found.step === rowStep(step)));
342
+ if (claim === "sent") continue;
343
+ if (typeof claim === "object") return "wait" in claim ? waitOrSkip(run, chain.at(-1)!, claim.wait) : stopChain(run, chain, claim.stop);
344
+ const failed = await settle(run, step, await send(run, step));
345
+ if (failed) return stopChain(run, chain, failed);
346
+ }
347
+ return { kind: "done", action: "logistics" };
348
+ }
349
+
350
+ /** Run one `logistics` job. `row` is the acceptance the outbound job already read. */
351
+ export async function runLogistics(
352
+ ctx: EngineContext,
353
+ payload: OutboundJobPayload,
354
+ row: LogisticsJobRow,
355
+ adapter: MarketplaceAdapter,
356
+ deps: LogisticsJobDeps,
357
+ ): Promise<LogisticsJobOutcome> {
358
+ const target = payload.logisticsStep;
359
+ if (!target || !LOGISTICS_STEPS.includes(target)) return skipped("a logistics call names no step");
360
+ const stopped = orderSkip(row, adapter) ?? confirmSkip(row, adapter, deps);
361
+ if (stopped) return skipped(stopped);
362
+ const table = statusTable(await ctx.ports.db());
363
+ if (!table) return skipped("the host has not composed the status model");
364
+ const call = await logisticsCallContext(ctx, payload.clientId, row.provider);
365
+ if (typeof call === "string") {
366
+ ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${target} for order ${row.orderId} not sent: ${call}`);
367
+ return skipped(call);
368
+ }
369
+ const chain = chainTo(target);
370
+ const key = payload.claimKey ?? "";
371
+ const driver = await courierWhileOwed(ctx, table, payload, row.orderId);
372
+ if (driver === "none") return releaseHeld(ctx, table, row.orderId, chain, key);
373
+ return runChain({ ctx, table, payload, row, call, logistics: adapter.logistics!, driver, key, deps }, chain);
374
+ }
375
+
376
+ /**
377
+ * The last attempt died on a throw: every SENDING claim of this run is FAILED,
378
+ * so nothing stays owed, and the failure is logged.
379
+ */
380
+ export async function failLogisticsJob(ctx: EngineContext, payload: OutboundJobPayload, error: unknown): Promise<LogisticsJobOutcome> {
381
+ const reason = error instanceof Error ? error.message : String(error);
382
+ const table = statusTable(await ctx.ports.db());
383
+ for (const step of table && payload.logisticsStep ? chainTo(payload.logisticsStep) : []) {
384
+ await settleStatusRow(table!, { orderId: payload.orderId, step: rowStep(step), claimKey: payload.claimKey ?? "" }, "FAILED");
385
+ }
386
+ ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${payload.logisticsStep ?? ""} for order ${payload.orderId} failed: ${reason}`);
387
+ return { kind: "failed", action: "logistics", reason };
388
+ }
@@ -1,4 +1,5 @@
1
1
  import type { MarketplaceAdapter, StatusStep } from "./adapter";
2
+ import type { LogisticsStep } from "./logistics";
2
3
  import type { EngineContext } from "./ports";
3
4
  import type { MarketplaceProvider } from "./types";
4
5
 
@@ -20,7 +21,7 @@ export const MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
20
21
  * step of the order the store reached (`status`, FUT-4653), or the pickup code
21
22
  * the store checked at the hand-over (`validatePickupCode`, FUT-5665).
22
23
  */
23
- export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode";
24
+ export type OutboundAction = "confirm" | "requestCancellation" | "status" | "validatePickupCode" | "logistics";
24
25
 
25
26
  /** The outbound job's payload. Identifiers only. */
26
27
  export interface OutboundJobPayload {
@@ -40,6 +41,8 @@ export interface OutboundJobPayload {
40
41
  * job needs to send, which no log line prints.
41
42
  */
42
43
  code?: string;
44
+ /** OPTIONAL (FUT-6166). The step a `logistics` call sends up to; absent on every other action. */
45
+ logisticsStep?: LogisticsStep;
43
46
  }
44
47
 
45
48
  /** The dedupe key: at most one queued call per (order, action). */
@@ -57,6 +60,8 @@ function ableTo(adapter: MarketplaceAdapter, payload: OutboundJobPayload): boole
57
60
  switch (payload.action) {
58
61
  case "status":
59
62
  return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
63
+ case "logistics":
64
+ return Boolean(adapter.logistics);
60
65
  case "confirm":
61
66
  return adapter.capabilities.apiConfirm;
62
67
  default:
@@ -1,5 +1,7 @@
1
1
  import { NO_STANDING_REQUEST } from "./cancellation";
2
+ import { LOGISTICS_ROW_PREFIX, type LogisticsStep } from "./logistics";
2
3
  import { sweepCatalogue } from "./catalogue-sweep";
4
+ import { sweepDisputes } from "./dispute-job";
3
5
  import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
4
6
  import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
5
7
  import { statusTable, type StatusRowStep } from "./status-store";
@@ -85,14 +87,16 @@ function sweepDedupeKey(action: OutboundAction, orderId: string, now: Date, step
85
87
  async function requeue(ctx: EngineContext, rows: readonly OwedRow[], action: OutboundAction, now: Date): Promise<number> {
86
88
  let queued = 0;
87
89
  for (const row of rows) {
90
+ // A Logistics claim (FUT-6166) is the `logistics` job's, sent up to its own step.
91
+ const logistics = row.step?.startsWith(LOGISTICS_ROW_PREFIX) === true;
88
92
  const payload = {
89
93
  clientId: row.clientId,
90
94
  orderId: row.orderId,
91
- action,
92
- ...(row.step ? { step: row.step as StatusStep } : {}),
95
+ action: logistics ? ("logistics" as const) : action,
96
+ ...(logistics ? { logisticsStep: row.step!.slice(LOGISTICS_ROW_PREFIX.length) as LogisticsStep } : row.step ? { step: row.step as StatusStep } : {}),
93
97
  ...(row.claimKey === undefined ? {} : { claimKey: row.claimKey }),
94
98
  };
95
- if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
99
+ if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(payload.action, row.orderId, now, row.step))) queued += 1;
96
100
  }
97
101
  return queued;
98
102
  }
@@ -167,10 +171,12 @@ async function sweepStatus(ctx: EngineContext, now: Date): Promise<{ requeued: n
167
171
  })) as OwedRow[];
168
172
  // The stale claim is TAKEN OVER under a fresh key, predicated on the old one, before the job
169
173
  // is queued under the new: a job still alive under the old key can then settle or fail
170
- // nothing, and a second sweep pass finds nothing to take.
174
+ // nothing, and a second sweep pass finds nothing to take. The key names the row's step: two
175
+ // rows of one order taken over in one pass must not share a claim (a logistics chain owns
176
+ // every SENDING row under its own key, so a shared one would send the overlap twice).
171
177
  const claimed: OwedRow[] = [];
172
178
  for (const row of owed) {
173
- const fresh = `sweep:${now.getTime()}`;
179
+ const fresh = `sweep:${now.getTime()}:${row.step}`;
174
180
  const taken = await table.updateMany({
175
181
  where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
176
182
  data: { claimKey: fresh },
@@ -214,5 +220,12 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
214
220
  if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
215
221
  const catalogueRequeued = await sweepCatalogue(ctx, now);
216
222
  const status = await sweepStatus(ctx, now);
217
- return { requeued: requeued + status.requeued, givenUp: givenUp + status.givenUp, timedOut, catalogueRequeued };
223
+ // A dispute's answer still owed (FUT-6099): re-queued, or given back after a day.
224
+ const disputes = await sweepDisputes(ctx, now);
225
+ return {
226
+ requeued: requeued + status.requeued + disputes.requeued,
227
+ givenUp: givenUp + status.givenUp + disputes.givenUp,
228
+ timedOut,
229
+ catalogueRequeued,
230
+ };
218
231
  }
@@ -10,7 +10,7 @@ import {
10
10
  import { readOutboundConnection, type OutboundConnection } from "./integration";
11
11
  import type { OutboundJobPayload } from "./outbound-queue";
12
12
  import { runPickupCode, tellPickupCode } from "./pickup-code";
13
- import { failStatusRow, runStatus } from "./status-job";
13
+ import { failLogisticsJob, failStatusRow, runLogistics, runStatus } from "./status-job";
14
14
  import { failAsTimeout } from "./outbound-sweep";
15
15
  import type { CancellationFailureReason, EngineContext } from "./ports";
16
16
  import { resolveReason } from "./registry";
@@ -374,10 +374,9 @@ async function runOnce(ctx: EngineContext, payload: OutboundJobPayload, attempt:
374
374
  if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
375
375
  const deps = { attempt, ref: refOf(row), retryError: (m: string) => new OutboundRetryError(m) };
376
376
  if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
377
+ if (payload.action === "logistics") return runLogistics(ctx, payload, row, adapter, deps);
377
378
  if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
378
- return payload.action === "confirm"
379
- ? runConfirm(ctx, payload, row, adapter, attempt)
380
- : runCancellation(ctx, payload, row, adapter, attempt);
379
+ return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
381
380
  }
382
381
 
383
382
  /**
@@ -395,6 +394,6 @@ export async function runOutbound(
395
394
  return await runOnce(ctx, payload, attempt);
396
395
  } catch (error) {
397
396
  if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
398
- return stampLastAttemptFailure(ctx, payload, error);
397
+ return payload.action === "logistics" ? failLogisticsJob(ctx, payload, error) : stampLastAttemptFailure(ctx, payload, error);
399
398
  }
400
399
  }
@@ -1,3 +1,4 @@
1
+ import { applyDeliveryCodeRequest } from "./delivery-code";
1
2
  import { cancelAcceptance } from "./acceptance";
2
3
  import { failCancellationRequest } from "./cancellation";
3
4
  import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-order";
@@ -16,6 +17,7 @@ import type {
16
17
  import { followCourierAndLifecycle } from "./courier";
17
18
  import { enqueueAcknowledge } from "./acknowledge";
18
19
  import { applyMarketplaceConfirmation } from "./marketplace-confirmed";
20
+ import { applyDisputeEvent } from "./disputes";
19
21
 
20
22
  /**
21
23
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -45,6 +47,8 @@ export type DeliveryOutcome =
45
47
  | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
46
48
  /** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */
47
49
  | { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
50
+ /** The marketplace asked the customer's delivery code; the host stored it (FUT-6167). */
51
+ | { kind: "deliveryCodeRequested"; orderId: string }
48
52
  /** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
49
53
  | { kind: "courier"; orderId: string; step: MarketplaceCourierStep }
50
54
  /**
@@ -53,6 +57,8 @@ export type DeliveryOutcome =
53
57
  * (with the host's `refusal`, when it refused), never expired.
54
58
  */
55
59
  | { kind: "confirmedByMarketplace"; orderId: string; accepted: boolean; refusal?: { code: string; message: string } }
60
+ /** A dispute opened or closed on the order (FUT-6099); `unchanged` for a second event of one already kept. */
61
+ | { kind: "dispute"; orderId: string; disputeId: string; change: "opened" | "settled" | "unchanged" }
56
62
  | { kind: "cancelled" }
57
63
  | { kind: "cancellationFailed" }
58
64
  /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
@@ -191,9 +197,9 @@ async function applyEvent(
191
197
  }
192
198
 
193
199
  /**
194
- * What the marketplace says about an order it already gave us: the store
195
- * accepted it in the marketplace's app (FUT-5653), or a courier or lifecycle
196
- * step. Null for anything else.
200
+ * What the marketplace says about an order it already gave us: a dispute
201
+ * (FUT-6099), the store accepted it in the marketplace's app (FUT-5653), or a
202
+ * courier or lifecycle step. Null for anything else.
197
203
  */
198
204
  async function followMarketplace(
199
205
  ctx: EngineContext,
@@ -202,8 +208,12 @@ async function followMarketplace(
202
208
  event: NormalizedEvent,
203
209
  settings: IngestSettings,
204
210
  ): Promise<DeliveryOutcome | null> {
211
+ const disputed = await applyDisputeEvent(ctx, inboxId, clientId, event);
212
+ if (disputed) return disputed;
205
213
  const confirmed = await applyMarketplaceConfirmation(ctx, inboxId, clientId, event);
206
- return confirmed ?? followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
214
+ if (confirmed) return confirmed;
215
+ const codeRequested = await applyDeliveryCodeRequest(ctx, inboxId, clientId, event);
216
+ return codeRequested ?? followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
207
217
  }
208
218
 
209
219
  /** An event with no order body is understood and ignored; one that carries an order is ingested. */
package/src/core/ports.ts CHANGED
@@ -2,8 +2,10 @@ import type { AdapterRegistry } from "./registry";
2
2
  import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
3
3
  import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
4
4
  import type { MarketplaceCourierAnswer, MarketplaceCourierFacts, PickupCodeValidation } from "./courier-port";
5
+ import type { MarketplaceDisputeChange, MarketplaceDisputeDelegate } from "./dispute-port";
5
6
  import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
6
7
  import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
8
+ import type { LogisticsOrderPort, LogisticsPorts } from "./logistics";
7
9
  import type {
8
10
  CancellationFailureReason,
9
11
  MarketplaceAdmission,
@@ -113,8 +115,12 @@ export interface MarketplaceDb {
113
115
  findMany(args: unknown): Promise<unknown[]>;
114
116
  create(args: unknown): Promise<unknown>;
115
117
  updateMany(args: unknown): Promise<{ count: number }>;
118
+ /** OPTIONAL (FUT-6166): a Logistics run lets go of its claims when the order has no courier now. */
119
+ deleteMany?(args: unknown): Promise<{ count: number }>;
116
120
  };
117
121
  marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate; // OPTIONAL, as above; absent: no linking (FUT-5613).
122
+ /** OPTIONAL (FUT-6099): the buyer's disputes, migration `20261203190000_marketplace_disputes`. */
123
+ marketplaceDispute?: MarketplaceDisputeDelegate;
118
124
  }
119
125
 
120
126
  /** One decision as the host's admission sees it, BEFORE the claim commits. */
@@ -139,7 +145,7 @@ export interface MarketplaceAdmissionRequest {
139
145
  * transition has already been claimed and committed when they are called, and
140
146
  * a host that fails its half must not un-decide the acceptance.
141
147
  */
142
- export interface MarketplaceOrderPort {
148
+ export interface MarketplaceOrderPort extends LogisticsOrderPort {
143
149
  /**
144
150
  * Judge a decision BEFORE its claim commits, inside the claim's
145
151
  * transaction: the stock check (and the draw) of an accept, anything the
@@ -246,6 +252,12 @@ export interface MarketplaceOrderPort {
246
252
  * logged. Absent: the verdict is only logged.
247
253
  */
248
254
  onPickupCodeValidated?(clientId: string, orderId: string, validation: PickupCodeValidation): Promise<void>;
255
+ /**
256
+ * OPTIONAL (FUT-6099). A dispute opened or closed on this order, after its
257
+ * commit: the host refreshes its board and tells a person. A throw is
258
+ * logged. Absent: only `publishChanged` is called.
259
+ */
260
+ onDispute?(clientId: string, orderId: string, change: MarketplaceDisputeChange): Promise<void>;
249
261
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
250
262
  summarize(
251
263
  clientId: string,
@@ -324,7 +336,7 @@ export interface MarketplaceCataloguePort {
324
336
  }
325
337
 
326
338
  /** Everything the host plugs in. */
327
- export interface MarketplacePorts {
339
+ export interface MarketplacePorts extends LogisticsPorts {
328
340
  db: () => Promise<MarketplaceDb>;
329
341
  /**
330
342
  * Run `fn` in ONE database transaction and hand it the transaction's client
@@ -346,6 +358,12 @@ export interface MarketplacePorts {
346
358
  * awaits it, and a dead bus costs latency, never a transition.
347
359
  */
348
360
  publishChanged: (clientId: string) => void;
361
+ /**
362
+ * OPTIONAL (FUT-5798). The periodic check saw the authorization of a store's
363
+ * centralized link arrive: the host hints that store's open screen to read
364
+ * its link again. Payload-free; absent, the screen sees it on its next read.
365
+ */
366
+ publishLinkSeen?: (clientId: string, provider: string) => void;
349
367
  /**
350
368
  * OPTIONAL. How long a store's cancellation request may wait for the
351
369
  * marketplace's answer before the outbound sweep fails it as TIMEOUT, in
@@ -5,6 +5,9 @@ import type { EngineContext, MarketplaceDb } from "./ports";
5
5
  import { insertStatusRow, readStatusRows, settleStatusRow, statusTable, type StatusRow } from "./status-store";
6
6
  import type { MarketplaceDeliveredBy } from "./types";
7
7
 
8
+ // The Logistics job (FUT-6166) is dispatched beside this one by the outbound job.
9
+ export { failLogisticsJob, runLogistics } from "./logistics";
10
+
8
11
  /**
9
12
  * The status job's body (FUT-4653), `marketplace.outbound` with action
10
13
  * `status`: tell the marketplace the order reached a step.
@@ -1,4 +1,5 @@
1
1
  import type { StatusStep } from "./adapter";
2
+ import type { LogisticsStep } from "./logistics";
2
3
  import type { EngineContext, MarketplaceDb } from "./ports";
3
4
 
4
5
  /**
@@ -10,7 +11,7 @@ import type { EngineContext, MarketplaceDb } from "./ports";
10
11
  */
11
12
 
12
13
  /** A step as the table holds it: the three the store informs, and the one only a marketplace announces. */
13
- export type StatusRowStep = StatusStep | "CONCLUDED";
14
+ export type StatusRowStep = StatusStep | "CONCLUDED" | `LOGISTICS_${LogisticsStep}`;
14
15
 
15
16
  /** Where a row stands. */
16
17
  export type StatusRowState = "SENDING" | "SENT" | "FAILED" | "NOTED";