@12-apps/marketplace 1.2.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.
Files changed (56) hide show
  1. package/ADOPTING.md +29 -4
  2. package/README.md +92 -3
  3. package/dist/99food/index.d.ts +48 -2
  4. package/dist/99food/index.js +84 -1
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-_iuSxvVD.d.ts → adapter-0l_EmuJA.d.ts} +172 -2
  7. package/dist/{chunk-CRYFYDQ2.js → chunk-AYYBRQJV.js} +28 -4
  8. package/dist/chunk-AYYBRQJV.js.map +1 -0
  9. package/dist/chunk-M2V4RFMA.js +23 -0
  10. package/dist/chunk-M2V4RFMA.js.map +1 -0
  11. package/dist/{chunk-24RQZPSV.js → chunk-RVBTARIY.js} +1 -1
  12. package/dist/chunk-RVBTARIY.js.map +1 -0
  13. package/dist/{chunk-D2X7TOR6.js → chunk-XUAFXNOH.js} +449 -85
  14. package/dist/chunk-XUAFXNOH.js.map +1 -0
  15. package/dist/{engine-D-a4mttc.d.ts → engine-CZsP8KWd.d.ts} +222 -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 +10 -2
  19. package/dist/ifood/index.js +246 -69
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +30 -4
  22. package/dist/index.js +148 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +3 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +1 -1
  27. package/dist/rappi/index.js +7 -1
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +12 -8
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +92 -1
  33. package/prisma/migrations/20261113120000_marketplace_catalogue/migration.sql +97 -0
  34. package/src/99food/catalogue.ts +117 -0
  35. package/src/99food/index.ts +4 -0
  36. package/src/99food/outbound.ts +3 -3
  37. package/src/core/adapter.ts +10 -1
  38. package/src/core/catalogue-category.ts +119 -0
  39. package/src/core/catalogue-ids.ts +23 -0
  40. package/src/core/catalogue-job.ts +332 -0
  41. package/src/core/catalogue-port.ts +173 -0
  42. package/src/core/catalogue-store.ts +172 -0
  43. package/src/core/catalogue-sweep.ts +43 -0
  44. package/src/core/catalogue.ts +226 -0
  45. package/src/core/engine.ts +46 -0
  46. package/src/core/outbound-sweep.ts +7 -2
  47. package/src/core/ports.ts +36 -0
  48. package/src/ifood/catalogue.ts +273 -0
  49. package/src/ifood/index.ts +4 -0
  50. package/src/ifood/outbound.ts +9 -6
  51. package/src/index.ts +40 -0
  52. package/src/rappi/index.ts +6 -0
  53. package/src/server/jobs.ts +39 -9
  54. package/dist/chunk-24RQZPSV.js.map +0 -1
  55. package/dist/chunk-CRYFYDQ2.js.map +0 -1
  56. package/dist/chunk-D2X7TOR6.js.map +0 -1
