@12-apps/marketplace 1.6.0 → 1.8.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 (74) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +56 -0
  3. package/dist/99food/index.d.ts +4 -2
  4. package/dist/99food/index.js +38 -6
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-CCWMqt2g.d.ts → adapter-CYJzu1c9.d.ts} +81 -2
  7. package/dist/{chunk-4CJ7B5OR.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-NFZT5TWR.js → chunk-BMCERPQX.js} +214 -24
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-RGMSD7S7.js → chunk-HEXLCTOG.js} +7 -1
  12. package/dist/chunk-HEXLCTOG.js.map +1 -0
  13. package/dist/{chunk-UYFYGGCS.js → chunk-NP4EYKPO.js} +3 -1
  14. package/dist/chunk-NP4EYKPO.js.map +1 -0
  15. package/dist/{engine-w2TgRrlc.d.ts → engine-wmW-VuBL.d.ts} +123 -9
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +3 -3
  18. package/dist/ifood/index.d.ts +1 -1
  19. package/dist/ifood/index.js +66 -6
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +119 -12
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/index.d.ts +3 -0
  25. package/dist/manifest/index.js +1 -1
  26. package/dist/manifest/server.d.ts +2 -2
  27. package/dist/manifest/server.js +3 -3
  28. package/dist/rappi/index.d.ts +7 -1
  29. package/dist/rappi/index.js +23 -5
  30. package/dist/rappi/index.js.map +1 -1
  31. package/dist/server/index.d.ts +6 -2
  32. package/dist/server/index.js +3 -3
  33. package/package.json +1 -1
  34. package/prisma/marketplace.prisma +48 -4
  35. package/prisma/migrations/20261125180000_marketplace_cancellation_failure_reason_widen/migration.sql +16 -0
  36. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  37. package/src/99food/index.ts +6 -0
  38. package/src/99food/normalize.ts +7 -1
  39. package/src/99food/outbound.ts +62 -2
  40. package/src/core/adapter.ts +58 -3
  41. package/src/core/bulk.ts +1 -1
  42. package/src/core/cancellation.ts +4 -1
  43. package/src/core/catalogue.ts +4 -3
  44. package/src/core/decisions.ts +3 -2
  45. package/src/core/engine.ts +9 -0
  46. package/src/core/fetch-order.ts +2 -2
  47. package/src/core/ingest.ts +6 -0
  48. package/src/core/integration.ts +17 -0
  49. package/src/core/lifecycle-port.ts +16 -0
  50. package/src/core/lifecycle.ts +133 -0
  51. package/src/core/order-fetch-marks.ts +13 -8
  52. package/src/core/outbound-queue.ts +24 -4
  53. package/src/core/outbound-sweep.ts +49 -5
  54. package/src/core/outbound.ts +26 -11
  55. package/src/core/pipeline.ts +35 -3
  56. package/src/core/ports.ts +54 -7
  57. package/src/core/state.ts +1 -1
  58. package/src/core/status-inform.ts +51 -0
  59. package/src/core/status-job.ts +207 -0
  60. package/src/core/status-store.ts +85 -0
  61. package/src/core/types.ts +39 -0
  62. package/src/ifood/index.ts +7 -1
  63. package/src/ifood/normalize.ts +70 -0
  64. package/src/ifood/outbound.ts +37 -1
  65. package/src/index.ts +9 -0
  66. package/src/rappi/index.ts +6 -1
  67. package/src/rappi/normalize.ts +6 -0
  68. package/src/rappi/outbound.ts +33 -3
  69. package/src/server/mcp.ts +2 -0
  70. package/src/server/webhook.ts +3 -1
  71. package/dist/chunk-4CJ7B5OR.js.map +0 -1
  72. package/dist/chunk-NFZT5TWR.js.map +0 -1
  73. package/dist/chunk-RGMSD7S7.js.map +0 -1
  74. package/dist/chunk-UYFYGGCS.js.map +0 -1
