@12-apps/marketplace 1.16.0 → 1.18.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 (79) hide show
  1. package/ADOPTING.md +185 -0
  2. package/dist/99food/index.d.ts +2 -2
  3. package/dist/99food/index.js +2 -2
  4. package/dist/{adapter-CjVdMhZ2.d.ts → adapter-ZpAWKoCk.d.ts} +300 -3
  5. package/dist/{chunk-TRUK5ZBE.js → chunk-3B5EULS6.js} +2 -2
  6. package/dist/{chunk-DJIMUEHT.js → chunk-BLHZ3MRB.js} +79 -7
  7. package/dist/chunk-BLHZ3MRB.js.map +1 -0
  8. package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
  9. package/dist/chunk-LO7OKO6V.js.map +1 -0
  10. package/dist/{chunk-TICWLBSA.js → chunk-MDEIRGNL.js} +1372 -823
  11. package/dist/chunk-MDEIRGNL.js.map +1 -0
  12. package/dist/{chunk-H2VQRD3B.js → chunk-Q5RMVNU5.js} +1 -1
  13. package/dist/chunk-Q5RMVNU5.js.map +1 -0
  14. package/dist/{chunk-BTKVZAJI.js → chunk-ZT6TZTLD.js} +1 -1
  15. package/dist/chunk-ZT6TZTLD.js.map +1 -0
  16. package/dist/{client-DgzCkl8u.d.ts → client-DpEq0yXb.d.ts} +1 -1
  17. package/dist/{engine-DSRj7qnC.d.ts → engine-DRRhAjZK.d.ts} +566 -293
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +4 -4
  20. package/dist/ifood/index.d.ts +14 -2
  21. package/dist/ifood/index.js +406 -120
  22. package/dist/ifood/index.js.map +1 -1
  23. package/dist/index.d.ts +21 -4
  24. package/dist/index.js +453 -43
  25. package/dist/index.js.map +1 -1
  26. package/dist/keeta/index.d.ts +2 -2
  27. package/dist/keeta/index.js +2 -2
  28. package/dist/manifest/index.d.ts +78 -0
  29. package/dist/manifest/index.js +1 -1
  30. package/dist/manifest/server.d.ts +6 -2
  31. package/dist/manifest/server.js +4 -4
  32. package/dist/rappi/index.d.ts +1 -1
  33. package/dist/rappi/index.js +1 -1
  34. package/dist/server/index.d.ts +93 -7
  35. package/dist/server/index.js +4 -4
  36. package/package.json +1 -1
  37. package/prisma/marketplace.prisma +70 -2
  38. package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
  39. package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
  40. package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
  41. package/src/core/adapter.ts +14 -2
  42. package/src/core/app-linking.ts +396 -0
  43. package/src/core/delivery-code.ts +119 -0
  44. package/src/core/dispute-engine.ts +32 -0
  45. package/src/core/dispute-job.ts +142 -0
  46. package/src/core/dispute-port.ts +133 -0
  47. package/src/core/dispute-store.ts +203 -0
  48. package/src/core/disputes.ts +263 -0
  49. package/src/core/engine.ts +12 -55
  50. package/src/core/integration.ts +3 -1
  51. package/src/core/link-engine.ts +176 -0
  52. package/src/core/link-store.ts +15 -0
  53. package/src/core/linking-port.ts +35 -1
  54. package/src/core/linking.ts +8 -0
  55. package/src/core/logistics.ts +388 -0
  56. package/src/core/outbound-queue.ts +6 -1
  57. package/src/core/outbound-sweep.ts +19 -6
  58. package/src/core/outbound.ts +4 -5
  59. package/src/core/pipeline.ts +14 -4
  60. package/src/core/ports.ts +20 -2
  61. package/src/core/status-job.ts +3 -0
  62. package/src/core/status-store.ts +2 -1
  63. package/src/core/types.ts +10 -0
  64. package/src/ifood/app-linking.ts +119 -0
  65. package/src/ifood/disputes.ts +209 -0
  66. package/src/ifood/index.ts +15 -1
  67. package/src/ifood/logistics.ts +38 -0
  68. package/src/ifood/normalize.ts +14 -1
  69. package/src/index.ts +44 -0
  70. package/src/server/jobs.ts +51 -3
  71. package/src/server/link-routes.ts +56 -4
  72. package/src/server/mcp-link.ts +44 -2
  73. package/src/server/mcp.ts +2 -1
  74. package/dist/chunk-BTKVZAJI.js.map +0 -1
  75. package/dist/chunk-DJIMUEHT.js.map +0 -1
  76. package/dist/chunk-H2VQRD3B.js.map +0 -1
  77. package/dist/chunk-SGOTN5PX.js.map +0 -1
  78. package/dist/chunk-TICWLBSA.js.map +0 -1
  79. /package/dist/{chunk-TRUK5ZBE.js.map → chunk-3B5EULS6.js.map} +0 -0
