@12-apps/marketplace 1.12.0 → 1.14.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 (64) hide show
  1. package/ADOPTING.md +184 -0
  2. package/README.md +39 -4
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-nUyZpLzz.d.ts → adapter-szxo9ohc.d.ts} +84 -3
  6. package/dist/{chunk-L6FG6T4S.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-LACBT6NC.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-45ZVN5XI.js → chunk-MDXSVE7Q.js} +707 -255
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-MIPNQ7X5.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-Ctas7WCS.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-CIy9P7Cq.d.ts → engine-CgKBbk9J.d.ts} +127 -3
  15. package/dist/hono/index.d.ts +2 -2
  16. package/dist/hono/index.js +2 -2
  17. package/dist/ifood/index.d.ts +26 -3
  18. package/dist/ifood/index.js +301 -140
  19. package/dist/ifood/index.js.map +1 -1
  20. package/dist/index.d.ts +29 -5
  21. package/dist/index.js +54 -6
  22. package/dist/index.js.map +1 -1
  23. package/dist/keeta/index.d.ts +2 -2
  24. package/dist/keeta/index.js +2 -2
  25. package/dist/manifest/server.d.ts +4 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +14 -5
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +17 -3
  33. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  34. package/src/core/acceptance.ts +12 -6
  35. package/src/core/acknowledge.ts +189 -0
  36. package/src/core/adapter.ts +76 -2
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/connection-stamp.ts +61 -0
  40. package/src/core/engine.ts +3 -2
  41. package/src/core/fetch-order.ts +54 -12
  42. package/src/core/ingest.ts +6 -0
  43. package/src/core/integration.ts +19 -4
  44. package/src/core/link-store.ts +2 -4
  45. package/src/core/marketplace-confirmed.ts +229 -0
  46. package/src/core/order-reasons.ts +119 -0
  47. package/src/core/outbound.ts +5 -1
  48. package/src/core/pipeline.ts +27 -1
  49. package/src/core/ports.ts +2 -0
  50. package/src/core/registry.ts +28 -2
  51. package/src/core/state.ts +10 -0
  52. package/src/core/status-job.ts +86 -3
  53. package/src/core/types.ts +6 -0
  54. package/src/ifood/fetch-order.ts +103 -0
  55. package/src/ifood/index.ts +31 -4
  56. package/src/ifood/normalize.ts +39 -3
  57. package/src/ifood/outbound.ts +131 -27
  58. package/src/index.ts +18 -0
  59. package/src/server/jobs.ts +57 -4
  60. package/src/server/webhook.ts +27 -4
  61. package/dist/chunk-45ZVN5XI.js.map +0 -1
  62. package/dist/chunk-LACBT6NC.js.map +0 -1
  63. package/dist/chunk-MIPNQ7X5.js.map +0 -1
  64. /package/dist/{chunk-L6FG6T4S.js.map → chunk-BNWRIR5J.js.map} +0 -0
@@ -38,6 +38,10 @@ import { readIfoodCourierEvent } from "./courier";
38
38
  /** iFood event codes this ingestion acts on. */
39
39
  const ORDER_PLACED = new Set(["PLC", "PLACED", "ORDER_PLACED"]);
40
40
  const ORDER_CANCELLED = new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
41
+ /** The store accepted the order on iFood's own app (FUT-5653). Also the echo of our own confirm. */
42
+ const ORDER_CONFIRMED = new Set(["CFM", "CONFIRMED"]);
43
+ /** iFood's presence heartbeat (FUT-5984, `presence.md`): every 30 s, naming no order. */
44
+ const KEEPALIVE = "KEEPALIVE";
41
45
  /** iFood refused the store's own cancellation request. */
42
46
  const CANCELLATION_REQUEST_FAILED = new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
43
47
 
@@ -202,8 +206,12 @@ function optional<K extends string, V>(key: K, value: V | undefined): { [P in K]
202
206
  return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });
203
207
  }
204
208
 
