@12-apps/marketplace 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/ADOPTING.md +76 -4
  2. package/README.md +163 -3
  3. package/dist/99food/index.d.ts +79 -2
  4. package/dist/99food/index.js +117 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/adapter-B8QtQ2RA.d.ts +612 -0
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-DPCZVN2C.js} +69 -5
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-D2X7TOR6.js → chunk-EBAIZQPB.js} +841 -86
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/chunk-M2V4RFMA.js +23 -0
  12. package/dist/chunk-M2V4RFMA.js.map +1 -0
  13. package/dist/{chunk-24RQZPSV.js → chunk-SZRZTLVU.js} +1 -1
  14. package/dist/chunk-SZRZTLVU.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-o5cm54vC.d.ts} +462 -2
  16. package/dist/hono/index.d.ts +2 -2
  17. package/dist/hono/index.js +2 -2
  18. package/dist/ifood/index.d.ts +22 -2
  19. package/dist/ifood/index.js +396 -56
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +445 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +5 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +62 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +25 -10
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +158 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  35. package/src/99food/catalogue.ts +117 -0
  36. package/src/99food/index.ts +14 -0
  37. package/src/99food/outbound.ts +3 -3
  38. package/src/99food/pause.ts +56 -0
  39. package/src/core/adapter.ts +20 -1
  40. package/src/core/catalogue-category.ts +119 -0
  41. package/src/core/catalogue-ids.ts +23 -0
  42. package/src/core/catalogue-job.ts +332 -0
  43. package/src/core/catalogue-port.ts +173 -0
  44. package/src/core/catalogue-store.ts +172 -0
  45. package/src/core/catalogue-sweep.ts +43 -0
  46. package/src/core/catalogue.ts +226 -0
  47. package/src/core/engine.ts +83 -0
  48. package/src/core/outbound-sweep.ts +7 -2
  49. package/src/core/pause-job.ts +381 -0
  50. package/src/core/pause-port.ts +110 -0
  51. package/src/core/pause-retired.ts +139 -0
  52. package/src/core/pause-store.ts +151 -0
  53. package/src/core/pause-sweep.ts +148 -0
  54. package/src/core/pause.ts +316 -0
  55. package/src/core/ports.ts +47 -0
  56. package/src/ifood/catalogue.ts +273 -0
  57. package/src/ifood/index.ts +8 -0
  58. package/src/ifood/outbound.ts +9 -6
  59. package/src/ifood/pause.ts +257 -0
  60. package/src/index.ts +64 -0
  61. package/src/rappi/index.ts +17 -0
  62. package/src/rappi/outbound.ts +2 -2
  63. package/src/rappi/pause.ts +98 -0
  64. package/src/server/index.ts +1 -0
  65. package/src/server/jobs.ts +100 -10
  66. package/dist/adapter-_iuSxvVD.d.ts +0 -319
  67. package/dist/chunk-24RQZPSV.js.map +0 -1
  68. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  69. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -0,0 +1,332 @@