@@ -1,7 +1,9 @@
1
1
  import type { MarketplaceCatalogue } from "./catalogue-port";
2
2
  import type { MarketplaceCourierApi } from "./courier-port";
3
+ import type { MarketplaceDisputeApi } from "./dispute-port";
3
4
  import type { CatalogueReader } from "./catalogue-read-port";
4
- import type { MarketplaceLinking } from "./linking-port";
5
+ import type { MarketplaceAppLinking, MarketplaceLinking } from "./linking-port";
6
+ import type { LogisticsAdapter } from "./logistics";
5
7
  import type { MarketplaceAvailability } from "./pause-port";
6
8
  import type {
7
9
  MarketplaceDeliveredBy,
@@ -112,6 +114,8 @@ export interface MarketplaceCapabilities {
112
114
  * it has not confirmed). Absent: steps never wait on the confirm.
113
115
  */
114
116
  statusAfterConfirm?: boolean;
117
+ /** OPTIONAL (FUT-6099). The buyer's disputes arrive as events and are answered through `disputes`. */
118
+ disputes?: boolean;
115
119
  }
116
120
 
117
121
  /**
@@ -239,7 +243,7 @@ export interface CancellationRequestInput {
239
243
  }
240
244
 
241
245
  /** One marketplace, in and out. */
