@12-apps/marketplace 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/ADOPTING.md +44 -9
  2. package/README.md +149 -4
  3. package/dist/99food/en-US.d.ts +19 -0
  4. package/dist/99food/en-US.js +23 -0
  5. package/dist/99food/en-US.js.map +1 -0
  6. package/dist/99food/index.d.ts +116 -0
  7. package/dist/99food/index.js +361 -0
  8. package/dist/99food/index.js.map +1 -0
  9. package/dist/99food/pt-BR.d.ts +23 -0
  10. package/dist/99food/pt-BR.js +23 -0
  11. package/dist/99food/pt-BR.js.map +1 -0
  12. package/dist/{adapter-CgCAYBSJ.d.ts → adapter-_iuSxvVD.d.ts} +41 -1
  13. package/dist/{chunk-OEKTWUQH.js → chunk-24RQZPSV.js} +1 -1
  14. package/dist/chunk-24RQZPSV.js.map +1 -0
  15. package/dist/chunk-BD7DS3XM.js +78 -0
  16. package/dist/chunk-BD7DS3XM.js.map +1 -0
  17. package/dist/{chunk-BEMTRJYM.js → chunk-CRYFYDQ2.js} +28 -4
  18. package/dist/{chunk-BEMTRJYM.js.map → chunk-CRYFYDQ2.js.map} +1 -1
  19. package/dist/chunk-D2X7TOR6.js +1240 -0
  20. package/dist/chunk-D2X7TOR6.js.map +1 -0
  21. package/dist/{engine-DDE0mnTu.d.ts → engine-D-a4mttc.d.ts} +117 -17
  22. package/dist/hono/index.d.ts +2 -2
  23. package/dist/hono/index.js +2 -2
  24. package/dist/ifood/index.d.ts +10 -12
  25. package/dist/ifood/index.js +19 -61
  26. package/dist/ifood/index.js.map +1 -1
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +113 -497
  29. package/dist/index.js.map +1 -1
  30. package/dist/manifest/server.d.ts +3 -2
  31. package/dist/manifest/server.js +2 -2
  32. package/dist/rappi/en-US.d.ts +14 -0
  33. package/dist/rappi/en-US.js +18 -0
  34. package/dist/rappi/en-US.js.map +1 -0
  35. package/dist/rappi/index.d.ts +190 -0
  36. package/dist/rappi/index.js +353 -0
  37. package/dist/rappi/index.js.map +1 -0
  38. package/dist/rappi/pt-BR.d.ts +18 -0
  39. package/dist/rappi/pt-BR.js +18 -0
  40. package/dist/rappi/pt-BR.js.map +1 -0
  41. package/dist/server/index.d.ts +12 -5
  42. package/dist/server/index.js +4 -2
  43. package/package.json +26 -2
  44. package/prisma/marketplace.prisma +12 -1
  45. package/prisma/migrations/20261112120000_marketplace_cancellation_failure/migration.sql +21 -0
  46. package/src/99food/copy.ts +36 -0
  47. package/src/99food/en-US.ts +19 -0
  48. package/src/99food/index.ts +121 -0
  49. package/src/99food/normalize.ts +263 -0
  50. package/src/99food/outbound.ts +220 -0
  51. package/src/99food/pt-BR.ts +23 -0
  52. package/src/core/acceptance.ts +30 -14
  53. package/src/core/adapter.ts +23 -1
  54. package/src/core/cancellation-outcome.ts +92 -0
  55. package/src/core/cancellation.ts +46 -15
  56. package/src/core/decisions.ts +94 -19
  57. package/src/core/engine.ts +8 -0
  58. package/src/core/fetch-order.ts +253 -0
  59. package/src/core/inbox.ts +8 -2
  60. package/src/core/ingest.ts +10 -2
  61. package/src/core/integration.ts +30 -1
  62. package/src/core/order-fetch-marks.ts +63 -0
  63. package/src/core/outbound-sweep.ts +87 -8
  64. package/src/core/outbound.ts +103 -7
  65. package/src/core/payload-read.ts +101 -0
  66. package/src/core/pipeline.ts +64 -15
  67. package/src/core/ports.ts +32 -0
  68. package/src/core/state.ts +6 -1
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +9 -0
  71. package/src/ifood/normalize.ts +15 -88
  72. package/src/index.ts +10 -1
  73. package/src/rappi/copy.ts +39 -0
  74. package/src/rappi/en-US.ts +14 -0
  75. package/src/rappi/index.ts +155 -0
  76. package/src/rappi/normalize.ts +314 -0
  77. package/src/rappi/outbound.ts +182 -0
  78. package/src/rappi/pt-BR.ts +18 -0
  79. package/src/server/index.ts +1 -0
  80. package/src/server/jobs.ts +38 -4
  81. package/dist/chunk-6OODIO3E.js +0 -395
  82. package/dist/chunk-6OODIO3E.js.map +0 -1
  83. package/dist/chunk-OEKTWUQH.js.map +0 -1