@@ -0,0 +1,60 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: following and informing a pedido's status (FUT-4653).
3
+ -- Additive and replay-safe, like the engine's earlier migrations: one new
4
+ -- column with a default, one new table with its CHECKs and indexes. No foreign
5
+ -- key into a host table, and nothing the previous release reads is changed.
6
+ --
7
+ -- `follow_status` is the connection's switch for the INBOUND move: ON for every
8
+ -- existing connection and every new one.
9
+ --
10
+ -- `marketplace_status_updates` holds one row per (order, step): the claim that
11
+ -- keeps a step from ever being sent twice, the marker an inbound echo is
12
+ -- recognised by, and the note of what the marketplace itself announced.
13
+ -- `claim_key` says WHICH run holds a SENDING claim, so two jobs for one step
14
+ -- never both call the marketplace.
15
+
16
+ ALTER TABLE "marketplace_integrations" ADD COLUMN IF NOT EXISTS "follow_status" BOOLEAN NOT NULL DEFAULT true;
17
+
18
+ CREATE TABLE IF NOT EXISTS "marketplace_status_updates" (
19
+ "id" TEXT NOT NULL,
20
+ "client_id" TEXT NOT NULL,
21
+ "order_id" TEXT NOT NULL,
22
+ "provider" TEXT NOT NULL,
23
+ "step" TEXT NOT NULL,
24
+ "source" TEXT NOT NULL,
25
+ "state" TEXT NOT NULL,
26
+ "claim_key" TEXT NOT NULL,
27
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
28
+ "updated_at" TIMESTAMP(3) NOT NULL,
29
+
30
+ CONSTRAINT "marketplace_status_updates_pkey" PRIMARY KEY ("id")
31
+ );
32
+
33
+ DO $$ BEGIN
34
+ ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_provider_shape"
35
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
36
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
37
+
38
+ DO $$ BEGIN
39
+ ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_step_check"
40
+ CHECK ("step" IN ('READY', 'DISPATCHED', 'HANDED_OVER', 'CONCLUDED'));
41
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
42
+
43
+ DO $$ BEGIN
44
+ ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_source_check"
45
+ CHECK ("source" IN ('STORE', 'MARKETPLACE'));
46
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
47
+
48
+ DO $$ BEGIN
49
+ ALTER TABLE "marketplace_status_updates" ADD CONSTRAINT "marketplace_status_updates_state_check"
50
+ CHECK ("state" IN ('SENDING', 'SENT', 'FAILED', 'NOTED'));
51
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
52
+
53
+ -- One row per step of an order: the claim's unique.
54
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_status_updates_order_id_step_key"
55
+ ON "marketplace_status_updates"("order_id", "step");
56
+
57
+ -- The outbound sweep reads only rows still SENDING.
58
+ CREATE INDEX IF NOT EXISTS "marketplace_status_updates_state_updated_at_idx"
59
+ ON "marketplace_status_updates"("updated_at")
60
+ WHERE "state" = 'SENDING';
@@ -9,7 +9,9 @@ import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDelive
9
9
  import {
10
10
  openDeliveryConfirm,
11
11
  openDeliveryFetchOrder,
12
+ openDeliveryInformStatus,
12
13
  openDeliveryRequestCancellation,
14
+ openDeliveryStatusSupported,
13
15
  type NinetyNineFoodApiBaseUrls,
14
16
  } from "./outbound";
15
17
  import { openDeliveryAvailability } from "./pause";
@@ -109,6 +111,8 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
109
111
  // `OrderConfirmed.preparationTime`, in minutes.
110
112
  confirmTakesPreparationTime: true,
111
113
  cancellationAnswerWindowMs: NINETY_NINE_FOOD_CANCELLATION_ANSWER_WINDOW_MS,
114
+ // Open Delivery's readyForPickup, dispatch and delivered / pickedUp (see `./outbound.ts`).
115
+ statusSteps: ["READY", "DISPATCHED", "HANDED_OVER"],
112
116
  },
113
117
  normalize: normalizeOpenDeliveryEvent,
114
118
  readSignature: (header) => header("x-app-signature"),
@@ -119,6 +123,8 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
119
123
  fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
120
124
  confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
121
125
  requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
