@12-apps/marketplace 1.10.0 → 1.12.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 +126 -1
- package/README.md +100 -1
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CYJzu1c9.d.ts → adapter-nUyZpLzz.d.ts} +448 -173
- package/dist/{chunk-2BA2EHNF.js → chunk-45ZVN5XI.js} +316 -42
- package/dist/chunk-45ZVN5XI.js.map +1 -0
- package/dist/{chunk-PYHNM47K.js → chunk-L6FG6T4S.js} +2 -2
- package/dist/{chunk-HEXLCTOG.js → chunk-LACBT6NC.js} +1 -1
- package/dist/chunk-LACBT6NC.js.map +1 -0
- package/dist/{chunk-WVZ2IXFH.js → chunk-MIPNQ7X5.js} +190 -12
- package/dist/chunk-MIPNQ7X5.js.map +1 -0
- package/dist/chunk-SGOTN5PX.js +345 -0
- package/dist/chunk-SGOTN5PX.js.map +1 -0
- package/dist/{client-B4EQCRD_.d.ts → client-Ctas7WCS.d.ts} +1 -1
- package/dist/{engine-DK3iV_Kk.d.ts → engine-CIy9P7Cq.d.ts} +149 -8
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +10 -2
- package/dist/ifood/index.js +297 -25
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +23 -4
- package/dist/index.js +424 -84
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -18
- package/dist/keeta/index.js +12 -3
- package/dist/keeta/index.js.map +1 -1
- package/dist/manifest/index.d.ts +219 -1
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +3 -3
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/en-US.d.ts +13 -0
- package/dist/server/en-US.js +13 -0
- package/dist/server/en-US.js.map +1 -1
- package/dist/server/index.d.ts +241 -7
- package/dist/server/index.js +3 -3
- package/dist/server/pt-BR.d.ts +13 -0
- package/dist/server/pt-BR.js +13 -0
- package/dist/server/pt-BR.js.map +1 -1
- package/package.json +1 -1
- package/prisma/marketplace.prisma +41 -0
- package/prisma/migrations/20261127090000_marketplace_app_link/migration.sql +81 -0
- package/src/core/adapter.ts +27 -0
- package/src/core/bulk.ts +43 -8
- package/src/core/courier-port.ts +100 -0
- package/src/core/courier.ts +153 -0
- package/src/core/engine.ts +63 -4
- package/src/core/integration.ts +60 -32
- package/src/core/lifecycle.ts +27 -4
- package/src/core/link-store.ts +170 -0
- package/src/core/linking-port.ts +100 -0
- package/src/core/linking.ts +363 -0
- package/src/core/merchant-claim.ts +106 -0
- package/src/core/outbound-queue.ts +24 -11
- package/src/core/outbound.ts +8 -6
- package/src/core/pickup-code.ts +136 -0
- package/src/core/pipeline.ts +15 -6
- package/src/core/ports.ts +26 -1
- package/src/core/status-store.ts +2 -3
- package/src/core/types.ts +56 -4
- package/src/ifood/courier.ts +210 -0
- package/src/ifood/index.ts +8 -0
- package/src/ifood/linking.ts +170 -0
- package/src/ifood/normalize.ts +7 -0
- package/src/ifood/outbound.ts +10 -3
- package/src/index.ts +30 -0
- package/src/keeta/normalize.ts +21 -6
- package/src/server/copy.ts +20 -2
- package/src/server/en-US.ts +13 -0
- package/src/server/index.ts +1 -1
- package/src/server/link-routes.ts +140 -0
- package/src/server/mcp-link.ts +103 -0
- package/src/server/mcp.ts +6 -2
- package/src/server/pt-BR.ts +13 -0
- package/src/server/routes.ts +5 -2
- package/src/server/webhook.ts +86 -0
- package/dist/chunk-2BA2EHNF.js.map +0 -1
- package/dist/chunk-HEXLCTOG.js.map +0 -1
- package/dist/chunk-WVZ2IXFH.js.map +0 -1
- package/dist/chunk-ZO4S3LF4.js +0 -254
- package/dist/chunk-ZO4S3LF4.js.map +0 -1
- /package/dist/{chunk-PYHNM47K.js.map → chunk-L6FG6T4S.js.map} +0 -0
package/src/core/bulk.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
type MarketplaceIntegrationView,
|
|
5
5
|
type SaveMarketplaceIntegrationInput,
|
|
6
6
|
} from "./integration";
|
|
7
|
+
import { MarketplaceMerchantTakenError, isUniqueViolation, merchantHeldElsewhere } from "./merchant-claim";
|
|
7
8
|
import { upsertLink, type MarketplaceMenuLinkView } from "./menu-links";
|
|
8
9
|
import type { EngineContext, MarketplaceAuditEntry, MarketplaceDb } from "./ports";
|
|
9
10
|
|
|
@@ -24,7 +25,9 @@ export type BulkProblemCode =
|
|
|
24
25
|
| "UNKNOWN_PROVIDER"
|
|
25
26
|
| "NOTHING_TO_UPDATE"
|
|
26
27
|
| "NOT_FOUND"
|
|
27
|
-
| "CATALOG_ITEM_NOT_FOUND"
|
|
28
|
+
| "CATALOG_ITEM_NOT_FOUND"
|
|
29
|
+
/** Another store's live connection holds the merchant id this row sets, or revives (FUT-5613). */
|
|
30
|
+
| "MERCHANT_TAKEN";
|
|
28
31
|
|
|
29
32
|
export interface BulkProblem {
|
|
30
33
|
path: (string | number)[];
|
|
@@ -87,6 +90,29 @@ function integrationRowProblems(
|
|
|
87
90
|
return changes ? [] : [{ path: ["integrations", index], code: "NOTHING_TO_UPDATE" }];
|
|
88
91
|
}
|
|
89
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The rows that would give a merchant id another store's live connection
|
|
95
|
+
* holds: an upsert setting it (refused at the merchant field), or an
|
|
96
|
+
* unarchive reviving it (refused at the provider).
|
|
97
|
+
*/
|
|
98
|
+
async function merchantProblems(
|
|
99
|
+
ctx: EngineContext,
|
|
100
|
+
clientId: string,
|
|
101
|
+
rows: readonly IntegrationRowInput[],
|
|
102
|
+
merchantOf: ReadonlyMap<string, string | null>,
|
|
103
|
+
): Promise<BulkProblem[]> {
|
|
104
|
+
const db = await ctx.ports.db();
|
|
105
|
+
const problems: BulkProblem[] = [];
|
|
106
|
+
for (const [index, row] of rows.entries()) {
|
|
107
|
+
const unarchive = row.operation === "unarchive";
|
|
108
|
+
const merchantId = unarchive ? merchantOf.get(row.provider) : "externalMerchantId" in row ? row.externalMerchantId : null;
|
|
109
|
+
if (row.operation === "archive" || !merchantId) continue;
|
|
110
|
+
if (!(await merchantHeldElsewhere(db, clientId, row.provider, merchantId))) continue;
|
|
111
|
+
problems.push({ path: ["integrations", index, unarchive ? "provider" : "externalMerchantId"], code: "MERCHANT_TAKEN" });
|
|
112
|
+
}
|
|
113
|
+
return problems;
|
|
114
|
+
}
|
|
115
|
+
|
|
90
116
|
/** Thrown inside the transaction to roll a `validateOnly` call back. */
|
|
91
117
|
class ValidateOnly extends Error {
|
|
92
118
|
constructor() {
|
|
@@ -136,14 +162,15 @@ export async function upsertIntegrations(
|
|
|
136
162
|
ctx: EngineContext,
|
|
137
163
|
input: { clientId: string; actorId: string | null; rows: readonly IntegrationRowInput[]; validateOnly?: boolean },
|
|
138
164
|
): Promise<BulkResult<MarketplaceIntegrationView>> {
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
);
|
|
165
|
+
const stored = await listMarketplaceIntegrations(ctx, input.clientId, { includeArchived: true });
|
|
166
|
+
const existing = new Set(stored.map((row) => row.provider));
|
|
167
|
+
const merchantOf = new Map(stored.map((row) => [row.provider as string, row.externalMerchantId]));
|
|
142
168
|
const problems = [
|
|
143
169
|
...duplicates(input.rows, (row) => row.provider, "integrations", "provider"),
|
|
144
170
|
...unknownProviders(ctx, input.rows, "integrations"),
|
|
145
171
|
...input.rows.flatMap((row, index) => integrationRowProblems(row, index, existing)),
|
|
146
172
|
];
|
|
173
|
+
if (problems.length === 0) problems.push(...(await merchantProblems(ctx, input.clientId, input.rows, merchantOf)));
|
|
147
174
|
if (problems.length > 0) return { kind: "refused", problems };
|
|
148
175
|
|
|
149
176
|
const validateOnly = input.validateOnly === true;
|
|
@@ -151,10 +178,18 @@ export async function upsertIntegrations(
|
|
|
151
178
|
// The audit lines are written INSIDE the archive's transaction, through its
|
|
152
179
|
// client: an archive never lands without its line, and an audit that fails
|
|
153
180
|
// rolls the archive back. A `validateOnly` call rolls both back.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
181
|
+
try {
|
|
182
|
+
await inTransaction(ctx, validateOnly, async (db) => {
|
|
183
|
+
for (const row of input.rows) await writeIntegration(ctx, db, input.clientId, row, now);
|
|
184
|
+
await auditArchives(ctx, db, input, now);
|
|
185
|
+
});
|
|
186
|
+
} catch (error) {
|
|
187
|
+
// A race lost to another store's write of the same merchant, seen by the save's own check or the unique index.
|
|
188
|
+
const raced = error instanceof MarketplaceMerchantTakenError || isUniqueViolation(error);
|
|
189
|
+
const lost = raced ? await merchantProblems(ctx, input.clientId, input.rows, merchantOf) : [];
|
|
190
|
+
if (lost.length === 0) throw error;
|
|
191
|
+
return { kind: "refused", problems: lost };
|
|
192
|
+
}
|
|
158
193
|
const providers = input.rows.map((row) => row.provider);
|
|
159
194
|
const rows = validateOnly
|
|
160
195
|
? []
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { AdapterCallContext, OutboundOrderRef, OutboundResult } from "./adapter";
|
|
2
|
+
import type { MarketplaceDeliveredBy } from "./types";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The marketplace's own courier (FUT-5665): what an adapter can do about the
|
|
6
|
+
* courier its marketplace sends, and what the host is told. Optional in every
|
|
7
|
+
* type, so a host or an adapter that knows nothing of it compiles unchanged.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Where the marketplace's courier is, as its tracking read says. Every field null when unstated. */
|
|
11
|
+
export interface MarketplaceCourierTracking {
|
|
12
|
+
/** When the courier reaches the store: the "chega em" time. */
|
|
13
|
+
pickupEtaAt: Date | null;
|
|
14
|
+
/** When the marketplace expects the bag at the buyer's door. */
|
|
15
|
+
deliveryEtaAt: Date | null;
|
|
16
|
+
latitude: number | null;
|
|
17
|
+
longitude: number | null;
|
|
18
|
+
/** When the marketplace took this reading. */
|
|
19
|
+
trackedAt: Date | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What an adapter's pickup-code check answers: the marketplace's verdict, or why there is none. */
|
|
23
|
+
export type PickupCodeCallResult =
|
|
24
|
+
| { kind: "answered"; valid: boolean }
|
|
25
|
+
| Exclude<OutboundResult, { kind: "accepted" }>;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What an adapter's tracking read answers: the reading; `notYet` (no courier
|
|
29
|
+
* is assigned, so there is nothing to track); or the refusal and retry shapes
|
|
30
|
+
* of an outbound call.
|
|
31
|
+
*/
|
|
32
|
+
export type CourierTrackingCallResult =
|
|
33
|
+
| { kind: "tracking"; tracking: MarketplaceCourierTracking }
|
|
34
|
+
| { kind: "notYet" }
|
|
35
|
+
| Exclude<OutboundResult, { kind: "accepted" }>;
|
|
36
|
+
|
|
37
|
+
/** The courier calls one marketplace takes. Present on an adapter whose marketplace has them (iFood). */
|
|
38
|
+
export interface MarketplaceCourierApi {
|
|
39
|
+
/**
|
|
40
|
+
* Tell the marketplace the code the store checked at the hand-over, and
|
|
41
|
+
* read its verdict. Called only from the `marketplace.outbound` job, action
|
|
42
|
+
* `validatePickupCode`, after the host's own hand-over committed.
|
|
43
|
+
*/
|
|
44
|
+
validatePickupCode(ctx: AdapterCallContext, order: OutboundOrderRef, input: { code: string }): Promise<PickupCodeCallResult>;
|
|
45
|
+
/** Read where the courier is. Called only by `engine.courierTracking`, which the host runs in a job. */
|
|
46
|
+
tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promise<CourierTrackingCallResult>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The marketplace's verdict on a pickup code, as the host is told it:
|
|
51
|
+
* `VALID`, `INVALID` (the hand-over has committed: warn, move nothing) or
|
|
52
|
+
* `UNVERIFIED` (no verdict came: a final refusal, retries that ran out, no
|
|
53
|
+
* connection).
|
|
54
|
+
*/
|
|
55
|
+
export type PickupCodeValidation = "VALID" | "INVALID" | "UNVERIFIED";
|
|
56
|
+
|
|
57
|
+
/** What the engine tells the host with a courier event. */
|
|
58
|
+
export interface MarketplaceCourierFacts {
|
|
59
|
+
/** Who carries the delivery, as the acceptance row holds it. */
|
|
60
|
+
deliveredBy: MarketplaceDeliveredBy | null;
|
|
61
|
+
/** When it happened: the event's own instant, or the engine's clock when the event states none. */
|
|
62
|
+
at: Date;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The host's answer to a courier event: `recorded` (it stored the facts),
|
|
67
|
+
* `unchanged` (nothing to store, with the engine's reason), or `unchanged`
|
|
68
|
+
* with the host's own reason, which becomes the inbox row's.
|
|
69
|
+
*/
|
|
70
|
+
export type MarketplaceCourierAnswer = "recorded" | "unchanged" | { kind: "unchanged"; reason: string };
|
|
71
|
+
|
|
72
|
+
/** What `engine.courierTracking` answers. */
|
|
73
|
+
export type CourierTrackingResult =
|
|
74
|
+
| CourierTrackingCallResult
|
|
75
|
+
/** Nothing to call: no such marketplace order, a marketplace with no tracking, or a bag the store carries itself. */
|
|
76
|
+
| { kind: "unsupported"; reason: string };
|
|
77
|
+
|
|
78
|
+
/** What the host says after its hand-over committed. */
|
|
79
|
+
export interface ValidatePickupCodeInput {
|
|
80
|
+
clientId: string;
|
|
81
|
+
/** The host's order id. */
|
|
82
|
+
orderId: string;
|
|
83
|
+
/** The code the store checked (the one the courier stated). */
|
|
84
|
+
code: string;
|
|
85
|
+
/** The hand-over's own instant: it makes the job's key, so a hand-over after an undo is a new job. */
|
|
86
|
+
at: Date;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The engine's courier calls (FUT-5665), part of `MarketplaceEngine`. */
|
|
90
|
+
export interface MarketplaceCourierEngine {
|
|
91
|
+
/**
|
|
92
|
+
* The store handed a marketplace courier's bag over after checking the
|
|
93
|
+
* pickup code locally: ONE enqueue of `marketplace.outbound`, action
|
|
94
|
+
* `validatePickupCode`, after the hand-over's commit. Never throws, runs no
|
|
95
|
+
* statement and calls nobody. True when the queue took it.
|
|
96
|
+
*/
|
|
97
|
+
validatePickupCode(input: ValidatePickupCodeInput): Promise<boolean>;
|
|
98
|
+
/** Read where the marketplace's courier is: one call to the marketplace, at once. Run it from a job. */
|
|
99
|
+
courierTracking(input: { clientId: string; orderId: string }): Promise<CourierTrackingResult>;
|
|
100
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import type { OutboundOrderRef } from "./adapter";
|
|
2
|
+
import type { CourierTrackingResult, MarketplaceCourierAnswer, MarketplaceCourierEngine } from "./courier-port";
|
|
3
|
+
import { deferInboxEvent, settleInboxEvent } from "./inbox";
|
|
4
|
+
import type { IngestSettings } from "./ingest";
|
|
5
|
+
import { readOutboundConnection } from "./integration";
|
|
6
|
+
import { followLifecycle } from "./lifecycle";
|
|
7
|
+
import { validatePickupCode } from "./pickup-code";
|
|
8
|
+
import type { DeliveryOutcome } from "./pipeline";
|
|
9
|
+
import type { EngineContext } from "./ports";
|
|
10
|
+
import type { MarketplaceDeliveredBy, MarketplaceCourierStep, NormalizedEvent } from "./types";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The marketplace's own courier (FUT-5665), the engine's half: courier events
|
|
14
|
+
* reach the host's `onCourier`, and the host's job reads the tracking.
|
|
15
|
+
*
|
|
16
|
+
* A courier event moves nothing: it is a fact the host stores (who is coming,
|
|
17
|
+
* when they arrived, the bag coming back). The one that also moves the order,
|
|
18
|
+
* `COLLECTED`, names the lifecycle too and goes through `followLifecycle`
|
|
19
|
+
* like a `DISPATCHED`, after the host stored its facts.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
interface CourierAcceptance {
|
|
23
|
+
orderId: string;
|
|
24
|
+
status: string;
|
|
25
|
+
deliveredBy: string | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What the courier half made of an event, before the inbox row is settled. */
|
|
29
|
+
type CourierStepOutcome =
|
|
30
|
+
| { kind: "deferred" }
|
|
31
|
+
| { kind: "stopped"; reason: string }
|
|
32
|
+
| { kind: "recorded"; orderId: string; step: MarketplaceCourierStep };
|
|
33
|
+
|
|
34
|
+
function deliveredByOf(value: string | null): MarketplaceDeliveredBy | null {
|
|
35
|
+
return value === "MERCHANT" || value === "MARKETPLACE" ? value : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function reasonOf(answer: MarketplaceCourierAnswer, step: MarketplaceCourierStep): string {
|
|
39
|
+
if (answer === "unchanged") return `nothing to record for ${step}`;
|
|
40
|
+
return answer === "recorded" ? "" : answer.reason;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Hand the courier's facts to the host, or null when this host or this event has none. */
|
|
44
|
+
async function followCourier(ctx: EngineContext, clientId: string, event: NormalizedEvent): Promise<CourierStepOutcome | null> {
|
|
45
|
+
const hook = ctx.ports.order.onCourier;
|
|
46
|
+
const courier = event.courier;
|
|
47
|
+
if (!hook || !courier || !event.externalOrderId) return null;
|
|
48
|
+
const db = await ctx.ports.db();
|
|
49
|
+
const held = (await db.marketplaceAcceptance.findFirst({
|
|
50
|
+
where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
|
|
51
|
+
select: { orderId: true, status: true, deliveredBy: true },
|
|
52
|
+
})) as CourierAcceptance | null;
|
|
53
|
+
if (!held) return { kind: "deferred" };
|
|
54
|
+
if (held.status !== "ACCEPTED") return { kind: "stopped", reason: `the order is ${held.status}, not ACCEPTED` };
|
|
55
|
+
const facts = { deliveredBy: deliveredByOf(held.deliveredBy), at: courier.at ?? ctx.ports.clock.now() };
|
|
56
|
+
const answer = await hook.call(ctx.ports.order, clientId, held.orderId, courier, facts);
|
|
57
|
+
if (answer === "recorded") return { kind: "recorded", orderId: held.orderId, step: courier.step };
|
|
58
|
+
return { kind: "stopped", reason: reasonOf(answer, courier.step) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Settle the inbox row for a courier event that named no lifecycle the host moved on. */
|
|
62
|
+
async function settleCourier(
|
|
63
|
+
ctx: EngineContext,
|
|
64
|
+
inboxId: string,
|
|
65
|
+
clientId: string,
|
|
66
|
+
outcome: CourierStepOutcome,
|
|
67
|
+
): Promise<DeliveryOutcome> {
|
|
68
|
+
if (outcome.kind === "recorded") {
|
|
69
|
+
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
70
|
+
ctx.ports.publishChanged(clientId);
|
|
71
|
+
return { kind: "courier", orderId: outcome.orderId, step: outcome.step };
|
|
72
|
+
}
|
|
73
|
+
if (outcome.kind === "deferred") {
|
|
74
|
+
const reason = "courier event before its order";
|
|
75
|
+
await deferInboxEvent(ctx, inboxId, reason);
|
|
76
|
+
return { kind: "ignored", reason };
|
|
77
|
+
}
|
|
78
|
+
await settleInboxEvent(ctx, inboxId, "IGNORED", outcome.reason);
|
|
79
|
+
return { kind: "ignored", reason: outcome.reason };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The courier's facts first, then the lifecycle the event names: null when
|
|
84
|
+
* neither applies (the caller then does what it did before). A lifecycle that
|
|
85
|
+
* moved the order answers for the row; one that moved nothing (already past
|
|
86
|
+
* it, an echo) leaves the row to the courier's facts when they were recorded.
|
|
87
|
+
*/
|
|
88
|
+
export async function followCourierAndLifecycle(
|
|
89
|
+
ctx: EngineContext,
|
|
90
|
+
inboxId: string,
|
|
91
|
+
clientId: string,
|
|
92
|
+
event: NormalizedEvent,
|
|
93
|
+
settings: IngestSettings,
|
|
94
|
+
): Promise<DeliveryOutcome | null> {
|
|
95
|
+
const courier = await followCourier(ctx, clientId, event);
|
|
96
|
+
const followed = await followLifecycle(ctx, inboxId, clientId, event, settings);
|
|
97
|
+
const recorded = courier?.kind === "recorded";
|
|
98
|
+
if (followed && !(recorded && followed.kind === "ignored")) return followed;
|
|
99
|
+
return courier ? settleCourier(ctx, inboxId, clientId, courier) : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface TrackedAcceptance {
|
|
103
|
+
orderId: string;
|
|
104
|
+
provider: string;
|
|
105
|
+
externalOrderId: string;
|
|
106
|
+
externalDisplayId: string | null;
|
|
107
|
+
deliveredBy: string | null;
|
|
108
|
+
createdAt: Date;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Read where the marketplace's courier is (FUT-5665). Calls the marketplace at
|
|
113
|
+
* once, so the host runs it in a job, never on a tap or a screen load, and at
|
|
114
|
+
* the marketplace's own rate (iFood: at most once per 30 s). `notYet` before a
|
|
115
|
+
* courier is assigned; `unsupported` with no call for an order the engine does
|
|
116
|
+
* not hold, a marketplace with no tracking, or a bag the store carries itself.
|
|
117
|
+
*/
|
|
118
|
+
async function readCourierTracking(
|
|
119
|
+
ctx: EngineContext,
|
|
120
|
+
input: { clientId: string; orderId: string },
|
|
121
|
+
): Promise<CourierTrackingResult> {
|
|
122
|
+
const db = await ctx.ports.db();
|
|
123
|
+
const row = (await db.marketplaceAcceptance.findFirst({
|
|
124
|
+
where: { clientId: input.clientId, orderId: input.orderId },
|
|
125
|
+
select: { orderId: true, provider: true, externalOrderId: true, externalDisplayId: true, deliveredBy: true, createdAt: true },
|
|
126
|
+
})) as TrackedAcceptance | null;
|
|
127
|
+
if (!row) return { kind: "unsupported", reason: "no marketplace order with this id" };
|
|
128
|
+
const api = ctx.registry.get(row.provider)?.courier;
|
|
129
|
+
if (!api) return { kind: "unsupported", reason: `${row.provider} has no courier tracking` };
|
|
130
|
+
if (row.deliveredBy !== "MARKETPLACE") return { kind: "unsupported", reason: "the order is not carried by the marketplace's courier" };
|
|
131
|
+
let connection;
|
|
132
|
+
try {
|
|
133
|
+
connection = await readOutboundConnection(ctx, input.clientId, row.provider);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
return { kind: "refused", status: 0, message: `credentials do not open: ${error instanceof Error ? error.message : String(error)}`, own: true };
|
|
136
|
+
}
|
|
137
|
+
if (!connection) return { kind: "refused", status: 0, message: "no credentials on file", own: true };
|
|
138
|
+
const ref: OutboundOrderRef = {
|
|
139
|
+
externalOrderId: row.externalOrderId,
|
|
140
|
+
externalDisplayId: row.externalDisplayId,
|
|
141
|
+
hostOrderCode: row.orderId,
|
|
142
|
+
placedAt: row.createdAt,
|
|
143
|
+
};
|
|
144
|
+
return api.tracking({ http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection }, ref);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The engine's courier calls, bound to its context. */
|
|
148
|
+
export function courierEngine(ctx: EngineContext): MarketplaceCourierEngine {
|
|
149
|
+
return {
|
|
150
|
+
validatePickupCode: (input) => validatePickupCode(ctx, input),
|
|
151
|
+
courierTracking: (input) => readCourierTracking(ctx, input),
|
|
152
|
+
};
|
|
153
|
+
}
|
package/src/core/engine.ts
CHANGED
|
@@ -35,6 +35,8 @@ import type { CatalogueMenuOptions } from "./catalogue-port";
|
|
|
35
35
|
import { readMarketplaceCatalogue } from "./catalogue-read";
|
|
36
36
|
import type { CatalogueReadResult } from "./catalogue-read-port";
|
|
37
37
|
import type { CataloguePublicationView } from "./catalogue-store";
|
|
38
|
+
import { courierEngine } from "./courier";
|
|
39
|
+
import type { MarketplaceCourierEngine } from "./courier-port";
|
|
38
40
|
import {
|
|
39
41
|
runFetchOrder,
|
|
40
42
|
type FetchOrderJobPayload,
|
|
@@ -52,12 +54,23 @@ import { ingestMarketplaceOrder, type IngestResult, type IngestSettings } from "
|
|
|
52
54
|
import {
|
|
53
55
|
listMarketplaceIntegrations,
|
|
54
56
|
resolveIngestionTarget,
|
|
55
|
-
resolveTenantByMerchant,
|
|
56
57
|
saveMarketplaceIntegration,
|
|
57
58
|
type IngestionTarget,
|
|
58
59
|
type MarketplaceIntegrationView,
|
|
59
60
|
type SaveMarketplaceIntegrationInput,
|
|
60
61
|
} from "./integration";
|
|
62
|
+
import {
|
|
63
|
+
finishLink,
|
|
64
|
+
linkState,
|
|
65
|
+
linkedMerchants,
|
|
66
|
+
selectLinkedMerchant,
|
|
67
|
+
startLink,
|
|
68
|
+
type LinkFailure,
|
|
69
|
+
type LinkFinished,
|
|
70
|
+
type LinkPendingView,
|
|
71
|
+
} from "./linking";
|
|
72
|
+
import type { LinkedMerchant } from "./linking-port";
|
|
73
|
+
import { guardMerchantClaim, resolveTenantByMerchant } from "./merchant-claim";
|
|
61
74
|
import { listMarketplaceMenuLinks, type MarketplaceMenuLinkView } from "./menu-links";
|
|
62
75
|
import { runOutbound, type OutboundAttempt, type OutboundOutcome } from "./outbound";
|
|
63
76
|
import { informStatus, type InformStatusInput } from "./status-inform";
|
|
@@ -86,7 +99,7 @@ import { readOrderStates, type MarketplaceOrderState } from "./state";
|
|
|
86
99
|
import type { MarketplaceProvider, NormalizedEvent, NormalizedMarketplaceOrder } from "./types";
|
|
87
100
|
|
|
88
101
|
/** Everything the mounted engine can do, with the ports and adapters bound in. */
|
|
89
|
-
export interface MarketplaceEngine {
|
|
102
|
+
export interface MarketplaceEngine extends MarketplaceCourierEngine {
|
|
90
103
|
/** Every registered marketplace, in registration order. */
|
|
91
104
|
providers(): readonly MarketplaceProvider[];
|
|
92
105
|
/** Whether a provider id (a URL segment, a body field) names a registered adapter. */
|
|
@@ -131,7 +144,7 @@ export interface MarketplaceEngine {
|
|
|
131
144
|
clientId: string,
|
|
132
145
|
options?: { providers?: readonly string[]; includeArchived?: boolean },
|
|
133
146
|
): Promise<MarketplaceIntegrationView[]>;
|
|
134
|
-
/** Create or patch ONE connection (the bulk call's single-row form, with no audit). */
|
|
147
|
+
/** Create or patch ONE connection (the bulk call's single-row form, with no audit). Throws MarketplaceMerchantTakenError. */
|
|
135
148
|
saveIntegration(input: SaveMarketplaceIntegrationInput): Promise<MarketplaceIntegrationView>;
|
|
136
149
|
/** Create, patch, archive or unarchive many connections, all-or-nothing. */
|
|
137
150
|
upsertIntegrations(input: {
|
|
@@ -141,6 +154,43 @@ export interface MarketplaceEngine {
|
|
|
141
154
|
validateOnly?: boolean;
|
|
142
155
|
}): Promise<BulkResult<MarketplaceIntegrationView>>;
|
|
143
156
|
|
|
157
|
+
/**
|
|
158
|
+
* Whether this store can link this marketplace through the software's own
|
|
159
|
+
* app (FUT-5613), and the linking it left in progress. `available` is false
|
|
160
|
+
* when the adapter links nothing, the host configured no app for it, or the
|
|
161
|
+
* link table is not composed: the store's own credentials still work.
|
|
162
|
+
*/
|
|
163
|
+
linkState(input: {
|
|
164
|
+
clientId: string;
|
|
165
|
+
provider: MarketplaceProvider;
|
|
166
|
+
environment?: "SANDBOX" | "PRODUCTION";
|
|
167
|
+
}): Promise<{ available: boolean; pending: LinkPendingView | null }>;
|
|
168
|
+
/** Ask for the portal code; the verifier stays sealed server-side. Replaces an earlier attempt. */
|
|
169
|
+
startLink(input: {
|
|
170
|
+
clientId: string;
|
|
171
|
+
provider: MarketplaceProvider;
|
|
172
|
+
environment?: "SANDBOX" | "PRODUCTION";
|
|
173
|
+
}): Promise<{ kind: "started"; pending: LinkPendingView } | LinkFailure>;
|
|
174
|
+
/** Exchange the pasted authorization code for the store's tokens; select the merchant when only one. */
|
|
175
|
+
finishLink(input: {
|
|
176
|
+
clientId: string;
|
|
177
|
+
provider: MarketplaceProvider;
|
|
178
|
+
authorizationCode: string;
|
|
179
|
+
actorId: string | null;
|
|
180
|
+
enabled?: boolean;
|
|
181
|
+
}): Promise<LinkFinished | LinkFailure>;
|
|
182
|
+
/** The merchants a linked connection's grant covers. */
|
|
183
|
+
linkedMerchants(input: {
|
|
184
|
+
clientId: string;
|
|
185
|
+
provider: MarketplaceProvider;
|
|
186
|
+
}): Promise<{ kind: "listed"; merchants: LinkedMerchant[] } | LinkFailure>;
|
|
187
|
+
/** Choose the marketplace store of a linked connection whose grant covers several. */
|
|
188
|
+
selectLinkedMerchant(input: {
|
|
189
|
+
clientId: string;
|
|
190
|
+
provider: MarketplaceProvider;
|
|
191
|
+
merchantId: string;
|
|
192
|
+
}): Promise<{ kind: "selected"; integration: MarketplaceIntegrationView } | LinkFailure>;
|
|
193
|
+
|
|
144
194
|
/** The SKU map. `unmappedOnly` is the store's attention list; `ids` narrows. */
|
|
145
195
|
menuLinks(input: {
|
|
146
196
|
clientId: string;
|
|
@@ -295,8 +345,16 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
295
345
|
deliver: (input) => processDelivery(ctx, input),
|
|
296
346
|
|
|
297
347
|
integrations: (clientId, options) => listMarketplaceIntegrations(ctx, clientId, options),
|
|
298
|
-
saveIntegration:
|
|
348
|
+
saveIntegration: (input) =>
|
|
349
|
+
guardMerchantClaim(ctx, { ...input, merchantId: input.externalMerchantId }, async () =>
|
|
350
|
+
saveMarketplaceIntegration(ctx, input, await ports.db()),
|
|
351
|
+
),
|
|
299
352
|
upsertIntegrations: (input) => upsertIntegrations(ctx, input),
|
|
353
|
+
linkState: (input) => linkState(ctx, input),
|
|
354
|
+
startLink: (input) => startLink(ctx, input),
|
|
355
|
+
finishLink: (input) => finishLink(ctx, input),
|
|
356
|
+
linkedMerchants: (input) => linkedMerchants(ctx, input),
|
|
357
|
+
selectLinkedMerchant: (input) => selectLinkedMerchant(ctx, input),
|
|
300
358
|
|
|
301
359
|
menuLinks: (input) => listMarketplaceMenuLinks(ctx, input),
|
|
302
360
|
upsertMenuLinks: (input) => upsertMenuLinks(ctx, input),
|
|
@@ -319,6 +377,7 @@ export function createMarketplaceEngine(config: MarketplaceEngineConfig): Market
|
|
|
319
377
|
runOutbound: (payload, attempt) => runOutbound(ctx, payload, attempt),
|
|
320
378
|
runFetchOrder: (payload, attempt) => runFetchOrder(ctx, payload, attempt),
|
|
321
379
|
informStatus: (input) => informStatus(ctx, input),
|
|
380
|
+
...courierEngine(ctx),
|
|
322
381
|
|
|
323
382
|
// Null too when the host bound no catalogue port: nothing could be published.
|
|
324
383
|
catalogueMode: (provider) => (ports.catalogue ? (registry.get(provider)?.catalogue?.mode ?? null) : null),
|
package/src/core/integration.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type { MarketplaceCredentials } from "./adapter";
|
|
1
|
+
import type { AdapterGrant, MarketplaceCredentials } from "./adapter";
|
|
2
|
+
import { appCredentialsOf, linkGrant, openLinkRefreshToken, type MarketplaceAuthMode } from "./link-store";
|
|
3
|
+
import { assertMerchantFree } from "./merchant-claim";
|
|
2
4
|
import type { EngineContext, MarketplaceDb } from "./ports";
|
|
3
5
|
import type { MarketplaceProvider } from "./types";
|
|
4
6
|
|
|
@@ -37,6 +39,12 @@ export interface MarketplaceIntegrationView {
|
|
|
37
39
|
lastVerifiedAt: Date | null;
|
|
38
40
|
/** Archived connections ingest nothing; null while live. */
|
|
39
41
|
archivedAt: Date | null;
|
|
42
|
+
/**
|
|
43
|
+
* How the connection authenticates (FUT-5613): CREDENTIALS, the store's own
|
|
44
|
+
* app; LINKED, the software's app the store authorized. Always set by this
|
|
45
|
+
* version; optional in the type so a view built by hand against 1.x compiles.
|
|
46
|
+
*/
|
|
47
|
+
authMode?: MarketplaceAuthMode;
|
|
40
48
|
}
|
|
41
49
|
|
|
42
50
|
interface IntegrationRow {
|
|
@@ -52,6 +60,7 @@ interface IntegrationRow {
|
|
|
52
60
|
lastEventAt: Date | null;
|
|
53
61
|
lastVerifiedAt: Date | null;
|
|
54
62
|
archivedAt: Date | null;
|
|
63
|
+
authMode?: string;
|
|
55
64
|
}
|
|
56
65
|
|
|
57
66
|
const VIEW_SELECT = {
|
|
@@ -67,6 +76,7 @@ const VIEW_SELECT = {
|
|
|
67
76
|
lastEventAt: true,
|
|
68
77
|
lastVerifiedAt: true,
|
|
69
78
|
archivedAt: true,
|
|
79
|
+
authMode: true,
|
|
70
80
|
} as const;
|
|
71
81
|
|
|
72
82
|
function toView(row: IntegrationRow): MarketplaceIntegrationView {
|
|
@@ -83,6 +93,7 @@ function toView(row: IntegrationRow): MarketplaceIntegrationView {
|
|
|
83
93
|
lastEventAt: row.lastEventAt,
|
|
84
94
|
lastVerifiedAt: row.lastVerifiedAt,
|
|
85
95
|
archivedAt: row.archivedAt ?? null,
|
|
96
|
+
authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS",
|
|
86
97
|
};
|
|
87
98
|
}
|
|
88
99
|
|
|
@@ -139,12 +150,16 @@ export interface SaveMarketplaceIntegrationInput {
|
|
|
139
150
|
* Re-entering credentials resets `status` to UNVERIFIED. The stored status is a
|
|
140
151
|
* claim about a specific secret; carrying VERIFIED across a credential change
|
|
141
152
|
* would assert that a probe which never ran had passed.
|
|
153
|
+
*
|
|
154
|
+
* A merchant id another store's live connection holds is refused with
|
|
155
|
+
* `MarketplaceMerchantTakenError`: the app's webhook routes by it.
|
|
142
156
|
*/
|
|
143
157
|
export async function saveMarketplaceIntegration(
|
|
144
158
|
ctx: EngineContext,
|
|
145
159
|
input: SaveMarketplaceIntegrationInput,
|
|
146
160
|
db: MarketplaceDb,
|
|
147
161
|
): Promise<MarketplaceIntegrationView> {
|
|
162
|
+
await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
|
|
148
163
|
const sealed = input.credentials
|
|
149
164
|
? ctx.ports.secrets.seal(JSON.stringify(input.credentials))
|
|
150
165
|
: undefined;
|
|
@@ -157,7 +172,8 @@ export async function saveMarketplaceIntegration(
|
|
|
157
172
|
...(input.autoAccept === undefined ? {} : { autoAccept: input.autoAccept }),
|
|
158
173
|
...(input.followStatus === undefined ? {} : { followStatus: input.followStatus }),
|
|
159
174
|
...(input.ackSlaSeconds === undefined ? {} : { ackSlaSeconds: input.ackSlaSeconds }),
|
|
160
|
-
|
|
175
|
+
// Typed credentials make the connection the store's own app again.
|
|
176
|
+
...(sealed === undefined ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }),
|
|
161
177
|
};
|
|
162
178
|
const row = (await db.marketplaceIntegration.upsert({
|
|
163
179
|
where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
|
|
@@ -230,8 +246,12 @@ export async function resolveIngestionTarget(
|
|
|
230
246
|
credentials: true,
|
|
231
247
|
archivedAt: true,
|
|
232
248
|
externalMerchantId: true,
|
|
249
|
+
authMode: true,
|
|
250
|
+
environment: true,
|
|
233
251
|
},
|
|
234
252
|
})) as {
|
|
253
|
+
authMode?: string;
|
|
254
|
+
environment?: string;
|
|
235
255
|
externalMerchantId: string | null;
|
|
236
256
|
enabled: boolean;
|
|
237
257
|
autoAccept: boolean;
|
|
@@ -251,11 +271,35 @@ export async function resolveIngestionTarget(
|
|
|
251
271
|
// An unopenable blob must not read as "no secret configured" — that would
|
|
252
272
|
// turn a key-rotation problem into an endpoint that accepts unsigned
|
|
253
273
|
// deliveries. The secrets port throws instead, and the caller answers 401.
|
|
254
|
-
webhookSecret:
|
|
255
|
-
row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret,
|
|
274
|
+
webhookSecret: await webhookSecretOf(ctx, provider, row),
|
|
256
275
|
};
|
|
257
276
|
}
|
|
258
277
|
|
|
278
|
+
/**
|
|
279
|
+
* The key a connection's deliveries are verified against: the store's own,
|
|
280
|
+
* or, for a linked connection, the software's app's (FUT-5613). A linked
|
|
281
|
+
* connection whose app is no longer configured THROWS, like a blob that will
|
|
282
|
+
* not open: it must never read as "no secret, accept unsigned".
|
|
283
|
+
*/
|
|
284
|
+
async function webhookSecretOf(
|
|
285
|
+
ctx: EngineContext,
|
|
286
|
+
provider: MarketplaceProvider,
|
|
287
|
+
row: { credentials: string; authMode?: string; environment?: string },
|
|
288
|
+
): Promise<string | null> {
|
|
289
|
+
if (row.authMode !== "LINKED") {
|
|
290
|
+
return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
|
|
291
|
+
}
|
|
292
|
+
const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
|
|
293
|
+
if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
|
|
294
|
+
// The marketplace signs with the app's client secret unless the host names another key.
|
|
295
|
+
const secret = app.webhookSecret || app.clientSecret;
|
|
296
|
+
if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
|
|
297
|
+
return secret;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const environmentOf = (value: string | undefined): "SANDBOX" | "PRODUCTION" =>
|
|
301
|
+
value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX";
|
|
302
|
+
|
|
259
303
|
/**
|
|
260
304
|
* Open a stored credential set.
|
|
261
305
|
*
|
|
@@ -281,28 +325,6 @@ function openCredentials(
|
|
|
281
325
|
};
|
|
282
326
|
}
|
|
283
327
|
|
|
284
|
-
/**
|
|
285
|
-
* Which tenant a delivery belongs to, resolved from the merchant id the
|
|
286
|
-
* marketplace names.
|
|
287
|
-
*
|
|
288
|
-
* Matched against the column OUTSIDE the ciphertext, which is the whole reason
|
|
289
|
-
* `externalMerchantId` lives there: attributing a delivery must not require
|
|
290
|
-
* decrypting every store's secrets to find the match.
|
|
291
|
-
*/
|
|
292
|
-
export async function resolveTenantByMerchant(
|
|
293
|
-
ctx: EngineContext,
|
|
294
|
-
provider: MarketplaceProvider,
|
|
295
|
-
externalMerchantId: string,
|
|
296
|
-
): Promise<string | null> {
|
|
297
|
-
const db = await ctx.ports.db();
|
|
298
|
-
const rows = (await db.marketplaceIntegration.findMany({
|
|
299
|
-
where: { provider, externalMerchantId, archivedAt: null },
|
|
300
|
-
select: { clientId: true },
|
|
301
|
-
take: 1,
|
|
302
|
-
})) as { clientId: string }[];
|
|
303
|
-
return rows[0]?.clientId ?? null;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
328
|
/** Stamp the connection's liveness marker. Best-effort; never blocks ingestion. */
|
|
307
329
|
export async function markMarketplaceEventSeen(
|
|
308
330
|
db: MarketplaceDb,
|
|
@@ -320,6 +342,8 @@ export async function markMarketplaceEventSeen(
|
|
|
320
342
|
export interface OutboundConnection {
|
|
321
343
|
environment: "SANDBOX" | "PRODUCTION";
|
|
322
344
|
credentials: MarketplaceCredentials;
|
|
345
|
+
/** A linked connection's token source (FUT-5613); absent for the store's own credentials. */
|
|
346
|
+
grant?: AdapterGrant;
|
|
323
347
|
}
|
|
324
348
|
|
|
325
349
|
/**
|
|
@@ -336,11 +360,15 @@ export async function readOutboundConnection(
|
|
|
336
360
|
const db = await ctx.ports.db();
|
|
337
361
|
const row = (await db.marketplaceIntegration.findUnique({
|
|
338
362
|
where: { clientId_provider: { clientId, provider } },
|
|
339
|
-
select: { environment: true, credentials: true },
|
|
340
|
-
})) as { environment: string; credentials: string } | null;
|
|
363
|
+
select: { environment: true, credentials: true, authMode: true },
|
|
364
|
+
})) as { environment: string; credentials: string; authMode?: string } | null;
|
|
341
365
|
if (!row || row.credentials === "") return null;
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
366
|
+
const environment = environmentOf(row.environment);
|
|
367
|
+
if (row.authMode !== "LINKED") return { environment, credentials: openCredentials(ctx, row.credentials) };
|
|
368
|
+
// Linked: the software's app speaks for the store, with the store's refresh token.
|
|
369
|
+
const app = await appCredentialsOf(ctx, provider, environment);
|
|
370
|
+
if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
|
|
371
|
+
const refreshToken = openLinkRefreshToken(ctx, row.credentials);
|
|
372
|
+
const link = { clientId, provider, environment, refreshToken, app, sealed: row.credentials };
|
|
373
|
+
return { environment, credentials: app, grant: linkGrant(ctx, link) };
|
|
346
374
|
}
|