@12-apps/marketplace 1.13.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 (60) hide show
  1. package/ADOPTING.md +143 -3
  2. package/README.md +27 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CQ4QiZPi.d.ts → adapter-szxo9ohc.d.ts} +82 -2
  6. package/dist/{chunk-NFJQQWG4.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-CEWTV2TC.js → chunk-MDXSVE7Q.js} +652 -246
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-W57TITU4.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-CCSnylou.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-1KlJ_8jK.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 +13 -3
  18. package/dist/ifood/index.js +114 -23
  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 +74 -1
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/engine.ts +3 -2
  40. package/src/core/ingest.ts +6 -0
  41. package/src/core/link-store.ts +2 -4
  42. package/src/core/marketplace-confirmed.ts +229 -0
  43. package/src/core/order-reasons.ts +119 -0
  44. package/src/core/outbound.ts +5 -1
  45. package/src/core/pipeline.ts +27 -1
  46. package/src/core/ports.ts +2 -0
  47. package/src/core/registry.ts +28 -2
  48. package/src/core/state.ts +10 -0
  49. package/src/core/status-job.ts +86 -3
  50. package/src/core/types.ts +6 -0
  51. package/src/ifood/index.ts +27 -4
  52. package/src/ifood/normalize.ts +16 -0
  53. package/src/ifood/outbound.ts +131 -27
  54. package/src/index.ts +18 -0
  55. package/src/server/jobs.ts +57 -4
  56. package/src/server/webhook.ts +27 -4
  57. package/dist/chunk-4J2KJ3ZW.js.map +0 -1
  58. package/dist/chunk-CEWTV2TC.js.map +0 -1
  59. package/dist/chunk-W57TITU4.js.map +0 -1
  60. /package/dist/{chunk-NFJQQWG4.js.map → chunk-BNWRIR5J.js.map} +0 -0
@@ -11,7 +11,11 @@ import type { MarketplaceDeliveredBy } from "./types";
11
11
  *
12
12
  * In order, stopping at the first rule that fails, with no row and no call:
13
13
  *
14
- * 1. the acceptance is ACCEPTED and no cancellation request stands;
14
+ * 1. the acceptance is ACCEPTED and no cancellation request stands, and the
15
+ * marketplace took the store's confirm (`confirmedAt`, FUT-5673), for a
16
+ * marketplace that states `statusAfterConfirm` (iFood): while the confirm
17
+ * is still owed the job is retried, and once it failed (`confirmFailedAt`)
18
+ * or on the last attempt it is skipped; any other marketplace never waits;
15
19
  * 2. the adapter states the step and takes it for this kind of order;