242
- export interface MarketplaceAdapter {
246
+ export interface MarketplaceAdapter extends LogisticsAdapter {
243
247
  readonly provider: MarketplaceProvider;
244
248
  readonly capabilities: MarketplaceCapabilities;
245
249
  /** Inbound: one delivery into the canonical shape, or null when it carries no order id. */
@@ -338,11 +342,19 @@ export interface MarketplaceAdapter {
338
342
  * marketplace (FUT-5613). Absent: a store connects with its own credentials only.
339
343
  */
340
344
  readonly linking?: MarketplaceLinking;
345
+ /**
346
+ * OPTIONAL. Linking a store through the software's CENTRALIZED app (FUT-5798):
347
+ * the store authorizes the app on the portal and picks its store from the
348
+ * app's list; no code, no token of its own. Wins over `linking` when both are set.
349
+ */
350
+ readonly appLinking?: MarketplaceAppLinking;
341
351
  /**
342
352
  * OPTIONAL. The marketplace's own courier (FUT-5665): the pickup-code check
343
353
  * and the tracking read. Absent: neither is offered, and the host says so.
344
354
  */
345
355
  readonly courier?: MarketplaceCourierApi;
356
+ /** OPTIONAL (FUT-6099). Answering the buyer's disputes; present with `capabilities.disputes`. */
357
+ readonly disputes?: MarketplaceDisputeApi;
346
358
  /** Where "open it on the marketplace" goes: the order when `perOrderAppLink`, else the portal. Always https. */
347
359
  appLink(order: Pick<OutboundOrderRef, "externalOrderId" | "externalDisplayId">): string;
348
360
  }
@@ -0,0 +1,396 @@
1
+ import { listMarketplaceIntegrations, type MarketplaceIntegrationView } from "./integration";
2
+ import { appCredentialsOf, sealAppLink } from "./link-store";
3
+ import type { LinkFailure, LinkRefusalCode } from "./linking";
4
+ import type { AppLinkCallContext, LinkedMerchant, MarketplaceAppLinking, MarketplaceLinkAttemptDelegate } from "./linking-port";
5
+ import { MarketplaceMerchantTakenError, guardMerchantClaim, isUniqueViolation } from "./merchant-claim";
6
+ import type { EngineContext, MarketplaceDb } from "./ports";
7
+ import type { MarketplaceProvider } from "./types";
8
+
9
+ /**
10
+ * Linking a store through the software's CENTRALIZED app (FUT-5798).
11
+ *
12
+ * The store authorizes the app on the marketplace's portal. From then on the
13
+ * app's own client-credentials token lists that store among the ones it may
14
+ * act for, and the store picks its own from the list: no code to type, nothing
15
+ * to paste, no token of the store's. The linked connection talks to the
16
+ * marketplace with the app's token, and the app's one webhook brings its orders.
17
+ *
18
+ * Between Conectar and the pick, the store has an ATTEMPT open (the
19
+ * `marketplace_link_attempts` row): it lives {@link ATTEMPT_MINUTES} minutes,
20
+ * renewed by every read the screen makes, and ends with Cancelar, a pick, or
21
+ * its expiry. While it is open the host's periodic job asks the list
22
+ * ({@link sweepAppLinks}) and records when it first showed a store this one
23
+ * may pick (`seenAt`), so the screen ticks itself through a realtime hint and
24
+ * never polls. A store another store's live connection holds is listed as
25
+ * `taken`, and is never a store this one may pick.
26
+ */
27
+
28
+ type Environment = "SANDBOX" | "PRODUCTION";
29
+
30
+ /** How long an attempt lives without a read: the portal's authorization can take ten minutes to reach the app. */
31
+ export const ATTEMPT_MINUTES = 30;
32
+ /** How often the list is asked while an attempt waits, at most. */
33
+ export const CHECK_EVERY_SECONDS = 30;
34
+
35
+ /** A centralized linking in progress, as a person sees it. */
36
+ export interface AppLinkPendingView {
37
+ /** Where the store authorizes the app. */
38
+ portalUrl: string;
39
+ expiresAt: Date;
40
+ /** When the app's list first showed a store this one may pick; null while waiting. */
41
+ seenAt: Date | null;
42
+ /** When the list was last asked; null before the first check. */
43
+ checkedAt: Date | null;
44
+ }
45
+
46
+ interface AttemptRow {
47
+ clientId: string;
48
+ provider: string;
49
+ environment: string;
50
+ verifier: string;
51
+ expiresAt: Date;
52
+ seenAt?: Date | null;
53
+ checkedAt?: Date | null;
54
+ }
55
+
56
+ interface Ready {
57
+ linking: MarketplaceAppLinking;
58
+ attempts: MarketplaceLinkAttemptDelegate;
59
+ call: AppLinkCallContext;
60
+ environment: Environment;
61
+ }
62
+
63
+ const refused = (code: LinkRefusalCode, status: number | null = null, message: string | null = null): LinkFailure => ({
64
+ kind: "refused",
65
+ code,
66
+ status,
67
+ message,
68
+ });
69
+
70
+ const keyOf = (clientId: string, provider: string) => ({ clientId_provider: { clientId, provider } });
71
+ const environmentOf = (value: string | undefined): Environment => (value === "SANDBOX" ? "SANDBOX" : "PRODUCTION");
72
+
73
+ /** Whether this marketplace links through a centralized app here. */
74
+ export function hasAppLinking(ctx: EngineContext, provider: MarketplaceProvider): boolean {
75
+ return ctx.registry.get(provider)?.appLinking !== undefined;
76
+ }
77
+
78
+ /** What a centralized linking call needs, or null when it is unavailable here. */
79
+ async function readyOf(ctx: EngineContext, provider: MarketplaceProvider, environment: Environment): Promise<Ready | null> {
80
+ const linking = ctx.registry.get(provider)?.appLinking;
81
+ if (!linking) return null;
82
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
83
+ if (!attempts) return null;
84
+ const app = await appCredentialsOf(ctx, provider, environment);
85
+ if (!app) return null;
86
+ const call = { http: ctx.ports.http, credentials: app, environment, now: ctx.ports.clock.now(), tokens: ctx.tokens };
87
+ return { linking, attempts, call, environment };
88
+ }
89
+
90
+ const pendingOf = (linking: MarketplaceAppLinking, row: AttemptRow): AppLinkPendingView => ({
91
+ portalUrl: linking.portalUrl,
92
+ expiresAt: row.expiresAt,
93
+ seenAt: row.seenAt ?? null,
94
+ checkedAt: row.checkedAt ?? null,
95
+ });
96
+
97
+ const isLive = (row: AttemptRow | null, now: Date): row is AttemptRow => row !== null && row.expiresAt.getTime() > now.getTime();
98
+ const renewed = (now: Date): Date => new Date(now.getTime() + ATTEMPT_MINUTES * 60_000);
99
+
100
+ async function liveAttempt(ready: Ready, clientId: string, provider: string): Promise<AttemptRow | null> {
101
+ const row = (await ready.attempts.findUnique({ where: keyOf(clientId, provider) })) as AttemptRow | null;
102
+ return isLive(row, ready.call.now) ? row : null;
103
+ }
104
+
105
+ /** The merchant ids another store's live connection holds, among `ids`. */
106
+ async function takenAmong(db: MarketplaceDb, clientId: string, provider: string, ids: readonly string[]): Promise<Set<string>> {
107
+ const held = await heldBy(db, provider, ids);
108
+ return new Set([...held].flatMap(([merchantId, holder]) => (holder === clientId ? [] : [merchantId])));
109
+ }
110
+
111
+ /** The app's list, each store judged `taken` or not, with its address when asked. */
112
+ async function listFor(
113
+ ctx: EngineContext,
114
+ ready: Ready,
115
+ input: { clientId: string; provider: string; addresses: boolean },
116
+ ): Promise<LinkedMerchant[] | LinkFailure> {
117
+ const listed = await ready.linking.merchants(ready.call);
118
+ if (listed.kind === "retry") return listed;
119
+ if (listed.kind === "refused") return refused("MARKETPLACE_REFUSED", listed.status, listed.message);
120
+ const taken = await takenAmong(await ctx.ports.db(), input.clientId, input.provider, listed.value.map((merchant) => merchant.id));
121
+ const judged = listed.value.map((merchant) => ({ ...merchant, taken: taken.has(merchant.id) }));
122
+ if (!input.addresses) return judged;
123
+ return withAddresses(ready, judged);
124
+ }
125
+
126
+ /** How many merchant details one list asks at once. */
127
+ const ADDRESS_CONCURRENCY = 4;
128
+
129
+ /**
130
+ * Each store this one may pick, with its address line; a taken store is shown
131
+ * by name only and costs no call. An address is a courtesy: one that does not
132
+ * answer leaves the card with the name and the id.
133
+ */
134
+ async function withAddresses(ready: Ready, judged: LinkedMerchant[]): Promise<LinkedMerchant[]> {
135
+ const out = judged.map((merchant) => ({ ...merchant, address: null as string | null }));
136
+ const queue = out.filter((merchant) => merchant.taken !== true);
137
+ const worker = async (): Promise<void> => {
138
+ for (let next = queue.shift(); next; next = queue.shift()) {
139
+ const answer = await ready.linking.address(ready.call, next.id).catch(() => null);
140
+ next.address = answer?.kind === "ok" ? answer.value : null;
141
+ }
142
+ };
143
+ await Promise.all(Array.from({ length: ADDRESS_CONCURRENCY }, worker));
144
+ return out;
145
+ }
146
+
147
+ const pickable = (merchants: readonly LinkedMerchant[]): boolean => merchants.some((merchant) => merchant.taken !== true);
148
+
149
+ /** Stamp a check on the attempt: renewed, asked now, and seen now if this is the first list with a store to pick. */
150
+ async function stamp(ready: Ready, row: AttemptRow, canPick: boolean, renew: boolean): Promise<AttemptRow> {
151
+ const now = ready.call.now;
152
+ const seen = row.seenAt ?? (canPick ? now : null);
153
+ const data = { checkedAt: now, seenAt: seen, ...(renew ? { expiresAt: renewed(now) } : {}) };
154
+ // Only the attempt that was read: a Cancelar or a new Conectar meanwhile is left as it is.
155
+ await ready.attempts.updateMany?.({ where: { clientId: row.clientId, provider: row.provider, verifier: row.verifier }, data });
156
+ return { ...row, ...data };
157
+ }
158
+
159
+ /** Whether this store can link through the app, and its attempt in progress, asked again when its last check is stale. */
160
+ export async function appLinkState(
161
+ ctx: EngineContext,
162
+ input: { clientId: string; provider: MarketplaceProvider; environment?: Environment },
163
+ ): Promise<{ available: boolean; pending: AppLinkPendingView | null }> {
164
+ const ready = await readyOf(ctx, input.provider, input.environment ?? "PRODUCTION");
165
+ if (!ready) return { available: false, pending: null };
166
+ const row = await liveAttempt(ready, input.clientId, input.provider);
167
+ if (!row) return { available: true, pending: null };
168
+ // Every read of a live attempt renews it: a store that leaves the card open keeps being checked (R2).
169
+ // A host with no periodic job (an inline driver) still sees the authorization arrive on the screen's next read.
170
+ const stale = row.seenAt == null && (row.checkedAt == null || ready.call.now.getTime() - row.checkedAt.getTime() >= CHECK_EVERY_SECONDS * 1000);
171
+ const listed = stale ? await listFor(ctx, ready, { ...input, addresses: false }) : null;
172
+ // An automatic check that fails changes nothing on the screen but the renewal (FUT-5798 E15).
173
+ const checked = Array.isArray(listed) ? await stamp(ready, row, pickable(listed), true) : await renew(ready, row);
174
+ return { available: true, pending: pendingOf(ready.linking, checked) };
175
+ }
176
+
177
+ /** Renew a live attempt read with no list asked: only that attempt, as {@link stamp} does. */
178
+ async function renew(ready: Ready, row: AttemptRow): Promise<AttemptRow> {
179
+ const data = { expiresAt: renewed(ready.call.now) };
180
+ await ready.attempts.updateMany?.({ where: { clientId: row.clientId, provider: row.provider, verifier: row.verifier }, data });
181
+ return { ...row, ...data };
182
+ }
183
+
184
+ /** Open (or open again) this store's attempt: Conectar, Reconectar. Asks nothing of the marketplace. */
185
+ export async function startAppLink(
186
+ ctx: EngineContext,
187
+ input: { clientId: string; provider: MarketplaceProvider; environment?: Environment },
188
+ ): Promise<{ kind: "started"; pending: AppLinkPendingView } | LinkFailure> {
189
+ const environment = input.environment ?? "PRODUCTION";
190
+ const ready = await readyOf(ctx, input.provider, environment);
191
+ if (!ready) return refused("UNAVAILABLE");
192
+ const portal = ready.linking.portalUrl;
193
+ const row = {
194
+ environment,
195
+ // No secret travels in a centralized link: the column keeps a fresh nonce, so each attempt tells itself from a later one.
196
+ verifier: ctx.ports.secrets.seal(`app-link:${globalThis.crypto.randomUUID()}`),
197
+ userCode: "",
198
+ verificationUrl: portal,
199
+ verificationUrlComplete: portal,
200
+ expiresAt: renewed(ready.call.now),
201
+ seenAt: null,
202
+ checkedAt: null,
203
+ };
204
+ await ready.attempts.upsert({
205
+ where: keyOf(input.clientId, input.provider),
206
+ create: { clientId: input.clientId, provider: input.provider, ...row },
207
+ update: row,
208
+ });
209
+ return { kind: "started", pending: pendingOf(ready.linking, { clientId: input.clientId, provider: input.provider, ...row }) };
210
+ }
211
+
212
+ /**
213
+ * The stores this one may pick, asked of the marketplace now: the screen's
214
+ * first read, "Já autorizei · verificar agora", and every read after a hint.
215
+ * Renews the attempt and records when the authorization was first seen. With
216
+ * no attempt open (a store choice reopened on a linked connection), it lists
217
+ * and stamps nothing.
218
+ */
219
+ export async function checkAppLink(
220
+ ctx: EngineContext,
221
+ input: { clientId: string; provider: MarketplaceProvider; environment?: Environment },
222
+ ): Promise<{ kind: "checked"; pending: AppLinkPendingView | null; merchants: LinkedMerchant[] } | LinkFailure> {
223
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
224
+ const stored = attempts ? ((await attempts.findUnique({ where: keyOf(input.clientId, input.provider) })) as AttemptRow | null) : null;
225
+ const environment = input.environment ?? environmentOf(stored?.environment);
226
+ const ready = await readyOf(ctx, input.provider, environment);
227
+ if (!ready) return refused("UNAVAILABLE");
228
+ const merchants = await listFor(ctx, ready, { ...input, addresses: true });
229
+ if (!Array.isArray(merchants)) return merchants;
230
+ const row = isLive(stored, ready.call.now) ? await stamp(ready, stored, pickable(merchants), true) : null;
231
+ return { kind: "checked", pending: row ? pendingOf(ready.linking, row) : null, merchants };
232
+ }
233
+
234
+ /** Cancelar: end this store's attempt. Nothing else changes; a linked connection stays linked. */
235
+ export async function cancelAppLink(ctx: EngineContext, input: { clientId: string; provider: MarketplaceProvider }): Promise<void> {
236
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
237
+ await attempts?.deleteMany({ where: { clientId: input.clientId, provider: input.provider } });
238
+ }
239
+
240
+ /**
241
+ * The periodic check: every attempt still alive and not yet seen, whose last
242
+ * check is older than {@link CHECK_EVERY_SECONDS}, asks the app's list once
243
+ * per marketplace and environment. Answers the stores whose authorization was
244
+ * seen by this pass, for the host to hint their screens. A list that does not
245
+ * answer leaves every attempt as it was, for the next pass.
246
+ */
247
+ export async function sweepAppLinks(
248
+ ctx: EngineContext,
249
+ input: { half?: boolean } = {},
250
+ ): Promise<{ seen: { clientId: string; provider: string }[]; waiting: number }> {
251
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
252
+ if (!attempts?.findMany) return { seen: [], waiting: 0 };
253
+ const now = ctx.ports.clock.now();
254
+ const rows = await dueAttempts(attempts, now);
255
+ const seen: { clientId: string; provider: string }[] = [];
256
+ for (const group of groupByApp(rows).values()) seen.push(...(await sweepGroup(ctx, group)));
257
+ for (const store of seen) ctx.ports.publishLinkSeen?.(store.clientId, store.provider);
258
+ // The schedule ticks each minute; the half-minute pass is queued by the tick itself, only while a store waits.
259
+ if (!input.half && rows.length > seen.length) await queueHalfPass(ctx, now);
260
+ return { seen, waiting: rows.length - seen.length };
261
+ }
262
+
263
+ /** The attempts a pass checks: alive, not seen, last asked over 30 s ago; the oldest expiries first. */
264
+ async function dueAttempts(attempts: MarketplaceLinkAttemptDelegate, now: Date): Promise<AttemptRow[]> {
265
+ const due = new Date(now.getTime() - CHECK_EVERY_SECONDS * 1000);
266
+ return (await attempts.findMany!({
267
+ where: { expiresAt: { gte: now }, seenAt: null, OR: [{ checkedAt: null }, { checkedAt: { lt: due } }] },
268
+ orderBy: { expiresAt: "asc" },
269
+ take: SWEEP_BATCH,
270
+ })) as AttemptRow[];
271
+ }
272
+
273
+ /** The attempts by marketplace and environment: one app, one list. */
274
+ function groupByApp(rows: readonly AttemptRow[]): Map<string, AttemptRow[]> {
275
+ const groups = new Map<string, AttemptRow[]>();
276
+ for (const row of rows) {
277
+ const key = `${row.provider}:${environmentOf(row.environment)}`;
278
+ groups.set(key, [...(groups.get(key) ?? []), row]);
279
+ }
280
+ return groups;
281
+ }
282
+
283
+ /**
284
+ * One app's pass: ONE list, whatever the number of stores waiting. A store may
285
+ * pick when the list holds a store nobody holds, or one it holds itself.
286
+ */
287
+ async function sweepGroup(ctx: EngineContext, group: readonly AttemptRow[]): Promise<{ clientId: string; provider: string }[]> {
288
+ const first = group[0]!;
289
+ const ready = await readyOf(ctx, first.provider, environmentOf(first.environment));
290
+ const listed = ready ? await ready.linking.merchants(ready.call) : null;
291
+ if (!ready || listed?.kind !== "ok") return [];
292
+ const held = await heldBy(await ctx.ports.db(), first.provider, listed.value.map((merchant) => merchant.id));
293
+ const anyFree = listed.value.some((merchant) => !held.has(merchant.id));
294
+ const holders = new Set(held.values());
295
+ const seen: { clientId: string; provider: string }[] = [];
296
+ for (const row of group) {
297
+ const checked = await stamp(ready, row, anyFree || holders.has(row.clientId), false);
298
+ if (checked.seenAt) seen.push({ clientId: row.clientId, provider: row.provider });
299
+ }
300
+ return seen;
301
+ }
302
+
303
+ /** The job that runs the check: each minute, and once more half a minute later while a store waits. */
304
+ export const MARKETPLACE_LINK_CHECK_JOB = "marketplace.link-check";
305
+
306
+ async function queueHalfPass(ctx: EngineContext, now: Date): Promise<void> {
307
+ const minute = Math.floor(now.getTime() / 60_000);
308
+ const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_LINK_CHECK_JOB, { half: true }, {
309
+ dedupeKey: `${MARKETPLACE_LINK_CHECK_JOB}:${minute}`,
310
+ delayMs: CHECK_EVERY_SECONDS * 1000,
311
+ });
312
+ if (!outcome.enqueued) ctx.ports.logger.warn(`${MARKETPLACE_LINK_CHECK_JOB}: the half-minute pass was not queued (${outcome.reason ?? "no reason"})`);
313
+ }
314
+
315
+ /** How many waiting attempts one pass checks: the oldest expiries first, the rest on the next pass. */
316
+ const SWEEP_BATCH = 200;
317
+
318
+ /** Which store's live connection holds each of `ids`, in one read. */
319
+ async function heldBy(db: MarketplaceDb, provider: string, ids: readonly string[]): Promise<Map<string, string>> {
320
+ if (ids.length === 0) return new Map();
321
+ const rows = (await db.marketplaceIntegration.findMany({
322
+ where: { provider, externalMerchantId: { in: [...ids] }, archivedAt: null },
323
+ select: { clientId: true, externalMerchantId: true },
324
+ })) as { clientId: string; externalMerchantId: string | null }[];
325
+ return new Map(rows.flatMap((row) => (row.externalMerchantId ? [[row.externalMerchantId, row.clientId] as const] : [])));
326
+ }
327
+
328
+ /** Write the picked store's connection: LINKED, VERIFIED, unarchived (audited), the attempt removed. */
329
+ async function savePick(
330
+ ctx: EngineContext,
331
+ input: { clientId: string; provider: string; merchantId: string; actorId: string | null },
332
+ environment: Environment,
333
+ ): Promise<void> {
334
+ const now = ctx.ports.clock.now();
335
+ await ctx.ports.transaction(async (db) => {
336
+ const existing = (await db.marketplaceIntegration.findUnique({
337
+ where: keyOf(input.clientId, input.provider),
338
+ select: { archivedAt: true },
339
+ })) as { archivedAt: Date | null } | null;
340
+ const data = {
341
+ credentials: sealAppLink(ctx),
342
+ authMode: "LINKED",
343
+ environment,
344
+ status: "VERIFIED",
345
+ lastVerifiedAt: now,
346
+ archivedAt: null,
347
+ externalMerchantId: input.merchantId,
348
+ };
349
+ await db.marketplaceIntegration.upsert({
350
+ where: keyOf(input.clientId, input.provider),
351
+ create: { clientId: input.clientId, provider: input.provider, ackSlaSeconds: ctx.ports.defaultAckSlaSeconds, enabled: true, ...data },
352
+ update: data,
353
+ });
354
+ if (existing?.archivedAt) {
355
+ await ctx.ports.audit.record(
356
+ { clientId: input.clientId, actorId: input.actorId, action: "marketplace.integration.unarchive", provider: input.provider, reason: "linked again", at: now },
357
+ db,
358
+ );
359
+ }
360
+ await db.marketplaceLinkAttempt?.deleteMany({ where: { clientId: input.clientId, provider: input.provider } });
361
+ });
362
+ }
363
+
364
+ /**
365
+ * Conectar esta loja: this store is `merchantId`. Refused when the app's list
366
+ * does not hold it (UNKNOWN_MERCHANT) or another store's live connection does
367
+ * (MERCHANT_TAKEN, re-checked here and by the unique index for the race).
368
+ */
369
+ export async function selectAppMerchant(
370
+ ctx: EngineContext,
371
+ input: { clientId: string; provider: MarketplaceProvider; merchantId: string; actorId?: string | null },
372
+ ): Promise<{ kind: "selected"; integration: MarketplaceIntegrationView } | LinkFailure> {
373
+ const attempts = (await ctx.ports.db()).marketplaceLinkAttempt;
374
+ const stored = attempts ? ((await attempts.findUnique({ where: keyOf(input.clientId, input.provider) })) as AttemptRow | null) : null;
375
+ const environment = environmentOf(stored?.environment);
376
+ const ready = await readyOf(ctx, input.provider, environment);
377
+ if (!ready) return refused("UNAVAILABLE");
378
+ const merchants = await listFor(ctx, ready, { ...input, addresses: false });
379
+ if (!Array.isArray(merchants)) return merchants;
380
+ const merchant = merchants.find((candidate) => candidate.id === input.merchantId);
381
+ if (!merchant) return refused("UNKNOWN_MERCHANT");
382
+ if (merchant.taken) return refused("MERCHANT_TAKEN");
383
+ const pick = { clientId: input.clientId, provider: input.provider, merchantId: input.merchantId, actorId: input.actorId ?? null };
384
+ const taken = await guardMerchantClaim(ctx, pick, () => savePick(ctx, pick, environment)).then(
385
+ () => false,
386
+ (error: unknown) => {
387
+ if (error instanceof MarketplaceMerchantTakenError || isUniqueViolation(error)) return true;
388
+ throw error;
389
+ },
390
+ );
391
+ if (taken) return refused("MERCHANT_TAKEN");
392
+ ctx.ports.publishChanged(input.clientId);
393
+ const [view] = await listMarketplaceIntegrations(ctx, input.clientId, { providers: [input.provider] });
394
+ if (!view) throw new Error(`The ${input.provider} connection of ${input.clientId} was not saved.`);
395
+ return { kind: "selected", integration: view };
396
+ }
@@ -0,0 +1,119 @@
1
+ import type { OutboundOrderRef } from "./adapter";
2
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
3
+ import { logisticsCallContext, type DeliveryCodeAnswer } from "./logistics";
4
+ import type { DeliveryOutcome } from "./pipeline";
5
+ import type { EngineContext } from "./ports";
6
+ import type { NormalizedEvent } from "./types";
7
+
8
+ /**
9
+ * The customer's delivery code (FUT-6167), the engine's half: the marketplace
10
+ * asks for it (iFood's `DELIVERY_DROP_CODE_REQUESTED`), the host stores that
11
+ * through `order.onDeliveryCodeRequested`, and the courier's close checks the
12
+ * typed code with {@link MarketplaceDeliveryCodeEngine.verifyDeliveryCode}.
13
+ *
14
+ * The check is a call the courier waits on at the door, so it runs in the
15
+ * request, never in a job, and never throws: a marketplace that cannot answer
16
+ * is UNAVAILABLE, and the host closes anyway and records it (a close is never
17
+ * refused, ADOPTING §17).
18
+ */
19
+
20
+ const CODE_BEFORE_ORDER = "delivery code request before its order";
21
+
22
+ interface HeldOrder {
23
+ orderId: string;
24
+ provider: string;
25
+ status: string;
26
+ deliveredBy: string | null;
27
+ externalOrderId: string;
28
+ externalDisplayId: string | null;
29
+ createdAt: Date;
30
+ }
31
+
32
+ const HELD_SELECT = {
33
+ orderId: true,
34
+ provider: true,
35
+ status: true,
36
+ deliveredBy: true,
37
+ externalOrderId: true,
38
+ externalDisplayId: true,
39
+ createdAt: true,
40
+ } as const;
41
+
42
+ /** A code request reaches a host that binds the hook; null for any other event. */
43
+ export async function applyDeliveryCodeRequest(
44
+ ctx: EngineContext,
45
+ inboxId: string,
46
+ clientId: string,
47
+ event: NormalizedEvent,
48
+ ): Promise<DeliveryOutcome | null> {
49
+ const hook = ctx.ports.order.onDeliveryCodeRequested;
50
+ if (!event.deliveryCodeRequested || !hook || !event.externalOrderId) return null;
51
+ const db = await ctx.ports.db();
52
+ const held = (await db.marketplaceAcceptance.findFirst({
53
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
54
+ select: HELD_SELECT,
55
+ })) as HeldOrder | null;
56
+ if (!held) {
57
+ await deferInboxEvent(ctx, inboxId, CODE_BEFORE_ORDER);
58
+ return { kind: "ignored", reason: CODE_BEFORE_ORDER };
59
+ }
60
+ if (held.status !== "ACCEPTED") {
61
+ const reason = `the order is ${held.status}, not ACCEPTED`;
62
+ await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
63
+ return { kind: "ignored", reason };
64
+ }
65
+ await hook.call(ctx.ports.order, clientId, held.orderId);
66
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
67
+ ctx.ports.publishChanged(clientId);
68
+ return { kind: "deliveryCodeRequested", orderId: held.orderId };
69
+ }
70
+
71
+ /** What the courier typed, for one of the host's orders. */
72
+ export interface VerifyDeliveryCodeInput {
73
+ clientId: string;
74
+ /** The host's own order id. */
75
+ orderId: string;
76
+ code: string;
77
+ }
78
+
79
+ /** The engine's delivery-code half (`MarketplaceEngine` extends it). */
80
+ export interface MarketplaceDeliveryCodeEngine {
81
+ /**
82
+ * Check the customer's delivery code with the marketplace (FUT-6167). Never
83
+ * throws; UNAVAILABLE says why nothing could be checked (no such order, the
84
+ * store does not carry it, no Logistics app, the marketplace did not answer).
85
+ */
86
+ verifyDeliveryCode(input: VerifyDeliveryCodeInput): Promise<DeliveryCodeAnswer>;
87
+ }
88
+
89
+ async function verifyDeliveryCode(ctx: EngineContext, input: VerifyDeliveryCodeInput): Promise<DeliveryCodeAnswer> {
90
+ try {
91
+ const db = await ctx.ports.db();
92
+ const held = (await db.marketplaceAcceptance.findFirst({
93
+ where: { clientId: input.clientId, orderId: input.orderId },
94
+ select: HELD_SELECT,
95
+ })) as HeldOrder | null;
96
+ if (!held) return { kind: "UNAVAILABLE", reason: "no marketplace order" };
97
+ if (held.deliveredBy !== "MERCHANT") return { kind: "UNAVAILABLE", reason: "the store does not carry this order" };
98
+ const logistics = ctx.registry.get(held.provider)?.logistics;
99
+ if (!logistics?.verifyDeliveryCode) return { kind: "UNAVAILABLE", reason: "the marketplace checks no delivery code" };
100
+ const call = await logisticsCallContext(ctx, input.clientId, held.provider);
101
+ if (typeof call === "string") return { kind: "UNAVAILABLE", reason: call };
102
+ const ref: OutboundOrderRef = {
103
+ externalOrderId: held.externalOrderId,
104
+ externalDisplayId: held.externalDisplayId,
105
+ hostOrderCode: held.orderId,
106
+ placedAt: held.createdAt,
107
+ };
108
+ return await logistics.verifyDeliveryCode(call, ref, input.code);
109
+ } catch (error) {
110
+ // The code is in no message: only that the check failed, and why.
111
+ ctx.ports.logger.warn(`delivery code for order ${input.orderId} not checked: ${error instanceof Error ? error.message : String(error)}`);
112
+ return { kind: "UNAVAILABLE", reason: "the check failed" };
113
+ }
114
+ }
115
+
116
+ /** Bind the delivery-code half to the engine's context. */
117
+ export function deliveryCodeEngine(ctx: EngineContext): MarketplaceDeliveryCodeEngine {
118
+ return { verifyDeliveryCode: (input) => verifyDeliveryCode(ctx, input) };
119
+ }
@@ -0,0 +1,32 @@
1
+ import { runDisputeAnswer, type DisputeAnswerJobPayload, type DisputeAnswerOutcome } from "./dispute-job";
2
+ import { readDisputes, type MarketplaceDisputeView } from "./dispute-store";
3
+ import { answerDispute, type AnswerDisputeResult, type DisputeAnswerInput } from "./disputes";
4
+ import type { EngineContext } from "./ports";
5
+
6
+ /**
7
+ * The engine's dispute calls (FUT-6099), bound to its context. ADOPTING §15
8
+ * is the host's contract.
9
+ */
10
+ export interface MarketplaceDisputeEngine {
11
+ /**
12
+ * The disputes to draw, oldest first: of these orders; or, with
13
+ * `settledSince`, every one still open, being answered or waiting on the
14
+ * marketplace, plus those settled since then. One statement.
15
+ */
16
+ disputes(input: { clientId: string; orderIds?: readonly string[]; settledSince?: Date }): Promise<MarketplaceDisputeView[]>;
17
+ /**
18
+ * The store's answer: judged, claimed and queued; refused locally with a code. No call to the marketplace.
19
+ * With `orderId`, a dispute of another order is NOT_FOUND, before anything is claimed.
20
+ */
21
+ answerDispute(input: { clientId: string; disputeId: string; orderId?: string; answer: DisputeAnswerInput; now?: Date }): Promise<AnswerDisputeResult>;
22
+ /** Send one claimed answer (the `marketplace.dispute-answer` job's body). */
23
+ runDisputeAnswer(payload: DisputeAnswerJobPayload, attempt: { attempt: number; maxAttempts: number }): Promise<DisputeAnswerOutcome>;
24
+ }
25
+
26
+ export function disputeEngine(ctx: EngineContext): MarketplaceDisputeEngine {
27
+ return {
28
+ disputes: (input) => readDisputes(ctx, input),
29
+ answerDispute: (input) => answerDispute(ctx, input),
30
+ runDisputeAnswer: (payload, attempt) => runDisputeAnswer(ctx, payload, attempt),
31
+ };
32
+ }