@12-apps/marketplace 1.3.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 (53) hide show
  1. package/ADOPTING.md +47 -0
  2. package/README.md +71 -0
  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-B8QtQ2RA.d.ts} +126 -3
  7. package/dist/{chunk-AYYBRQJV.js → chunk-DPCZVN2C.js} +43 -3
  8. package/dist/chunk-DPCZVN2C.js.map +1 -0
  9. package/dist/{chunk-XUAFXNOH.js → chunk-EBAIZQPB.js} +395 -4
  10. package/dist/chunk-EBAIZQPB.js.map +1 -0
  11. package/dist/{chunk-RVBTARIY.js → chunk-SZRZTLVU.js} +1 -1
  12. package/dist/chunk-SZRZTLVU.js.map +1 -0
  13. package/dist/{engine-CZsP8KWd.d.ts → engine-o5cm54vC.d.ts} +242 -2
  14. package/dist/hono/index.d.ts +2 -2
  15. package/dist/hono/index.js +2 -2
  16. package/dist/ifood/index.d.ts +14 -2
  17. package/dist/ifood/index.js +164 -1
  18. package/dist/ifood/index.js.map +1 -1
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +300 -3
  21. package/dist/index.js.map +1 -1
  22. package/dist/manifest/server.d.ts +4 -2
  23. package/dist/manifest/server.js +2 -2
  24. package/dist/rappi/index.d.ts +15 -2
  25. package/dist/rappi/index.js +56 -2
  26. package/dist/rappi/index.js.map +1 -1
  27. package/dist/server/index.d.ts +18 -7
  28. package/dist/server/index.js +4 -2
  29. package/package.json +1 -1
  30. package/prisma/marketplace.prisma +67 -1
  31. package/prisma/migrations/20261113230000_marketplace_store_pause/migration.sql +70 -0
  32. package/src/99food/index.ts +10 -0
  33. package/src/99food/pause.ts +56 -0
  34. package/src/core/adapter.ts +12 -2
  35. package/src/core/engine.ts +37 -0
  36. package/src/core/pause-job.ts +381 -0
  37. package/src/core/pause-port.ts +110 -0
  38. package/src/core/pause-retired.ts +139 -0
  39. package/src/core/pause-store.ts +151 -0
  40. package/src/core/pause-sweep.ts +148 -0
  41. package/src/core/pause.ts +316 -0
  42. package/src/core/ports.ts +11 -0
  43. package/src/ifood/index.ts +4 -0
  44. package/src/ifood/pause.ts +257 -0
  45. package/src/index.ts +24 -0
  46. package/src/rappi/index.ts +11 -0
  47. package/src/rappi/outbound.ts +2 -2
  48. package/src/rappi/pause.ts +98 -0
  49. package/src/server/index.ts +1 -0
  50. package/src/server/jobs.ts +64 -4
  51. package/dist/chunk-AYYBRQJV.js.map +0 -1
  52. package/dist/chunk-RVBTARIY.js.map +0 -1
  53. package/dist/chunk-XUAFXNOH.js.map +0 -1
