@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,97 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: the catalogue publication (FUT-4768). Additive and
3
+ -- replay-safe, like the engine's other migrations: two new tables, their
4
+ -- indexes and their CHECKs. No column of an existing table changes.
5
+ --
6
+ -- One row per (store, marketplace, host product): whether the store wants the
7
+ -- product in that marketplace's catalogue, the price it set for that
8
+ -- marketplace (NULL: the store's own), and what the marketplace made of it.
9
+ -- `product_id` is a by-value scalar, like `menu_item_id`: no foreign key into
10
+ -- a host table.
11
+
12
+ CREATE TABLE IF NOT EXISTS "marketplace_catalogue_publications" (
13
+ "id" TEXT NOT NULL,
14
+ "client_id" TEXT NOT NULL,
15
+ "provider" TEXT NOT NULL,
16
+ "product_id" TEXT NOT NULL,
17
+ "status" TEXT NOT NULL DEFAULT 'PUBLISHING',
18
+ "price_cents" INTEGER,
19
+ "sent_price_cents" INTEGER,
20
+ "external_id" TEXT,
21
+ "image_ref" TEXT,
22
+ "image_source_url" TEXT,
23
+ "warning_code" TEXT,
24
+ "failed_action" TEXT,
25
+ "failure_code" TEXT,
26
+ "failure_reason" TEXT,
27
+ "requested_at" TIMESTAMP(3) NOT NULL,
28
+ "published_at" TIMESTAMP(3),
29
+ "withdrawn_at" TIMESTAMP(3),
30
+ "failed_at" TIMESTAMP(3),
31
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
32
+ "updated_at" TIMESTAMP(3) NOT NULL,
33
+
34
+ CONSTRAINT "marketplace_catalogue_publications_pkey" PRIMARY KEY ("id")
35
+ );
36
+
37
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_catalogue_publications_client_provider_product_key"
38
+ ON "marketplace_catalogue_publications"("client_id", "provider", "product_id");
39
+ CREATE INDEX IF NOT EXISTS "marketplace_catalogue_publications_client_id_product_id_idx"
40
+ ON "marketplace_catalogue_publications"("client_id", "product_id");
41
+ CREATE INDEX IF NOT EXISTS "marketplace_catalogue_publications_status_requested_at_idx"
42
+ ON "marketplace_catalogue_publications"("status", "requested_at");
43
+
44
+ DO $$ BEGIN
45
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_provider_shape"
46
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
47
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
48
+
49
+ DO $$ BEGIN
50
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_status_check"
51
+ CHECK ("status" IN ('PUBLISHING', 'PUBLISHED', 'WITHDRAWING', 'WITHDRAWN', 'FAILED'));
52
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
53
+
54
+ DO $$ BEGIN
55
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_failed_action_check"
56
+ CHECK ("failed_action" IS NULL OR "failed_action" IN ('PUBLISH', 'WITHDRAW'));
57
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
58
+
59
+ DO $$ BEGIN
60
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_failure_code_check"
61
+ CHECK ("failure_code" IS NULL OR "failure_code" IN ('REFUSED', 'UNAVAILABLE', 'TIMEOUT', 'NOT_CONNECTED',
62
+ 'CREDENTIALS', 'PRODUCT_GONE', 'UNSUPPORTED', 'INTERNAL'));
63
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
64
+
65
+ DO $$ BEGIN
66
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_warning_code_check"
67
+ CHECK ("warning_code" IS NULL OR "warning_code" IN ('IMAGE_TOO_LARGE', 'IMAGE_REFUSED'));
68
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
69
+
70
+ DO $$ BEGIN
71
+ ALTER TABLE "marketplace_catalogue_publications" ADD CONSTRAINT "marketplace_catalogue_publications_price_check"
72
+ CHECK (("price_cents" IS NULL OR "price_cents" > 0)
73
+ AND ("sent_price_cents" IS NULL OR "sent_price_cents" > 0));
74
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
75
+
76
+ -- The marketplace's id for one host category on one connection, found or
77
+ -- created by name once and reused; claimed while it is being created.
78
+ CREATE TABLE IF NOT EXISTS "marketplace_catalogue_categories" (
79
+ "id" TEXT NOT NULL,
80
+ "client_id" TEXT NOT NULL,
81
+ "provider" TEXT NOT NULL,
82
+ "name" TEXT NOT NULL,
83
+ "external_id" TEXT,
84
+ "claimed_at" TIMESTAMP(3),
85
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
86
+ "updated_at" TIMESTAMP(3) NOT NULL,
87
+
88
+ CONSTRAINT "marketplace_catalogue_categories_pkey" PRIMARY KEY ("id")
89
+ );
90
+
91
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_catalogue_categories_client_id_provider_name_key"
92
+ ON "marketplace_catalogue_categories"("client_id", "provider", "name");
93
+
94
+ DO $$ BEGIN
95
+ ALTER TABLE "marketplace_catalogue_categories" ADD CONSTRAINT "marketplace_catalogue_categories_provider_shape"
96
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
97
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
@@ -0,0 +1,70 @@
1
+ -- @domains: marketplace
2
+ -- @12-apps/marketplace: a store's pause on each marketplace (FUT-4851).
3
+ -- Additive and replay-safe, like the engine's earlier migrations: one new
4
+ -- table, its CHECKs and indexes. No foreign key into a host table.
5
+ --
6
+ -- One row per (store, marketplace). `wanted` is the host's last ask (PAUSED
7
+ -- or OPEN); `state` is where the marketplace stands (OPEN, PAUSING, PAUSED,
8
+ -- RESUMING, FAILED). The engine deletes on a marketplace only what a row
9
+ -- records: `external_id`, `retired_external_ids` (space-separated), or a
10
+ -- closure created under `attempt_key` (recognised by `attempt_until`).
11
+
12
+ CREATE TABLE IF NOT EXISTS "marketplace_store_pauses" (
13
+ "id" TEXT NOT NULL,
14
+ "client_id" TEXT NOT NULL,
15
+ "provider" TEXT NOT NULL,
16
+ "state" TEXT NOT NULL DEFAULT 'OPEN',
17
+ "wanted" TEXT NOT NULL DEFAULT 'OPEN',
18
+ "until" TIMESTAMP(3),
19
+ "reason" TEXT,
20
+ "time_zone" TEXT,
21
+ "external_id" TEXT,
22
+ "sent_until" TIMESTAMP(3),
23
+ "attempt_key" TEXT,
24
+ "attempt_until" TIMESTAMP(3),
25
+ "retired_external_ids" TEXT,
26
+ "failure_code" TEXT,
27
+ "failure_detail" TEXT,
28
+ "requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
29
+ "lease_until" TIMESTAMP(3),
30
+ "paused_at" TIMESTAMP(3),
31
+ "resumed_at" TIMESTAMP(3),
32
+ "failed_at" TIMESTAMP(3),
33
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
34
+ "updated_at" TIMESTAMP(3) NOT NULL,
35
+
36
+ CONSTRAINT "marketplace_store_pauses_pkey" PRIMARY KEY ("id")
37
+ );
38
+
39
+ DO $$ BEGIN
40
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_provider_shape"
41
+ CHECK ("provider" ~ '^[A-Z][A-Z0-9_]*$');
42
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
43
+
44
+ DO $$ BEGIN
45
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_state_check"
46
+ CHECK ("state" IN ('OPEN', 'PAUSING', 'PAUSED', 'RESUMING', 'FAILED'));
47
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
48
+
49
+ DO $$ BEGIN
50
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_wanted_check"
51
+ CHECK ("wanted" IN ('PAUSED', 'OPEN'));
52
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
53
+
54
+ DO $$ BEGIN
55
+ ALTER TABLE "marketplace_store_pauses" ADD CONSTRAINT "marketplace_store_pauses_failure_code_check"
56
+ CHECK ("failure_code" IS NULL OR "failure_code" IN (
57
+ 'UNSUPPORTED', 'NOT_CONNECTED', 'PAUSE_REFUSED', 'PAUSE_UNANSWERED', 'RESUME_REFUSED', 'RESUME_UNANSWERED'));
58
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
59
+
60
+ -- One pause per store and marketplace: the upsert's key.
61
+ CREATE UNIQUE INDEX IF NOT EXISTS "marketplace_store_pauses_client_id_provider_key"
62
+ ON "marketplace_store_pauses"("client_id", "provider");
63
+
64
+ -- The sweep: asks still owed, by age.
65
+ CREATE INDEX IF NOT EXISTS "marketplace_store_pauses_state_requested_at_idx"
66
+ ON "marketplace_store_pauses"("state", "requested_at");
67
+
68
+ -- The sweep: pauses past their end.
69
+ CREATE INDEX IF NOT EXISTS "marketplace_store_pauses_wanted_until_idx"
70
+ ON "marketplace_store_pauses"("wanted", "until");
@@ -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,
@@ -11,6 +12,7 @@ import {
11
12
  openDeliveryRequestCancellation,
12
13
  type NinetyNineFoodApiBaseUrls,
13
14
  } from "./outbound";
