@12-apps/marketplace 1.15.1 → 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.
- package/ADOPTING.md +146 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CjVdMhZ2.d.ts → adapter-CxzF-qGx.d.ts} +185 -2
- package/dist/{chunk-TRUK5ZBE.js → chunk-7IYUO2KC.js} +2 -2
- package/dist/{chunk-BTKVZAJI.js → chunk-CF5BSXE5.js} +1 -1
- package/dist/chunk-CF5BSXE5.js.map +1 -0
- package/dist/{chunk-DJIMUEHT.js → chunk-EABVLQKK.js} +79 -7
- package/dist/chunk-EABVLQKK.js.map +1 -0
- package/dist/{chunk-H2VQRD3B.js → chunk-KKFMDV5K.js} +1 -1
- package/dist/chunk-KKFMDV5K.js.map +1 -0
- package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
- package/dist/chunk-LO7OKO6V.js.map +1 -0
- package/dist/{chunk-TICWLBSA.js → chunk-UZO2NILN.js} +365 -6
- package/dist/chunk-UZO2NILN.js.map +1 -0
- package/dist/{client-DgzCkl8u.d.ts → client-C-4QvVq3.d.ts} +1 -1
- package/dist/{engine-DSRj7qnC.d.ts → engine-Y6Rpf5p7.d.ts} +430 -185
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +4 -4
- package/dist/ifood/index.d.ts +65 -2
- package/dist/ifood/index.js +374 -23
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +21 -4
- package/dist/index.js +381 -42
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/index.d.ts +78 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +6 -2
- package/dist/manifest/server.js +4 -4
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +93 -7
- package/dist/server/index.js +4 -4
- package/package.json +1 -1
- package/prisma/marketplace.prisma +69 -1
- package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
- package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
- package/src/core/adapter.ts +12 -1
- package/src/core/app-linking.ts +396 -0
- package/src/core/dispute-engine.ts +32 -0
- package/src/core/dispute-job.ts +142 -0
- package/src/core/dispute-port.ts +133 -0
- package/src/core/dispute-store.ts +203 -0
- package/src/core/disputes.ts +263 -0
- package/src/core/engine.ts +4 -55
- package/src/core/integration.ts +3 -1
- package/src/core/link-engine.ts +176 -0
- package/src/core/link-store.ts +15 -0
- package/src/core/linking-port.ts +35 -1
- package/src/core/linking.ts +8 -0
- package/src/core/outbound-sweep.ts +9 -1
- package/src/core/pipeline.ts +8 -3
- package/src/core/ports.ts +15 -0
- package/src/core/types.ts +8 -0
- package/src/ifood/app-linking.ts +119 -0
- package/src/ifood/disputes.ts +209 -0
- package/src/ifood/index.ts +25 -1
- package/src/ifood/logistics.ts +195 -0
- package/src/ifood/normalize.ts +3 -0
- package/src/ifood/outbound.ts +1 -1
- package/src/index.ts +34 -0
- package/src/server/jobs.ts +51 -3
- package/src/server/link-routes.ts +56 -4
- package/src/server/mcp-link.ts +44 -2
- package/src/server/mcp.ts +2 -1
- package/dist/chunk-BTKVZAJI.js.map +0 -1
- package/dist/chunk-DJIMUEHT.js.map +0 -1
- package/dist/chunk-H2VQRD3B.js.map +0 -1
- package/dist/chunk-SGOTN5PX.js.map +0 -1
- package/dist/chunk-TICWLBSA.js.map +0 -1
- /package/dist/{chunk-TRUK5ZBE.js.map → chunk-7IYUO2KC.js.map} +0 -0
package/src/core/engine.ts
CHANGED
|
@@ -38,6 +38,8 @@ import type { CataloguePublicationView } from "./catalogue-store";
|
|
|
38
38
|
import { courierEngine } from "./courier";
|
|
39
39
|
import type { MarketplaceCourierEngine } from "./courier-port";
|
|
40
40
|
import { conformityEngine, type MarketplaceConformityEngine } from "./conformity";
|
|
41
|
+
import { linkEngine, type MarketplaceLinkEngine } from "./link-engine";
|
|
42
|
+
import { disputeEngine, type MarketplaceDisputeEngine } from "./dispute-engine";
|
|
41
43
|
import {
|
|
42
44
|
runFetchOrder,
|
|
43
45
|
type FetchOrderJobPayload,
|
|
@@ -60,17 +62,6 @@ import {
|
|
|
60
62
|
type MarketplaceIntegrationView,
|
|
61
63
|
type SaveMarketplaceIntegrationInput,
|
|
62
64
|
} 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
65
|
import { guardMerchantClaim, resolveTenantByMerchant } from "./merchant-claim";
|
|
75
66
|
import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
|
|
76
67
|
import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
|
|
@@ -100,7 +91,7 @@ import { readOrderStates, type MarketplaceOrderState } from "./state";
|
|
|
100
91
|
import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
101
92
|
|
|
102
93
|
/** Everything the mounted engine can do, with the ports and adapters bound in. */
|
|
103
|
-
export interface MarketplaceEngine extends MarketplaceCourierEngine, MarketplaceConformityEngine {
|
|
94
|
+
export interface MarketplaceEngine extends MarketplaceCourierEngine, MarketplaceConformityEngine, MarketplaceLinkEngine, MarketplaceDisputeEngine {
|
|
104
95
|
/** Every registered marketplace, in registration order. */
|
|
105
96
|
providers(): readonly MarketplaceProvider[];
|
|
106
97
|
/** Whether a provider id (a URL segment, a body field) names a registered adapter. */
|
|
@@ -155,43 +146,6 @@ export interface MarketplaceEngine extends MarketplaceCourierEngine, Marketplace
|
|
|
155
146
|
validateOnly?: boolean;
|
|
156
147
|
}): Promise<BulkResult<MarketplaceIntegrationView>>;
|
|
157
148
|
|
|
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
149
|
/** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */
|
|
196
150
|
menuLinks(input: {
|
|
197
151
|
clientId: string;
|
|
@@ -351,11 +305,6 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
351
305
|
saveMarketplaceIntegration(ctx, input, await ports.db()),
|
|
352
306
|
),
|
|
353
307
|
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
308
|
|
|
360
309
|
menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),
|
|
361
310
|
upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),
|
|
@@ -378,7 +327,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
378
327
|
runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
|
|
379
328
|
runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
|
|
380
329
|
informStatus: (input) => informStatus(ctx, input),
|
|
381
|
-
...{ ...courierEngine(ctx), ...conformityEngine(ctx) },
|
|
330
|
+
...{ ...courierEngine(ctx), ...conformityEngine(ctx), ...linkEngine(ctx), ...disputeEngine(ctx) },
|
|
382
331
|
|
|
383
332
|
// Null too when the host bound no catalogue port: nothing could be published.
|
|
384
333
|
catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
|
package/src/core/integration.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/core/link-store.ts
CHANGED
|
@@ -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,
|
package/src/core/linking-port.ts
CHANGED
|
@@ -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
|
}
|
package/src/core/linking.ts
CHANGED
|
@@ -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 {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { NO_STANDING_REQUEST } from "./cancellation";
|
|
2
2
|
import { sweepCatalogue } from "./catalogue-sweep";
|
|
3
|
+
import { sweepDisputes } from "./dispute-job";
|
|
3
4
|
import { cancellationWindowMs, failedRequestData, requestsFirst, tellCancellationFailed } from "./cancellation-outcome";
|
|
4
5
|
import { MARKETPLACE_OUTBOUND_JOB, enqueueOutbound, type OutboundAction } from "./outbound-queue";
|
|
5
6
|
import { statusTable, type StatusRowStep } from "./status-store";
|
|
@@ -214,5 +215,12 @@ export async function sweepOutbound(ctx: EngineContext, now: Date): Promise<Outb
|
|
|
214
215
|
if (givenUp > 0) ctx.ports.logger.error(`marketplace.outbound-sweep: gave up on ${givenUp} cancellation request(s).`);
|
|
215
216
|
const catalogueRequeued = await sweepCatalogue(ctx, now);
|
|
216
217
|
const status = await sweepStatus(ctx, now);
|
|
217
|
-
|
|
218
|
+
// A dispute's answer still owed (FUT-6099): re-queued, or given back after a day.
|
|
219
|
+
const disputes = await sweepDisputes(ctx, now);
|
|
220
|
+
return {
|
|
221
|
+
requeued: requeued + status.requeued + disputes.requeued,
|
|
222
|
+
givenUp: givenUp + status.givenUp + disputes.givenUp,
|
|
223
|
+
timedOut,
|
|
224
|
+
catalogueRequeued,
|
|
225
|
+
};
|
|
218
226
|
}
|
package/src/core/pipeline.ts
CHANGED
|
@@ -16,6 +16,7 @@ import type {
|
|
|
16
16
|
import { followCourierAndLifecycle } from "./courier";
|
|
17
17
|
import { enqueueAcknowledge } from "./acknowledge";
|
|
18
18
|
import { applyMarketplaceConfirmation } from "./marketplace-confirmed";
|
|
19
|
+
import { applyDisputeEvent } from "./disputes";
|
|
19
20
|
|
|
20
21
|
/**
|
|
21
22
|
* One delivery, start to finish: normalize → inbox → ingest.
|
|
@@ -53,6 +54,8 @@ export type DeliveryOutcome =
|
|
|
53
54
|
* (with the host's `refusal`, when it refused), never expired.
|
|
54
55
|
*/
|
|
55
56
|
| { kind: "confirmedByMarketplace"; orderId: string; accepted: boolean; refusal?: { code: string; message: string } }
|
|
57
|
+
/** A dispute opened or closed on the order (FUT-6099); `unchanged` for a second event of one already kept. */
|
|
58
|
+
| { kind: "dispute"; orderId: string; disputeId: string; change: "opened" | "settled" | "unchanged" }
|
|
56
59
|
| { kind: "cancelled" }
|
|
57
60
|
| { kind: "cancellationFailed" }
|
|
58
61
|
/** Recorded; the order body is fetched by the `marketplace.fetch-order` job. */
|
|
@@ -191,9 +194,9 @@ async function applyEvent(
|
|
|
191
194
|
}
|
|
192
195
|
|
|
193
196
|
/**
|
|
194
|
-
* What the marketplace says about an order it already gave us:
|
|
195
|
-
* accepted it in the marketplace's app (FUT-5653), or a
|
|
196
|
-
* step. Null for anything else.
|
|
197
|
+
* What the marketplace says about an order it already gave us: a dispute
|
|
198
|
+
* (FUT-6099), the store accepted it in the marketplace's app (FUT-5653), or a
|
|
199
|
+
* courier or lifecycle step. Null for anything else.
|
|
197
200
|
*/
|
|
198
201
|
async function followMarketplace(
|
|
199
202
|
ctx: EngineContext,
|
|
@@ -202,6 +205,8 @@ async function followMarketplace(
|
|
|
202
205
|
event: NormalizedEvent,
|
|
203
206
|
settings: IngestSettings,
|
|
204
207
|
): Promise<DeliveryOutcome | null> {
|
|
208
|
+
const disputed = await applyDisputeEvent(ctx, inboxId, clientId, event);
|
|
209
|
+
if (disputed) return disputed;
|
|
205
210
|
const confirmed = await applyMarketplaceConfirmation(ctx, inboxId, clientId, event);
|
|
206
211
|
return confirmed ?? followCourierAndLifecycle(ctx, inboxId, clientId, event, settings);
|
|
207
212
|
}
|
package/src/core/ports.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { AdapterRegistry } from "./registry";
|
|
|
2
2
|
import type { AdapterTokenCache, MarketplaceAdapter, MarketplaceHttp, StatusStep } from "./adapter";
|
|
3
3
|
import type { CatalogueImage, CatalogueItem } from "./catalogue-port";
|
|
4
4
|
import type { MarketplaceCourierAnswer, MarketplaceCourierFacts, PickupCodeValidation } from "./courier-port";
|
|
5
|
+
import type { MarketplaceDisputeChange, MarketplaceDisputeDelegate } from "./dispute-port";
|
|
5
6
|
import type { MarketplaceLifecycleAnswer, MarketplaceLifecycleFacts } from "./lifecycle-port";
|
|
6
7
|
import type { MarketplaceAppCredentialsPort, MarketplaceLinkAttemptDelegate } from "./linking-port";
|
|
7
8
|
import type {
|
|
@@ -115,6 +116,8 @@ export interface MarketplaceDb {
|
|
|
115
116
|
updateMany(args: unknown): Promise<{ count: number }>;
|
|
116
117
|
};
|
|
117
118
|
marketplaceLinkAttempt?: MarketplaceLinkAttemptDelegate; // OPTIONAL, as above; absent: no linking (FUT-5613).
|
|
119
|
+
/** OPTIONAL (FUT-6099): the buyer's disputes, migration `20261203190000_marketplace_disputes`. */
|
|
120
|
+
marketplaceDispute?: MarketplaceDisputeDelegate;
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
/** One decision as the host's admission sees it, BEFORE the claim commits. */
|
|
@@ -246,6 +249,12 @@ export interface MarketplaceOrderPort {
|
|
|
246
249
|
* logged. Absent: the verdict is only logged.
|
|
247
250
|
*/
|
|
248
251
|
onPickupCodeValidated?(clientId: string, orderId: string, validation: PickupCodeValidation): Promise<void>;
|
|
252
|
+
/**
|
|
253
|
+
* OPTIONAL (FUT-6099). A dispute opened or closed on this order, after its
|
|
254
|
+
* commit: the host refreshes its board and tells a person. A throw is
|
|
255
|
+
* logged. Absent: only `publishChanged` is called.
|
|
256
|
+
*/
|
|
257
|
+
onDispute?(clientId: string, orderId: string, change: MarketplaceDisputeChange): Promise<void>;
|
|
249
258
|
/** Queue facts for a batch of orders, keyed by id. Missing ids are dropped. */
|
|
250
259
|
summarize(
|
|
251
260
|
clientId: string,
|
|
@@ -346,6 +355,12 @@ export interface MarketplacePorts {
|
|
|
346
355
|
* awaits it, and a dead bus costs latency, never a transition.
|
|
347
356
|
*/
|
|
348
357
|
publishChanged: (clientId: string) => void;
|
|
358
|
+
/**
|
|
359
|
+
* OPTIONAL (FUT-5798). The periodic check saw the authorization of a store's
|
|
360
|
+
* centralized link arrive: the host hints that store's open screen to read
|
|
361
|
+
* its link again. Payload-free; absent, the screen sees it on its next read.
|
|
362
|
+
*/
|
|
363
|
+
publishLinkSeen?: (clientId: string, provider: string) => void;
|
|
349
364
|
/**
|
|
350
365
|
* OPTIONAL. How long a store's cancellation request may wait for the
|
|
351
366
|
* marketplace's answer before the outbound sweep fails it as TIMEOUT, in
|
package/src/core/types.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { NormalizedDisputeEvent } from "./dispute-port";
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* The canonical shape every marketplace adapter normalizes INTO.
|
|
3
5
|
*
|
|
@@ -348,4 +350,10 @@ export interface NormalizedEvent {
|
|
|
348
350
|
* host's admit, with no confirm sent back. Carries no order body.
|
|
349
351
|
*/
|
|
350
352
|
marketplaceConfirmed?: boolean;
|
|
353
|
+
/**
|
|
354
|
+
* OPTIONAL (FUT-6099). A dispute the marketplace opened or closed on this
|
|
355
|
+
* order (iFood's HSD / HSS). Carries no order body, and never moves the
|
|
356
|
+
* order or its acceptance.
|
|
357
|
+
*/
|
|
358
|
+
dispute?: NormalizedDisputeEvent | null;
|
|
351
359
|
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { AdapterCallContext, MarketplaceHttpResponse } from "../core/adapter";
|
|
2
|
+
import { outboundResultOf } from "../core/adapter";
|
|
3
|
+
import type { AppLinkCallContext, LinkResult, LinkedMerchant, MarketplaceAppLinking } from "../core/linking-port";
|
|
4
|
+
import { asString, pick } from "../core/payload-read";
|
|
5
|
+
import { IFOOD_API, withIfoodToken } from "./outbound";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* iFood's CENTRALIZED-APP linking, the wire format only (FUT-5798).
|
|
9
|
+
*
|
|
10
|
+
* The store authorizes the software's app on iFood's Portal do Parceiro; the
|
|
11
|
+
* app's own `client_credentials` token then lists that store with the others
|
|
12
|
+
* that authorized it, and the store picks its own. iFood offers its webhook
|
|
13
|
+
* only to centralized apps, which is why the software links this way.
|
|
14
|
+
*
|
|
15
|
+
* - `GET /merchant/v1.0/merchants?page=&size=` (size default 100) → 200
|
|
16
|
+
* `[{ id, name, corporateName }]`: every store the app may act for.
|
|
17
|
+
* - `GET /merchant/v1.0/merchants/{merchantId}` → 200 with `address`
|
|
18
|
+
* (sandbox, 2026-12-02: `id, name, corporateName, description,
|
|
19
|
+
* averageTicket, type, createdAt, test, status, address, operations`).
|
|
20
|
+
* Neither carries a CNPJ.
|
|
21
|
+
*
|
|
22
|
+
* The token is the one every outbound call of the app uses, from the same
|
|
23
|
+
* cache key: bought once, renewed only when expired or answered 401.
|
|
24
|
+
*
|
|
25
|
+
* ESTIMATED, not settled by iFood's pages: the address fields' names
|
|
26
|
+
* (`street`/`streetName`, `number`/`streetNumber`, `district`/`neighborhood`),
|
|
27
|
+
* read with fallbacks; and the portal's apps page as the place to authorize.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const MERCHANTS_URL = `${IFOOD_API}/merchant/v1.0/merchants`;
|
|
31
|
+
/** One page of the merchant list; iFood's documented default. */
|
|
32
|
+
const MERCHANT_PAGE_SIZE = 100;
|
|
33
|
+
/** A ceiling on pages read, so a misbehaving answer cannot loop. */
|
|
34
|
+
const MAX_MERCHANT_PAGES = 20;
|
|
35
|
+
/** Where a store authorizes the software's app: the Portal do Parceiro's apps page. */
|
|
36
|
+
export const IFOOD_APPS_PORTAL_URL = "https://portal.ifood.com.br/apps";
|
|
37
|
+
|
|
38
|
+
function json(body: string): unknown {
|
|
39
|
+
try {
|
|
40
|
+
return body === "" ? null : (JSON.parse(body) as unknown);
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const adapterContext = (ctx: AppLinkCallContext): AdapterCallContext => ({
|
|
47
|
+
http: ctx.http,
|
|
48
|
+
credentials: ctx.credentials,
|
|
49
|
+
environment: ctx.environment,
|
|
50
|
+
tokens: ctx.tokens,
|
|
51
|
+
now: ctx.now,
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
/** One GET with the app's token; its 2xx body read by `read`. */
|
|
55
|
+
async function get<T>(ctx: AppLinkCallContext, url: string, read: (body: unknown) => T | null): Promise<LinkResult<T>> {
|
|
56
|
+
try {
|
|
57
|
+
const response = await withIfoodToken(adapterContext(ctx), (token) =>
|
|
58
|
+
ctx.http({ method: "GET", url, headers: { Authorization: `Bearer ${token}` } }),
|
|
59
|
+
);
|
|
60
|
+
if (response === null) return { kind: "refused", status: 401, message: "iFood refused the app's token" };
|
|
61
|
+
if ("kind" in response) return response.kind === "accepted" ? { kind: "retry", reason: "no answer" } : response;
|
|
62
|
+
const result = outboundResultOf(response as MarketplaceHttpResponse);
|
|
63
|
+
if (result.kind !== "accepted") return result;
|
|
64
|
+
const value = read(json(response.body));
|
|
65
|
+
return value === null ? { kind: "refused", status: response.status, message: "iFood's answer is not the documented shape" } : { kind: "ok", value };
|
|
66
|
+
} catch (error) {
|
|
67
|
+
return { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function merchantsOf(body: unknown): LinkedMerchant[] | null {
|
|
72
|
+
if (!Array.isArray(body)) return null;
|
|
73
|
+
return body.flatMap((raw: unknown) => {
|
|
74
|
+
const id = asString(pick(raw, "id"));
|
|
75
|
+
return id ? [{ id, name: asString(pick(raw, "name")), corporateName: asString(pick(raw, "corporateName")) }] : [];
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const first = (raw: unknown, ...keys: string[]): string | null => {
|
|
80
|
+
for (const key of keys) {
|
|
81
|
+
const value = pick(raw, key);
|
|
82
|
+
const text = typeof value === "number" ? String(value) : asString(value);
|
|
83
|
+
if (text && text.trim() !== "") return text.trim();
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** "Rua Pernambuco, 1000 · Savassi": the street and number, then the district; null when the detail carries no street. */
|
|
89
|
+
export function ifoodAddressLine(body: unknown): string | null {
|
|
90
|
+
const address = pick(body, "address");
|
|
91
|
+
const street = first(address, "street", "streetName");
|
|
92
|
+
if (!street) return null;
|
|
93
|
+
const number = first(address, "number", "streetNumber");
|
|
94
|
+
const district = first(address, "district", "neighborhood");
|
|
95
|
+
// The sandbox's street already carries the number and the district ("Ramal Bujari, 122, Bujari"): never twice.
|
|
96
|
+
const line = number && !street.includes(number) ? `${street}, ${number}` : street;
|
|
97
|
+
return district && !line.includes(district) ? `${line} · ${district}` : line;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Every store the app may act for, page by page until a short page. */
|
|
101
|
+
async function listMerchants(ctx: AppLinkCallContext): Promise<LinkResult<LinkedMerchant[]>> {
|
|
102
|
+
const all: LinkedMerchant[] = [];
|
|
103
|
+
for (let page = 1; page <= MAX_MERCHANT_PAGES; page += 1) {
|
|
104
|
+
const answer = await get(ctx, `${MERCHANTS_URL}?page=${page}&size=${MERCHANT_PAGE_SIZE}`, merchantsOf);
|
|
105
|
+
if (answer.kind !== "ok") return answer;
|
|
106
|
+
all.push(...answer.value);
|
|
107
|
+
if (answer.value.length < MERCHANT_PAGE_SIZE) break;
|
|
108
|
+
}
|
|
109
|
+
return { kind: "ok", value: all };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The iFood adapter's centralized linking half. */
|
|
113
|
+
export const IFOOD_APP_LINKING: MarketplaceAppLinking = {
|
|
114
|
+
portalUrl: IFOOD_APPS_PORTAL_URL,
|
|
115
|
+
merchants: listMerchants,
|
|
116
|
+
address: (ctx, merchantId) => get(ctx, `${MERCHANTS_URL}/${encodeURIComponent(merchantId)}`, (body) => (body === null ? null : { line: ifoodAddressLine(body) })).then(
|
|
117
|
+
(answer) => (answer.kind === "ok" ? { kind: "ok", value: answer.value.line } : answer),
|
|
118
|
+
),
|
|
119
|
+
};
|