@12-apps/marketplace 1.7.0 → 1.9.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 (96) hide show
  1. package/ADOPTING.md +17 -0
  2. package/README.md +153 -3
  3. package/dist/99food/index.d.ts +30 -52
  4. package/dist/99food/index.js +62 -391
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-DOjTak1H.d.ts → adapter-CYJzu1c9.d.ts} +45 -1
  7. package/dist/{chunk-YVUZHXUF.js → chunk-6N2HEV3U.js} +4 -4
  8. package/dist/chunk-6N2HEV3U.js.map +1 -0
  9. package/dist/{chunk-SJUKBCVO.js → chunk-BMCERPQX.js} +198 -12
  10. package/dist/chunk-BMCERPQX.js.map +1 -0
  11. package/dist/{chunk-L3DCOZUU.js → chunk-HEXLCTOG.js} +1 -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/chunk-PYHNM47K.js +478 -0
  16. package/dist/chunk-PYHNM47K.js.map +1 -0
  17. package/dist/client-B4EQCRD_.d.ts +20 -0
  18. package/dist/{engine-DG1fg43Y.d.ts → engine-wmW-VuBL.d.ts} +107 -4
  19. package/dist/hono/index.d.ts +2 -2
  20. package/dist/hono/index.js +3 -3
  21. package/dist/ifood/index.d.ts +1 -1
  22. package/dist/ifood/index.js +29 -3
  23. package/dist/ifood/index.js.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +104 -7
  26. package/dist/index.js.map +1 -1
  27. package/dist/keeta/en-US.d.ts +19 -0
  28. package/dist/keeta/en-US.js +23 -0
  29. package/dist/keeta/en-US.js.map +1 -0
  30. package/dist/keeta/index.d.ts +253 -0
  31. package/dist/keeta/index.js +388 -0
  32. package/dist/keeta/index.js.map +1 -0
  33. package/dist/keeta/pt-BR.d.ts +23 -0
  34. package/dist/keeta/pt-BR.js +23 -0
  35. package/dist/keeta/pt-BR.js.map +1 -0
  36. package/dist/manifest/index.d.ts +3 -0
  37. package/dist/manifest/index.js +1 -1
  38. package/dist/manifest/server.d.ts +2 -2
  39. package/dist/manifest/server.js +3 -3
  40. package/dist/rappi/index.d.ts +7 -1
  41. package/dist/rappi/index.js +20 -3
  42. package/dist/rappi/index.js.map +1 -1
  43. package/dist/server/index.d.ts +6 -2
  44. package/dist/server/index.js +3 -3
  45. package/package.json +14 -2
  46. package/prisma/marketplace.prisma +45 -1
  47. package/prisma/migrations/20261126120000_marketplace_status_updates/migration.sql +60 -0
  48. package/src/99food/catalogue.ts +19 -89
  49. package/src/99food/copy.ts +4 -19
  50. package/src/99food/index.ts +29 -28
  51. package/src/99food/normalize.ts +11 -247
  52. package/src/99food/outbound.ts +29 -215
  53. package/src/99food/pause.ts +7 -22
  54. package/src/core/adapter.ts +41 -1
  55. package/src/core/bulk.ts +1 -1
  56. package/src/core/engine.ts +9 -0
  57. package/src/core/ingest.ts +6 -0
  58. package/src/core/integration.ts +17 -0
  59. package/src/core/lifecycle-port.ts +16 -0
  60. package/src/core/lifecycle.ts +133 -0
  61. package/src/core/outbound-queue.ts +24 -4
  62. package/src/core/outbound-sweep.ts +49 -5
  63. package/src/core/outbound.ts +11 -0
  64. package/src/core/pipeline.ts +22 -2
  65. package/src/core/ports.ts +39 -3
  66. package/src/core/status-inform.ts +51 -0
  67. package/src/core/status-job.ts +207 -0
  68. package/src/core/status-store.ts +85 -0
  69. package/src/core/types.ts +14 -0
  70. package/src/ifood/index.ts +7 -1
  71. package/src/ifood/normalize.ts +17 -0
  72. package/src/ifood/outbound.ts +35 -0
  73. package/src/index.ts +8 -1
  74. package/src/keeta/authorization.ts +226 -0
  75. package/src/keeta/copy.ts +27 -0
  76. package/src/keeta/en-US.ts +19 -0
  77. package/src/keeta/index.ts +162 -0
  78. package/src/keeta/merchant.ts +70 -0
  79. package/src/keeta/normalize.ts +131 -0
  80. package/src/keeta/outbound.ts +55 -0
  81. package/src/keeta/pt-BR.ts +23 -0
  82. package/src/keeta/signature.ts +85 -0
  83. package/src/open-delivery/client.ts +185 -0
  84. package/src/open-delivery/merchant.ts +126 -0
  85. package/src/open-delivery/normalize.ts +269 -0
  86. package/src/open-delivery/orders.ts +241 -0
  87. package/src/open-delivery/reasons.ts +26 -0
  88. package/src/rappi/index.ts +6 -1
  89. package/src/rappi/normalize.ts +6 -0
  90. package/src/rappi/outbound.ts +31 -2
  91. package/src/server/mcp.ts +2 -0
  92. package/src/server/webhook.ts +3 -1
  93. package/dist/chunk-L3DCOZUU.js.map +0 -1
  94. package/dist/chunk-SJUKBCVO.js.map +0 -1
  95. package/dist/chunk-UYFYGGCS.js.map +0 -1
  96. package/dist/chunk-YVUZHXUF.js.map +0 -1