@@ -0,0 +1,92 @@
1
+ import type { MarketplaceAdapter } from "./adapter";
2
+ import type { CancellationFailureReason, EngineContext, MarketplaceDb } from "./ports";
3
+
4
+ /**
5
+ * How the store's own cancellation request ENDS, told to the host (FUT-4758).
6
+ *
7
+ * A host that requests first and cancels only on the marketplace's answer
8
+ * needs both ends: the confirmation, to run its cancel, and the failure, to
9
+ * put the pedido back in a person's hands. Both are optional order-port
10
+ * callbacks, so a 1.0.0 host compiles and behaves unchanged. Each is called by
11
+ * whichever path moved the row (the outbound job, the marketplace's event, the
12
+ * sweep's expiry), once, and a host failure is logged, never rethrown: the
13
+ * row's stamp has committed, and a host that fails its half must not undo it.
14
+ */
15
+
16
+ async function tell(ctx: EngineContext, what: string, orderId: string, call: () => Promise<void>): Promise<void> {
17
+ try {
18
+ await call();
19
+ } catch (error) {
20
+ ctx.ports.logger.error(
21
+ `marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` +
22
+ (error instanceof Error ? error.message : String(error)),
23
+ );
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Whether the host REQUESTS FIRST and cancels on the marketplace's
29
+ * confirmation: it binds `onCancellationConfirmed` (FUT-4758). A host that
30
+ * does not keeps 1.0.0's behaviour exactly — the store's cancel is stamped
31
+ * REJECTED at request time and `onRefused` runs then.
32
+ */
33
+ export function requestsFirst(ctx: EngineContext): boolean {
34
+ return ctx.ports.order.onCancellationConfirmed !== undefined;
35
+ }
36
+
37
+ /**
38
+ * Move a row whose cancellation was just confirmed off the clock: REJECTED,
39
+ * acknowledged now when it was still AWAITING (the table's CHECK pairs the
40
+ * two); an accepted row keeps its acceptance instant.
41
+ */
42
+ export async function rejectConfirmed(db: MarketplaceDb, orderId: string, now: Date): Promise<void> {
43
+ await db.marketplaceAcceptance.updateMany({
44
+ where: { orderId, status: "AWAITING" },
45
+ data: { status: "REJECTED", acknowledgedAt: now },
46
+ });
47
+ await db.marketplaceAcceptance.updateMany({
48
+ where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
49
+ data: { status: "REJECTED" },
50
+ });
51
+ }
52
+
53
+ /**
54
+ * The store's confirmed request, told to the host: `onCancellationConfirmed`
55
+ * when bound, else `onRefused(…, "CANCELLED")` as in 1.0.0.
56
+ */
57
+ export async function confirmedToHost(ctx: EngineContext, clientId: string, orderId: string): Promise<void> {
58
+ if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
59
+ await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
60
+ }
61
+
62
+ /** The marketplace confirmed the store's request. Returns whether the host took it (it has the callback). */
63
+ export async function tellCancellationConfirmed(ctx: EngineContext, clientId: string, orderId: string): Promise<boolean> {
64
+ const hook = ctx.ports.order.onCancellationConfirmed;
65
+ if (!hook) return false;
66
+ await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
67
+ return true;
68
+ }
69
+
70
+ /** The store's request failed, refused or timed out. */
71
+ export async function tellCancellationFailed(
72
+ ctx: EngineContext,
73
+ clientId: string,
74
+ orderId: string,
75
+ reason: CancellationFailureReason,
76
+ ): Promise<void> {
77
+ const hook = ctx.ports.order.onCancellationFailed;
78
+ if (!hook) return;
79
+ await tell(ctx, `had its cancellation request fail (${reason})`, orderId, () =>
80
+ hook.call(ctx.ports.order, clientId, orderId, reason),
81
+ );
82
+ }
83
+
84
+ /** How long a request to this adapter may wait for its answer: the engine's override, else the adapter's own. */
85
+ export function cancellationWindowMs(ctx: EngineContext, adapter: MarketplaceAdapter): number | null {
86
+ return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
87
+ }
88
+
89
+ /** The columns a request that FAILED for `reason` writes. */
90
+ export function failedRequestData(reason: CancellationFailureReason): Record<string, unknown> {
91
+ return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
92
+ }
@@ -1,5 +1,6 @@
1
1
  import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
2
  import type { CancellationReason, MarketplaceAdapter } from "./adapter";
3
+ import { failedRequestData, tellCancellationFailed } from "./cancellation-outcome";
3
4
  import type { EngineContext } from "./ports";
4
5
  import { resolveReason } from "./registry";
5
6
  import type { MarketplaceProvider } from "./types";
@@ -9,13 +10,24 @@ import type { MarketplaceProvider } from "./types";
9
10
  * the marketplace. Lives on the acceptance row:
10
11
  *
11
12
  * null ──refuse/cancel──▶ PENDING ──job 2xx──▶ REQUESTED ──event──▶ CONFIRMED
12
- * │ └──job 4xx / last attempt──▶ FAILED ──event──▶ CONFIRMED
13
+ * │ ├──job 4xx / last attempt / event──▶ FAILED (REFUSED) ──event──▶ CONFIRMED
14
+ * │ └──past the window (sweep)──▶ FAILED (TIMEOUT)
13
15
  * └──event (the marketplace cancelled)──▶ CONFIRMED
14
16
  *
15
17
  * CONFIRMED is terminal; every write is predicated on the statuses it may come
16
- * from, so an out-of-order event cannot undo it.
18
+ * from, so an out-of-order event cannot undo it. A FAILED request stands for
19
+ * nothing: the order may be decided again, or the cancellation asked again
20
+ * (FUT-4758: a refused or timed-out request leaves the order as it was).
17
21
  */
18
22
 
23
+ /** No request of the store's is waiting on the marketplace: never asked, or asked and FAILED. */
24
+ function noStandingRequest(cancellationStatus: string | null): boolean {
25
+ return cancellationStatus === null || cancellationStatus === "FAILED";
26
+ }
27
+
28
+ /** The same, as the `where` a claim is predicated on. */
29
+ export const NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] } as const;
30
+
19
31
  /** Why a decision (or a store cancellation) was refused. Vocabulary, not copy. */