@@ -0,0 +1,117 @@
1
+ import { answered, outboundResultOf, type OutboundResult } from "../core/adapter";
2
+ import { stableUuid } from "../core/catalogue-ids";
3
+ import type { CatalogueCallContext, CatalogueMenuEntry, CatalogueMenuOptions, PullCatalogue } from "../core/catalogue-port";
4
+ import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outbound";
5
+
6
+ /**
7
+ * The 99Food adapter's CATALOGUE half, on Open Delivery v1.7.1: PULL (FUT-4768).
8
+ *
9
+ * In Open Delivery the store's software does not write the menu to the
10
+ * marketplace. The SOFTWARE SERVICE (the host) serves `GET /v1/merchant`, a
11
+ * `Merchant` document carrying `menus`, `categories`, `items` and
12
+ * `itemOffers` (the price lives on the offer), and the ORDERING APPLICATION
13
+ * (99Food) pulls it, again when its `TTL` runs out or when told the merchant
14
+ * changed (`POST /v1/merchantUpdate`, sent with an empty body: "pull
15
+ * everything again"). Spec: https://abrasel-nacional.github.io/opendelivery/openapi.yaml
16
+ *
17
+ * So the adapter does two things: build the menu part of that document from
18
+ * the items the store switched on (`menuDocument`, pure; the host merges it
19
+ * into the rest of the `Merchant`, which is its own: `basicInfo`, `services`,
20
+ * `lastUpdate`, `TTL`, `status`), and tell 99Food the menu changed
21
+ * (`notifyMenuChanged`).
22
+ *
23
+ * ESTIMATED, to be checked once 99Food grants partner access:
24
+ * - the path: the spec's route table and prose name `POST /merchantUpdate`
25
+ * (`/v1/merchantUpdate`), while its path key is `/v1/menuUpdated`; this
26
+ * sends the prose's;
27
+ * - the `X-App-MerchantId` header on it: the operation lists none, and one
28
+ * client app may serve many merchants, so it is sent to name which;
29
+ * - that 99Food reads the whole `Merchant` on that notification (scenario 1
30
+ * of the operation) rather than needing `entityType`/`updatedObjects`.
31
+ *
32
+ * Every id in the document is a UUID the software generates (the spec's
33
+ * `format: uuid`), derived from the publication's stable reference, so the
34
+ * same product keeps the same ids across pulls.
35
+ */
36
+
37
+ /** One category per host category name, in first-seen order. */
38
+ function categoriesOf(merchantId: string, entries: readonly CatalogueMenuEntry[]) {
39
+ const byName = new Map<string, { id: string; name: string; offers: string[] }>();
40
+ for (const entry of entries) {
41
+ const name = entry.categoryName.trim();
42
+ const category = byName.get(name) ?? { id: stableUuid(`${merchantId}:category:${name}`), name, offers: [] };
43
+ category.offers.push(stableUuid(`${entry.ref}:offer`));
44
+ byName.set(name, category);
45
+ }
46
+ return [...byName.values()];
47
+ }
48
+
49
+ /** The menu part of Open Delivery's `Merchant`: `menus`, `categories`, `items`, `itemOffers`. */
50
+ export function openDeliveryMenuDocument(input: {
51
+ externalMerchantId: string;
52
+ entries: readonly CatalogueMenuEntry[];
53
+ options: CatalogueMenuOptions;
54
+ }) {
55
+ const { externalMerchantId: merchantId, entries, options } = input;
56
+ const categories = categoriesOf(merchantId, entries);
57
+ return {
58
+ menus: [
59
+ {
60
+ id: stableUuid(`${merchantId}:menu`),
61
+ name: options.menuName,
62
+ externalCode: "menu",
63
+ categoryId: categories.map((category) => category.id),
64
+ },
65
+ ],
66
+ categories: categories.map((category, index) => ({
67
+ id: category.id,
68
+ index,
69
+ name: category.name,
70
+ externalCode: category.name,
71
+ status: "AVAILABLE",
72
+ itemOfferId: category.offers,
73
+ })),
74
+ items: entries.map((entry) => ({
75
+ id: stableUuid(`${entry.ref}:item`),
76
+ name: entry.name,
77
+ description: entry.description ?? "",
78
+ externalCode: entry.productId,
79
+ status: "AVAILABLE",
80
+ unit: "UN",
81
+ ...(entry.imageUrl === null ? {} : { image: { URL: entry.imageUrl } }),
82
+ })),
83
+ itemOffers: entries.map((entry, index) => {
84
+ const value = Math.round(entry.priceCents) / 100;
85
+ return {
86
+ id: stableUuid(`${entry.ref}:offer`),
87
+ itemId: stableUuid(`${entry.ref}:item`),
88
+ index,
89
+ status: "AVAILABLE",
90
+ price: { value, originalValue: value, currency: options.currency },
91
+ };
92
+ }),
93
+ };
94
+ }
95
+
96
+ /** `POST /v1/merchantUpdate` with no body: 99Food pulls the whole `Merchant` again. 200 or 204. */
97
+ async function notify(ctx: CatalogueCallContext, bases: NinetyNineFoodApiBaseUrls): Promise<OutboundResult> {
98
+ const auth = await bearer(ctx, bases);
99
+ if (!("token" in auth)) return auth;
100
+ const response = await ctx.http({
101
+ method: "POST",
102
+ url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
103
+ headers: { Authorization: `Bearer ${auth.token}`, "X-App-MerchantId": ctx.externalMerchantId },
104
+ });
105
+ if (response.status !== 401) return outboundResultOf(response);
106
+ ctx.tokens.delete(tokenKey(ctx));
107
+ return { kind: "retry", reason: "99Food refused the token" };
108
+ }
109
+
110
+ /** 99Food's catalogue capability, for the base URLs it was given. */
111
+ export function openDeliveryCatalogue(bases: NinetyNineFoodApiBaseUrls): PullCatalogue {
112
+ return {
113
+ mode: "pull",
114
+ menuDocument: openDeliveryMenuDocument,
115
+ notifyMenuChanged: (ctx) => answered(() => notify(ctx, bases)),
116
+ };
117
+ }
@@ -4,6 +4,7 @@ import {
4
4
  type NinetyNineFoodAdapterCopy,
5
5
  type NinetyNineFoodReasonCode,
6
6
  } from "./copy";