15
+ import { openDeliveryAvailability } from "./pause";
14
16
 
15
17
  /**
16
18
  * `@12-apps/marketplace/99food` — 99Food, as one adapter on the engine.
@@ -60,6 +62,13 @@ export interface NinetyNineFoodAdapterConfig {
60
62
  * per-order deep link, so the link is the portal. Required; https only.
61
63
  */
62
64
  portalUrl: string;
65
+ /**
66
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Open
67
+ * Delivery's `merchantStatus`, a store-wide switch with no id: a store the
68
+ * owner also closed by hand on 99Food during the kitchen's pause is opened
69
+ * with it. A host turns this on knowing that.
70
+ */
71
+ pauseByStoreSwitch?: boolean;
63
72
  }
64
73
 
65
74
  function assertHttps(name: string, url: string): void {
@@ -105,10 +114,13 @@ export function createNinetyNineFoodAdapter(config: NinetyNineFoodAdapterConfig)
105
114
  readSignature: (header) => header("x-app-signature"),
106
115
  verifySignature: verifyOpenDeliverySignature,
107
116
  cancellationReasons: () => reasons,
117
+ // PULL: 99Food reads the menu the host serves (`GET /v1/merchant`) and is told when it changed (FUT-4768).
118
+ catalogue: openDeliveryCatalogue(bases),
108
119
  fetchOrder: (ctx, order) => openDeliveryFetchOrder(ctx, bases, order, normalizeOptions),
109
120
  confirm: (ctx, order, input) => openDeliveryConfirm(ctx, bases, order, input),
110
121
  requestCancellation: (ctx, order, input) => openDeliveryRequestCancellation(ctx, bases, order, input),
111
122
  appLink: () => config.portalUrl,
123
+ ...(config.pauseByStoreSwitch ? { availability: openDeliveryAvailability(bases) } : {}),
112
124
  };
