@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
@@ -0,0 +1,263 @@
1
+ import type { DisputeAlternative, MarketplaceDisputeChange, NormalizedDisputeOpened, NormalizedDisputeSettled } from "./dispute-port";
2
+ import {
3
+ MARKETPLACE_DISPUTE_ANSWER_JOB,
4
+ alternativesOf,
5
+ disputeTable,
6
+ disputeView,
7
+ findDispute,
8
+ reasonsOf,
9
+ type DisputeRow,
10
+ type MarketplaceDisputeView,
11
+ } from "./dispute-store";
12
+ import { deferInboxEvent, settleInboxEvent } from "./inbox";
13
+ import type { DeliveryOutcome } from "./pipeline";
14
+ import type { EngineContext } from "./ports";
15
+ import type { NormalizedEvent } from "./types";
16
+
17
+ export type { MarketplaceDisputeChange } from "./dispute-port";
18
+
19
+ /**
20
+ * A marketplace's disputes (FUT-6099), the engine's half: the event that opens
21
+ * or closes one is kept per order, and the store's answer is claimed here and
22
+ * sent by the `marketplace.dispute-answer` job, never inside the request.
23
+ *
24
+ * A dispute never touches the order or its acceptance: it may arrive for an
25
+ * order in any state (delivered, in preparation, late), and what the store
26
+ * does about it is an answer to the marketplace, not a move of the order.
27
+ */
28
+
29
+ /** The answer a person gives, before the engine judges it. */
30
+ export type DisputeAnswerInput =
31
+ | { kind: "ACCEPT" }
32
+ | { kind: "REJECT"; reasonCode: string }
33
+ | { kind: "ALTERNATIVE"; alternativeId: string; amountCents?: number | null; minutes?: number | null };
34
+
35
+ /** Why an answer is refused locally, before anything is queued. */
36
+ export type DisputeRefusalCode =
37
+ | "NOT_FOUND"
38
+ | "ALREADY_ANSWERED"
39
+ | "EXPIRED"
40
+ | "UNSUPPORTED"
41
+ | "INVALID_REASON"
42
+ | "INVALID_ALTERNATIVE"
43
+ | "INVALID_AMOUNT"
44
+ | "INVALID_MINUTES";
45
+
46
+ export type AnswerDisputeResult =
47
+ | { kind: "queued"; dispute: MarketplaceDisputeView }
48
+ | { kind: "refused"; code: DisputeRefusalCode };
49
+
50
+ interface HeldOrder {
51
+ orderId: string;
52
+ }
53
+
54
+ /** The order the event names, as the engine holds it. */
55
+ async function heldOrder(ctx: EngineContext, clientId: string, event: NormalizedEvent): Promise<HeldOrder | null> {
56
+ const db = await ctx.ports.db();
57
+ return (await db.marketplaceAcceptance.findFirst({
58
+ where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
59
+ select: { orderId: true },
60
+ })) as HeldOrder | null;
61
+ }
62
+
63
+ /** Tell the host after the commit; a throw is logged and changes nothing. */
64
+ async function tellHost(ctx: EngineContext, clientId: string, orderId: string, change: MarketplaceDisputeChange): Promise<void> {
65
+ ctx.ports.publishChanged(clientId);
66
+ const hook = ctx.ports.order.onDispute;
67
+ if (!hook) return;
68
+ try {
69
+ await hook.call(ctx.ports.order, clientId, orderId, change);
70
+ } catch (error) {
71
+ ctx.ports.logger.error(`marketplace.dispute: the host's onDispute failed for order ${orderId}`, error);
72
+ }
73
+ }
74
+
75
+ function openedData(clientId: string, orderId: string, event: NormalizedEvent, dispute: NormalizedDisputeOpened, now: Date) {
76
+ return {
77
+ clientId,
78
+ orderId,
79
+ provider: event.provider,
80
+ externalOrderId: event.externalOrderId,
81
+ disputeId: dispute.disputeId,
82
+ status: "OPEN",
83
+ action: dispute.action,
84
+ handshakeType: dispute.handshakeType,
85
+ reason: dispute.reason,
86
+ message: dispute.message,
87
+ evidences: dispute.evidenceUrls,
88
+ items: dispute.items,
89
+ requestedAmountCents: dispute.requestedAmountCents,
90
+ expiresAt: dispute.expiresAt,
91
+ openedAt: dispute.openedAt ?? now,
92
+ timeoutAction: dispute.timeoutAction,
93
+ alternatives: dispute.alternatives,
94
+ rejectReasons: dispute.rejectReasons,
95
+ acceptReasons: dispute.acceptReasons,
96
+ };
97
+ }
98
+
99
+ /** Keep an opened dispute once: a second event for the same dispute changes nothing. */
100
+ async function keepOpened(
101
+ ctx: EngineContext,
102
+ clientId: string,
103
+ order: HeldOrder,
104
+ event: NormalizedEvent,
105
+ dispute: NormalizedDisputeOpened,
106
+ ): Promise<"opened" | "unchanged"> {
107
+ const table = await disputeTable(ctx);
108
+ if (!table) throw new Error("marketplace disputes need migration 20261203190000_marketplace_disputes");
109
+ const existing = await table.findFirst({ where: { provider: event.provider, disputeId: dispute.disputeId } });
110
+ if (existing) return "unchanged";
111
+ await table.create({ data: openedData(clientId, order.orderId, event, dispute, ctx.ports.clock.now()) });
112
+ return "opened";
113
+ }
114
+
115
+ /** Close a kept dispute with the marketplace's outcome; null when it is not kept (yet). */
116
+ async function keepSettled(
117
+ ctx: EngineContext,
118
+ clientId: string,
119
+ event: NormalizedEvent,
120
+ settlement: NormalizedDisputeSettled,
121
+ ): Promise<{ orderId: string; changed: boolean } | null> {
122
+ const table = await disputeTable(ctx);
123
+ const row = table ? await findDispute(table, clientId, settlement.disputeId) : null;
124
+ if (!table || !row || row.provider !== event.provider) return null;
125
+ if (row.status === "SETTLED") return { orderId: row.orderId, changed: false };
126
+ await table.updateMany({
127
+ where: { id: row.id },
128
+ data: {
129
+ status: "SETTLED",
130
+ settlement: settlement.outcome,
131
+ settledAt: settlement.at ?? ctx.ports.clock.now(),
132
+ settledAmountCents: settlement.amountCents,
133
+ },
134
+ });
135
+ return { orderId: row.orderId, changed: true };
136
+ }
137
+
138
+ async function deferred(ctx: EngineContext, inboxId: string, reason: string): Promise<DeliveryOutcome> {
139
+ await deferInboxEvent(ctx, inboxId, reason);
140
+ return { kind: "ignored", reason };
141
+ }
142
+
143
+ /**
144
+ * Act on a dispute event (HSD / HSS): kept, the inbox row PROCESSED, the host
145
+ * told. One that outran its order, or a close that outran its open, waits
146
+ * PENDING for the reconcile pass.
147
+ */
148
+ export async function applyDisputeEvent(
149
+ ctx: EngineContext,
150
+ inboxId: string,
151
+ clientId: string,
152
+ event: NormalizedEvent,
153
+ ): Promise<DeliveryOutcome | null> {
154
+ const dispute = event.dispute;
155
+ if (!dispute || !event.externalOrderId) return null;
156
+ if (dispute.kind === "settled") {
157
+ const settled = await keepSettled(ctx, clientId, event, dispute.settlement);
158
+ if (!settled) return deferred(ctx, inboxId, "settlement before its dispute");
159
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
160
+ const disputeId = dispute.settlement.disputeId;
161
+ if (settled.changed) await tellHost(ctx, clientId, settled.orderId, { kind: "settled", disputeId });
162
+ return { kind: "dispute", orderId: settled.orderId, disputeId, change: settled.changed ? "settled" : "unchanged" };
163
+ }
164
+ const order = await heldOrder(ctx, clientId, event);
165
+ if (!order) return deferred(ctx, inboxId, "dispute before its order");
166
+ const change = await keepOpened(ctx, clientId, order, event, dispute.dispute);
167
+ await settleInboxEvent(ctx, inboxId, "PROCESSED");
168
+ const disputeId = dispute.dispute.disputeId;
169
+ if (change === "opened") await tellHost(ctx, clientId, order.orderId, { kind: "opened", disputeId });
170
+ return { kind: "dispute", orderId: order.orderId, disputeId, change };
171
+ }
172
+
173
+ /** The columns an answer stamps. */
174
+ interface AnswerColumns {
175
+ answer: "ACCEPT" | "REJECT" | "ALTERNATIVE";
176
+ answerReasonCode: string | null;
177
+ answerAlternativeId: string | null;
178
+ answerAmountCents: number | null;
179
+ answerMinutes: number | null;
180
+ }
181
+
182
+ const NONE = { answerReasonCode: null, answerAlternativeId: null, answerAmountCents: null, answerMinutes: null };
183
+
184
+ function isPositiveInteger(value: number | null | undefined): value is number {
185
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
186
+ }
187
+
188
+ /** An alternative's amount or minutes, judged against what the marketplace allows. */
189
+ function judgeAlternative(
190
+ alternative: DisputeAlternative,
191
+ input: { amountCents?: number | null; minutes?: number | null },
192
+ ): AnswerColumns | DisputeRefusalCode {
193
+ const base = { ...NONE, answer: "ALTERNATIVE" as const, answerAlternativeId: alternative.id };
194
+ if (alternative.type === "ADDITIONAL_TIME") {
195
+ const minutes = input.minutes;
196
+ if (!isPositiveInteger(minutes)) return "INVALID_MINUTES";
197
+ if (alternative.allowedMinutes.length > 0 && !alternative.allowedMinutes.includes(minutes)) return "INVALID_MINUTES";
198
+ return { ...base, answerMinutes: minutes };
199
+ }
200
+ const amount = input.amountCents;
201
+ if (!isPositiveInteger(amount)) return "INVALID_AMOUNT";
202
+ if (alternative.maxAmountCents !== null && amount > alternative.maxAmountCents) return "INVALID_AMOUNT";
203
+ return { ...base, answerAmountCents: amount };
204
+ }
205
+
206
+ /** The person's answer against what the marketplace sent for this dispute. */
207
+ function judgeAnswer(row: DisputeRow, input: DisputeAnswerInput): AnswerColumns | DisputeRefusalCode {
208
+ if (input.kind === "ACCEPT") {
209
+ // No reason from the person (D5, owner 2026-12-03); the first the marketplace lists, when it lists any (R16).
210
+ return { ...NONE, answer: "ACCEPT", answerReasonCode: reasonsOf(row.acceptReasons)[0]?.code ?? null };
211
+ }
212
+ if (input.kind === "REJECT") {
213
+ const known = reasonsOf(row.rejectReasons).some((reason) => reason.code === input.reasonCode);
214
+ return known ? { ...NONE, answer: "REJECT", answerReasonCode: input.reasonCode } : "INVALID_REASON";
215
+ }
216
+ const alternative = alternativesOf(row.alternatives).find((entry) => entry.id === input.alternativeId);
217
+ return alternative ? judgeAlternative(alternative, input) : "INVALID_ALTERNATIVE";
218
+ }
219
+
220
+ /** Why this dispute takes no answer now, or null. */
221
+ function closedFor(ctx: EngineContext, row: DisputeRow, now: Date): DisputeRefusalCode | null {
222
+ if (row.status !== "OPEN") return "ALREADY_ANSWERED";
223
+ if (row.expiresAt !== null && now.getTime() >= row.expiresAt.getTime()) return "EXPIRED";
224
+ return ctx.registry.get(row.provider)?.disputes ? null : "UNSUPPORTED";
225
+ }
226
+
227
+ /** Queue the send; a refused enqueue is the outbound sweep's to re-queue. */
228
+ export async function enqueueDisputeAnswer(ctx: EngineContext, row: { clientId: string; disputeId: string }, key: string): Promise<boolean> {
229
+ const outcome = await ctx.ports.enqueue.enqueue(
230
+ MARKETPLACE_DISPUTE_ANSWER_JOB,
231
+ { clientId: row.clientId, disputeId: row.disputeId },
232
+ { dedupeKey: `${MARKETPLACE_DISPUTE_ANSWER_JOB}:${row.disputeId}:${key}` },
233
+ );
234
+ if (!outcome.enqueued) {
235
+ ctx.ports.logger.warn(`${MARKETPLACE_DISPUTE_ANSWER_JOB}: dispute ${row.disputeId} not queued; the sweep re-queues it` + (outcome.reason ? ` (${outcome.reason})` : ""));
236
+ }
237
+ return outcome.enqueued;
238
+ }
239
+
240
+ /**
241
+ * The store answers one dispute: judged against what the marketplace sent,
242
+ * claimed (OPEN → SENDING, so two tablets never both answer) and queued. No
243
+ * call to the marketplace here; the job sends it.
244
+ */
245
+ export async function answerDispute(
246
+ ctx: EngineContext,
247
+ input: { clientId: string; disputeId: string; orderId?: string; answer: DisputeAnswerInput; now?: Date },
248
+ ): Promise<AnswerDisputeResult> {
249
+ const now = input.now ?? ctx.ports.clock.now();
250
+ const table = await disputeTable(ctx);
251
+ const row = table ? await findDispute(table, input.clientId, input.disputeId, input.orderId) : null;
252
+ if (!table || !row) return { kind: "refused", code: "NOT_FOUND" };
253
+ const closed = closedFor(ctx, row, now);
254
+ if (closed) return { kind: "refused", code: closed };
255
+ const judged = judgeAnswer(row, input.answer);
256
+ if (typeof judged === "string") return { kind: "refused", code: judged };
257
+ const data = { ...judged, status: "SENDING", answeredAt: now, answerFailure: null };
258
+ const claimed = await table.updateMany({ where: { id: row.id, status: "OPEN" }, data });
259
+ if (claimed.count === 0) return { kind: "refused", code: "ALREADY_ANSWERED" };
260
+ await enqueueDisputeAnswer(ctx, row, String(now.getTime()));
261
+ ctx.ports.publishChanged(input.clientId);
262
+ return { kind: "queued", dispute: disputeView({ ...row, ...data }) };
263
+ }
@@ -1,3 +1,4 @@
1
+ import { deliveryCodeEngine, type MarketplaceDeliveryCodeEngine } from "./delivery-code";
1
2
  import {
2
3
  cancelAcceptance,
3
4
  expireLapsedAcceptances,
@@ -38,6 +39,8 @@ import type { CataloguePublicationView } from "./catalogue-store";
38
39
  import { courierEngine } from "./courier";
39
40
  import type { MarketplaceCourierEngine } from "./courier-port";
40
41
  import { conformityEngine, type MarketplaceConformityEngine } from "./conformity";
42
+ import { linkEngine, type MarketplaceLinkEngine } from "./link-engine";
43
+ import { disputeEngine, type MarketplaceDisputeEngine } from "./dispute-engine";
41
44
  import {
42
45
  runFetchOrder,
43
46
  type FetchOrderJobPayload,
@@ -60,21 +63,11 @@ import {
60
63
  type MarketplaceIntegrationView,
61
64
  type SaveMarketplaceIntegrationInput,
62
65
  } from "./integration";
63
- import {
64
- finishLink,
65
- linkState,
66
- linkedMerchants,
67
- selectLinkedMerchant,
68
- startLink,
69
- type LinkFailure,
70
- type LinkFinished,
71
- type LinkPendingView,
72
- } from "./linking";
73
- import type { LinkedMerchant } from "./linking-port";
74
66
  import { guardMerchantClaim, resolveTenantByMerchant } from "./merchant-claim";
75
67
  import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
76
68
  import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
77
69
  import { informStatus, type InformStatusInput } from "./status-inform";
70
+ import { logisticsEngine, type MarketplaceLogisticsEngine } from "./logistics";
78
71
  import {
79
72
  availabilityState,
80
73
  pauseStore,
@@ -100,7 +93,13 @@ import { readOrderStates, type MarketplaceOrderState } from "./state";
100
93
  import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
101
94
 
102
95
  /** Everything the mounted engine can do, with the ports and adapters bound in. */
103
- export interface MarketplaceEngine extends MarketplaceCourierEngine, MarketplaceConformityEngine {
96
+ export interface MarketplaceEngine
97
+ extends MarketplaceCourierEngine,
98
+ MarketplaceConformityEngine,
99
+ MarketplaceLinkEngine,
100
+ MarketplaceDisputeEngine,
101
+ MarketplaceLogisticsEngine,
102
+ MarketplaceDeliveryCodeEngine {
104
103
  /** Every registered marketplace, in registration order. */
105
104
  providers(): readonly MarketplaceProvider[];
106
105
  /** Whether a provider id (a URL segment, a body field) names a registered adapter. */
@@ -155,43 +154,6 @@ export interface MarketplaceEngine extends MarketplaceCourierEngine, Marketplace
155
154
  validateOnly?: boolean;
156
155
  }): Promise<BulkResult<MarketplaceIntegrationView>>;
157
156
 
158
- /**
159
- * Whether this store can link this marketplace through the software's own
160
- * app (FUT-5613), and the linking it left in progress. `available` is false
161
- * when the adapter links nothing, the host configured no app for it, or the
162
- * link table is not composed: the store's own credentials still work.
163
- */
164
- linkState(input: {
165
- clientId: string;
166
- provider: MarketplaceProvider;
167
- environment?: "SANDBOX" | "PRODUCTION";
168
- }): Promise<{ available: boolean; pending: LinkPendingView | null }>;
169
- /** Ask for the portal code; the verifier stays sealed server-side. Replaces an earlier attempt. */
170
- startLink(input: {
171
- clientId: string;
172
- provider: MarketplaceProvider;
173
- environment?: "SANDBOX" | "PRODUCTION";
174
- }): Promise<{ kind: "started"; pending: LinkPendingView } | LinkFailure>;
175
- /** Exchange the pasted authorization code for the store's tokens; select the merchant when only one. */
176
- finishLink(input: {
177
- clientId: string;
178
- provider: MarketplaceProvider;
179
- authorizationCode: string;
180
- actorId: string | null;
181
- enabled?: boolean;
182
- }): Promise<LinkFinished | LinkFailure>;
183
- /** The merchants a linked connection's grant covers. */
184
- linkedMerchants(input: {
185
- clientId: string;
186
- provider: MarketplaceProvider;
187
- }): Promise<{ kind: "listed"; merchants: LinkedMerchant[] } | LinkFailure>;
188
- /** Choose the marketplace store of a linked connection whose grant covers several. */
189
- selectLinkedMerchant(input: {
190
- clientId: string;
191
- provider: MarketplaceProvider;
192
- merchantId: string;
193
- }): Promise<{ kind: "selected"; integration: MarketplaceIntegrationView } | LinkFailure>;
194
-
195
157
  /** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */
196
158
  menuLinks(input: {
197
159
  clientId: string;
@@ -351,11 +313,6 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
351
313
  saveMarketplaceIntegration(ctx, input, await ports.db()),
352
314
  ),
353
315
  upsertIntegrations: (input) => upsertIntegrations(ctx, input),
354
- linkState: (input) => linkState(ctx, input),
355
- startLink: (input) => startLink(ctx, input),
356
- finishLink: (input) => finishLink(ctx, input),
357
- linkedMerchants: (input) => linkedMerchants(ctx, input),
358
- selectLinkedMerchant: (input) => selectLinkedMerchant(ctx, input),
359
316
 
360
317
  menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),
361
318
  upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),
@@ -378,7 +335,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
378
335
  runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
379
336
  runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
380
337
  informStatus: (input) => informStatus(ctx, input),
381
- ...{ ...courierEngine(ctx), ...conformityEngine(ctx) },
338
+ ...{ ...courierEngine(ctx), ...conformityEngine(ctx), ...linkEngine(ctx), ...disputeEngine(ctx), ...logisticsEngine(ctx), ...deliveryCodeEngine(ctx) },
382
339
 
383
340
  // Null too when the host bound no catalogue port: nothing could be published.
384
341
  catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
@@ -1,5 +1,5 @@
1
1
  import type { AdapterGrant, MarketplaceCredentials } from "./adapter";
2
- import { appCredentialsOf, linkGrant, openLinkRefreshToken, type MarketplaceAuthMode } from "./link-store";
2
+ import { appCredentialsOf, isAppLinkBlob, linkGrant, openLinkRefreshToken, type MarketplaceAuthMode } from "./link-store";
3
3
  import { assertMerchantFree } from "./merchant-claim";
4
4
  import type { EngineContext, MarketplaceDb } from "./ports";
5
5
  import type { MarketplaceProvider } from "./types";
@@ -383,6 +383,8 @@ export async function readSealedOutboundConnection(
383
383
  // Linked: the software's app speaks for the store, with the store's refresh token.
384
384
  const app = await appCredentialsOf(ctx, provider, environment);
385
385
  if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
386
+ // Linked through the CENTRALIZED app (FUT-5798): the app's own token speaks for every store that authorized it.
387
+ if (isAppLinkBlob(ctx, sealed)) return { connection: { environment, credentials: app }, sealed };
386
388
  const refreshToken = openLinkRefreshToken(ctx, sealed);
387
389
  const link = { clientId, provider, environment, refreshToken, app, sealed };
388
390
  return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
@@ -0,0 +1,176 @@
1
+ import {
2
+ appLinkState,
3
+ cancelAppLink,
4
+ checkAppLink,
5
+ hasAppLinking,
6
+ selectAppMerchant,
7
+ startAppLink,
8
+ sweepAppLinks,
9
+ type AppLinkPendingView,
10
+ } from "./app-linking";
11
+ import type { MarketplaceIntegrationView } from "./integration";
12
+ import {
13
+ finishLink,
14
+ linkState,
15
+ linkedMerchants,
16
+ selectLinkedMerchant,
17
+ startLink,
18
+ type LinkFailure,
19
+ type LinkFinished,
20
+ type LinkPendingView,
21
+ } from "./linking";
22
+ import type { LinkedMerchant } from "./linking-port";
23
+ import type { EngineContext } from "./ports";
24
+ import type { MarketplaceProvider } from "./types";
25
+
26
+ /**
27
+ * The engine's linking surface (FUT-5613, centralized since FUT-5798): one
28
+ * entry per call, dispatched to the centralized app's half (`./app-linking`)
29
+ * when the adapter declares `appLinking`, else to the code flow (`./linking`).
30
+ */
31
+ export interface MarketplaceLinkEngine {
32
+ /**
33
+ * Whether this store can link this marketplace through the software's own
34
+ * app (FUT-5613), and the linking it left in progress. `available` is false
35
+ * when the adapter links nothing, the host configured no app for it, or the
36
+ * link table is not composed: the store's own credentials still work.
37
+ */
38
+ linkState(input: {
39
+ clientId: string;
40
+ provider: MarketplaceProvider;
41
+ environment?: "SANDBOX" | "PRODUCTION";
42
+ }): Promise<{ available: boolean; pending: LinkPendingView | null }>;
43
+ /** Ask for the portal code; the verifier stays sealed server-side. Replaces an earlier attempt. */
44
+ startLink(input: {
45
+ clientId: string;
46
+ provider: MarketplaceProvider;
47
+ environment?: "SANDBOX" | "PRODUCTION";
48
+ }): Promise<{ kind: "started"; pending: LinkPendingView } | LinkFailure>;
49
+ /** Exchange the pasted authorization code for the store's tokens; select the merchant when only one. */
50
+ finishLink(input: {
51
+ clientId: string;
52
+ provider: MarketplaceProvider;
53
+ authorizationCode: string;
54
+ actorId: string | null;
55
+ enabled?: boolean;
56
+ }): Promise<LinkFinished | LinkFailure>;
57
+ /** The merchants a linked connection's grant covers. */
58
+ linkedMerchants(input: {
59
+ clientId: string;
60
+ provider: MarketplaceProvider;
61
+ }): Promise<{ kind: "listed"; merchants: LinkedMerchant[] } | LinkFailure>;
62
+ /** Choose the marketplace store of a linked connection whose grant covers several. */
63
+ selectLinkedMerchant(input: {
64
+ clientId: string;
65
+ provider: MarketplaceProvider;
66
+ merchantId: string;
67
+ /** Who picked it, for the audit line of a connection unarchived by the pick (centralized linking). */
68
+ actorId?: string | null;
69
+ }): Promise<
70
+ { kind: "selected"; integration: MarketplaceIntegrationView } | LinkFailure
71
+ >;
72
+ /**
73
+ * Centralized linking (FUT-5798): ask the app's list NOW ("Já autorizei ·
74
+ * verificar agora", the screen's first read and every read after a hint),
75
+ * renewing the attempt. Refused UNAVAILABLE for a marketplace that links
76
+ * through codes.
77
+ */
78
+ checkLink(input: {
79
+ clientId: string;
80
+ provider: MarketplaceProvider;
81
+ }): Promise<
82
+ | {
83
+ kind: "checked";
84
+ pending: LinkPendingView | null;
85
+ merchants: LinkedMerchant[];
86
+ }
87
+ | LinkFailure
88
+ >;
89
+ /** End this store's linking in progress (Cancelar). Nothing else changes. */
90
+ cancelLink(input: {
91
+ clientId: string;
92
+ provider: MarketplaceProvider;
93
+ }): Promise<void>;
94
+ /**
95
+ * The host's periodic job (every 30 s): every centralized attempt still
96
+ * waiting asks the app's list; answers the stores whose authorization this
97
+ * pass saw, for the host to hint their screens. Asks nothing when none waits.
98
+ */
99
+ sweepLinks(input?: {
100
+ half?: boolean;
101
+ }): Promise<{
102
+ seen: { clientId: string; provider: string }[];
103
+ waiting: number;
104
+ }>;
105
+ }
106
+
107
+ /** A centralized attempt in the one pending shape the routes answer. */
108
+ const appPendingView = (pending: AppLinkPendingView): LinkPendingView => ({
109
+ userCode: "",
110
+ verificationUrl: pending.portalUrl,
111
+ verificationUrlComplete: pending.portalUrl,
112
+ expiresAt: pending.expiresAt,
113
+ mode: "app",
114
+ seenAt: pending.seenAt,
115
+ checkedAt: pending.checkedAt,
116
+ });
117
+
118
+ const NO_CODE: LinkFailure = {
119
+ kind: "refused",
120
+ code: "UNAVAILABLE",
121
+ status: null,
122
+ message: "this marketplace links without a code",
123
+ };
124
+
125
+ /** The linking methods, bound to the engine's context; spread into the engine. */
126
+ export function linkEngine(ctx: EngineContext): MarketplaceLinkEngine {
127
+ const app = (provider: MarketplaceProvider) => hasAppLinking(ctx, provider);
128
+ return {
129
+ linkState: async (input) => {
130
+ if (!app(input.provider)) return linkState(ctx, input);
131
+ const state = await appLinkState(ctx, input);
132
+ return {
133
+ available: state.available,
134
+ pending: state.pending ? appPendingView(state.pending) : null,
135
+ };
136
+ },
137
+ startLink: async (input) => {
138
+ if (!app(input.provider)) return startLink(ctx, input);
139
+ const started = await startAppLink(ctx, input);
140
+ return started.kind === "started"
141
+ ? { kind: "started", pending: appPendingView(started.pending) }
142
+ : started;
143
+ },
144
+ finishLink: (input) =>
145
+ app(input.provider) ? Promise.resolve(NO_CODE) : finishLink(ctx, input),
146
+ linkedMerchants: async (input) => {
147
+ if (!app(input.provider)) return linkedMerchants(ctx, input);
148
+ const checked = await checkAppLink(ctx, input);
149
+ return checked.kind === "checked"
150
+ ? { kind: "listed", merchants: checked.merchants }
151
+ : checked;
152
+ },
153
+ selectLinkedMerchant: (input) =>
154
+ app(input.provider)
155
+ ? selectAppMerchant(ctx, input)
156
+ : selectLinkedMerchant(ctx, input),
157
+ checkLink: async (input) => {
158
+ if (!app(input.provider))
159
+ return {
160
+ kind: "refused",
161
+ code: "UNAVAILABLE",
162
+ status: null,
163
+ message: null,
164
+ };
165
+ const checked = await checkAppLink(ctx, input);
166
+ return checked.kind === "checked"
167
+ ? {
168
+ ...checked,
169
+ pending: checked.pending ? appPendingView(checked.pending) : null,
170
+ }
171
+ : checked;
172
+ },
173
+ cancelLink: (input) => cancelAppLink(ctx, input),
174
+ sweepLinks: (input) => sweepAppLinks(ctx, input),
175
+ };
176
+ }
@@ -29,6 +29,21 @@ export function openLinkRefreshToken(ctx: EngineContext, sealed: string): string
29
29
  return token;
30
30
  }
31
31
 
32
+ /** The blob of a connection linked through the CENTRALIZED app (FUT-5798): no token of the store's; the app's speaks for it. */
33
+ export function sealAppLink(ctx: EngineContext): string {
34
+ return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, app: true }));
35
+ }
36
+
37
+ /** Whether a linked connection's blob is a centralized link. */
38
+ export function isAppLinkBlob(ctx: EngineContext, sealed: string): boolean {
39
+ try {
40
+ const parsed: unknown = JSON.parse(ctx.ports.secrets.open(sealed));
41
+ return typeof parsed === "object" && parsed !== null && (parsed as { app?: unknown }).app === true;
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+
32
47
  /** The software's own app on this marketplace, or null when the host configured none. */
33
48
  export async function appCredentialsOf(
34
49
  ctx: EngineContext,
@@ -58,11 +58,15 @@ export interface LinkGrant {
58
58
  refreshToken: string | null;
59
59
  }
60
60
 
61
- /** One marketplace store the grant covers. */
61
+ /** One marketplace store the grant (or, centralized, the app's authorization) covers. */
62
62
  export interface LinkedMerchant {
63
63
  id: string;
64
64
  name: string | null;
65
65
  corporateName: string | null;
66
+ /** One line of the store's address, read off its detail (centralized linking, FUT-5798); absent when not asked. */
67
+ address?: string | null;
68
+ /** Another store's live connection already holds it (centralized linking, FUT-5798); absent when not judged. */
69
+ taken?: boolean;
66
70
  }
67
71
 
68
72
  /**
@@ -92,9 +96,39 @@ export type MarketplaceAppCredentialsPort = (
92
96
  environment: "SANDBOX" | "PRODUCTION",
93
97
  ) => MarketplaceCredentials | null | Promise<MarketplaceCredentials | null>;
94
98
 
99
+ /**
100
+ * LINKING through the software's CENTRALIZED app (FUT-5798): the store
101
+ * authorizes the app on the marketplace's portal, and that is all. No code is
102
+ * typed, nothing is pasted, no token is the store's: the app's own
103
+ * client-credentials token sees every store that authorized it, and the store
104
+ * picks its own from that list. A linked connection then talks to the
105
+ * marketplace with the app's token, and the app's webhook brings its orders.
106
+ *
107
+ * The adapter's half is the wire format of the list and nothing else; the
108
+ * attempt, the claim and the rows are the engine's (`./app-linking.ts`).
109
+ */
110
+ export interface MarketplaceAppLinking {
111
+ /** The portal page where the store authorizes the app. Always https. */
112
+ readonly portalUrl: string;
113
+ /** Every store the app is authorized for, through the app's own token. */
114
+ merchants(ctx: AppLinkCallContext): Promise<LinkResult<LinkedMerchant[]>>;
115
+ /** One line of a store's address, for the person to recognise it; null when the detail carries none. */
116
+ address(ctx: AppLinkCallContext, merchantId: string): Promise<LinkResult<string | null>>;
117
+ }
118
+
119
+ /** What a centralized linking call is handed: the APP's credentials and the engine's token cache. */
120
+ export interface AppLinkCallContext extends LinkCallContext {
121
+ /** The engine's per-process token cache: the app's token is shared with its outbound calls, never bought early. */
122
+ tokens: Map<string, { token: string; expiresAt: number }>;
123
+ }
124
+
95
125
  /** The link-attempt delegate the engine reads and writes (the `MarketplaceLinkAttempt` model). */
96
126
  export interface MarketplaceLinkAttemptDelegate {
97
127
  findUnique(args: unknown): Promise<unknown>;
98
128
  upsert(args: unknown): Promise<unknown>;
99
129
  deleteMany(args: unknown): Promise<{ count: number }>;
130
+ /** The live attempts the periodic check walks (FUT-5798). Absent: the check finds none. */
131
+ findMany?(args: unknown): Promise<unknown[]>;
132
+ /** Stamp a check on an attempt (FUT-5798). */
133
+ updateMany?(args: unknown): Promise<{ count: number }>;
100
134
  }
@@ -48,6 +48,14 @@ export interface LinkPendingView {
48
48
  verificationUrl: string;
49
49
  verificationUrlComplete: string;
50
50
  expiresAt: Date;
51
+ /**
52
+ * `app` for a centralized link (FUT-5798): no code (`userCode` is empty), the
53
+ * portal is `verificationUrl`, and `seenAt` / `checkedAt` say when the app's
54
+ * list first showed a store to pick and when it was last asked. Absent: a code.
55
+ */
56
+ mode?: "code" | "app";
57
+ seenAt?: Date | null;
58
+ checkedAt?: Date | null;
51
59
  }
52
60
 
53
61
  interface AttemptRow {