20
32
  export type DecisionProblemCode =
21
33
  | "DUPLICATE"
@@ -64,7 +76,7 @@ export function notPendingProblem(
64
76
  allowed: readonly string[] = ["AWAITING"],
65
77
  ): DecisionProblem | null {
66
78
  if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
67
- if (allowed.includes(row.status) && row.cancellationStatus === null) return null;
79
+ if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
68
80
  const status = row.status as AcceptanceStatus;
69
81
  return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
70
82
  }
@@ -148,28 +160,47 @@ export function refusalData(plan: CancellationPlan, fromStatus: string, now: Dat
148
160
  cancellationReasonCode: plan.reason?.code ?? null,
149
161
  cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
150
162
  cancellationRequestedAt: plan.status === "PENDING" ? now : null,
163
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * The columns the store's own cancellation REQUEST writes (FUT-4758): the
169
+ * request alone. The decision status stays as it is (AWAITING or ACCEPTED)
170
+ * while the marketplace answers, so a refused or timed-out request leaves the
171
+ * order acceptable and still on the acceptance clock; only the marketplace's
172
+ * confirmation moves it to REJECTED.
173
+ */
174
+ export function requestData(plan: CancellationPlan, now: Date): Record<string, unknown> {
175
+ return {
176
+ cancellationStatus: plan.status,
177
+ cancellationReasonCode: plan.reason?.code ?? null,
178
+ cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
179
+ cancellationRequestedAt: plan.status === "PENDING" ? now : null,
180
+ cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
151
181
  };
152
182
  }
153
183
 
154
184
  /**
155
- * The marketplace refused the store's cancellation request. FAILED, from
156
- * PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving
157
- * after the cancellation changes nothing. Returns whether a row moved.
185
+ * The marketplace refused the store's cancellation request. FAILED (REFUSED),
186
+ * from PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving
187
+ * after the cancellation changes nothing. The host hears it once, from the
188
+ * call that moved the row. Returns whether a row moved.
158
189
  */
159
190
  export async function failCancellationRequest(
160
191
  ctx: EngineContext,
161
192
  input: { clientId: string; provider: MarketplaceProvider; externalOrderId: string },
162
193
  ): Promise<boolean> {
163
194
  const db = await ctx.ports.db();
195
+ const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
196
+ const row = (await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } })) as { orderId: string } | null;
197
+ if (!row) return false;
164
198
  const moved = await db.marketplaceAcceptance.updateMany({
165
- where: {
166
- clientId: input.clientId,
167
- provider: input.provider,
168
- externalOrderId: input.externalOrderId,
169
- cancellationStatus: { in: ["PENDING", "REQUESTED"] },
170
- },
171
- data: { cancellationStatus: "FAILED" },
199
+ where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
200
+ data: failedRequestData("REFUSED"),
172
201
  });