@@ -0,0 +1,316 @@
1
+ import type { EngineContext } from "./ports";
2
+ import {
3
+ availabilityDedupeKey,
4
+ enqueueAvailability,
5
+ holdsSomething,
6
+ pauseTable,
7
+ readPause,
8
+ type StorePauseFailureCode,
9
+ type StorePauseRow,
10
+ type StorePauseState,
11
+ type StorePauseWanted,
12
+ } from "./pause-store";
13
+ import type { MarketplaceProvider } from "./types";
14
+
15
+ /**
16
+ * The store pause, as the host calls it (FUT-4851): `pauseStore` when the
17
+ * kitchen pauses and on every renewal, `resumeStore` the moment the pause is
18
+ * over, `availabilityState` for the screen. The host owns the debounce; these
19
+ * calls only record the ask and queue `marketplace.availability`, whose job
20
+ * makes the calls (`./pause-job.ts`). No path that answers a request reaches
21
+ * a marketplace.
22
+ */
23
+
24
+ /** What `pauseStore` did on one marketplace. */
25
+ export type PauseOutcome =
26
+ /** The ask was recorded and the job queued. */
27
+ | "queued"
28
+ /** A pause with exactly this end already stands or is on its way. */
29
+ | "unchanged"
30
+ /** The marketplace's adapter cannot pause a store: the host says so. */
31
+ | "unsupported"
32
+ /** The connection has no credentials or no merchant id. */
33
+ | "not-connected";
34
+
35
+ /** What `resumeStore` did on one marketplace. */
36
+ export type ResumeOutcome =
37
+ /** Something of ours stands on the marketplace: the job deletes it. */
38
+ | "queued"
39
+ /** Nothing of ours stands there: the record is OPEN, and nobody is called. */
40
+ | "open"
41
+ /** A resume is already on its way. */
42
+ | "unchanged";
43
+
44
+ export interface PauseStoreInput {
45
+ clientId: string;
46
+ /** The kitchen's estimated reopening time: the end every marketplace is given. */
47
+ until: Date;
48
+ /** The host's words for the closure (its copy, in the store's language). */
49
+ reason: string;
50
+ /** The store's IANA time zone. */
51
+ timeZone: string;
52
+ now?: Date;
53
+ }
54
+
55
+ export type PauseStoreResult =
56
+ | { kind: "invalid"; code: "UNTIL_NOT_FUTURE" | "TIME_ZONE_INVALID" }
57
+ | { kind: "ok"; marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] };
58
+
59
+ /** One marketplace's pause as the screen shows it. */
60
+ export interface StoreAvailabilityView {
61
+ provider: MarketplaceProvider;
62
+ /** The adapter can pause a store at all. */
63
+ supported: boolean;
64
+ /** `interruption` (an id and an end) or `switch` (on/off); null when unsupported. */
65
+ kind: "interruption" | "switch" | null;
66
+ /** The connection has credentials and a merchant id. */
67
+ connected: boolean;
68
+ state: StorePauseState;
69
+ wanted: StorePauseWanted;
70
+ /** The end the host asked for. */
71
+ until: Date | null;
72
+ /** The end the marketplace was given and confirmed. */
73
+ sentUntil: Date | null;
74
+ failureCode: StorePauseFailureCode | null;
75
+ /** The marketplace's own words, verbatim and cut; never copy to show as is. */
76
+ failureDetail: string | null;
77
+ pausedAt: Date | null;
78
+ resumedAt: Date | null;
79
+ updatedAt: Date | null;
80
+ }
81
+
82
+ interface ConnectionRow {
83
+ provider: string;
84
+ externalMerchantId: string | null;
85
+ credentials: string;
86
+ }
87
+
88
+ /** The store's live connections (enabled, not archived), with whether each can be called. */
89
+ async function liveConnections(ctx: EngineContext, clientId: string): Promise<ConnectionRow[]> {
90
+ const db = await ctx.ports.db();
91
+ return (await db.marketplaceIntegration.findMany({
92
+ where: { clientId, enabled: true, archivedAt: null },
93
+ select: { provider: true, externalMerchantId: true, credentials: true },
94
+ orderBy: { provider: "asc" },
95
+ })) as ConnectionRow[];
96
+ }
97
+
98
+ const isConnected = (row: ConnectionRow): boolean => row.credentials !== "" && Boolean(row.externalMerchantId);
99
+
100
+ /** Whether an IANA zone name is one this runtime knows. */
101
+ function validTimeZone(timeZone: string): boolean {
102
+ try {
103
+ new Intl.DateTimeFormat("en-US", { timeZone });
104
+ return timeZone !== "";
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Whether a pause with exactly this end already stands, or is on its way. An
112
+ * earlier end is asked like a later one: the store is never closed on a
113
+ * marketplace longer than the kitchen's own pause.
114
+ */
115
+ function alreadyAsked(row: StorePauseRow | null, until: Date): boolean {
116
+ if (!row || row.wanted !== "PAUSED") return false;
117
+ if (row.state !== "PAUSING" && row.state !== "PAUSED") return false;
118
+ return row.until !== null && row.until.getTime() === until.getTime();
119
+ }
120
+
121
+ /** Record one marketplace's pause and queue its job, unless it already stands. */
122
+ async function askPause(ctx: EngineContext, input: Required<PauseStoreInput>, provider: string): Promise<PauseOutcome> {
123
+ const existing = await readPause(ctx, input.clientId, provider);
124
+ if (alreadyAsked(existing, input.until)) return "unchanged";
125
+ const table = pauseTable(await ctx.ports.db());
126
+ const data = {
127
+ wanted: "PAUSED",
128
+ state: "PAUSING",
129
+ until: input.until,
130
+ reason: input.reason,
131
+ timeZone: input.timeZone,
132
+ requestedAt: input.now,
133
+ // No key is minted here: the job writes one just before its call, so a
134
+ // resume that lands first knows nothing of ours can stand there. A key
135
+ // still in doubt stays on the row (its create may have landed).
136
+ failureCode: null,
137
+ failureDetail: null,
138
+ failedAt: null,
139
+ };
140
+ await table.upsert({
141
+ where: { clientId_provider: { clientId: input.clientId, provider } },
142
+ create: { clientId: input.clientId, provider, ...data },
143
+ update: data,
144
+ });
145
+ const payload = { clientId: input.clientId, provider };
146
+ await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, input.now));
147
+ return "queued";
148
+ }
149
+
150
+ /**
151
+ * Pause the store on every live connection whose marketplace can be paused.
152
+ * Idempotent: a pause already standing (or on its way) with exactly this end
153
+ * does nothing; any other end renews it, an earlier one included. Called again
154
+ * on every renewal of the kitchen's pause.
155
+ */
156
+ export async function pauseStore(ctx: EngineContext, input: PauseStoreInput): Promise<PauseStoreResult> {
157
+ const now = input.now ?? ctx.ports.clock.now();
158
+ if (input.until.getTime() <= now.getTime()) return { kind: "invalid", code: "UNTIL_NOT_FUTURE" };
159
+ if (!validTimeZone(input.timeZone)) return { kind: "invalid", code: "TIME_ZONE_INVALID" };
160
+ pauseTable(await ctx.ports.db());
161
+ const full = { ...input, now };
162
+ const marketplaces: { provider: MarketplaceProvider; outcome: PauseOutcome }[] = [];
163
+ for (const connection of await liveConnections(ctx, input.clientId)) {
164
+ const adapter = ctx.registry.get(connection.provider);
165
+ let outcome: PauseOutcome;
166
+ if (!adapter?.availability) outcome = "unsupported";
167
+ else if (!isConnected(connection)) outcome = "not-connected";
168
+ else outcome = await askPause(ctx, full, connection.provider);
169
+ marketplaces.push({ provider: connection.provider, outcome });
170
+ }
171
+ if (marketplaces.some((entry) => entry.outcome === "queued")) ctx.ports.publishChanged(input.clientId);
172
+ return { kind: "ok", marketplaces };
173
+ }
174
+
175
+ /**
176
+ * Rewrite one record's ask to OPEN; queue the job when something of ours
177
+ * stands there OR may be on its way: a PAUSING record may have a call in
178
+ * flight whose key the job wrote after this read. The write is predicated on
179
+ * the key read, so a claim that lands in between makes this re-read.
180
+ */
181
+ async function askResume(ctx: EngineContext, read: StorePauseRow, now: Date): Promise<ResumeOutcome> {
182
+ let row: StorePauseRow | null = read;
183
+ for (let tries = 0; row && tries < 3; tries += 1) {
184
+ if (resumeAsked(row)) return "unchanged";
185
+ const outcome = await writeResume(ctx, row, now);
186
+ if (outcome !== null) return outcome;
187
+ row = await readPause(ctx, read.clientId, read.provider);
188
+ }
189
+ return row ? forceResume(ctx, row, now) : "unchanged";
190
+ }
191
+
192
+ /**
193
+ * Every predicated write missed (the row kept moving): the resume is never
194
+ * lost. RESUMING with no predicate, and the job queued: it re-reads the row
195
+ * and deletes whatever of ours stands, or finds nothing and settles OPEN.
196
+ */
197
+ async function forceResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome> {
198
+ const table = pauseTable(await ctx.ports.db());
199
+ await table.updateMany({
200
+ where: { id: row.id },
201
+ data: { wanted: "OPEN", state: "RESUMING", requestedAt: now, failureCode: null, failureDetail: null, failedAt: null },
202
+ });
203
+ const payload = { clientId: row.clientId, provider: row.provider };
204
+ await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));
205
+ return "queued";
206
+ }
207
+
208
+ /** Whether a resume already stands: on its way, or OPEN with nothing of ours left. */
209
+ function resumeAsked(row: StorePauseRow): boolean {
210
+ if (row.wanted !== "OPEN") return false;
211
+ return row.state === "RESUMING" || (row.state === "OPEN" && !holdsSomething(row));
212
+ }
213
+
214
+ /** The resume's write, predicated on the key read; null when the row moved under it. */
215
+ async function writeResume(ctx: EngineContext, row: StorePauseRow, now: Date): Promise<ResumeOutcome | null> {
216
+ const held = holdsSomething(row) || row.state === "PAUSING";
217
+ const table = pauseTable(await ctx.ports.db());
218
+ const moved = await table.updateMany({
219
+ where: { id: row.id, attemptKey: row.attemptKey },
220
+ data: {
221
+ wanted: "OPEN",
222
+ state: held ? "RESUMING" : "OPEN",
223
+ requestedAt: now,
224
+ failureCode: null,
225
+ failureDetail: null,
226
+ failedAt: null,
227
+ ...(held ? {} : { resumedAt: now }),
228
+ },
229
+ });
230
+ if (moved.count === 0) return null;
231
+ if (!held) return "open";
232
+ const payload = { clientId: row.clientId, provider: row.provider };
233
+ await enqueueAvailability(ctx, payload, availabilityDedupeKey(payload, now));
234
+ return "queued";
235
+ }
236
+
237
+ /**
238
+ * The kitchen's pause is over: open the store again wherever the engine
239
+ * closed it. Only what the engine created is deleted; a marketplace where
240
+ * nothing of ours stands is not called at all. Every record is answered,
241
+ * a connection disabled since the pause included.
242
+ */
243
+ export async function resumeStore(
244
+ ctx: EngineContext,
245
+ input: { clientId: string; now?: Date },
246
+ ): Promise<{ marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] }> {
247
+ const now = input.now ?? ctx.ports.clock.now();
248
+ const table = pauseTable(await ctx.ports.db());
249
+ const rows = (await table.findMany({
250
+ where: { clientId: input.clientId },
251
+ orderBy: { provider: "asc" },
252
+ })) as StorePauseRow[];
253
+ const marketplaces: { provider: MarketplaceProvider; outcome: ResumeOutcome }[] = [];
254
+ for (const row of rows) marketplaces.push({ provider: row.provider, outcome: await askResume(ctx, row, now) });
255
+ if (marketplaces.some((entry) => entry.outcome !== "unchanged")) ctx.ports.publishChanged(input.clientId);
256
+ return { marketplaces };
257
+ }
258
+
259
+ /** What a marketplace with no record reads as: OPEN, never asked. */
260
+ const NEVER_ASKED: Omit<StoreAvailabilityView, "provider" | "supported" | "kind" | "connected"> = {
261
+ state: "OPEN",
262
+ wanted: "OPEN",
263
+ until: null,
264
+ sentUntil: null,
265
+ failureCode: null,
266
+ failureDetail: null,
267
+ pausedAt: null,
268
+ resumedAt: null,
269
+ updatedAt: null,
270
+ };
271
+
272
+ function viewOf(ctx: EngineContext, provider: string, connection: ConnectionRow | undefined, row: StorePauseRow | undefined): StoreAvailabilityView {
273
+ const availability = ctx.registry.get(provider)?.availability;
274
+ const recorded = row
275
+ ? {
276
+ state: row.state,
277
+ wanted: row.wanted,
278
+ until: row.until,
279
+ sentUntil: row.sentUntil,
280
+ failureCode: row.failureCode,
281
+ failureDetail: row.failureDetail,
282
+ pausedAt: row.pausedAt,
283
+ resumedAt: row.resumedAt,
284
+ updatedAt: row.updatedAt,
285
+ }
286
+ : NEVER_ASKED;
287
+ return {
288
+ provider,
289
+ supported: availability !== undefined,
290
+ kind: availability?.kind ?? null,
291
+ connected: connection !== undefined && isConnected(connection),
292
+ ...recorded,
293
+ };
294
+ }
295
+
296
+ /**
297
+ * Where the store's pause stands on each marketplace: every live connection,
298
+ * plus any record of a connection since disabled that still holds something.
299
+ * A host on a database without the pause model reads every marketplace OPEN.
300
+ */
301
+ export async function availabilityState(ctx: EngineContext, clientId: string): Promise<StoreAvailabilityView[]> {
302
+ const db = await ctx.ports.db();
303
+ const connections = await liveConnections(ctx, clientId);
304
+ const rows = db.marketplaceStorePause
305
+ ? ((await db.marketplaceStorePause.findMany({ where: { clientId } })) as StorePauseRow[])
306
+ : [];
307
+ const byProvider = new Map(rows.map((row) => [row.provider, row]));
308
+ const views = connections.map((connection) =>
309
+ viewOf(ctx, connection.provider, connection, byProvider.get(connection.provider)),
310
+ );
311
+ const live = new Set(connections.map((connection) => connection.provider));
312
+ for (const row of rows) {
313
+ if (!live.has(row.provider) && holdsSomething(row)) views.push(viewOf(ctx, row.provider, undefined, row));
314
+ }
315
+ return views;
316
+ }
package/src/core/ports.ts CHANGED
@@ -70,6 +70,17 @@ export interface MarketplaceDb {
70
70
  create(args: unknown): Promise<unknown>;
71
71
  updateMany(args: unknown): Promise<{ count: number }>;
72
72
  };