113
125
  }
114
126
 
@@ -119,3 +131,5 @@ export {
119
131
  } from "./copy";
120
132
  export { normalizeOpenDeliveryEvent, normalizeOpenDeliveryOrder, verifyOpenDeliverySignature } from "./normalize";
121
133
  export type { NinetyNineFoodApiBaseUrls } from "./outbound";
134
+ export { openDeliveryCatalogue, openDeliveryMenuDocument } from "./catalogue";
135
+ export { openDeliveryAvailability, openDeliverySetMerchantStatus } from "./pause";
@@ -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" }>> {
@@ -0,0 +1,56 @@
1
+ import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
2
+ import type { MarketplaceAvailability } from "../core/pause-port";
3
+ import { baseOf, bearer, tokenKey, type NinetyNineFoodApiBaseUrls } from "./outbound";
4
+
5
+ /**
6
+ * 99Food's half of the store pause (FUT-4851), on Open Delivery v1.7.1: the
7
+ * software PUSHES the merchant's status to the Ordering Application.
8
+ *
9
+ * `POST /v1/merchantUpdate` (host: the Ordering Application, OAuth2 `od.all`)
10
+ * "sent with only the `merchantStatus` field ... will force the opening or
11
+ * closing of the merchant within the Ordering Application"; `merchantStatus`
12
+ * is `AVAILABLE | UNAVAILABLE`, "only use this type when you must close
13
+ * (disable) the merchant due to an unexpected event and you don't know when
14
+ * the service will be re-established"; 204 (200 "for compatibility"), 400,
15
+ * 401, 403, 404, 503 (openapi.yaml v1.7.1, README "Pausing a store").
16
+ *
17
+ * A SWITCH, with no id and no end, so offered only when the host opts in
18
+ * (`pauseByStoreSwitch`; see `../core/pause-port.ts`). ESTIMATED: the path
19
+ * (the spec files this webhook under the key `/v1/menuUpdated` while its own
20
+ * description and route table say `POST /v1/merchantUpdate`; the latter is
21
+ * sent), that 99Food implements it at all, and that the token names the
22
+ * merchant (Open Delivery authenticates per merchant, so the body names none).
23
+ */
24
+
25
+ /** Set the merchant's status. */
26
+ export function openDeliverySetMerchantStatus(
27
+ ctx: AdapterCallContext,
28
+ bases: NinetyNineFoodApiBaseUrls,
29
+ status: "AVAILABLE" | "UNAVAILABLE",
30
+ ): Promise<OutboundResult> {
31
+ return answered(async () => {
32
+ const auth = await bearer(ctx, bases);
33
+ if (!("token" in auth)) return auth;
34
+ const response = await ctx.http({
35
+ method: "POST",
36
+ url: `${baseOf(ctx, bases)}/v1/merchantUpdate`,
37
+ headers: { Authorization: `Bearer ${auth.token}`, "Content-Type": "application/json" },
38
+ body: JSON.stringify({ merchantStatus: status }),
39
+ });
40
+ if (response.status !== 401) return outboundResultOf(response);
41
+ ctx.tokens.delete(tokenKey(ctx));
42
+ return { kind: "retry", reason: "99Food refused the token" };
43
+ });
44
+ }
45
+
46
+ /** 99Food's availability capability: Open Delivery's merchant status, a switch. */
47
+ export function openDeliveryAvailability(bases: NinetyNineFoodApiBaseUrls): MarketplaceAvailability {
48
+ return {
49
+ kind: "switch",
50
+ pause: async (ctx, request) => {
51
+ const result = await openDeliverySetMerchantStatus(ctx, bases, "UNAVAILABLE");
52
+ return result.kind === "accepted" ? { kind: "paused", externalId: null, until: request.until } : result;
53
+ },
54
+ resume: (ctx) => openDeliverySetMerchantStatus(ctx, bases, "AVAILABLE"),
55
+ };
56
+ }
@@ -1,3 +1,5 @@
1
+ import type { MarketplaceCatalogue } from "./catalogue-port";
2
+ import type { MarketplaceAvailability } from "./pause-port";
1
3
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
2
4
 