126
+ statusSupported: openDeliveryStatusSupported,
127
+ informStatus: (ctx, order, facts) => openDeliveryInformStatus(ctx, bases, order, facts),
122
128
  appLink: () => config.portalUrl,
123
129
  ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),
124
130
  };
@@ -8,6 +8,7 @@ import {
8
8
  verifyHmacSha256Hex,
9
9
  } from "../core/payload-read";
10
10
  import type {
11
+ MarketplaceLifecycle,
11
12
  MarketplaceDeliveredBy,
12
13
  MarketplaceOrderType,
13
14
  NormalizedAddress,
@@ -39,6 +40,8 @@ export const NINETY_NINE_FOOD_PROVIDER = "NINETY_NINE_FOOD";
39
40
  const CREATED = "CREATED";
40
41
  /** The order is cancelled: the store's request was granted, or a mandatory cancellation. */
41
42
  const CANCELLED = "CANCELLED";
43
+ /** The order left (DISPATCHED) and the order is finished (CONCLUDED): the lifecycle events (FUT-4653). */
44
+ const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = { DISPATCHED: "DISPATCHED", CONCLUDED: "CONCLUDED" };
42
45
  /** The marketplace refused the store's own cancellation request. */
43
46
  const CANCELLATION_REQUEST_DENIED = "CANCELLATION_REQUEST_DENIED";
44
47
 
@@ -68,7 +71,9 @@ export function verifyOpenDeliverySignature(
68
71
  * - `CREATED` announces an order: `orderToFetch`, the body is the fetch job's.
69
72
  * - `CANCELLED` is a cancellation, whether the store asked for it or not.
70
73
  * - `CANCELLATION_REQUEST_DENIED` refuses the store's request.
71
- * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, `DISPATCHED`, the
74
+ * - `DISPATCHED` and `CONCLUDED` are lifecycle events (FUT-4653): the engine
75
+ * asks the host to move the order forward, when the store follows them.
76
+ * - Everything else (`CONFIRMED`, `CANCELLATION_REQUESTED`, the
72
77
  * consumer's `ORDER_CANCELLATION_REQUEST` handshake…) is understood and
73
78
  * recorded, and acts on nothing: an IGNORED inbox row.
74
79
  *
@@ -93,6 +98,7 @@ export function normalizeOpenDeliveryEvent(payload: unknown): NormalizedEvent |
93
98
  orderToFetch: eventType === CREATED,
94
99
  cancelled,
95
100
  cancellationOutcome: cancelled ? "CONFIRMED" : denied ? "FAILED" : null,
101
+ ...(LIFECYCLE_OF[eventType] ? { lifecycle: LIFECYCLE_OF[eventType] } : {}),
96
102
  };
97
103
  }
98
104
 
@@ -1,12 +1,14 @@
1
1
  import {
2
2
  answered,
3
3
  outboundResultOf,
4
+ tokenGrantResultOf,
4
5
  type AdapterCallContext,
5
6
  type CancellationRequestInput,
6
7
  type FetchOrderResult,
7
8
  type MarketplaceHttpResponse,
8
9
  type OutboundOrderRef,
9
10
  type OutboundResult,
11
+ type StatusFacts,
10
12
  } from "../core/adapter";
11
13
  import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from "./normalize";
12
14
 
@@ -76,7 +78,7 @@ export async function bearer(
76
78
  }).toString(),
77
79
  });
78
80
  if (response.status < 200 || response.status >= 300) {
79
- const result = outboundResultOf(response);
81
+ const result = tokenGrantResultOf(response);
80
82
  return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
81
83
  }
82
84
  const token = tokenOf(response.body);
@@ -215,6 +217,64 @@ export function openDeliveryRequestCancellation(
215
217
  body: { reason: input.text === "" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },
216
218
  });
217
219
  if ("kind" in response) return response;
