@12-apps/marketplace 1.16.0 → 1.17.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 (71) hide show
  1. package/ADOPTING.md +115 -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-CxzF-qGx.d.ts} +185 -2
  5. package/dist/{chunk-TRUK5ZBE.js → chunk-7IYUO2KC.js} +2 -2
  6. package/dist/{chunk-BTKVZAJI.js → chunk-CF5BSXE5.js} +1 -1
  7. package/dist/chunk-CF5BSXE5.js.map +1 -0
  8. package/dist/{chunk-DJIMUEHT.js → chunk-EABVLQKK.js} +79 -7
  9. package/dist/chunk-EABVLQKK.js.map +1 -0
  10. package/dist/{chunk-H2VQRD3B.js → chunk-KKFMDV5K.js} +1 -1
  11. package/dist/chunk-KKFMDV5K.js.map +1 -0
  12. package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
  13. package/dist/chunk-LO7OKO6V.js.map +1 -0
  14. package/dist/{chunk-TICWLBSA.js → chunk-UZO2NILN.js} +365 -6
  15. package/dist/chunk-UZO2NILN.js.map +1 -0
  16. package/dist/{client-DgzCkl8u.d.ts → client-C-4QvVq3.d.ts} +1 -1
  17. package/dist/{engine-DSRj7qnC.d.ts → engine-Y6Rpf5p7.d.ts} +430 -185
  18. package/dist/hono/index.d.ts +2 -2
  19. package/dist/hono/index.js +4 -4
  20. package/dist/ifood/index.d.ts +9 -2
  21. package/dist/ifood/index.js +271 -23
  22. package/dist/ifood/index.js.map +1 -1
  23. package/dist/index.d.ts +21 -4
  24. package/dist/index.js +381 -42
  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 +69 -1
  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/src/core/adapter.ts +12 -1
  41. package/src/core/app-linking.ts +396 -0
  42. package/src/core/dispute-engine.ts +32 -0
  43. package/src/core/dispute-job.ts +142 -0
  44. package/src/core/dispute-port.ts +133 -0
  45. package/src/core/dispute-store.ts +203 -0
  46. package/src/core/disputes.ts +263 -0
  47. package/src/core/engine.ts +4 -55
  48. package/src/core/integration.ts +3 -1
  49. package/src/core/link-engine.ts +176 -0
  50. package/src/core/link-store.ts +15 -0
  51. package/src/core/linking-port.ts +35 -1
  52. package/src/core/linking.ts +8 -0
  53. package/src/core/outbound-sweep.ts +9 -1
  54. package/src/core/pipeline.ts +8 -3
  55. package/src/core/ports.ts +15 -0
  56. package/src/core/types.ts +8 -0
  57. package/src/ifood/app-linking.ts +119 -0
  58. package/src/ifood/disputes.ts +209 -0
  59. package/src/ifood/index.ts +12 -1
  60. package/src/ifood/normalize.ts +3 -0
  61. package/src/index.ts +34 -0
  62. package/src/server/jobs.ts +51 -3
  63. package/src/server/link-routes.ts +56 -4
  64. package/src/server/mcp-link.ts +44 -2
  65. package/src/server/mcp.ts +2 -1
  66. package/dist/chunk-BTKVZAJI.js.map +0 -1
  67. package/dist/chunk-DJIMUEHT.js.map +0 -1
  68. package/dist/chunk-H2VQRD3B.js.map +0 -1
  69. package/dist/chunk-SGOTN5PX.js.map +0 -1
  70. package/dist/chunk-TICWLBSA.js.map +0 -1
  71. /package/dist/{chunk-TRUK5ZBE.js.map → chunk-7IYUO2KC.js.map} +0 -0
