@12-apps/marketplace 1.11.0 → 1.13.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 (55) hide show
  1. package/ADOPTING.md +134 -1
  2. package/README.md +49 -3
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CD0SfdVS.d.ts → adapter-CQ4QiZPi.d.ts} +327 -174
  6. package/dist/{chunk-TVZU4HNT.js → chunk-4J2KJ3ZW.js} +1 -1
  7. package/dist/{chunk-TVZU4HNT.js.map → chunk-4J2KJ3ZW.js.map} +1 -1
  8. package/dist/{chunk-YWMEIMO3.js → chunk-CEWTV2TC.js} +176 -40
  9. package/dist/chunk-CEWTV2TC.js.map +1 -0
  10. package/dist/{chunk-DCWOQ5PN.js → chunk-NFJQQWG4.js} +2 -2
  11. package/dist/{chunk-OS4TSIFU.js → chunk-W57TITU4.js} +2 -2
  12. package/dist/{client-11sncog4.d.ts → client-CCSnylou.d.ts} +1 -1
  13. package/dist/{engine-C_3RK8wC.d.ts → engine-1KlJ_8jK.d.ts} +34 -5
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +20 -2
  17. package/dist/ifood/index.js +349 -125
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +162 -65
  21. package/dist/index.js.map +1 -1
  22. package/dist/keeta/index.d.ts +2 -18
  23. package/dist/keeta/index.js +12 -3
  24. package/dist/keeta/index.js.map +1 -1
  25. package/dist/manifest/server.d.ts +2 -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 +2 -2
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/src/core/adapter.ts +8 -1
  33. package/src/core/connection-stamp.ts +61 -0
  34. package/src/core/courier-port.ts +100 -0
  35. package/src/core/courier.ts +153 -0
  36. package/src/core/engine.ts +4 -1
  37. package/src/core/fetch-order.ts +54 -12
  38. package/src/core/integration.ts +19 -4
  39. package/src/core/lifecycle.ts +27 -4
  40. package/src/core/outbound-queue.ts +24 -11
  41. package/src/core/outbound.ts +8 -6
  42. package/src/core/pickup-code.ts +136 -0
  43. package/src/core/pipeline.ts +15 -6
  44. package/src/core/ports.ts +23 -1
  45. package/src/core/status-store.ts +2 -3
  46. package/src/core/types.ts +56 -4
  47. package/src/ifood/courier.ts +210 -0
  48. package/src/ifood/fetch-order.ts +103 -0
  49. package/src/ifood/index.ts +9 -1
  50. package/src/ifood/normalize.ts +30 -3
  51. package/src/index.ts +16 -0
  52. package/src/keeta/normalize.ts +21 -6
  53. package/dist/chunk-YWMEIMO3.js.map +0 -1
  54. /package/dist/{chunk-DCWOQ5PN.js.map → chunk-NFJQQWG4.js.map} +0 -0
  55. /package/dist/{chunk-OS4TSIFU.js.map → chunk-W57TITU4.js.map} +0 -0
@@ -6,8 +6,14 @@ import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
6
6
  import { connectionMerchantId, resolveIngestionTarget } from "./integration";
7
7
  import { CANCELLED_BEFORE_INGEST_REASON, cancelledBeforeIngest, markCancelledBeforeIngest } from "./order-fetch-marks";
8
8
  import type { EngineContext } from "./ports";