@@ -1,225 +1,39 @@
1
- import {
2
- answered,
3
- outboundResultOf,
4
- tokenGrantResultOf,
5
- type AdapterCallContext,
6
- type CancellationRequestInput,
7
- type FetchOrderResult,
8
- type MarketplaceHttpResponse,
9
- type OutboundOrderRef,
10
- type OutboundResult,
11
- } from "../core/adapter";
12
- import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryOrder } from "./normalize";
1
+ import type { OpenDeliveryApiBaseUrls, OpenDeliveryDialect } from "../open-delivery/client";
2
+ import { NINETY_NINE_FOOD_PROVIDER } from "./normalize";
13
3
 
14
4
  /**
15
- * The 99Food adapter's OUTBOUND half, on Open Delivery v1.7.1: the OAuth
16
- * grant, the order fetch, confirm and requestCancellation. Paths, verbs,
17
- * bodies and answers are the spec's; the job that calls these, its retries
18
- * and what a failure shows are the engine's.
5
+ * 99Food's Open Delivery DIALECT: v1.7.1 as the standard writes it. The calls
6
+ * themselves (the grant, the order fetch, confirm, requestCancellation, the
7
+ * status steps) are `../open-delivery/`'s; this file only says where and how
8
+ * 99Food takes them.
9
+ *
10
+ * - Token: `POST /oauth/token`, form-encoded `client_id`, `client_secret`,
11
+ * `grant_type=client_credentials`.
12
+ * - Bodies: plain JSON; no request signature.
19
13
  *
20
14
  * The one thing the spec cannot pin is WHERE: Open Delivery standardizes the
21
15
  * paths under each Ordering Application's own base URL, and 99Food gives its
22
16
  * base URLs to a partner at onboarding. So the base URL per environment is
23
- * the adapter's REQUIRED config, never a guessed default. Tests never reach
24
- * 99Food: the HTTP client is the host's port, answered by a fake.
17
+ * the adapter's REQUIRED config, never a guessed default.
25
18
  */
26
19
 
27
20
  /** Where 99Food serves Open Delivery, per environment (given at partner onboarding). */