@@ -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,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
+ }
@@ -0,0 +1,142 @@
1
+ import type { DisputeAnswer, DisputeAnswerResult, DisputeFailureCode, MarketplaceDisputeDelegate } from "./dispute-port";
2
+ import { MARKETPLACE_DISPUTE_ANSWER_JOB, alternativesOf, disputeTable, findDispute, type DisputeRow } from "./dispute-store";
3
+ import { enqueueDisputeAnswer } from "./disputes";
4
+ import { readOutboundConnection } from "./integration";
5
+ import type { EngineContext } from "./ports";
6
+
7
+ /**
8
+ * The `marketplace.dispute-answer` job (FUT-6099): sends one claimed answer
9
+ * and stamps what the marketplace said. Idempotent by the row: only a SENDING
10
+ * row is sent, so a duplicate run calls nobody.
11
+ */
12
+
13
+ /** The job's payload: identifiers only. */
14
+ export interface DisputeAnswerJobPayload {
15
+ clientId: string;
16
+ /** The marketplace's id for the dispute. */
17
+ disputeId: string;
18
+ }
19
+
20
+ export type DisputeAnswerOutcome =
21
+ | { kind: "skipped"; reason: string }
22
+ | { kind: "answered" }
23
+ | { kind: "failed"; code: DisputeFailureCode };
24
+
25
+ /** Thrown so the queue retries. */
26
+ export class DisputeAnswerRetryError extends Error {
27
+ constructor(message: string) {
28
+ super(message);
29
+ this.name = "DisputeAnswerRetryError";
30
+ }
31
+ }
32
+
33
+ /** The kept answer, as the adapter sends it; null when the row no longer holds one it can send. */
34
+ function answerToSend(row: DisputeRow): DisputeAnswer | null {
35
+ if (row.answer === "ACCEPT") return { kind: "ACCEPT", reasonCode: row.answerReasonCode };
36
+ if (row.answer === "REJECT") return row.answerReasonCode ? { kind: "REJECT", reasonCode: row.answerReasonCode } : null;
37
+ const alternative = alternativesOf(row.alternatives).find((entry) => entry.id === row.answerAlternativeId);
38
+ if (row.answer !== "ALTERNATIVE" || !alternative) return null;
39
+ return { kind: "ALTERNATIVE", alternative, amountCents: row.answerAmountCents, minutes: row.answerMinutes };
40
+ }
41
+
42
+ /** Give the answer back: OPEN, with why, so a person answers again. */
43
+ async function giveBack(
44
+ ctx: EngineContext,
45
+ table: MarketplaceDisputeDelegate,
46
+ row: DisputeRow,
47
+ code: DisputeFailureCode,
48
+ ): Promise<DisputeAnswerOutcome> {
49
+ await table.updateMany({
50
+ where: { id: row.id, status: "SENDING" },
51
+ data: {
52
+ status: "OPEN",
53
+ answerFailure: code,
54
+ answer: null,
55
+ answerReasonCode: null,
56
+ answerAlternativeId: null,
57
+ answerAmountCents: null,
58
+ answerMinutes: null,
59
+ answeredAt: null,
60
+ },
61
+ });
62
+ ctx.ports.logger.warn(`${MARKETPLACE_DISPUTE_ANSWER_JOB}: dispute ${row.disputeId} not answered: ${code}`);
63
+ ctx.ports.publishChanged(row.clientId);
64
+ return { kind: "failed", code };
65
+ }
66
+
67
+ /** The marketplace took the answer, or someone else's answer stands: ANSWERED either way. */
68
+ async function stampAnswered(
69
+ ctx: EngineContext,
70
+ table: MarketplaceDisputeDelegate,
71
+ row: DisputeRow,
72
+ failure: DisputeFailureCode | null,
73
+ ): Promise<DisputeAnswerOutcome> {
74
+ await table.updateMany({ where: { id: row.id, status: "SENDING" }, data: { status: "ANSWERED", answerFailure: failure } });
75
+ ctx.ports.publishChanged(row.clientId);
76
+ return { kind: "answered" };
77
+ }
78
+
79
+ /** What the marketplace's answer makes of the row. */
80
+ async function settleSend(
81
+ ctx: EngineContext,
82
+ table: MarketplaceDisputeDelegate,
83
+ row: DisputeRow,
84
+ result: DisputeAnswerResult,
85
+ attempt: { attempt: number; maxAttempts: number },
86
+ ): Promise<DisputeAnswerOutcome> {
87
+ if (result.kind === "accepted") return stampAnswered(ctx, table, row, null);
88
+ if (result.kind === "refused") {
89
+ return result.code === "ALREADY_ANSWERED" ? stampAnswered(ctx, table, row, "ALREADY_ANSWERED") : giveBack(ctx, table, row, result.code);
90
+ }
91
+ if (attempt.attempt < attempt.maxAttempts) throw new DisputeAnswerRetryError(`dispute ${row.disputeId}: ${result.reason}`);
92
+ return giveBack(ctx, table, row, "UNREACHABLE");
93
+ }
94
+
95
+ /** Run one send. Throws {@link DisputeAnswerRetryError} for a retryable answer before the last attempt. */
96
+ export async function runDisputeAnswer(
97
+ ctx: EngineContext,
98
+ payload: DisputeAnswerJobPayload,
99
+ attempt: { attempt: number; maxAttempts: number },
100
+ ): Promise<DisputeAnswerOutcome> {
101
+ const table = await disputeTable(ctx);
102
+ const row = table ? await findDispute(table, payload.clientId, payload.disputeId) : null;
103
+ if (!table || !row || row.status !== "SENDING") return { kind: "skipped", reason: "no answer to send" };
104
+ const api = ctx.registry.get(row.provider)?.disputes;
105
+ const answer = answerToSend(row);
106
+ if (!api || !answer) return giveBack(ctx, table, row, "UNSUPPORTED");
107
+ const connection = await readOutboundConnection(ctx, row.clientId, row.provider).catch(() => null);
108
+ if (!connection) return giveBack(ctx, table, row, "NOT_CONNECTED");
109
+ const call = { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection };
110
+ const result = await api.answer(call, { externalOrderId: row.externalOrderId, disputeId: row.disputeId }, answer);
111
+ return settleSend(ctx, table, row, result, attempt);
112
+ }
113
+
114
+ /** At most this many owed answers per pass: the next pass takes the rest. */
115
+ const SWEEP_BATCH = 100;
116
+
117
+ /** An answer still SENDING past this is owed: the job's three attempts are long over. */
118
+ const DISPUTE_STALE_MS = 10 * 60_000;
119
+ /** Past this the marketplace has long settled it on its own clock: given back OPEN, UNREACHABLE. */
120
+ const DISPUTE_GIVE_UP_MS = 24 * 60 * 60_000;
121
+
122
+ /**
123
+ * The outbound sweep's dispute pass: re-queue an answer still SENDING after
124
+ * {@link DISPUTE_STALE_MS} (a refused enqueue, a dead process), under a key
125
+ * of its own per pass; give one older than a day back.
126
+ */
127
+ export async function sweepDisputes(ctx: EngineContext, now: Date): Promise<{ requeued: number; givenUp: number }> {
128
+ const table = await disputeTable(ctx);
129
+ if (!table) return { requeued: 0, givenUp: 0 };
130
+ const stale = new Date(now.getTime() - DISPUTE_STALE_MS);
131
+ const giveUp = new Date(now.getTime() - DISPUTE_GIVE_UP_MS);
132
+ const rows = (await table.findMany({ where: { status: "SENDING", answeredAt: { lt: stale } }, orderBy: { answeredAt: "asc" }, take: SWEEP_BATCH })) as DisputeRow[];
133
+ let requeued = 0;
134
+ let givenUp = 0;
135
+ for (const row of rows) {
136
+ if (row.answeredAt !== null && row.answeredAt.getTime() < giveUp.getTime()) {
137
+ await giveBack(ctx, table, row, "UNREACHABLE");
138
+ givenUp += 1;
139
+ } else if (await enqueueDisputeAnswer(ctx, row, `sweep:${now.getTime()}`)) requeued += 1;
140
+ }
141
+ return { requeued, givenUp };
142
+ }