@12-apps/marketplace 1.19.1 → 1.20.1

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.
@@ -0,0 +1,213 @@
1
+ import type { AdapterCallContext, OrderCancellationReason } from "../core/adapter";
2
+ import { firstString, pick } from "../core/payload-read";
3
+ import type { IfoodShippingQuoteRef } from "./shipping";
4
+ import { ifoodShippingAddressBody, type IfoodShippingAddress } from "./shipping-address";
5
+ import {
6
+ IFOOD_SHIPPING_API,
7
+ parsedBody,
8
+ reais,
9
+ shippingCall,
10
+ shippingPost,
11
+ idempotencyKeyValid,
12
+ type IfoodShippingFailure,
13
+ type IfoodShippingInvalid,
14
+ type IfoodShippingRequested,
15
+ } from "./shipping-wire";
16
+
17
+ /**
18
+ * iFood Shipping for an order placed OFF the iFood platform (FUT-5667): the
19
+ * store's own pedido, carried by an iFood courier. Its creation and cancel,
20
+ * per the `outside` and `endpoints` guides (sources in `./shipping-wire.ts`);
21
+ * the address flow and the safe-delivery score are `./shipping-address.ts`.
22
+ *
23
+ * Only an order already paid online is sent: the body never carries
24
+ * `payments` ("Pagamento Online: Não enviar o objeto `payments`"). The phone
25
+ * goes as `type: CUSTOMER`, so the drop code is its last 4 digits.
26
+ */
27
+
28
+ const orderUrl = (orderId: string, action: string): string => `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(orderId)}/${action}`;
29
+
30
+ /** One line of the order. Money in cents. */
31
+ export interface IfoodShippingItem {
32
+ id: string;
33
+ name: string;
34
+ externalCode?: string;
35
+ quantity: number;
36
+ unitPriceCents: number;
37
+ /** The line's complements, in total. */
38
+ optionsPriceCents: number;
39
+ }
40
+
41
+ /** What creating an order on demand takes. Money in cents. */
42
+ export interface IfoodShippingOrderInput {
43
+ customer: {
44
+ name: string;
45
+ /** A Brazilian phone with its area code, in any punctuation, country code optional. Required. */
46
+ phone: string;
47
+ };
48
+ delivery: {
49
+ /** `merchantFee`: the delivery fee the store charged its customer. */
50
+ merchantFeeCents: number;
51
+ /** When iFood allocates the courier, in seconds; 0 or absent is at once. */
52
+ preparationTimeSeconds?: number;
53
+ quote: IfoodShippingQuoteRef;
54
+ address: IfoodShippingAddress;
55
+ };
56
+ items: IfoodShippingItem[];
57
+ /** A short id iFood shows, at most 4 characters. */
58
+ displayId?: string;
59
+ }
60
+
61
+ export type IfoodShippingCreateResult =
62
+ /** 202: the order exists at iFood and a courier is being allocated. `trackingUrl` is null unless https. */
63
+ | { kind: "created"; id: string; trackingUrl: string | null }
64
+ | IfoodShippingFailure;
65
+
66
+ const NAME_MAX = 50;
67
+ const text = (value: string | undefined, max: number): string => (value ?? "").trim().slice(0, max);
68
+
69
+ /**
70
+ * The phone as iFood's parts: `55`, a 2-digit area code and an 8-9 digit
71
+ * number. Fewer than 10 digits has no area code: refused, never split into a
72
+ * wrong one (the drop code and the address OTP go to this phone).
73
+ */
74
+ function phoneOf(raw: string): { countryCode: string; areaCode: string; number: string } | null {
75
+ let digits = raw.replace(/\D/g, "");
76
+ if (digits.length >= 12 && digits.startsWith("55")) digits = digits.slice(2);
77
+ if (digits.length < 10 || digits.length > 11) return null;
78
+ return { countryCode: "55", areaCode: digits.slice(0, 2), number: digits.slice(2) };
79
+ }
80
+
81
+ const cents = (value: number): boolean => Number.isInteger(value) && value >= 0;
82
+
83
+ function itemsBody(items: IfoodShippingItem[]): Record<string, unknown>[] | null {
84
+ if (items.length === 0) return null;
85
+ const valid = items.every(
86
+ (item) => text(item.id, 100) !== "" && text(item.name, NAME_MAX) !== "" && Number.isInteger(item.quantity) && item.quantity > 0 && cents(item.unitPriceCents) && cents(item.optionsPriceCents),
87
+ );
88
+ if (!valid) return null;
89
+ return items.map((item) => {
90
+ const priceCents = item.quantity * item.unitPriceCents;
91
+ return {
92
+ id: item.id,
93
+ name: text(item.name, NAME_MAX),
94
+ ...(item.externalCode ? { externalCode: item.externalCode } : {}),
95
+ quantity: item.quantity,
96
+ unitPrice: reais(item.unitPriceCents),
97
+ price: reais(priceCents),
98
+ optionsPrice: reais(item.optionsPriceCents),
99
+ totalPrice: reais(priceCents + item.optionsPriceCents),
100
+ };
101
+ });
102
+ }
103
+
104
+ /** The customer part, or the first field iFood would refuse. */
105
+ function customerBody(customer: IfoodShippingOrderInput["customer"]): Record<string, unknown> | IfoodShippingInvalid {
106
+ const name = text(customer.name, NAME_MAX);
107
+ if (name === "") return { kind: "invalid", reason: "CUSTOMER_NAME" };
108
+ const phone = phoneOf(customer.phone);
109
+ if (phone === null) return { kind: "invalid", reason: "CUSTOMER_PHONE" };
110
+ return { name, phone: { ...phone, type: "CUSTOMER" } };
111
+ }
112
+
113
+ /** The delivery part, or the first field iFood would refuse. An expired quote is never sent. */
114
+ function deliveryBody(delivery: IfoodShippingOrderInput["delivery"], now: Date): Record<string, unknown> | IfoodShippingInvalid {
115
+ if (delivery.quote.expiresAt.getTime() <= now.getTime()) return { kind: "invalid", reason: "QUOTE_EXPIRED" };
116
+ if (!cents(delivery.merchantFeeCents)) return { kind: "invalid", reason: "MERCHANT_FEE" };
117
+ if (!cents(delivery.preparationTimeSeconds ?? 0)) return { kind: "invalid", reason: "PREPARATION_TIME" };
118
+ const deliveryAddress = ifoodShippingAddressBody(delivery.address, "order");
119
+ if (deliveryAddress === null) return { kind: "invalid", reason: "ADDRESS" };
120
+ return {
121
+ merchantFee: reais(delivery.merchantFeeCents),
122
+ ...(delivery.preparationTimeSeconds === undefined ? {} : { preparationTime: delivery.preparationTimeSeconds }),
123
+ quoteId: delivery.quote.id,
124
+ deliveryAddress,
125
+ };
126
+ }
127
+
128
+ const isInvalid = (value: Record<string, unknown> | IfoodShippingInvalid): value is IfoodShippingInvalid => value.kind === "invalid";
129
+
130
+ /** The documented body, or the first input iFood would refuse. Never a `payments` object: paid online only. */
131
+ function orderBody(input: IfoodShippingOrderInput, now: Date): Record<string, unknown> | IfoodShippingInvalid {
132
+ const customer = customerBody(input.customer);
133
+ if (isInvalid(customer)) return customer;
134
+ const delivery = deliveryBody(input.delivery, now);
135
+ if (isInvalid(delivery)) return delivery;
136
+ const items = itemsBody(input.items);
137
+ if (items === null) return { kind: "invalid", reason: "ITEMS" };
138
+ if (input.displayId !== undefined && !/^\S{1,4}$/.test(input.displayId)) return { kind: "invalid", reason: "DISPLAY_ID" };
139
+ return { customer, delivery, items, ...(input.displayId === undefined ? {} : { displayId: input.displayId }) };
140
+ }
141
+
142
+ function httpsUrl(value: string | null): string | null {
143
+ if (value === null || value.length > 2048) return null;
144
+ try {
145
+ return new URL(value).protocol === "https:" ? value : null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * `POST /shipping/v1.0/merchants/{merchantId}/orders`: registers the order
153
+ * and starts the courier search; 202 `{id, trackingUrl}`. "Se a entrega não
154
+ * for viável, o pedido não será criado." A create whose answer was lost, or a
155
+ * 2xx without an id, is `uncertain`: the delivery may exist, so it is retried
156
+ * only with the same `idempotencyKey`, never as a new one.
157
+ */
158
+ export async function ifoodShippingCreateOrder(
159
+ ctx: AdapterCallContext,
160
+ merchantId: string,
161
+ input: IfoodShippingOrderInput,
162
+ idempotencyKey: string,
163
+ ): Promise<IfoodShippingCreateResult> {
164
+ if (!idempotencyKeyValid(idempotencyKey)) return { kind: "invalid", reason: "IDEMPOTENCY_KEY" };
165
+ const body = orderBody(input, ctx.now);
166
+ if (isInvalid(body)) return body;
167
+ const url = `${IFOOD_SHIPPING_API}/merchants/${encodeURIComponent(merchantId)}/orders`;
168
+ const answer = await shippingCall(ctx, { method: "POST", url, body, idempotencyKey });
169
+ if (answer.kind !== "answer") return answer;
170
+ const parsed = parsedBody(answer.body);
171
+ const id = firstString(parsed, [["id"]]);
172
+ if (id === null) return { kind: "uncertain", reason: "iFood Shipping took the order without an id" };
173
+ return { kind: "created", id, trackingUrl: httpsUrl(firstString(parsed, [["trackingUrl"]])) };
174
+ }
175
+
176
+ export type IfoodShippingReasonsResult =
177
+ | { kind: "reasons"; reasons: OrderCancellationReason[] }
178
+ /** 204: the order can no longer be cancelled (the courier left with it, or it is over). */
179
+ | { kind: "not-cancellable" }
180
+ | IfoodShippingFailure;
181
+
182
+ /** `GET /shipping/v1.0/orders/{orderId}/cancellationReasons`: `[{cancelCodeId, description}]`, never hard-coded. */
183
+ export async function ifoodShippingCancellationReasons(ctx: AdapterCallContext, orderId: string): Promise<IfoodShippingReasonsResult> {
184
+ const answer = await shippingCall(ctx, { method: "GET", url: orderUrl(orderId, "cancellationReasons") });
185
+ if (answer.kind !== "answer") return answer;
186
+ if (answer.status === 204) return { kind: "not-cancellable" };
187
+ const list = parsedBody(answer.body);
188
+ if (!Array.isArray(list)) return { kind: "retry", reason: "iFood Shipping answered the reasons with no list" };
189
+ const reasons = list.flatMap((entry: unknown) => {
190
+ const code = pick(entry, "cancelCodeId");
191
+ if (typeof code !== "string" && typeof code !== "number") return [];
192
+ return [{ code: String(code), description: firstString(entry, [["description"]]) ?? String(code) }];
193
+ });
194
+ return { kind: "reasons", reasons };
195
+ }
196
+
197
+ /**
198
+ * `POST /shipping/v1.0/orders/{orderId}/cancel {reason, cancellationCode}`:
199
+ * 202, then `CANCELLED` or `CANCELLATION_REQUEST_FAILED` (e.g. the courier
200
+ * already left) as an event.
201
+ */
202
+ export function ifoodShippingCancel(
203
+ ctx: AdapterCallContext,
204
+ orderId: string,
205
+ input: { code: string; reason: string },
206
+ idempotencyKey: string,
207
+ ): Promise<IfoodShippingRequested | IfoodShippingFailure> {
208
+ if (!/^\d{1,9}$/.test(input.code)) return Promise.resolve({ kind: "invalid", reason: "CANCELLATION_CODE" });
209
+ // `reason` is required (the `outside` guide's table): an empty one is refused here.
210
+ const reason = input.reason.trim();
211
+ if (reason === "") return Promise.resolve({ kind: "invalid", reason: "CANCELLATION_REASON" });
212
+ return shippingPost(ctx, orderUrl(orderId, "cancel"), idempotencyKey, { reason, cancellationCode: Number(input.code) });
213
+ }
@@ -0,0 +1,274 @@
1
+ import type { AdapterCallContext } from "../core/adapter";
2
+ import { pick } from "../core/payload-read";
3
+ import { IFOOD_API, ifoodTokenKey, withIfoodToken } from "./outbound";
4
+
5
+ /**
6
+ * The wire half every iFood SHIPPING call shares (FUT-5667, FUT-5666): the
7
+ * base URL, the token, the idempotency key and how an answer reads. The calls
8
+ * themselves are `./shipping.ts` and `./shipping-orders.ts`.
9
+ *
10
+ * Read off iFood's Shipping guides on 2026-12-04, each page's markdown source:
11
+ *
12
+ * - https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/shipping/endpoints
13
+ * - https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/shipping/inside
14
+ * - https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/shipping/outside
15
+ * - https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/shipping/homologacao
16
+ * - https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/shipping/best-practices-troubleshooting/boas-praticas-e-troubleshooting
17
+ *
18
+ * Which app: Shipping is a module of the store's PDV (Delivery) app, the one
19
+ * whose token carries the `shipping` scope for the stores that authorized it.
20
+ * The context is used as the host hands it, a linked store's grant included,
21
+ * unlike the Logistics module's own app (`./logistics.ts`).
22
+ *
23
+ * Tests never reach iFood: the HTTP client is the host's port.
24
+ */
25
+
26
+ export const IFOOD_SHIPPING_API = `${IFOOD_API}/shipping/v1.0`;
27
+
28
+ /**
29
+ * The Shipping homologation's token rule: "Renove tokens antes do vencimento
30
+ * (recomendado: 5 minutos antes)". A Shipping call renews a cached token this
31
+ * close to its expiry; outside the window the cached one is used.
32
+ */
33
+ export const IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS = 5 * 60_000;
34
+
35
+ /**
36
+ * Every error code the Shipping guides document for a 400 (and the address
37
+ * answers' 409s). Anything else iFood names is read as `UNKNOWN`, so a code a
38
+ * host branches on is always one of these.
39
+ */
40
+ export const IFOOD_SHIPPING_ERROR_CODES = [
41
+ "BadRequest",
42
+ "BadRequestCustomer",
43
+ "BadRequestMerchant",
44
+ "DeliveryDistanceTooHigh",
45
+ "OffOpeningHours",
46
+ "OriginNotFound",
47
+ "ServiceAreaMismatch",
48
+ "HighDemand",
49
+ "MerchantStatusAvailability",
50
+ "MerchantEasyDeliveryDisabled",
51
+ "InvalidPaymentMethods",
52
+ "SaturatedOfflinePayment",
53
+ "NRELimitExceeded",
54
+ "UnavailableFleet",
55
+ "PaymentMethodNotFound",
56
+ "PaymentTotalInvalid",
57
+ "OrderNotFound",
58
+ "OrderWithoutSafeDelivery",
59
+ "ChangeAddressOperationConflict",
60
+ "ChangeAddressOperationNotStarted",
61
+ "MaxDistanceHigherThanAllowed",
62
+ "RegionMismatch",
63
+ ] as const;
64
+
65
+ export type IfoodShippingErrorCode = (typeof IFOOD_SHIPPING_ERROR_CODES)[number] | "UNKNOWN";
66
+
67
+ /**
68
+ * The codes iFood tells the integrator to try again later ("Tente novamente
69
+ * em alguns minutos", "Aguarde conclusão de entregas"): the moment, not the
70
+ * order, is the problem.
71
+ */
72
+ const TRANSIENT_CODES: ReadonlySet<string> = new Set(["HighDemand", "OffOpeningHours", "NRELimitExceeded", "UnavailableFleet"]);
73
+
74
+ /** A call refused here, before reaching iFood: nothing was sent. */
75
+ export interface IfoodShippingInvalid {
76
+ kind: "invalid";
77
+ reason:
78
+ | "IDEMPOTENCY_KEY"
79
+ | "QUOTE_EXPIRED"
80
+ | "COORDINATES"
81
+ | "CUSTOMER_NAME"
82
+ | "CUSTOMER_PHONE"
83
+ | "ADDRESS"
84
+ | "ADDRESS_TOO_FAR"
85
+ | "MERCHANT_FEE"
86
+ | "PREPARATION_TIME"
87
+ | "ITEMS"
88
+ | "DISPLAY_ID"
89
+ | "CANCELLATION_CODE"
90
+ | "CANCELLATION_REASON";
91
+ }
92
+
93
+ /** How a Shipping call can fail. */
94
+ export type IfoodShippingFailure =
95
+ /** A documented "not now / not here" answer: iFood's code, and whether the guides say to try again later. */
96
+ | { kind: "unavailable"; status: number; code: IfoodShippingErrorCode; transient: boolean }
97
+ /** Any other final 4xx. The message names the status and code only: an answer body can echo a customer. */
98
+ | { kind: "refused"; status: number; message: string; own?: true }
99
+ /**
100
+ * Nothing was changed, ask again (with backoff): a read answered 408, 425,
101
+ * 429 or 5xx, a POST answered 425, 429 or 503, a lost read, a lost token grant.
102
+ */
103
+ | { kind: "retry"; reason: string }
104
+ /**
105
+ * A state-changing request was SENT and may have been applied: no answer
106
+ * came back, or a POST was answered 408, 500, 502, 504 (or another 5xx but
107
+ * 503). Never retried blindly; a retry goes with the SAME idempotency key.
108
+ */
109
+ | { kind: "uncertain"; reason: string }
110
+ | IfoodShippingInvalid;
111
+
112
+ /** A state-changing call iFood took (2xx). Its outcome arrives as an event. */
113
+ export interface IfoodShippingRequested {
114
+ kind: "requested";
115
+ }
116
+
117
+ /** An answer read as the client acts on it: the 2xx body, or a failure. */
118
+ type IfoodShippingAnswer = { kind: "answer"; status: number; body: string } | IfoodShippingFailure;
119
+
120
+ /**
121
+ * The caller's idempotency key: stable for one logical operation (an order's
122
+ * creation, its cancel), never minted per attempt, so a retry carries the key
123
+ * of the request it repeats.
124
+ */
125
+ export function idempotencyKeyValid(key: string): boolean {
126
+ return /^[\w:.-]{1,255}$/.test(key);
127
+ }
128
+
129
+ /** iFood's `code` from an error body, as the closed set. */
130
+ function errorCodeOf(body: string): IfoodShippingErrorCode | null {
131
+ let parsed: unknown;
132
+ try {
133
+ parsed = JSON.parse(body) as unknown;
134
+ } catch {
135
+ return null;
136
+ }
137
+ const code = pick(parsed, "code");
138
+ if (typeof code !== "string") return null;
139
+ return (IFOOD_SHIPPING_ERROR_CODES as readonly string[]).includes(code) ? (code as IfoodShippingErrorCode) : "UNKNOWN";
140
+ }
141
+
142
+ /** Statuses that say "ask again later" for a read: nothing was changed. */
143
+ const READ_RETRY_STATUSES = new Set([408, 425, 429]);
144
+
145
+ /**
146
+ * Statuses that say iFood did not process a state-changing request: 425 and
147
+ * 429 refuse it before processing, 503 is the documented "unavailable". Any
148
+ * other 5xx, and a 408, may come after iFood applied it (a gateway timing out
149
+ * after the write), so a POST answered so is `uncertain`, never `retry`: until
150
+ * iFood confirms it drops a duplicate by `Idempotency-Key`, a blind re-send
151
+ * could make a second delivery.
152
+ */
153
+ const POST_RETRY_STATUSES = new Set([425, 429, 503]);
154
+
155
+ /** Whether a non-2xx answer says "ask again": per method (see the two sets above). */
156
+ function retriable(method: "GET" | "POST", status: number): boolean {
157
+ if (method === "POST") return POST_RETRY_STATUSES.has(status);
158
+ return status >= 500 || READ_RETRY_STATUSES.has(status) || POST_RETRY_STATUSES.has(status);
159
+ }
160
+
161
+ /** A POST answer that may come after iFood applied it. */
162
+ const mayBeApplied = (method: "GET" | "POST", status: number): boolean => method === "POST" && (status >= 500 || status === 408);
163
+
164
+ /** A non-2xx answer as the client's failure. iFood's message is never kept. */
165
+ function failureOf(method: "GET" | "POST", status: number, body: string): IfoodShippingFailure {
166
+ const code = errorCodeOf(body);
167
+ const reason = `iFood Shipping answered ${status}`;
168
+ if (status >= 400 && retriable(method, status)) return { kind: "retry", reason };
169
+ if (mayBeApplied(method, status)) return { kind: "uncertain", reason };
170
+ // The guides document their codes on 400s, and on the address answers' 409s; a 3xx is refused.
171
+ if ((status === 400 || status === 409) && code !== null) return { kind: "unavailable", status, code, transient: TRANSIENT_CODES.has(code) };
172
+ return { kind: "refused", status, message: `${reason}${code ? ` ${code}` : ""}` };
173
+ }
174
+
175
+ /** Forget a cached token that expires within the homologation's 5-minute window. A linked grant renews itself. */
176
+ function renewAhead(ctx: AdapterCallContext): void {
177
+ if (ctx.grant) return;
178
+ const key = ifoodTokenKey(ctx);
179
+ const cached = ctx.tokens.get(key);
180
+ if (cached && cached.expiresAt - ctx.now.getTime() <= IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS) ctx.tokens.delete(key);
181
+ }
182
+
183
+ interface ShippingRequest {
184
+ method: "GET" | "POST";
185
+ url: string;
186
+ body?: unknown;
187
+ /** Required on every POST: sent as `Idempotency-Key` (Shipping homologation, "Idempotência"). */
188
+ idempotencyKey?: string;
189
+ }
190
+
191
+ /**
192
+ * One authenticated Shipping call. A 401 renews the token once
193
+ * (`withIfoodToken`). A throw before the request left (the token grant, or
194
+ * after a 401) is a retry; a throw after a POST left is `uncertain`; a lost
195
+ * GET is a retry.
196
+ */
197
+ export async function shippingCall(ctx: AdapterCallContext, request: ShippingRequest): Promise<IfoodShippingAnswer> {
198
+ let sent = false;
199
+ try {
200
+ renewAhead(ctx);
201
+ const response = await withIfoodToken(ctx, async (token) => {
202
+ sent = true;
203
+ const answer = await ctx.http({
204
+ method: request.method,
205
+ url: request.url,
206
+ headers: {
207
+ Authorization: `Bearer ${token}`,
208
+ ...(request.body === undefined ? {} : { "Content-Type": "application/json" }),
209
+ ...(request.idempotencyKey === undefined ? {} : { "Idempotency-Key": request.idempotencyKey }),
210
+ },
211
+ ...(request.body === undefined ? {} : { body: JSON.stringify(request.body) }),
212
+ });
213
+ // A 401 was refused before anything was applied: the next attempt starts unsent.
214
+ if (answer.status === 401) sent = false;
215
+ return answer;
216
+ });
217
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
218
+ if ("kind" in response) return response.kind === "accepted" ? { kind: "retry", reason: "no token" } : response;
219
+ if (response.status >= 200 && response.status < 300) return { kind: "answer", status: response.status, body: response.body };
220
+ return failureOf(request.method, response.status, response.body);
221
+ } catch {
222
+ // Fixed reasons: a host client's error text can carry a URL or an answer body.
223
+ if (sent && request.method === "POST") return { kind: "uncertain", reason: "iFood Shipping request sent, no answer" };
224
+ return { kind: "retry", reason: sent ? "iFood Shipping read got no answer" : "iFood token request got no answer" };
225
+ }
226
+ }
227
+
228
+ /** A state-changing POST whose 2xx says only "taken". */
229
+ export async function shippingPost(
230
+ ctx: AdapterCallContext,
231
+ url: string,
232
+ idempotencyKey: string,
233
+ body?: unknown,
234
+ ): Promise<IfoodShippingRequested | IfoodShippingFailure> {
235
+ if (!idempotencyKeyValid(idempotencyKey)) return { kind: "invalid", reason: "IDEMPOTENCY_KEY" };
236
+ const answer = await shippingCall(ctx, { method: "POST", url, body, idempotencyKey });
237
+ return answer.kind === "answer" ? { kind: "requested" } : answer;
238
+ }
239
+
240
+ /** A JSON body, or null. */
241
+ export function parsedBody(body: string): unknown {
242
+ try {
243
+ return JSON.parse(body) as unknown;
244
+ } catch {
245
+ return null;
246
+ }
247
+ }
248
+
249
+ /** A finite number at `key`, or null. */
250
+ export function numberAt(source: unknown, ...path: string[]): number | null {
251
+ const value = pick(source, ...path);
252
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
253
+ }
254
+
255
+ /** Cents as iFood's reais, two decimals. */
256
+ export const reais = (cents: number): number => Math.round(cents) / 100;
257
+
258
+ /** Coordinates a delivery can be at. */
259
+ export function coordinatesValid(point: { latitude: number; longitude: number }): boolean {
260
+ const { latitude, longitude } = point;
261
+ return Number.isFinite(latitude) && Number.isFinite(longitude) && Math.abs(latitude) <= 90 && Math.abs(longitude) <= 180;
262
+ }
263
+
264
+ /**
265
+ * How long to wait before an attempt (1-based) of a call that answered
266
+ * `retry`: the best-practices guide's table, 2x with jitter (immediate, 1 s,
267
+ * 2 s, 4 s, 8 s, each plus under a second), at most 5 attempts. Null: stop.
268
+ * The host's job schedules it; the client never sleeps.
269
+ */
270
+ export function ifoodShippingRetryDelayMs(attempt: number, random: () => number = Math.random): number | null {
271
+ if (!Number.isInteger(attempt) || attempt < 1 || attempt > 5) return null;
272
+ if (attempt === 1) return 0;
273
+ return 2 ** (attempt - 2) * 1000 + Math.floor(random() * 1000);
274
+ }
@@ -0,0 +1,184 @@
1
+ import type { AdapterCallContext } from "../core/adapter";
2
+ import type { MarketplaceCourierTracking } from "../core/courier-port";
3
+ import { firstDate, firstString, pick, toCents } from "../core/payload-read";
4
+ import { readIfoodTracking } from "./courier";
5
+ import {
6
+ IFOOD_SHIPPING_API,
7
+ coordinatesValid,
8
+ numberAt,
9
+ parsedBody,
10
+ shippingCall,
11
+ shippingPost,
12
+ type IfoodShippingFailure,
13
+ type IfoodShippingRequested,
14
+ } from "./shipping-wire";
15
+
16
+ export {
17
+ IFOOD_SHIPPING_API,
18
+ IFOOD_SHIPPING_ERROR_CODES,
19
+ IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS,
20
+ ifoodShippingRetryDelayMs,
21
+ type IfoodShippingErrorCode,
22
+ type IfoodShippingFailure,
23
+ type IfoodShippingInvalid,
24
+ type IfoodShippingRequested,
25
+ } from "./shipping-wire";
26
+
27
+ /**
28
+ * iFood's SHIPPING module ("Entrega Sob Demanda"): an iFood courier for a
29
+ * delivery the store would otherwise carry. Wire format only, like
30
+ * `./logistics.ts`: when a call is made, the job that makes it and what the
31
+ * store sees are the host's.
32
+ *
33
+ * This file: the quote (both kinds), and, for an order placed ON the iFood
34
+ * platform (FUT-5666), `requestDriver` and `cancelRequestDriver`; and the
35
+ * tracking read both kinds share. An order placed OFF the platform (FUT-5667)
36
+ * is `./shipping-orders.ts`. Sources and the token rule: `./shipping-wire.ts`.
37
+ */
38
+
39
+ const orderUrl = (externalOrderId: string, action: string): string =>
40
+ `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(externalOrderId)}/${action}`;
41
+
42
+ /** One way the courier can be paid at the door, as the quote lists it. */
43
+ export interface IfoodShippingPaymentMethod {
44
+ /** CREDIT, DEBIT or CASH. */
45
+ method: string;
46
+ /** OFFLINE: paid at the door. */
47
+ paymentType: string;
48
+ brand: string | null;
49
+ liability: string | null;
50
+ }
51
+
52
+ /** iFood's quote, money in cents. Valid until `expiresAt` (about 24 h); a later request is refused. */
53
+ export interface IfoodShippingQuote {
54
+ /** The `quoteId` a request or an order names. */
55
+ id: string;
56
+ expiresAt: Date;
57
+ createdAt: Date | null;
58
+ distanceMeters: number | null;
59
+ /** The preparation time iFood suggests, in seconds. Only the off-platform quote states one. */
60
+ preparationTimeSeconds: number | null;
61
+ grossCents: number;
62
+ discountCents: number;
63
+ /** Only the off-platform quote states a raise; 0 otherwise. */
64
+ raiseCents: number;
65
+ /** What the store pays: `gross - discount + raise`, as iFood states it. */
66
+ netCents: number;
67
+ deliveryTimeSeconds: { min: number | null; max: number | null };
68
+ paymentMethods: IfoodShippingPaymentMethod[];
69
+ }
70
+
71
+ export type IfoodShippingQuoteResult = { kind: "quote"; quote: IfoodShippingQuote } | IfoodShippingFailure;
72
+
73
+ function paymentMethodsOf(body: unknown): IfoodShippingPaymentMethod[] {
74
+ const list = pick(body, "paymentMethods");
75
+ if (!Array.isArray(list)) return [];
76
+ return list.flatMap((entry: unknown) => {
77
+ const method = firstString(entry, [["method"]]);
78
+ const paymentType = firstString(entry, [["paymentType"]]);
79
+ if (method === null || paymentType === null) return [];
80
+ return [{ method, paymentType, brand: firstString(entry, [["brand"]]), liability: firstString(entry, [["liability"]]) }];
81
+ });
82
+ }
83
+
84
+ /** The 200 body of either `deliveryAvailabilities`. Null: no usable quote (no id, no expiry or no price). */
85
+ function quoteOf(body: unknown): IfoodShippingQuote | null {
86
+ const id = firstString(body, [["id"]]);
87
+ const expiresAt = firstDate(body, [["expirationAt"]]);
88
+ const grossCents = toCents(pick(body, "quote", "grossValue"));
89
+ const netCents = toCents(pick(body, "quote", "netValue"));
90
+ if (id === null || expiresAt === null || grossCents === null || netCents === null) return null;
91
+ return {
92
+ id,
93
+ expiresAt,
94
+ createdAt: firstDate(body, [["createdAt"]]),
95
+ distanceMeters: numberAt(body, "distance"),
96
+ preparationTimeSeconds: numberAt(body, "preparationTime"),
97
+ grossCents,
98
+ discountCents: toCents(pick(body, "quote", "discount")) ?? 0,
99
+ raiseCents: toCents(pick(body, "quote", "raise")) ?? 0,
100
+ netCents,
101
+ deliveryTimeSeconds: { min: numberAt(body, "deliveryTime", "min"), max: numberAt(body, "deliveryTime", "max") },
102
+ paymentMethods: paymentMethodsOf(body),
103
+ };
104
+ }
105
+
106
+ async function quote(ctx: AdapterCallContext, url: string): Promise<IfoodShippingQuoteResult> {
107
+ const answer = await shippingCall(ctx, { method: "GET", url });
108
+ if (answer.kind !== "answer") return answer;
109
+ const read = quoteOf(parsedBody(answer.body));
110
+ return read ? { kind: "quote", quote: read } : { kind: "retry", reason: "iFood Shipping answered a quote without an id" };
111
+ }
112
+
113
+ /**
114
+ * `GET /shipping/v1.0/orders/{orderId}/deliveryAvailabilities`: the quote for
115
+ * an order placed on the iFood platform (FUT-5666). Its 400 codes are the
116
+ * `inside` guide's list.
117
+ */
118
+ export function ifoodShippingQuoteForOrder(ctx: AdapterCallContext, externalOrderId: string): Promise<IfoodShippingQuoteResult> {
119
+ return quote(ctx, orderUrl(externalOrderId, "deliveryAvailabilities"));
120
+ }
121
+
122
+ /**
123
+ * `GET /shipping/v1.0/merchants/{merchantId}/deliveryAvailabilities?latitude&longitude`:
124
+ * the quote for a door, for an order placed off the platform (FUT-5667).
125
+ */
126
+ export async function ifoodShippingQuoteForAddress(
127
+ ctx: AdapterCallContext,
128
+ merchantId: string,
129
+ point: { latitude: number; longitude: number },
130
+ ): Promise<IfoodShippingQuoteResult> {
131
+ if (!coordinatesValid(point)) return { kind: "invalid", reason: "COORDINATES" };
132
+ const query = new URLSearchParams({ latitude: String(point.latitude), longitude: String(point.longitude) });
133
+ return quote(ctx, `${IFOOD_SHIPPING_API}/merchants/${encodeURIComponent(merchantId)}/deliveryAvailabilities?${query.toString()}`);
134
+ }
135
+
136
+ /** The quote a request names. */
137
+ export interface IfoodShippingQuoteRef {
138
+ id: string;
139
+ expiresAt: Date;
140
+ }
141
+
142
+ /**
143
+ * `POST /shipping/v1.0/orders/{orderId}/requestDriver {quoteId}` (FUT-5666):
144
+ * 202, then `REQUEST_DRIVER_SUCCESS` or `REQUEST_DRIVER_FAILED` as an event.
145
+ * An expired quote is never sent ("Solicitar após é inválido").
146
+ */
147
+ export async function ifoodRequestDriver(
148
+ ctx: AdapterCallContext,
149
+ input: { externalOrderId: string; quote: IfoodShippingQuoteRef; idempotencyKey: string },
150
+ ): Promise<IfoodShippingRequested | IfoodShippingFailure> {
151
+ if (input.quote.expiresAt.getTime() <= ctx.now.getTime()) return { kind: "invalid", reason: "QUOTE_EXPIRED" };
152
+ return shippingPost(ctx, orderUrl(input.externalOrderId, "requestDriver"), input.idempotencyKey, { quoteId: input.quote.id });
153
+ }
154
+
155
+ /**
156
+ * `POST /shipping/v1.0/orders/{orderId}/cancelRequestDriver`, no body: only
157
+ * before a courier accepts, free and irreversible. The outcome is
158
+ * `DELIVERY_CANCELLATION_REQUEST_ACCEPTED` or `..._REJECTED` (the courier had
159
+ * accepted: the order's own cancellation applies then).
160
+ */
161
+ export function ifoodCancelRequestDriver(
162
+ ctx: AdapterCallContext,
163
+ input: { externalOrderId: string; idempotencyKey: string },
164
+ ): Promise<IfoodShippingRequested | IfoodShippingFailure> {
165
+ return shippingPost(ctx, orderUrl(input.externalOrderId, "cancelRequestDriver"), input.idempotencyKey);
166
+ }
167
+
168
+ export type IfoodShippingTrackingResult =
169
+ | { kind: "tracking"; tracking: MarketplaceCourierTracking }
170
+ /** 404: no courier assigned yet ("Nunca consultar tracking antes de REQUEST_DRIVER_SUCCESS"). */
171
+ | { kind: "notYet" }
172
+ | IfoodShippingFailure;
173
+
174
+ /**
175
+ * `GET /shipping/v1.0/orders/{orderId}/tracking`, for either kind of order
176
+ * (the off-platform order by the id its creation answered). At most once per
177
+ * 30 s, which is the caller's schedule.
178
+ */
179
+ export async function ifoodShippingTracking(ctx: AdapterCallContext, orderId: string): Promise<IfoodShippingTrackingResult> {
180
+ const answer = await shippingCall(ctx, { method: "GET", url: orderUrl(orderId, "tracking") });
181
+ if (answer.kind === "refused" && answer.status === 404) return { kind: "notYet" };
182
+ if (answer.kind !== "answer") return answer;
183
+ return { kind: "tracking", tracking: readIfoodTracking(parsedBody(answer.body), ctx.now) };
184
+ }