28
- export type NinetyNineFoodApiBaseUrls = Readonly<Record<"SANDBOX" | "PRODUCTION", string>>;
29
-
30
- /** A token is renewed this long before it expires. */
31
- const TOKEN_MARGIN_MS = 60_000;
32
- /** `expires_in` is optional in the spec's `TokenResponse`; an hour when absent. ESTIMATED. */
33
- const DEFAULT_TOKEN_SECONDS = 3600;
34
-
35
- /** The base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
36
- export function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {
37
- const base = bases[ctx.environment];
38
- let end = base.length;
39
- while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
40
- return base.slice(0, end);
41
- }
42
- export const tokenKey = (ctx: AdapterCallContext): string =>
43
- `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;
44
-
45
- /** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */
46
- function tokenOf(body: string): { token: string; expiresInSeconds: number } | null {
47
- try {
48
- const parsed = JSON.parse(body) as { access_token?: unknown; expires_in?: unknown };
49
- if (typeof parsed.access_token !== "string" || parsed.access_token === "") return null;
50
- const expires =
51
- typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : DEFAULT_TOKEN_SECONDS;
52
- return { token: parsed.access_token, expiresInSeconds: expires };
53
- } catch {
54
- return null;
55
- }
56
- }
57
-
58
- /**
59
- * A bearer token from the per-process cache, or a fresh `client_credentials`
60
- * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,
61
- * `grant_type`). Keyed by environment and client id; memory only.
62
- */
63
- export async function bearer(
64
- ctx: AdapterCallContext,
65
- bases: NinetyNineFoodApiBaseUrls,
66
- ): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
67
- const cached = ctx.tokens.get(tokenKey(ctx));
68
- if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
69
- const response = await ctx.http({
70
- method: "POST",
71
- url: `${baseOf(ctx, bases)}/oauth/token`,
72
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
73
- body: new URLSearchParams({
74
- client_id: ctx.credentials.clientId,
75
- client_secret: ctx.credentials.clientSecret,
76
- grant_type: "client_credentials",
77
- }).toString(),
78
- });
79
- if (response.status < 200 || response.status >= 300) {
80
- const result = tokenGrantResultOf(response);
81
- return result.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : result;
82
- }
83
- const token = tokenOf(response.body);
84
- if (!token) return { kind: "retry", reason: "99Food answered the token grant without a token" };
85
- ctx.tokens.set(tokenKey(ctx), { token: token.token, expiresAt: ctx.now.getTime() + token.expiresInSeconds * 1000 });
86
- return { token: token.token };
87
- }
88
-
89
- /** One authenticated call to an order's resource, the raw answer or the result that ends it. */
90
- async function callOrder(
91
- ctx: AdapterCallContext,
92
- bases: NinetyNineFoodApiBaseUrls,
93
- request: { method: "GET" | "POST"; externalOrderId: string; action: string | null; body?: unknown },
94
- ): Promise<MarketplaceHttpResponse | Exclude<OutboundResult, { kind: "accepted" }>> {
95
- const auth = await bearer(ctx, bases);
96
- if (!("token" in auth)) return auth;
97
- const suffix = request.action === null ? "" : `/${request.action}`;
98
- const response = await ctx.http({
99
- method: request.method,
100
- url: `${baseOf(ctx, bases)}/v1/orders/${encodeURIComponent(request.externalOrderId)}${suffix}`,
101
- headers: {
102
- Authorization: `Bearer ${auth.token}`,
103
- ...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
104
- },
105
- ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
106
- });
107
- // A 401 is a token that went stale under us: forget it, and the retry fetches another.
108
- if (response.status !== 401) return response;
109
- ctx.tokens.delete(tokenKey(ctx));
110
- return { kind: "retry", reason: "99Food refused the token" };
111
- }
112
-
113
- /** Whether a 422 answer's `CancellationError.cancellationStatus` says the order is already cancelled. */
114
- function alreadyCancelled(response: MarketplaceHttpResponse): boolean {
115
- if (response.status !== 422) return false;
116
- try {
117
- return (JSON.parse(response.body) as { cancellationStatus?: unknown }).cancellationStatus === "CANCELLED";
118
- } catch {
119
- return false;
120
- }
121
- }
122
-
123
- /** {@link answered} for a fetch: a call that never got an answer is a retry. */
124
- async function fetched(call: () => Promise<FetchOrderResult>): Promise<FetchOrderResult> {
125
- try {
126
- return await call();
127
- } catch (error) {
128
- return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
129
- }
130
- }
131
-
132
- /** `GET /v1/orders/{orderId}`: the order an event announced, normalized. A 404 is an expired order: refused. */
133
- export function openDeliveryFetchOrder(
134
- ctx: AdapterCallContext,
135
- bases: NinetyNineFoodApiBaseUrls,
136
- order: { externalOrderId: string },
137
- options: { missingStreetNumber: string },
138
- ): Promise<FetchOrderResult> {
139
- return fetched(async () => {
140
- const response = await callOrder(ctx, bases, { method: "GET", externalOrderId: order.externalOrderId, action: null });
141
- if ("kind" in response) return response;
142
- const result = outboundResultOf(response);
143
- if (result.kind !== "accepted") return result;
144
- let body: unknown;
145
- try {
146
- body = JSON.parse(response.body);
147
- } catch {
148
- return { kind: "refused", status: response.status, message: "the order is not JSON" };
149
- }
150
- const normalized = normalizeOpenDeliveryOrder(body, options);
151
- return normalized
152
- ? { kind: "order", order: normalized }
153
- : { kind: "refused", status: response.status, message: "the order carries no id or no line" };
154
- });
155
- }
156
-
157
- /**
158
- * `POST /v1/orders/{orderId}/confirm` with the spec's `OrderConfirmed`:
159
- * `orderExternalCode` (the host's own order id) and `createdAt`, plus the
160
- * `preparationTime` in minutes when the store stated one. The spec describes
161
- * `createdAt` with the ORDER's creation text (a copy of another schema's), so
162
- * it is sent as the moment of the confirmation: ESTIMATED.
163
- *
164
- * Every 422 is a refusal. It is the spec's generic `UnprocessableEntity`
165
- * ("unable to process the contained instructions. (Check if the instruction
166
- * has not been sent before.)"), and its body cannot tell a duplicate from a
167
- * cancelled order. So a retried confirm whose first answer was lost reads
168
- * "não confirmou" with the app link — a false alarm a person dismisses on
169
- * 99Food — and a confirm 99Food truly refused is never stamped confirmed.
170
- */
171
- export function openDeliveryConfirm(
172
- ctx: AdapterCallContext,
173
- bases: NinetyNineFoodApiBaseUrls,
174
- order: OutboundOrderRef,
175
- input: { preparationMinutes: number | null },
176
- ): Promise<OutboundResult> {
177
- return answered(async () => {
178
- const response = await callOrder(ctx, bases, {
179
- method: "POST",
180
- externalOrderId: order.externalOrderId,
181
- action: "confirm",
182
- body: {
183
- orderExternalCode: order.hostOrderCode,
184
- createdAt: ctx.now.toISOString(),
185
- ...(input.preparationMinutes === null ? {} : { preparationTime: input.preparationMinutes }),
186
- },
187
- });
188
- if ("kind" in response) return response;
189
- return outboundResultOf(response);
190
- });
191
- }
192
-
193
- /**
194
- * `POST /v1/orders/{orderId}/requestCancellation` with the spec's
195
- * `RequestCancelled`: `reason` (free text: the store's, else the label),
196
- * `code` (one of the spec's codes) and `mode` (`MANUAL` or `AUTO`). 202 means
197
- * taken; the outcome is a later `CANCELLED` or `CANCELLATION_REQUEST_DENIED`
198
- * event. A 422 whose `cancellationStatus` is `CANCELLED` means the order is
199
- * cancelled already, which is what the request wanted.
200
- *
201
- * `outOfStockItems` is not sent: the spec wants the ITEM ids (uuids) there,
202
- * and the engine keeps the marketplace's SKUs (`externalCode`), which the SKU
203
- * map is keyed on. The field is optional.
204
- */
205
- export function openDeliveryRequestCancellation(
206
- ctx: AdapterCallContext,
207
- bases: NinetyNineFoodApiBaseUrls,
208
- order: OutboundOrderRef,
209
- input: CancellationRequestInput,
210
- ): Promise<OutboundResult> {
211
- return answered(async () => {
212
- const response = await callOrder(ctx, bases, {
213
- method: "POST",
214
- externalOrderId: order.externalOrderId,
215
- action: "requestCancellation",
216
- body: { reason: input.text === "" ? input.reason.label : input.text, code: input.reason.code, mode: input.mode },
217
- });
218
- if ("kind" in response) return response;
219
- if (alreadyCancelled(response)) return { kind: "accepted" };
220
- const result = outboundResultOf(response);
221
- // Open Delivery's 400 is a malformed request (a bad id or body: ours);
222
- // its 422 is the business answer and stays a refusal.
223
- return result.kind === "refused" && result.status === 400 ? { ...result, own: true } : result;
224
- });
21
+ export type NinetyNineFoodApiBaseUrls = OpenDeliveryApiBaseUrls;
22
+
23
+ /** 99Food's dialect, for the base URLs it was given. */
24
+ export function ninetyNineFoodDialect(bases: NinetyNineFoodApiBaseUrls): OpenDeliveryDialect {
25
+ return {
26
+ provider: NINETY_NINE_FOOD_PROVIDER,
27
+ name: "99Food",
28
+ bases,
29
+ tokenGrant: (ctx) => ({
30
+ contentType: "application/x-www-form-urlencoded",
31
+ body: new URLSearchParams({
32
+ client_id: ctx.credentials.clientId,
33
+ client_secret: ctx.credentials.clientSecret,
34
+ grant_type: "client_credentials",
35
+ }).toString(),
36
+ }),
37
+ serialize: (body) => JSON.stringify(body),
38
+ };
225
39
  }
@@ -1,6 +1,7 @@
1
- import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
1
+ import type { AdapterCallContext, OutboundResult } from "../core/adapter";
2
2
  import type { MarketplaceAvailability } from "../core/pause-port";
3
- import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outbound";
3
+ import { openDeliveryMerchantUpdate, openDeliverySwitchAvailability } from "../open-delivery/merchant";
4
+ import { ninetyNineFoodDialect, type NinetyNineFoodApiBaseUrls } from "./outbound";
4
5
 
5
6
  /**
6
7
  * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
@@ -28,29 +29,13 @@ export function openDeliverySetMerchantStatus(
28
29
  bases: NinetyNineFoodApiBaseUrls,
29
30
  status: "AVAILABLE" | "UNAVAILABLE",
30
31
  ): Promise<OutboundResult> {
31
- return answered(async () => {
32
- const auth = await bearer(ctx, bases);
33
- if (!("token" in auth)) return auth;
34
- const response = await ctx.http({
35
- method: "POST",
36
- url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
37
- headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
38
- body: JSON.stringify({ merchantStatus: status }),
39
- });
40
- if (response.status !== 401) return outboundResultOf(response);
41
- ctx.tokens.delete(tokenKey(ctx));
42
- return { kind: "retry", reason: "99Food refused the token" };
32
+ return openDeliveryMerchantUpdate(ctx, ninetyNineFoodDialect(bases), {
33
+ path: "/v1/merchantUpdate",
34
+ body: { merchantStatus: status },
43
35
  });
44
36
  }
45
37
 
46
38
  /** 99Food's availability capability: Open Delivery's merchant status, a switch. */
47
39
  export function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {
48
- return {
49
- kind: "switch",
50
- pause: async (ctx, request) => {
51
- const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
52
- return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
53
- },
54
- resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"),
55
- };
40
+ return openDeliverySwitchAvailability((ctx, _merchantId, status) => openDeliverySetMerchantStatus(ctx, bases, status));
56
41
  }
@@ -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. */
@@ -176,6 +198,24 @@ export interface MarketplaceAdapter {
176
198
  order: OutboundOrderRef,
177
199
  input: CancellationRequestInput,
178
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" }>;
179
219
  /**
180
220
  * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a
181
221
  * marketplace whose events carry no order body). Called only from the
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,
@@ -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),
@@ -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 };
@@ -0,0 +1,133 @@
1
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
2
+ import type { IngestSettings } from "./ingest";
3
+ import type { DeliveryOutcome } from "./pipeline";
4
+ import type { EngineContext } from "./ports";
5
+ import { readStatusRows, noteMarketplaceStep, statusTable } from "./status-store";
6
+ import type { MarketplaceDeliveredBy, MarketplaceLifecycle, NormalizedEvent } from "./types";
7
+
8
+ /**
9
+ * Inbound lifecycle (FUT-4653): the marketplace says the order was dispatched
10
+ * or concluded, and the order follows, FORWARD only.
11
+ *
12
+ * What the engine owns, in order, each stopping the event with a reason the
13
+ * inbox row keeps:
14
+ *
15
+ * 1. an order the engine does not hold yet is DEFERRED (PENDING, one attempt
16
+ * counted), so the reconcile pass applies the event after the order's own
17
+ * event ingests, and retires it after `maxInboxAttempts` like any row;
18
+ * 2. an order that is not ACCEPTED is never moved: the aceite is where the
19
+ * stock is judged, and an ended order is not revived;
20
+ * 3. a cancellation request standing (PENDING or REQUESTED) is the store's
21
+ * last word and nothing here contradicts it;
22
+ * 4. an event that answers a step WE informed (a STORE row for DISPATCHED, or
23
+ * for HANDED_OVER when the event is CONCLUDED) is an echo: the failure case
24
+ * of forward-only alone is the store's undo, where the echo would
25
+ * dispatch a card again with no courier.
26
+ *
27
+ * What the host owns (`onLifecycle`): whether the order can move, to where,
28
+ * and how. Whatever it answers, the step is NOTED as the marketplace's, so our
29
+ * own job never informs it back and nothing is informed after a CONCLUDED.
30
+ *
31
+ * A host that binds no `onLifecycle`, a connection with the switch OFF (or
32
+ * settings built by hand without it) and a host without the status model get
33
+ * `null`: the caller's old answer, "no order body", byte for byte.
34
+ */
35
+
36
+ /** The step of the table an event's echo is looked for under. */
37
+ const ECHO_OF: Record<MarketplaceLifecycle, "DISPATCHED" | "HANDED_OVER"> = {
38
+ DISPATCHED: "DISPATCHED",
39
+ CONCLUDED: "HANDED_OVER",
40
+ };
41
+
42
+ interface HeldAcceptance {
43
+ orderId: string;
44
+ status: string;
45
+ deliveredBy: string | null;
46
+ cancellationStatus: string | null;
47
+ }
48
+
49
+ /** Settle the row IGNORED with a reason, and answer it. */
50
+ async function ignored(ctx: EngineContext, inboxId: string, reason: string): Promise<DeliveryOutcome> {
51
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
52
+ return { kind: "ignored", reason };
53
+ }
54
+
55
+ /** Why a held order is not moved by the marketplace's word, or null when it may be. */
56
+ function refusal(held: HeldAcceptance): string | null {
57
+ if (held.status !== "ACCEPTED") return `the order is ${held.status}, not ACCEPTED`;
58
+ // A request that FAILED left the order the store's own: only a standing one stops us.
59
+ if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") {
60
+ return `a cancellation request is ${held.cancellationStatus}`;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function deliveredByOf(held: HeldAcceptance): MarketplaceDeliveredBy | null {
66
+ return held.deliveredBy === "MERCHANT" || held.deliveredBy === "MARKETPLACE" ? held.deliveredBy : null;
67
+ }
68
+
69
+ /** What `followLifecycle` needs once it is known the connection follows this event. */
70
+ interface Following {
71
+ lifecycle: MarketplaceLifecycle;
72
+ externalOrderId: string;
73
+ hook: NonNullable<EngineContext["ports"]["order"]["onLifecycle"]>;
74
+ }
75
+
76
+ /** Whether this ingestion follows this event at all: a lifecycle, the switch ON, a host hook. */
77
+ function following(ctx: EngineContext, event: NormalizedEvent, settings: IngestSettings): Following | null {
78
+ const hook = ctx.ports.order.onLifecycle;
79
+ if (!event.lifecycle || !event.externalOrderId || !settings.followStatus || !hook) return null;
80
+ return { lifecycle: event.lifecycle, externalOrderId: event.externalOrderId, hook };
81
+ }
82
+
83
+ /**
84
+ * Apply one lifecycle event, or null when this ingestion does not follow it
85
+ * (no lifecycle, switch OFF, no hook, no status model): the caller then does
86
+ * what it did before FUT-4653.
87
+ */
88
+ export async function followLifecycle(
89
+ ctx: EngineContext,
90
+ inboxId: string,
91
+ clientId: string,
92
+ event: NormalizedEvent,
93
+ settings: IngestSettings,
94
+ ): Promise<DeliveryOutcome | null> {
95
+ const follow = following(ctx, event, settings);
96
+ if (!follow) return null;
97
+ const { lifecycle, hook } = follow;
98
+ const db = await ctx.ports.db();
99
+ const table = statusTable(db);
100
+ if (!table) return null;
101
+
102
+ const held = (await db.marketplaceAcceptance.findFirst({
103
+ where: { clientId, provider: event.provider, externalOrderId: follow.externalOrderId },
104
+ select: { orderId: true, status: true, deliveredBy: true, cancellationStatus: true },
105
+ })) as HeldAcceptance | null;
106
+ if (!held) {
107
+ const reason = "lifecycle before its order";
108
+ await deferInboxEvent(ctx, inboxId, reason);
109
+ return { kind: "ignored", reason };
110
+ }
111
+ const stopped = refusal(held);
112
+ if (stopped) return ignored(ctx, inboxId, stopped);
113
+
114
+ const echo = ECHO_OF[lifecycle];
115
+ const ours = (await readStatusRows(table, held.orderId, [echo])).some((row) => row.source === "STORE");
116
+ if (ours) return ignored(ctx, inboxId, `echo of our ${echo}`);
117
+
118
+ // Two statements, not one: the echo was read above and the marketplace's word is noted below. A
119
+ // genuine event judged "no echo" can lose the unique on its note to our own job claiming in
120
+ // between, and that job then sends a step the marketplace already has. Harmless (at worst a 4xx,
121
+ // FAILED and logged): the marketplace's state and ours already agree, and a stricter ordering
122
+ // would put a write before the host's answer on every event.
123
+ const answer = await hook.call(ctx.ports.order, clientId, held.orderId, event, { deliveredBy: deliveredByOf(held) });
124
+ await noteMarketplaceStep(ctx, { clientId, orderId: held.orderId, provider: event.provider, step: lifecycle });
125
+ if (answer === "moved") {
126
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
127
+ ctx.ports.publishChanged(clientId);
128
+ return { kind: "moved", orderId: held.orderId, lifecycle };
129
+ }
130
+ const reason = answer === "unchanged" ? `already at or past ${lifecycle}` : answer.reason;
131
+ if (answer !== "unchanged") ctx.ports.logger.warn(`marketplace.lifecycle: ${event.provider} order ${held.orderId}: ${reason}`);
132
+ return ignored(ctx, inboxId, reason);
133
+ }