@12-apps/marketplace 1.3.0 → 1.5.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 (59) hide show
  1. package/ADOPTING.md +47 -0
  2. package/README.md +122 -1
  3. package/dist/99food/index.d.ts +33 -2
  4. package/dist/99food/index.js +34 -2
  5. package/dist/99food/index.js.map +1 -1
  6. package/dist/{adapter-0l_EmuJA.d.ts → adapter-CCWMqt2g.d.ts} +275 -3
  7. package/dist/{chunk-XUAFXNOH.js → chunk-FKUEFVVA.js} +396 -4
  8. package/dist/chunk-FKUEFVVA.js.map +1 -0
  9. package/dist/{chunk-RVBTARIY.js → chunk-RGMSD7S7.js} +1 -1
  10. package/dist/chunk-RGMSD7S7.js.map +1 -0
  11. package/dist/{chunk-AYYBRQJV.js → chunk-UONWZIBO.js} +43 -3
  12. package/dist/chunk-UONWZIBO.js.map +1 -0
  13. package/dist/chunk-WN2EK4KX.js +15 -0
  14. package/dist/chunk-WN2EK4KX.js.map +1 -0
  15. package/dist/{engine-CZsP8KWd.d.ts → engine-C3uq_BJd.d.ts} +252 -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 +44 -2
  19. package/dist/ifood/index.js +441 -1
  20. package/dist/ifood/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +342 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/manifest/server.d.ts +4 -2
  25. package/dist/manifest/server.js +2 -2
  26. package/dist/rappi/index.d.ts +15 -2
  27. package/dist/rappi/index.js +56 -2
  28. package/dist/rappi/index.js.map +1 -1
  29. package/dist/server/index.d.ts +18 -7
  30. package/dist/server/index.js +4 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +67 -1
  33. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  34. package/src/99food/index.ts +10 -0
  35. package/src/99food/pause.ts +56 -0
  36. package/src/core/adapter.ts +19 -2
  37. package/src/core/catalogue-read-port.ts +151 -0
  38. package/src/core/catalogue-read.ts +51 -0
  39. package/src/core/engine.ts +46 -0
  40. package/src/core/pause-job.ts +381 -0
  41. package/src/core/pause-port.ts +110 -0
  42. package/src/core/pause-retired.ts +139 -0
  43. package/src/core/pause-store.ts +151 -0
  44. package/src/core/pause-sweep.ts +148 -0
  45. package/src/core/pause.ts +316 -0
  46. package/src/core/ports.ts +11 -0
  47. package/src/ifood/catalogue-read.ts +187 -0
  48. package/src/ifood/catalogue-snapshot.ts +246 -0
  49. package/src/ifood/index.ts +9 -0
  50. package/src/ifood/pause.ts +257 -0
  51. package/src/index.ts +39 -0
  52. package/src/rappi/index.ts +11 -0
  53. package/src/rappi/outbound.ts +2 -2
  54. package/src/rappi/pause.ts +98 -0
  55. package/src/server/index.ts +1 -0
  56. package/src/server/jobs.ts +64 -4
  57. package/dist/chunk-AYYBRQJV.js.map +0 -1
  58. package/dist/chunk-RVBTARIY.js.map +0 -1
  59. package/dist/chunk-XUAFXNOH.js.map +0 -1
@@ -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,4 +1,6 @@
1
1
  import type { MarketplaceCatalogue } from "./catalogue-port";
2
+ import type { CatalogueReader } from "./catalogue-read-port";
3
+ import type { MarketplaceAvailability } from "./pause-port";
2
4
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
3
5
 
4
6
  /**
@@ -42,8 +44,11 @@ export interface MarketplaceCredentials {
42
44
 
43
45
  /** What the host's HTTP client takes. */