218
- return alreadyCancelled(response) ? { kind: "accepted" } : outboundResultOf(response);
220
+ if (alreadyCancelled(response)) return { kind: "accepted" };
221
+ const result = outboundResultOf(response);
222
+ // Open Delivery's 400 is a malformed request (a bad id or body: ours);
223
+ // its 422 is the business answer and stays a refusal.
224
+ return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
225
+ });
226
+ }
227
+
228
+ /**
229
+ * What 99Food is told per step (FUT-4653), from Open Delivery v1.7.1's
230
+ * `openapi.yaml` (https://abrasel-nacional.github.io/opendelivery/openapi.yaml,
231
+ * read 2026-11-25, paths at lines 1605-1890):
232
+ *
233
+ * - READY: `POST /v1/orders/{id}/readyForPickup`, "ready for pickup by the
234
+ * customer or delivery person"; 202. Every kind of order.
235
+ * - DISPATCHED: `POST /v1/orders/{id}/dispatch`, body `OrderDispatched`
236
+ * (`deliveryTrackingInfo` optional, sent empty), and "a DISPATCHED event is
237
+ * expected after this action". Only where the logistics is the merchant's.
238
+ * - HANDED_OVER: the merchant's bag `POST /v1/orders/{id}/delivered`; a
239
+ * take-out `POST /v1/orders/{id}/pickedUp`. Both optional in the spec. The
240
+ * marketplace's own fleet: none.
241
+ *
242
+ * The kind of order is `deliveredBy` (null: a take-out). That a take-out's
243
+ * order states no `deliveredBy` is how 99Food's order reads (ESTIMATED: an
244
+ * order that merely omits it reads as a take-out here).
245
+ */
246
+ const STATUS_PATH: Readonly<Record<string, (facts: StatusFacts) => { action: string; body?: unknown } | null>> = {
247
+ READY: () => ({ action: "readyForPickup" }),
248
+ DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? { action: "dispatch", body: {} } : null),
249
+ HANDED_OVER: (facts) =>
250
+ facts.deliveredBy === "MERCHANT"
251
+ ? { action: "delivered", body: {} }
252
+ : facts.deliveredBy === null
253
+ ? { action: "pickedUp", body: {} }
254
+ : null,
255
+ };
256
+
257
+ /** Whether 99Food takes this step for this kind of order: answered offline. */
258
+ export function openDeliveryStatusSupported(facts: StatusFacts): boolean {
259
+ return STATUS_PATH[facts.step]?.(facts) != null;
260
+ }
261
+
262
+ /** Tell 99Food a step happened. `unsupported` when the spec has no call for it. */
263
+ export function openDeliveryInformStatus(
264
+ ctx: AdapterCallContext,
265
+ bases: NinetyNineFoodApiBaseUrls,
266
+ order: OutboundOrderRef,
267
+ facts: StatusFacts,
268
+ ): Promise<OutboundResult | { kind: "unsupported" }> {
269
+ const path = STATUS_PATH[facts.step]?.(facts) ?? null;
270
+ if (path === null) return Promise.resolve({ kind: "unsupported" });
271
+ return answered(async () => {
272
+ const response = await callOrder(ctx, bases, {
273
+ method: "POST",
274
+ externalOrderId: order.externalOrderId,
275
+ action: path.action,
276
+ ...(path.body === undefined ? {} : { body: path.body }),
277
+ });
278
+ return "kind" in response ? response : outboundResultOf(response);
219
279
  });
220
280
  }
@@ -1,7 +1,12 @@
1
1
  import type { MarketplaceCatalogue } from "./catalogue-port";
2
2
  import type { CatalogueReader } from "./catalogue-read-port";
3
3
  import type { MarketplaceAvailability } from "./pause-port";
4
- import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
4
+ import type {
5
+ MarketplaceDeliveredBy,
6
+ MarketplaceProvider,
7
+ NormalizedEvent,
8
+ NormalizedMarketplaceOrder,
9
+ } from "./types";
5
10
 
6
11
  /**
7
12
  * The adapter port: everything one marketplace is, behind one shape.
@@ -83,6 +88,23 @@ export interface MarketplaceCapabilities {
83
88
  * the request as TIMEOUT. Absent: only the 24-hour give-up applies.
84
89
  */
85
90
  cancellationAnswerWindowMs?: number;