205
- /** The order body of a placed-order event, or null when it carries none. */
206
- function readOrder(
209
+ /**
210
+ * The order body of a placed-order event, or null when it carries none. Also
211
+ * reads the order iFood serves at `GET /order/v1.0/orders/{id}` (`./fetch-order.ts`),
212
+ * whose fields are the same ones the event's `order` would carry.
213
+ */
214
+ export function readIfoodOrder(
207
215
  payload: unknown,
208
216
  externalOrderId: string,
209
217
  missingStreetNumber: string,
@@ -246,6 +254,22 @@ function readOrder(
246
254
  };
247
255
  }
248
256
 
257
+ /**
258
+ * The order a PLACED carries, or, when it carries none, the mark that has it
259
+ * fetched: iFood's events carry only the order id (sandbox, 2026-11-27), so the
260
+ * `marketplace.fetch-order` job reads it (FUT-5800). Any other event: no order.
261
+ */
262
+ function placedOrder(
263
+ payload: unknown,
264
+ placed: boolean,
265
+ externalOrderId: string,
266
+ missingStreetNumber: string,
267
+ ): Pick<NormalizedEvent, "order" | "orderToFetch"> {
268
+ if (!placed) return { order: null };
269
+ const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);
270
+ return order ? { order } : { order: null, orderToFetch: true };
271
+ }
272
+
249
273
  /**
250
274
  * Normalize one iFood delivery.
251
275
  *
@@ -276,10 +300,22 @@ export function normalizeIfoodEvent(
276
300
  eventType,
277
301
  externalMerchantId: firstString(payload, [["merchantId"], ["merchant", "id"]]),
278
302
  externalOrderId,
279
- order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
303
+ ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),
280
304
  cancelled,
281
305
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
282
306
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
283
307
  ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
308
+ ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
284
309
  };
285
310
  }
311
+
312
+ /**
313
+ * iFood's `KEEPALIVE` (FUT-5984): `{ code, fullCode, id }`, and `merchantIds`
314
+ * in the per-merchant mode. Null for any other delivery.
315
+ */
316
+ export function readIfoodPresence(payload: unknown): { merchantIds: readonly string[] | null } | null {
317
+ const code = firstString(payload, [["fullCode"], ["code"]]);
318
+ if (code?.toUpperCase() !== KEEPALIVE) return null;
319
+ const ids = pick(payload, "merchantIds");
320
+ return { merchantIds: Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : null };
321
+ }
@@ -4,9 +4,14 @@ import {
4
4
  tokenGrantResultOf,
5
5
  type AdapterCallContext,
6
6
  type CancellationRequestInput,
7
+ type MarketplaceAcknowledgement,
8
+ type MarketplaceHttpResponse,
9
+ type OrderCancellationReason,
10
+ type OrderCancellationReasonsResult,
7
11
  type OutboundOrderRef,
8
12
  type OutboundResult,
9
13
  type StatusFacts,
14
+ type StatusStep,
10
15
  } from "../core/adapter";
11
16
 
12
17
  /**
@@ -35,9 +40,6 @@ const orderUrl = (externalOrderId: string, action: string): string =>
35
40
  */
36
41
  export const IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
37
42
 
