@12-apps/marketplace 1.11.0 → 1.12.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 (51) hide show
  1. package/ADOPTING.md +90 -1
  2. package/README.md +37 -1
  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-nUyZpLzz.d.ts} +325 -173
  6. package/dist/{chunk-YWMEIMO3.js → chunk-45ZVN5XI.js} +114 -24
  7. package/dist/chunk-45ZVN5XI.js.map +1 -0
  8. package/dist/{chunk-DCWOQ5PN.js → chunk-L6FG6T4S.js} +2 -2
  9. package/dist/{chunk-TVZU4HNT.js → chunk-LACBT6NC.js} +1 -1
  10. package/dist/{chunk-TVZU4HNT.js.map → chunk-LACBT6NC.js.map} +1 -1
  11. package/dist/{chunk-OS4TSIFU.js → chunk-MIPNQ7X5.js} +2 -2
  12. package/dist/{client-11sncog4.d.ts → client-Ctas7WCS.d.ts} +1 -1
  13. package/dist/{engine-C_3RK8wC.d.ts → engine-CIy9P7Cq.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 +7 -2
  17. package/dist/ifood/index.js +184 -30
  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 +6 -0
  33. package/src/core/courier-port.ts +100 -0
  34. package/src/core/courier.ts +153 -0
  35. package/src/core/engine.ts +4 -1
  36. package/src/core/lifecycle.ts +27 -4
  37. package/src/core/outbound-queue.ts +24 -11
  38. package/src/core/outbound.ts +8 -6
  39. package/src/core/pickup-code.ts +136 -0
  40. package/src/core/pipeline.ts +15 -6
  41. package/src/core/ports.ts +23 -1
  42. package/src/core/status-store.ts +2 -3
  43. package/src/core/types.ts +56 -4
  44. package/src/ifood/courier.ts +210 -0
  45. package/src/ifood/index.ts +4 -0
  46. package/src/ifood/normalize.ts +7 -0
  47. package/src/index.ts +16 -0
  48. package/src/keeta/normalize.ts +21 -6
  49. package/dist/chunk-YWMEIMO3.js.map +0 -1
  50. /package/dist/{chunk-DCWOQ5PN.js.map → chunk-L6FG6T4S.js.map} +0 -0
  51. /package/dist/{chunk-OS4TSIFU.js.map → chunk-MIPNQ7X5.js.map} +0 -0
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 };
@@ -2,6 +2,7 @@ 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";
5
6
  import { IFOOD_LINKING } from "./linking";
6
7
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
7
8
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodInformStatus, ifoodRequestCancellation, ifoodStatusSupported } from "./outbound";
@@ -82,6 +83,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
82
83
  availability: IFOOD_AVAILABILITY,
83
84
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
84
85
  linking: IFOOD_LINKING,
86
+ // iFood's fleet: the pickup-code check and the courier's tracking (FUT-5665).
87
+ courier: IFOOD_COURIER,
85
88
  // No per-order deep link is known, so the portal, where a live order is
86
89
  // on the first screen.
87
90
  appLink: () => IFOOD_PORTAL_URL,
@@ -93,5 +96,6 @@ export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
93
96
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
94
97
  export { IFOOD_CATALOGUE_READER } from "./catalogue-read";
95
98
  export { IFOOD_LINKING } from "./linking";
99
+ export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
96
100
  export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