7
+ import { openDeliveryCatalogue } from "./catalogue";
7
8
  import { NINETY_NINE_FOOD_PROVIDER, normalizeOpenDeliveryEvent, verifyOpenDeliverySignature } from "./normalize";
8
9
  import {
9
10
  openDeliveryConfirm,
@@ -105,6 +106,8 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
105
106
  readSignature: (header) => header("x-app-signature"),
106
107
  verifySignature: verifyOpenDeliverySignature,
107
108
  cancellationReasons: () => reasons,
109
+ // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).
110
+ catalogue: openDeliveryCatalogue(bases),
108
111
  fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
109
112
  confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
110
113
  requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
@@ -119,3 +122,4 @@ export {
119
122
  } from "./copy";
120
123
  export { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from "./normalize";
121
124
  export type { NinetyNineFoodApiBaseUrls } from "./outbound";
125
+ export { openDeliveryCatalogue, openDeliveryMenuDocument } from "./catalogue";
@@ -32,13 +32,13 @@ const TOKEN_MARGIN_MS = 60_000;
32
32
  const DEFAULT_TOKEN_SECONDS = 3600;
33
33
 
34
34
  /** The base URL with its trailing slashes cut, by a loop: a `/\/+$/` regex backtracks polynomially on many slashes. */
35
- function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {
35
+ export function baseOf(ctx: AdapterCallContext, bases: NinetyNineFoodApiBaseUrls): string {
36
36
  const base = bases[ctx.environment];
37
37
  let end = base.length;
38
38
  while (end > 0 && base.charCodeAt(end - 1) === 47) end -= 1;
39
39
  return base.slice(0, end);
40
40
  }
41
- const tokenKey = (ctx: AdapterCallContext): string =>
41
+ export const tokenKey = (ctx: AdapterCallContext): string =>
42
42
  `${NINETY_NINE_FOOD_PROVIDER}:${ctx.environment}:${ctx.credentials.clientId}`;
43
43
 
44
44
  /** The spec's `TokenResponse` (`access_token`, `token_type`, `expires_in`), read defensively. */
@@ -59,7 +59,7 @@ function tokenOf(body: string): { token: string; expiresInSeconds: number } | nu
59
59
  * grant (`POST /oauth/token`, form-encoded `client_id`, `client_secret`,
60
60
  * `grant_type`). Keyed by environment and client id; memory only.
61
61
  */
62
- async function bearer(
62
+ export async function bearer(
63
63
  ctx: AdapterCallContext,
64
64
  bases: NinetyNineFoodApiBaseUrls,
65
65
  ): Promise<{ token: string } | Exclude<OutboundResult, { kind: "accepted" }>> {
@@ -1,3 +1,4 @@
1
+ import type { MarketplaceCatalogue } from "./catalogue-port";
1
2
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
2
3
 
3
4
  /**
@@ -41,7 +42,8 @@ export interface MarketplaceCredentials {
41
42
 
42
43
  /** What the host's HTTP client takes. */
43
44
  export interface MarketplaceHttpRequest {
44
- method: "GET" | "POST" | "PUT";
45
+ /** `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it. */
46
+ method: "GET" | "POST" | "PUT" | "PATCH";
45
47
  url: string;
46
48
  headers: Record<string, string>;
47
49
  body?: string;
@@ -171,6 +173,13 @@ export interface MarketplaceAdapter {
171
173
  * order (iFood) leaves it out.
172
174
  */
173
175
  fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;
176
+ /**
177
+ * OPTIONAL. Publishing the store's products to this marketplace's catalogue
178
+ * (FUT-4768): `push` (the adapter writes each item) or `pull` (the
179
+ * marketplace reads a menu document the host serves). Absent: the
180
+ * marketplace cannot be published to, and the host says so.
181
+ */
182
+ readonly catalogue?: MarketplaceCatalogue;
174
183
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
175
184
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
176
185
  }
@@ -0,0 +1,119 @@
1
+ import type { CatalogueFailure } from "./catalogue-port";
2
+ import type { EngineContext, MarketplaceDb } from "./ports";
3
+ import type { MarketplaceProvider } from "./types";
4
+
5
+ /**
6
+ * The marketplace's id for a host category, found or created ONCE per
7
+ * (connection, name) and reused (FUT-4768).
8
+ *
9
+ * A push marketplace issues its own category ids, so an adapter finds a
10
+ * category by name and creates it when it is missing. Two products switched
11
+ * on at once into a new category would each miss it and each create it,
12
+ * leaving two categories of the same name in front of the buyer. So the engine
13
+ * stores the id, and the first publish to need it CLAIMS the creation: its
14
+ * row holds the name with no id yet; a second publish meanwhile is told to
15
+ * retry (the job's backoff), and finds the id stored when it does. A claim
16
+ * whose publish died is taken over once it is older than {@link CLAIM_STALE_MS}.
17
+ */
18
+
19
+ /**
20
+ * A claim older than this was left by a publish that died; another takes it
21
+ * over. Well above three slow marketplace calls, so a live holder on a slow
22
+ * call keeps its claim (a shorter window let a second publish create the
23
+ * category again). A publish that only waited is left PUBLISHING for the
24
+ * sweep, which re-queues it after 10 minutes, so a long window costs nothing.
25
+ */
26
+ const CLAIM_STALE_MS = 3 * 60_000;
27
+
28
+ /** What one publish learnt about the category claims it met: whether another held one. */
29
+ export interface CategoryRunState {
30
+ waited: boolean;
31
+ }
32
+
33
+ type CategoryTable = NonNullable<MarketplaceDb["marketplaceCatalogueCategory"]>;
34
+
35
+ interface CategoryRow {
36
+ externalId: string | null;
37
+ }
38
+
39
+ /** Take the creation of this category, or learn someone else holds it. */
40
+ async function claim(table: CategoryTable, key: Record<string, string>, row: CategoryRow | null, now: Date): Promise<boolean> {
41
+ if (!row) {
42
+ try {
43
+ await table.create({ data: { ...key, claimedAt: now } });
44
+ return true;
45
+ } catch (error) {
46
+ if ((error as { code?: string }).code === "P2002") return false;
47
+ throw error;
48
+ }
49
+ }
50
+ const stale = new Date(now.getTime() - CLAIM_STALE_MS);
51
+ const moved = await table.updateMany({
52
+ where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },
53
+ data: { claimedAt: now },
54
+ });
55
+ return moved.count > 0;
56
+ }
57
+
58
+ /**
59
+ * Store the id this publish resolved, or release its claim. Only this
60
+ * publish's own claim (`claimedAt` it set) is released: one taken over
61
+ * meanwhile stays its new holder's.
62
+ */
63
+ async function release(table: CategoryTable, key: Record<string, string>, claimedAt: Date, id: string | null): Promise<void> {
64
+ if (id !== null) {
65
+ await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });
66
+ return;
67
+ }
68
+ await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });
69
+ }
70
+
71
+ /**
72
+ * The category's id: the stored one, else `resolve()` (the adapter's find or
73
+ * create) run under this publish's claim and stored. A host without the
74
+ * category table resolves every time, unserialized, as before it.
75
+ */
76
+ export async function resolveCategory(
77
+ ctx: EngineContext,
78
+ connection: { clientId: string; provider: MarketplaceProvider },
79
+ name: string,
80
+ resolve: () => Promise<{ id: string } | CatalogueFailure>,
81
+ state: CategoryRunState = { waited: false },
82
+ ): Promise<{ id: string } | CatalogueFailure> {
83
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
84
+ if (!table) return resolve();
85
+ const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };
86
+ const row = (await table.findFirst({ where: key, select: { externalId: true } })) as CategoryRow | null;
87
+ if (row?.externalId) return { id: row.externalId };
88
+ const now = ctx.ports.clock.now();
89
+ if (!(await claim(table, key, row, now))) {
90
+ state.waited = true;
91
+ return { kind: "retry", reason: `another publish is creating the category "${key.name}"` };
92
+ }
93
+ let result: { id: string } | CatalogueFailure = { kind: "retry", reason: "the category was not resolved" };
94
+ try {
95
+ result = await resolve();
96
+ } catch (error) {
97
+ // A call that never got an answer (a timeout) is a retry, like every outbound call.
98
+ result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
99
+ } finally {
100
+ // The claim is released whatever happened, so the next attempt (this
101
+ // publish's or another's) goes on at once instead of waiting it out.
102
+ await release(table, key, now, "id" in result ? result.id : null);
103
+ }
104
+ return result;
105
+ }
106
+
107
+ /** Forget a stored category id the marketplace no longer has, so the next resolve finds or creates it again. */
108
+ export async function forgetCategory(
109
+ ctx: EngineContext,
110
+ connection: { clientId: string; provider: MarketplaceProvider },
111
+ name: string,
112
+ ): Promise<void> {
113
+ const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
114
+ if (!table) return;
115
+ await table.updateMany({
116
+ where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
117
+ data: { externalId: null, claimedAt: null },
118
+ });
119
+ }
@@ -0,0 +1,23 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /**
4
+ * A UUID v4-shaped id derived from a seed, the same for the same seed (FUT-4768).
5
+ *
6
+ * Some marketplaces make the store's software invent the id of a catalogue
7
+ * entity (iFood's Catalog API v2.0 and Open Delivery both want a UUID the
8
+ * software generates). Deriving it from the engine's stable publication
9
+ * reference, instead of drawing a random one, makes a retried publish whose
10
+ * first answer was lost name the SAME item rather than a second one, and needs
11
+ * no write before the call.
12
+ */
13
+ export function stableUuid(seed: string): string {
14
+ const hex = createHash("sha256").update(seed, "utf8").digest("hex");
15
+ const variant = ((Number.parseInt(hex.slice(16, 17), 16) & 0x3) | 0x8).toString(16);
16
+ return [
17
+ hex.slice(0, 8),
18
+ hex.slice(8, 12),
19
+ `4${hex.slice(13, 16)}`,
20
+ `${variant}${hex.slice(17, 20)}`,
21
+ hex.slice(20, 32),
22
+ ].join("-");
23
+ }
@@ -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
+ }