173
- if (moved.count > 0) ctx.ports.publishChanged(input.clientId);
174
- return moved.count > 0;
202
+ if (moved.count === 0) return false;
203
+ ctx.ports.publishChanged(input.clientId);
204
+ await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
205
+ return true;
175
206
  }
@@ -1,14 +1,17 @@
1
1
  import type { AcceptanceStatus, CancellationStatus } from "./acceptance";
2
2
  import {
3
3
  CLAIM_SELECT,
4
+ NO_STANDING_REQUEST,
4
5
  notPendingProblem,
5
6
  planCancellation,
6
7
  refusalData,
8
+ requestData,
7
9
  type CancellationPlan,
8
10
  type ClaimRow,
9
11
  type DecisionProblem,
10
12
  type DecisionProblemCode,
11
13
  } from "./cancellation";
14
+ import { requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
12
15
  import { enqueueOutbound } from "./outbound-queue";
13
16
  import type { EngineContext, MarketplaceAdmission, MarketplaceDb } from "./ports";
14
17
 
@@ -51,10 +54,14 @@ export type DecisionInput =
51
54
  offendingSkus?: readonly string[];
52
55
  };
53
56
 
54
- /** One decided row. */
57
+ /**
58
+ * One decided row. `status` is the row's status after the call: ACCEPTED or
59
+ * REJECTED, or — for a refusal of a host that requests first (FUT-4758) —
60
+ * the status it keeps (AWAITING, ACCEPTED) while `cancellation` waits.
61
+ */
55
62
  export interface DecidedRow {
56
63
  orderId: string;
57
- status: Extract<AcceptanceStatus, "ACCEPTED" | "REJECTED">;
64
+ status: AcceptanceStatus;
58
65
  cancellation: CancellationStatus | null;
59
66
  reasonCode: string | null;
60
67
  offendingSkus: string[];
@@ -88,6 +95,8 @@ interface PlannedDecision {
88
95
  row: ClaimRow;
89
96
  data: Record<string, unknown>;
90
97
  decided: DecidedRow;
98
+ /** A refusal that only REQUESTS the cancellation: the host cancels on the marketplace's confirmation. */
99
+ requestOnly: boolean;
91
100
  }
92
101
 
93
102
  /** Thrown inside the transaction to roll it back, carrying the reason. */
@@ -108,16 +117,37 @@ function duplicateProblems(decisions: readonly DecisionInput[]): DecisionProblem
108
117
  });
