@12-apps/marketplace 1.17.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.
- package/ADOPTING.md +70 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CxzF-qGx.d.ts → adapter-ZpAWKoCk.d.ts} +116 -2
- package/dist/{chunk-7IYUO2KC.js → chunk-3B5EULS6.js} +2 -2
- package/dist/{chunk-EABVLQKK.js → chunk-BLHZ3MRB.js} +2 -2
- package/dist/{chunk-UZO2NILN.js → chunk-MDEIRGNL.js} +1067 -877
- package/dist/chunk-MDEIRGNL.js.map +1 -0
- package/dist/{chunk-KKFMDV5K.js → chunk-Q5RMVNU5.js} +1 -1
- package/dist/{chunk-KKFMDV5K.js.map → chunk-Q5RMVNU5.js.map} +1 -1
- package/dist/{chunk-CF5BSXE5.js → chunk-ZT6TZTLD.js} +1 -1
- package/dist/chunk-ZT6TZTLD.js.map +1 -0
- package/dist/{client-C-4QvVq3.d.ts → client-DpEq0yXb.d.ts} +1 -1
- package/dist/{engine-Y6Rpf5p7.d.ts → engine-DRRhAjZK.d.ts} +171 -143
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +3 -3
- package/dist/ifood/index.d.ts +7 -2
- package/dist/ifood/index.js +138 -100
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +76 -5
- 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/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/index.d.ts +2 -2
- package/dist/server/index.js +3 -3
- package/package.json +1 -1
- package/prisma/marketplace.prisma +1 -1
- package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
- package/src/core/adapter.ts +2 -1
- package/src/core/delivery-code.ts +119 -0
- package/src/core/engine.ts +10 -2
- package/src/core/logistics.ts +388 -0
- package/src/core/outbound-queue.ts +6 -1
- package/src/core/outbound-sweep.ts +10 -5
- package/src/core/outbound.ts +4 -5
- package/src/core/pipeline.ts +6 -1
- package/src/core/ports.ts +5 -2
- package/src/core/status-job.ts +3 -0
- package/src/core/status-store.ts +2 -1
- package/src/core/types.ts +2 -0
- package/src/ifood/index.ts +3 -0
- package/src/ifood/logistics.ts +38 -0
- package/src/ifood/normalize.ts +11 -1
- package/src/index.ts +10 -0
- package/dist/chunk-CF5BSXE5.js.map +0 -1
- package/dist/chunk-UZO2NILN.js.map +0 -1
- /package/dist/{chunk-7IYUO2KC.js.map → chunk-3B5EULS6.js.map} +0 -0
- /package/dist/{chunk-EABVLQKK.js.map → chunk-BLHZ3MRB.js.map} +0 -0
|
@@ -1,922 +1,1139 @@
|
|
|
1
1
|
import {
|
|
2
2
|
PROVIDER_ID_PATTERN
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-Q5RMVNU5.js";
|
|
4
4
|
import {
|
|
5
5
|
__name
|
|
6
6
|
} from "./chunk-7QVYU63E.js";
|
|
7
7
|
|
|
8
|
-
// src/core/
|
|
9
|
-
var
|
|
8
|
+
// src/core/merchant-claim.ts
|
|
9
|
+
var MarketplaceMerchantTakenError = class extends Error {
|
|
10
10
|
static {
|
|
11
|
-
__name(this, "
|
|
11
|
+
__name(this, "MarketplaceMerchantTakenError");
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
13
|
+
code = "MERCHANT_TAKEN";
|
|
14
|
+
/** The field the refusal is about, as a problem path. */
|
|
15
|
+
path = ["externalMerchantId"];
|
|
16
|
+
constructor(provider, merchantId) {
|
|
17
|
+
super(`The ${provider} merchant ${merchantId} is already held by another store's live connection.`);
|
|
18
|
+
this.name = "MarketplaceMerchantTakenError";
|
|
16
19
|
}
|
|
17
20
|
};
|
|
18
|
-
function
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
if (reason.code.trim() === "") {
|
|
22
|
-
throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);
|
|
23
|
-
}
|
|
24
|
-
if (codes.has(reason.code)) {
|
|
25
|
-
throw new MarketplaceAdapterRegistrationError(
|
|
26
|
-
`${adapter.provider} declares the reason code "${reason.code}" twice.`
|
|
27
|
-
);
|
|
28
|
-
}
|
|
29
|
-
codes.add(reason.code);
|
|
30
|
-
}
|
|
31
|
-
if (adapter.capabilities.apiCancel && codes.size === 0) {
|
|
32
|
-
throw new MarketplaceAdapterRegistrationError(
|
|
33
|
-
`${adapter.provider} can cancel through its API but declares no reason to cancel with.`
|
|
34
|
-
);
|
|
35
|
-
}
|
|
21
|
+
function isUniqueViolation(error) {
|
|
22
|
+
const code = error?.code;
|
|
23
|
+
return code === "P2002" || code === "23505";
|
|
36
24
|
}
|
|
37
|
-
__name(
|
|
38
|
-
function
|
|
39
|
-
|
|
40
|
-
|
|
25
|
+
__name(isUniqueViolation, "isUniqueViolation");
|
|
26
|
+
async function merchantHeldElsewhere(db, clientId, provider, merchantId) {
|
|
27
|
+
const rows = await db.marketplaceIntegration.findMany({
|
|
28
|
+
where: { provider, externalMerchantId: merchantId, archivedAt: null },
|
|
29
|
+
select: { clientId: true }
|
|
30
|
+
});
|
|
31
|
+
return rows.some((row) => row.clientId !== clientId);
|
|
32
|
+
}
|
|
33
|
+
__name(merchantHeldElsewhere, "merchantHeldElsewhere");
|
|
34
|
+
async function assertMerchantFree(db, clientId, provider, merchantId) {
|
|
35
|
+
if (merchantId && await merchantHeldElsewhere(db, clientId, provider, merchantId)) {
|
|
36
|
+
throw new MarketplaceMerchantTakenError(provider, merchantId);
|
|
41
37
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
49
|
-
if (
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
assertReasons(adapter);
|
|
53
|
-
byProvider.set(adapter.provider, adapter);
|
|
38
|
+
}
|
|
39
|
+
__name(assertMerchantFree, "assertMerchantFree");
|
|
40
|
+
async function guardMerchantClaim(ctx, claim3, write2) {
|
|
41
|
+
try {
|
|
42
|
+
return await write2();
|
|
43
|
+
} catch (error) {
|
|
44
|
+
const { merchantId } = claim3;
|
|
45
|
+
if (!isUniqueViolation(error) || !merchantId) throw error;
|
|
46
|
+
if (!await merchantHeldElsewhere(await ctx.ports.db(), claim3.clientId, claim3.provider, merchantId)) throw error;
|
|
47
|
+
throw new MarketplaceMerchantTakenError(claim3.provider, merchantId);
|
|
54
48
|
}
|
|
55
|
-
const providers = [...byProvider.keys()];
|
|
56
|
-
return {
|
|
57
|
-
get: /* @__PURE__ */ __name((provider) => byProvider.get(provider) ?? null, "get"),
|
|
58
|
-
has: /* @__PURE__ */ __name((provider) => byProvider.has(provider), "has"),
|
|
59
|
-
providers: /* @__PURE__ */ __name(() => providers, "providers")
|
|
60
|
-
};
|
|
61
49
|
}
|
|
62
|
-
__name(
|
|
63
|
-
function
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
50
|
+
__name(guardMerchantClaim, "guardMerchantClaim");
|
|
51
|
+
async function resolveTenantByMerchant(ctx, provider, externalMerchantId) {
|
|
52
|
+
const db = await ctx.ports.db();
|
|
53
|
+
const rows = await db.marketplaceIntegration.findMany({
|
|
54
|
+
where: { provider, externalMerchantId, archivedAt: null },
|
|
55
|
+
select: { clientId: true },
|
|
56
|
+
take: 2
|
|
68
57
|
});
|
|
58
|
+
if (rows.length > 1) {
|
|
59
|
+
ctx.ports.logger.warn(`marketplace: ${provider} merchant ${externalMerchantId} is held by several live connections`);
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
return rows[0]?.clientId ?? null;
|
|
69
63
|
}
|
|
70
|
-
__name(
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
return
|
|
76
|
-
(reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false }
|
|
77
|
-
);
|
|
64
|
+
__name(resolveTenantByMerchant, "resolveTenantByMerchant");
|
|
65
|
+
|
|
66
|
+
// src/core/outbound-queue.ts
|
|
67
|
+
var MARKETPLACE_OUTBOUND_JOB = "marketplace.outbound";
|
|
68
|
+
function outboundDedupeKey(payload) {
|
|
69
|
+
return `${MARKETPLACE_OUTBOUND_JOB}:${payload.action}:${payload.step ? `${payload.step}:` : ""}${payload.orderId}`;
|
|
78
70
|
}
|
|
79
|
-
__name(
|
|
80
|
-
function
|
|
81
|
-
|
|
82
|
-
if (code === null || code === void 0) return reasons[0] ?? null;
|
|
83
|
-
return reasons.find((reason) => reason.code === code) ?? null;
|
|
71
|
+
__name(outboundDedupeKey, "outboundDedupeKey");
|
|
72
|
+
function statusDedupeKey(step, orderId, at) {
|
|
73
|
+
return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
|
|
84
74
|
}
|
|
85
|
-
__name(
|
|
86
|
-
function
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
75
|
+
__name(statusDedupeKey, "statusDedupeKey");
|
|
76
|
+
function ableTo(adapter, payload) {
|
|
77
|
+
switch (payload.action) {
|
|
78
|
+
case "status":
|
|
79
|
+
return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
|
|
80
|
+
case "logistics":
|
|
81
|
+
return Boolean(adapter.logistics);
|
|
82
|
+
case "confirm":
|
|
83
|
+
return adapter.capabilities.apiConfirm;
|
|
84
|
+
default:
|
|
85
|
+
return adapter.capabilities.apiCancel;
|
|
91
86
|
}
|
|
92
|
-
return reasons[0] ?? null;
|
|
93
87
|
}
|
|
94
|
-
__name(
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
ctx.ports.logger.
|
|
102
|
-
|
|
88
|
+
__name(ableTo, "ableTo");
|
|
89
|
+
async function enqueueOutbound(ctx, payload, provider, dedupeKey = outboundDedupeKey(payload)) {
|
|
90
|
+
const adapter = ctx.registry.get(provider);
|
|
91
|
+
if (!adapter) return false;
|
|
92
|
+
if (!ableTo(adapter, payload)) return false;
|
|
93
|
+
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, { dedupeKey });
|
|
94
|
+
if (!outcome.enqueued) {
|
|
95
|
+
ctx.ports.logger.warn(
|
|
96
|
+
`${MARKETPLACE_OUTBOUND_JOB}: ${payload.action} for order ${payload.orderId} was not queued; the outbound sweep will re-queue it` + (outcome.reason ? ` (${outcome.reason})` : "")
|
|
103
97
|
);
|
|
104
98
|
}
|
|
99
|
+
return outcome.enqueued;
|
|
105
100
|
}
|
|
106
|
-
__name(
|
|
107
|
-
|
|
108
|
-
|
|
101
|
+
__name(enqueueOutbound, "enqueueOutbound");
|
|
102
|
+
|
|
103
|
+
// src/core/link-store.ts
|
|
104
|
+
function sealLink(ctx, refreshToken) {
|
|
105
|
+
return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, refreshToken }));
|
|
109
106
|
}
|
|
110
|
-
__name(
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
await db.marketplaceAcceptance.updateMany({
|
|
117
|
-
where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
|
|
118
|
-
data: { status: "REJECTED" }
|
|
119
|
-
});
|
|
107
|
+
__name(sealLink, "sealLink");
|
|
108
|
+
function openLinkRefreshToken(ctx, sealed) {
|
|
109
|
+
const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
|
|
110
|
+
const token = typeof parsed === "object" && parsed !== null ? parsed.refreshToken : null;
|
|
111
|
+
if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
|
|
112
|
+
return token;
|
|
120
113
|
}
|
|
121
|
-
__name(
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
|
|
114
|
+
__name(openLinkRefreshToken, "openLinkRefreshToken");
|
|
115
|
+
function sealAppLink(ctx) {
|
|
116
|
+
return ctx.ports.secrets.seal(JSON.stringify({ clientId: "", clientSecret: "", webhookSecret: null, app: true }));
|
|
125
117
|
}
|
|
126
|
-
__name(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
118
|
+
__name(sealAppLink, "sealAppLink");
|
|
119
|
+
function isAppLinkBlob(ctx, sealed) {
|
|
120
|
+
try {
|
|
121
|
+
const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
|
|
122
|
+
return typeof parsed === "object" && parsed !== null && parsed.app === true;
|
|
123
|
+
} catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
132
126
|
}
|
|
133
|
-
__name(
|
|
134
|
-
async function
|
|
135
|
-
const
|
|
136
|
-
if (!
|
|
137
|
-
await
|
|
138
|
-
|
|
139
|
-
`had its cancellation request fail (${reason})`,
|
|
140
|
-
orderId,
|
|
141
|
-
() => hook.call(ctx.ports.order, clientId, orderId, reason)
|
|
142
|
-
);
|
|
127
|
+
__name(isAppLinkBlob, "isAppLinkBlob");
|
|
128
|
+
async function appCredentialsOf(ctx, provider, environment) {
|
|
129
|
+
const port = ctx.ports.appCredentials;
|
|
130
|
+
if (!port) return null;
|
|
131
|
+
const credentials = await port(provider, environment);
|
|
132
|
+
return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
|
|
143
133
|
}
|
|
144
|
-
__name(
|
|
145
|
-
|
|
146
|
-
|
|
134
|
+
__name(appCredentialsOf, "appCredentialsOf");
|
|
135
|
+
var linkTokenKey = /* @__PURE__ */ __name((provider, environment, clientId) => `LINK:${provider}:${environment}:${clientId}`, "linkTokenKey");
|
|
136
|
+
async function cacheLinkToken(ctx, link, key, grant) {
|
|
137
|
+
const db = await ctx.ports.db();
|
|
138
|
+
const row = await db.marketplaceIntegration.findUnique({
|
|
139
|
+
where: { clientId_provider: { clientId: link.clientId, provider: link.provider } },
|
|
140
|
+
select: { credentials: true }
|
|
141
|
+
});
|
|
142
|
+
if (row?.credentials !== link.sealed) return false;
|
|
143
|
+
setToken(ctx, key, grant);
|
|
144
|
+
return true;
|
|
147
145
|
}
|
|
148
|
-
__name(
|
|
149
|
-
function
|
|
150
|
-
|
|
146
|
+
__name(cacheLinkToken, "cacheLinkToken");
|
|
147
|
+
function setToken(ctx, key, grant) {
|
|
148
|
+
const expiresAt = ctx.ports.clock.now().getTime() + Math.max(grant.expiresInSeconds, 1) * 1e3;
|
|
149
|
+
ctx.tokens.set(key, { token: grant.accessToken, expiresAt });
|
|
151
150
|
}
|
|
152
|
-
__name(
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
151
|
+
__name(setToken, "setToken");
|
|
152
|
+
var inflight = /* @__PURE__ */ new WeakMap();
|
|
153
|
+
async function storeRotated(ctx, link, refreshToken) {
|
|
154
|
+
const db = await ctx.ports.db();
|
|
155
|
+
const { count } = await db.marketplaceIntegration.updateMany({
|
|
156
|
+
where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", archivedAt: null, credentials: link.sealed },
|
|
157
|
+
data: { credentials: sealLink(ctx, refreshToken) }
|
|
158
|
+
});
|
|
159
|
+
return count > 0;
|
|
157
160
|
}
|
|
158
|
-
__name(
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
};
|
|
168
|
-
function notPendingProblem(row, path, allowed = ["AWAITING"]) {
|
|
169
|
-
if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
|
|
170
|
-
if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
|
|
171
|
-
const status = row.status;
|
|
172
|
-
return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
|
|
173
|
-
}
|
|
174
|
-
__name(notPendingProblem, "notPendingProblem");
|
|
175
|
-
function lineSkusOf(row) {
|
|
176
|
-
return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
|
|
161
|
+
__name(storeRotated, "storeRotated");
|
|
162
|
+
async function markLinkFailed(ctx, link) {
|
|
163
|
+
const db = await ctx.ports.db();
|
|
164
|
+
const { count } = await db.marketplaceIntegration.updateMany({
|
|
165
|
+
where: { clientId: link.clientId, provider: link.provider, authMode: "LINKED", credentials: link.sealed },
|
|
166
|
+
data: { status: "FAILED" }
|
|
167
|
+
});
|
|
168
|
+
if (count > 0) ctx.ports.publishChanged(link.clientId);
|
|
169
|
+
return count > 0;
|
|
177
170
|
}
|
|
178
|
-
__name(
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
const
|
|
182
|
-
if (!
|
|
183
|
-
|
|
184
|
-
|
|
171
|
+
__name(markLinkFailed, "markLinkFailed");
|
|
172
|
+
var RELINKED = { kind: "retry", reason: "the connection was linked again during the refresh" };
|
|
173
|
+
async function refreshOnce(ctx, link, key) {
|
|
174
|
+
const linking = ctx.registry.get(link.provider)?.linking;
|
|
175
|
+
if (!linking) return { kind: "refused", status: 0, message: "this marketplace links no store", own: true };
|
|
176
|
+
const answer = await linking.refresh(
|
|
177
|
+
{ http: ctx.ports.http, credentials: link.app, environment: link.environment, now: ctx.ports.clock.now() },
|
|
178
|
+
{ refreshToken: link.refreshToken }
|
|
185
179
|
);
|
|
180
|
+
if (answer.kind === "retry") return answer;
|
|
181
|
+
if (answer.kind === "refused") return await markLinkFailed(ctx, link) ? { ...answer, own: true } : RELINKED;
|
|
182
|
+
const rotated = answer.value.refreshToken;
|
|
183
|
+
if (rotated === null || rotated === link.refreshToken) {
|
|
184
|
+
return await cacheLinkToken(ctx, link, key, answer.value) ? { token: answer.value.accessToken } : RELINKED;
|
|
185
|
+
}
|
|
186
|
+
const stored = await storeRotated(ctx, link, rotated).catch((error) => {
|
|
187
|
+
ctx.ports.logger.error(
|
|
188
|
+
`marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` + (error instanceof Error ? error.message : String(error))
|
|
189
|
+
);
|
|
190
|
+
return null;
|
|
191
|
+
});
|
|
192
|
+
if (stored === false) return RELINKED;
|
|
193
|
+
setToken(ctx, key, answer.value);
|
|
194
|
+
return { token: answer.value.accessToken };
|
|
186
195
|
}
|
|
187
|
-
__name(
|
|
188
|
-
function
|
|
189
|
-
|
|
190
|
-
const validCodes = reasonsForOrder(adapter, input.stored).map((candidate) => candidate.code);
|
|
191
|
-
return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
|
|
192
|
-
}
|
|
193
|
-
__name(invalidReasonProblem, "invalidReasonProblem");
|
|
194
|
-
function planCancellation(adapter, input, row, path) {
|
|
195
|
-
if (!adapter) return { status: null, reason: null, skus: [] };
|
|
196
|
-
const reason = resolveReason(adapter, input.reasonCode, row.cancellationReasons);
|
|
197
|
-
const invalid = invalidReasonProblem(adapter, reason, { code: input.reasonCode, stored: row.cancellationReasons }, path);
|
|
198
|
-
if (invalid) return [invalid];
|
|
199
|
-
const skus = [...new Set(input.offendingSkus ?? [])];
|
|
200
|
-
const problems = skuProblems(reason, skus, row, path);
|
|
201
|
-
if (problems.length > 0) return problems;
|
|
202
|
-
const { apiCancel, cancelAfterAccept } = adapter.capabilities;
|
|
203
|
-
const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
|
|
204
|
-
return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
|
|
205
|
-
}
|
|
206
|
-
__name(planCancellation, "planCancellation");
|
|
207
|
-
function refusalData(plan, fromStatus, now) {
|
|
196
|
+
__name(refreshOnce, "refreshOnce");
|
|
197
|
+
function linkGrant(ctx, link) {
|
|
198
|
+
const key = linkTokenKey(link.provider, link.environment, link.clientId);
|
|
208
199
|
return {
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
200
|
+
key,
|
|
201
|
+
accessToken: /* @__PURE__ */ __name(async () => {
|
|
202
|
+
const cached = ctx.tokens.get(key);
|
|
203
|
+
if (cached && cached.expiresAt > ctx.ports.clock.now().getTime()) return { token: cached.token };
|
|
204
|
+
let running = inflight.get(ctx.tokens);
|
|
205
|
+
if (!running) {
|
|
206
|
+
running = /* @__PURE__ */ new Map();
|
|
207
|
+
inflight.set(ctx.tokens, running);
|
|
208
|
+
}
|
|
209
|
+
const pending = running.get(key);
|
|
210
|
+
if (pending) return pending;
|
|
211
|
+
const call2 = refreshOnce(ctx, link, key).catch((error) => ({
|
|
212
|
+
kind: "retry",
|
|
213
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
214
|
+
})).finally(() => running.delete(key));
|
|
215
|
+
running.set(key, call2);
|
|
216
|
+
return call2;
|
|
217
|
+
}, "accessToken")
|
|
219
218
|
};
|
|
220
219
|
}
|
|
221
|
-
__name(
|
|
222
|
-
|
|
220
|
+
__name(linkGrant, "linkGrant");
|
|
221
|
+
|
|
222
|
+
// src/core/integration.ts
|
|
223
|
+
var VIEW_SELECT = {
|
|
224
|
+
provider: true,
|
|
225
|
+
enabled: true,
|
|
226
|
+
environment: true,
|
|
227
|
+
status: true,
|
|
228
|
+
externalMerchantId: true,
|
|
229
|
+
autoAccept: true,
|
|
230
|
+
followStatus: true,
|
|
231
|
+
ackSlaSeconds: true,
|
|
232
|
+
credentials: true,
|
|
233
|
+
lastEventAt: true,
|
|
234
|
+
lastVerifiedAt: true,
|
|
235
|
+
archivedAt: true,
|
|
236
|
+
authMode: true
|
|
237
|
+
};
|
|
238
|
+
function toView(row) {
|
|
223
239
|
return {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
240
|
+
provider: row.provider,
|
|
241
|
+
enabled: row.enabled,
|
|
242
|
+
environment: row.environment,
|
|
243
|
+
status: row.status,
|
|
244
|
+
externalMerchantId: row.externalMerchantId,
|
|
245
|
+
autoAccept: row.autoAccept,
|
|
246
|
+
followStatus: row.followStatus ?? true,
|
|
247
|
+
ackSlaSeconds: row.ackSlaSeconds,
|
|
248
|
+
connected: row.credentials !== "",
|
|
249
|
+
lastEventAt: row.lastEventAt,
|
|
250
|
+
lastVerifiedAt: row.lastVerifiedAt,
|
|
251
|
+
archivedAt: row.archivedAt ?? null,
|
|
252
|
+
authMode: row.authMode === "LINKED" ? "LINKED" : "CREDENTIALS"
|
|
230
253
|
};
|
|
231
254
|
}
|
|
232
|
-
__name(
|
|
233
|
-
async function
|
|
255
|
+
__name(toView, "toView");
|
|
256
|
+
async function listMarketplaceIntegrations(ctx, clientId, options = {}) {
|
|
234
257
|
const db = await ctx.ports.db();
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
258
|
+
const rows = await db.marketplaceIntegration.findMany({
|
|
259
|
+
where: {
|
|
260
|
+
clientId,
|
|
261
|
+
...options.providers ? { provider: { in: [...options.providers] } } : {},
|
|
262
|
+
...options.includeArchived ? {} : { archivedAt: null }
|
|
263
|
+
},
|
|
264
|
+
select: VIEW_SELECT,
|
|
265
|
+
orderBy: { provider: "asc" }
|
|
241
266
|
});
|
|
242
|
-
|
|
243
|
-
ctx.ports.publishChanged(input.clientId);
|
|
244
|
-
await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
|
|
245
|
-
return true;
|
|
267
|
+
return rows.map(toView);
|
|
246
268
|
}
|
|
247
|
-
__name(
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
269
|
+
__name(listMarketplaceIntegrations, "listMarketplaceIntegrations");
|
|
270
|
+
async function saveMarketplaceIntegration(ctx, input, db) {
|
|
271
|
+
await assertMerchantFree(db, input.clientId, input.provider, input.externalMerchantId);
|
|
272
|
+
const sealed = input.credentials ? ctx.ports.secrets.seal(JSON.stringify(input.credentials)) : void 0;
|
|
273
|
+
const mutable = {
|
|
274
|
+
...input.enabled === void 0 ? {} : { enabled: input.enabled },
|
|
275
|
+
...input.environment === void 0 ? {} : { environment: input.environment },
|
|
276
|
+
...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
|
|
277
|
+
...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
|
|
278
|
+
...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
|
|
279
|
+
...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
|
|
280
|
+
// Typed credentials make the connection the store's own app again.
|
|
281
|
+
...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }
|
|
282
|
+
};
|
|
283
|
+
const row = await db.marketplaceIntegration.upsert({
|
|
284
|
+
where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
|
|
285
|
+
create: {
|
|
286
|
+
clientId: input.clientId,
|
|
287
|
+
provider: input.provider,
|
|
288
|
+
credentials: sealed ?? "",
|
|
289
|
+
ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
|
|
290
|
+
...mutable
|
|
291
|
+
},
|
|
292
|
+
update: mutable,
|
|
293
|
+
select: VIEW_SELECT
|
|
256
294
|
});
|
|
257
|
-
|
|
258
|
-
try {
|
|
259
|
-
const row = await db.marketplaceInboxEvent.create({
|
|
260
|
-
data: {
|
|
261
|
-
clientId: input.clientId,
|
|
262
|
-
provider: input.event.provider,
|
|
263
|
-
eventId: input.event.eventId,
|
|
264
|
-
eventType: input.event.eventType,
|
|
265
|
-
externalOrderId: input.event.externalOrderId,
|
|
266
|
-
payload: input.payload,
|
|
267
|
-
// The engine's clock, not the database's: an announced order's
|
|
268
|
-
// acceptance window counts from here (`./fetch-order.ts`).
|
|
269
|
-
receivedAt: ctx.ports.clock.now()
|
|
270
|
-
},
|
|
271
|
-
select: { id: true }
|
|
272
|
-
});
|
|
273
|
-
return { id: row.id, fresh: true };
|
|
274
|
-
} catch (error) {
|
|
275
|
-
if (error.code !== "P2002") throw error;
|
|
276
|
-
const raced = await db.marketplaceInboxEvent.findUnique({
|
|
277
|
-
where: key,
|
|
278
|
-
select: { id: true }
|
|
279
|
-
});
|
|
280
|
-
return { id: raced?.id ?? "", fresh: false };
|
|
281
|
-
}
|
|
295
|
+
return toView(row);
|
|
282
296
|
}
|
|
283
|
-
__name(
|
|
284
|
-
async function
|
|
285
|
-
if (!id) return;
|
|
297
|
+
__name(saveMarketplaceIntegration, "saveMarketplaceIntegration");
|
|
298
|
+
async function connectionMerchantId(ctx, clientId, provider) {
|
|
286
299
|
const db = await ctx.ports.db();
|
|
287
|
-
await db.
|
|
288
|
-
where: {
|
|
289
|
-
|
|
290
|
-
status: outcome,
|
|
291
|
-
// Truncated: a provider's error body can be a page of HTML, and the
|
|
292
|
-
// column exists to be read by a human in a list.
|
|
293
|
-
error: error ? error.slice(0, 500) : null,
|
|
294
|
-
processedAt: ctx.ports.clock.now(),
|
|
295
|
-
attempts: { increment: 1 }
|
|
296
|
-
}
|
|
300
|
+
const row = await db.marketplaceIntegration.findUnique({
|
|
301
|
+
where: { clientId_provider: { clientId, provider } },
|
|
302
|
+
select: { externalMerchantId: true, archivedAt: true }
|
|
297
303
|
});
|
|
304
|
+
return row && !row.archivedAt ? row.externalMerchantId ?? null : null;
|
|
298
305
|
}
|
|
299
|
-
__name(
|
|
300
|
-
async function
|
|
301
|
-
if (!id) return;
|
|
306
|
+
__name(connectionMerchantId, "connectionMerchantId");
|
|
307
|
+
async function resolveIngestionTarget(ctx, clientId, provider) {
|
|
302
308
|
const db = await ctx.ports.db();
|
|
303
|
-
await db.
|
|
304
|
-
where: {
|
|
305
|
-
|
|
306
|
-
|
|
309
|
+
const row = await db.marketplaceIntegration.findUnique({
|
|
310
|
+
where: { clientId_provider: { clientId, provider } },
|
|
311
|
+
select: {
|
|
312
|
+
enabled: true,
|
|
313
|
+
autoAccept: true,
|
|
314
|
+
followStatus: true,
|
|
315
|
+
ackSlaSeconds: true,
|
|
316
|
+
credentials: true,
|
|
317
|
+
archivedAt: true,
|
|
318
|
+
externalMerchantId: true,
|
|
319
|
+
authMode: true,
|
|
320
|
+
environment: true
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
if (!row || row.archivedAt) return null;
|
|
324
|
+
return {
|
|
325
|
+
enabled: row.enabled,
|
|
326
|
+
autoAccept: row.autoAccept,
|
|
327
|
+
followStatus: row.followStatus ?? true,
|
|
328
|
+
ackSlaSeconds: row.ackSlaSeconds,
|
|
329
|
+
externalMerchantId: row.externalMerchantId ?? null,
|
|
330
|
+
// An unopenable blob must not read as "no secret configured" — that would
|
|
331
|
+
// turn a key-rotation problem into an endpoint that accepts unsigned
|
|
332
|
+
// deliveries. The secrets port throws instead, and the caller answers 401.
|
|
333
|
+
webhookSecret: await webhookSecretOf(ctx, provider, row)
|
|
334
|
+
};
|
|
307
335
|
}
|
|
308
|
-
__name(
|
|
309
|
-
async function
|
|
336
|
+
__name(resolveIngestionTarget, "resolveIngestionTarget");
|
|
337
|
+
async function webhookSecretOf(ctx, provider, row) {
|
|
338
|
+
if (row.authMode !== "LINKED") {
|
|
339
|
+
return row.credentials === "" ? null : openCredentials(ctx, row.credentials).webhookSecret;
|
|
340
|
+
}
|
|
341
|
+
const app = await appCredentialsOf(ctx, provider, environmentOf(row.environment));
|
|
342
|
+
if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
|
|
343
|
+
const secret = app.webhookSecret || app.clientSecret;
|
|
344
|
+
if (!secret) throw new Error(`No webhook key is configured for ${provider}.`);
|
|
345
|
+
return secret;
|
|
346
|
+
}
|
|
347
|
+
__name(webhookSecretOf, "webhookSecretOf");
|
|
348
|
+
var environmentOf = /* @__PURE__ */ __name((value) => value === "PRODUCTION" ? "PRODUCTION" : "SANDBOX", "environmentOf");
|
|
349
|
+
function openCredentials(ctx, sealed) {
|
|
350
|
+
const parsed = JSON.parse(ctx.ports.secrets.open(sealed));
|
|
351
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
352
|
+
throw new Error("Stored marketplace credentials are not an object.");
|
|
353
|
+
}
|
|
354
|
+
const record = parsed;
|
|
355
|
+
return {
|
|
356
|
+
clientId: String(record.clientId ?? ""),
|
|
357
|
+
clientSecret: String(record.clientSecret ?? ""),
|
|
358
|
+
webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
__name(openCredentials, "openCredentials");
|
|
362
|
+
async function markMarketplaceEventSeen(db, clientId, provider, at) {
|
|
363
|
+
await db.marketplaceIntegration.updateMany({
|
|
364
|
+
where: { clientId, provider },
|
|
365
|
+
data: { lastEventAt: at }
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
__name(markMarketplaceEventSeen, "markMarketplaceEventSeen");
|
|
369
|
+
async function readOutboundConnection(ctx, clientId, provider) {
|
|
370
|
+
return (await readSealedOutboundConnection(ctx, clientId, provider))?.connection ?? null;
|
|
371
|
+
}
|
|
372
|
+
__name(readOutboundConnection, "readOutboundConnection");
|
|
373
|
+
async function readSealedOutboundConnection(ctx, clientId, provider) {
|
|
310
374
|
const db = await ctx.ports.db();
|
|
311
|
-
const
|
|
312
|
-
where: {
|
|
313
|
-
|
|
314
|
-
clientId: { not: null },
|
|
315
|
-
attempts: { lt: ctx.ports.maxInboxAttempts }
|
|
316
|
-
},
|
|
317
|
-
orderBy: { receivedAt: "asc" },
|
|
318
|
-
take: ctx.ports.reconcileBatchSize,
|
|
319
|
-
select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
|
|
375
|
+
const row = await db.marketplaceIntegration.findUnique({
|
|
376
|
+
where: { clientId_provider: { clientId, provider } },
|
|
377
|
+
select: { environment: true, credentials: true, authMode: true }
|
|
320
378
|
});
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
379
|
+
if (!row || row.credentials === "") return null;
|
|
380
|
+
const sealed = row.credentials;
|
|
381
|
+
const environment = environmentOf(row.environment);
|
|
382
|
+
if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
|
|
383
|
+
const app = await appCredentialsOf(ctx, provider, environment);
|
|
384
|
+
if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
|
|
385
|
+
if (isAppLinkBlob(ctx, sealed)) return { connection: { environment, credentials: app }, sealed };
|
|
386
|
+
const refreshToken = openLinkRefreshToken(ctx, sealed);
|
|
387
|
+
const link = { clientId, provider, environment, refreshToken, app, sealed };
|
|
388
|
+
return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
|
|
328
389
|
}
|
|
329
|
-
__name(
|
|
390
|
+
__name(readSealedOutboundConnection, "readSealedOutboundConnection");
|
|
330
391
|
|
|
331
|
-
// src/core/
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
cancellationStatus: null,
|
|
345
|
-
cancellationReasonCode: null,
|
|
346
|
-
cancellationOffendingSkus: null,
|
|
347
|
-
cancellationFailureReason: null
|
|
348
|
-
};
|
|
349
|
-
async function claimConfirmed(ctx, clientId, held, now) {
|
|
350
|
-
if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") return { accepted: false };
|
|
392
|
+
// src/core/status-store.ts
|
|
393
|
+
function statusTable(db) {
|
|
394
|
+
return db.marketplaceStatusUpdate ?? null;
|
|
395
|
+
}
|
|
396
|
+
__name(statusTable, "statusTable");
|
|
397
|
+
async function readStatusRows(table, orderId, steps2) {
|
|
398
|
+
return await table.findMany({
|
|
399
|
+
where: { orderId, step: { in: [...steps2] } },
|
|
400
|
+
select: { orderId: true, step: true, source: true, state: true, claimKey: true }
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
__name(readStatusRows, "readStatusRows");
|
|
404
|
+
async function insertStatusRow(table, row) {
|
|
351
405
|
try {
|
|
352
|
-
await
|
|
353
|
-
|
|
354
|
-
clientId,
|
|
355
|
-
orderId: held.orderId,
|
|
356
|
-
decision: "ACCEPT",
|
|
357
|
-
admission: {},
|
|
358
|
-
db: tx
|
|
359
|
-
});
|
|
360
|
-
if (!answer.admitted) throw new NotClaimed({ code: answer.code, message: answer.message });
|
|
361
|
-
const claimed = await tx.marketplaceAcceptance.updateMany({
|
|
362
|
-
where: { orderId: held.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
|
|
363
|
-
data: {
|
|
364
|
-
status: "ACCEPTED",
|
|
365
|
-
acknowledgedAt: now,
|
|
366
|
-
confirmedAt: now,
|
|
367
|
-
...held.cancellationStatus === "FAILED" ? CLEARED_FAILED_REQUEST : {}
|
|
368
|
-
}
|
|
369
|
-
});
|
|
370
|
-
if (claimed.count === 0) throw new NotClaimed(null);
|
|
371
|
-
});
|
|
372
|
-
return { accepted: true };
|
|
406
|
+
await table.create({ data: row });
|
|
407
|
+
return true;
|
|
373
408
|
} catch (error) {
|
|
374
|
-
if (
|
|
375
|
-
|
|
409
|
+
if (error.code === "P2002") return false;
|
|
410
|
+
throw error;
|
|
376
411
|
}
|
|
377
412
|
}
|
|
378
|
-
__name(
|
|
379
|
-
async function
|
|
413
|
+
__name(insertStatusRow, "insertStatusRow");
|
|
414
|
+
async function noteMarketplaceStep(ctx, row) {
|
|
415
|
+
const table = statusTable(await ctx.ports.db());
|
|
416
|
+
if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
|
|
417
|
+
}
|
|
418
|
+
__name(noteMarketplaceStep, "noteMarketplaceStep");
|
|
419
|
+
async function settleStatusRow(table, where, state) {
|
|
420
|
+
return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
|
|
421
|
+
}
|
|
422
|
+
__name(settleStatusRow, "settleStatusRow");
|
|
423
|
+
|
|
424
|
+
// src/core/logistics.ts
|
|
425
|
+
var LOGISTICS_STEPS = ["ASSIGNED", "GOING_TO_ORIGIN", "ARRIVED_AT_ORIGIN", "DISPATCHED", "ARRIVED_AT_DESTINATION"];
|
|
426
|
+
var LOGISTICS_ROW_PREFIX = "LOGISTICS_";
|
|
427
|
+
var rowStep = /* @__PURE__ */ __name((step) => `${LOGISTICS_ROW_PREFIX}${step}`, "rowStep");
|
|
428
|
+
function logisticsDedupeKey(step, orderId, at) {
|
|
429
|
+
return `${MARKETPLACE_OUTBOUND_JOB}:logistics:${step}:${orderId}:${at.getTime()}`;
|
|
430
|
+
}
|
|
431
|
+
__name(logisticsDedupeKey, "logisticsDedupeKey");
|
|
432
|
+
async function informLogistics(ctx, input) {
|
|
433
|
+
const payload = {
|
|
434
|
+
clientId: input.clientId,
|
|
435
|
+
orderId: input.orderId,
|
|
436
|
+
action: "logistics",
|
|
437
|
+
logisticsStep: input.step,
|
|
438
|
+
// The step is in the key: two moves at one instant never share a claim.
|
|
439
|
+
claimKey: `${input.step}:${input.at.getTime()}`
|
|
440
|
+
};
|
|
380
441
|
try {
|
|
381
|
-
|
|
442
|
+
const options = {
|
|
443
|
+
dedupeKey: logisticsDedupeKey(input.step, input.orderId, input.at),
|
|
444
|
+
...input.delayMs === void 0 ? {} : { delayMs: input.delayMs }
|
|
445
|
+
};
|
|
446
|
+
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_OUTBOUND_JOB, payload, options);
|
|
447
|
+
if (!outcome.enqueued) ctx.ports.logger.warn(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued`);
|
|
448
|
+
return outcome.enqueued;
|
|
382
449
|
} catch (error) {
|
|
383
|
-
ctx.ports.logger.
|
|
384
|
-
|
|
450
|
+
ctx.ports.logger.warn(
|
|
451
|
+
`${MARKETPLACE_OUTBOUND_JOB}: logistics ${input.step} for order ${input.orderId} was not queued: ` + (error instanceof Error ? error.message : String(error))
|
|
385
452
|
);
|
|
453
|
+
return false;
|
|
386
454
|
}
|
|
387
455
|
}
|
|
388
|
-
__name(
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
const db = await ctx.ports.db();
|
|
392
|
-
await db.marketplaceAcceptance.updateMany({
|
|
393
|
-
where: { orderId: held.orderId, clientId, status: "AWAITING", confirmedAt: null },
|
|
394
|
-
data: { confirmedAt: now }
|
|
395
|
-
});
|
|
396
|
-
const claim3 = await claimConfirmed(ctx, clientId, held, now);
|
|
397
|
-
const note = claim3.accepted ? void 0 : `accepted on the marketplace; waits for a person${claim3.refusal ? ` (${claim3.refusal.code})` : ""}`;
|
|
398
|
-
await settleInboxEvent(ctx, inboxId, "PROCESSED", note);
|
|
399
|
-
if (claim3.accepted) await tellAccepted(ctx, clientId, held.orderId);
|
|
400
|
-
ctx.ports.publishChanged(clientId);
|
|
401
|
-
return { kind: "confirmedByMarketplace", orderId: held.orderId, ...claim3 };
|
|
456
|
+
__name(informLogistics, "informLogistics");
|
|
457
|
+
function logisticsEngine(ctx) {
|
|
458
|
+
return { informLogistics: /* @__PURE__ */ __name((input) => informLogistics(ctx, input), "informLogistics") };
|
|
402
459
|
}
|
|
403
|
-
__name(
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
}
|
|
411
|
-
if (!held) {
|
|
412
|
-
await deferInboxEvent(ctx, inboxId, CONFIRMED_BEFORE_ORDER);
|
|
413
|
-
return { kind: "ignored", reason: CONFIRMED_BEFORE_ORDER };
|
|
414
|
-
}
|
|
415
|
-
if (held.status === "ACCEPTED") return confirmAccepted(ctx, inboxId, clientId, held.orderId);
|
|
416
|
-
if (held.status !== "AWAITING") {
|
|
417
|
-
const reason = `the order is ${held.status}, not AWAITING`;
|
|
418
|
-
await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
|
|
419
|
-
return { kind: "ignored", reason };
|
|
420
|
-
}
|
|
421
|
-
return confirmHeld(ctx, inboxId, clientId, held);
|
|
460
|
+
__name(logisticsEngine, "logisticsEngine");
|
|
461
|
+
var skipped = /* @__PURE__ */ __name((reason) => ({ kind: "skipped", reason }), "skipped");
|
|
462
|
+
function orderSkip(row, adapter) {
|
|
463
|
+
if (!adapter.logistics) return "the marketplace has no Logistics half";
|
|
464
|
+
if (row.deliveredBy !== "MERCHANT") return "the store does not carry this order";
|
|
465
|
+
if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
|
|
466
|
+
const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
|
|
467
|
+
return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
|
|
422
468
|
}
|
|
423
|
-
__name(
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
});
|
|
430
|
-
if (stamped.count === 0) {
|
|
431
|
-
const reason = "the order is ACCEPTED and its confirm already stamped";
|
|
432
|
-
await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
|
|
433
|
-
return { kind: "ignored", reason };
|
|
434
|
-
}
|
|
435
|
-
await settleInboxEvent(ctx, inboxId, "PROCESSED", "accepted here first; the marketplace took the acceptance");
|
|
436
|
-
ctx.ports.publishChanged(clientId);
|
|
437
|
-
return { kind: "confirmedByMarketplace", orderId, accepted: true };
|
|
469
|
+
__name(orderSkip, "orderSkip");
|
|
470
|
+
function confirmSkip(row, adapter, deps) {
|
|
471
|
+
if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
|
|
472
|
+
if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
|
|
473
|
+
if (deps.attempt.attempt < deps.attempt.maxAttempts) throw deps.retryError(`logistics for order ${row.orderId}: the store's confirm has not reached the marketplace yet`);
|
|
474
|
+
return "the store's confirm has not reached the marketplace";
|
|
438
475
|
}
|
|
439
|
-
__name(
|
|
440
|
-
async function
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
476
|
+
__name(confirmSkip, "confirmSkip");
|
|
477
|
+
async function logisticsAppOf(ctx, provider, environment) {
|
|
478
|
+
const port = ctx.ports.logisticsCredentials;
|
|
479
|
+
if (!port) return null;
|
|
480
|
+
const credentials = await port(provider, environment);
|
|
481
|
+
return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
|
|
482
|
+
}
|
|
483
|
+
__name(logisticsAppOf, "logisticsAppOf");
|
|
484
|
+
async function environmentOf2(ctx, clientId, provider) {
|
|
485
|
+
try {
|
|
486
|
+
const connection = await readOutboundConnection(ctx, clientId, provider);
|
|
487
|
+
return connection ? { environment: connection.environment } : { missing: "no credentials on file" };
|
|
488
|
+
} catch (error) {
|
|
489
|
+
return { missing: `credentials do not open: ${error instanceof Error ? error.message : String(error)}` };
|
|
447
490
|
}
|
|
448
|
-
return applied;
|
|
449
491
|
}
|
|
450
|
-
__name(
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
if (!ctx.registry.get(input.provider)?.capabilities.marketplaceConfirms) return;
|
|
454
|
-
const db = await ctx.ports.db();
|
|
455
|
-
const rows = await db.marketplaceInboxEvent.findMany({
|
|
456
|
-
where: { ...input, status: "PENDING", error: CONFIRMED_BEFORE_ORDER },
|
|
457
|
-
select: DEFERRED_SELECT
|
|
458
|
-
});
|
|
459
|
-
await applyRows(ctx, rows);
|
|
460
|
-
}
|
|
461
|
-
__name(applyDeferredConfirmations, "applyDeferredConfirmations");
|
|
462
|
-
async function applyOwedConfirmations(ctx, lapsed) {
|
|
463
|
-
if (lapsed.length === 0) return /* @__PURE__ */ new Set();
|
|
464
|
-
const db = await ctx.ports.db();
|
|
465
|
-
const rows = await db.marketplaceInboxEvent.findMany({
|
|
466
|
-
where: {
|
|
467
|
-
status: "PENDING",
|
|
468
|
-
error: CONFIRMED_BEFORE_ORDER,
|
|
469
|
-
clientId: { not: null },
|
|
470
|
-
externalOrderId: { in: [...new Set(lapsed.map((row) => row.externalOrderId))] }
|
|
471
|
-
},
|
|
472
|
-
select: DEFERRED_SELECT
|
|
473
|
-
});
|
|
474
|
-
const named = new Set(lapsed.map((row) => `${row.provider}:${row.externalOrderId}`));
|
|
475
|
-
return applyRows(ctx, rows.filter((row) => named.has(`${row.provider}:${row.externalOrderId ?? ""}`)));
|
|
492
|
+
__name(environmentOf2, "environmentOf");
|
|
493
|
+
function chainTo(target) {
|
|
494
|
+
return LOGISTICS_STEPS.slice(0, LOGISTICS_STEPS.indexOf(target) + 1);
|
|
476
495
|
}
|
|
477
|
-
__name(
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
__name(this, "MarketplaceMerchantTakenError");
|
|
483
|
-
}
|
|
484
|
-
code = "MERCHANT_TAKEN";
|
|
485
|
-
/** The field the refusal is about, as a problem path. */
|
|
486
|
-
path = ["externalMerchantId"];
|
|
487
|
-
constructor(provider, merchantId) {
|
|
488
|
-
super(`The ${provider} merchant ${merchantId} is already held by another store's live connection.`);
|
|
489
|
-
this.name = "MarketplaceMerchantTakenError";
|
|
490
|
-
}
|
|
491
|
-
};
|
|
492
|
-
function isUniqueViolation(error) {
|
|
493
|
-
const code = error?.code;
|
|
494
|
-
return code === "P2002" || code === "23505";
|
|
496
|
+
__name(chainTo, "chainTo");
|
|
497
|
+
async function waitOrSkip(run, target, reason) {
|
|
498
|
+
if (run.deps.attempt.attempt < run.deps.attempt.maxAttempts) throw run.deps.retryError(`logistics for order ${run.row.orderId}: ${reason}`);
|
|
499
|
+
await claimStep(run, target, void 0);
|
|
500
|
+
return skipped(reason);
|
|
495
501
|
}
|
|
496
|
-
__name(
|
|
497
|
-
async function
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
});
|
|
502
|
-
return rows.some((row) => row.clientId !== clientId);
|
|
502
|
+
__name(waitOrSkip, "waitOrSkip");
|
|
503
|
+
async function send(run, step) {
|
|
504
|
+
if (step !== "ASSIGNED") return run.logistics.step(run.call, run.deps.ref, step);
|
|
505
|
+
if (!run.driver) return { kind: "invalid", reason: "the host names no courier for this order" };
|
|
506
|
+
return run.logistics.assignDriver(run.call, run.deps.ref, run.driver);
|
|
503
507
|
}
|
|
504
|
-
__name(
|
|
505
|
-
async function
|
|
506
|
-
|
|
507
|
-
|
|
508
|
+
__name(send, "send");
|
|
509
|
+
async function settle(run, step, result) {
|
|
510
|
+
const where = { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key };
|
|
511
|
+
if (result.kind === "accepted") {
|
|
512
|
+
await settleStatusRow(run.table, where, "SENT");
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
const reason = result.kind === "refused" ? `refused ${result.status}: ${result.message}` : result.reason;
|
|
516
|
+
if (result.kind === "retry" && run.deps.attempt.attempt < run.deps.attempt.maxAttempts) {
|
|
517
|
+
throw run.deps.retryError(`logistics ${step} for order ${run.row.orderId}: ${reason}`);
|
|
508
518
|
}
|
|
519
|
+
await settleStatusRow(run.table, where, "FAILED");
|
|
520
|
+
run.ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${step} for order ${run.row.orderId} failed: ${reason}`);
|
|
521
|
+
return reason;
|
|
509
522
|
}
|
|
510
|
-
__name(
|
|
511
|
-
async function
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
523
|
+
__name(settle, "settle");
|
|
524
|
+
async function claimStep(run, step, found) {
|
|
525
|
+
if (found?.state === "SENT") return "sent";
|
|
526
|
+
if (found?.state === "FAILED") return { stop: `${step} failed earlier` };
|
|
527
|
+
if (found?.state === "SENDING") return found.claimKey === run.key ? "mine" : { wait: `${step} is being sent by another run` };
|
|
528
|
+
const claimed = await insertStatusRow(run.table, {
|
|
529
|
+
clientId: run.payload.clientId,
|
|
530
|
+
orderId: run.row.orderId,
|
|
531
|
+
provider: run.row.provider,
|
|
532
|
+
step: rowStep(step),
|
|
533
|
+
source: "STORE",
|
|
534
|
+
state: "SENDING",
|
|
535
|
+
claimKey: run.key
|
|
536
|
+
});
|
|
537
|
+
return claimed ? "mine" : { wait: `another run holds the claim on ${step}` };
|
|
538
|
+
}
|
|
539
|
+
__name(claimStep, "claimStep");
|
|
540
|
+
async function logisticsCallContext(ctx, clientId, provider) {
|
|
541
|
+
const connection = await environmentOf2(ctx, clientId, provider);
|
|
542
|
+
if ("missing" in connection) return connection.missing;
|
|
543
|
+
const app = await logisticsAppOf(ctx, provider, connection.environment);
|
|
544
|
+
if (!app) return "no Logistics app credentials are configured";
|
|
545
|
+
return { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), environment: connection.environment, credentials: app };
|
|
546
|
+
}
|
|
547
|
+
__name(logisticsCallContext, "logisticsCallContext");
|
|
548
|
+
async function stopChain(run, chain, reason) {
|
|
549
|
+
for (const step of chain) await settleStatusRow(run.table, { orderId: run.row.orderId, step: rowStep(step), claimKey: run.key }, "FAILED");
|
|
550
|
+
return { kind: "failed", action: "logistics", reason };
|
|
551
|
+
}
|
|
552
|
+
__name(stopChain, "stopChain");
|
|
553
|
+
async function courierWhileOwed(ctx, table, payload, orderId) {
|
|
554
|
+
const [assigned] = await readStatusRows(table, orderId, [rowStep("ASSIGNED")]);
|
|
555
|
+
if (assigned?.state === "SENT") return null;
|
|
556
|
+
return await ctx.ports.order.logisticsDriver?.call(ctx.ports.order, payload.clientId, orderId) ?? "none";
|
|
557
|
+
}
|
|
558
|
+
__name(courierWhileOwed, "courierWhileOwed");
|
|
559
|
+
async function releaseHeld(ctx, table, orderId, chain, key) {
|
|
560
|
+
await table.deleteMany?.({ where: { orderId, step: { in: chain.map(rowStep) }, state: "SENDING", claimKey: key } });
|
|
561
|
+
ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics for order ${orderId} not sent: the host names no courier for it now`);
|
|
562
|
+
return skipped("the host names no courier for this order");
|
|
563
|
+
}
|
|
564
|
+
__name(releaseHeld, "releaseHeld");
|
|
565
|
+
async function runChain(run, chain) {
|
|
566
|
+
const rows = await readStatusRows(run.table, run.row.orderId, chain.map(rowStep));
|
|
567
|
+
for (const step of chain) {
|
|
568
|
+
const claim3 = await claimStep(run, step, rows.find((found) => found.step === rowStep(step)));
|
|
569
|
+
if (claim3 === "sent") continue;
|
|
570
|
+
if (typeof claim3 === "object") return "wait" in claim3 ? waitOrSkip(run, chain.at(-1), claim3.wait) : stopChain(run, chain, claim3.stop);
|
|
571
|
+
const failed = await settle(run, step, await send(run, step));
|
|
572
|
+
if (failed) return stopChain(run, chain, failed);
|
|
573
|
+
}
|
|
574
|
+
return { kind: "done", action: "logistics" };
|
|
575
|
+
}
|
|
576
|
+
__name(runChain, "runChain");
|
|
577
|
+
async function runLogistics(ctx, payload, row, adapter, deps) {
|
|
578
|
+
const target = payload.logisticsStep;
|
|
579
|
+
if (!target || !LOGISTICS_STEPS.includes(target)) return skipped("a logistics call names no step");
|
|
580
|
+
const stopped = orderSkip(row, adapter) ?? confirmSkip(row, adapter, deps);
|
|
581
|
+
if (stopped) return skipped(stopped);
|
|
582
|
+
const table = statusTable(await ctx.ports.db());
|
|
583
|
+
if (!table) return skipped("the host has not composed the status model");
|
|
584
|
+
const call2 = await logisticsCallContext(ctx, payload.clientId, row.provider);
|
|
585
|
+
if (typeof call2 === "string") {
|
|
586
|
+
ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${target} for order ${row.orderId} not sent: ${call2}`);
|
|
587
|
+
return skipped(call2);
|
|
519
588
|
}
|
|
589
|
+
const chain = chainTo(target);
|
|
590
|
+
const key = payload.claimKey ?? "";
|
|
591
|
+
const driver = await courierWhileOwed(ctx, table, payload, row.orderId);
|
|
592
|
+
if (driver === "none") return releaseHeld(ctx, table, row.orderId, chain, key);
|
|
593
|
+
return runChain({ ctx, table, payload, row, call: call2, logistics: adapter.logistics, driver, key, deps }, chain);
|
|
520
594
|
}
|
|
521
|
-
__name(
|
|
522
|
-
async function
|
|
523
|
-
const
|
|
524
|
-
const
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
take: 2
|
|
528
|
-
});
|
|
529
|
-
if (rows.length > 1) {
|
|
530
|
-
ctx.ports.logger.warn(`marketplace: ${provider} merchant ${externalMerchantId} is held by several live connections`);
|
|
531
|
-
return null;
|
|
595
|
+
__name(runLogistics, "runLogistics");
|
|
596
|
+
async function failLogisticsJob(ctx, payload, error) {
|
|
597
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
598
|
+
const table = statusTable(await ctx.ports.db());
|
|
599
|
+
for (const step of table && payload.logisticsStep ? chainTo(payload.logisticsStep) : []) {
|
|
600
|
+
await settleStatusRow(table, { orderId: payload.orderId, step: rowStep(step), claimKey: payload.claimKey ?? "" }, "FAILED");
|
|
532
601
|
}
|
|
533
|
-
|
|
602
|
+
ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: logistics ${payload.logisticsStep ?? ""} for order ${payload.orderId} failed: ${reason}`);
|
|
603
|
+
return { kind: "failed", action: "logistics", reason };
|
|
534
604
|
}
|
|
535
|
-
__name(
|
|
605
|
+
__name(failLogisticsJob, "failLogisticsJob");
|
|
536
606
|
|
|
537
|
-
// src/core/
|
|
538
|
-
var
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
}
|
|
542
|
-
__name(outboundDedupeKey, "outboundDedupeKey");
|
|
543
|
-
function statusDedupeKey(step, orderId, at) {
|
|
544
|
-
return `${MARKETPLACE_OUTBOUND_JOB}:status:${step}:${orderId}:${at.getTime()}`;
|
|
545
|
-
}
|
|
546
|
-
__name(statusDedupeKey, "statusDedupeKey");
|
|
547
|
-
function ableTo(adapter, payload) {
|
|
548
|
-
switch (payload.action) {
|
|
549
|
-
case "status":
|
|
550
|
-
return Boolean(payload.step && adapter.capabilities.statusSteps?.includes(payload.step));
|
|
551
|
-
case "confirm":
|
|
552
|
-
return adapter.capabilities.apiConfirm;
|
|
553
|
-
default:
|
|
554
|
-
return adapter.capabilities.apiCancel;
|
|
607
|
+
// src/core/registry.ts
|
|
608
|
+
var MarketplaceAdapterRegistrationError = class extends Error {
|
|
609
|
+
static {
|
|
610
|
+
__name(this, "MarketplaceAdapterRegistrationError");
|
|
555
611
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
const
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
612
|
+
constructor(message) {
|
|
613
|
+
super(`@12-apps/marketplace: ${message}`);
|
|
614
|
+
this.name = "MarketplaceAdapterRegistrationError";
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
function assertReasons(adapter) {
|
|
618
|
+
const codes = /* @__PURE__ */ new Set();
|
|
619
|
+
for (const reason of adapter.cancellationReasons()) {
|
|
620
|
+
if (reason.code.trim() === "") {
|
|
621
|
+
throw new MarketplaceAdapterRegistrationError(`${adapter.provider} declares a reason with a blank code.`);
|
|
622
|
+
}
|
|
623
|
+
if (codes.has(reason.code)) {
|
|
624
|
+
throw new MarketplaceAdapterRegistrationError(
|
|
625
|
+
`${adapter.provider} declares the reason code "${reason.code}" twice.`
|
|
626
|
+
);
|
|
627
|
+
}
|
|
628
|
+
codes.add(reason.code);
|
|
629
|
+
}
|
|
630
|
+
if (adapter.capabilities.apiCancel && codes.size === 0) {
|
|
631
|
+
throw new MarketplaceAdapterRegistrationError(
|
|
632
|
+
`${adapter.provider} can cancel through its API but declares no reason to cancel with.`
|
|
566
633
|
);
|
|
567
634
|
}
|
|
568
|
-
return outcome.enqueued;
|
|
569
635
|
}
|
|
570
|
-
__name(
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
throw error;
|
|
636
|
+
__name(assertReasons, "assertReasons");
|
|
637
|
+
function createAdapterRegistry(adapters) {
|
|
638
|
+
if (adapters.length === 0) {
|
|
639
|
+
throw new MarketplaceAdapterRegistrationError("an engine needs at least one adapter.");
|
|
640
|
+
}
|
|
641
|
+
const byProvider = /* @__PURE__ */ new Map();
|
|
642
|
+
for (const adapter of adapters) {
|
|
643
|
+
if (!PROVIDER_ID_PATTERN.test(adapter.provider)) {
|
|
644
|
+
throw new MarketplaceAdapterRegistrationError(
|
|
645
|
+
`provider id "${adapter.provider}" must be uppercase letters, digits and underscores.`
|
|
646
|
+
);
|
|
582
647
|
}
|
|
648
|
+
if (byProvider.has(adapter.provider)) {
|
|
649
|
+
throw new MarketplaceAdapterRegistrationError(`two adapters claim "${adapter.provider}".`);
|
|
650
|
+
}
|
|
651
|
+
assertReasons(adapter);
|
|
652
|
+
byProvider.set(adapter.provider, adapter);
|
|
583
653
|
}
|
|
584
|
-
const
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
654
|
+
const providers = [...byProvider.keys()];
|
|
655
|
+
return {
|
|
656
|
+
get: /* @__PURE__ */ __name((provider) => byProvider.get(provider) ?? null, "get"),
|
|
657
|
+
has: /* @__PURE__ */ __name((provider) => byProvider.has(provider), "has"),
|
|
658
|
+
providers: /* @__PURE__ */ __name(() => providers, "providers")
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
__name(createAdapterRegistry, "createAdapterRegistry");
|
|
662
|
+
function storedReasons(value) {
|
|
663
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
664
|
+
return value.flatMap((entry) => {
|
|
665
|
+
const { code, description } = entry ?? {};
|
|
666
|
+
return typeof code === "string" ? [{ code, description: typeof description === "string" ? description : code }] : [];
|
|
588
667
|
});
|
|
589
|
-
return moved.count > 0;
|
|
590
668
|
}
|
|
591
|
-
__name(
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
669
|
+
__name(storedReasons, "storedReasons");
|
|
670
|
+
function reasonsForOrder(adapter, stored) {
|
|
671
|
+
const own = storedReasons(stored);
|
|
672
|
+
if (own === null) return adapter.cancellationReasons();
|
|
673
|
+
const known = new Map(adapter.cancellationReasons().map((reason) => [reason.code, reason]));
|
|
674
|
+
return own.map(
|
|
675
|
+
(reason) => known.get(reason.code) ?? { code: reason.code, label: reason.description, itemUnavailable: false, needsItems: false }
|
|
676
|
+
);
|
|
598
677
|
}
|
|
599
|
-
__name(
|
|
600
|
-
|
|
601
|
-
const
|
|
602
|
-
if (
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
678
|
+
__name(reasonsForOrder, "reasonsForOrder");
|
|
679
|
+
function resolveReason(adapter, code, stored) {
|
|
680
|
+
const reasons = reasonsForOrder(adapter, stored);
|
|
681
|
+
if (code === null || code === void 0) return reasons[0] ?? null;
|
|
682
|
+
return reasons.find((reason) => reason.code === code) ?? null;
|
|
683
|
+
}
|
|
684
|
+
__name(resolveReason, "resolveReason");
|
|
685
|
+
function suggestReason(adapter, input) {
|
|
686
|
+
const reasons = adapter.cancellationReasons();
|
|
687
|
+
if (input.itemUnavailable) {
|
|
688
|
+
const unavailable = reasons.find((reason) => reason.itemUnavailable);
|
|
689
|
+
if (unavailable) return unavailable;
|
|
610
690
|
}
|
|
611
|
-
|
|
691
|
+
return reasons[0] ?? null;
|
|
692
|
+
}
|
|
693
|
+
__name(suggestReason, "suggestReason");
|
|
694
|
+
|
|
695
|
+
// src/core/cancellation-outcome.ts
|
|
696
|
+
async function tell(ctx, what, orderId, call2) {
|
|
612
697
|
try {
|
|
613
|
-
|
|
698
|
+
await call2();
|
|
614
699
|
} catch (error) {
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
700
|
+
ctx.ports.logger.error(
|
|
701
|
+
`marketplace.cancellation: order ${orderId} ${what} but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
|
|
702
|
+
);
|
|
618
703
|
}
|
|
619
|
-
return result;
|
|
620
704
|
}
|
|
621
|
-
__name(
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
if (!table) return;
|
|
625
|
-
await table.updateMany({
|
|
626
|
-
where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
|
|
627
|
-
data: { externalId: null, claimedAt: null }
|
|
628
|
-
});
|
|
705
|
+
__name(tell, "tell");
|
|
706
|
+
function requestsFirst(ctx) {
|
|
707
|
+
return ctx.ports.order.onCancellationConfirmed !== void 0;
|
|
629
708
|
}
|
|
630
|
-
__name(
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
709
|
+
__name(requestsFirst, "requestsFirst");
|
|
710
|
+
async function rejectConfirmed(db, orderId, now) {
|
|
711
|
+
await db.marketplaceAcceptance.updateMany({
|
|
712
|
+
where: { orderId, status: "AWAITING" },
|
|
713
|
+
data: { status: "REJECTED", acknowledgedAt: now }
|
|
714
|
+
});
|
|
715
|
+
await db.marketplaceAcceptance.updateMany({
|
|
716
|
+
where: { orderId, status: { in: ["ACCEPTED", "EXPIRED"] } },
|
|
717
|
+
data: { status: "REJECTED" }
|
|
718
|
+
});
|
|
635
719
|
}
|
|
636
|
-
__name(
|
|
637
|
-
function
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
if (typeof token !== "string" || token === "") throw new Error("The linked connection holds no refresh token.");
|
|
641
|
-
return token;
|
|
720
|
+
__name(rejectConfirmed, "rejectConfirmed");
|
|
721
|
+
async function confirmedToHost(ctx, clientId, orderId) {
|
|
722
|
+
if (await tellCancellationConfirmed(ctx, clientId, orderId)) return;
|
|
723
|
+
await ctx.ports.order.onRefused(clientId, orderId, "CANCELLED");
|
|
642
724
|
}
|
|
643
|
-
__name(
|
|
644
|
-
function
|
|
645
|
-
|
|
725
|
+
__name(confirmedToHost, "confirmedToHost");
|
|
726
|
+
async function tellCancellationConfirmed(ctx, clientId, orderId) {
|
|
727
|
+
const hook = ctx.ports.order.onCancellationConfirmed;
|
|
728
|
+
if (!hook) return false;
|
|
729
|
+
await tell(ctx, "was cancelled on the store's request", orderId, () => hook.call(ctx.ports.order, clientId, orderId));
|
|
730
|
+
return true;
|
|
646
731
|
}
|
|
647
|
-
__name(
|
|
648
|
-
function
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
732
|
+
__name(tellCancellationConfirmed, "tellCancellationConfirmed");
|
|
733
|
+
async function tellCancellationFailed(ctx, clientId, orderId, reason) {
|
|
734
|
+
const hook = ctx.ports.order.onCancellationFailed;
|
|
735
|
+
if (!hook) return;
|
|
736
|
+
await tell(
|
|
737
|
+
ctx,
|
|
738
|
+
`had its cancellation request fail (${reason})`,
|
|
739
|
+
orderId,
|
|
740
|
+
() => hook.call(ctx.ports.order, clientId, orderId, reason)
|
|
741
|
+
);
|
|
655
742
|
}
|
|
656
|
-
__name(
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
if (!port) return null;
|
|
660
|
-
const credentials = await port(provider, environment);
|
|
661
|
-
return credentials && credentials.clientId !== "" && credentials.clientSecret !== "" ? credentials : null;
|
|
743
|
+
__name(tellCancellationFailed, "tellCancellationFailed");
|
|
744
|
+
function cancellationWindowMs(ctx, adapter) {
|
|
745
|
+
return ctx.ports.cancellationWindowMs ?? adapter.capabilities.cancellationAnswerWindowMs ?? null;
|
|
662
746
|
}
|
|
663
|
-
__name(
|
|
664
|
-
|
|
665
|
-
|
|
747
|
+
__name(cancellationWindowMs, "cancellationWindowMs");
|
|
748
|
+
function failedRequestData(reason) {
|
|
749
|
+
return { cancellationStatus: "FAILED", cancellationFailureReason: reason };
|
|
750
|
+
}
|
|
751
|
+
__name(failedRequestData, "failedRequestData");
|
|
752
|
+
|
|
753
|
+
// src/core/cancellation.ts
|
|
754
|
+
function noStandingRequest(cancellationStatus) {
|
|
755
|
+
return cancellationStatus === null || cancellationStatus === "FAILED";
|
|
756
|
+
}
|
|
757
|
+
__name(noStandingRequest, "noStandingRequest");
|
|
758
|
+
var NO_STANDING_REQUEST = { OR: [{ cancellationStatus: null }, { cancellationStatus: "FAILED" }] };
|
|
759
|
+
var CLAIM_SELECT = {
|
|
760
|
+
orderId: true,
|
|
761
|
+
provider: true,
|
|
762
|
+
status: true,
|
|
763
|
+
cancellationStatus: true,
|
|
764
|
+
lineSkus: true,
|
|
765
|
+
cancellationReasons: true
|
|
766
|
+
};
|
|
767
|
+
function notPendingProblem(row, path, allowed = ["AWAITING"]) {
|
|
768
|
+
if (!row) return { path: [...path, "orderId"], code: "NOT_FOUND" };
|
|
769
|
+
if (allowed.includes(row.status) && noStandingRequest(row.cancellationStatus)) return null;
|
|
770
|
+
const status = row.status;
|
|
771
|
+
return { path: [...path, "orderId"], code: status === "EXPIRED" ? "EXPIRED" : "ALREADY_DECIDED", status };
|
|
772
|
+
}
|
|
773
|
+
__name(notPendingProblem, "notPendingProblem");
|
|
774
|
+
function lineSkusOf(row) {
|
|
775
|
+
return Array.isArray(row.lineSkus) ? new Set(row.lineSkus.map(String)) : null;
|
|
776
|
+
}
|
|
777
|
+
__name(lineSkusOf, "lineSkusOf");
|
|
778
|
+
function skuProblems(reason, skus, row, path) {
|
|
779
|
+
if (reason?.needsItems && skus.length === 0) return [{ path: [...path, "offendingSkus"], code: "ITEMS_REQUIRED" }];
|
|
780
|
+
const known = lineSkusOf(row);
|
|
781
|
+
if (!known) return [];
|
|
782
|
+
return skus.flatMap(
|
|
783
|
+
(sku, index) => known.has(sku) ? [] : [{ path: [...path, "offendingSkus", index], code: "UNKNOWN_ITEM" }]
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
__name(skuProblems, "skuProblems");
|
|
787
|
+
function invalidReasonProblem(adapter, reason, input, path) {
|
|
788
|
+
if (input.code === null || input.code === void 0 || reason) return null;
|
|
789
|
+
const validCodes = reasonsForOrder(adapter, input.stored).map((candidate) => candidate.code);
|
|
790
|
+
return { path: [...path, "reasonCode"], code: "INVALID_REASON", validCodes };
|
|
791
|
+
}
|
|
792
|
+
__name(invalidReasonProblem, "invalidReasonProblem");
|
|
793
|
+
function planCancellation(adapter, input, row, path) {
|
|
794
|
+
if (!adapter) return { status: null, reason: null, skus: [] };
|
|
795
|
+
const reason = resolveReason(adapter, input.reasonCode, row.cancellationReasons);
|
|
796
|
+
const invalid = invalidReasonProblem(adapter, reason, { code: input.reasonCode, stored: row.cancellationReasons }, path);
|
|
797
|
+
if (invalid) return [invalid];
|
|
798
|
+
const skus = [...new Set(input.offendingSkus ?? [])];
|
|
799
|
+
const problems = skuProblems(reason, skus, row, path);
|
|
800
|
+
if (problems.length > 0) return problems;
|
|
801
|
+
const { apiCancel, cancelAfterAccept } = adapter.capabilities;
|
|
802
|
+
const canAsk = apiCancel && reason !== null && (row.status === "AWAITING" || cancelAfterAccept);
|
|
803
|
+
return { status: canAsk ? "PENDING" : "FAILED", reason, skus };
|
|
804
|
+
}
|
|
805
|
+
__name(planCancellation, "planCancellation");
|
|
806
|
+
function refusalData(plan, fromStatus, now) {
|
|
807
|
+
return {
|
|
808
|
+
status: "REJECTED",
|
|
809
|
+
// An accepted row keeps the instant it was accepted; a row leaving the
|
|
810
|
+
// clock is acknowledged now (the table's CHECK pairs the two).
|
|
811
|
+
...fromStatus === "AWAITING" ? { acknowledgedAt: now } : {},
|
|
812
|
+
cancellationStatus: plan.status,
|
|
813
|
+
cancellationReasonCode: plan.reason?.code ?? null,
|
|
814
|
+
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
815
|
+
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
816
|
+
// FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
|
|
817
|
+
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
__name(refusalData, "refusalData");
|
|
821
|
+
function requestData(plan, now) {
|
|
822
|
+
return {
|
|
823
|
+
cancellationStatus: plan.status,
|
|
824
|
+
cancellationReasonCode: plan.reason?.code ?? null,
|
|
825
|
+
cancellationOffendingSkus: plan.skus.length > 0 ? plan.skus : null,
|
|
826
|
+
cancellationRequestedAt: plan.status === "PENDING" ? now : null,
|
|
827
|
+
// FAILED here means the adapter has no cancellation API to call: the marketplace's own limit, REFUSED.
|
|
828
|
+
cancellationFailureReason: plan.status === "FAILED" ? "REFUSED" : null
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
__name(requestData, "requestData");
|
|
832
|
+
async function failCancellationRequest(ctx, input) {
|
|
666
833
|
const db = await ctx.ports.db();
|
|
667
|
-
const
|
|
668
|
-
|
|
669
|
-
|
|
834
|
+
const where = { clientId: input.clientId, provider: input.provider, externalOrderId: input.externalOrderId };
|
|
835
|
+
const row = await db.marketplaceAcceptance.findFirst({ where, select: { orderId: true } });
|
|
836
|
+
if (!row) return false;
|
|
837
|
+
const moved = await db.marketplaceAcceptance.updateMany({
|
|
838
|
+
where: { ...where, cancellationStatus: { in: ["PENDING", "REQUESTED"] } },
|
|
839
|
+
data: failedRequestData("REFUSED")
|
|
670
840
|
});
|
|
671
|
-
if (
|
|
672
|
-
|
|
841
|
+
if (moved.count === 0) return false;
|
|
842
|
+
ctx.ports.publishChanged(input.clientId);
|
|
843
|
+
await tellCancellationFailed(ctx, input.clientId, row.orderId, "REFUSED");
|
|
673
844
|
return true;
|
|
674
845
|
}
|
|
675
|
-
__name(
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
}
|
|
680
|
-
__name(setToken, "setToken");
|
|
681
|
-
var inflight = /* @__PURE__ */ new WeakMap();
|
|
682
|
-
async function storeRotated(ctx, link, refreshToken) {
|
|
846
|
+
__name(failCancellationRequest, "failCancellationRequest");
|
|
847
|
+
|
|
848
|
+
// src/core/inbox.ts
|
|
849
|
+
async function recordInboxEvent(ctx, input) {
|
|
683
850
|
const db = await ctx.ports.db();
|
|
684
|
-
const {
|
|
685
|
-
|
|
686
|
-
|
|
851
|
+
const key = { provider_eventId: { provider: input.event.provider, eventId: input.event.eventId } };
|
|
852
|
+
const existing = await db.marketplaceInboxEvent.findUnique({
|
|
853
|
+
where: key,
|
|
854
|
+
select: { id: true }
|
|
687
855
|
});
|
|
688
|
-
return
|
|
856
|
+
if (existing) return { id: existing.id, fresh: false };
|
|
857
|
+
try {
|
|
858
|
+
const row = await db.marketplaceInboxEvent.create({
|
|
859
|
+
data: {
|
|
860
|
+
clientId: input.clientId,
|
|
861
|
+
provider: input.event.provider,
|
|
862
|
+
eventId: input.event.eventId,
|
|
863
|
+
eventType: input.event.eventType,
|
|
864
|
+
externalOrderId: input.event.externalOrderId,
|
|
865
|
+
payload: input.payload,
|
|
866
|
+
// The engine's clock, not the database's: an announced order's
|
|
867
|
+
// acceptance window counts from here (`./fetch-order.ts`).
|
|
868
|
+
receivedAt: ctx.ports.clock.now()
|
|
869
|
+
},
|
|
870
|
+
select: { id: true }
|
|
871
|
+
});
|
|
872
|
+
return { id: row.id, fresh: true };
|
|
873
|
+
} catch (error) {
|
|
874
|
+
if (error.code !== "P2002") throw error;
|
|
875
|
+
const raced = await db.marketplaceInboxEvent.findUnique({
|
|
876
|
+
where: key,
|
|
877
|
+
select: { id: true }
|
|
878
|
+
});
|
|
879
|
+
return { id: raced?.id ?? "", fresh: false };
|
|
880
|
+
}
|
|
689
881
|
}
|
|
690
|
-
__name(
|
|
691
|
-
async function
|
|
882
|
+
__name(recordInboxEvent, "recordInboxEvent");
|
|
883
|
+
async function settleInboxEvent(ctx, id, outcome, error) {
|
|
884
|
+
if (!id) return;
|
|
692
885
|
const db = await ctx.ports.db();
|
|
693
|
-
|
|
694
|
-
where: {
|
|
695
|
-
data: {
|
|
886
|
+
await db.marketplaceInboxEvent.update({
|
|
887
|
+
where: { id },
|
|
888
|
+
data: {
|
|
889
|
+
status: outcome,
|
|
890
|
+
// Truncated: a provider's error body can be a page of HTML, and the
|
|
891
|
+
// column exists to be read by a human in a list.
|
|
892
|
+
error: error ? error.slice(0, 500) : null,
|
|
893
|
+
processedAt: ctx.ports.clock.now(),
|
|
894
|
+
attempts: { increment: 1 }
|
|
895
|
+
}
|
|
696
896
|
});
|
|
697
|
-
if (count > 0) ctx.ports.publishChanged(link.clientId);
|
|
698
|
-
return count > 0;
|
|
699
897
|
}
|
|
700
|
-
__name(
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
const
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
{
|
|
707
|
-
{ refreshToken: link.refreshToken }
|
|
708
|
-
);
|
|
709
|
-
if (answer.kind === "retry") return answer;
|
|
710
|
-
if (answer.kind === "refused") return await markLinkFailed(ctx, link) ? { ...answer, own: true } : RELINKED;
|
|
711
|
-
const rotated = answer.value.refreshToken;
|
|
712
|
-
if (rotated === null || rotated === link.refreshToken) {
|
|
713
|
-
return await cacheLinkToken(ctx, link, key, answer.value) ? { token: answer.value.accessToken } : RELINKED;
|
|
714
|
-
}
|
|
715
|
-
const stored = await storeRotated(ctx, link, rotated).catch((error) => {
|
|
716
|
-
ctx.ports.logger.error(
|
|
717
|
-
`marketplace.link: ${link.provider} rotated refresh token of ${link.clientId} not stored: ` + (error instanceof Error ? error.message : String(error))
|
|
718
|
-
);
|
|
719
|
-
return null;
|
|
898
|
+
__name(settleInboxEvent, "settleInboxEvent");
|
|
899
|
+
async function deferInboxEvent(ctx, id, reason) {
|
|
900
|
+
if (!id) return;
|
|
901
|
+
const db = await ctx.ports.db();
|
|
902
|
+
await db.marketplaceInboxEvent.update({
|
|
903
|
+
where: { id },
|
|
904
|
+
data: { error: reason.slice(0, 500), attempts: { increment: 1 } }
|
|
720
905
|
});
|
|
721
|
-
if (stored === false) return RELINKED;
|
|
722
|
-
setToken(ctx, key, answer.value);
|
|
723
|
-
return { token: answer.value.accessToken };
|
|
724
906
|
}
|
|
725
|
-
__name(
|
|
726
|
-
function
|
|
727
|
-
const
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
return call2;
|
|
746
|
-
}, "accessToken")
|
|
747
|
-
};
|
|
907
|
+
__name(deferInboxEvent, "deferInboxEvent");
|
|
908
|
+
async function listRetryableInboxEvents(ctx) {
|
|
909
|
+
const db = await ctx.ports.db();
|
|
910
|
+
const rows = await db.marketplaceInboxEvent.findMany({
|
|
911
|
+
where: {
|
|
912
|
+
status: { in: ["PENDING", "FAILED"] },
|
|
913
|
+
clientId: { not: null },
|
|
914
|
+
attempts: { lt: ctx.ports.maxInboxAttempts }
|
|
915
|
+
},
|
|
916
|
+
orderBy: { receivedAt: "asc" },
|
|
917
|
+
take: ctx.ports.reconcileBatchSize,
|
|
918
|
+
select: { id: true, clientId: true, provider: true, payload: true, receivedAt: true }
|
|
919
|
+
});
|
|
920
|
+
return rows.map((row) => ({
|
|
921
|
+
id: row.id,
|
|
922
|
+
clientId: row.clientId,
|
|
923
|
+
provider: row.provider,
|
|
924
|
+
payload: row.payload,
|
|
925
|
+
receivedAt: row.receivedAt
|
|
926
|
+
}));
|
|
748
927
|
}
|
|
749
|
-
__name(
|
|
928
|
+
__name(listRetryableInboxEvents, "listRetryableInboxEvents");
|
|
750
929
|
|
|
751
|
-
// src/core/
|
|
752
|
-
var
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
lastEventAt: true,
|
|
763
|
-
lastVerifiedAt: true,
|
|
764
|
-
archivedAt: true,
|
|
765
|
-
authMode: true
|
|
930
|
+
// src/core/marketplace-confirmed.ts
|
|
931
|
+
var CONFIRMED_BEFORE_ORDER = "confirmed before its order";
|
|
932
|
+
var NotClaimed = class extends Error {
|
|
933
|
+
constructor(refusal) {
|
|
934
|
+
super("not claimed");
|
|
935
|
+
this.refusal = refusal;
|
|
936
|
+
}
|
|
937
|
+
refusal;
|
|
938
|
+
static {
|
|
939
|
+
__name(this, "NotClaimed");
|
|
940
|
+
}
|
|
766
941
|
};
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
942
|
+
var CLEARED_FAILED_REQUEST = {
|
|
943
|
+
cancellationStatus: null,
|
|
944
|
+
cancellationReasonCode: null,
|
|
945
|
+
cancellationOffendingSkus: null,
|
|
946
|
+
cancellationFailureReason: null
|
|
947
|
+
};
|
|
948
|
+
async function claimConfirmed(ctx, clientId, held, now) {
|
|
949
|
+
if (held.cancellationStatus === "PENDING" || held.cancellationStatus === "REQUESTED") return { accepted: false };
|
|
950
|
+
try {
|
|
951
|
+
await ctx.ports.transaction(async (tx) => {
|
|
952
|
+
const answer = await ctx.ports.order.admit({
|
|
953
|
+
clientId,
|
|
954
|
+
orderId: held.orderId,
|
|
955
|
+
decision: "ACCEPT",
|
|
956
|
+
admission: {},
|
|
957
|
+
db: tx
|
|
958
|
+
});
|
|
959
|
+
if (!answer.admitted) throw new NotClaimed({ code: answer.code, message: answer.message });
|
|
960
|
+
const claimed = await tx.marketplaceAcceptance.updateMany({
|
|
961
|
+
where: { orderId: held.orderId, clientId, status: "AWAITING", ...NO_STANDING_REQUEST },
|
|
962
|
+
data: {
|
|
963
|
+
status: "ACCEPTED",
|
|
964
|
+
acknowledgedAt: now,
|
|
965
|
+
confirmedAt: now,
|
|
966
|
+
...held.cancellationStatus === "FAILED" ? CLEARED_FAILED_REQUEST : {}
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
if (claimed.count === 0) throw new NotClaimed(null);
|
|
970
|
+
});
|
|
971
|
+
return { accepted: true };
|
|
972
|
+
} catch (error) {
|
|
973
|
+
if (!(error instanceof NotClaimed)) throw error;
|
|
974
|
+
return error.refusal ? { accepted: false, refusal: error.refusal } : { accepted: false };
|
|
975
|
+
}
|
|
783
976
|
}
|
|
784
|
-
__name(
|
|
785
|
-
async function
|
|
977
|
+
__name(claimConfirmed, "claimConfirmed");
|
|
978
|
+
async function tellAccepted(ctx, clientId, orderId) {
|
|
979
|
+
try {
|
|
980
|
+
await ctx.ports.order.onAccepted(clientId, orderId);
|
|
981
|
+
} catch (error) {
|
|
982
|
+
ctx.ports.logger.error(
|
|
983
|
+
`marketplace.confirmed: order ${orderId} is ACCEPTED but the host's half failed: ` + (error instanceof Error ? error.message : String(error))
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
__name(tellAccepted, "tellAccepted");
|
|
988
|
+
async function confirmHeld(ctx, inboxId, clientId, held) {
|
|
989
|
+
const now = ctx.ports.clock.now();
|
|
786
990
|
const db = await ctx.ports.db();
|
|
787
|
-
|
|
788
|
-
where: {
|
|
789
|
-
|
|
790
|
-
...options.providers ? { provider: { in: [...options.providers] } } : {},
|
|
791
|
-
...options.includeArchived ? {} : { archivedAt: null }
|
|
792
|
-
},
|
|
793
|
-
select: VIEW_SELECT,
|
|
794
|
-
orderBy: { provider: "asc" }
|
|
991
|
+
await db.marketplaceAcceptance.updateMany({
|
|
992
|
+
where: { orderId: held.orderId, clientId, status: "AWAITING", confirmedAt: null },
|
|
993
|
+
data: { confirmedAt: now }
|
|
795
994
|
});
|
|
796
|
-
|
|
995
|
+
const claim3 = await claimConfirmed(ctx, clientId, held, now);
|
|
996
|
+
const note = claim3.accepted ? void 0 : `accepted on the marketplace; waits for a person${claim3.refusal ? ` (${claim3.refusal.code})` : ""}`;
|
|
997
|
+
await settleInboxEvent(ctx, inboxId, "PROCESSED", note);
|
|
998
|
+
if (claim3.accepted) await tellAccepted(ctx, clientId, held.orderId);
|
|
999
|
+
ctx.ports.publishChanged(clientId);
|
|
1000
|
+
return { kind: "confirmedByMarketplace", orderId: held.orderId, ...claim3 };
|
|
797
1001
|
}
|
|
798
|
-
__name(
|
|
799
|
-
async function
|
|
800
|
-
|
|
801
|
-
const
|
|
802
|
-
const
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
...input.externalMerchantId === void 0 ? {} : { externalMerchantId: input.externalMerchantId },
|
|
806
|
-
...input.autoAccept === void 0 ? {} : { autoAccept: input.autoAccept },
|
|
807
|
-
...input.followStatus === void 0 ? {} : { followStatus: input.followStatus },
|
|
808
|
-
...input.ackSlaSeconds === void 0 ? {} : { ackSlaSeconds: input.ackSlaSeconds },
|
|
809
|
-
// Typed credentials make the connection the store's own app again.
|
|
810
|
-
...sealed === void 0 ? {} : { credentials: sealed, status: "UNVERIFIED", authMode: "CREDENTIALS" }
|
|
811
|
-
};
|
|
812
|
-
const row = await db.marketplaceIntegration.upsert({
|
|
813
|
-
where: { clientId_provider: { clientId: input.clientId, provider: input.provider } },
|
|
814
|
-
create: {
|
|
815
|
-
clientId: input.clientId,
|
|
816
|
-
provider: input.provider,
|
|
817
|
-
credentials: sealed ?? "",
|
|
818
|
-
ackSlaSeconds: ctx.ports.defaultAckSlaSeconds,
|
|
819
|
-
...mutable
|
|
820
|
-
},
|
|
821
|
-
update: mutable,
|
|
822
|
-
select: VIEW_SELECT
|
|
1002
|
+
__name(confirmHeld, "confirmHeld");
|
|
1003
|
+
async function applyMarketplaceConfirmation(ctx, inboxId, clientId, event) {
|
|
1004
|
+
if (!event.marketplaceConfirmed || !event.externalOrderId) return null;
|
|
1005
|
+
const db = await ctx.ports.db();
|
|
1006
|
+
const held = await db.marketplaceAcceptance.findFirst({
|
|
1007
|
+
where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
|
|
1008
|
+
select: { orderId: true, status: true, cancellationStatus: true }
|
|
823
1009
|
});
|
|
824
|
-
|
|
1010
|
+
if (!held) {
|
|
1011
|
+
await deferInboxEvent(ctx, inboxId, CONFIRMED_BEFORE_ORDER);
|
|
1012
|
+
return { kind: "ignored", reason: CONFIRMED_BEFORE_ORDER };
|
|
1013
|
+
}
|
|
1014
|
+
if (held.status === "ACCEPTED") return confirmAccepted(ctx, inboxId, clientId, held.orderId);
|
|
1015
|
+
if (held.status !== "AWAITING") {
|
|
1016
|
+
const reason = `the order is ${held.status}, not AWAITING`;
|
|
1017
|
+
await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
|
|
1018
|
+
return { kind: "ignored", reason };
|
|
1019
|
+
}
|
|
1020
|
+
return confirmHeld(ctx, inboxId, clientId, held);
|
|
1021
|
+
}
|
|
1022
|
+
__name(applyMarketplaceConfirmation, "applyMarketplaceConfirmation");
|
|
1023
|
+
async function confirmAccepted(ctx, inboxId, clientId, orderId) {
|
|
1024
|
+
const db = await ctx.ports.db();
|
|
1025
|
+
const stamped = await db.marketplaceAcceptance.updateMany({
|
|
1026
|
+
where: { orderId, clientId, status: "ACCEPTED", confirmedAt: null },
|
|
1027
|
+
data: { confirmedAt: ctx.ports.clock.now(), confirmFailedAt: null }
|
|
1028
|
+
});
|
|
1029
|
+
if (stamped.count === 0) {
|
|
1030
|
+
const reason = "the order is ACCEPTED and its confirm already stamped";
|
|
1031
|
+
await settleInboxEvent(ctx, inboxId, "IGNORED", reason);
|
|
1032
|
+
return { kind: "ignored", reason };
|
|
1033
|
+
}
|
|
1034
|
+
await settleInboxEvent(ctx, inboxId, "PROCESSED", "accepted here first; the marketplace took the acceptance");
|
|
1035
|
+
ctx.ports.publishChanged(clientId);
|
|
1036
|
+
return { kind: "confirmedByMarketplace", orderId, accepted: true };
|
|
1037
|
+
}
|
|
1038
|
+
__name(confirmAccepted, "confirmAccepted");
|
|
1039
|
+
async function applyRows(ctx, rows) {
|
|
1040
|
+
const applied = /* @__PURE__ */ new Set();
|
|
1041
|
+
for (const row of rows) {
|
|
1042
|
+
const event = ctx.registry.get(row.provider)?.normalize(row.payload) ?? null;
|
|
1043
|
+
if (!event?.marketplaceConfirmed) continue;
|
|
1044
|
+
const outcome = await applyMarketplaceConfirmation(ctx, row.id, row.clientId, event);
|
|
1045
|
+
if (outcome?.kind === "confirmedByMarketplace") applied.add(outcome.orderId);
|
|
1046
|
+
}
|
|
1047
|
+
return applied;
|
|
825
1048
|
}
|
|
826
|
-
__name(
|
|
827
|
-
|
|
1049
|
+
__name(applyRows, "applyRows");
|
|
1050
|
+
var DEFERRED_SELECT = { id: true, clientId: true, provider: true, externalOrderId: true, payload: true };
|
|
1051
|
+
async function applyDeferredConfirmations(ctx, input) {
|
|
1052
|
+
if (!ctx.registry.get(input.provider)?.capabilities.marketplaceConfirms) return;
|
|
828
1053
|
const db = await ctx.ports.db();
|
|
829
|
-
const
|
|
830
|
-
where: {
|
|
831
|
-
select:
|
|
1054
|
+
const rows = await db.marketplaceInboxEvent.findMany({
|
|
1055
|
+
where: { ...input, status: "PENDING", error: CONFIRMED_BEFORE_ORDER },
|
|
1056
|
+
select: DEFERRED_SELECT
|
|
832
1057
|
});
|
|
833
|
-
|
|
1058
|
+
await applyRows(ctx, rows);
|
|
834
1059
|
}
|
|
835
|
-
__name(
|
|
836
|
-
async function
|
|
1060
|
+
__name(applyDeferredConfirmations, "applyDeferredConfirmations");
|
|
1061
|
+
async function applyOwedConfirmations(ctx, lapsed) {
|
|
1062
|
+
if (lapsed.length === 0) return /* @__PURE__ */ new Set();
|
|
837
1063
|
const db = await ctx.ports.db();
|
|
838
|
-
const
|
|
839
|
-
where: {
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
archivedAt: true,
|
|
847
|
-
externalMerchantId: true,
|
|
848
|
-
authMode: true,
|
|
849
|
-
environment: true
|
|
850
|
-
}
|
|
1064
|
+
const rows = await db.marketplaceInboxEvent.findMany({
|
|
1065
|
+
where: {
|
|
1066
|
+
status: "PENDING",
|
|
1067
|
+
error: CONFIRMED_BEFORE_ORDER,
|
|
1068
|
+
clientId: { not: null },
|
|
1069
|
+
externalOrderId: { in: [...new Set(lapsed.map((row) => row.externalOrderId))] }
|
|
1070
|
+
},
|
|
1071
|
+
select: DEFERRED_SELECT
|
|
851
1072
|
});
|
|
852
|
-
|
|
853
|
-
return {
|
|
854
|
-
enabled: row.enabled,
|
|
855
|
-
autoAccept: row.autoAccept,
|
|
856
|
-
followStatus: row.followStatus ?? true,
|
|
857
|
-
ackSlaSeconds: row.ackSlaSeconds,
|
|
858
|
-
externalMerchantId: row.externalMerchantId ?? null,
|
|
859
|
-
// An unopenable blob must not read as "no secret configured" — that would
|
|
860
|
-
// turn a key-rotation problem into an endpoint that accepts unsigned
|
|
861
|
-
// deliveries. The secrets port throws instead, and the caller answers 401.
|
|
862
|
-
webhookSecret: await webhookSecretOf(ctx, provider, row)
|
|
863
|
-
};
|
|
1073
|
+
const named = new Set(lapsed.map((row) => `${row.provider}:${row.externalOrderId}`));
|
|
1074
|
+
return applyRows(ctx, rows.filter((row) => named.has(`${row.provider}:${row.externalOrderId ?? ""}`)));
|
|
864
1075
|
}
|
|
865
|
-
__name(
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1076
|
+
__name(applyOwedConfirmations, "applyOwedConfirmations");
|
|
1077
|
+
|
|
1078
|
+
// src/core/catalogue-category.ts
|
|
1079
|
+
var CLAIM_STALE_MS = 3 * 6e4;
|
|
1080
|
+
async function claim(table, key, row, now) {
|
|
1081
|
+
if (!row) {
|
|
1082
|
+
try {
|
|
1083
|
+
await table.create({ data: { ...key, claimedAt: now } });
|
|
1084
|
+
return true;
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
if (error.code === "P2002") return false;
|
|
1087
|
+
throw error;
|
|
1088
|
+
}
|
|
869
1089
|
}
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1090
|
+
const stale = new Date(now.getTime() - CLAIM_STALE_MS);
|
|
1091
|
+
const moved = await table.updateMany({
|
|
1092
|
+
where: { ...key, externalId: null, OR: [{ claimedAt: null }, { claimedAt: { lt: stale } }] },
|
|
1093
|
+
data: { claimedAt: now }
|
|
1094
|
+
});
|
|
1095
|
+
return moved.count > 0;
|
|
875
1096
|
}
|
|
876
|
-
__name(
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
throw new Error("Stored marketplace credentials are not an object.");
|
|
1097
|
+
__name(claim, "claim");
|
|
1098
|
+
async function release(table, key, claimedAt, id) {
|
|
1099
|
+
if (id !== null) {
|
|
1100
|
+
await table.updateMany({ where: { ...key, externalId: null }, data: { externalId: id, claimedAt: null } });
|
|
1101
|
+
return;
|
|
882
1102
|
}
|
|
883
|
-
|
|
884
|
-
return {
|
|
885
|
-
clientId: String(record.clientId ?? ""),
|
|
886
|
-
clientSecret: String(record.clientSecret ?? ""),
|
|
887
|
-
webhookSecret: record.webhookSecret ? String(record.webhookSecret) : null
|
|
888
|
-
};
|
|
889
|
-
}
|
|
890
|
-
__name(openCredentials, "openCredentials");
|
|
891
|
-
async function markMarketplaceEventSeen(db, clientId, provider, at) {
|
|
892
|
-
await db.marketplaceIntegration.updateMany({
|
|
893
|
-
where: { clientId, provider },
|
|
894
|
-
data: { lastEventAt: at }
|
|
895
|
-
});
|
|
1103
|
+
await table.updateMany({ where: { ...key, externalId: null, claimedAt }, data: { claimedAt: null } });
|
|
896
1104
|
}
|
|
897
|
-
__name(
|
|
898
|
-
async function
|
|
899
|
-
|
|
1105
|
+
__name(release, "release");
|
|
1106
|
+
async function resolveCategory(ctx, connection, name, resolve, state = { waited: false }) {
|
|
1107
|
+
const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
|
|
1108
|
+
if (!table) return resolve();
|
|
1109
|
+
const key = { clientId: connection.clientId, provider: connection.provider, name: name.trim() };
|
|
1110
|
+
const row = await table.findFirst({ where: key, select: { externalId: true } });
|
|
1111
|
+
if (row?.externalId) return { id: row.externalId };
|
|
1112
|
+
const now = ctx.ports.clock.now();
|
|
1113
|
+
if (!await claim(table, key, row, now)) {
|
|
1114
|
+
state.waited = true;
|
|
1115
|
+
return { kind: "retry", reason: `another publish is creating the category "${key.name}"` };
|
|
1116
|
+
}
|
|
1117
|
+
let result = { kind: "retry", reason: "the category was not resolved" };
|
|
1118
|
+
try {
|
|
1119
|
+
result = await resolve();
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
result = { kind: "retry", reason: error instanceof Error ? error.message : String(error) };
|
|
1122
|
+
} finally {
|
|
1123
|
+
await release(table, key, now, "id" in result ? result.id : null);
|
|
1124
|
+
}
|
|
1125
|
+
return result;
|
|
900
1126
|
}
|
|
901
|
-
__name(
|
|
902
|
-
async function
|
|
903
|
-
const
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
1127
|
+
__name(resolveCategory, "resolveCategory");
|
|
1128
|
+
async function forgetCategory(ctx, connection, name) {
|
|
1129
|
+
const table = (await ctx.ports.db()).marketplaceCatalogueCategory;
|
|
1130
|
+
if (!table) return;
|
|
1131
|
+
await table.updateMany({
|
|
1132
|
+
where: { clientId: connection.clientId, provider: connection.provider, name: name.trim() },
|
|
1133
|
+
data: { externalId: null, claimedAt: null }
|
|
907
1134
|
});
|
|
908
|
-
if (!row || row.credentials === "") return null;
|
|
909
|
-
const sealed = row.credentials;
|
|
910
|
-
const environment = environmentOf(row.environment);
|
|
911
|
-
if (row.authMode !== "LINKED") return { connection: { environment, credentials: openCredentials(ctx, sealed) }, sealed };
|
|
912
|
-
const app = await appCredentialsOf(ctx, provider, environment);
|
|
913
|
-
if (!app) throw new Error(`No app credentials are configured for ${provider}.`);
|
|
914
|
-
if (isAppLinkBlob(ctx, sealed)) return { connection: { environment, credentials: app }, sealed };
|
|
915
|
-
const refreshToken = openLinkRefreshToken(ctx, sealed);
|
|
916
|
-
const link = { clientId, provider, environment, refreshToken, app, sealed };
|
|
917
|
-
return { connection: { environment, credentials: app, grant: linkGrant(ctx, link) }, sealed };
|
|
918
1135
|
}
|
|
919
|
-
__name(
|
|
1136
|
+
__name(forgetCategory, "forgetCategory");
|
|
920
1137
|
|
|
921
1138
|
// src/core/catalogue-store.ts
|
|
922
1139
|
var CATALOGUE_ROW_SELECT = {
|
|
@@ -1140,10 +1357,10 @@ async function runOnce(ctx, table, payload, attempt) {
|
|
|
1140
1357
|
if (row.status !== WANTED[action]) return { kind: "skipped", reason: `the publication is ${row.status}, not ${WANTED[action]}` };
|
|
1141
1358
|
const run = await runFor(ctx, row, action);
|
|
1142
1359
|
if ("code" in run) return fail(ctx, table, row, action, { code: run.code, reason: null }, run.code);
|
|
1143
|
-
return
|
|
1360
|
+
return settle2(ctx, table, row, action, run, attempt);
|
|
1144
1361
|
}
|
|
1145
1362
|
__name(runOnce, "runOnce");
|
|
1146
|
-
async function
|
|
1363
|
+
async function settle2(ctx, table, row, action, run, attempt) {
|
|
1147
1364
|
const { result } = run;
|
|
1148
1365
|
if (result.kind === "accepted" || result.kind === "published") {
|
|
1149
1366
|
await stampSuccess(ctx, table, row, action, result, run.sentPriceCents);
|
|
@@ -1158,7 +1375,7 @@ async function settle(ctx, table, row, action, run, attempt) {
|
|
|
1158
1375
|
if (result.kind === "retry" && run.waited) return waitedOut(ctx, row, action, detail);
|
|
1159
1376
|
return fail(ctx, table, row, action, failureOf(result), detail);
|
|
1160
1377
|
}
|
|
1161
|
-
__name(
|
|
1378
|
+
__name(settle2, "settle");
|
|
1162
1379
|
function readRow(table, payload) {
|
|
1163
1380
|
return table.findFirst({
|
|
1164
1381
|
where: { id: payload.publicationId, clientId: payload.clientId },
|
|
@@ -1238,7 +1455,7 @@ async function runAcknowledge(ctx, payload, attempt) {
|
|
|
1238
1455
|
{ http: ctx.ports.http, tokens: ctx.tokens, now, ...connection },
|
|
1239
1456
|
[...new Set(owed.map((row) => row.eventId))]
|
|
1240
1457
|
);
|
|
1241
|
-
return
|
|
1458
|
+
return settle3(ctx, payload, owed, result, attempt);
|
|
1242
1459
|
}
|
|
1243
1460
|
__name(runAcknowledge, "runAcknowledge");
|
|
1244
1461
|
async function stampSettled(ctx, owed) {
|
|
@@ -1249,7 +1466,7 @@ async function stampSettled(ctx, owed) {
|
|
|
1249
1466
|
});
|
|
1250
1467
|
}
|
|
1251
1468
|
__name(stampSettled, "stampSettled");
|
|
1252
|
-
async function
|
|
1469
|
+
async function settle3(ctx, payload, owed, result, attempt) {
|
|
1253
1470
|
if (result.kind === "accepted") {
|
|
1254
1471
|
await stampSettled(ctx, owed);
|
|
1255
1472
|
return { kind: "done", acknowledged: owed.length };
|
|
@@ -1266,7 +1483,7 @@ async function settle2(ctx, payload, owed, result, attempt) {
|
|
|
1266
1483
|
ctx.ports.logger.error(`${MARKETPLACE_ACKNOWLEDGE_JOB}: ${payload.provider} events of ${payload.clientId} not acknowledged: ${reason}`);
|
|
1267
1484
|
return { kind: "failed", reason };
|
|
1268
1485
|
}
|
|
1269
|
-
__name(
|
|
1486
|
+
__name(settle3, "settle");
|
|
1270
1487
|
async function sweepAcknowledgements(ctx) {
|
|
1271
1488
|
const db = await ctx.ports.db();
|
|
1272
1489
|
let requeued = 0;
|
|
@@ -2225,38 +2442,6 @@ async function sweepCatalogue(ctx, now) {
|
|
|
2225
2442
|
}
|
|
2226
2443
|
__name(sweepCatalogue, "sweepCatalogue");
|
|
2227
2444
|
|
|
2228
|
-
// src/core/status-store.ts
|
|
2229
|
-
function statusTable(db) {
|
|
2230
|
-
return db.marketplaceStatusUpdate ?? null;
|
|
2231
|
-
}
|
|
2232
|
-
__name(statusTable, "statusTable");
|
|
2233
|
-
async function readStatusRows(table, orderId, steps2) {
|
|
2234
|
-
return await table.findMany({
|
|
2235
|
-
where: { orderId, step: { in: [...steps2] } },
|
|
2236
|
-
select: { orderId: true, step: true, source: true, state: true, claimKey: true }
|
|
2237
|
-
});
|
|
2238
|
-
}
|
|
2239
|
-
__name(readStatusRows, "readStatusRows");
|
|
2240
|
-
async function insertStatusRow(table, row) {
|
|
2241
|
-
try {
|
|
2242
|
-
await table.create({ data: row });
|
|
2243
|
-
return true;
|
|
2244
|
-
} catch (error) {
|
|
2245
|
-
if (error.code === "P2002") return false;
|
|
2246
|
-
throw error;
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
__name(insertStatusRow, "insertStatusRow");
|
|
2250
|
-
async function noteMarketplaceStep(ctx, row) {
|
|
2251
|
-
const table = statusTable(await ctx.ports.db());
|
|
2252
|
-
if (table) await insertStatusRow(table, { ...row, source: "MARKETPLACE", state: "NOTED", claimKey: "" });
|
|
2253
|
-
}
|
|
2254
|
-
__name(noteMarketplaceStep, "noteMarketplaceStep");
|
|
2255
|
-
async function settleStatusRow(table, where, state) {
|
|
2256
|
-
return (await table.updateMany({ where: { ...where, state: "SENDING" }, data: { state } })).count;
|
|
2257
|
-
}
|
|
2258
|
-
__name(settleStatusRow, "settleStatusRow");
|
|
2259
|
-
|
|
2260
2445
|
// src/core/outbound-sweep.ts
|
|
2261
2446
|
var OUTBOUND_STALE_MS = 10 * 6e4;
|
|
2262
2447
|
var OUTBOUND_GIVE_UP_MS = 24 * 60 * 6e4;
|
|
@@ -2269,14 +2454,15 @@ __name(sweepDedupeKey, "sweepDedupeKey");
|
|
|
2269
2454
|
async function requeue(ctx, rows, action, now) {
|
|
2270
2455
|
let queued = 0;
|
|
2271
2456
|
for (const row of rows) {
|
|
2457
|
+
const logistics = row.step?.startsWith(LOGISTICS_ROW_PREFIX) === true;
|
|
2272
2458
|
const payload = {
|
|
2273
2459
|
clientId: row.clientId,
|
|
2274
2460
|
orderId: row.orderId,
|
|
2275
|
-
action,
|
|
2276
|
-
...row.step ? { step: row.step } : {},
|
|
2461
|
+
action: logistics ? "logistics" : action,
|
|
2462
|
+
...logistics ? { logisticsStep: row.step.slice(LOGISTICS_ROW_PREFIX.length) } : row.step ? { step: row.step } : {},
|
|
2277
2463
|
...row.claimKey === void 0 ? {} : { claimKey: row.claimKey }
|
|
2278
2464
|
};
|
|
2279
|
-
if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(action, row.orderId, now, row.step))) queued += 1;
|
|
2465
|
+
if (await enqueueOutbound(ctx, payload, row.provider, sweepDedupeKey(payload.action, row.orderId, now, row.step))) queued += 1;
|
|
2280
2466
|
}
|
|
2281
2467
|
return queued;
|
|
2282
2468
|
}
|
|
@@ -2331,7 +2517,7 @@ async function sweepStatus(ctx, now) {
|
|
|
2331
2517
|
});
|
|
2332
2518
|
const claimed = [];
|
|
2333
2519
|
for (const row of owed) {
|
|
2334
|
-
const fresh = `sweep:${now.getTime()}`;
|
|
2520
|
+
const fresh = `sweep:${now.getTime()}:${row.step}`;
|
|
2335
2521
|
const taken = await table.updateMany({
|
|
2336
2522
|
where: { orderId: row.orderId, step: row.step, state: "SENDING", claimKey: row.claimKey, updatedAt: { lt: stale } },
|
|
2337
2523
|
data: { claimKey: fresh }
|
|
@@ -2459,14 +2645,14 @@ function deliveredByOf(row) {
|
|
|
2459
2645
|
return row.deliveredBy === "MERCHANT" || row.deliveredBy === "MARKETPLACE" ? row.deliveredBy : null;
|
|
2460
2646
|
}
|
|
2461
2647
|
__name(deliveredByOf, "deliveredByOf");
|
|
2462
|
-
var
|
|
2648
|
+
var skipped2 = /* @__PURE__ */ __name((reason) => ({ kind: "skipped", reason }), "skipped");
|
|
2463
2649
|
function acceptanceSkip(row) {
|
|
2464
2650
|
if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
|
|
2465
2651
|
const standing = row.cancellationStatus !== null && row.cancellationStatus !== "FAILED";
|
|
2466
2652
|
return standing ? `a cancellation request is ${row.cancellationStatus}` : null;
|
|
2467
2653
|
}
|
|
2468
2654
|
__name(acceptanceSkip, "acceptanceSkip");
|
|
2469
|
-
function
|
|
2655
|
+
function confirmSkip2(row, adapter, deps) {
|
|
2470
2656
|
if (!adapter.capabilities.statusAfterConfirm || row.confirmedAt) return null;
|
|
2471
2657
|
if (row.confirmFailedAt) return "the marketplace never took the store's confirm";
|
|
2472
2658
|
if (deps.attempt.attempt < deps.attempt.maxAttempts) {
|
|
@@ -2474,7 +2660,7 @@ function confirmSkip(row, adapter, deps) {
|
|
|
2474
2660
|
}
|
|
2475
2661
|
return "the store's confirm has not reached the marketplace";
|
|
2476
2662
|
}
|
|
2477
|
-
__name(
|
|
2663
|
+
__name(confirmSkip2, "confirmSkip");
|
|
2478
2664
|
async function adapterAndHostSkip(ctx, payload, step, row, adapter) {
|
|
2479
2665
|
const takes = adapter.informStatus !== void 0 && adapter.capabilities.statusSteps?.includes(step) === true && adapter.statusSupported?.({ step, deliveredBy: deliveredByOf(row) }) !== false;
|
|
2480
2666
|
if (!takes) return `the marketplace does not take ${step} for this order`;
|
|
@@ -2499,7 +2685,7 @@ function callAdapter(ctx, connection, adapter, row, step, ref) {
|
|
|
2499
2685
|
});
|
|
2500
2686
|
}
|
|
2501
2687
|
__name(callAdapter, "callAdapter");
|
|
2502
|
-
async function
|
|
2688
|
+
async function settle4(ctx, db, where, result, deps) {
|
|
2503
2689
|
const table = statusTable(db);
|
|
2504
2690
|
if (result.kind === "accepted") {
|
|
2505
2691
|
await settleStatusRow(table, where, "SENT");
|
|
@@ -2513,7 +2699,7 @@ async function settle3(ctx, db, where, result, deps) {
|
|
|
2513
2699
|
ctx.ports.logger.error(`${MARKETPLACE_OUTBOUND_JOB}: status ${where.step} for order ${where.orderId} failed: ${reason}`);
|
|
2514
2700
|
return { kind: "failed", action: "status", reason };
|
|
2515
2701
|
}
|
|
2516
|
-
__name(
|
|
2702
|
+
__name(settle4, "settle");
|
|
2517
2703
|
function ownsClaim(found, key) {
|
|
2518
2704
|
return found.source === "STORE" && found.state === "SENDING" && found.claimKey === key;
|
|
2519
2705
|
}
|
|
@@ -2539,24 +2725,24 @@ async function claim2(table, payload, row, step, key) {
|
|
|
2539
2725
|
__name(claim2, "claim");
|
|
2540
2726
|
async function runStatus(ctx, payload, row, adapter, deps) {
|
|
2541
2727
|
const step = payload.step;
|
|
2542
|
-
if (!step) return
|
|
2543
|
-
const stopped = acceptanceSkip(row) ??
|
|
2544
|
-
if (stopped) return
|
|
2728
|
+
if (!step) return skipped2("a status call names no step");
|
|
2729
|
+
const stopped = acceptanceSkip(row) ?? confirmSkip2(row, adapter, deps) ?? await adapterAndHostSkip(ctx, payload, step, row, adapter);
|
|
2730
|
+
if (stopped) return skipped2(stopped);
|
|
2545
2731
|
const db = await ctx.ports.db();
|
|
2546
2732
|
const table = statusTable(db);
|
|
2547
|
-
if (!table) return
|
|
2733
|
+
if (!table) return skipped2("the host has not composed the status model");
|
|
2548
2734
|
const connection = await connectionOf(ctx, payload.clientId, row.provider);
|
|
2549
2735
|
if (typeof connection === "string") {
|
|
2550
2736
|
ctx.ports.logger.info(`${MARKETPLACE_OUTBOUND_JOB}: status ${step} for order ${row.orderId} not sent: ${connection}`);
|
|
2551
|
-
return
|
|
2737
|
+
return skipped2(connection);
|
|
2552
2738
|
}
|
|
2553
2739
|
const key = payload.claimKey ?? "";
|
|
2554
2740
|
const unclaimed = await claim2(table, payload, row, step, key);
|
|
2555
|
-
if (unclaimed) return
|
|
2741
|
+
if (unclaimed) return skipped2(unclaimed);
|
|
2556
2742
|
const before = await sendPrerequisite(ctx, { table, payload, row, step, key, connection, adapter }, deps);
|
|
2557
2743
|
if (before) return before;
|
|
2558
2744
|
const result = await callAdapter(ctx, connection, adapter, row, step, deps.ref);
|
|
2559
|
-
return
|
|
2745
|
+
return settle4(ctx, db, { orderId: row.orderId, step, claimKey: key }, result, deps);
|
|
2560
2746
|
}
|
|
2561
2747
|
__name(runStatus, "runStatus");
|
|
2562
2748
|
function prerequisiteState(found, key, run, first, deps) {
|
|
@@ -2565,7 +2751,7 @@ function prerequisiteState(found, key, run, first, deps) {
|
|
|
2565
2751
|
if (deps.attempt.attempt < deps.attempt.maxAttempts) {
|
|
2566
2752
|
throw deps.retryError(`status ${run.step} for order ${run.row.orderId}: waiting for ${first}, held by another run`);
|
|
2567
2753
|
}
|
|
2568
|
-
return
|
|
2754
|
+
return skipped2(`${first} is still being sent by another run`);
|
|
2569
2755
|
}
|
|
2570
2756
|
__name(prerequisiteState, "prerequisiteState");
|
|
2571
2757
|
async function sendPrerequisite(ctx, run, deps) {
|
|
@@ -2582,7 +2768,7 @@ async function sendPrerequisite(ctx, run, deps) {
|
|
|
2582
2768
|
if (!claimed) return sendPrerequisite(ctx, run, deps);
|
|
2583
2769
|
}
|
|
2584
2770
|
const result = await callAdapter(ctx, run.connection, run.adapter, run.row, first, deps.ref);
|
|
2585
|
-
const outcome = await
|
|
2771
|
+
const outcome = await settle4(ctx, await ctx.ports.db(), { orderId: run.row.orderId, step: first, claimKey: key }, result, deps);
|
|
2586
2772
|
return outcome.kind === "skipped" ? outcome : null;
|
|
2587
2773
|
}
|
|
2588
2774
|
__name(sendPrerequisite, "sendPrerequisite");
|
|
@@ -2630,7 +2816,7 @@ function refOf(row) {
|
|
|
2630
2816
|
};
|
|
2631
2817
|
}
|
|
2632
2818
|
__name(refOf, "refOf");
|
|
2633
|
-
function
|
|
2819
|
+
function confirmSkip3(row, adapter) {
|
|
2634
2820
|
if (row.status !== "ACCEPTED") return `the order is ${row.status}, not ACCEPTED`;
|
|
2635
2821
|
if (row.cancellationStatus !== null && row.cancellationStatus !== "FAILED") {
|
|
2636
2822
|
return `a cancellation request is ${row.cancellationStatus}`;
|
|
@@ -2639,7 +2825,7 @@ function confirmSkip2(row, adapter) {
|
|
|
2639
2825
|
if (!adapter.capabilities.apiConfirm) return "the marketplace has no confirm API";
|
|
2640
2826
|
return null;
|
|
2641
2827
|
}
|
|
2642
|
-
__name(
|
|
2828
|
+
__name(confirmSkip3, "confirmSkip");
|
|
2643
2829
|
async function stampConfirm(ctx, row, succeeded, now) {
|
|
2644
2830
|
const db = await ctx.ports.db();
|
|
2645
2831
|
await db.marketplaceAcceptance.updateMany({
|
|
@@ -2695,7 +2881,7 @@ async function connectionFor(ctx, clientId, provider) {
|
|
|
2695
2881
|
}
|
|
2696
2882
|
}
|
|
2697
2883
|
__name(connectionFor, "connectionFor");
|
|
2698
|
-
async function
|
|
2884
|
+
async function settle5(ctx, payload, row, result, attempt, succeed, fail3) {
|
|
2699
2885
|
if (result.kind === "accepted") {
|
|
2700
2886
|
await succeed();
|
|
2701
2887
|
ctx.ports.publishChanged(payload.clientId);
|
|
@@ -2710,9 +2896,9 @@ async function settle4(ctx, payload, row, result, attempt, succeed, fail3) {
|
|
|
2710
2896
|
ctx.ports.publishChanged(payload.clientId);
|
|
2711
2897
|
return { kind: "failed", action: payload.action, reason };
|
|
2712
2898
|
}
|
|
2713
|
-
__name(
|
|
2899
|
+
__name(settle5, "settle");
|
|
2714
2900
|
async function runConfirm(ctx, payload, row, adapter, attempt) {
|
|
2715
|
-
const skip =
|
|
2901
|
+
const skip = confirmSkip3(row, adapter);
|
|
2716
2902
|
if (skip) return { kind: "skipped", reason: skip };
|
|
2717
2903
|
const now = ctx.ports.clock.now();
|
|
2718
2904
|
const connection = await connectionFor(ctx, payload.clientId, row.provider);
|
|
@@ -2722,7 +2908,7 @@ async function runConfirm(ctx, payload, row, adapter, attempt) {
|
|
|
2722
2908
|
// The stated preparation time, for a marketplace whose confirm takes one.
|
|
2723
2909
|
{ preparationMinutes: adapter.capabilities.confirmTakesPreparationTime ? row.preparationMinutes : null }
|
|
2724
2910
|
);
|
|
2725
|
-
return
|
|
2911
|
+
return settle5(
|
|
2726
2912
|
ctx,
|
|
2727
2913
|
payload,
|
|
2728
2914
|
row,
|
|
@@ -2765,7 +2951,7 @@ async function runCancellation(ctx, payload, row, adapter, attempt) {
|
|
|
2765
2951
|
);
|
|
2766
2952
|
}
|
|
2767
2953
|
const taken = adapter.capabilities.asyncCancellationOutcome ? "REQUESTED" : "CONFIRMED";
|
|
2768
|
-
return
|
|
2954
|
+
return settle5(
|
|
2769
2955
|
ctx,
|
|
2770
2956
|
payload,
|
|
2771
2957
|
row,
|
|
@@ -2811,6 +2997,7 @@ async function runOnce2(ctx, payload, attempt) {
|
|
|
2811
2997
|
if (!adapter) return { kind: "skipped", reason: `no adapter for ${row.provider}` };
|
|
2812
2998
|
const deps = { attempt, ref: refOf(row), retryError: /* @__PURE__ */ __name((m) => new OutboundRetryError(m), "retryError") };
|
|
2813
2999
|
if (payload.action === "status") return runStatus(ctx, payload, row, adapter, deps);
|
|
3000
|
+
if (payload.action === "logistics") return runLogistics(ctx, payload, row, adapter, deps);
|
|
2814
3001
|
if (payload.action === "validatePickupCode") return runPickupCode(ctx, payload, row, adapter, deps);
|
|
2815
3002
|
return payload.action === "confirm" ? runConfirm(ctx, payload, row, adapter, attempt) : runCancellation(ctx, payload, row, adapter, attempt);
|
|
2816
3003
|
}
|
|
@@ -2820,7 +3007,7 @@ async function runOutbound(ctx, payload, attempt) {
|
|
|
2820
3007
|
return await runOnce2(ctx, payload, attempt);
|
|
2821
3008
|
} catch (error) {
|
|
2822
3009
|
if (error instanceof OutboundRetryError || attempt.attempt < attempt.maxAttempts) throw error;
|
|
2823
|
-
return stampLastAttemptFailure(ctx, payload, error);
|
|
3010
|
+
return payload.action === "logistics" ? failLogisticsJob(ctx, payload, error) : stampLastAttemptFailure(ctx, payload, error);
|
|
2824
3011
|
}
|
|
2825
3012
|
}
|
|
2826
3013
|
__name(runOutbound, "runOutbound");
|
|
@@ -3207,30 +3394,10 @@ async function runAvailability(ctx, payload, attempt) {
|
|
|
3207
3394
|
__name(runAvailability, "runAvailability");
|
|
3208
3395
|
|
|
3209
3396
|
export {
|
|
3210
|
-
requestsFirst,
|
|
3211
|
-
tellCancellationFailed,
|
|
3212
|
-
MarketplaceAdapterRegistrationError,
|
|
3213
|
-
createAdapterRegistry,
|
|
3214
|
-
storedReasons,
|
|
3215
|
-
reasonsForOrder,
|
|
3216
|
-
resolveReason,
|
|
3217
|
-
suggestReason,
|
|
3218
|
-
NO_STANDING_REQUEST,
|
|
3219
|
-
CLAIM_SELECT,
|
|
3220
|
-
notPendingProblem,
|
|
3221
|
-
planCancellation,
|
|
3222
|
-
refusalData,
|
|
3223
|
-
requestData,
|
|
3224
|
-
failCancellationRequest,
|
|
3225
3397
|
recordInboxEvent,
|
|
3226
3398
|
settleInboxEvent,
|
|
3227
3399
|
deferInboxEvent,
|
|
3228
3400
|
listRetryableInboxEvents,
|
|
3229
|
-
CONFIRMED_BEFORE_ORDER,
|
|
3230
|
-
applyMarketplaceConfirmation,
|
|
3231
|
-
listPendingAcceptances,
|
|
3232
|
-
expireLapsedAcceptances,
|
|
3233
|
-
cancelAcceptance,
|
|
3234
3401
|
sealLink,
|
|
3235
3402
|
sealAppLink,
|
|
3236
3403
|
appCredentialsOf,
|
|
@@ -3246,12 +3413,38 @@ export {
|
|
|
3246
3413
|
connectionMerchantId,
|
|
3247
3414
|
resolveIngestionTarget,
|
|
3248
3415
|
readOutboundConnection,
|
|
3249
|
-
listMarketplaceMenuLinks,
|
|
3250
|
-
upsertLink,
|
|
3251
3416
|
MARKETPLACE_OUTBOUND_JOB,
|
|
3252
3417
|
outboundDedupeKey,
|
|
3253
3418
|
statusDedupeKey,
|
|
3254
3419
|
enqueueOutbound,
|
|
3420
|
+
statusTable,
|
|
3421
|
+
readStatusRows,
|
|
3422
|
+
noteMarketplaceStep,
|
|
3423
|
+
LOGISTICS_STEPS,
|
|
3424
|
+
logisticsEngine,
|
|
3425
|
+
logisticsCallContext,
|
|
3426
|
+
requestsFirst,
|
|
3427
|
+
tellCancellationFailed,
|
|
3428
|
+
MarketplaceAdapterRegistrationError,
|
|
3429
|
+
createAdapterRegistry,
|
|
3430
|
+
storedReasons,
|
|
3431
|
+
reasonsForOrder,
|
|
3432
|
+
resolveReason,
|
|
3433
|
+
suggestReason,
|
|
3434
|
+
NO_STANDING_REQUEST,
|
|
3435
|
+
CLAIM_SELECT,
|
|
3436
|
+
notPendingProblem,
|
|
3437
|
+
planCancellation,
|
|
3438
|
+
refusalData,
|
|
3439
|
+
requestData,
|
|
3440
|
+
failCancellationRequest,
|
|
3441
|
+
CONFIRMED_BEFORE_ORDER,
|
|
3442
|
+
applyMarketplaceConfirmation,
|
|
3443
|
+
listPendingAcceptances,
|
|
3444
|
+
expireLapsedAcceptances,
|
|
3445
|
+
cancelAcceptance,
|
|
3446
|
+
listMarketplaceMenuLinks,
|
|
3447
|
+
upsertLink,
|
|
3255
3448
|
CATALOGUE_ROW_SELECT,
|
|
3256
3449
|
catalogueTable,
|
|
3257
3450
|
viewOf,
|
|
@@ -3262,9 +3455,6 @@ export {
|
|
|
3262
3455
|
catalogueDedupeKey,
|
|
3263
3456
|
enqueueCatalogue,
|
|
3264
3457
|
runCatalogue,
|
|
3265
|
-
statusTable,
|
|
3266
|
-
readStatusRows,
|
|
3267
|
-
noteMarketplaceStep,
|
|
3268
3458
|
validatePickupCode,
|
|
3269
3459
|
MARKETPLACE_ACKNOWLEDGE_JOB,
|
|
3270
3460
|
AcknowledgeRetryError,
|
|
@@ -3310,4 +3500,4 @@ export {
|
|
|
3310
3500
|
AvailabilityRetryError,
|
|
3311
3501
|
runAvailability
|
|
3312
3502
|
};
|
|
3313
|
-
//# sourceMappingURL=chunk-
|
|
3503
|
+
//# sourceMappingURL=chunk-MDEIRGNL.js.map
|