9
- import type { MarketplaceLifecycle, MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
10
- import { followLifecycle } from "./lifecycle";
9
+ import type {
10
+ MarketplaceCourierStep,
11
+ MarketplaceLifecycle,
12
+ MarketplaceProvider,
13
+ NormalizedEvent,
14
+ NormalizedMarketplaceOrder,
15
+ } from "./types";
16
+ import { followCourierAndLifecycle } from "./courier";
11
17
 
12
18
  /**
13
19
  * One delivery, start to finish: normalize → inbox → ingest.
@@ -37,6 +43,8 @@ export type DeliveryOutcome =
37
43
  | { kind: "ingested"; orderId: string; unmappedSkus: string[] }
38
44
  /** A lifecycle event moved the order forward, through the host's `onLifecycle` (FUT-4653). */
39
45
  | { kind: "moved"; orderId: string; lifecycle: MarketplaceLifecycle }
46
+ /** A courier event's facts were stored by the host's `onCourier` (FUT-5665). */
47
+ | { kind: "courier"; orderId: string; step: MarketplaceCourierStep }
40
48
  | { kind: "cancelled" }
41
49
  | { kind: "cancellationFailed" }
42
50
  /** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
@@ -163,10 +171,11 @@ async function applyEvent(
163
171
  return { kind: "awaitingOrder" };
164
172
  }
165
173
 
166
- // A lifecycle event (dispatched, concluded) of an order we hold: with the
167
- // connection's switch ON and a host that binds the hook, the order follows.
168
- // Anything else falls through to "understood, nothing to do", as before.
169
- const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
174
+ // A courier event (FUT-5665) reaches a host that binds `onCourier`; a
175
+ // lifecycle event (dispatched, collected, concluded) of an order we hold:
176
+ // with the connection's switch ON and a host that binds the hook, the order
177
+ // follows. Anything else falls through to "understood, nothing to do", as before.
178
+ const followed = await followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
170
179
  if (followed) return followed;
171
180
  return ingestOrIgnore(ctx, inboxId, clientId, event, settings, now);
172
181
  }
package/src/core/ports.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { AdapterRegistry } from "./registry";
2
2
  import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
3
3
  import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
4
+ import type { MarketplaceCourierAnswer, MarketplaceCourierFacts, PickupCodeValidation } from "./courier-port";
4
5
  import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
5
6
  import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
6
7
  import type {
@@ -11,7 +12,7 @@ import type {
11
12
  MarketplaceRefusal,
12
13
  ResolvedOrderLine,
13
14
  } from "./order-types";
14
- import type { NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
15
+ import type { NormalizedCourierEvent, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
15
16
 
16
17
  export type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
17
18
  export type {
@@ -222,6 +223,27 @@ export interface MarketplaceOrderPort {
222
223
  * Absent: the engine cannot tell, and sends nothing.
223
224
  */
224
225
  statusHolds?(clientId: string, orderId: string, step: StatusStep): Promise<boolean>;
226
+ /**
227
+ * OPTIONAL (FUT-5665). The marketplace's courier moved: named, on the way,
228
+ * at the counter, holding the bag, or bringing it back. Store the facts on
229
+ * the order; never move it (a `COLLECTED` moves through `onLifecycle`).
230
+ * Idempotent: a redelivery is deduped, but the reconcile pass re-runs a
231
+ * FAILED row. Asked for an ACCEPTED order only, whatever the connection's
232
+ * `followStatus`. Absent: courier events are understood and ignored.
233
+ */
234
+ onCourier?(
235
+ clientId: string,
236
+ orderId: string,
237
+ event: NormalizedCourierEvent,
238
+ facts: MarketplaceCourierFacts,
239
+ ): Promise<MarketplaceCourierAnswer>;
240
+ /**
241
+ * OPTIONAL (FUT-5665). The marketplace's verdict on the pickup code the host
242
+ * sent with `engine.validatePickupCode`. Called once per job, after the
243
+ * hand-over has committed: `INVALID` warns, it moves nothing. A throw is
244
+ * logged. Absent: the verdict is only logged.
245
+ */
246
+ onPickupCodeValidated?(clientId: string, orderId: string, validation: PickupCodeValidation): Promise<void>;
225
247
  /** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
226
248
  summarize(
227
249
  clientId: string,
@@ -1,6 +1,5 @@
1
1
  import type { StatusStep } from "./adapter";
2
2
  import type { EngineContext, MarketplaceDb } from "./ports";
3
- import type { MarketplaceLifecycle } from "./types";
4
3
 
5
4
  /**
6
5
  * The engine's memory of what was said about an order's steps, in
@@ -11,7 +10,7 @@ import type { MarketplaceLifecycle } from "./types";
11
10
  */
12
11
 
13
12
  /** A step as the table holds it: the three the store informs, and the one only a marketplace announces. */
14
- export type StatusRowStep = StatusStep | MarketplaceLifecycle;
13
+ export type StatusRowStep = StatusStep | "CONCLUDED";
15
14
 
16
15
  /** Where a row stands. */
17
16
  export type StatusRowState = "SENDING" | "SENT" | "FAILED" | "NOTED";
@@ -65,7 +64,7 @@ export async function insertStatusRow(
65
64
  /** Remember a step the marketplace announced, so our own job never informs it back. */
66
65
  export async function noteMarketplaceStep(
67
66
  ctx: EngineContext,
68
- row: { clientId: string; orderId: string; provider: string; step: MarketplaceLifecycle },
67
+ row: { clientId: string; orderId: string; provider: string; step: StatusRowStep },
69
68
  ): Promise<void> {
70
69
  const table = statusTable(await ctx.ports.db());
71
70
  if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
package/src/core/types.ts CHANGED
@@ -127,6 +127,14 @@ export interface NormalizedMarketplaceOrder {
127
127
  * the connection's is refused.
128
128
  */
129
129
  externalMerchantId?: string | null;
130
+ /**
131
+ * OPTIONAL (FUT-5665). The code the marketplace's courier states at the
132
+ * counter to collect the bag (iFood's `delivery.pickupCode`), for the host
133
+ * to check locally at the hand-over. Null or absent: the marketplace asks
134
+ * none for this order (the check is off for the store, or the store carries
135
+ * the bag itself).
136
+ */
137
+ pickupCode?: string | null;
130
138
  }
131
139
 
132
140
  /**
@@ -138,11 +146,49 @@ export type CancellationOutcome = "CONFIRMED" | "FAILED";
138
146
 
139
147
  /**
140
148
  * A step of the order's life a marketplace announces about an order it
141
- * already has (FUT-4653): the courier left (`DISPATCHED`) or the order is
142
- * finished (`CONCLUDED`). An event that names one moves nothing by itself; the
143
- * engine asks the host to move the order forward (`onLifecycle`).
149
+ * already has (FUT-4653): the courier left (`DISPATCHED`), the marketplace's
150
+ * courier has the bag (`COLLECTED`, FUT-5665: for a fleet bag it is the same
151
+ * hand-over as `DISPATCHED`) or the order is finished (`CONCLUDED`). An event
152
+ * that names one moves nothing by itself; the engine asks the host to move the
153
+ * order forward (`onLifecycle`).
144
154
  */
145
- export type MarketplaceLifecycle = "DISPATCHED" | "CONCLUDED";
155
+ export type MarketplaceLifecycle = "DISPATCHED" | "COLLECTED" | "CONCLUDED";
156
+
157
+ /**
158
+ * Where the marketplace's own courier is with a bag (FUT-5665), provider-
159
+ * neutral: named (`ASSIGNED`), on the way to the store (`GOING_TO_ORIGIN`),
160
+ * at the counter (`ARRIVED_AT_ORIGIN`), holding the bag (`COLLECTED`), or
161
+ * bringing it back (`RETURNING_TO_ORIGIN`, then `RETURNED_TO_ORIGIN`).
162
+ */
163
+ export type MarketplaceCourierStep =
164
+ | "ASSIGNED"
165
+ | "GOING_TO_ORIGIN"
166
+ | "ARRIVED_AT_ORIGIN"
167
+ | "COLLECTED"
168
+ | "RETURNING_TO_ORIGIN"
169
+ | "RETURNED_TO_ORIGIN";
170
+
171
+ /** What the courier rides, as a closed set the host has words for. `OTHER`: stated, and none of these. */
172
+ export type MarketplaceCourierVehicle = "MOTORCYCLE" | "BICYCLE" | "CAR" | "OTHER";
173
+
174
+ /** Who the marketplace sent, as much as it says. */
175
+ export interface MarketplaceCourier {
176
+ name: string | null;
177
+ /** An https URL of the courier's photo, or null (any other scheme is dropped). */
178
+ photoUrl: string | null;
179
+ vehicle: MarketplaceCourierVehicle | null;
180
+ }
181
+
182
+ /** One courier event, normalized (FUT-5665). */
183
+ export interface NormalizedCourierEvent {
184
+ step: MarketplaceCourierStep;
185
+ /** When the marketplace says it happened; null when it does not (the engine then hands the host its clock). */
186
+ at: Date | null;
187
+ /** Who is coming: on `ASSIGNED`, when the marketplace names them; null otherwise. */
188
+ courier: MarketplaceCourier | null;
189
+ /** The bag is coming back (`RETURNING`) or is back (`RETURNED`); null on every other step. */
190
+ returning: "RETURNING" | "RETURNED" | null;
191
+ }
146
192
 
147
193
  /** What an adapter makes of one inbound delivery. */
148
194
  export interface NormalizedEvent {
@@ -181,4 +227,10 @@ export interface NormalizedEvent {
181
227
  * names one carries no order body.
182
228
  */
183
229
  lifecycle?: MarketplaceLifecycle | null;
230
+ /**
231
+ * OPTIONAL (FUT-5665). Where the marketplace's courier is, when this event
232
+ * says. A `COLLECTED` names the lifecycle too. Absent or null: the event
233
+ * names no courier step.
234
+ */
235
+ courier?: NormalizedCourierEvent | null;
184
236
  }
@@ -0,0 +1,210 @@
1
+ import { outboundResultOf, type AdapterCallContext, type OutboundOrderRef } from "../core/adapter";
2
+ import type {
3
+ CourierTrackingCallResult,
4
+ MarketplaceCourierApi,
5
+ MarketplaceCourierTracking,
6
+ PickupCodeCallResult,
7
+ } from "../core/courier-port";
8
+ import { firstDate, firstString, pick } from "../core/payload-read";
9
+ import type { MarketplaceCourier, MarketplaceCourierStep, MarketplaceCourierVehicle, NormalizedCourierEvent } from "../core/types";
10
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
11
+
12
+ /**
13
+ * iFood's own fleet (FUT-5665), both halves: the courier events of iFood's
14
+ * stream, and the two calls about the courier (the pickup-code check and the
15
+ * tracking read). Only for an order iFood's fleet carries
16
+ * (`delivery.deliveredBy = IFOOD`); the engine never calls either for another.
17
+ *
18
+ * Source: the iFood research of 2026-11-26 (Levantamento, lines 95-115),
19
+ * marked confirmed there against iFood's Order module docs; what it could not
20
+ * confirm is marked ESTIMATED below, in this file only.
21
+ */
22
+
23
+ /**
24
+ * iFood's courier event codes, short and long. The four short codes and every
25
+ * long form are confirmed; the two return events have no documented short
26
+ * code, so only their long forms are read (ESTIMATED: none is guessed).
27
+ */
28
+ const COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {
29
+ ADR: "ASSIGNED",
30
+ ASSIGN_DRIVER: "ASSIGNED",
31
+ GTO: "GOING_TO_ORIGIN",
32
+ GOING_TO_ORIGIN: "GOING_TO_ORIGIN",
33
+ AAO: "ARRIVED_AT_ORIGIN",
34
+ ARRIVED_AT_ORIGIN: "ARRIVED_AT_ORIGIN",
35
+ CLT: "COLLECTED",
36
+ COLLECTED: "COLLECTED",
37
+ DELIVERY_RETURNING_TO_ORIGIN: "RETURNING_TO_ORIGIN",
38
+ DELIVERY_RETURNED_TO_ORIGIN: "RETURNED_TO_ORIGIN",
39
+ };
40
+
41
+ /**
42
+ * `workerVehicleType` as the host's closed set. ESTIMATED: the field is
43
+ * confirmed, its values are not documented in the research; these are the
44
+ * words a vehicle is plausibly named with, and anything else stated is OTHER.
45
+ */
46
+ const VEHICLE_OF: Readonly<Record<string, MarketplaceCourierVehicle>> = {
47
+ MOTORCYCLE: "MOTORCYCLE",
48
+ MOTORBIKE: "MOTORCYCLE",
49
+ MOTO: "MOTORCYCLE",
50
+ BICYCLE: "BICYCLE",
51
+ BIKE: "BICYCLE",
52
+ CAR: "CAR",
53
+ CARRO: "CAR",
54
+ };
55
+
56
+ /** The longest courier name kept: a longer one is truncated, never refused. */
57
+ export const IFOOD_COURIER_NAME_MAX = 120;
58
+ /** The longest photo URL kept: a longer one is dropped (a truncated URL is a broken one). */
59
+ const IFOOD_COURIER_PHOTO_URL_MAX = 2048;
60
+
61
+ /** An https URL of bounded length, or null: a photo the host renders is never another scheme. */
62
+ function httpsUrl(value: string | null): string | null {
63
+ if (!value || value.length > IFOOD_COURIER_PHOTO_URL_MAX) return null;
64
+ try {
65
+ return new URL(value).protocol === "https:" ? value : null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /** The event's `metadata`: an object, or a JSON string of one. */
72
+ function metadataOf(payload: unknown): unknown {
73
+ const raw = pick(payload, "metadata");
74
+ if (typeof raw !== "string") return raw;
75
+ try {
76
+ return JSON.parse(raw) as unknown;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /** The courier an ADR names: `workerName`, `workerPhotoUrl`, `workerVehicleType`. Null when it names nothing. */
83
+ function readCourier(payload: unknown): MarketplaceCourier | null {
84
+ const metadata = metadataOf(payload);
85
+ const name = firstString(metadata, [["workerName"]])?.slice(0, IFOOD_COURIER_NAME_MAX) ?? null;
86
+ const photoUrl = httpsUrl(firstString(metadata, [["workerPhotoUrl"]]));
87
+ const stated = firstString(metadata, [["workerVehicleType"]])?.toUpperCase() ?? null;
88
+ const vehicle = stated === null ? null : (VEHICLE_OF[stated] ?? "OTHER");
89
+ return name === null && photoUrl === null && vehicle === null ? null : { name, photoUrl, vehicle };
90
+ }
91
+
92
+ /** The courier step an iFood event names, or null. */
93
+ export function readIfoodCourierEvent(payload: unknown, eventType: string): NormalizedCourierEvent | null {
94
+ const step = COURIER_STEP_OF[eventType.toUpperCase()];
95
+ if (!step) return null;
96
+ return {
97
+ step,
98
+ at: firstDate(payload, [["createdAt"]]),
99
+ courier: step === "ASSIGNED" ? readCourier(payload) : null,
100
+ returning: step === "RETURNING_TO_ORIGIN" ? "RETURNING" : step === "RETURNED_TO_ORIGIN" ? "RETURNED" : null,
101
+ };
102
+ }
103
+
104
+ const orderUrl = (ref: OutboundOrderRef, action: string): string =>
105
+ `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(ref.externalOrderId)}/${action}`;
106
+
107
+ /** One authenticated call; a 401 forgets the token so the retry fetches another. */
108
+ async function call(
109
+ ctx: AdapterCallContext,
110
+ request: { method: "GET" | "POST"; url: string; body?: unknown },
111
+ ): Promise<{ status: number; body: string } | { kind: "refused"; status: number; message: string; own?: true } | { kind: "retry"; reason: string }> {
112
+ const auth = await bearer(ctx);
113
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "no token" } : auth;
114
+ const response = await ctx.http({
115
+ method: request.method,
116
+ url: request.url,
117
+ headers: {
118
+ Authorization: `Bearer ${auth.token}`,
119
+ ...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
120
+ },
121
+ ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
122
+ });
123
+ if (response.status !== 401) return response;
124
+ ctx.tokens.delete(ifoodTokenKey(ctx));
125
+ return { kind: "retry", reason: "iFood refused the token" };
126
+ }
127
+
128
+ function parsed(body: string): unknown {
129
+ try {
130
+ return JSON.parse(body) as unknown;
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+
136
+ /**
137
+ * `POST /order/v1.0/orders/{id}/validatePickupCode {"code"}`, answering
138
+ * `{"valid": true|false}` (confirmed). A 2xx without a boolean `valid` is no
139
+ * verdict: our own refusal, never read as INVALID.
140
+ */
141
+ async function validatePickupCode(
142
+ ctx: AdapterCallContext,
143
+ order: OutboundOrderRef,
144
+ input: { code: string },
145
+ ): Promise<PickupCodeCallResult> {
146
+ try {
147
+ const response = await call(ctx, { method: "POST", url: orderUrl(order, "validatePickupCode"), body: { code: input.code } });
148
+ if ("kind" in response) return response;
149
+ const read = outboundResultOf(response);
150
+ if (read.kind !== "accepted") return read;
151
+ const valid = pick(parsed(response.body), "valid");
152
+ return typeof valid === "boolean"
153
+ ? { kind: "answered", valid }
154
+ : { kind: "refused", status: response.status, message: "iFood answered without a verdict", own: true };
155
+ } catch (error) {
156
+ return retryOf(error);
157
+ }
158
+ }
159
+
160
+ /** A call that never got an answer is a retry. */
161
+ function retryOf(error: unknown): { kind: "retry"; reason: string } {
162
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
163
+ }
164
+
165
+ function numberAt(source: unknown, key: string): number | null {
166
+ const value = pick(source, key);
167
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
168
+ }
169
+
170
+ /** `base` plus a number of seconds, or null when either is missing. */
171
+ function plusSeconds(base: Date, seconds: number | null): Date | null {
172
+ return seconds === null ? null : new Date(base.getTime() + seconds * 1000);
173
+ }
174
+
175
+ /**
176
+ * The tracking body. Confirmed: latitude, longitude, `expectedDelivery`,
177
+ * `trackDate`, and seconds to the pickup and to the delivery. ESTIMATED: the
178
+ * names of the two second counts (`pickupEtaStart`, `deliveryEtaEnd`, or
179
+ * `pickupEta`, `deliveryEta`), counted from `trackDate`.
180
+ */
181
+ function readTracking(body: unknown, now: Date): MarketplaceCourierTracking {
182
+ const trackedAt = firstDate(body, [["trackDate"]]);
183
+ const base = trackedAt ?? now;
184
+ const pickupSeconds = numberAt(body, "pickupEtaStart") ?? numberAt(body, "pickupEta");
185
+ const deliverySeconds = numberAt(body, "deliveryEtaEnd") ?? numberAt(body, "deliveryEta");
186
+ return {
187
+ pickupEtaAt: plusSeconds(base, pickupSeconds),
188
+ deliveryEtaAt: firstDate(body, [["expectedDelivery"]]) ?? plusSeconds(base, deliverySeconds),
189
+ latitude: numberAt(body, "latitude"),
190
+ longitude: numberAt(body, "longitude"),
191
+ trackedAt,
192
+ };
193
+ }
194
+
195
+ /** `GET /order/v1.0/orders/{id}/tracking` (confirmed): 404 before ASSIGN_DRIVER is "not yet". */
196
+ async function tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult> {
197
+ try {
198
+ const response = await call(ctx, { method: "GET", url: orderUrl(order, "tracking") });
199
+ if ("kind" in response) return response;
200
+ if (response.status === 404) return { kind: "notYet" };
201
+ const read = outboundResultOf(response);
202
+ if (read.kind !== "accepted") return read;
203
+ return { kind: "tracking", tracking: readTracking(parsed(response.body), ctx.now) };
204
+ } catch (error) {
205
+ return retryOf(error);
206
+ }
207
+ }
208
+
209
+ /** iFood's courier calls, for the adapter's `courier`. */
210
+ export const IFOOD_COURIER: MarketplaceCourierApi = { validatePickupCode, tracking };
@@ -0,0 +1,103 @@
1
+ import {
2
+ outboundResultOf,
3
+ type AdapterCallContext,
4
+ type FetchOrderResult,
5
+ type MarketplaceHttpResponse,
6
+ } from "../core/adapter";
7
+ import { firstString } from "../core/payload-read";
8
+ import { readIfoodOrder } from "./normalize";
9
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
10
+
11
+ /**
12
+ * The iFood adapter's order read (FUT-5800): `GET /order/v1.0/orders/{id}`.
13
+ *
14
+ * iFood's events carry only the order id, so a PLACED with no items is marked
15
+ * `orderToFetch` (`./normalize.ts`) and the engine's `marketplace.fetch-order`
16
+ * job calls this, after the webhook's row is committed, never inside the
17
+ * request. The order iFood serves has the fields the event's `order` would
18
+ * have carried, so it is normalized by the same reader: a fetched order and a
19
+ * carried one land identically.
20
+ *
21
+ * How an answer is read:
22
+ * - 2xx with an order: the order, with the merchant its `merchant.id` names
23
+ * (the engine refuses one naming another merchant than the connection's).
24
+ * - 2xx that is not JSON: retried. 2xx naming another order, or no items: refused.
25
+ * - 401: the cached token is forgotten and a new one asked for, ONCE, in the
26
+ * same call. A second 401 is our credentials refused (`own`), as is a 403
27
+ * (the merchant has not authorized this app) and a token grant iFood refuses.
28
+ * - 404: retried. ESTIMATED: an order read right after its PLACED may not be
29
+ * served yet; the job's attempt bound ends it.
30
+ * - Everything else: the engine's one rule (`outboundResultOf`).
31
+ */
32
+
33
+ const orderResourceUrl = (externalOrderId: string): string =>
34
+ `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`;
35
+
36
+ /** One authenticated GET, or the token's refusal or retry in its place. */
37
+ async function getOrder(
38
+ ctx: AdapterCallContext,
39
+ externalOrderId: string,
40
+ ): Promise<{ response: MarketplaceHttpResponse } | Exclude<FetchOrderResult, { kind: "order" }>> {
41
+ const auth = await bearer(ctx);
42
+ if (!("token" in auth)) {
43
+ return auth.kind === "accepted" ? { kind: "retry", reason: "iFood answered the token grant without a token" } : auth;
44
+ }
45
+ const response = await ctx.http({
46
+ method: "GET",
47
+ url: orderResourceUrl(externalOrderId),
48
+ headers: { Authorization: `Bearer ${auth.token}`, Accept: "application/json" },
49
+ });
50
+ return { response };
51
+ }
52
+
53
+ /** The order in a 2xx answer, or why it is not one. */
54
+ function orderOf(body: string, externalOrderId: string, missingStreetNumber: string): FetchOrderResult {
55
+ let parsed: unknown;
56
+ try {
57
+ parsed = JSON.parse(body) as unknown;
58
+ } catch {
59
+ return { kind: "retry", reason: "iFood answered the order read with a body that is not JSON" };
60
+ }
61
+ const named = firstString(parsed, [["id"]]);
62
+ if (named !== null && named !== externalOrderId) {
63
+ return { kind: "refused", status: 200, message: `iFood answered order ${named} for ${externalOrderId}` };
64
+ }
65
+ const order = readIfoodOrder(parsed, externalOrderId, missingStreetNumber);
66
+ if (!order) return { kind: "refused", status: 200, message: "iFood answered an order with no items" };
67
+ return { kind: "order", order: { ...order, externalMerchantId: firstString(parsed, [["merchant", "id"]]) } };
68
+ }
69
+
70
+ /** What a non-2xx answer means for the fetch. */
71
+ function failureOf(response: MarketplaceHttpResponse): Exclude<FetchOrderResult, { kind: "order" }> {
72
+ const message = response.body.slice(0, 300);
73
+ if (response.status === 401 || response.status === 403) {
74
+ return { kind: "refused", status: response.status, message, own: true };
75
+ }
76
+ if (response.status === 404) return { kind: "retry", reason: `status 404: ${message}` };
77
+ const result = outboundResultOf(response);
78
+ return result.kind === "accepted" ? { kind: "retry", reason: `status ${response.status}` } : result;
79
+ }
80
+
81
+ /** Fetch one order iFood's event only named. Never throws: no answer is a retry. */
82
+ export async function ifoodFetchOrder(
83
+ ctx: AdapterCallContext,
84
+ ref: { externalOrderId: string },
85
+ options: { missingStreetNumber: string },
86
+ ): Promise<FetchOrderResult> {
87
+ try {
88
+ let answer = await getOrder(ctx, ref.externalOrderId);
89
+ if ("response" in answer && answer.response.status === 401) {
90
+ // A token that went stale under us: forget it and try once with a new one.
91
+ ctx.tokens.delete(ifoodTokenKey(ctx));
92
+ answer = await getOrder(ctx, ref.externalOrderId);
93
+ }
94
+ if (!("response" in answer)) return answer;
95
+ const { response } = answer;
96
+ if (response.status >= 200 && response.status < 300) {
97
+ return orderOf(response.body, ref.externalOrderId, options.missingStreetNumber);
98
+ }
99
+ return failureOf(response);
100
+ } catch (error) {
101
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
102
+ }
103
+ }
@@ -2,6 +2,8 @@ import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
2
2
  import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { IFOOD_CATALOGUE_READER } from "./catalogue-read";
5
+ import { IFOOD_COURIER } from "./courier";
6
+ import { ifoodFetchOrder } from "./fetch-order";
5
7
  import { IFOOD_LINKING } from "./linking";
6
8
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
7
9
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
@@ -76,12 +78,16 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
76
78
  catalogueReader: IFOOD_CATALOGUE_READER,
77
79
  confirm: (ctx, order) => ifoodConfirm(ctx, order),
78
80
  requestCancellation: ifoodRequestCancellation,
81
+ // iFood's events carry only the order id: a PLACED with no items is fetched (FUT-5800).
82
+ fetchOrder: (ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions),
79
83
  statusSupported: ifoodStatusSupported,
80
84
  informStatus: ifoodInformStatus,
81
85
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
82
86
  availability: IFOOD_AVAILABILITY,
83
87
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
84
88
  linking: IFOOD_LINKING,
89
+ // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
90
+ courier: IFOOD_COURIER,
85
91
  // No per-order deep link is known, so the portal, where a live order is
86
92
  // on the first screen.
87
93
  appLink: () => IFOOD_PORTAL_URL,
@@ -89,9 +95,11 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
89
95
  }
90
96
 
91
97
  export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
92
- export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
98
+ export { normalizeIfoodEvent, readIfoodOrder, verifyIfoodSignature } from "./normalize";
99
+ export { ifoodFetchOrder } from "./fetch-order";
93
100
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
94
101
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
95
102
  export { IFOOD_LINKING } from "./linking";
103
+ export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
96
104
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
97
105
  export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
@@ -19,6 +19,7 @@ import {
19
19
  toCents,
20
20
  verifyHmacSha256Hex,
21
21
  } from "../core/payload-read";
22
+ import { readIfoodCourierEvent } from "./courier";
22
23
 
23
24
  /**
24
25
  * The iFood adapter's INBOUND half: one delivery → a {@link NormalizedEvent}.
@@ -53,6 +54,9 @@ const LIFECYCLE_OF: Readonly<Record<string, MarketplaceLifecycle>> = {
53
54
  DISPATCHED: "DISPATCHED",
54
55
  CON: "CONCLUDED",
55
56
  CONCLUDED: "CONCLUDED",
57
+ // iFood's courier has the bag (FUT-5665): for a fleet bag, the same hand-over as DSP.
58
+ CLT: "COLLECTED",
59
+ COLLECTED: "COLLECTED",
56
60
  };
57
61
 
58
62
  /**
@@ -198,8 +202,12 @@ function optional<K extends string, V>(key: K, value: V | undefined): { [P in K]
198
202
  return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });
199
203
  }
200
204
 
201
- /** The order body of a placed-order event, or null when it carries none. */
202
- function readOrder(
205
+ /**
206
+ * The order body of a placed-order event, or null when it carries none. Also
207
+ * reads the order iFood serves at `GET /order/v1.0/orders/{id}` (`./fetch-order.ts`),
208
+ * whose fields are the same ones the event's `order` would carry.
209
+ */
210
+ export function readIfoodOrder(
203
211
  payload: unknown,
204
212
  externalOrderId: string,
205
213
  missingStreetNumber: string,
@@ -237,9 +245,27 @@ function readOrder(
237
245
  deliveryFeeCents: firstCents(order, [["total", "deliveryFee"]]),
238
246
  subtotalCents: firstCents(order, [["total", "subTotal"]]),
239
247
  ...optional("discounts", readDiscounts(order)),
248
+ // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.
249
+ pickupCode: firstString(order, [["delivery", "pickupCode"]]),
240
250
  };
241
251
  }
242
252
 
253
+ /**
254
+ * The order a PLACED carries, or, when it carries none, the mark that has it
255
+ * fetched: iFood's events carry only the order id (sandbox, 2026-11-27), so the
256
+ * `marketplace.fetch-order` job reads it (FUT-5800). Any other event: no order.
257
+ */
258
+ function placedOrder(
259
+ payload: unknown,
260
+ placed: boolean,
261
+ externalOrderId: string,
262
+ missingStreetNumber: string,
263
+ ): Pick<NormalizedEvent, "order" | "orderToFetch"> {
264
+ if (!placed) return { order: null };
265
+ const order = readIfoodOrder(payload, externalOrderId, missingStreetNumber);
266
+ return order ? { order } : { order: null, orderToFetch: true };
267
+ }
268
+
243
269
  /**
244
270
  * Normalize one iFood delivery.
245
271
  *
@@ -270,9 +296,10 @@ export function normalizeIfoodEvent(
270
296
  eventType,
271
297
  externalMerchantId: firstString(payload, [["merchantId"], ["merchant", "id"]]),
272
298
  externalOrderId,
273
- order: placed ? readOrder(payload, externalOrderId, options.missingStreetNumber) : null,
299
+ ...placedOrder(payload, placed, externalOrderId, options.missingStreetNumber),
274
300
  cancelled,
275
301
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
276
302
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
303
+ ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
277
304
  };
278
305
  }
package/src/index.ts CHANGED
@@ -83,6 +83,10 @@ export {
83
83
  type NormalizedAddress,
84
84
  type NormalizedBuyer,
85
85
  type MarketplaceLifecycle,
86
+ type MarketplaceCourier,
87
+ type MarketplaceCourierStep,
88
+ type MarketplaceCourierVehicle,
89
+ type NormalizedCourierEvent,
86
90
  type NormalizedEvent,
87
91
  type NormalizedMarketplaceOrder,
88
92
  type NormalizedOrderDiscount,
@@ -136,6 +140,18 @@ export {
136
140
  } from "./core/outbound-queue";
137
141
  export type { DeliveryOutcome } from "./core/pipeline";
138
142
  export type { InformStatusInput } from "./core/status-inform";
143
+ export type {
144
+ CourierTrackingCallResult,
145
+ CourierTrackingResult,
146
+ MarketplaceCourierAnswer,
147
+ MarketplaceCourierApi,
148
+ MarketplaceCourierEngine,
149
+ MarketplaceCourierFacts,
150
+ MarketplaceCourierTracking,
151
+ PickupCodeCallResult,
152
+ PickupCodeValidation,
153
+ ValidatePickupCodeInput,
154
+ } from "./core/courier-port";
139
155
  export {
140
156
  FetchOrderRetryError,
141
157
  MARKETPLACE_FETCH_ORDER_JOB,