109
118
  }
110
119
 
111
- function decidedOf(input: DecisionInput, plan: CancellationPlan | null): DecidedRow {
120
+ function decidedOf(input: DecisionInput, plan: CancellationPlan | null, keptStatus?: string): DecidedRow {
121
+ const decided: AcceptanceStatus = input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED";
112
122
  return {
113
123
  orderId: input.orderId,
114
- status: input.decision === "ACCEPT" ? "ACCEPTED" : "REJECTED",
124
+ status: (keptStatus as AcceptanceStatus | undefined) ?? decided,
115
125
  cancellation: plan?.status ?? null,
116
126
  reasonCode: plan?.reason?.code ?? null,
117
127
  offendingSkus: plan?.skus ?? [],
118
128
  };
119
129
  }
120
130
 
131
+ /**
132
+ * The columns of a request that no longer stands, cleared, but for its
133
+ * TOMBSTONE: `cancellation_requested_at` stays, naming the request that was
134
+ * made (FUT-4765, R3-N2).
135
+ *
136
+ * A synchronous marketplace answers a cancellation in the call's response,
137
+ * never by event. When the sweep times a request out while that call is still
138
+ * in flight and the store then accepts the order, the late answer must still
139
+ * find the request it answers: "cancelled" means the marketplace cancelled the
140
+ * order, and dropping it would leave the order ACCEPTED here and cancelled
141
+ * there. The outbound job matches a status-less row by this instant
142
+ * (`stampConfirmedCancellation`); nothing else reads it without a status.
143
+ */
144
+ const CLEARED_REQUEST = {
145
+ cancellationStatus: null,
146
+ cancellationReasonCode: null,
147
+ cancellationOffendingSkus: null,
148
+ cancellationFailureReason: null,
149
+ } as const;
150
+
121
151
  /** Plan one decision against its row, or name what is wrong with it. */
122
152
  function planOne(
123
153
  ctx: EngineContext,
@@ -130,12 +160,33 @@ function planOne(
130
160
  const stale = notPendingProblem(row, path);
131
161
  if (stale || !row) return stale ? [stale] : [];
132
162
  if (input.decision === "ACCEPT") {
133
- const data = { status: "ACCEPTED", acknowledgedAt: now, preparationMinutes: input.preparationMinutes ?? null };
134
- return { input, index, row, data, decided: decidedOf(input, null) };
163
+ // An accept after a FAILED request (FUT-4758) leaves no request behind it,
164
+ // only its tombstone (see CLEARED_REQUEST).
165
+ const data = {
166
+ status: "ACCEPTED",
167
+ acknowledgedAt: now,
168
+ preparationMinutes: input.preparationMinutes ?? null,
169
+ ...(row.cancellationStatus === null ? {} : CLEARED_REQUEST),
170
+ };
171
+ return { input, index, row, data, decided: decidedOf(input, null), requestOnly: false };
135
172
  }
136
173
  const plan = planCancellation(ctx.registry.get(row.provider), input, row, path);
137
174
  if (Array.isArray(plan)) return plan;
138
- return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan) };
175
+ if (requestOnly(ctx, plan)) {
176
+ return { input, index, row, data: requestData(plan, now), decided: decidedOf(input, plan, row.status), requestOnly: true };
177
+ }
178
+ return { input, index, row, data: refusalData(plan, row.status, now), decided: decidedOf(input, plan), requestOnly: false };
179
+ }
180
+
181
+ /**
182
+ * Whether a refusal only REQUESTS the cancellation (FUT-4758): the host
183
+ * requests first (it binds `onCancellationConfirmed`), and there is a request
184
+ * to make — PENDING, or FAILED at once for a marketplace that cannot take it
185
+ * through its API (a person cancels in its app, and its event confirms). A
186
+ * provider with no adapter has nothing to ask: refused at once, as ever.
187
+ */
188
+ function requestOnly(ctx: EngineContext, plan: CancellationPlan): boolean {
189
+ return requestsFirst(ctx) && plan.status !== null;
139
190
  }