73
+ /**
74
+ * OPTIONAL in the type, so a host on 1.x that has not yet composed the
75
+ * pause model still compiles; `pauseStore` refuses without it (FUT-4851,
76
+ * migration `20261113230000_marketplace_store_pause`).
77
+ */
78
+ marketplaceStorePause?: {
79
+ findFirst(args: unknown): Promise<unknown>;
80
+ findMany(args: unknown): Promise<unknown[]>;
81
+ upsert(args: unknown): Promise<unknown>;
82
+ updateMany(args: unknown): Promise<{ count: number }>;
83
+ };
73
84
  }
74
85
 
75
86
  /**
@@ -3,6 +3,7 @@ import { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from
3
3
  import { IFOOD_CATALOGUE } from "./catalogue";
4
4
  import { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
5
5
  import { IFOOD_PORTAL_URL, ifoodConfirm, ifoodRequestCancellation } from "./outbound";
6
+ import { IFOOD_AVAILABILITY } from "./pause";
6
7
 
7
8
  /**
8
9
  * `@12-apps/marketplace/ifood` — iFood, as one adapter on the engine.
@@ -67,6 +68,8 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
67
68
  catalogue: IFOOD_CATALOGUE,
68
69
  confirm: (ctx, order) => ifoodConfirm(ctx, order),
69
70
  requestCancellation: ifoodRequestCancellation,
71
+ // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
72
+ availability: IFOOD_AVAILABILITY,
70
73
  // No per-order deep link is known, so the portal, where a live order is
71
74
  // on the first screen.
72
75
  appLink: () => IFOOD_PORTAL_URL,
@@ -76,3 +79,4 @@ export function createIfoodAdapter(config: IfoodAdapterConfig): MarketplaceAdapt
76
79
  export { IFOOD_REASON_CODES, type IfoodAdapterCopy, type IfoodReasonCode } from "./copy";
77
80
  export { normalizeIfoodEvent, verifyIfoodSignature } from "./normalize";
78
81
  export { IFOOD_CATALOGUE, ifoodItemBody, ifoodItemId, ifoodProductId } from "./catalogue";
82
+ export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
@@ -0,0 +1,257 @@
1
+ import {
2
+ answered,
3
+ outboundResultOf,
4
+ type AdapterCallContext,
5
+ type MarketplaceHttpRequest,
6
+ type MarketplaceHttpResponse,
7
+ type OutboundResult,
8
+ } from "../core/adapter";
9
+ import type { MarketplaceAvailability, StorePauseRef, StorePauseRequest, StorePauseResult } from "../core/pause-port";
10
+ import { IFOOD_API, bearer, ifoodTokenKey } from "./outbound";
11
+
12
+ /**
13
+ * iFood's half of the store pause (FUT-4851): the Merchant API's
14
+ * INTERRUPTIONS, a closure with its own id, a start and an end, that does not
15
+ * touch the store's opening hours.
16
+ *
17
+ * - List: `GET /merchant/v1.0/merchants/{merchantId}/interruptions`
18
+ * (active and future interruptions).
19
+ * - Create: `POST …/interruptions` with `{ id, description, start, end }`,
20
+ * 201 with the interruption.
21
+ * - Delete: `DELETE …/interruptions/{interruptionId}`, 204.
22
+ *
23
+ * iFood's developer portal refuses our reader (403), so the paths, verbs and
24
+ * the body's `description`/`start`/`end` come from two public third-party
25
+ * clients of the API (README, "Pausing a store"): ESTIMATED until the
26
+ * homologation run. Also ESTIMATED: that iFood takes the client's own `id`.
27
+ * It is sent, but the adapter does not rely on it: every create is preceded
28
+ * by a list, and an interruption is ours when it carries our id OR, where
29
+ * iFood assigned its own, exactly the end and the description the create
30
+ * sent, so a retry after a lost answer never makes a second one and a resume
31
+ * by key deletes the one that landed. An interruption the owner made by hand
32
+ * is neither. ESTIMATED too: that there is no call to move an interruption's
33
+ * end (so no `extend`: the engine creates the new one, then deletes the old);
34
+ * that iFood ACCEPTS the two overlapping for that moment (if it refuses an
35
+ * overlap, the renewal is FAILED with iFood's words and the old interruption
36
+ * still holds to its own end); and how iFood reads a
37
+ * time: one client says the offset is discarded and the time read as the
38
+ * store's own clock, so the time goes out as the store's wall clock WITH its
39
+ * offset, which reads the same either way. A 404 on delete is "already gone".
40
+ */
41
+
42
+ const interruptionsUrl = (merchantId: string): string =>
43
+ `${IFOOD_API}/merchant/v1.0/merchants/${encodeURIComponent(merchantId)}/interruptions`;
44
+
45
+ type Settled = Exclude<OutboundResult, { kind: "accepted" }>;
46
+
47
+ /** One authenticated call: the raw answer, or the result that ends it. */
48
+ async function call(
49
+ ctx: AdapterCallContext,
50
+ request: Omit<MarketplaceHttpRequest, "headers"> & { json?: unknown },
51
+ ): Promise<MarketplaceHttpResponse | Settled> {
52
+ const auth = await bearer(ctx);
53
+ if (!("token" in auth)) return auth.kind === "accepted" ? { kind: "retry", reason: "unexpected token answer" } : auth;
54
+ const response = await ctx.http({
55
+ method: request.method,
56
+ url: request.url,
57
+ headers: {
58
+ Authorization: `Bearer ${auth.token}`,
59
+ ...(request.json === undefined ? {} : { "Content-Type": "application/json" }),
60
+ },
61
+ ...(request.json === undefined ? {} : { body: JSON.stringify(request.json) }),
62
+ });
63
+ // A 401 is a token that went stale under us: forget it, and the retry fetches another.
64
+ if (response.status !== 401) return response;
65
+ ctx.tokens.delete(ifoodTokenKey(ctx));
66
+ return { kind: "retry", reason: "iFood refused the token" };
67
+ }
68
+
69
+ const settled = (value: MarketplaceHttpResponse | Settled): value is Settled => "kind" in value;
70
+
71
+ /** The answer as anything but 2xx, read the engine's way. */
72
+ function notOk(response: MarketplaceHttpResponse): Settled | null {
73
+ const result = outboundResultOf(response);
74
+ return result.kind === "accepted" ? null : result;
75
+ }
76
+
77
+ /** One interruption as the list answers it, read defensively. */
78
+ interface Interruption {
79
+ id: string;
80
+ end: string | null;
81
+ description: string | null;
82
+ }
83
+
84
+ /** The interruptions on the merchant, or the result that ends the call. */
85
+ async function listInterruptions(ctx: AdapterCallContext, merchantId: string): Promise<Interruption[] | Settled> {
86
+ const response = await call(ctx, { method: "GET", url: interruptionsUrl(merchantId) });
87
+ if (settled(response)) return response;
88
+ const failure = notOk(response);
89
+ if (failure) return failure;
90
+ try {
91
+ const parsed = JSON.parse(response.body === "" ? "[]" : response.body) as unknown;
92
+ if (!Array.isArray(parsed)) return [];
93
+ return parsed.flatMap((entry: unknown) => {
94
+ const value = (entry ?? {}) as { id?: unknown; end?: unknown; description?: unknown };
95
+ if (typeof value.id !== "string") return [];
96
+ return [
97
+ {
98
+ id: value.id,
99
+ end: typeof value.end === "string" ? value.end : null,
100
+ description: typeof value.description === "string" ? value.description : null,
101
+ },
102
+ ];
103
+ });
104
+ } catch {
105
+ return { kind: "retry", reason: "iFood answered the interruption list with something that is not JSON" };
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Whether iFood's `end` is the instant the create sent. An `end` that states
111
+ * its zone (`Z` or an offset) is compared as an instant, and only as one: an
112
+ * owner's interruption at another instant is never claimed because its digits
113
+ * look like ours. Only an `end` with no zone (iFood echoing the store's own
114
+ * clock) is compared as the store's wall clock.
115
+ */
116
+ function sameEnd(end: string, until: Date, timeZone: string): boolean {
117
+ const sent = ifoodLocalTime(until, timeZone);
118
+ if (end === sent) return true;
119
+ if (/(?:[zZ]|[+-]\d{2}:?\d{2})$/u.test(end)) {
120
+ const parsed = Date.parse(end);
121
+ return !Number.isNaN(parsed) && Math.floor(parsed / 1000) === Math.floor(until.getTime() / 1000);
122
+ }
123
+ return end.slice(0, 19) === sent.slice(0, 19);
124
+ }
125
+
126
+ /**
127
+ * The interruption the create under `key` made: by our id, or by the end and
128
+ * description it carried, never one the engine already holds (`keep`).
129
+ */
130
+ function ours(
131
+ list: readonly Interruption[],
132
+ key: string,
133
+ sent: { until: Date; reason: string; timeZone: string } | null,
134
+ keep: readonly string[] = [],
135
+ ): Interruption | undefined {
136
+ const candidates = list.filter((entry) => !keep.includes(entry.id));
137
+ const byKey = candidates.find((entry) => entry.id === key);
138
+ if (byKey || !sent) return byKey;
139
+ return candidates.find(
140
+ (entry) => entry.description === sent.reason && entry.end !== null && sameEnd(entry.end, sent.until, sent.timeZone),
141
+ );
142
+ }
143
+
144
+ interface WallClock {
145
+ year: number;
146
+ month: number;
147
+ day: number;
148
+ hour: number;
149
+ minute: number;
150
+ second: number;
151
+ }
152
+
153
+ /** The wall clock of `date` in `timeZone`. */
154
+ function wallClock(date: Date, timeZone: string): WallClock {
155
+ const format = new Intl.DateTimeFormat("en-US", {
156
+ timeZone,
157
+ hourCycle: "h23",
158
+ year: "numeric",
159
+ month: "2-digit",
160
+ day: "2-digit",
161
+ hour: "2-digit",
162
+ minute: "2-digit",
163
+ second: "2-digit",
164
+ });
165
+ const clock: WallClock = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
166
+ for (const part of format.formatToParts(date)) {
167
+ if (part.type in clock) clock[part.type as keyof WallClock] = Number(part.value);
168
+ }
169
+ return clock;
170
+ }
171
+
172
+ const pad = (value: number, width = 2): string => String(value).padStart(width, "0");
173
+
174
+ /**
175
+ * `date` as the store's wall clock with its offset: `2026-11-13T15:30:00-03:00`.
176
+ * Read the same whether iFood honours the offset or reads the store's clock.
177
+ */
178
+ export function ifoodLocalTime(date: Date, timeZone: string): string {
179
+ const local = wallClock(date, timeZone);
180
+ const asUtc = Date.UTC(local.year, local.month - 1, local.day, local.hour, local.minute, local.second);
181
+ const offset = Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60_000);
182
+ const abs = Math.abs(offset);
183
+ return (
184
+ `${pad(local.year, 4)}-${pad(local.month)}-${pad(local.day)}` +
185
+ `T${pad(local.hour)}:${pad(local.minute)}:${pad(local.second)}` +
186
+ `${offset < 0 ? "-" : "+"}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
187
+ );
188
+ }
189
+
190
+ /** The created interruption's id: iFood's answer, else the one the engine sent. */
191
+ function createdId(body: string, sent: string): string {
192
+ try {
193
+ const id = (JSON.parse(body) as { id?: unknown }).id;
194
+ return typeof id === "string" && id !== "" ? id : sent;
195
+ } catch {
196
+ return sent;
197
+ }
198
+ }
199
+
200
+ /** Close the store until `request.until`: find one a lost answer created under the key, else create it. */
201
+ export function ifoodPause(ctx: AdapterCallContext, request: StorePauseRequest): Promise<StorePauseResult> {
202
+ return answeredPause(async () => {
203
+ const list = await listInterruptions(ctx, request.merchantId);
204
+ if (!Array.isArray(list)) return list;
205
+ const landed = ours(list, request.key, { until: request.until, reason: request.reason, timeZone: request.timeZone }, request.keep);
206
+ if (landed) return { kind: "paused", externalId: landed.id, until: request.until };
207
+ const response = await call(ctx, {
208
+ method: "POST",
209
+ url: interruptionsUrl(request.merchantId),
210
+ json: {
211
+ id: request.key,
212
+ description: request.reason,
213
+ start: ifoodLocalTime(ctx.now, request.timeZone),
214
+ end: ifoodLocalTime(request.until, request.timeZone),
215
+ },
216
+ });
217
+ if (settled(response)) return response;
218
+ const failure = notOk(response);
219
+ if (failure) return failure;
220
+ return { kind: "paused", externalId: createdId(response.body, request.key), until: request.until };
221
+ });
222
+ }
223
+
224
+ /** Delete THIS interruption: by its id, or the one a lost answer created under the key (by id, or by its end and description). */
225
+ export function ifoodResume(ctx: AdapterCallContext, ref: StorePauseRef): Promise<OutboundResult> {
226
+ return answered(async () => {
227
+ let id = ref.externalId;
228
+ if (id === null && ref.key !== null) {
229
+ const list = await listInterruptions(ctx, ref.merchantId);
230
+ if (!Array.isArray(list)) return list;
231
+ id = ours(list, ref.key, ref.sent, ref.keep)?.id ?? null;
232
+ }
233
+ // Nothing of ours stands: there is nothing to delete.
234
+ if (id === null) return { kind: "accepted" };
235
+ const response = await call(ctx, { method: "DELETE", url: `${interruptionsUrl(ref.merchantId)}/${encodeURIComponent(id)}` });
236
+ if (settled(response)) return response;
237
+ // Already gone: it ended, or a person removed it.
238
+ if (response.status === 404) return { kind: "accepted" };
239
+ return outboundResultOf(response);
240
+ });
241
+ }
242
+
243
+ /** {@link answered} for a pause: a call that never got an answer is a retry. */
244
+ async function answeredPause(run: () => Promise<StorePauseResult>): Promise<StorePauseResult> {
245
+ try {
246
+ return await run();
247
+ } catch (error) {
248
+ return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
249
+ }
250
+ }
251
+
252
+ /** iFood's availability capability: interruptions, no extend. */
253
+ export const IFOOD_AVAILABILITY: MarketplaceAvailability = {
254
+ kind: "interruption",
255
+ pause: ifoodPause,
256
+ resume: ifoodResume,
257
+ };
package/src/index.ts CHANGED
@@ -169,3 +169,27 @@ export type {
169
169
  CatalogueStatus,
170
170
  } from "./core/catalogue-store";
171
171
  export { CATALOGUE_GIVE_UP_MS, CATALOGUE_STALE_MS } from "./core/catalogue-sweep";
172
+ export type {
173
+ MarketplaceAvailability,
174
+ StorePauseRef,
175
+ StorePauseRequest,
176
+ StorePauseResult,
177
+ } from "./core/pause-port";
178
+ export type {
179
+ PauseOutcome,
180
+ PauseStoreInput,
181
+ PauseStoreResult,
182
+ ResumeOutcome,
183
+ StoreAvailabilityView,
184
+ } from "./core/pause";
185
+ export { AvailabilityRetryError, type AvailabilityOutcome } from "./core/pause-job";
186
+ export {
187
+ MARKETPLACE_AVAILABILITY_JOB,
188
+ STORE_PAUSE_LEASE_MS,
189
+ availabilityDedupeKey,
190
+ type AvailabilityJobPayload,
191
+ type StorePauseFailureCode,
192
+ type StorePauseState,
193
+ type StorePauseWanted,
194
+ } from "./core/pause-store";
195
+ export type { AvailabilitySweepResult } from "./core/pause-sweep";
@@ -8,6 +8,7 @@ import {
8
8
  type RappiAmountUnit,
9
9
  } from "./normalize";
10
10
  import { rappiReject, rappiTake, type RappiBaseUrls } from "./outbound";
11
+ import { rappiAvailability } from "./pause";
11
12
 
12
13
  /**
13
14
  * `@12-apps/marketplace/rappi` — Rappi, as one adapter on the engine.
@@ -86,6 +87,14 @@ export interface RappiAdapterConfig {
86
87
  portalUrl: string;
87
88
  /** How Rappi states money for this host's country (see {@link RappiAmountUnit}). Required: ESTIMATED for Brazil. */
88
89
  amountUnit: RappiAmountUnit;
90
+ /**
91
+ * OPTIONAL, off by default. Offer the store pause (FUT-4851) through Rappi's
92
+ * store on/off switch. A switch has no id, so the engine cannot tell its own
93
+ * closure from one the owner made by hand meanwhile: a store the owner also
94
+ * turned off on Rappi during the kitchen's pause is turned on with it. A
95
+ * host turns this on knowing that.
96
+ */
97
+ pauseByStoreSwitch?: boolean;
89
98
  }
90
99
 
91
100
  function assertHttps(name: string, url: string): void {
@@ -147,6 +156,7 @@ export function createRappiAdapter(config: RappiAdapterConfig): MarketplaceAdapt
147
156
  confirm: (ctx, order, input) => rappiTake(ctx, hosts, order, input),
148
157
  requestCancellation: (ctx, order, input) => rappiReject(ctx, hosts, order, input),
149
158
  appLink: () => config.portalUrl,
159
+ ...(config.pauseByStoreSwitch ? { availability: rappiAvailability(hosts) } : {}),
150
160
  };
151
161
  }
152
162
 
@@ -159,3 +169,4 @@ export {
159
169
  type RappiNormalizeOptions,
160
170
  } from "./normalize";
161
171
  export type { RappiBaseUrls, RappiHosts } from "./outbound";
172
+ export { rappiAvailability, rappiSetStoreEnabled } from "./pause";