97
101
  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
  /**
@@ -237,6 +241,8 @@ function readOrder(
237
241
  deliveryFeeCents: firstCents(order, [["total", "deliveryFee"]]),
238
242
  subtotalCents: firstCents(order, [["total", "subTotal"]]),
239
243
  ...optional("discounts", readDiscounts(order)),
244
+ // The code iFood's courier states at the counter (FUT-5665; confirmed field). Null when iFood asks none.
245
+ pickupCode: firstString(order, [["delivery", "pickupCode"]]),
240
246
  };
241
247
  }
242
248
 
@@ -274,5 +280,6 @@ export function normalizeIfoodEvent(
274
280
  cancelled,
275
281
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
276
282
  ...(LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {}),
283
+ ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? undefined),
277
284
  };
278
285
  }
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,
@@ -1,6 +1,6 @@
1
1
  import { outboundResultOf, type AdapterCallContext } from "../core/adapter";
2
- import { pick } from "../core/payload-read";
3
- import type { NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
2
+ import { firstDate, pick } from "../core/payload-read";
3
+ import type { MarketplaceCourierStep, NormalizedEvent, NormalizedMarketplaceOrder } from "../core/types";
4
4
  import { isStop, openDeliveryCall, type OpenDeliveryDialect } from "../open-delivery/client";
5
5
  import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../open-delivery/normalize";
6
6
 
@@ -12,15 +12,26 @@ import { normalizeOpenDeliveryEventAs, normalizeOpenDeliveryOrderAs } from "../o
12
12
  *
13
13
  * Events (Keeta's order guide, read 2026-11-26): `CREATED` → fetch;
14
14
  * `CANCELLED` (with a JSON-string `metadata` carrying `reason` and `code`) →
15
- * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle. Keeta has NO
15
+ * cancelled; `DISPATCHED`, `CONCLUDED` → lifecycle; `RIDER_ARRIVED_AT_STORE`,
16
+ * `ORDER_COLLECTED` → courier steps (the second a lifecycle too). Keeta has NO
16
17
  * `CANCELLATION_REQUEST_DENIED`: a store's request that Keeta does not grant
17
18
  * produces no event, so it ends TIMEOUT at the adapter's answer window. The
18
- * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`,
19
- * `RIDER_ARRIVED_AT_STORE`, `ORDER_COLLECTED`, `DELIVERED`,
19
+ * rest (`CONFIRMED`, `READY_FOR_PICKUP`, `PICKUP_ONGOING`, `DELIVERED`,
20
20
  * `CANCELLATION_REQUESTED`, `USER_REFUND_REQUEST`, `REFUNDED`,
21
21
  * `REFUND_FAILED`, `RECOMMENDED_PREPARATION_START`) are recorded and IGNORED.
22
22
  */
23
23
 
24
+ /**
25
+ * Keeta's rider events as courier steps (FUT-5665). ESTIMATED: the event names
26
+ * are Keeta's order guide's (read 2026-11-26), their meaning is read off the
27
+ * names; they carry no rider's name, photo or vehicle. `PICKUP_ONGOING` is left
28
+ * IGNORED: whether it means "on the way" or "at the counter" is not stated.
29
+ */
30
+ const KEETA_COURIER_STEP_OF: Readonly<Record<string, MarketplaceCourierStep>> = {
31
+ RIDER_ARRIVED_AT_STORE: "ARRIVED_AT_ORIGIN",
32
+ ORDER_COLLECTED: "COLLECTED",
33
+ };
34
+
24
35
  /** The provider id Keeta is registered under. Uppercase: the column's CHECK holds that shape. */
25
36
  export const KEETA_PROVIDER = "KEETA";
26
37
 
@@ -31,7 +42,11 @@ const DECRYPT_BATCH = 50;
31
42
 
32
43
  /** Normalize one webhook `Event`. Null only when it names no order. */
33
44
  export function normalizeKeetaEvent(payload: unknown): NormalizedEvent | null {
34
- return normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
45
+ const event = normalizeOpenDeliveryEventAs(KEETA_PROVIDER, payload);
46
+ const step = event ? KEETA_COURIER_STEP_OF[event.eventType] : undefined;
47
+ if (!event || !step) return event;
48
+ const courier = { step, at: firstDate(payload, [["createdAt"]]), courier: null, returning: null };
49
+ return { ...event, courier, ...(step === "COLLECTED" ? { lifecycle: "COLLECTED" as const } : {}) };
35
50
  }
36
51
 
37
52
  /** Normalize one `Order`, after {@link revealKeetaOrder}. Null when it carries no id or no line. */