140
191
 
141
192
  /** Admit every decision through the host, then claim every row, in one transaction. */
@@ -164,7 +215,7 @@ async function admitAndClaim(
164
215
  if (refused.length > 0) throw new Rollback(refused);
165
216
  for (const one of planned) {
166
217
  const claimed = await tx.marketplaceAcceptance.updateMany({
167
- where: { orderId: one.input.orderId, clientId, status: "AWAITING" },
218
+ where: { orderId: one.input.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
168
219
  data: one.data,
169
220
  });
170
221
  if (claimed.count === 0) refused.push({ path: ["decisions", one.index, "orderId"], code: "CONFLICT" });
@@ -178,14 +229,17 @@ async function admitAndClaim(
178
229
  async function afterCommit(ctx: EngineContext, clientId: string, planned: readonly PlannedDecision[]): Promise<void> {
179
230
  for (const one of planned) {
180
231
  const { orderId } = one.input;
181
- if (one.decided.status === "ACCEPTED") {
232
+ if (one.input.decision === "ACCEPT") {
182
233
  await enqueueOutbound(ctx, { clientId, orderId, action: "confirm" }, one.row.provider);
183
234
  } else if (one.decided.cancellation === "PENDING") {
184
235
  await enqueueOutbound(ctx, { clientId, orderId, action: "requestCancellation" }, one.row.provider);
185
236
  }
186
237
  try {
187
- if (one.decided.status === "ACCEPTED") await ctx.ports.order.onAccepted(clientId, orderId);
188
- else await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
238
+ if (one.decided.status === "ACCEPTED" && one.input.decision === "ACCEPT") await ctx.ports.order.onAccepted(clientId, orderId);
239
+ else if (!one.requestOnly) await ctx.ports.order.onRefused(clientId, orderId, "REJECTED");
240
+ // A request the marketplace cannot take through its API failed at once:
241
+ // the order stays, and a person cancels it in the marketplace's app.
242
+ else if (one.decided.cancellation === "FAILED") await tellCancellationFailed(ctx, clientId, orderId, "REFUSED");
189
243
  } catch (error) {
190
244
  ctx.ports.logger.error(
191
245
  `marketplace.decide: order ${orderId} is ${one.decided.status} but the host's half failed: ` +
@@ -271,13 +325,22 @@ export async function decideOne(
271
325
  }
272
326
 
273
327
  /**
274
- * The STORE cancelled an order through the host's own cancel — before or
275
- * after accepting it. Stamps the request the marketplace must hear and queues
276
- * it. The host's own cancel already ran, so the engine neither admits nor
277
- * calls `onRefused`: it records and queues, and nothing else.
328
+ * The STORE asks to cancel an order — before or after accepting it. Stamps
329
+ * the request the marketplace must hear and queues it; the engine neither
330
+ * admits nor calls `onRefused`: it records and queues, and nothing else.
331
+ *
332
+ * REQUEST FIRST (FUT-4758), for a host that binds `onCancellationConfirmed`:
333
+ * only the request moves. The decision status stays AWAITING or ACCEPTED while
334
+ * the marketplace answers, so the host keeps the order as it was until then,
335
+ * and a refused or timed-out request (`onCancellationFailed`) leaves it
336
+ * acceptable. The marketplace's confirmation moves it to REJECTED. A FAILED
337
+ * request may be asked again. A host that binds no `onCancellationConfirmed`
338
+ * cancelled first and gets 1.0.0's stamps exactly: REJECTED at once.
339
+ *
340
+ * The returned row's `status` is the row's after the call.
278
341
  *
279
342
  * `stale` (ALREADY_DECIDED) when the marketplace already cancelled it, the
280
- * clock lapsed (EXPIRED), or a request was already made.
343
+ * clock lapsed (EXPIRED), or a request is already waiting.
281
344
  */
282
345
  export async function recordStoreCancellation(
283
346
  ctx: EngineContext,
@@ -289,16 +352,28 @@ export async function recordStoreCancellation(
289
352
  const plan = planCancellation(ctx.registry.get(row.provider), input, row, []);
290
353
  if (Array.isArray(plan)) return resultOfProblem(plan[0]!);
291
354
 
355
+ return claimStoreCancellation(ctx, input, row, plan);
356
+ }
357
+
358
+ /** Stamp the store's cancellation (the request alone, or 1.0.0's REJECTED), queue it, and tell the host. */
359
+ async function claimStoreCancellation(
360
+ ctx: EngineContext,
361
+ input: { clientId: string; orderId: string; now?: Date },
362
+ row: ClaimRow,
363
+ plan: CancellationPlan,
364
+ ): Promise<DecisionResult> {
292
365
  const now = input.now ?? ctx.ports.clock.now();
293
366
  const db = await ctx.ports.db();
367
+ const only = requestOnly(ctx, plan);
294
368
  const claimed = await db.marketplaceAcceptance.updateMany({
295
- where: { orderId: input.orderId, clientId: input.clientId, status: row.status, cancellationStatus: null },
296
- data: refusalData(plan, row.status, now),
369
+ where: { orderId: input.orderId, clientId: input.clientId, status: row.status, ...NO_STANDING_REQUEST },
370
+ data: only ? requestData(plan, now) : refusalData(plan, row.status, now),
297
371
  });
298
372
  if (claimed.count === 0) return { kind: "stale", reason: "CONFLICT", status: null };
299
373
  if (plan.status === "PENDING") {
300
374
  await enqueueOutbound(ctx, { clientId: input.clientId, orderId: input.orderId, action: "requestCancellation" }, row.provider);
301
375
  }
302
376
  ctx.ports.publishChanged(input.clientId);
303
- return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan) };
377
+ if (only && plan.status === "FAILED") await tellCancellationFailed(ctx, input.clientId, input.orderId, "REFUSED");
378
+ return { kind: "decided", ...decidedOf({ orderId: input.orderId, decision: "REJECT" }, plan, only ? row.status : undefined) };
304
379
  }
@@ -20,6 +20,11 @@ import {
20
20
  type DecisionInput,
21
21
  type DecisionResult,
22
22
  } from "./decisions";
23
+ import {
24
+ runFetchOrder,
25
+ type FetchOrderJobPayload,
26
+ type FetchOrderOutcome,
27
+ } from "./fetch-order";
23
28
  import { sweepOutbound, type OutboundSweepResult } from "./outbound-sweep";
24
29
  import type {
25
30
  AdapterTokenCache,
@@ -163,6 +168,8 @@ export interface MarketplaceEngine {
163
168
  sweepOutbound(now?: Date): Promise<OutboundSweepResult>;
164
169
  /** Run one queued outbound call (the `marketplace.outbound` job's body). */
165
170
  runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;
171
+ /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */
172
+ runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;
166
173
  }
167
174
 
168
175
  /**
@@ -225,5 +232,6 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
225
232
  reprocess: (event) => reprocessStoredDelivery(ctx, event),
226
233
  sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),
227
234
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
235
+ runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
228
236
  };
229
237
  }