1
+ import type { OutboundResult } from "./adapter";
2
+ import type { CatalogueCallContext, CatalogueFailure, CataloguePublishResult, MarketplaceCatalogue } from "./catalogue-port";
3
+ import {
4
+ CATALOGUE_ROW_SELECT,
5
+ NO_FAILURE,
6
+ catalogueConnection,
7
+ catalogueTable,
8
+ truncateReason,
9
+ type CatalogueFailureCode,
10
+ type CatalogueRow,
11
+ type CatalogueTable,
12
+ } from "./catalogue-store";
13
+ import type { EngineContext } from "./ports";
14
+
15
+ /**
16
+ * The catalogue job (`marketplace.catalogue`): one publish or withdraw of one
17
+ * product on one marketplace, start to finish (FUT-4768).
18
+ *
19
+ * The same rules as the outbound job, for the same reasons:
20
+ *
21
+ * - **idempotent by the ROW** — a run acts only while the row still asks for
22
+ * its action (PUBLISHING for a publish, WITHDRAWING for a withdraw) at the
23
+ * instant it was asked (`requested_at`), so a duplicate or stale job calls
24
+ * nobody, and a stamp never overwrites a newer ask;
25
+ * - **2xx done, a final 4xx FAILED with the marketplace's reason, anything
26
+ * else retried** until the last attempt, which ends FAILED;
27
+ * - **queued, never called inline** — `publish` and `withdraw` only stamp and
28
+ * enqueue; the sweep re-queues a row still owed.
29
+ *
30
+ * Push or pull is the adapter's `catalogue.mode`, never a provider check: a
31
+ * push marketplace gets the item written or withdrawn; a pull marketplace is
32
+ * told its menu changed (the host serves the document, which already reflects
33
+ * the row).
34
+ */
35
+
36
+ /** The wire name, `<namespace>.<blueprint>` as the jobs contribution binds it. */
37
+ export const MARKETPLACE_CATALOGUE_JOB = "marketplace.catalogue";
38
+
39
+ /** What one run does to its row. */
40
+ export type CatalogueAction = "publish" | "withdraw";
41
+
42
+ /** The job's payload. Identifiers only: what to send lives on the row and in the host's catalogue. */
43
+ export interface CatalogueJobPayload {
44
+ clientId: string;
45
+ publicationId: string;
46
+ action: CatalogueAction;
47
+ }
48
+
49
+ /** What one run did. */
50
+ export type CatalogueOutcome =
51
+ | { kind: "skipped"; reason: string }
52
+ | { kind: "done"; action: CatalogueAction }
53
+ /** `reason` is the row's failure code; the detail went to the log. */
54
+ | { kind: "failed"; action: CatalogueAction; reason: string };
55
+
56
+ /** Thrown so the queue retries. Its message is what the job log reads. */
57
+ export class CatalogueRetryError extends Error {
58
+ constructor(message: string) {
59
+ super(message);
60
+ this.name = "CatalogueRetryError";
61
+ }
62
+ }
63
+
64
+ const WANTED: Record<CatalogueAction, string> = { publish: "PUBLISHING", withdraw: "WITHDRAWING" };
65
+
66
+ /** The dedupe key: one queued run per (row, ask). A re-ask carries a new instant, so it is never swallowed. */
67
+ export function catalogueDedupeKey(payload: CatalogueJobPayload, requestedAt: Date): string {
68
+ return `${MARKETPLACE_CATALOGUE_JOB}:${payload.action}:${payload.publicationId}:${requestedAt.getTime()}`;
69
+ }
70
+
71
+ /** Queue one run. The queue port never throws; a refusal is logged, and the sweep re-queues the row. */
72
+ export async function enqueueCatalogue(ctx: EngineContext, payload: CatalogueJobPayload, dedupeKey: string): Promise<void> {
73
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CATALOGUE_JOB, payload, { dedupeKey });
74
+ if (outcome.enqueued) return;
75
+ ctx.ports.logger.warn(
76
+ `${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} was not queued; the outbound sweep will re-queue it` +
77
+ (outcome.reason ? ` (${outcome.reason})` : ""),
78
+ );
79
+ }
80
+
81
+ type RunResult = CataloguePublishResult | OutboundResult;
82
+
83
+ /** What a run did instead of a call: an engine-side reason it cannot be made. */
84
+ type Run =
85
+ | { result: RunResult; sentPriceCents: number | null; name?: string; waited?: boolean }
86
+ | { code: CatalogueFailureCode };
87
+
88
+ /** The call this run makes, or the code that stands in for it. */
89
+ async function callFor(
90
+ ctx: EngineContext,
91
+ row: CatalogueRow,
92
+ action: CatalogueAction,
93
+ catalogue: MarketplaceCatalogue,
94
+ call: CatalogueCallContext,
95
+ ): Promise<Run> {
96
+ if (action === "withdraw") {
97
+ if (catalogue.mode === "pull") return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: null };
98
+ const ref = { ref: row.id, productId: row.productId, externalId: row.externalId };
99
+ return { result: await catalogue.withdrawItem(call, ref), sentPriceCents: null };
100
+ }
101
+ const item = (await ctx.ports.catalogue?.items(row.clientId, [row.productId]))?.get(row.productId);
102
+ if (!item) return { code: "PRODUCT_GONE" };
103
+ const priceCents = row.priceCents ?? item.priceCents;
104
+ if (catalogue.mode === "pull") {
105
+ return { result: await catalogue.notifyMenuChanged(call), sentPriceCents: priceCents, name: item.name };
106
+ }
107
+ const storedImage = row.imageRef && row.imageSourceUrl ? { ref: row.imageRef, sourceUrl: row.imageSourceUrl } : null;
108
+ const out = { ...item, priceCents, ref: row.id, productId: row.productId, externalId: row.externalId, storedImage };
109
+ return { result: await catalogue.publishItem(call, out), sentPriceCents: priceCents, name: item.name };
110
+ }
111
+
112
+ /** The predicate a stamp holds to: the row still asks for this action, at the instant this run read. */
113
+ const stillAsked = (row: CatalogueRow, action: CatalogueAction) => ({
114
+ id: row.id,
115
+ status: WANTED[action],
116
+ requestedAt: row.requestedAt,
117
+ });
118
+
119
+ /**
120
+ * A publish that landed after the store asked for the product out (a withdraw
121
+ * while publishing): the item is on the marketplace now, so the withdraw is
122
+ * owed again. The row goes back to WITHDRAWING with a fresh ask, carrying the
123
+ * id the publish answered, and the withdraw is queued.
124
+ */
125
+ async function withdrawLateLanding(ctx: EngineContext, table: CatalogueTable, row: CatalogueRow, externalId: string | null): Promise<void> {
126
+ const now = ctx.ports.clock.now();
127
+ const moved = await table.updateMany({
128
+ where: { id: row.id, status: { in: ["WITHDRAWING", "WITHDRAWN"] } },
129
+ data: { status: "WITHDRAWING", requestedAt: now, ...(externalId === null ? {} : { externalId }) },
130
+ });
131
+ if (moved.count === 0) return;
132
+ const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action: "withdraw" };
133
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));
134
+ }
135
+
136
+ /**
137
+ * A withdraw that landed after the store switched the product back on (a
138
+ * publish while withdrawing): the item is out on the marketplace now, so the
139
+ * publish is owed again, whether or not its own run already went out. The row
140
+ * takes a fresh ask and the publish is queued: the store's last tap wins.
141
+ */
142
+ async function publishLateLanding(ctx: EngineContext, table: CatalogueTable, row: CatalogueRow): Promise<void> {
143
+ const now = ctx.ports.clock.now();
144
+ const moved = await table.updateMany({
145
+ where: { id: row.id, status: { in: ["PUBLISHING", "PUBLISHED"] } },
146
+ data: { status: "PUBLISHING", requestedAt: now },
147
+ });
148
+ if (moved.count === 0) return;
149
+ const payload: CatalogueJobPayload = { clientId: row.clientId, publicationId: row.id, action: "publish" };
150
+ await enqueueCatalogue(ctx, payload, catalogueDedupeKey(payload, now));
151
+ }
152
+
153
+ /**
154
+ * Map the SKU the marketplace's orders will carry for a published item to the
155
+ * host's product, so those orders arrive mapped instead of on the attention
156
+ * list — only when the SKU has no link yet, or an unmapped one: a store that
157
+ * mapped it to another product on purpose keeps its own mapping. Kept on a
158
+ * withdraw: an order placed before it still maps.
159
+ */
160
+ async function mapPublishedSku(ctx: EngineContext, row: CatalogueRow, result: RunResult, name: string | undefined): Promise<void> {
161
+ const sku = (result.kind === "published" ? result.sku : undefined) ?? row.productId;
162
+ const db = await ctx.ports.db();
163
+ const key = { clientId: row.clientId, provider: row.provider, externalSku: sku };
164
+ const existing = (await db.marketplaceMenuLink.findMany({ where: key, select: { menuItemId: true }, take: 1 })) as {
165
+ menuItemId: string | null;
166
+ }[];
167
+ if (existing[0]?.menuItemId) return;
168
+ await db.marketplaceMenuLink.upsert({
169
+ where: { clientId_provider_externalSku: key },
170
+ create: { ...key, externalName: name ?? null, menuItemId: row.productId, lastSeenAt: ctx.ports.clock.now() },
171
+ update: { menuItemId: row.productId },
172
+ });
173
+ }
174
+
175
+ /** What a successful publish leaves on the row beyond its state: the item's id, the photo held, the warning. */
176
+ function publishedExtras(result: RunResult): Record<string, unknown> {
177
+ if (result.kind !== "published") return { warningCode: null };
178
+ const image =
179
+ result.image === undefined
180
+ ? {}
181
+ : { imageRef: result.image?.ref ?? null, imageSourceUrl: result.image?.sourceUrl ?? null };
182
+ return { externalId: result.externalId, warningCode: result.warning ?? null, ...image };
183
+ }
184
+
185
+ async function stampSuccess(
186
+ ctx: EngineContext,
187
+ table: CatalogueTable,
188
+ row: CatalogueRow,
189
+ action: CatalogueAction,
190
+ result: RunResult,
191
+ sentPriceCents: number | null,
192
+ ): Promise<void> {
193
+ const now = ctx.ports.clock.now();
194
+ const externalId = result.kind === "published" ? result.externalId : null;
195
+ const data =
196
+ action === "publish"
197
+ ? { status: "PUBLISHED", publishedAt: now, sentPriceCents, ...publishedExtras(result), ...NO_FAILURE }
198
+ : { status: "WITHDRAWN", withdrawnAt: now, ...NO_FAILURE };
199
+ const moved = await table.updateMany({ where: stillAsked(row, action), data });
200
+ if (moved.count > 0) return;
201
+ if (action === "publish") await withdrawLateLanding(ctx, table, row, externalId);
202
+ else await publishLateLanding(ctx, table, row);
203
+ }
204
+
205
+ /** One failure, as the row keeps it: a code, and the marketplace's own words only for a refusal. */
206
+ interface Failure {
207
+ code: CatalogueFailureCode;
208
+ reason: string | null;
209
+ }
210
+
211
+ async function stampFailure(table: CatalogueTable, row: CatalogueRow, action: CatalogueAction, failure: Failure, now: Date): Promise<void> {
212
+ await table.updateMany({
213
+ where: stillAsked(row, action),
214
+ data: {
215
+ status: "FAILED",
216
+ failedAction: action === "publish" ? "PUBLISH" : "WITHDRAW",
217
+ failureCode: failure.code,
218
+ failureReason: failure.reason === null ? null : truncateReason(failure.reason),
219
+ failedAt: now,
220
+ },
221
+ });
222
+ }
223
+
224
+ /** A final answer as the row keeps it: the marketplace's refusal with its words, or UNAVAILABLE. */
225
+ function failureOf(result: CatalogueFailure): Failure {
226
+ if (result.kind === "retry") return { code: "UNAVAILABLE", reason: null };
227
+ return { code: "REFUSED", reason: result.message === "" ? null : result.message };
228
+ }
229
+
230
+ /** The run this row gets: the adapter's call, or the code that stands in for it. */
231
+ async function runFor(ctx: EngineContext, row: CatalogueRow, action: CatalogueAction): Promise<Run> {
232
+ const catalogue = ctx.registry.get(row.provider)?.catalogue;
233
+ if (!catalogue) return { code: "UNSUPPORTED" };
234
+ const categoryState = { waited: false };
235
+ const connection = await catalogueConnection(ctx, row.clientId, row.provider, categoryState);
236
+ // A withdraw for a connection that is gone (archived, removed) has nobody to tell: it is out.
237
+ if ("problem" in connection && connection.problem === "NOT_CONNECTED" && action === "withdraw") {
238
+ return { result: { kind: "accepted" }, sentPriceCents: null };
239
+ }
240
+ if ("problem" in connection) return { code: connection.problem };
241
+ const run = await callFor(ctx, row, action, catalogue, { ...connection, now: ctx.ports.clock.now() });
242
+ return "result" in run ? { ...run, waited: categoryState.waited } : run;
243
+ }
244
+
245
+ /**
246
+ * The last attempt of a publish that only ever WAITED for another publish to
247
+ * create its category: not a failure of this item. The row stays PUBLISHING
248
+ * (the store still sees "sending…") and the outbound sweep re-queues it; by
249
+ * then the category is stored, or its claim is stale and taken over.
250
+ */
251
+ function waitedOut(ctx: EngineContext, row: CatalogueRow, action: CatalogueAction, detail: string): CatalogueOutcome {
252
+ ctx.ports.logger.warn(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} left for the sweep: ${detail}`);
253
+ return { kind: "skipped", reason: detail };
254
+ }
255
+
256
+ async function fail(ctx: EngineContext, table: CatalogueTable, row: CatalogueRow, action: CatalogueAction, failure: Failure, detail: string) {
257
+ await stampFailure(table, row, action, failure, ctx.ports.clock.now());
258
+ ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${action} of ${row.productId} on ${row.provider} failed (${failure.code}): ${detail}`);
259
+ ctx.ports.publishChanged(row.clientId);
260
+ return { kind: "failed" as const, action, reason: failure.code };
261
+ }
262
+
263
+ async function runOnce(
264
+ ctx: EngineContext,
265
+ table: CatalogueTable,
266
+ payload: CatalogueJobPayload,
267
+ attempt: { attempt: number; maxAttempts: number },
268
+ ): Promise<CatalogueOutcome> {
269
+ const row = await readRow(table, payload);
270
+ if (!row) return { kind: "skipped", reason: "no such publication for this tenant" };
271
+ const { action } = payload;
272
+ if (row.status !== WANTED[action]) return { kind: "skipped", reason: `the publication is ${row.status}, not ${WANTED[action]}` };
273
+ const run = await runFor(ctx, row, action);
274
+ if ("code" in run) return fail(ctx, table, row, action, { code: run.code, reason: null }, run.code);
275
+ return settle(ctx, table, row, action, run, attempt);
276
+ }
277
+
278
+ /** Turn a call's answer into the row's stamp, a retry, a wait for the sweep, or a failure. */
279
+ async function settle(
280
+ ctx: EngineContext,
281
+ table: CatalogueTable,
282
+ row: CatalogueRow,
283
+ action: CatalogueAction,
284
+ run: Exclude<Run, { code: CatalogueFailureCode }>,
285
+ attempt: { attempt: number; maxAttempts: number },
286
+ ): Promise<CatalogueOutcome> {
287
+ const { result } = run;
288
+ if (result.kind === "accepted" || result.kind === "published") {
289
+ await stampSuccess(ctx, table, row, action, result, run.sentPriceCents);
290
+ if (action === "publish") await mapPublishedSku(ctx, row, result, run.name);
291
+ ctx.ports.publishChanged(row.clientId);
292
+ return { kind: "done", action };
293
+ }
294
+ const detail = result.kind === "retry" ? result.reason : `refused ${result.status}: ${result.message}`;
295
+ if (result.kind === "retry" && attempt.attempt < attempt.maxAttempts) {
296
+ throw new CatalogueRetryError(`${action} of ${row.productId} on ${row.provider}: ${detail}`);
297
+ }
298
+ if (result.kind === "retry" && run.waited) return waitedOut(ctx, row, action, detail);
299
+ return fail(ctx, table, row, action, failureOf(result), detail);
300
+ }
301
+
302
+ function readRow(table: CatalogueTable, payload: CatalogueJobPayload): Promise<CatalogueRow | null> {
303
+ return table.findFirst({
304
+ where: { id: payload.publicationId, clientId: payload.clientId },
305
+ select: CATALOGUE_ROW_SELECT,
306
+ }) as Promise<CatalogueRow | null>;
307
+ }
308
+
309
+ /**
310
+ * Run one queued catalogue call. Throws {@link CatalogueRetryError} for an
311
+ * answer worth retrying before the last attempt; any other throw is rethrown
312
+ * for the queue to retry, and on the last attempt ends FAILED, INTERNAL (the
313
+ * message is logged, never stored).
314
+ */
315
+ export async function runCatalogue(
316
+ ctx: EngineContext,
317
+ payload: CatalogueJobPayload,
318
+ attempt: { attempt: number; maxAttempts: number },
319
+ ): Promise<CatalogueOutcome> {
320
+ const table = await catalogueTable(ctx);
321
+ if (!table) return { kind: "skipped", reason: "the host has no catalogue table" };
322
+ try {
323
+ return await runOnce(ctx, table, payload, attempt);
324
+ } catch (error) {
325
+ if (error instanceof CatalogueRetryError || attempt.attempt < attempt.maxAttempts) throw error;
326
+ const detail = error instanceof Error ? error.message : String(error);
327
+ const row = await readRow(table, payload);
328
+ if (row && row.status === WANTED[payload.action]) return fail(ctx, table, row, payload.action, { code: "INTERNAL", reason: null }, detail);
329
+ ctx.ports.logger.error(`${MARKETPLACE_CATALOGUE_JOB}: ${payload.action} of ${payload.publicationId} failed: ${detail}`);
330
+ return { kind: "failed", action: payload.action, reason: "INTERNAL" };
331
+ }
332
+ }
@@ -0,0 +1,173 @@
1
+ import type { AdapterCallContext, OutboundResult } from "./adapter";
2
+
3
+ /**
4
+ * The catalogue half of the adapter port (FUT-4768): a store turns one of its
5
+ * products ON or OFF per connected marketplace, with an optional price for
6
+ * that marketplace, and the engine keeps the marketplace's catalogue in step.
7
+ *
8
+ * Marketplaces differ in exactly one way that shapes the engine: who moves the
9
+ * menu.
10
+ *
11
+ * - **push** — the store's software writes each item to the marketplace's API
12
+ * (iFood's Catalog API v2.0). The adapter publishes and withdraws ONE item.
13
+ * - **pull** — the marketplace reads the menu from the store's software (Open
14
+ * Delivery's `GET /v1/merchant`, which 99Food implements). The adapter turns
15
+ * the published items into the marketplace's menu document, which the HOST
16
+ * serves, and tells the marketplace the menu changed.
17
+ *
18
+ * A marketplace whose adapter states no `catalogue` cannot be published to,
19
+ * and the host says so (`engine.catalogueMode(provider)` is null). Everything
20
+ * else — the publication record and its states, the job, its retries, the
21
+ * sweep, the price rule — is the engine's and does not change with the
22
+ * marketplace.
23
+ */
24
+
25
+ /** One product as it goes out to a marketplace. The host maps its product into this shape. */
26
+ export interface CatalogueItem {
27
+ name: string;
28
+ description: string | null;
29
+ /**
30
+ * An absolute https URL of the product's photo, or null. It must CHANGE when
31
+ * the photo changes (a versioned URL: a content hash or an upload id in it):
32
+ * a marketplace that holds an uploaded copy reuses it while the URL is the
33
+ * same, so new bytes at an old URL are never sent.
34
+ */
35
+ imageUrl: string | null;
36
+ /** The name of the host category the product sits in; the adapter finds or creates it. */
37
+ categoryName: string;
38
+ /** The store's own price, in the smallest currency unit. */
39
+ priceCents: number;
40
+ }
41
+
42
+ /**
43
+ * What the adapter is handed to publish: the host's item with `priceCents`
44
+ * already the price for THIS marketplace (the connection's own price when the
45
+ * store set one, else the store's), and the engine's stable reference.
46
+ */
47
+ export interface CatalogueItemOut extends CatalogueItem {
48
+ /**
49
+ * The engine's stable id for this (connection, product) publication. The
50
+ * same across retries and re-publishes, so an adapter that must invent the
51
+ * marketplace's id (iFood wants a UUID it does not issue) derives it from
52
+ * this and a lost answer never creates a second item.
53
+ */
54
+ ref: string;
55
+ /** The host's product id: the item's external code on the marketplace. */
56
+ productId: string;
57
+ /** The marketplace's id from the last publish, or null before the first. */
58
+ externalId: string | null;
59
+ /**
60
+ * The photo this marketplace already holds for the item, from an earlier
61
+ * publish: the adapter's own reference (iFood's `imagePath`) and the
62
+ * `imageUrl` it was made from. Reuse it while `sourceUrl` is still the
63
+ * item's `imageUrl` rather than uploading again; null when none is held.
64
+ */
65
+ storedImage: CatalogueStoredImage | null;
66
+ }
67
+
68
+ /** A photo a marketplace holds: the adapter's reference to it, and the URL it was made from. */
69
+ export interface CatalogueStoredImage {
70
+ ref: string;
71
+ sourceUrl: string;
72
+ }
73
+
74
+ /**
75
+ * Something a publish that SUCCEEDED could not do, for the host to say:
76
+ * the photo was too large for the marketplace, or it refused the photo.
77
+ */
78
+ export type CatalogueWarningCode = "IMAGE_TOO_LARGE" | "IMAGE_REFUSED";
79
+
80
+ /** What the adapter is handed to withdraw. */
81
+ export type CatalogueItemRef = Pick<CatalogueItemOut, "ref" | "productId" | "externalId">;
82
+
83
+ /** An image's bytes, for a marketplace that takes an upload rather than a URL. */
84
+ export interface CatalogueImage {
85
+ contentType: string;
86
+ /** The file, base64-encoded, no data-URL prefix. */
87
+ base64: string;
88
+ }
89
+
90
+ /** An outbound call's answer when it is not a success: refused (final) or retry. */
91
+ export type CatalogueFailure = Exclude<OutboundResult, { kind: "accepted" }>;
92
+
93
+ /** What one catalogue call is handed: the outbound context plus the store's merchant id and the image loader. */
94
+ export interface CatalogueCallContext extends AdapterCallContext {
95
+ /** The connection's merchant id on the marketplace. */
96
+ externalMerchantId: string;
97
+ /** The host's image loader: the bytes behind an item's `imageUrl`, or null when it cannot load them. */
98
+ loadImage(url: string): Promise<CatalogueImage | null>;
99
+ /**
100
+ * The marketplace's id for the host category `name`: the one the engine
101
+ * stored for this connection, else `resolve()` (the adapter's find-or-create)
102
+ * run by ONE publish at a time and stored. A second publish into a category
103
+ * being created is answered `retry`, so a new category is created once.
104
+ */
105
+ category(name: string, resolve: () => Promise<{ id: string } | CatalogueFailure>): Promise<{ id: string } | CatalogueFailure>;
106
+ /**
107
+ * Forget the id stored for the host category `name` (the marketplace no
108
+ * longer has it: the store deleted it on the marketplace's portal), so the
109
+ * next `category` finds or creates it again.
110
+ */
111
+ forgetCategory(name: string): Promise<void>;
112
+ }
113
+
114
+ /** A publish's answer: the marketplace's id for the item, or the refusal and retry shapes of every outbound call. */
115
+ export type CataloguePublishResult =
116
+ | {
117
+ kind: "published";
118
+ externalId: string;
119
+ /**
120
+ * OPTIONAL. The SKU this marketplace's orders will carry for the item,
121
+ * when it is not the host's product id (the item's external code). The
122
+ * engine maps it to the product, so its orders arrive mapped.
123
+ */
124
+ sku?: string;
125
+ /**
126
+ * OPTIONAL. The photo the marketplace now holds (stored for the next
127
+ * publish to reuse), null when it holds none; absent leaves the stored one.
128
+ */
129
+ image?: CatalogueStoredImage | null;
130
+ /** OPTIONAL. What the publish could not do although it succeeded. */
131
+ warning?: CatalogueWarningCode;
132
+ }
133
+ | CatalogueFailure;
134
+
135
+ /** A marketplace the store's software writes to. */
136
+ export interface PushCatalogue {
137
+ readonly mode: "push";
138
+ /** Create or replace ONE item in the marketplace's catalogue, available for sale. Idempotent by `item.ref`. */
139
+ publishItem(ctx: CatalogueCallContext, item: CatalogueItemOut): Promise<CataloguePublishResult>;
140
+ /** Take ONE item out of the marketplace's catalogue. An item already absent is `accepted`. */
141
+ withdrawItem(ctx: CatalogueCallContext, item: CatalogueItemRef): Promise<OutboundResult>;
142
+ }
143
+
144
+ /** One published item, as a pull marketplace's menu document lists it. */
145
+ export type CatalogueMenuEntry = CatalogueItemOut;
146
+
147
+ /** What the host states about the menu a pull marketplace reads: its words and money, never the engine's. */
148
+ export interface CatalogueMenuOptions {
149
+ /** The menu's display name, in the store's language. */
150
+ menuName: string;
151
+ /** ISO 4217 code of the prices. */
152
+ currency: string;
153
+ }
154
+
155
+ /** A marketplace that reads the menu from the store's software. */
156
+ export interface PullCatalogue {
157
+ readonly mode: "pull";
158
+ /**
159
+ * The menu part of the document the marketplace pulls, built from every item
160
+ * published to this connection. Pure and offline: the host serves it, merged
161
+ * into whatever else that document carries (the store's own details).
162
+ */
163
+ menuDocument(input: {
164
+ externalMerchantId: string;
165
+ entries: readonly CatalogueMenuEntry[];
166
+ options: CatalogueMenuOptions;
167
+ }): unknown;
168
+ /** Tell the marketplace the menu changed, so it pulls it again. */
169
+ notifyMenuChanged(ctx: CatalogueCallContext): Promise<OutboundResult>;
170
+ }
171
+
172
+ /** The catalogue capability an adapter states, or leaves out. */
173
+ export type MarketplaceCatalogue = PushCatalogue | PullCatalogue;
@@ -0,0 +1,172 @@
1
+ import { forgetCategory, resolveCategory, type CategoryRunState } from "./catalogue-category";
2
+ import type { CatalogueCallContext, CatalogueWarningCode } from "./catalogue-port";
3
+ import { connectionMerchantId, readOutboundConnection } from "./integration";
4
+ import type { EngineContext, MarketplaceDb } from "./ports";
5
+ import type { MarketplaceProvider } from "./types";
6
+
7
+ /**
8
+ * The catalogue publication's rows and the reads every catalogue path shares
9
+ * (FUT-4768). The table is `marketplace_catalogue_publications`; its states
10
+ * are the mechanism's vocabulary, never a language.
11
+ */
12
+
13
+ /** Where one product stands in one marketplace's catalogue. */
14
+ export type CatalogueStatus = "PUBLISHING" | "PUBLISHED" | "WITHDRAWING" | "WITHDRAWN" | "FAILED";
15
+
16
+ /** Which action a FAILED row failed at. */
17
+ export type CatalogueFailedAction = "PUBLISH" | "WITHDRAW";
18
+
19
+ /**
20
+ * Why a row FAILED, as a code the host turns into its own words. Vocabulary,
21
+ * not copy: the engine writes no sentence a person reads.
22
+ *
23
+ * - `REFUSED` — the marketplace said no; its own words are in `failureReason`.
24
+ * - `UNAVAILABLE` — no usable answer on any attempt (5xx, 429, timeouts).
25
+ * - `TIMEOUT` — still on its way a day later (the sweep gave up).
26
+ * - `NOT_CONNECTED` — no live connection with a merchant id (archived, removed).
27
+ * - `CREDENTIALS` — no credentials on file, or they would not open.
28
+ * - `PRODUCT_GONE` — the host's catalogue no longer has the product.
29
+ * - `UNSUPPORTED` — the marketplace has no catalogue capability any more.
30
+ * - `INTERNAL` — the engine or the adapter threw (logged, never shown).
31
+ */
32
+ export type CatalogueFailureCode =
33
+ | "REFUSED"
34
+ | "UNAVAILABLE"
35
+ | "TIMEOUT"
36
+ | "NOT_CONNECTED"
37
+ | "CREDENTIALS"
38
+ | "PRODUCT_GONE"
39
+ | "UNSUPPORTED"
40
+ | "INTERNAL";
41
+
42
+ /** One publication as a host reads it. */
43
+ export interface CataloguePublicationView {
44
+ provider: MarketplaceProvider;
45
+ productId: string;
46
+ status: CatalogueStatus;
47
+ /** The store's price for this marketplace; null is "the store's own price". */
48
+ priceCents: number | null;
49
+ /** The price the last successful publish sent. */
50
+ sentPriceCents: number | null;
51
+ /** The marketplace's id for the item, from the last successful publish. */
52
+ externalId: string | null;
53
+ /** What the last successful publish could not do (the photo); null when it did everything. */
54
+ warningCode: CatalogueWarningCode | null;
55
+ failedAction: CatalogueFailedAction | null;
56
+ /** Why it FAILED; null unless FAILED. The host's copy is keyed by it. */
57
+ failureCode: CatalogueFailureCode | null;
58
+ /**
59
+ * The marketplace's OWN words for a `REFUSED` (its answer's body, truncated);
60
+ * null for every other code. Never an engine or internal message.
61
+ */
62
+ failureReason: string | null;
63
+ requestedAt: Date;
64
+ publishedAt: Date | null;
65
+ withdrawnAt: Date | null;
66
+ failedAt: Date | null;
67
+ }
68
+
69
+ /** A publication row, with the engine's own columns. */
70
+ export interface CatalogueRow extends CataloguePublicationView {
71
+ id: string;
72
+ clientId: string;
73
+ imageRef: string | null;
74
+ imageSourceUrl: string | null;
75
+ }
76
+
77
+ export const CATALOGUE_ROW_SELECT = {
78
+ id: true,
79
+ clientId: true,
80
+ provider: true,
81
+ productId: true,
82
+ status: true,
83
+ priceCents: true,
84
+ sentPriceCents: true,
85
+ externalId: true,
86
+ imageRef: true,
87
+ imageSourceUrl: true,
88
+ warningCode: true,
89
+ failedAction: true,
90
+ failureCode: true,
91
+ failureReason: true,
92
+ requestedAt: true,
93
+ publishedAt: true,
94
+ withdrawnAt: true,
95
+ failedAt: true,
96
+ } as const;
97
+
98
+ /** The delegate, or null on a host that has not composed the catalogue model. */
99
+ export type CatalogueTable = NonNullable<MarketplaceDb["marketplaceCataloguePublication"]>;
100
+
101
+ export async function catalogueTable(ctx: EngineContext): Promise<CatalogueTable | null> {
102
+ return (await ctx.ports.db()).marketplaceCataloguePublication ?? null;
103
+ }
104
+
105
+ /** A row without the engine's own columns. */
106
+ export function viewOf(row: CatalogueRow): CataloguePublicationView {
107
+ return {
108
+ provider: row.provider,
109
+ productId: row.productId,
110
+ status: row.status,
111
+ priceCents: row.priceCents,
112
+ sentPriceCents: row.sentPriceCents,
113
+ externalId: row.externalId,
114
+ warningCode: row.warningCode,
115
+ failedAction: row.failedAction,
116
+ failureCode: row.failureCode,
117
+ failureReason: row.failureReason,
118
+ requestedAt: row.requestedAt,
119
+ publishedAt: row.publishedAt,
120
+ withdrawnAt: row.withdrawnAt,
121
+ failedAt: row.failedAt,
122
+ };
123
+ }
124
+
125
+ /** The failure columns cleared, for every write that leaves FAILED. */
126
+ export const NO_FAILURE = { failedAction: null, failureCode: null, failureReason: null, failedAt: null } as const;
127
+
128
+ /** The longest failure reason a row keeps: the column is read by a person in a list. */
129
+ const REASON_LIMIT = 300;
130
+
131
+ export function truncateReason(reason: string): string {
132
+ return reason.length > REASON_LIMIT ? reason.slice(0, REASON_LIMIT) : reason;
133
+ }
134
+
135
+ /** Why a connection cannot carry a catalogue call. */
136
+ interface ConnectionProblem {
137
+ problem: "NOT_CONNECTED" | "CREDENTIALS";
138
+ }
139
+
140
+ /**
141
+ * Everything one catalogue call needs from the store's connection, or why it
142
+ * cannot be used: NOT_CONNECTED (none, archived, no merchant id) or
143
+ * CREDENTIALS (none on file, or they will not open).
144
+ */
145
+ export async function catalogueConnection(
146
+ ctx: EngineContext,
147
+ clientId: string,
148
+ provider: MarketplaceProvider,
149
+ categoryState?: CategoryRunState,
150
+ ): Promise<Omit<CatalogueCallContext, "now"> | ConnectionProblem> {
151
+ const merchantId = await connectionMerchantId(ctx, clientId, provider);
152
+ if (merchantId === null) return { problem: "NOT_CONNECTED" };
153
+ try {
154
+ const connection = await readOutboundConnection(ctx, clientId, provider);
155
+ if (!connection) return { problem: "CREDENTIALS" };
156
+ const catalogue = ctx.ports.catalogue;
157
+ return {
158
+ ...connection,
159
+ http: ctx.ports.http,
160
+ tokens: ctx.tokens,
161
+ externalMerchantId: merchantId,
162
+ loadImage: (url) => (catalogue ? catalogue.image(url) : Promise.resolve(null)),
163
+ category: (name, resolve) => resolveCategory(ctx, { clientId, provider }, name, resolve, categoryState),
164
+ forgetCategory: (name) => forgetCategory(ctx, { clientId, provider }, name),
165
+ };
166
+ } catch (error) {
167
+ ctx.ports.logger.error(
168
+ `marketplace.catalogue: ${provider} credentials of ${clientId} do not open: ${error instanceof Error ? error.message : String(error)}`,
169
+ );
170
+ return { problem: "CREDENTIALS" };
171
+ }
172
+ }