91
+ /**
92
+ * OPTIONAL. The steps this marketplace can be told about (`informStatus`).
93
+ * Absent or empty: the engine tells it nothing.
94
+ */
95
+ statusSteps?: readonly StatusStep[];
96
+ }
97
+
98
+ /**
99
+ * A step of the order the store tells the marketplace about (FUT-4653): the
100
+ * order is ready for pickup, the courier left, the order was handed over.
101
+ */
102
+ export type StatusStep = "READY" | "DISPATCHED" | "HANDED_OVER";
103
+
104
+ /** What a status call is told about the order: who carries it (null: a take-out, or unstated). */
105
+ export interface StatusFacts {
106
+ step: StatusStep;
107
+ deliveredBy: MarketplaceDeliveredBy | null;
86
108
  }
87
109
 
88
110
  /** One reason a store may give for refusing or cancelling an order. */
@@ -124,8 +146,13 @@ export interface AdapterCallContext {
124
146
  export type OutboundResult =
125
147
  /** 2xx. For a marketplace whose outcome is asynchronous, "the request was taken". */
126
148
  | { kind: "accepted" }
127
- /** A final 4xx (not 408/425/429): never retried. */
128
- | { kind: "refused"; status: number; message: string }
149
+ /**
150
+ * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that
151
+ * is not the marketplace's judgement of the order: our credentials were not
152
+ * accepted, or our request was malformed. A cancellation request that ends
153
+ * so fails as UNREACHABLE, not REFUSED.
154
+ */
155
+ | { kind: "refused"; status: number; message: string; own?: true }
129
156
  /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */
130
157
  | { kind: "retry"; reason: string };
131
158
 
@@ -171,6 +198,24 @@ export interface MarketplaceAdapter {
171
198
  order: OutboundOrderRef,
172
199
  input: CancellationRequestInput,
173
200
  ): Promise<OutboundResult>;
201
+ /**
202
+ * OPTIONAL. Whether this marketplace takes this step for this kind of order,
203
+ * answered offline, with no call: the job asks it BEFORE it claims anything
204
+ * (an unsupported step leaves no row). Absent: every step in
205
+ * `capabilities.statusSteps` is taken for every order.
206
+ */
207
+ statusSupported?(facts: StatusFacts): boolean;
208
+ /**
209
+ * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called
210
+ * only from the `marketplace.outbound` job, action `status`. `unsupported`
211
+ * (no endpoint for this step and this kind of order) ends the job with no
212
+ * row. Absent: the marketplace is told nothing.
213
+ */
214
+ informStatus?(
215
+ ctx: AdapterCallContext,
216
+ order: OutboundOrderRef,
217
+ facts: StatusFacts,
218
+ ): Promise<OutboundResult | { kind: "unsupported" }>;
174
219
  /**
175
220
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
176
221
  * marketplace whose events carry no order body). Called only from the
@@ -222,6 +267,16 @@ export function outboundResultOf(response: MarketplaceHttpResponse): OutboundRes
222
267
  return { kind: "retry", reason: `status ${response.status}: ${message}` };
223
268
  }
224
269
 
270
+ /**
271
+ * {@link outboundResultOf} for a token grant: a final 4xx there says our
272
+ * credentials were not accepted, never a judgement of any order, so it is an
273
+ * `own` refusal.
274
+ */
275
+ export function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {
276
+ const result = outboundResultOf(response);
277
+ return result.kind === "refused" ? { ...result, own: true } : result;
278
+ }
279
+
225
280
  /** A call that never got an answer is a retry, with the reason a log can read. */
226
281
  export async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {
227
282
  try {
package/src/core/bulk.ts CHANGED
@@ -67,7 +67,7 @@ function unknownProviders(ctx: EngineContext, rows: readonly { provider: string
67
67
  );
68
68
  }
69
69
 
70
- const SETTING_KEYS = ["enabled", "environment", "externalMerchantId", "autoAccept", "ackSlaSeconds", "credentials"] as const;
70
+ const SETTING_KEYS = ["enabled", "environment", "externalMerchantId", "autoAccept", "followStatus", "ackSlaSeconds", "credentials"] as const;
71
71
 
72
72
  function integrationRowProblems(
73
73
  row: IntegrationRowInput,
@@ -160,6 +160,7 @@ export function refusalData(plan: CancellationPlan, fromStatus: string, now: Dat
160
160
  cancellationReasonCode: plan.reason?.code ?? null,
161
161
  cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
162
162
  cancellationRequestedAt: plan.status === "PENDING" ? now : null,
163
+ // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
163
164
  cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
164
165
  };
165
166
  }
@@ -177,12 +178,14 @@ export function requestData(plan: CancellationPlan, now: Date): Record<string, u
177
178
  cancellationReasonCode: plan.reason?.code ?? null,
178
179
  cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
179
180
  cancellationRequestedAt: plan.status === "PENDING" ? now : null,
181
+ // FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
180
182
  cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null,
181
183
  };
182
184
  }
183
185
 
184
186
  /**
185
- * The marketplace refused the store's cancellation request. FAILED (REFUSED),
187
+ * The marketplace refused the store's cancellation request: its denial event.
188
+ * FAILED (REFUSED),
186
189
  * from PENDING or REQUESTED only: CONFIRMED is terminal, so a refusal arriving
187
190
  * after the cancellation changes nothing. The host hears it once, from the
188
191
  * call that moved the row. Returns whether a row moved.
@@ -207,8 +207,9 @@ export async function readCatalogueDocument(
207
207
  const catalogue = ctx.registry.get(input.provider)?.catalogue;
208
208
  const table = await usableTable(ctx, input.provider);
209
209
  if (!table || catalogue?.mode !== "pull") return { kind: "refused", code: "UNSUPPORTED" };
210
- const connection = await catalogueConnection(ctx, input.clientId, input.provider);
211
- if ("problem" in connection) return { kind: "refused", code: "NOT_CONNECTED" };
210
+ // The document needs only the merchant id: no credentials are opened to serve it.
211
+ const externalMerchantId = await connectionMerchantId(ctx, input.clientId, input.provider);
212
+ if (externalMerchantId === null) return { kind: "refused", code: "NOT_CONNECTED" };
212
213
  const rows = (await table.findMany({
213
214
  where: { clientId: input.clientId, provider: input.provider, status: { in: IN_MENU } },
214
215
  select: CATALOGUE_ROW_SELECT,
@@ -221,6 +222,6 @@ export async function readCatalogueDocument(
221
222
  if (!item || priceCents === null) return [];
222
223
  return [{ ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage: null }];
223
224
  });
224
- const document = catalogue.menuDocument({ externalMerchantId: connection.externalMerchantId, entries, options: input.options });
225
+ const document = catalogue.menuDocument({ externalMerchantId, entries, options: input.options });
225
226
  return { kind: "document", document };
226
227
  }
@@ -237,8 +237,9 @@ async function afterCommit(ctx: EngineContext, clientId: string, planned: readon
237
237
  try {
238
238
  if (one.decided.status === "ACCEPTED" && one.input.decision === "ACCEPT") await ctx.ports.order.onAccepted(clientId, orderId);
239
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.
240
+ // A request the marketplace cannot take through its API failed at once
241
+ // (REFUSED: its own limit): the order stays, and a person cancels it in
242
+ // the marketplace's app.
242
243
  else if (one.decided.cancellation === "FAILED") await tellCancellationFailed(ctx, clientId, orderId, "REFUSED");
243
244
  } catch (error) {
244
245
  ctx.ports.logger.error(
@@ -60,6 +60,7 @@ import {
60
60
  } from "./integration";
61
61
  import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
62
62
  import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
63
+ import { informStatus, type InformStatusInput } from "./status-inform";
63
64
  import {
64
65
  availabilityState,
65
66
  pauseStore,
@@ -195,6 +196,13 @@ export interface MarketplaceEngine {
195
196
  sweepOutbound(now?: Date): Promise<OutboundSweepResult>;
196
197
  /** Run one queued outbound call (the `marketplace.outbound` job's body). */
197
198
  runOutbound(payload: OutboundJobPayload, attempt: OutboundAttempt): Promise<OutboundOutcome>;
199
+ /**
200
+ * Tell the marketplace the order reached a step (FUT-4653): ONE enqueue of
201
+ * the `marketplace.outbound` job, action `status`. Never throws, runs no
202
+ * statement and calls nobody: the job decides everything else. True when the
203
+ * queue took it.
204
+ */
205
+ informStatus(input: InformStatusInput): Promise<boolean>;
198
206
  /** Fetch and ingest one announced order (the `marketplace.fetch-order` job's body). */
199
207
  runFetchOrder(payload: FetchOrderJobPayload, attempt: OutboundAttempt): Promise<FetchOrderOutcome>;
200
208
 
@@ -310,6 +318,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
310
318
  sweepOutbound: (now) => sweepOutbound(ctx, now ?? ports.clock.now()),
311
319
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
312
320
  runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
321
+ informStatus: (input) => informStatus(ctx, input),
313
322
 
314
323
  // Null too when the host bound no catalogue port: nothing could be published.
315
324
  catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
@@ -3,7 +3,7 @@ import { ingestMarketplaceOrder } from "./ingest";
3
3
  import { readOutboundConnection, resolveIngestionTarget } from "./integration";
4
4
  import type { FetchOrderResult } from "./adapter";
5
5
  import { cancelAcceptance } from "./acceptance";
6
- import { cancelledBeforeIngest } from "./order-fetch-marks";
6
+ import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest } from "./order-fetch-marks";
7
7
  import type { EngineContext } from "./ports";