16
20
  * 3. the host says the order still holds the step (a dispatch undone inside
17
21
  * the board's undo window sends nothing);
@@ -19,7 +23,12 @@ import type { MarketplaceDeliveredBy } from "./types";
19
23
  * the order (a step it announced itself is in the same table);
20
24
  * 5. claim: insert the row (STORE, SENDING), unique on (order, step); a lost
21
25
  * claim stops the run;
22
- * 6. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
26
+ * 6. a step the adapter says must follow another for this order
27
+ * (`statusPrerequisite`: iFood's dispatch of a merchant bag follows its
28
+ * `readyToPickup`, FUT-5984) sends that one first, under its own row,
29
+ * unless it is already SENT or FAILED; one still SENDING under another run
30
+ * makes this one wait (retried);
31
+ * 7. call the adapter: 2xx SENT; a final 4xx FAILED, logged at error, never
23
32
  * retried; 408/425/429/5xx/timeout retried, the last attempt FAILED. A run
24
33
  * on a SENDING row it owns (a retry, or the sweep's re-queue) calls again.
25
34
  *
@@ -34,6 +43,8 @@ interface StatusJobRow {
34
43
  status: string;
35
44
  cancellationStatus: string | null;
36
45
  deliveredBy: string | null;
46
+ confirmedAt?: Date | null;
47
+ confirmFailedAt?: Date | null;
37
48
  }
38
49
 
39
50
  /** What one run did, in the outbound job's own shape. */
@@ -61,6 +72,20 @@ function acceptanceSkip(row: StatusJobRow): string | null {
61
72
  return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
62
73
  }
63
74
 
75
+ /**
76
+ * Rule 1's second half (FUT-5673): why the confirm stops the job, or null once
77
+ * the marketplace took it. Still owed and attempts left: retried.
78
+ */
79
+ function confirmSkip(row: StatusJobRow, adapter: MarketplaceAdapter, deps: StatusJobDeps): string | null {
80
+ // Only a marketplace that states it (iFood, FUT-5673): every other one tells its steps as before.
81
+ if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
82
+ if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
83
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) {
84
+ throw deps.retryError(`status for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
85
+ }
86
+ return "the store's confirm has not reached the marketplace";
87
+ }
88
+
64
89
  /** Why rules 2 and 3 stop the job, or null. Rule 3 asks the host, so it comes last. */
65
90
  async function adapterAndHostSkip(
66
91
  ctx: EngineContext,
@@ -177,7 +202,7 @@ export async function runStatus(
177
202
  ): Promise<StatusJobOutcome> {
178
203
  const step = payload.step;
179
204
  if (!step) return skipped("a status call names no step");
180
- const stopped = acceptanceSkip(row) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
205
+ const stopped = acceptanceSkip(row) ?? confirmSkip(row, adapter, deps) ?? (await adapterAndHostSkip(ctx, payload, step, row, adapter));
181
206
  if (stopped) return skipped(stopped);
182
207
  const db = await ctx.ports.db();
183
208
  const table = statusTable(db);
@@ -194,10 +219,68 @@ export async function runStatus(
194
219
  const key = payload.claimKey ?? "";
195
220
  const unclaimed = await claim(table, payload, row, step, key);
196
221
  if (unclaimed) return skipped(unclaimed);
222
+ const before = await sendPrerequisite(ctx, { table, payload, row, step, key, connection, adapter }, deps);
223
+ if (before) return before;
197
224
  const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
198
225
  return settle(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
199
226
  }
200
227
 
228
+ /** What rule 6 needs: the claimed step's run, and the connection it calls with. */
229
+ interface PrerequisiteRun {
230
+ table: NonNullable<MarketplaceDb["marketplaceStatusUpdate"]>;
231
+ payload: OutboundJobPayload;
232
+ row: StatusJobRow;
233
+ step: StatusStep;
234
+ key: string;
235
+ connection: OutboundConnection;
236
+ adapter: MarketplaceAdapter;
237
+ }
238
+
239
+ /**
240
+ * Whether a prerequisite row lets this run go on: `proceed` (it stands SENT or
241
+ * FAILED), `send` (absent, or this run's own claim), or a wait. A wait is
242
+ * retried; on the last attempt it ends skipped, never sent out of order.
243
+ */
244
+ function prerequisiteState(
245
+ found: StatusRow | undefined,
246
+ key: string,
247
+ run: PrerequisiteRun,
248
+ first: StatusStep,
249
+ deps: StatusJobDeps,
250
+ ): "proceed" | "send" | StatusJobOutcome {
251
+ if (!found || ownsClaim(found, key)) return "send";
252
+ if (found.state !== "SENDING") return "proceed";
253
+ if (deps.attempt.attempt < deps.attempt.maxAttempts) {
254
+ throw deps.retryError(`status ${run.step} for order ${run.row.orderId}: waiting for ${first}, held by another run`);
255
+ }
256
+ return skipped(`${first} is still being sent by another run`);
257
+ }
258
+
259
+ /**
260
+ * Rule 6: the step this one must follow, sent first under its own row and key
261
+ * (`<key>:<step>`, so this run's retry owns it), or null when there is none or
262
+ * it already stands. A prerequisite refused is FAILED and logged; the step
263
+ * itself still goes.
264
+ */
265
+ async function sendPrerequisite(ctx: EngineContext, run: PrerequisiteRun, deps: StatusJobDeps): Promise<StatusJobOutcome | null> {
266
+ const first = run.adapter.statusPrerequisite?.({ step: run.step, deliveredBy: deliveredByOf(run.row) }) ?? null;
267
+ if (first === null) return null;
268
+ const key = `${run.key}:${first}`;
269
+ const [found] = await readStatusRows(run.table, run.row.orderId, [first]);
270
+ const state = prerequisiteState(found, key, run, first, deps);
271
+ if (state === "proceed") return null;
272
+ if (typeof state !== "string") return state;
273
+ if (!found) {
274
+ const row = { clientId: run.payload.clientId, orderId: run.row.orderId, provider: run.row.provider };
275
+ const claimed = await insertStatusRow(run.table, { ...row, step: first, source: "STORE", state: "SENDING", claimKey: key });
276
+ if (!claimed) return sendPrerequisite(ctx, run, deps);
277
+ }
278
+ const result = await callAdapter(ctx, run.connection, run.adapter, run.row, first, deps.ref);
279
+ const outcome = await settle(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
280
+ return outcome.kind === "skipped" ? outcome : null;
281
+ }
282
+
283
+
201
284
  /** The last attempt died without an answer: FAILED, never left SENDING. Best-effort. */
202
285
  export async function failStatusRow(ctx: EngineContext, payload: OutboundJobPayload): Promise<void> {
203
286
  const table = statusTable(await ctx.ports.db());
package/src/core/types.ts CHANGED
@@ -233,4 +233,10 @@ export interface NormalizedEvent {
233
233
  * names no courier step.
234
234
  */
235
235
  courier?: NormalizedCourierEvent | null;
236
+ /**
237
+ * OPTIONAL (FUT-5653). The store accepted the order in the marketplace's own
238
+ * app (iFood's `CFM`): an order still AWAITING here is accepted through the
239
+ * host's admit, with no confirm sent back. Carries no order body.
240
+ */
241
+ marketplaceConfirmed?: boolean;
236
242
  }
@@ -5,8 +5,17 @@ import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
5
  import { IFOOD_COURIER } from "./courier";
6
6
  import { ifoodFetchOrder } from "./fetch-order";
7
7
  import { IFOOD_LINKING } from "./linking";
8
- import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
9
- import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
8
+ import { normalizeIfoodEvent, readIfoodPresence, verifyIfoodSignature } from "./normalize";
9
+ import {
10
+ IFOOD_ACKNOWLEDGEMENT,
11
+ IFOOD_PORTAL_URL,
12
+ ifoodConfirm,
13
+ ifoodInformStatus,
14
+ ifoodOrderCancellationReasons,
15
+ ifoodRequestCancellation,
16
+ ifoodStatusPrerequisite,
17
+ ifoodStatusSupported,
18
+ } from "./outbound";
10
19
  import { IFOOD_AVAILABILITY } from "./pause";
11
20
 
12
21
  /**
@@ -39,7 +48,10 @@ export interface IfoodAdapterConfig {
39
48
  copy: IfoodAdapterCopy;
40
49
  }
41
50
 
42
- /** Build the iFood adapter. Its reasons are static: a dialog never waits on iFood. */
51
+ /**
52
+ * Build the iFood adapter. Its static reasons are the fallback: each order's
53
+ * own are read from iFood in a job after its ingest (FUT-5984).
54
+ */
43
55
  export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapter {
44
56
  const reasons: readonly CancellationReason[] = IFOOD_REASON_CODES.map((code) => ({
45
57
  code,
@@ -67,6 +79,12 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
67
79
  // pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
68
80
  // CONCLUDED is that.
69
81
  statusSteps: ["READY", "DISPATCHED"],
82
+ // "Retorne `202 Accepted` em até 5 segundos" (Events `webhook-overview`, FUT-5984).
83
+ webhookAnswerStatus: 202,
84
+ // CFM: the store accepted on iFood's own app (FUT-5653).
85
+ marketplaceConfirms: true,
86
+ // A step is told only once iFood took the confirm (FUT-5673).
87
+ statusAfterConfirm: true,
70
88
  },
71
89
  normalize: (payload) => normalizeIfoodEvent(payload, normalizeOptions),
72
90
  readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
@@ -82,6 +100,11 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
82
100
  fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),
83
101
  statusSupported: ifoodStatusSupported,
84
102
  informStatus: ifoodInformStatus,
103
+ statusPrerequisite: ifoodStatusPrerequisite,
104
+ // The presence heartbeat, the events' acknowledgment and each order's own reasons (FUT-5984).
105
+ presence: readIfoodPresence,
106
+ acknowledgement: IFOOD_ACKNOWLEDGEMENT,
107
+ orderCancellationReasons: ifoodOrderCancellationReasons,
85
108
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
86
109
  availability: IFOOD_AVAILABILITY,
87
110
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
@@ -95,7 +118,7 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
95
118
  }
96
119
 
97
120
  export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
98
- export { normalizeIfoodEvent, readIfoodOrder, verifyIfoodSignature } from "./normalize";
121
+ export { normalizeIfoodEvent, readIfoodOrder, readIfoodPresence, verifyIfoodSignature } from "./normalize";
99
122
  export { ifoodFetchOrder } from "./fetch-order";
100
123
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
101
124
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
@@ -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
 
@@ -301,5 +305,17 @@ export function normalizeIfoodEvent(
301
305
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
302
306
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
303
307
  ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
308
+ ...(ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}),
304
309
  };
305
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,