@12-apps/marketplace 1.13.0 → 1.15.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.
- package/ADOPTING.md +258 -3
- package/README.md +27 -2
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +3 -3
- package/dist/{adapter-CQ4QiZPi.d.ts → adapter-CjVdMhZ2.d.ts} +177 -4
- package/dist/{chunk-CEWTV2TC.js → chunk-B4DYPQFE.js} +657 -251
- package/dist/chunk-B4DYPQFE.js.map +1 -0
- package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
- package/dist/chunk-BTKVZAJI.js.map +1 -0
- package/dist/{chunk-BD7DS3XM.js → chunk-E4XJXHUK.js} +20 -1
- package/dist/chunk-E4XJXHUK.js.map +1 -0
- package/dist/{chunk-W57TITU4.js → chunk-FQI56NGC.js} +53 -6
- package/dist/chunk-FQI56NGC.js.map +1 -0
- package/dist/chunk-H2VQRD3B.js +16 -0
- package/dist/chunk-H2VQRD3B.js.map +1 -0
- package/dist/{chunk-NFJQQWG4.js → chunk-TRUK5ZBE.js} +12 -4
- package/dist/chunk-TRUK5ZBE.js.map +1 -0
- package/dist/{client-CCSnylou.d.ts → client-DgzCkl8u.d.ts} +1 -1
- package/dist/{engine-1KlJ_8jK.d.ts → engine-BSLdhAGC.d.ts} +134 -3
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -2
- package/dist/hono/index.js.map +1 -1
- package/dist/ifood/index.d.ts +13 -3
- package/dist/ifood/index.js +219 -29
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +29 -5
- package/dist/index.js +59 -7
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +3 -3
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +3 -2
- package/dist/manifest/server.js.map +1 -1
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +2 -2
- package/dist/server/index.d.ts +14 -5
- package/dist/server/index.js +3 -2
- package/package.json +1 -1
- package/prisma/marketplace.prisma +17 -3
- package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
- package/src/core/acceptance.ts +12 -6
- package/src/core/acknowledge.ts +189 -0
- package/src/core/adapter.ts +74 -1
- package/src/core/cancellation.ts +10 -6
- package/src/core/conformity.ts +63 -0
- package/src/core/engine.ts +3 -2
- package/src/core/ingest.ts +7 -0
- package/src/core/link-store.ts +2 -4
- package/src/core/marketplace-confirmed.ts +229 -0
- package/src/core/order-reasons.ts +119 -0
- package/src/core/order-types.ts +8 -0
- package/src/core/outbound.ts +5 -1
- package/src/core/payload-read.ts +24 -0
- package/src/core/pipeline.ts +27 -1
- package/src/core/ports.ts +2 -0
- package/src/core/registry.ts +28 -2
- package/src/core/state.ts +10 -0
- package/src/core/status-job.ts +86 -3
- package/src/core/types.ts +117 -2
- package/src/ifood/index.ts +27 -4
- package/src/ifood/normalize.ts +38 -5
- package/src/ifood/order-details.ts +120 -0
- package/src/ifood/outbound.ts +131 -27
- package/src/index.ts +24 -0
- package/src/open-delivery/normalize.ts +9 -0
- package/src/server/jobs.ts +57 -4
- package/src/server/webhook.ts +27 -4
- package/dist/chunk-4J2KJ3ZW.js.map +0 -1
- package/dist/chunk-BD7DS3XM.js.map +0 -1
- package/dist/chunk-CEWTV2TC.js.map +0 -1
- package/dist/chunk-NFJQQWG4.js.map +0 -1
- package/dist/chunk-W57TITU4.js.map +0 -1
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
MarketplacePaymentMethod,
|
|
3
|
+
NormalizedLineOption,
|
|
4
|
+
NormalizedOrderFee,
|
|
5
|
+
NormalizedPaymentMethod,
|
|
6
|
+
NormalizedPayments,
|
|
7
|
+
} from "../core/types";
|
|
8
|
+
import { firstCents, firstString, firstTaxId, pick, toCents } from "../core/payload-read";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The parts of an iFood order beyond its items' base price (FUT-5803): each
|
|
12
|
+
* item's options, the payment, the fees besides delivery and the buyer's
|
|
13
|
+
* document. Field names follow iFood's order-details guide
|
|
14
|
+
* ("Detalhes do pedido", developer portal); read
|
|
15
|
+
* defensively like the rest of the adapter, so an absent part is absent,
|
|
16
|
+
* never a refused order.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** A whole, positive count; 1 when absent or nonsense. */
|
|
20
|
+
function countOf(source: unknown): number {
|
|
21
|
+
const stated = Number(pick(source, "quantity") ?? 1);
|
|
22
|
+
return Number.isFinite(stated) && stated > 0 ? Math.round(stated) : 1;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The option's rows, each with `unitPriceCents × quantity` exactly its total,
|
|
27
|
+
* because a host writes the two and must read the stated price back. Kept as
|
|
28
|
+
* stated when they agree. Otherwise the stated total is split over the stated
|
|
29
|
+
* quantity, as Open Delivery's lines are: one row when it divides, else
|
|
30
|
+
* `quantity - 1` at the floor and one carrying the remainder (R$ 10.00 over 3
|
|
31
|
+
* is 2 × 3.33 + 1 × 3.34). The count the kitchen reads never changes.
|
|
32
|
+
*/
|
|
33
|
+
function priced(quantity: number, unit: number | null, total: number): { quantity: number; unitPriceCents: number; totalCents: number }[] {
|
|
34
|
+
if (unit !== null && unit * quantity === total) return [{ quantity, unitPriceCents: unit, totalCents: total }];
|
|
35
|
+
const floor = Math.floor(total / quantity);
|
|
36
|
+
const remainder = total - floor * quantity;
|
|
37
|
+
if (remainder === 0) return [{ quantity, unitPriceCents: floor, totalCents: total }];
|
|
38
|
+
const last = { quantity: 1, unitPriceCents: floor + remainder, totalCents: floor + remainder };
|
|
39
|
+
return quantity === 1 ? [last] : [{ quantity: quantity - 1, unitPriceCents: floor, totalCents: floor * (quantity - 1) }, last];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One `items[].options[]` entry as its rows (one, or two when its price splits); none for one with no name and no price. */
|
|
43
|
+
function readOption(raw: unknown): NormalizedLineOption[] {
|
|
44
|
+
const quantity = countOf(raw);
|
|
45
|
+
const unit = toCents(pick(raw, "unitPrice"));
|
|
46
|
+
const total = toCents(pick(raw, "price")) ?? (unit ?? 0) * quantity;
|
|
47
|
+
const name = firstString(raw, [["name"], ["externalCode"]]);
|
|
48
|
+
if (name === null && total === 0) return [];
|
|
49
|
+
const option = { externalCode: firstString(raw, [["externalCode"]]), name: name ?? "", groupName: firstString(raw, [["groupName"]]) };
|
|
50
|
+
return priced(quantity, unit, total).map((row) => ({ ...option, ...row }));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** An item's options; undefined when it states none, so a plain line stays as it was. */
|
|
54
|
+
export function readIfoodOptions(item: unknown): NormalizedLineOption[] | undefined {
|
|
55
|
+
const raw = pick(item, "options");
|
|
56
|
+
if (!Array.isArray(raw)) return undefined;
|
|
57
|
+
const options = raw.flatMap(readOption);
|
|
58
|
+
return options.length > 0 ? options : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const METHODS: ReadonlySet<string> = new Set<MarketplacePaymentMethod>([
|
|
62
|
+
"CREDIT",
|
|
63
|
+
"DEBIT",
|
|
64
|
+
"MEAL_VOUCHER",
|
|
65
|
+
"FOOD_VOUCHER",
|
|
66
|
+
"PIX",
|
|
67
|
+
"CASH",
|
|
68
|
+
"DIGITAL_WALLET",
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
/** `type` ONLINE is prepaid and OFFLINE is collected; failing both, the method's own `prepaid` flag. */
|
|
72
|
+
function prepaidOf(raw: unknown): boolean | null {
|
|
73
|
+
const type = firstString(raw, [["type"]])?.toUpperCase();
|
|
74
|
+
if (type === "ONLINE") return true;
|
|
75
|
+
if (type === "OFFLINE") return false;
|
|
76
|
+
const flag = pick(raw, "prepaid");
|
|
77
|
+
return typeof flag === "boolean" ? flag : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** One `payments.methods[]` entry. A method with no value states 0: the method itself is what the door needs. */
|
|
81
|
+
function readMethod(raw: unknown): NormalizedPaymentMethod {
|
|
82
|
+
const stated = firstString(raw, [["method"]])?.toUpperCase() ?? null;
|
|
83
|
+
return {
|
|
84
|
+
method: stated !== null && METHODS.has(stated) ? (stated as MarketplacePaymentMethod) : "OTHER",
|
|
85
|
+
statedMethod: stated,
|
|
86
|
+
prepaid: prepaidOf(raw),
|
|
87
|
+
valueCents: toCents(pick(raw, "value")) ?? 0,
|
|
88
|
+
cardBrand: firstString(raw, [["card", "brand"]]),
|
|
89
|
+
changeForCents: firstCents(raw, [["cash", "changeFor"], ["changeFor"]]),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** `payments`: what is prepaid, what is pending, and each method. Undefined when the order states no payment. */
|
|
94
|
+
export function readIfoodPayments(order: unknown): NormalizedPayments | undefined {
|
|
95
|
+
const payments = pick(order, "payments");
|
|
96
|
+
if (typeof payments !== "object" || payments === null) return undefined;
|
|
97
|
+
const methods = pick(payments, "methods");
|
|
98
|
+
return {
|
|
99
|
+
prepaidCents: firstCents(payments, [["prepaid"]]),
|
|
100
|
+
pendingCents: firstCents(payments, [["pending"]]),
|
|
101
|
+
methods: Array.isArray(methods) ? methods.map(readMethod) : [],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** `additionalFees[]`: each with a type and a value. Undefined when unstated; a fee with no value is skipped. */
|
|
106
|
+
export function readIfoodAdditionalFees(order: unknown): NormalizedOrderFee[] | undefined {
|
|
107
|
+
const raw = pick(order, "additionalFees");
|
|
108
|
+
if (!Array.isArray(raw)) return undefined;
|
|
109
|
+
return raw.flatMap((fee): NormalizedOrderFee[] => {
|
|
110
|
+
const cents = toCents(pick(fee, "value"));
|
|
111
|
+
if (cents === null) return [];
|
|
112
|
+
const name = firstString(fee, [["description"]]);
|
|
113
|
+
return [{ kind: firstString(fee, [["type"]])?.toUpperCase() ?? "OTHER", cents, ...(name === null ? {} : { name }) }];
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The buyer's CPF or CNPJ, digits only (`documentNumber`, or `document`, text or a number); null when unstated. */
|
|
118
|
+
export function readIfoodBuyerDocument(order: unknown): string | null {
|
|
119
|
+
return firstTaxId(order, [["customer", "documentNumber"], ["customer", "document"]]);
|
|
120
|
+
}
|
package/src/ifood/outbound.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
/**
|
|
90
|
-
|
|
91
|
-
|
|
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
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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
|
|
134
|
-
*
|
|
135
|
-
*
|
|
136
|
-
*
|
|
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
|
-
|
|
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,
|
|
@@ -75,6 +79,7 @@ export type {
|
|
|
75
79
|
} from "./core/ports";
|
|
76
80
|
export {
|
|
77
81
|
PROVIDER_ID_PATTERN,
|
|
82
|
+
normalizedLineTotalCents,
|
|
78
83
|
type CancellationOutcome,
|
|
79
84
|
type MarketplaceDeliveredBy,
|
|
80
85
|
type MarketplaceDiscountSponsor,
|
|
@@ -91,6 +96,11 @@ export {
|
|
|
91
96
|
type NormalizedMarketplaceOrder,
|
|
92
97
|
type NormalizedOrderDiscount,
|
|
93
98
|
type NormalizedOrderLine,
|
|
99
|
+
type NormalizedLineOption,
|
|
100
|
+
type MarketplacePaymentMethod,
|
|
101
|
+
type NormalizedPaymentMethod,
|
|
102
|
+
type NormalizedPayments,
|
|
103
|
+
type NormalizedOrderFee,
|
|
94
104
|
} from "./core/types";
|
|
95
105
|
export type {
|
|
96
106
|
AcceptanceStatus,
|
|
@@ -159,6 +169,20 @@ export {
|
|
|
159
169
|
type FetchOrderOutcome,
|
|
160
170
|
} from "./core/fetch-order";
|
|
161
171
|
export type { MarketplaceOrderState } from "./core/state";
|
|
172
|
+
export {
|
|
173
|
+
AcknowledgeRetryError,
|
|
174
|
+
MARKETPLACE_ACKNOWLEDGE_JOB,
|
|
175
|
+
type AcknowledgeJobPayload,
|
|
176
|
+
type AcknowledgeOutcome,
|
|
177
|
+
} from "./core/acknowledge";
|
|
178
|
+
export {
|
|
179
|
+
CancellationReasonsRetryError,
|
|
180
|
+
MARKETPLACE_CANCELLATION_REASONS_JOB,
|
|
181
|
+
type CancellationReasonsJobPayload,
|
|
182
|
+
type CancellationReasonsOutcome,
|
|
183
|
+
} from "./core/order-reasons";
|
|
184
|
+
export { CONFIRMED_BEFORE_ORDER } from "./core/marketplace-confirmed";
|
|
185
|
+
export type { MarketplaceConformityEngine } from "./core/conformity";
|
|
162
186
|
export {
|
|
163
187
|
CatalogueRetryError,
|
|
164
188
|
catalogueDedupeKey,
|
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
firstCents,
|
|
4
4
|
firstDate,
|
|
5
5
|
firstString,
|
|
6
|
+
firstTaxId,
|
|
6
7
|
pick,
|
|
7
8
|
toCents,
|
|
8
9
|
verifyHmacSha256Hex,
|
|
@@ -220,6 +221,12 @@ function readAddress(order: unknown, missingStreetNumber: string): NormalizedAdd
|
|
|
220
221
|
};
|
|
221
222
|
}
|
|
222
223
|
|
|
224
|
+
/** `customer.documentNumber` (text or a number), digits only, as `{ document }`; nothing when unstated. */
|
|
225
|
+
function buyerDocument(order: unknown): { document?: string } {
|
|
226
|
+
const digits = firstTaxId(order, [["customer", "documentNumber"]]);
|
|
227
|
+
return digits ? { document: digits } : {};
|
|
228
|
+
}
|
|
229
|
+
|
|
223
230
|
/**
|
|
224
231
|
* Normalize one `Order` (the answer of `GET /v1/orders/{orderId}`). Null when
|
|
225
232
|
* it carries no id or no line.
|
|
@@ -248,6 +255,8 @@ export function normalizeOpenDeliveryOrderAs(
|
|
|
248
255
|
externalId: firstString(order, [["customer", "id"]]),
|
|
249
256
|
name: firstString(order, [["customer", "name"]]),
|
|
250
257
|
phone: firstString(order, [["customer", "phone", "number"]]),
|
|
258
|
+
// FUT-5803: the CPF or CNPJ for the invoice, digits only; absent when unstated.
|
|
259
|
+
...buyerDocument(order),
|
|
251
260
|
},
|
|
252
261
|
lines,
|
|
253
262
|
// The line sum is the FALLBACK: the stated total carries the fees and
|
package/src/server/jobs.ts
CHANGED
|
@@ -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
|
|
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.
|
|
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
|
-
|
|
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,
|
package/src/server/webhook.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { WireRequest, WireResponse, WireRoute } from "@12-apps/wiring";
|
|
2
2
|
|
|
3
|
+
import type { PresenceProbe } from "../core/adapter";
|
|
3
4
|
import type { IngestionTarget } from "../core/integration";
|
|
4
5
|
import type { MarketplaceApiConfig } from "./http";
|
|
5
6
|
|
|
@@ -13,7 +14,8 @@ import type { MarketplaceApiConfig } from "./http";
|
|
|
13
14
|
* (which header carries the signature, and how it is computed) — the route
|
|
14
15
|
* itself knows no marketplace.
|
|
15
16
|
*
|
|
16
|
-
* It answers 2xx for almost everything, deliberately
|
|
17
|
+
* It answers 2xx for almost everything, deliberately: 200, or the status the
|
|
18
|
+
* adapter states (`webhookAnswerStatus`: iFood's 202, FUT-5984). A marketplace
|
|
17
19
|
* redelivers on any non-2xx, so the only failures worth signalling are the
|
|
18
20
|
* ones a redelivery could fix: a genuine processing failure answers 500, and
|
|
19
21
|
* the inbox row it left is retried by the sweep regardless. Refusals (unknown
|
|
@@ -93,17 +95,31 @@ async function handleWebhook(config: MarketplaceApiConfig, request: WireRequest<
|
|
|
93
95
|
return deliverAdmitted(config, admitted);
|
|
94
96
|
}
|
|
95
97
|
|
|
98
|
+
/**
|
|
99
|
+
* The answer to a proven presence heartbeat (FUT-5984, iFood's `KEEPALIVE`):
|
|
100
|
+
* 202, and in the per-merchant mode every merchant it asked about named
|
|
101
|
+
* online. Nothing is recorded.
|
|
102
|
+
*/
|
|
103
|
+
function presenceAnswer(probe: PresenceProbe): WireResponse {
|
|
104
|
+
return probe.merchantIds === null
|
|
105
|
+
? { status: 202, body: { received: true } }
|
|
106
|
+
: { status: 202, body: { merchantIds: [...probe.merchantIds] } };
|
|
107
|
+
}
|
|
108
|
+
|
|
96
109
|
/** Record and act on a delivery whose store and signature are proven. */
|
|
97
110
|
async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted): Promise<WireResponse> {
|
|
98
111
|
const { clientId, provider, payload, target } = admitted;
|
|
99
112
|
const { engine } = config;
|
|
113
|
+
const probe = engine.presence(provider, payload);
|
|
114
|
+
if (probe) return presenceAnswer(probe);
|
|
115
|
+
const status = engine.answerStatus(provider);
|
|
100
116
|
|
|
101
117
|
const event = engine.normalize(provider, payload);
|
|
102
118
|
if (!event) {
|
|
103
|
-
// Nothing the adapter can key on.
|
|
119
|
+
// Nothing the adapter can key on. 2xx: redelivering an unreadable payload
|
|
104
120
|
// produces an identical unreadable payload.
|
|
105
121
|
config.logger.warn(`marketplace.webhook: ${provider} payload did not normalize`);
|
|
106
|
-
return { status
|
|
122
|
+
return { status, body: { received: true, ignored: "unrecognized_payload" } };
|
|
107
123
|
}
|
|
108
124
|
const outcome = await engine.deliver({
|
|
109
125
|
clientId,
|
|
@@ -118,7 +134,8 @@ async function deliverAdmitted(config: MarketplaceApiConfig, admitted: Admitted)
|
|
|
118
134
|
if (outcome.kind === "failed") {
|
|
119
135
|
return { status: 500, body: { received: true, error: outcome.reason } };
|
|
120
136
|
}
|
|
121
|
-
|
|
137
|
+
// After the inbox row is written: iFood's 202 means "recorded" (FUT-5984).
|
|
138
|
+
return { status, body: { received: true, outcome: outcome.kind } };
|
|
122
139
|
}
|
|
123
140
|
|
|
124
141
|
/**
|
|
@@ -138,6 +155,12 @@ async function admitApp(
|
|
|
138
155
|
const rawBody = await raw.text();
|
|
139
156
|
const payload = parsedJson(rawBody);
|
|
140
157
|
if (payload === undefined) return { status: 400, body: { error: "invalid_json" } };
|
|
158
|
+
// A presence heartbeat names no store: proved by the app's own key, with no statement (FUT-5984).
|
|
159
|
+
const probe = config.engine.presence(provider, payload);
|
|
160
|
+
if (probe) {
|
|
161
|
+
const signature = config.engine.readSignature(provider, (name) => raw.headers.get(name));
|
|
162
|
+
return (await config.engine.signedByApp(provider, rawBody, signature)) ? presenceAnswer(probe) : UNAUTHORIZED;
|
|
163
|
+
}
|
|
141
164
|
const found = await appConnection(config, provider, payload);
|
|
142
165
|
if ("status" in found) return found;
|
|
143
166
|
// The app's address never takes an unsigned delivery, whatever the store's own setting.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { MarketplaceCatalogue } from \"./catalogue-port\";\nimport type { MarketplaceCourierApi } from \"./courier-port\";\nimport type { CatalogueReader } from \"./catalogue-read-port\";\nimport type { MarketplaceLinking } from \"./linking-port\";\nimport type { MarketplaceAvailability } from \"./pause-port\";\nimport type {\n MarketplaceDeliveredBy,\n MarketplaceProvider,\n NormalizedEvent,\n NormalizedMarketplaceOrder,\n} from \"./types\";\n\n/**\n * The adapter port: everything one marketplace is, behind one shape.\n *\n * The owner's rule, which this file exists to make true: \"the integration\n * engine must be the same for all integrations: iFood, Rappi, 99. Only an\n * adapter is made for each one, to connect to the base engine.\"\n *\n * A marketplace differs from the next in five ways that matter to a store:\n * how its deliveries look and are signed (`normalize`, `readSignature`,\n * `verifySignature`), what it lets a store answer through its API (`confirm`,\n * `requestCancellation`), which reasons a refusal may carry\n * (`cancellationReasons`), and where a person goes when the API cannot do it\n * (`appLink`). Everything else — the inbox, the clock, the SKU map, the\n * outbound bookkeeping and its retries — is the engine's and does not change\n * with the marketplace.\n *\n * What a marketplace CAN do is stated by its adapter as\n * {@link MarketplaceCapabilities} and read by the engine and the host. It is\n * never inferred from the provider's id: a branch on the id outside an adapter\n * would make the next marketplace a code change instead of an adapter.\n *\n * The HTTP client is a host port ({@link MarketplaceHttp}), handed to every\n * outbound call. An adapter never reaches the network on its own, so tests\n * answer the seam and nothing else, and the host owns the timeout, the proxy\n * and the CA.\n */\n\n/** A marketplace's credentials, as the merchant supplies them. Sealed at rest. */\nexport interface MarketplaceCredentials {\n clientId: string;\n clientSecret: string;\n /**\n * The shared secret a delivery's signature is verified against. Separate\n * from the OAuth pair: a merchant rotating their webhook secret has not\n * re-onboarded.\n */\n webhookSecret: string | null;\n}\n\n/** What the host's HTTP client takes. */\nexport interface MarketplaceHttpRequest {\n /**\n * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.\n * `DELETE` since FUT-4851: iFood removes an interruption with it.\n */\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n url: string;\n headers: Record<string, string>;\n body?: string;\n}\n\n/** What the host's HTTP client answers: any status, never a throw for a 4xx or 5xx. */\nexport interface MarketplaceHttpResponse {\n status: number;\n body: string;\n}\n\n/** The host's HTTP client. It throws only when no answer arrived (a timeout, a network error). */\nexport type MarketplaceHttp = (request: MarketplaceHttpRequest) => Promise<MarketplaceHttpResponse>;\n\n/** What a marketplace can do, stated by its adapter. */\nexport interface MarketplaceCapabilities {\n /** Accepting is answered through the API. */\n apiConfirm: boolean;\n /** A cancellation can be requested through the API at all. */\n apiCancel: boolean;\n /** …and still once the order was accepted. */\n cancelAfterAccept: boolean;\n /** The cancellation's outcome arrives later as an event rather than in the answer. */\n asyncCancellationOutcome: boolean;\n /** `appLink` names this order, rather than only the marketplace's portal. */\n perOrderAppLink: boolean;\n /** Confirming states a preparation time. */\n confirmTakesPreparationTime: boolean;\n /**\n * OPTIONAL. How long the marketplace takes, at most, to answer a store's\n * cancellation request, in milliseconds: past it the outbound sweep fails\n * the request as TIMEOUT. Absent: only the 24-hour give-up applies.\n */\n cancellationAnswerWindowMs?: number;\n /**\n * OPTIONAL. The steps this marketplace can be told about (`informStatus`).\n * Absent or empty: the engine tells it nothing.\n */\n statusSteps?: readonly StatusStep[];\n}\n\n/**\n * A step of the order the store tells the marketplace about (FUT-4653): the\n * order is ready for pickup, the courier left, the order was handed over.\n */\nexport type StatusStep = \"READY\" | \"DISPATCHED\" | \"HANDED_OVER\";\n\n/** What a status call is told about the order: who carries it (null: a take-out, or unstated). */\nexport interface StatusFacts {\n step: StatusStep;\n deliveredBy: MarketplaceDeliveredBy | null;\n}\n\n/** One reason a store may give for refusing or cancelling an order. */\nexport interface CancellationReason {\n /** The marketplace's own code, sent verbatim. */\n code: string;\n /** The label the host was configured with for this code (a named pack). */\n label: string;\n /** This reason means \"an item is unavailable\": the host preselects it when stock is short. */\n itemUnavailable: boolean;\n /** The marketplace requires the offending SKUs with this reason. */\n needsItems: boolean;\n}\n\n/** The order an outbound call is about, as the engine knows it. */\nexport interface OutboundOrderRef {\n externalOrderId: string;\n externalDisplayId: string | null;\n /** The host's own id for the order. */\n hostOrderCode: string;\n /** When the engine recorded the order. */\n placedAt: Date;\n}\n\n/** A per-engine token cache an adapter reads and fills. Never persisted. */\nexport type AdapterTokenCache = Map<string, { token: string; expiresAt: number }>;\n\n/**\n * A connection LINKED through the software's own app (FUT-5613): the store's\n * access token comes from its refresh token, not from a client-credentials\n * grant. `key` is where the token sits in {@link AdapterTokenCache} (delete it\n * to forget a token the marketplace refused); `accessToken` answers the cached\n * one or refreshes, once per connection however many calls ask at once.\n */\nexport interface AdapterGrant {\n key: string;\n accessToken(): Promise<{ token: string } | OutboundResult>;\n}\n\n/** What one outbound call is handed. */\nexport interface AdapterCallContext {\n http: MarketplaceHttp;\n /** The store's own credentials, or, for a linked connection, the software's app. */\n credentials: MarketplaceCredentials;\n environment: \"SANDBOX\" | \"PRODUCTION\";\n /** Written to no row, log or audit entry: memory only, per process. */\n tokens: AdapterTokenCache;\n now: Date;\n /** Present for a linked connection: the token comes from here, never from a client-credentials grant. */\n grant?: AdapterGrant;\n}\n\n/** One outbound call's answer, in the three shapes the engine acts on. */\nexport type OutboundResult =\n /** 2xx. For a marketplace whose outcome is asynchronous, \"the request was taken\". */\n | { kind: \"accepted\" }\n /**\n * A final 4xx (not 408/425/429): never retried. `own` marks a refusal that\n * is not the marketplace's judgement of the order: our credentials were not\n * accepted, or our request was malformed. A cancellation request that ends\n * so fails as UNREACHABLE, not REFUSED.\n */\n | { kind: \"refused\"; status: number; message: string; own?: true }\n /** 408, 425, 429, 5xx, a timeout, a network error: retried until the last attempt. */\n | { kind: \"retry\"; reason: string };\n\n/**\n * One order-body fetch's answer: the order, normalized, or the same refusal and\n * retry shapes an outbound call answers with (a 404 for an expired order is a\n * refusal; a 5xx, a timeout or a 429 is a retry).\n */\nexport type FetchOrderResult =\n | { kind: \"order\"; order: NormalizedMarketplaceOrder }\n | Exclude<OutboundResult, { kind: \"accepted\" }>;\n\n/** What a cancellation request carries. */\nexport interface CancellationRequestInput {\n reason: CancellationReason;\n /** Free text from the store; empty means \"the reason's own label\". */\n text: string;\n mode: \"MANUAL\" | \"AUTO\";\n offendingSkus: readonly string[];\n}\n\n/** One marketplace, in and out. */\nexport interface MarketplaceAdapter {\n readonly provider: MarketplaceProvider;\n readonly capabilities: MarketplaceCapabilities;\n /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */\n normalize(payload: unknown): NormalizedEvent | null;\n /** Which header carries this marketplace's signature, read off the request. */\n readSignature(header: (name: string) => string | null): string | null;\n /** Is this delivery's signature the one this store's secret would produce? */\n verifySignature(rawBody: string, signature: string | null, secret: string | null): boolean;\n /** The marketplace's documented reasons, static and offline: a dialog never waits on the network. */\n cancellationReasons(): readonly CancellationReason[];\n /** Tell the marketplace the store accepted the order. */\n confirm(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: { preparationMinutes: number | null },\n ): Promise<OutboundResult>;\n /** Ask the marketplace to cancel the order, with one of its own reasons. */\n requestCancellation(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n input: CancellationRequestInput,\n ): Promise<OutboundResult>;\n /**\n * OPTIONAL. Whether this marketplace takes this step for this kind of order,\n * answered offline, with no call: the job asks it BEFORE it claims anything\n * (an unsupported step leaves no row). Absent: every step in\n * `capabilities.statusSteps` is taken for every order.\n */\n statusSupported?(facts: StatusFacts): boolean;\n /**\n * OPTIONAL. Tell the marketplace the order reached a step (FUT-4653). Called\n * only from the `marketplace.outbound` job, action `status`. `unsupported`\n * (no endpoint for this step and this kind of order) ends the job with no\n * row. Absent: the marketplace is told nothing.\n */\n informStatus?(\n ctx: AdapterCallContext,\n order: OutboundOrderRef,\n facts: StatusFacts,\n ): Promise<OutboundResult | { kind: \"unsupported\" }>;\n /**\n * OPTIONAL. Fetch the order an event announced with `orderToFetch` (a\n * marketplace whose events carry no order body). Called only from the\n * `marketplace.fetch-order` job. An adapter whose events always carry the\n * order leaves it out. A final `refused` marked `own` with a 4xx status is\n * our credentials refused: the engine stamps the connection FAILED.\n */\n fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;\n /**\n * OPTIONAL. Publishing the store's products to this marketplace's catalogue\n * (FUT-4768): `push` (the adapter writes each item) or `pull` (the\n * marketplace reads a menu document the host serves). Absent: the\n * marketplace cannot be published to, and the host says so.\n */\n readonly catalogue?: MarketplaceCatalogue;\n /**\n * OPTIONAL. Reading the menu the store already keeps on this marketplace,\n * through its own connection, for the host to import (FUT-951). Absent: the\n * menu cannot be read through an API, and the host says so.\n */\n readonly catalogueReader?: CatalogueReader;\n /**\n * OPTIONAL. Closing the store on this marketplace for a while, and opening\n * it again (FUT-4851). Absent: the marketplace cannot be paused through an\n * API, and the host says so.\n */\n readonly availability?: MarketplaceAvailability;\n /**\n * OPTIONAL. Linking a store through the software's own app on this\n * marketplace (FUT-5613). Absent: a store connects with its own credentials only.\n */\n readonly linking?: MarketplaceLinking;\n /**\n * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check\n * and the tracking read. Absent: neither is offered, and the host says so.\n */\n readonly courier?: MarketplaceCourierApi;\n /** Where \"open it on the marketplace\" goes: the order when `perOrderAppLink`, else the portal. Always https. */\n appLink(order: Pick<OutboundOrderRef, \"externalOrderId\" | \"externalDisplayId\">): string;\n}\n\n/**\n * The 4xx statuses that are NOT a refusal: a request timeout (408), \"too\n * early\" (425) and a rate limit (429) say \"ask again later\" by HTTP's own\n * semantics, and a marketplace rate-limits its merchant API.\n */\nconst TRANSIENT_CLIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * Read one HTTP answer the way the engine acts on it. Shared by every adapter\n * whose API speaks plain status codes, so the rule is one rule rather than one\n * per marketplace: 2xx accepted; a 4xx other than 408/425/429 refused and\n * final; everything else (408, 425, 429, 5xx, anything unexpected) retried.\n */\nexport function outboundResultOf(response: MarketplaceHttpResponse): OutboundResult {\n if (response.status >= 200 && response.status < 300) return { kind: \"accepted\" };\n const message = response.body.slice(0, 300);\n const refusal = response.status >= 400 && response.status < 500 && !TRANSIENT_CLIENT_STATUSES.has(response.status);\n if (refusal) return { kind: \"refused\", status: response.status, message };\n return { kind: \"retry\", reason: `status ${response.status}: ${message}` };\n}\n\n/**\n * {@link outboundResultOf} for a token grant: a final 4xx there says our\n * credentials were not accepted, never a judgement of any order, so it is an\n * `own` refusal.\n */\nexport function tokenGrantResultOf(response: MarketplaceHttpResponse): OutboundResult {\n const result = outboundResultOf(response);\n return result.kind === \"refused\" ? { ...result, own: true } : result;\n}\n\n/** A call that never got an answer is a retry, with the reason a log can read. */\nexport async function answered(call: () => Promise<OutboundResult>): Promise<OutboundResult> {\n try {\n return await call();\n } catch (error) {\n return { kind: \"retry\", reason: error instanceof Error ? error.message : String(error) };\n }\n}\n"],"mappings":";;;;;AAyRA,IAAM,4BAA4B,oBAAI,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAQlD,SAAS,iBAAiB,UAAmD;AAClF,MAAI,SAAS,UAAU,OAAO,SAAS,SAAS,IAAK,QAAO,EAAE,MAAM,WAAW;AAC/E,QAAM,UAAU,SAAS,KAAK,MAAM,GAAG,GAAG;AAC1C,QAAM,UAAU,SAAS,UAAU,OAAO,SAAS,SAAS,OAAO,CAAC,0BAA0B,IAAI,SAAS,MAAM;AACjH,MAAI,QAAS,QAAO,EAAE,MAAM,WAAW,QAAQ,SAAS,QAAQ,QAAQ;AACxE,SAAO,EAAE,MAAM,SAAS,QAAQ,UAAU,SAAS,MAAM,KAAK,OAAO,GAAG;AAC1E;AANgB;AAaT,SAAS,mBAAmB,UAAmD;AACpF,QAAM,SAAS,iBAAiB,QAAQ;AACxC,SAAO,OAAO,SAAS,YAAY,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI;AAChE;AAHgB;AAMhB,eAAsB,SAAS,MAA8D;AAC3F,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,OAAO;AACd,WAAO,EAAE,MAAM,SAAS,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AAAA,EACzF;AACF;AANsB;","names":[]}
|