3
5
  /**
@@ -41,7 +43,11 @@ export interface MarketplaceCredentials {
41
43
 
42
44
  /** What the host's HTTP client takes. */
43
45
  export interface MarketplaceHttpRequest {
44
- method: "GET" | "POST" | "PUT";
46
+ /**
47
+ * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.
48
+ * `DELETE` since FUT-4851: iFood removes an interruption with it.
49
+ */
50
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
45
51
  url: string;
46
52
  headers: Record<string, string>;
47
53
  body?: string;
@@ -171,6 +177,19 @@ export interface MarketplaceAdapter {
171
177
  * order (iFood) leaves it out.
172
178
  */
173
179
  fetchOrder?(ctx: AdapterCallContext, order: { externalOrderId: string }): Promise<FetchOrderResult>;
180
+ /**
181
+ * OPTIONAL. Publishing the store's products to this marketplace's catalogue
182
+ * (FUT-4768): `push` (the adapter writes each item) or `pull` (the
183
+ * marketplace reads a menu document the host serves). Absent: the
184
+ * marketplace cannot be published to, and the host says so.
185
+ */
186
+ readonly catalogue?: MarketplaceCatalogue;
187
+ /**
188
+ * OPTIONAL. Closing the store on this marketplace for a while, and opening
189
+ * it again (FUT-4851). Absent: the marketplace cannot be paused through an
190
+ * API, and the host says so.
191
+ */
192
+ readonly availability?: MarketplaceAvailability;
174
193
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
175
194
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
176
195
  }
@@ -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
+ }