38
- /** A token is renewed this long before iFood says it expires. */
39
- const TOKEN_MARGIN_MS = 60_000;
40
-
41
43
  /**
42
44
  * The token cache key: per environment and merchant app, or, for a store
43
45
  * linked through the software's app (FUT-5613), the store's own grant key, so
@@ -68,7 +70,9 @@ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string }
68
70
  if (ctx.grant) return ctx.grant.accessToken();
69
71
  const key = ifoodTokenKey(ctx);
70
72
  const cached = ctx.tokens.get(key);
71
- if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
73
+ // Renewed only once expired, never early: "Renove tokens de autenticação apenas quando expirados,
74
+ // não antecipadamente" (iFood's Order homologation criteria, FUT-5984). A 401 renews it sooner.
75
+ if (cached && cached.expiresAt > ctx.now.getTime()) return { token: cached.token };
72
76
  const response = await ctx.http({
73
77
  method: "POST",
74
78
  url: TOKEN_URL,
@@ -86,26 +90,56 @@ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string }
86
90
  return { token: token.token };
87
91
  }
88
92
 
89
- /** One authenticated POST to an order's resource. */
90
- function postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {
91
- return answered(async () => {
93
+ /**
94
+ * One authenticated call, its token renewed once on a 401: the token is
95
+ * forgotten, a new one bought and the call made again, inside the same call
96
+ * (iFood: "Prepare seu aplicativo para solicitar um novo token quando receber
97
+ * status 401"). A second 401 forgets that one too and answers `null`.
98
+ */
99
+ async function withIfoodToken(
100
+ ctx: AdapterCallContext,
101
+ call: (token: string) => Promise<MarketplaceHttpResponse>,
102
+ ): Promise<MarketplaceHttpResponse | OutboundResult | null> {
103
+ for (let round = 0; round < 2; round += 1) {
92
104
  const auth = await bearer(ctx);
93
105
  if (!("token" in auth)) return auth;
94
- const response = await ctx.http({
95
- method: "POST",
96
- url: orderUrl(externalOrderId, action),
97
- headers: {
98
- Authorization: `Bearer ${auth.token}`,
99
- ...(body === undefined ? {} : { "Content-Type": "application/json" }),
100
- },
101
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
102
- });
103
- // A 401 is a token that went stale under us: forget it, and the retry fetches another.
104
- if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));
105
- return response.status === 401 ? { kind: "retry", reason: "iFood refused the token" } : outboundResultOf(response);
106
+ const response = await call(auth.token);
107
+ if (response.status !== 401) return response;
108
+ ctx.tokens.delete(ifoodTokenKey(ctx));
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /** One authenticated request to an order's resource. */
114
+ function callOrder(
115
+ ctx: AdapterCallContext,
116
+ externalOrderId: string,
117
+ action: string,
118
+ body?: unknown,
119
+ method: "POST" | "GET" = "POST",
120
+ ): Promise<OutboundResult> {
121
+ return answered(async () => {
122
+ const response = await withIfoodToken(ctx, (token) =>
123
+ ctx.http({
124
+ method,
125
+ url: orderUrl(externalOrderId, action),
126
+ headers: {
127
+ Authorization: `Bearer ${token}`,
128
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
129
+ },
130
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
131
+ }),
132
+ );
133
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
134
+ return "kind" in response ? response : outboundResultOf(response);
106
135
  });
107
136
  }
108
137
 
138
+ /** One authenticated POST to an order's resource. */
139
+ function postOrder(ctx: AdapterCallContext, externalOrderId: string, action: string, body?: unknown): Promise<OutboundResult> {
140
+ return callOrder(ctx, externalOrderId, action, body);
141
+ }
142
+
109
143
  /** Tell iFood the store accepted the order. No body: the URL names the order. */
110
144
  export function ifoodConfirm(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<OutboundResult> {
111
145
  return postOrder(ctx, order.externalOrderId, "confirm");
@@ -117,12 +151,73 @@ export function ifoodRequestCancellation(
117
151
  order: OutboundOrderRef,
118
152
  input: CancellationRequestInput,
119
153
  ): Promise<OutboundResult> {
120
- return postOrder(ctx, order.externalOrderId, "requestCancellation", {
121
- reason: input.text === "" ? input.reason.label : input.text,
122
- cancellationCode: input.reason.code,
154
+ // The body is the code alone (`cancellation.md`: `-d '{"reason": "503"}'`), one of the order's own
155
+ // `cancellationReasons` (FUT-5984); iFood takes no free text with it.
156
+ return postOrder(ctx, order.externalOrderId, "requestCancellation", { reason: input.reason.code });
157
+ }
158
+
159
+ /** iFood's reasons for this order, read live (FUT-5984): `{ reasons: [{ code, description }] }`, or a bare array. */
160
+ function reasonsOf(body: string): OrderCancellationReason[] | null {
161
+ try {
162
+ const parsed = JSON.parse(body) as unknown;
163
+ const list = Array.isArray(parsed) ? parsed : (parsed as { reasons?: unknown } | null)?.reasons;
164
+ if (!Array.isArray(list)) return null;
165
+ return list.flatMap((entry: unknown) => {
166
+ const { code, description } = (entry ?? {}) as { code?: unknown; description?: unknown };
167
+ if (typeof code !== "string" && typeof code !== "number") return [];
168
+ return [{ code: String(code), description: typeof description === "string" ? description : String(code) }];
169
+ });
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+
175
+ /** `GET /order/v1.0/orders/{id}/cancellationReasons`: the codes iFood accepts for cancelling this order now. */
176
+ export async function ifoodOrderCancellationReasons(
177
+ ctx: AdapterCallContext,
178
+ order: { externalOrderId: string },
179
+ ): Promise<OrderCancellationReasonsResult> {
180
+ let body = "";
181
+ const result = await answered(async () => {
182
+ const response = await withIfoodToken(ctx, (token) =>
183
+ ctx.http({ method: "GET", url: orderUrl(order.externalOrderId, "cancellationReasons"), headers: { Authorization: `Bearer ${token}` } }),
184
+ );
185
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
186
+ if ("kind" in response) return response;
187
+ body = response.body;
188
+ return outboundResultOf(response);
123
189
  });
190
+ if (result.kind !== "accepted") return result;
191
+ const reasons = reasonsOf(body);
192
+ return reasons ? { kind: "reasons", reasons } : { kind: "retry", reason: "iFood answered the reasons with no list" };
124
193
  }
125
194
 
195
+ /** iFood keeps an event 8 hours (`polling-overview`: "até 8 horas"); an older one is never acknowledged. */
196
+ const IFOOD_EVENT_RETENTION_MS = 8 * 60 * 60_000;
197
+
198
+ /**
199
+ * Acknowledge recorded events (FUT-5984): `POST /events/v1.0/events/acknowledgment`
200
+ * with `[{ id }]`, at most 2000 ids a call ("Limite: até 2000 IDs por requisição").
201
+ */
202
+ export const IFOOD_ACKNOWLEDGEMENT: MarketplaceAcknowledgement = {
203
+ batchSize: 2000,
204
+ retentionMs: IFOOD_EVENT_RETENTION_MS,
205
+ send: (ctx, eventIds) =>
206
+ answered(async () => {
207
+ const body = JSON.stringify(eventIds.map((id) => ({ id })));
208
+ const response = await withIfoodToken(ctx, (token) =>
209
+ ctx.http({
210
+ method: "POST",
211
+ url: `${IFOOD_API}/events/v1.0/events/acknowledgment`,
212
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
213
+ body,
214
+ }),
215
+ );
216
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
217
+ return "kind" in response ? response : outboundResultOf(response);
218
+ }),
219
+ };
220
+
126
221
  /**
127
222
  * What iFood is told, per step (FUT-4653). ESTIMATED, every row: iFood's
128
223
  * developer portal answered 403 behind Cloudflare to our reader
@@ -130,18 +225,27 @@ export function ifoodRequestCancellation(
130
225
  * the Merchant API's commonly documented ones (`order/v1.0`), not read off a
131
226
  * page.
132
227
  *
133
- * - READY: `POST /orders/{id}/readyToPickup`, for a take-out, and ESTIMATED
134
- * whether iFood takes it for its own fleet; not for a bag the merchant
135
- * delivers, which is dispatched, not made ready for pickup.
136
- * - DISPATCHED: `POST /orders/{id}/dispatch`, only for `deliveredBy: MERCHANT`.
228
+ * - READY: `POST /orders/{id}/readyToPickup`, for every order: CONFIRMED for
229
+ * the merchant's own bag by the Order Endpoints page (read 2026-12-02), which
230
+ * wants it before the dispatch. The homologation page spells it PUT; the
231
+ * Endpoints page's POST is kept.
232
+ * - DISPATCHED: `POST /orders/{id}/dispatch`, only for `deliveredBy: MERCHANT`,
233
+ * strictly after READY ({@link ifoodStatusPrerequisite}).
137
234
  * - HANDED_OVER: none. iFood has no conclude endpoint for a merchant;
138
235
  * CONCLUDED is iFood's own event.
139
236
  */
140
237
  const STATUS_ACTION: Readonly<Record<string, (facts: StatusFacts) => string | null>> = {
141
- READY: (facts) => (facts.deliveredBy === "MERCHANT" ? null : "readyToPickup"),
238
+ // Every order, the merchant's own bag included (FUT-5984, `endpoints.md`: "Para entrega própria,
239
+ // notifique o pedido pronto via `POST /orders/{id}/readyToPickup` antes de despachar via `/dispatch`").
240
+ READY: () => "readyToPickup",
142
241
  DISPATCHED: (facts) => (facts.deliveredBy === "MERCHANT" ? "dispatch" : null),
143
242
  };
144
243
 
244
+ /** A merchant bag's dispatch goes strictly after its `readyToPickup` (FUT-5984). */
245
+ export function ifoodStatusPrerequisite(facts: StatusFacts): StatusStep | null {
246
+ return facts.step === "DISPATCHED" && facts.deliveredBy === "MERCHANT" ? "READY" : null;
247
+ }
248
+
145
249
  /** Whether iFood takes this step for this kind of order: answered offline. */
146
250
  export function ifoodStatusSupported(facts: StatusFacts): boolean {
147
251
  return STATUS_ACTION[facts.step]?.(facts) != null;
package/src/index.ts CHANGED
@@ -39,6 +39,10 @@ export {
39
39
  type MarketplaceHttp,
40
40
  type MarketplaceHttpRequest,
41
41
  type MarketplaceHttpResponse,
42
+ type MarketplaceAcknowledgement,
43
+ type OrderCancellationReason,
44
+ type OrderCancellationReasonsResult,
45
+ type PresenceProbe,
42
46
  type OutboundOrderRef,
43
47
  type StatusFacts,
44
48
  type StatusStep,
@@ -159,6 +163,20 @@ export {
159
163
  type FetchOrderOutcome,
160
164
  } from "./core/fetch-order";
161
165
  export type { MarketplaceOrderState } from "./core/state";
166
+ export {
167
+ AcknowledgeRetryError,
168
+ MARKETPLACE_ACKNOWLEDGE_JOB,
169
+ type AcknowledgeJobPayload,
170
+ type AcknowledgeOutcome,
171
+ } from "./core/acknowledge";
172
+ export {
173
+ CancellationReasonsRetryError,
174
+ MARKETPLACE_CANCELLATION_REASONS_JOB,
175
+ type CancellationReasonsJobPayload,
176
+ type CancellationReasonsOutcome,
177
+ } from "./core/order-reasons";
178
+ export { CONFIRMED_BEFORE_ORDER } from "./core/marketplace-confirmed";
179
+ export type { MarketplaceConformityEngine } from "./core/conformity";
162
180
  export {
163
181
  CatalogueRetryError,
164
182
  catalogueDedupeKey,
@@ -2,14 +2,16 @@ import type { JobsContribution, WireJobBlueprint } from "@12-apps/wiring";
2
2
 
3
3
  import type { MarketplaceEngine } from "../core/engine";
4
4
  import { CatalogueRetryError, type CatalogueJobPayload } from "../core/catalogue-job";
5
+ import { AcknowledgeRetryError, type AcknowledgeJobPayload } from "../core/acknowledge";
5
6
  import { FetchOrderRetryError, type FetchOrderJobPayload } from "../core/fetch-order";
7
+ import { CancellationReasonsRetryError, type CancellationReasonsJobPayload } from "../core/order-reasons";
6
8
  import { OutboundRetryError } from "../core/outbound";
7
9
  import type { OutboundJobPayload } from "../core/outbound-queue";
8
10
  import { AvailabilityRetryError } from "../core/pause-job";
9
11
  import type { AvailabilityJobPayload } from "../core/pause-store";
10
12
 
11
13
  /**
12
- * The engine's eight jobs, declared here because every number in them is the
14
+ * The engine's ten jobs, declared here because every number in them is the
13
15
  * engine's knowledge, not a host's:
14
16
  *
15
17
  * - `expire-acceptances`, every minute: the unit being measured is minutes (a
@@ -24,6 +26,12 @@ import type { AvailabilityJobPayload } from "../core/pause-store";
24
26
  * - `fetch-order`, on demand: one GET of an order a marketplace's event only
25
27
  * announced (`orderToFetch`), then the one ingest path. Three attempts with
26
28
  * backoff; the reconciliation sweep re-queues a row still owed.
29
+ * - `acknowledge`, on demand: tells the marketplace a store's recorded events
30
+ * were received (FUT-5984, iFood). Three attempts with backoff; the
31
+ * reconcile pass re-queues a store still owing some.
32
+ * - `cancellation-reasons`, on demand: reads one order's own cancellation
33
+ * reasons once, after its ingest (FUT-5984, iFood). Three attempts; the
34
+ * static list stays the fallback.
27
35
  * - `catalogue`, on demand: one publish or withdraw of one product on one
28
36
  * marketplace's catalogue (FUT-4768). Three attempts with backoff; the
29
37
  * last one stamps FAILED with a failure code.
@@ -43,7 +51,8 @@ import type { AvailabilityJobPayload } from "../core/pause-store";
43
51
  *
44
52
  * Bound with `{ engine }`, these arrive at a runner as
45
53
  * `marketplace.expire-acceptances`, `marketplace.reconcile-inbox`,
46
- * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.catalogue`,
54
+ * `marketplace.outbound`, `marketplace.fetch-order`, `marketplace.acknowledge`,
55
+ * `marketplace.cancellation-reasons`, `marketplace.catalogue`,
47
56
  * `marketplace.outbound-sweep`, `marketplace.availability` and
48
57
  * `marketplace.availability-sweep`.
49
58
  */
@@ -57,6 +66,9 @@ export interface MarketplaceJobDeps {
57
66
  | "reprocess"
58
67
  | "runOutbound"
59
68
  | "runFetchOrder"
69
+ | "runAcknowledge"
70
+ | "sweepAcknowledgements"
71
+ | "runCancellationReasons"
60
72
  | "runCatalogue"
61
73
  | "sweepOutbound"
62
74
  | "runAvailability"
@@ -105,9 +117,12 @@ const reconcileInbox: WireJobBlueprint<void, MarketplaceJobDeps> = {
105
117
  const outcome = await deps.engine.reprocess(event);
106
118
  if (outcome.kind === "ingested") ingested += 1;
107
119
  }
108
- if (pending.length === 0) return;
120
+ // The events still owed an acknowledgment are re-queued, one job per store (FUT-5984).
121
+ const { requeued } = await deps.engine.sweepAcknowledgements();
122
+ if (pending.length === 0 && requeued === 0) return;
109
123
  context.logger.info(
110
- `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s).`,
124
+ `marketplace.reconcile-inbox: re-ran ${pending.length} stored delivery(ies), ${ingested} became order(s); ` +
125
+ `re-queued the acknowledgment of ${requeued} store(s).`,
111
126
  );
112
127
  },
113
128
  };
@@ -156,6 +171,42 @@ const fetchOrder: WireJobBlueprint<FetchOrderJobPayload, MarketplaceJobDeps> = {
156
171
  },
157
172
  };
158
173
 
174
+ /** The acknowledgment's attempts: the last one leaves the events owed, for the reconcile pass. */
175
+ const MARKETPLACE_ACKNOWLEDGE_ATTEMPTS = 3;
176
+
177
+ const acknowledge: WireJobBlueprint<AcknowledgeJobPayload, MarketplaceJobDeps> = {
178
+ name: "acknowledge",
179
+ attempts: MARKETPLACE_ACKNOWLEDGE_ATTEMPTS,
180
+ backoff: { type: "exponential", delayMs: 10_000 },
181
+ handle: async (payload, deps, context) => {
182
+ try {
183
+ const outcome = await deps.engine.runAcknowledge(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });
184
+ if (outcome.kind === "skipped") context.logger.info(`marketplace.acknowledge: ${payload.provider} ${payload.clientId} skipped: ${outcome.reason}`);
185
+ } catch (error) {
186
+ if (error instanceof AcknowledgeRetryError) context.logger.warn(`marketplace.acknowledge: ${error.message}`);
187
+ throw error;
188
+ }
189
+ },
190
+ };
191
+
192
+ /** The reasons read's attempts: the last one leaves the static list in place. */
193
+ const MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS = 3;
194
+
195
+ const cancellationReasons: WireJobBlueprint<CancellationReasonsJobPayload, MarketplaceJobDeps> = {
196
+ name: "cancellation-reasons",
197
+ attempts: MARKETPLACE_CANCELLATION_REASONS_ATTEMPTS,
198
+ backoff: { type: "exponential", delayMs: 10_000 },
199
+ handle: async (payload, deps, context) => {
200
+ try {
201
+ const outcome = await deps.engine.runCancellationReasons(payload, { attempt: context.attempt, maxAttempts: context.maxAttempts });
202
+ if (outcome.kind === "skipped") context.logger.info(`marketplace.cancellation-reasons: ${payload.orderId} skipped: ${outcome.reason}`);
203
+ } catch (error) {
204
+ if (error instanceof CancellationReasonsRetryError) context.logger.warn(`marketplace.cancellation-reasons: ${error.message}`);
205
+ throw error;
206
+ }
207
+ },
208
+ };
209
+
159
210
  /** The catalogue job's attempts: the last one stamps FAILED. */
160
211
  const MARKETPLACE_CATALOGUE_ATTEMPTS = 3;
161
212
 
@@ -247,6 +298,8 @@ export const MARKETPLACE_JOBS = {
247
298
  "reconcile-inbox": reconcileInbox,
248
299
  outbound,
249
300
  "fetch-order": fetchOrder,
301
+ acknowledge,
302
+ "cancellation-reasons": cancellationReasons,
250
303
  catalogue,
251
304
  "outbound-sweep": outboundSweep,
252
305
  availability,
@@ -1,5 +1,6 @@
1
1
  import type { WireRequest, WireResponse, WireRoute } from "@12-apps/wiring";
2
2
 
3
+ import type { PresenceProbe } from "../core/adapter";
3
4
  import type { IngestionTarget } from "../core/integration";
4
5
  import type { MarketplaceApiConfig } from "./http";
5
6
 
@@ -13,7 +14,8 @@ import type { MarketplaceApiConfig } from "./http";
13
14
  * (which header carries the signature, and how it is computed) — the route
14
15
  * itself knows no marketplace.
15
16
  *
16
- * It answers 2xx for almost everything, deliberately. A marketplace
17
+ * It answers 2xx for almost everything, deliberately: 200, or the status the
18
+ * adapter states (`webhookAnswerStatus`: iFood's 202, FUT-5984). A marketplace
17
19
  * redelivers on any non-2xx, so the only failures worth signalling are the
18
20
  * ones a redelivery could fix: a genuine processing failure answers 500, and
19
21
  * the inbox row it left is retried by the sweep regardless. Refusals (unknown
@@ -93,17 +95,31 @@ async function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<
93
95
  return deliverAdmitted(config, admitted);
94
96
  }
95
97
 
98
+ /**
99
+ * The answer to a proven presence heartbeat (FUT-5984, iFood's `KEEPALIVE`):
100
+ * 202, and in the per-merchant mode every merchant it asked about named
101
+ * online. Nothing is recorded.
102
+ */
103
+ function presenceAnswer(probe: PresenceProbe): WireResponse {
104
+ return probe.merchantIds === null
105
+ ? { status: 202, body: { received: true } }
106
+ : { status: 202, body: { merchantIds: [...probe.merchantIds] } };
107
+ }
108
+
96
109
  /** Record and act on a delivery whose store and signature are proven. */
97
110
  async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {
98
111
  const { clientId, provider, payload, target } = admitted;
99
112
  const { engine } = config;
113
+ const probe = engine.presence(provider, payload);
114
+ if (probe) return presenceAnswer(probe);
115
+ const status = engine.answerStatus(provider);
100
116
 
101
117
  const event = engine.normalize(provider, payload);
102
118
  if (!event) {
103
- // Nothing the adapter can key on. 200: redelivering an unreadable payload
119
+ // Nothing the adapter can key on. 2xx: redelivering an unreadable payload
104
120
  // produces an identical unreadable payload.
105
121
  config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);
106
- return { status: 200, body: { received: true, ignored: "unrecognized_payload" } };
122
+ return { status, body: { received: true, ignored: "unrecognized_payload" } };
107
123
  }
108
124
  const outcome = await engine.deliver({
109
125
  clientId,
@@ -118,7 +134,8 @@ async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted)
118
134
  if (outcome.kind === "failed") {
119
135
  return { status: 500, body: { received: true, error: outcome.reason } };
120
136
  }
121
- return { status: 200, body: { received: true, outcome: outcome.kind } };
137
+ // After the inbox row is written: iFood's 202 means "recorded" (FUT-5984).
138
+ return { status, body: { received: true, outcome: outcome.kind } };
122
139
  }
123
140
 
124
141
  /**
@@ -138,6 +155,12 @@ async function admitApp(
138
155
  const rawBody = await raw.text();
139
156
  const payload = parsedJson(rawBody);
140
157
  if (payload === undefined) return { status: 400, body: { error: "invalid_json" } };
158
+ // A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).
159
+ const probe = config.engine.presence(provider, payload);
160
+ if (probe) {
161
+ const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
162
+ return (await config.engine.signedByApp(provider, rawBody, signature)) ? presenceAnswer(probe) : UNAUTHORIZED;
163
+ }
141
164
  const found = await appConnection(config, provider, payload);
142
165
  if ("status" in found) return found;
143
166
  // The app's address never takes an unsigned delivery, whatever the store's own setting.