@12-apps/marketplace 1.1.0 → 1.3.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 +37 -7
- package/README.md +238 -4
- package/dist/99food/en-US.d.ts +19 -0
- package/dist/99food/en-US.js +23 -0
- package/dist/99food/en-US.js.map +1 -0
- package/dist/99food/index.d.ts +162 -0
- package/dist/99food/index.js +444 -0
- package/dist/99food/index.js.map +1 -0
- package/dist/99food/pt-BR.d.ts +23 -0
- package/dist/99food/pt-BR.js +23 -0
- package/dist/99food/pt-BR.js.map +1 -0
- package/dist/{adapter-BggtVFf9.d.ts → adapter-0l_EmuJA.d.ts} +206 -2
- package/dist/{chunk-NGNEL4HS.js → chunk-AYYBRQJV.js} +52 -4
- package/dist/chunk-AYYBRQJV.js.map +1 -0
- package/dist/chunk-BD7DS3XM.js +78 -0
- package/dist/chunk-BD7DS3XM.js.map +1 -0
- package/dist/chunk-M2V4RFMA.js +23 -0
- package/dist/chunk-M2V4RFMA.js.map +1 -0
- package/dist/{chunk-7BYVGNU5.js → chunk-RVBTARIY.js} +1 -1
- package/dist/chunk-RVBTARIY.js.map +1 -0
- package/dist/chunk-XUAFXNOH.js +1604 -0
- package/dist/chunk-XUAFXNOH.js.map +1 -0
- package/dist/{engine-KrgZ4pA4.d.ts → engine-CZsP8KWd.d.ts} +278 -2
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +16 -12
- package/dist/ifood/index.js +248 -121
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +30 -4
- package/dist/index.js +189 -346
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +4 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/en-US.d.ts +14 -0
- package/dist/rappi/en-US.js +18 -0
- package/dist/rappi/en-US.js.map +1 -0
- package/dist/rappi/index.d.ts +190 -0
- package/dist/rappi/index.js +359 -0
- package/dist/rappi/index.js.map +1 -0
- package/dist/rappi/pt-BR.d.ts +18 -0
- package/dist/rappi/pt-BR.js +18 -0
- package/dist/rappi/pt-BR.js.map +1 -0
- package/dist/server/index.d.ts +19 -8
- package/dist/server/index.js +4 -2
- package/package.json +26 -2
- package/prisma/marketplace.prisma +97 -2
- package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
- package/src/99food/catalogue.ts +117 -0
- package/src/99food/copy.ts +36 -0
- package/src/99food/en-US.ts +19 -0
- package/src/99food/index.ts +125 -0
- package/src/99food/normalize.ts +263 -0
- package/src/99food/outbound.ts +220 -0
- package/src/99food/pt-BR.ts +23 -0
- package/src/core/adapter.ts +27 -2
- package/src/core/catalogue-category.ts +119 -0
- package/src/core/catalogue-ids.ts +23 -0
- package/src/core/catalogue-job.ts +332 -0
- package/src/core/catalogue-port.ts +173 -0
- package/src/core/catalogue-store.ts +172 -0
- package/src/core/catalogue-sweep.ts +43 -0
- package/src/core/catalogue.ts +226 -0
- package/src/core/decisions.ts +16 -4
- package/src/core/engine.ts +54 -0
- package/src/core/fetch-order.ts +253 -0
- package/src/core/inbox.ts +8 -2
- package/src/core/ingest.ts +10 -2
- package/src/core/integration.ts +30 -1
- package/src/core/order-fetch-marks.ts +63 -0
- package/src/core/outbound-sweep.ts +7 -2
- package/src/core/outbound.ts +22 -2
- package/src/core/payload-read.ts +101 -0
- package/src/core/pipeline.ts +64 -15
- package/src/core/ports.ts +36 -0
- package/src/core/types.ts +14 -0
- package/src/ifood/catalogue.ts +273 -0
- package/src/ifood/index.ts +4 -0
- package/src/ifood/normalize.ts +15 -88
- package/src/ifood/outbound.ts +9 -6
- package/src/index.ts +49 -1
- package/src/rappi/copy.ts +39 -0
- package/src/rappi/en-US.ts +14 -0
- package/src/rappi/index.ts +161 -0
- package/src/rappi/normalize.ts +314 -0
- package/src/rappi/outbound.ts +182 -0
- package/src/rappi/pt-BR.ts +18 -0
- package/src/server/index.ts +1 -0
- package/src/server/jobs.ts +71 -8
- package/dist/chunk-7BYVGNU5.js.map +0 -1
- package/dist/chunk-DVIRN42O.js +0 -707
- package/dist/chunk-DVIRN42O.js.map +0 -1
- package/dist/chunk-NGNEL4HS.js.map +0 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The defensive readers every adapter's normalizer is built from.
|
|
5
|
+
*
|
|
6
|
+
* A marketplace payload is UNTRUSTED: a documented shape and the shape that
|
|
7
|
+
* actually arrives drift, and a `TypeError` reading a missing field would
|
|
8
|
+
* reject a paid order at the door. Every reader here produces a value or
|
|
9
|
+
* null, never a throw. They are wire-format-neutral (no marketplace's key
|
|
10
|
+
* names), which is why they live beside the engine rather than in an adapter.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Read a nested value without asserting the shape of anything on the way. */
|
|
14
|
+
export function pick(source: unknown, ...path: string[]): unknown {
|
|
15
|
+
let cursor: unknown = source;
|
|
16
|
+
for (const key of path) {
|
|
17
|
+
if (typeof cursor !== "object" || cursor === null) return undefined;
|
|
18
|
+
cursor = (cursor as Record<string, unknown>)[key];
|
|
19
|
+
}
|
|
20
|
+
return cursor;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A non-blank string (trimmed), a finite number as text, or null. */
|
|
24
|
+
export function asString(value: unknown): string | null {
|
|
25
|
+
if (typeof value === "string" && value.trim() !== "") return value.trim();
|
|
26
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The first of several candidate paths that yields a string.
|
|
32
|
+
*
|
|
33
|
+
* A marketplace states the same fact under different keys depending on which
|
|
34
|
+
* API version delivered it, so nearly every read is a fallback chain. Expressed
|
|
35
|
+
* as data rather than as `??` so a chain grows by one entry, not one branch.
|
|
36
|
+
*/
|
|
37
|
+
export function firstString(source: unknown, paths: string[][]): string | null {
|
|
38
|
+
for (const path of paths) {
|
|
39
|
+
const found = asString(pick(source, ...path));
|
|
40
|
+
if (found !== null) return found;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Money stated in DECIMAL units (`12.9`) → integer cents.
|
|
47
|
+
*
|
|
48
|
+
* Rounded rather than truncated: `Math.trunc(12.9 * 100)` is 1289 on IEEE-754,
|
|
49
|
+
* so truncation loses a cent on ordinary prices, always in the store's
|
|
50
|
+
* disfavour.
|
|
51
|
+
*/
|
|
52
|
+
export function toCents(value: unknown): number | null {
|
|
53
|
+
const numeric = typeof value === "string" ? Number(value) : value;
|
|
54
|
+
if (typeof numeric !== "number" || !Number.isFinite(numeric)) return null;
|
|
55
|
+
return Math.round(numeric * 100);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** {@link firstString} for money. */
|
|
59
|
+
export function firstCents(source: unknown, paths: string[][]): number | null {
|
|
60
|
+
for (const path of paths) {
|
|
61
|
+
const found = toCents(pick(source, ...path));
|
|
62
|
+
if (found !== null) return found;
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** An ISO timestamp → a Date, or null when absent or unparseable. */
|
|
68
|
+
function toDate(value: unknown): Date | null {
|
|
69
|
+
const raw = asString(value);
|
|
70
|
+
if (!raw) return null;
|
|
71
|
+
const parsed = new Date(raw);
|
|
72
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** {@link firstString} for timestamps. */
|
|
76
|
+
export function firstDate(source: unknown, paths: string[][]): Date | null {
|
|
77
|
+
for (const path of paths) {
|
|
78
|
+
const found = toDate(pick(source, ...path));
|
|
79
|
+
if (found !== null) return found;
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Verify a lowercase-hex HMAC-SHA256 of the raw body (an optional `sha256=`
|
|
86
|
+
* prefix tolerated), keyed by `secret`.
|
|
87
|
+
*
|
|
88
|
+
* Unsigned deliveries are refused whenever a secret is CONFIGURED; a store
|
|
89
|
+
* that has not set one yet is accepted, and that state is visible on the
|
|
90
|
+
* connection screen rather than silent. Compared in constant time over bytes:
|
|
91
|
+
* an early-exit `===` on a hex digest leaks the prefix a forger already got
|
|
92
|
+
* right, one request at a time.
|
|
93
|
+
*/
|
|
94
|
+
export function verifyHmacSha256Hex(rawBody: string, signature: string | null, secret: string | null): boolean {
|
|
95
|
+
if (!secret) return true;
|
|
96
|
+
if (!signature) return false;
|
|
97
|
+
const expected = createHmac("sha256", secret).update(rawBody, "utf8").digest("hex");
|
|
98
|
+
const given = Buffer.from(signature.trim().toLowerCase().replace(/^sha256=/u, ""), "utf8");
|
|
99
|
+
const mine = Buffer.from(expected, "utf8");
|
|
100
|
+
return given.length === mine.length && timingSafeEqual(given, mine);
|
|
101
|
+
}
|
package/src/core/pipeline.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { cancelAcceptance } from "./acceptance";
|
|
2
2
|
import { failCancellationRequest } from "./cancellation";
|
|
3
|
+
import { awaitOrderBody, merchantMismatch, requeueOwedFetch } from "./fetch-order";
|
|
3
4
|
import { deferInboxEvent, recordInboxEvent, settleInboxEvent } from "./inbox";
|
|
4
5
|
import { ingestMarketplaceOrder, type IngestSettings } from "./ingest";
|
|
5
|
-
import { resolveIngestionTarget } from "./integration";
|
|
6
|
+
import { connectionMerchantId, resolveIngestionTarget } from "./integration";
|
|
7
|
+
import { markCancelledBeforeIngest } from "./order-fetch-marks";
|
|
6
8
|
import type { EngineContext } from "./ports";
|
|
7
|
-
import type { MarketplaceProvider, NormalizedEvent } from "./types";
|
|
9
|
+
import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
8
10
|
|
|
9
11
|
/**
|
|
10
12
|
* One delivery, start to finish: normalize → inbox → ingest.
|
|
@@ -34,6 +36,8 @@ export type DeliveryOutcome =
|
|
|
34
36
|
| { kind: "ingested"; orderId: string; unmappedSkus: string[] }
|
|
35
37
|
| { kind: "cancelled" }
|
|
36
38
|
| { kind: "cancellationFailed" }
|
|
39
|
+
/** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
|
|
40
|
+
| { kind: "awaitingOrder" }
|
|
37
41
|
| { kind: "duplicate" }
|
|
38
42
|
| { kind: "ignored"; reason: string }
|
|
39
43
|
| { kind: "failed"; reason: string };
|
|
@@ -88,6 +92,28 @@ export async function processDelivery(
|
|
|
88
92
|
}
|
|
89
93
|
}
|
|
90
94
|
|
|
95
|
+
/** The event names an order whose body the marketplace serves apart (`orderToFetch`). */
|
|
96
|
+
function announcesOrderToFetch(event: NormalizedEvent): boolean {
|
|
97
|
+
return event.order === null && event.orderToFetch === true && event.externalOrderId !== null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Why an order the event CARRIES must not be ingested for this store: it names
|
|
102
|
+
* another merchant than the connection's (a wrong webhook URL, a replay), the
|
|
103
|
+
* rule a fetched order is held to. Read only for an order that names its
|
|
104
|
+
* merchant (an adapter that sets `externalMerchantId` on the order); an order
|
|
105
|
+
* that names none costs no read.
|
|
106
|
+
*/
|
|
107
|
+
async function carriedOrderMismatch(
|
|
108
|
+
ctx: EngineContext,
|
|
109
|
+
clientId: string,
|
|
110
|
+
order: NormalizedMarketplaceOrder,
|
|
111
|
+
): Promise<string | null> {
|
|
112
|
+
if (!order.externalMerchantId) return null;
|
|
113
|
+
// The one column, never the whole target: no credentials opened per order.
|
|
114
|
+
return merchantMismatch(order, await connectionMerchantId(ctx, clientId, order.provider));
|
|
115
|
+
}
|
|
116
|
+
|
|
91
117
|
/**
|
|
92
118
|
* Act on one recorded delivery: cancel, ingest, or deliberately nothing.
|
|
93
119
|
*
|
|
@@ -118,16 +144,22 @@ async function applyEvent(
|
|
|
118
144
|
}
|
|
119
145
|
|
|
120
146
|
if (event.cancelled && event.externalOrderId) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
now,
|
|
126
|
-
});
|
|
147
|
+
const order = { clientId, provider: event.provider, externalOrderId: event.externalOrderId };
|
|
148
|
+
// A cancellation that outran a fetched order's body leaves its marker, so
|
|
149
|
+
// the fetch that follows ingests nothing.
|
|
150
|
+
if (!(await cancelAcceptance(ctx, { ...order, now }))) await markCancelledBeforeIngest(ctx, order);
|
|
127
151
|
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
128
152
|
return { kind: "cancelled" };
|
|
129
153
|
}
|
|
130
154
|
|
|
155
|
+
if (announcesOrderToFetch(event)) {
|
|
156
|
+
// The event announces an order whose body the marketplace serves apart.
|
|
157
|
+
// Fetching is a call to the marketplace, so it is a job's, never this
|
|
158
|
+
// request's: the row waits PENDING and the fetch is queued.
|
|
159
|
+
await awaitOrderBody(ctx, clientId, inboxId);
|
|
160
|
+
return { kind: "awaitingOrder" };
|
|
161
|
+
}
|
|
162
|
+
|
|
131
163
|
if (!event.order) {
|
|
132
164
|
// An event type this ingestion does not act on. Marketplaces emit a wide
|
|
133
165
|
// stream (dispatched, concluded, driver assigned…) and most of it is not an
|
|
@@ -138,12 +170,27 @@ async function applyEvent(
|
|
|
138
170
|
return { kind: "ignored", reason };
|
|
139
171
|
}
|
|
140
172
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
173
|
+
return ingestCarried(ctx, inboxId, clientId, event.order, settings, now);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Ingest the order an event carries, unless it names another merchant than the connection's. */
|
|
177
|
+
async function ingestCarried(
|
|
178
|
+
ctx: EngineContext,
|
|
179
|
+
inboxId: string,
|
|
180
|
+
clientId: string,
|
|
181
|
+
order: NormalizedMarketplaceOrder,
|
|
182
|
+
settings: IngestSettings,
|
|
183
|
+
now: Date | undefined,
|
|
184
|
+
): Promise<DeliveryOutcome> {
|
|
185
|
+
const mismatch = await carriedOrderMismatch(ctx, clientId, order);
|
|
186
|
+
if (mismatch) {
|
|
187
|
+
// FAILED, so the reconciliation sweep retries it once the connection's
|
|
188
|
+
// merchant id is corrected, within the inbox's attempt bound.
|
|
189
|
+
await settleInboxEvent(ctx, inboxId, "FAILED", mismatch);
|
|
190
|
+
ctx.ports.logger.error(`marketplace.ingest: inbox row ${inboxId} refused: ${mismatch}`);
|
|
191
|
+
return { kind: "failed", reason: mismatch };
|
|
192
|
+
}
|
|
193
|
+
const result = await ingestMarketplaceOrder(ctx, { clientId, order, settings, now });
|
|
147
194
|
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
148
195
|
return { kind: "ingested", orderId: result.orderId, unmappedSkus: result.unmappedSkus };
|
|
149
196
|
}
|
|
@@ -158,7 +205,7 @@ async function applyEvent(
|
|
|
158
205
|
*/
|
|
159
206
|
export async function reprocessStoredDelivery(
|
|
160
207
|
ctx: EngineContext,
|
|
161
|
-
input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown },
|
|
208
|
+
input: { id: string; clientId: string; provider: MarketplaceProvider; payload: unknown; receivedAt?: Date | null },
|
|
162
209
|
): Promise<DeliveryOutcome> {
|
|
163
210
|
const event = normalizeEvent(ctx, input.provider, input.payload);
|
|
164
211
|
if (!event) {
|
|
@@ -176,6 +223,8 @@ export async function reprocessStoredDelivery(
|
|
|
176
223
|
await deferInboxEvent(ctx, input.id, reason);
|
|
177
224
|
return { kind: "ignored", reason };
|
|
178
225
|
}
|
|
226
|
+
// A row waiting for its order body is the fetch job's: re-queued, never fetched here.
|
|
227
|
+
if (announcesOrderToFetch(event)) return requeueOwedFetch(ctx, input);
|
|
179
228
|
try {
|
|
180
229
|
return await applyEvent(
|
|
181
230
|
ctx,
|
package/src/core/ports.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AdapterRegistry } from "./registry";
|
|
2
2
|
import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp } from "./adapter";
|
|
3
|
+
import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
|
|
3
4
|
import type { NormalizedMarketplaceOrder } from "./types";
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -52,6 +53,23 @@ export interface MarketplaceDb {
|
|
|
52
53
|
create(args: unknown): Promise<unknown>;
|
|
53
54
|
updateMany(args: unknown): Promise<{ count: number }>;
|
|
54
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* OPTIONAL in the type, so a host on 1.x that has not yet composed the
|
|
58
|
+
* catalogue model still compiles; the catalogue calls refuse without it
|
|
59
|
+
* (FUT-4768, migration `20261113120000_marketplace_catalogue`).
|
|
60
|
+
*/
|
|
61
|
+
marketplaceCataloguePublication?: {
|
|
62
|
+
findFirst(args: unknown): Promise<unknown>;
|
|
63
|
+
findMany(args: unknown): Promise<unknown[]>;
|
|
64
|
+
upsert(args: unknown): Promise<unknown>;
|
|
65
|
+
updateMany(args: unknown): Promise<{ count: number }>;
|
|
66
|
+
};
|
|
67
|
+
/** OPTIONAL, as above: the marketplace's category ids, found or created once per name. */
|
|
68
|
+
marketplaceCatalogueCategory?: {
|
|
69
|
+
findFirst(args: unknown): Promise<unknown>;
|
|
70
|
+
create(args: unknown): Promise<unknown>;
|
|
71
|
+
updateMany(args: unknown): Promise<{ count: number }>;
|
|
72
|
+
};
|
|
55
73
|
}
|
|
56
74
|
|
|
57
75
|
/**
|
|
@@ -239,6 +257,19 @@ export interface MarketplaceLogger {
|
|
|
239
257
|
error(message: string, ...meta: unknown[]): void;
|
|
240
258
|
}
|
|
241
259
|
|
|
260
|
+
/**
|
|
261
|
+
* The host's catalogue, as the catalogue publishing reads it (FUT-4768). The
|
|
262
|
+
* engine never reads a host table: the host maps its product into the item
|
|
263
|
+
* shape, at the moment the job sends it, so what goes out is the product as it
|
|
264
|
+
* is now rather than as it was when the switch was turned on.
|
|
265
|
+
*/
|
|
266
|
+
export interface MarketplaceCataloguePort {
|
|
267
|
+
/** These products as they go out, keyed by product id. Missing ids are products that no longer exist. */
|
|
268
|
+
items(clientId: string, productIds: readonly string[]): Promise<Map<string, CatalogueItem>>;
|
|
269
|
+
/** The bytes behind an item's photo, for a marketplace that takes an upload; null when they cannot be read. */
|
|
270
|
+
image(url: string): Promise<CatalogueImage | null>;
|
|
271
|
+
}
|
|
272
|
+
|
|
242
273
|
/** Everything the host plugs in. */
|
|
243
274
|
export interface MarketplacePorts {
|
|
244
275
|
db: () => Promise<MarketplaceDb>;
|
|
@@ -270,6 +301,11 @@ export interface MarketplacePorts {
|
|
|
270
301
|
* only given up on after `OUTBOUND_GIVE_UP_MS`.
|
|
271
302
|
*/
|
|
272
303
|
cancellationWindowMs?: number;
|
|
304
|
+
/**
|
|
305
|
+
* OPTIONAL. The host's catalogue, for publishing products to a marketplace's
|
|
306
|
+
* catalogue. Absent: every catalogue call answers `UNSUPPORTED`.
|
|
307
|
+
*/
|
|
308
|
+
catalogue?: MarketplaceCataloguePort;
|
|
273
309
|
/** The acceptance window a connection gets when it does not state its own. */
|
|
274
310
|
defaultAckSlaSeconds: number;
|
|
275
311
|
/** How many stored deliveries one reconciliation pass re-runs. */
|
package/src/core/types.ts
CHANGED
|
@@ -96,6 +96,12 @@ export interface NormalizedMarketplaceOrder {
|
|
|
96
96
|
deliveredBy?: MarketplaceDeliveredBy | null;
|
|
97
97
|
/** Null on a take-out and when unstated. */
|
|
98
98
|
deliveryAddress?: NormalizedAddress | null;
|
|
99
|
+
/**
|
|
100
|
+
* OPTIONAL. The merchant the order names, when its body says (Open
|
|
101
|
+
* Delivery's `merchant.id`). A fetched order naming another merchant than
|
|
102
|
+
* the connection's is refused.
|
|
103
|
+
*/
|
|
104
|
+
externalMerchantId?: string | null;
|
|
99
105
|
}
|
|
100
106
|
|
|
101
107
|
/**
|
|
@@ -128,4 +134,12 @@ export interface NormalizedEvent {
|
|
|
128
134
|
* one. A `cancelled: true` event reads as `CONFIRMED` when this is absent.
|
|
129
135
|
*/
|
|
130
136
|
cancellationOutcome?: CancellationOutcome | null;
|
|
137
|
+
/**
|
|
138
|
+
* OPTIONAL. This event announces an order whose body the marketplace serves
|
|
139
|
+
* separately (Open Delivery's `CREATED` carries only the order's id): the
|
|
140
|
+
* engine fetches it through the adapter's `fetchOrder`, in the
|
|
141
|
+
* `marketplace.fetch-order` job, never inside the request that delivered
|
|
142
|
+
* the event. Ignored when `order` is present.
|
|
143
|
+
*/
|
|
144
|
+
orderToFetch?: boolean;
|
|
131
145
|
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import {
|
|
2
|
+
answered,
|
|
3
|
+
outboundResultOf,
|
|
4
|
+
type MarketplaceHttpResponse,
|
|
5
|
+
type OutboundResult,
|
|
6
|
+
} from "../core/adapter";
|
|
7
|
+
import { stableUuid } from "../core/catalogue-ids";
|
|
8
|
+
import type {
|
|
9
|
+
CatalogueCallContext,
|
|
10
|
+
CatalogueImage,
|
|
11
|
+
CatalogueItemOut,
|
|
12
|
+
CatalogueItemRef,
|
|
13
|
+
CataloguePublishResult,
|
|
14
|
+
CatalogueStoredImage,
|
|
15
|
+
CatalogueWarningCode,
|
|
16
|
+
PushCatalogue,
|
|
17
|
+
} from "../core/catalogue-port";
|
|
18
|
+
import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The iFood adapter's CATALOGUE half: iFood's Catalog API v2.0, push (FUT-4768).
|
|
22
|
+
*
|
|
23
|
+
* Read 2026-11-13 from iFood's developer portal (the Catalog module's
|
|
24
|
+
* Introduction, Fundamentals, Endpoints and Errors pages, and the rate-limit
|
|
25
|
+
* page); the package README's "Catalogue publishing" table marks each fact
|
|
26
|
+
* CONFIRMED with its URL or ESTIMATED. What is ESTIMATED here is said beside
|
|
27
|
+
* it, and lives in this file only, so the homologation run corrects one file.
|
|
28
|
+
*
|
|
29
|
+
* One publish is, in order:
|
|
30
|
+
* 1. the category, by name: `GET /categories`, else `POST /categories`
|
|
31
|
+
* (`template: "DEFAULT"`);
|
|
32
|
+
* 2. the photo, when the item has one: the `imagePath` iFood already holds
|
|
33
|
+
* for the same photo URL, else `POST /image/upload` with a base64 data URL
|
|
34
|
+
* of the bytes the host's loader reads, which answers `imagePath`;
|
|
35
|
+
* 3. the item: `PUT /items` with `item`, `products`, `optionGroups`,
|
|
36
|
+
* `options` — idempotent, it replaces the whole item, and the item appears
|
|
37
|
+
* at once (synchronous).
|
|
38
|
+
*
|
|
39
|
+
* iFood wants item and product ids the software generates, UUID v4 (any other
|
|
40
|
+
* shape answers 404), so they are derived from the engine's publication
|
|
41
|
+
* reference: a retried publish names the same item. The item's `externalCode`
|
|
42
|
+
* is the host's product id (unique per merchant).
|
|
43
|
+
*
|
|
44
|
+
* A withdraw pauses the item, `PATCH /items/status` with `UNAVAILABLE`: the
|
|
45
|
+
* Endpoints page lists no item delete, and a paused item is not shown in the
|
|
46
|
+
* app (ESTIMATED that this is what "off" should mean; a re-publish puts it
|
|
47
|
+
* back AVAILABLE with the same id).
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
const catalogUrl = (merchantId: string, path: string): string =>
|
|
51
|
+
`${IFOOD_API}/catalog/v2.0/merchants/${encodeURIComponent(merchantId)}/${path}`;
|
|
52
|
+
|
|
53
|
+
/** The item's and its product's ids, stable per publication. */
|
|
54
|
+
export const ifoodItemId = (ref: string): string => stableUuid(`${ref}:item`);
|
|
55
|
+
export const ifoodProductId = (ref: string): string => stableUuid(`${ref}:product`);
|
|
56
|
+
|
|
57
|
+
type Failure = Exclude<OutboundResult, { kind: "accepted" }>;
|
|
58
|
+
|
|
59
|
+
/** iFood's price object: a decimal of the currency's major unit. */
|
|
60
|
+
const priceOf = (cents: number): { value: number } => ({ value: Math.round(cents) / 100 });
|
|
61
|
+
|
|
62
|
+
/** One authenticated call to the catalogue: the raw answer, or the failure that ends it. */
|
|
63
|
+
async function call(
|
|
64
|
+
ctx: CatalogueCallContext,
|
|
65
|
+
method: "GET" | "POST" | "PUT" | "PATCH",
|
|
66
|
+
path: string,
|
|
67
|
+
body?: unknown,
|
|
68
|
+
): Promise<MarketplaceHttpResponse | Failure> {
|
|
69
|
+
const auth = await bearer(ctx);
|
|
70
|
+
if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
|
|
71
|
+
const response = await ctx.http({
|
|
72
|
+
method,
|
|
73
|
+
url: catalogUrl(ctx.externalMerchantId, path),
|
|
74
|
+
headers: {
|
|
75
|
+
Authorization: `Bearer ${auth.token}`,
|
|
76
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
77
|
+
},
|
|
78
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
79
|
+
});
|
|
80
|
+
if (response.status !== 401) return response;
|
|
81
|
+
ctx.tokens.delete(ifoodTokenKey(ctx));
|
|
82
|
+
return { kind: "retry", reason: "iFood refused the token" };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A non-2xx answer as the failure it is (never `accepted`). */
|
|
86
|
+
function failureOf(response: MarketplaceHttpResponse): Failure {
|
|
87
|
+
const result = outboundResultOf(response);
|
|
88
|
+
return result.kind === "accepted" ? { kind: "retry", reason: "unexpected answer" } : result;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const ok = (response: MarketplaceHttpResponse): boolean => response.status >= 200 && response.status < 300;
|
|
92
|
+
|
|
93
|
+
function parse(body: string): unknown {
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(body) as unknown;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The id of the category named `name`, from a category list. ESTIMATED: the list answers an array of `{ id, name }`. */
|
|
102
|
+
function categoryIdIn(body: string, name: string): string | null {
|
|
103
|
+
const parsed = parse(body);
|
|
104
|
+
if (!Array.isArray(parsed)) return null;
|
|
105
|
+
const wanted = name.trim().toLowerCase();
|
|
106
|
+
const found = parsed.find(
|
|
107
|
+
(entry: unknown) =>
|
|
108
|
+
typeof entry === "object" && entry !== null && String((entry as { name?: unknown }).name ?? "").trim().toLowerCase() === wanted,
|
|
109
|
+
) as { id?: unknown } | undefined;
|
|
110
|
+
return typeof found?.id === "string" ? found.id : null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The category named `name` on iFood, or null; the failure that ended the read otherwise. */
|
|
114
|
+
async function findCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string | null } | Failure> {
|
|
115
|
+
const listed = await call(ctx, "GET", "categories");
|
|
116
|
+
if ("kind" in listed) return listed;
|
|
117
|
+
if (!ok(listed)) return failureOf(listed);
|
|
118
|
+
return { id: categoryIdIn(listed.body, name) };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Find the category by name, else create it, then read the list again and
|
|
123
|
+
* adopt the first of that name: a POST whose answer was lost and was retried
|
|
124
|
+
* is found rather than created twice. The engine runs this once per
|
|
125
|
+
* (connection, name) at a time and stores the id (`ctx.category`).
|
|
126
|
+
*/
|
|
127
|
+
async function findOrCreateCategory(ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> {
|
|
128
|
+
const found = await findCategory(ctx, name);
|
|
129
|
+
if ("kind" in found) return found;
|
|
130
|
+
if (found.id) return { id: found.id };
|
|
131
|
+
const created = await call(ctx, "POST", "categories", { name, status: "AVAILABLE", template: "DEFAULT" });
|
|
132
|
+
if ("kind" in created) return created;
|
|
133
|
+
if (!ok(created)) return failureOf(created);
|
|
134
|
+
const id = (parse(created.body) as { id?: unknown } | null)?.id;
|
|
135
|
+
if (typeof id !== "string") return { kind: "retry", reason: "iFood created the category without an id" };
|
|
136
|
+
// ESTIMATED: the list answers categories in creation order, so the first match is the oldest.
|
|
137
|
+
const again = await findCategory(ctx, name);
|
|
138
|
+
return "id" in again && again.id ? { id: again.id } : { id };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const categoryId = (ctx: CatalogueCallContext, name: string): Promise<{ id: string } | Failure> =>
|
|
142
|
+
ctx.category(name, () => findOrCreateCategory(ctx, name));
|
|
143
|
+
|
|
144
|
+
/** The photo the item goes out with, and what the publish could not do about it. */
|
|
145
|
+
interface PhotoOutcome {
|
|
146
|
+
image: CatalogueStoredImage | null;
|
|
147
|
+
warning?: CatalogueWarningCode;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The photo for this publish, uploading only when it must:
|
|
152
|
+
* - no `imageUrl`: no photo;
|
|
153
|
+
* - the photo iFood already holds was made from this same URL: reuse it;
|
|
154
|
+
* - else upload the bytes the host's loader reads; when it reads nothing,
|
|
155
|
+
* keep the photo iFood holds, if any (PUT replaces the whole item, so
|
|
156
|
+
* sending none would drop it);
|
|
157
|
+
* - an upload iFood refuses (413 over 5 MB, another final 4xx) publishes
|
|
158
|
+
* without a photo and says why as a warning, rather than failing the item.
|
|
159
|
+
*/
|
|
160
|
+
async function photoFor(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<PhotoOutcome | Failure> {
|
|
161
|
+
const stored = item.storedImage;
|
|
162
|
+
if (item.imageUrl === null) return { image: null };
|
|
163
|
+
if (stored && stored.sourceUrl === item.imageUrl) return { image: stored };
|
|
164
|
+
const bytes = await ctx.loadImage(item.imageUrl);
|
|
165
|
+
return bytes ? upload(ctx, bytes, item.imageUrl) : { image: stored };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `POST /image/upload`: the new photo, a warning for a refused one, or the failure to retry. */
|
|
169
|
+
async function upload(ctx: CatalogueCallContext, bytes: CatalogueImage, sourceUrl: string): Promise<PhotoOutcome | Failure> {
|
|
170
|
+
const uploaded = await call(ctx, "POST", "image/upload", { image: `data:${bytes.contentType};base64,${bytes.base64}` });
|
|
171
|
+
if ("kind" in uploaded) return uploaded;
|
|
172
|
+
if (!ok(uploaded)) {
|
|
173
|
+
const failure = failureOf(uploaded);
|
|
174
|
+
if (failure.kind === "retry") return failure;
|
|
175
|
+
return { image: null, warning: uploaded.status === 413 ? "IMAGE_TOO_LARGE" : "IMAGE_REFUSED" };
|
|
176
|
+
}
|
|
177
|
+
const path = (parse(uploaded.body) as { imagePath?: unknown } | null)?.imagePath;
|
|
178
|
+
if (typeof path !== "string") return { kind: "retry", reason: "iFood answered the upload without an imagePath" };
|
|
179
|
+
return { image: { ref: path, sourceUrl } };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The `PUT /items` body for one simple item with no add-ons. */
|
|
183
|
+
export function ifoodItemBody(item: CatalogueItemOut, category: string, image: string | null): unknown {
|
|
184
|
+
const itemId = ifoodItemId(item.ref);
|
|
185
|
+
const productId = ifoodProductId(item.ref);
|
|
186
|
+
return {
|
|
187
|
+
item: {
|
|
188
|
+
id: itemId,
|
|
189
|
+
type: "DEFAULT",
|
|
190
|
+
categoryId: category,
|
|
191
|
+
status: "AVAILABLE",
|
|
192
|
+
price: priceOf(item.priceCents),
|
|
193
|
+
externalCode: item.productId,
|
|
194
|
+
// ESTIMATED: the guide's examples link item and product implicitly; the
|
|
195
|
+
// field naming the product is not shown on the pages read.
|
|
196
|
+
productId,
|
|
197
|
+
},
|
|
198
|
+
products: [
|
|
199
|
+
{
|
|
200
|
+
id: productId,
|
|
201
|
+
name: item.name,
|
|
202
|
+
description: item.description ?? "",
|
|
203
|
+
externalCode: `${item.productId}-product`,
|
|
204
|
+
// ESTIMATED field name: the Errors page names `imagePath` as what the upload returns and the item carries.
|
|
205
|
+
...(image === null ? {} : { imagePath: image }),
|
|
206
|
+
},
|
|
207
|
+
],
|
|
208
|
+
optionGroups: [],
|
|
209
|
+
options: [],
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Whether a refused PUT was refused because the stored category is gone (the
|
|
215
|
+
* store deleted it on iFood's portal): iFood's 400 and 404 do not say which id
|
|
216
|
+
* was unknown, so the list is read again, and a category of that name with
|
|
217
|
+
* another id, or none at all, means the stored one is stale. ESTIMATED that a
|
|
218
|
+
* deleted category answers 400 or 404.
|
|
219
|
+
*/
|
|
220
|
+
async function categoryWentStale(ctx: CatalogueCallContext, put: MarketplaceHttpResponse, name: string, used: string): Promise<boolean> {
|
|
221
|
+
if (put.status !== 400 && put.status !== 404) return false;
|
|
222
|
+
const found = await findCategory(ctx, name);
|
|
223
|
+
return !("kind" in found) && found.id !== used;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** `PUT /items`, once more with the category found or created again when the stored one went stale. */
|
|
227
|
+
async function putItem(ctx: CatalogueCallContext, item: CatalogueItemOut, image: string | null): Promise<MarketplaceHttpResponse | Failure> {
|
|
228
|
+
const category = await categoryId(ctx, item.categoryName);
|
|
229
|
+
if ("kind" in category) return category;
|
|
230
|
+
const put = await call(ctx, "PUT", "items", ifoodItemBody(item, category.id, image));
|
|
231
|
+
if ("kind" in put || ok(put) || !(await categoryWentStale(ctx, put, item.categoryName, category.id))) return put;
|
|
232
|
+
await ctx.forgetCategory(item.categoryName);
|
|
233
|
+
const again = await categoryId(ctx, item.categoryName);
|
|
234
|
+
if ("kind" in again) return again;
|
|
235
|
+
return call(ctx, "PUT", "items", ifoodItemBody(item, again.id, image));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function publish(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult> {
|
|
239
|
+
const photo = await photoFor(ctx, item);
|
|
240
|
+
if ("kind" in photo) return photo;
|
|
241
|
+
const put = await putItem(ctx, item, photo.image?.ref ?? null);
|
|
242
|
+
if ("kind" in put) return put;
|
|
243
|
+
if (!ok(put)) return failureOf(put);
|
|
244
|
+
// iFood's orders carry the item's `externalCode` as the line's SKU (the order normalizer reads it).
|
|
245
|
+
const published = { kind: "published" as const, externalId: ifoodItemId(item.ref), sku: item.productId, image: photo.image };
|
|
246
|
+
return photo.warning ? { ...published, warning: photo.warning } : published;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function withdraw(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult> {
|
|
250
|
+
const itemId = item.externalId ?? ifoodItemId(item.ref);
|
|
251
|
+
const patched = await call(ctx, "PATCH", "items/status", { itemId, status: "UNAVAILABLE" });
|
|
252
|
+
if ("kind" in patched) return patched;
|
|
253
|
+
// ESTIMATED: a 404 means iFood does not have the item, so it is already out
|
|
254
|
+
// of its catalogue (the Errors page says 404 is "the resource does not exist").
|
|
255
|
+
if (patched.status === 404) return { kind: "accepted" };
|
|
256
|
+
return outboundResultOf(patched);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** A call that never got an answer is a retry. */
|
|
260
|
+
async function publishedOrRetry(run: () => Promise<CataloguePublishResult>): Promise<CataloguePublishResult> {
|
|
261
|
+
try {
|
|
262
|
+
return await run();
|
|
263
|
+
} catch (error) {
|
|
264
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** iFood's catalogue capability. */
|
|
269
|
+
export const IFOOD_CATALOGUE: PushCatalogue = {
|
|
270
|
+
mode: "push",
|
|
271
|
+
publishItem: (ctx, item) => publishedOrRetry(() => publish(ctx, item)),
|
|
272
|
+
withdrawItem: (ctx, item) => answered(() => withdraw(ctx, item)),
|
|
273
|
+
};
|
package/src/ifood/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { CancellationReason, MarketplaceAdapter } from "../core/adapter";
|
|
2
2
|
import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
|
|
3
|
+
import { IFOOD_CATALOGUE } from "./catalogue";
|
|
3
4
|
import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
|
|
4
5
|
import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from "./outbound";
|
|
5
6
|
|
|
@@ -62,6 +63,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
62
63
|
readSignature: (header) => header("x-ifood-signature") ?? header("x-signature"),
|
|
63
64
|
verifySignature: verifyIfoodSignature,
|
|
64
65
|
cancellationReasons: () => reasons,
|
|
66
|
+
// The Catalog API v2.0: each item is written and paused through the API (FUT-4768).
|
|
67
|
+
catalogue: IFOOD_CATALOGUE,
|
|
65
68
|
confirm: (ctx, order) => ifoodConfirm(ctx, order),
|
|
66
69
|
requestCancellation: ifoodRequestCancellation,
|
|
67
70
|
// No per-order deep link is known, so the portal, where a live order is
|
|
@@ -72,3 +75,4 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
|
|
|
72
75
|
|
|
73
76
|
export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
|
|
74
77
|
export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
|
|
78
|
+
export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
|