8
8
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
9
9
 
@@ -171,7 +171,7 @@ async function refusalOf(
171
171
  connectionMerchantId: string | null,
172
172
  ): Promise<{ settle: "IGNORED" | "FAILED"; reason: string; failed: boolean } | null> {
173
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 };
174
+ return { settle: "IGNORED", reason: CANCELLED_BEFORE_INGEST_REASON, failed: false };
175
175
  }
176
176
  const mismatch = merchantMismatch(order, connectionMerchantId);
177
177
  // FAILED, not IGNORED: a connection whose merchant id was entered wrong is
@@ -41,6 +41,12 @@ export interface IngestResult {
41
41
  export interface IngestSettings {
42
42
  autoAccept: boolean;
43
43
  ackSlaSeconds: number;
44
+ /**
45
+ * OPTIONAL. The connection's switch for following the marketplace's status
46
+ * (FUT-4653). Absent is OFF: a host that builds settings by hand keeps the
47
+ * behaviour it had before the switch existed.
48
+ */
49
+ followStatus?: boolean;
44
50
  }
45
51
 
46
52
  /**
@@ -19,6 +19,12 @@ export interface MarketplaceIntegrationView {
19
19
  status: "UNVERIFIED" | "VERIFIED" | "FAILED";
20
20
  externalMerchantId: string | null;
21
21
  autoAccept: boolean;
22
+ /**
23
+ * Whether the marketplace's DISPATCHED and CONCLUDED events move the order
24
+ * forward here (FUT-4653). Always set by this version; optional in the type
25
+ * so a view built by hand against 1.x still compiles.
26
+ */
27
+ followStatus?: boolean;
22
28
  ackSlaSeconds: number;
23
29
  /**
24
30
  * Whether the store has a usable connection — i.e. whether secrets are on
@@ -40,6 +46,7 @@ interface IntegrationRow {
40
46
  status: string;
41
47
  externalMerchantId: string | null;
42
48
  autoAccept: boolean;
49
+ followStatus?: boolean;
43
50
  ackSlaSeconds: number;
44
51
  credentials: string;
45
52
  lastEventAt: Date | null;
@@ -54,6 +61,7 @@ const VIEW_SELECT = {
54
61
  status: true,
55
62
  externalMerchantId: true,
56
63
  autoAccept: true,
64
+ followStatus: true,
57
65
  ackSlaSeconds: true,
58
66
  credentials: true,
59
67
  lastEventAt: true,
@@ -69,6 +77,7 @@ function toView(row: IntegrationRow): MarketplaceIntegrationView {
69
77
  status: row.status as MarketplaceIntegrationView["status"],
70
78
  externalMerchantId: row.externalMerchantId,
71
79
  autoAccept: row.autoAccept,
80
+ followStatus: row.followStatus ?? true,
72
81
  ackSlaSeconds: row.ackSlaSeconds,
73
82
  connected: row.credentials !== "",
74
83
  lastEventAt: row.lastEventAt,
@@ -107,6 +116,8 @@ export interface SaveMarketplaceIntegrationInput {
107
116
  environment?: "SANDBOX" | "PRODUCTION";
108
117
  externalMerchantId?: string | null;
109
118
  autoAccept?: boolean;
119
+ /** Whether the marketplace's DISPATCHED and CONCLUDED events move the order forward here. New connections: true. */
120
+ followStatus?: boolean;
110
121
  ackSlaSeconds?: number;
111
122
  /**
112
123
  * The secrets, when the operator re-entered them. Absent means "leave the
@@ -144,6 +155,7 @@ export async function saveMarketplaceIntegration(
144
155
  ? {}
145
156
  : { externalMerchantId: input.externalMerchantId }),
146
157
  ...(input.autoAccept === undefined ? {} : { autoAccept: input.autoAccept }),
158
+ ...(input.followStatus === undefined ? {} : { followStatus: input.followStatus }),
147
159
  ...(input.ackSlaSeconds === undefined ? {} : { ackSlaSeconds: input.ackSlaSeconds }),
148
160
  ...(sealed === undefined ? {} : { credentials: sealed, status: "UNVERIFIED" }),
149
161
  };
@@ -166,6 +178,8 @@ export async function saveMarketplaceIntegration(
166
178
  export interface IngestionTarget {
167
179
  enabled: boolean;
168
180
  autoAccept: boolean;
181
+ /** Whether lifecycle events move the order forward (FUT-4653). */
182
+ followStatus: boolean;
169
183
  ackSlaSeconds: number;
170
184
  webhookSecret: string | null;
171
185
  /** The merchant the store connected; a fetched order naming another is refused. */
@@ -211,6 +225,7 @@ export async function resolveIngestionTarget(
211
225
  select: {
212
226
  enabled: true,
213
227
  autoAccept: true,
228
+ followStatus: true,
214
229
  ackSlaSeconds: true,
215
230
  credentials: true,
216
231
  archivedAt: true,
@@ -220,6 +235,7 @@ export async function resolveIngestionTarget(
220
235
  externalMerchantId: string | null;
221
236
  enabled: boolean;
222
237
  autoAccept: boolean;
238
+ followStatus?: boolean;
223
239
  ackSlaSeconds: number;
224
240
  credentials: string;
225
241
  archivedAt: Date | null;
@@ -229,6 +245,7 @@ export async function resolveIngestionTarget(
229
245
  return {
230
246
  enabled: row.enabled,
231
247
  autoAccept: row.autoAccept,
248
+ followStatus: row.followStatus ?? true,
232
249
  ackSlaSeconds: row.ackSlaSeconds,
233
250
  externalMerchantId: row.externalMerchantId ?? null,
234
251
  // An unopenable blob must not read as "no secret configured" — that would
@@ -0,0 +1,16 @@
1
+ import type { MarketplaceDeliveredBy } from "./types";
2
+
3
+ /** What the engine tells the host about the order a lifecycle event names. */
4
+ export interface MarketplaceLifecycleFacts {
5
+ /** Who carries the delivery: the merchant's courier, the marketplace's fleet; null for a take-out or when unstated. */
6
+ deliveredBy: MarketplaceDeliveredBy | null;
7
+ }
8
+
9
+ /**
10
+ * The host's answer to a lifecycle event: `moved` (the order moved forward),
11
+ * `unchanged` (it did not, with the engine's default reason), or `unchanged`
12
+ * with the host's own reason, which becomes the inbox row's (an inbox row is
13
+ * a human's; "no courier named for a merchant delivery" is more use than
14
+ * "already at or past DISPATCHED").
15
+ */
16
+ export type MarketplaceLifecycleAnswer = "moved" | "unchanged" | { kind: "unchanged"; reason: string };