44
46
  export interface MarketplaceHttpRequest {
45
- /** `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it. */
46
- method: "GET" | "POST" | "PUT" | "PATCH";
47
+ /**
48
+ * `PATCH` since FUT-4768: iFood's catalogue sets an item's status with it.
49
+ * `DELETE` since FUT-4851: iFood removes an interruption with it.
50
+ */
51
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
47
52
  url: string;
48
53
  headers: Record<string, string>;
49
54
  body?: string;
@@ -180,6 +185,18 @@ export interface MarketplaceAdapter {
180
185
  * marketplace cannot be published to, and the host says so.
181
186
  */
182
187
  readonly catalogue?: MarketplaceCatalogue;
188
+ /**
189
+ * OPTIONAL. Reading the menu the store already keeps on this marketplace,
190
+ * through its own connection, for the host to import (FUT-951). Absent: the
191
+ * menu cannot be read through an API, and the host says so.
192
+ */
193
+ readonly catalogueReader?: CatalogueReader;
194
+ /**
195
+ * OPTIONAL. Closing the store on this marketplace for a while, and opening
196
+ * it again (FUT-4851). Absent: the marketplace cannot be paused through an
197
+ * API, and the host says so.
198
+ */
199
+ readonly availability?: MarketplaceAvailability;
183
200
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
184
201
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
185
202
  }
@@ -0,0 +1,151 @@
1
+ import type { AdapterCallContext } from "./adapter";
2
+
3
+ /**
4
+ * The catalogue READ half of the adapter port (FUT-951): the menu a store
5
+ * already keeps on a marketplace, read through the store's own connection, so
6
+ * the host can import it (onboarding: "bring my menu over").
7
+ *
8
+ * The opposite direction of `catalogue-port.ts` and independent of it: an
9
+ * adapter may read a menu it cannot publish to, or publish to one it cannot
10
+ * read. Nothing here names a marketplace; each adapter maps its own catalogue
11
+ * into the {@link CatalogueSnapshot} below.
12
+ *
13
+ * Money is integer cents of the menu's currency ({@link centsFromMajor}).
14
+ * Nothing the adapter cannot map is dropped silently: a field it could not read
15
+ * is a {@link CatalogueReadWarning} on the item, and an item or category it
16
+ * could not read at all is a {@link CatalogueReadNotice} on the snapshot.
17
+ */
18
+
19
+ /** Why part of an item could not be mapped. Vocabulary, not copy: the host words it. */
20
+ export type CatalogueReadWarningCode =
21
+ /** The item carries no readable price: `priceCents` is null. */
22
+ | "PRICE_MISSING"
23
+ /** An option carries no readable price: its `priceDeltaCents` is null. */
24
+ | "OPTION_PRICE_MISSING"
25
+ /** A group of choices could not be read (no name, no options, bounds that make no sense): left out. */
26
+ | "OPTION_GROUP_UNREADABLE"
27
+ /** One choice of a group could not be read (no name): left out of its group. */
28
+ | "OPTION_UNREADABLE"
29
+ /** The photo reference is there but is not a path or URL the adapter can resolve: `photoUrl` is null. */
30
+ | "PHOTO_UNREADABLE"
31
+ /** The item is of a kind this reader maps only partly (a combo, a pizza by halves): read as a plain item. */
32
+ | "ITEM_TYPE_UNSUPPORTED";
33
+
34
+ /** One thing about an item the read could not map. */
35
+ export interface CatalogueReadWarning {
36
+ code: CatalogueReadWarningCode;
37
+ /** The marketplace's id of the group or option concerned, or null when it is the item itself. */
38
+ subject: string | null;
39
+ /** What the marketplace sent, for a developer (never shown as copy). */
40
+ detail: string | null;
41
+ }
42
+
43
+ /** One choice of a group: a size, a flavour, an add-on. */
44
+ export interface CatalogueSnapshotOption {
45
+ externalId: string;
46
+ /** The store's own code for it on the marketplace, when it set one. */
47
+ externalCode: string | null;
48
+ name: string;
49
+ description: string | null;
50
+ /** What choosing it adds to the item's price, in cents (0 = free); null when the marketplace sent none. */
51
+ priceDeltaCents: number | null;
52
+ photoUrl: string | null;
53
+ available: boolean;
54
+ }
55
+
56
+ /** A group of choices on an item: "Size" (min 1, max 1), "Extras" (min 0, max 3). */
57
+ export interface CatalogueSnapshotOptionGroup {
58
+ externalId: string;
59
+ externalCode: string | null;
60
+ name: string;
61
+ /** At least this many choices (0 = optional). */
62
+ min: number;
63
+ /** At most this many choices (always >= `min` and >= 1). */
64
+ max: number;
65
+ available: boolean;
66
+ options: CatalogueSnapshotOption[];
67
+ }
68
+
69
+ /** One item as the marketplace sells it. */
70
+ export interface CatalogueSnapshotItem {
71
+ externalId: string;
72
+ externalCode: string | null;
73
+ name: string;
74
+ description: string | null;
75
+ /** The item's own price in cents; null when the marketplace sent none (with a PRICE_MISSING warning). */
76
+ priceCents: number | null;
77
+ /** An absolute https URL of the photo, or null when the item has none. */
78
+ photoUrl: string | null;
79
+ /** Whether the marketplace sells it now (a paused item is still read). */
80
+ available: boolean;
81
+ optionGroups: CatalogueSnapshotOptionGroup[];
82
+ warnings: CatalogueReadWarning[];
83
+ }
84
+
85
+ /** One category, its items in the marketplace's order. */
86
+ export interface CatalogueSnapshotCategory {
87
+ externalId: string;
88
+ externalCode: string | null;
89
+ name: string;
90
+ available: boolean;
91
+ items: CatalogueSnapshotItem[];
92
+ }
93
+
94
+ /** An item or a category the read could not map at all, said rather than dropped. */
95
+ export interface CatalogueReadNotice {
96
+ code: "ITEM_UNREADABLE" | "CATEGORY_UNREADABLE";
97
+ /** The category it was found in (the category itself for CATEGORY_UNREADABLE), or null when it had no id. */
98
+ categoryExternalId: string | null;
99
+ /** The item's id, when it had one; null for a category. */
100
+ externalId: string | null;
101
+ detail: string;
102
+ }
103
+
104
+ /** The store's menu on a marketplace, as read. */
105
+ export interface CatalogueSnapshot {
106
+ categories: CatalogueSnapshotCategory[];
107
+ notices: CatalogueReadNotice[];
108
+ }
109
+
110
+ /**
111
+ * Why a read failed for good. Vocabulary, not copy.
112
+ * - `UNSUPPORTED`: the marketplace's adapter states no catalogue read.
113
+ * - `NOT_CONNECTED`: no live connection with a merchant id for that marketplace.
114
+ * - `CREDENTIALS`: no credentials on file, they do not open, or the marketplace refused them.
115
+ * - `NOT_AUTHORIZED`: the marketplace refused this merchant to this app (not
116
+ * authorized, the catalogue module not enabled, an unknown merchant id).
117
+ * - `REFUSED`: any other final refusal.
118
+ */
119
+ export type CatalogueReadRefusalCode = "UNSUPPORTED" | "NOT_CONNECTED" | "CREDENTIALS" | "NOT_AUTHORIZED" | "REFUSED";
120
+
121
+ /** What a read answers: the snapshot, a final refusal, or a failure worth asking again later (429, 5xx, a timeout). */
122
+ export type CatalogueReadResult =
123
+ | { kind: "snapshot"; snapshot: CatalogueSnapshot }
124
+ /** `status` and `message` are the marketplace's answer; null when the engine refused before calling. */
125
+ | { kind: "refused"; code: CatalogueReadRefusalCode; status: number | null; message: string | null }
126
+ | { kind: "retry"; reason: string };
127
+
128
+ /** What one catalogue read is handed: the outbound context plus the connection's merchant id. */
129
+ export interface CatalogueReadContext extends AdapterCallContext {
130
+ externalMerchantId: string;
131
+ }
132
+
133
+ /** A marketplace whose menu can be read. */
134
+ export interface CatalogueReader {
135
+ /** Read the whole menu. Never throws: a call with no answer is a `retry`. */
136
+ read(ctx: CatalogueReadContext): Promise<CatalogueReadResult>;
137
+ }
138
+
139
+ /**
140
+ * A price in the currency's MAJOR unit (`25.9`) as integer cents (`2590`), or
141
+ * null when it is not a finite, non-negative number.
142
+ *
143
+ * Rounding is explicit: the product is first cut to 12 significant digits,
144
+ * which removes binary floating-point error (`1.005 * 100` is
145
+ * `100.49999999999999`), and then rounded half up to the cent (`1.005` →
146
+ * `101`, `0.125` → `13`).
147
+ */
148
+ export function centsFromMajor(value: unknown): number | null {
149
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
150
+ return Math.round(Number((value * 100).toPrecision(12)));
151
+ }
@@ -0,0 +1,51 @@
1
+ import type { CatalogueReadResult } from "./catalogue-read-port";
2
+ import { connectionMerchantId, readOutboundConnection } from "./integration";
3
+ import type { EngineContext } from "./ports";
4
+ import type { MarketplaceProvider } from "./types";
5
+
6
+ /**
7
+ * Reading the menu a store keeps on a marketplace, as a host calls it
8
+ * (FUT-951): through the store's OWN connection (its merchant id and its
9
+ * sealed credentials), with the adapter's `catalogueReader`. Nothing is
10
+ * stamped or queued: the read is a question the host asks while the store
11
+ * waits, and it answers the snapshot or why there is none.
12
+ */
13
+ export async function readMarketplaceCatalogue(
14
+ ctx: EngineContext,
15
+ input: { clientId: string; provider: MarketplaceProvider; now?: Date },
16
+ ): Promise<CatalogueReadResult> {
17
+ const reader = ctx.registry.get(input.provider)?.catalogueReader;
18
+ if (!reader) return engineRefusal("UNSUPPORTED");
19
+ const merchantId = await connectionMerchantId(ctx, input.clientId, input.provider);
20
+ if (merchantId === null) return engineRefusal("NOT_CONNECTED");
21
+ let connection: Awaited<ReturnType<typeof readOutboundConnection>>;
22
+ try {
23
+ connection = await readOutboundConnection(ctx, input.clientId, input.provider);
24
+ } catch (error) {
25
+ ctx.ports.logger.error(
26
+ `marketplace.catalogue-read: ${input.provider} credentials of ${input.clientId} do not open: ` +
27
+ (error instanceof Error ? error.message : String(error)),
28
+ );
29
+ return engineRefusal("CREDENTIALS");
30
+ }
31
+ if (!connection) return engineRefusal("CREDENTIALS");
32
+ try {
33
+ return await reader.read({
34
+ ...connection,
35
+ http: ctx.ports.http,
36
+ tokens: ctx.tokens,
37
+ now: input.now ?? ctx.ports.clock.now(),
38
+ externalMerchantId: merchantId,
39
+ });
40
+ } catch (error) {
41
+ // The port says an adapter never throws; one that does is asked again later, not crashed on.
42
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
43
+ }
44
+ }
45
+
46
+ const engineRefusal = (code: "UNSUPPORTED" | "NOT_CONNECTED" | "CREDENTIALS"): CatalogueReadResult => ({
47
+ kind: "refused",
48
+ code,
49
+ status: null,
50
+ message: null,
51
+ });
@@ -32,6 +32,8 @@ import {
32
32
  } from "./catalogue";
33
33
  import { runCatalogue, type CatalogueJobPayload, type CatalogueOutcome } from "./catalogue-job";
34
34
  import type { CatalogueMenuOptions } from "./catalogue-port";
35
+ import { readMarketplaceCatalogue } from "./catalogue-read";
36
+ import type { CatalogueReadResult } from "./catalogue-read-port";
35
37
  import type { CataloguePublicationView } from "./catalogue-store";
36
38
  import {
37
39
  runFetchOrder,
@@ -58,6 +60,18 @@ import {
58
60
  } from "./integration";
59
61
  import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
60
62
  import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
63
+ import {
64
+ availabilityState,
65
+ pauseStore,
66
+ resumeStore,
67
+ type PauseStoreInput,
68
+ type PauseStoreResult,
69
+ type ResumeOutcome,
70
+ type StoreAvailabilityView,
71
+ } from "./pause";
72
+ import { runAvailability, type AvailabilityOutcome } from "./pause-job";
73
+ import type { AvailabilityJobPayload } from "./pause-store";
74
+ import { sweepAvailability, type AvailabilitySweepResult } from "./pause-sweep";
61
75
  import type { OutboundJobPayload } from "./outbound-queue";
62
76
  import {
63
77
  normalizeEvent,
@@ -206,8 +220,33 @@ export interface MarketplaceEngine {
206
220
  provider: MarketplaceProvider;
207
221
  options: CatalogueMenuOptions;
208
222
  }): Promise<CatalogueDocumentResult>;
223
+ /**
224
+ * Read the menu the store keeps on a marketplace, through its own
225
+ * connection (FUT-951): the snapshot, a final refusal, or a `retry` (429,
226
+ * 5xx, a timeout). Calls the marketplace at once; nothing is queued.
227
+ */
228
+ readCatalogue(input: { clientId: string; provider: MarketplaceProvider; now?: Date }): Promise<CatalogueReadResult>;
209
229
  /** Run one queued publish or withdraw (the `marketplace.catalogue` job's body). */
210
230
  runCatalogue(payload: CatalogueJobPayload, attempt: OutboundAttempt): Promise<CatalogueOutcome>;
231
+
232
+ /**
233
+ * The kitchen paused (or renewed its pause): close the store until `until`
234
+ * on every live connection whose marketplace can be paused (FUT-4851).
235
+ * Idempotent: the `until` already standing does nothing; any other, an
236
+ * earlier one included, renews the closure.
237
+ */
238
+ pauseStore(input: PauseStoreInput): Promise<PauseStoreResult>;
239
+ /** The kitchen's pause is over: delete every closure the engine created, and nothing else. */
240
+ resumeStore(input: {
241
+ clientId: string;
242
+ now?: Date;
243
+ }): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }>;
244
+ /** Where the store's pause stands on each marketplace, for the screen. */
245
+ availabilityState(clientId: string): Promise<StoreAvailabilityView[]>;
246
+ /** Bring one marketplace in line with the last ask (the `marketplace.availability` job's body). */
247
+ runAvailability(payload: AvailabilityJobPayload, attempt: OutboundAttempt): Promise<AvailabilityOutcome>;
248
+ /** Expire, re-queue and give up on store pauses (the `marketplace.availability-sweep` job's body). */
249
+ sweepAvailability(now?: Date): Promise<AvailabilitySweepResult>;
211
250
  }
212
251
 
213
252
  /**
@@ -279,5 +318,12 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
279
318
  catalogueState: (input) => readCatalogueState(ctx, input),
280
319
  catalogueDocument: (input) => readCatalogueDocument(ctx, input),
281
320
  runCatalogue: (payload, attempt) => runCatalogue(ctx, payload, attempt),
321
+ readCatalogue: (input) => readMarketplaceCatalogue(ctx, input),
322
+
323
+ pauseStore: (input) => pauseStore(ctx, input),
324
+ resumeStore: (input) => resumeStore(ctx, input),
325
+ availabilityState: (clientId) => availabilityState(ctx, clientId),
326
+ runAvailability: (payload, attempt) => runAvailability(ctx, payload, attempt),
327
+ sweepAvailability: (now) => sweepAvailability(ctx, now ?? ports.clock.now()),
282
328
  };
283
329
  }