@revenexx/cover 0.20.0 → 0.21.1
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/app/components/account/approvals/AccountPendingApprovals.vue +54 -13
- package/app/components/account/approvals/AccountPendingOrderDetail.vue +156 -0
- package/app/components/account/orders/AccountOrderContents.vue +142 -0
- package/app/components/account/orders/AccountOrderDetail.vue +16 -178
- package/app/components/account/orders/AccountOrderHead.vue +79 -0
- package/app/components/account/orders/AccountOrderPay.vue +13 -3
- package/app/components/account/orders/AccountOrdersTable.vue +2 -0
- package/app/components/cart/position/CartPosition.vue +6 -6
- package/app/components/checkout/onepage/CheckoutPaymentSection.vue +20 -8
- package/app/components/checkout/return/CheckoutPaymentReturn.vue +209 -0
- package/app/composables/useAccountDashboard.ts +1 -0
- package/app/composables/useCheckoutOnePage.ts +71 -7
- package/app/composables/usePendingApprovals.ts +11 -3
- package/app/composables/usePspCheckout.ts +130 -29
- package/app/config/colorRamp.ts +55 -0
- package/app/interfaces/account/approvals.ts +34 -1
- package/app/interfaces/account/order-list.ts +8 -1
- package/app/interfaces/cart-calculation.ts +7 -1
- package/app/interfaces/cart-item.ts +12 -0
- package/app/interfaces/payment.ts +22 -0
- package/app/pages/checkout/payment-return.vue +17 -0
- package/app/payments/psp/novalnet.ts +254 -0
- package/app/payments/psp/registry.ts +7 -3
- package/app/payments/psp/rules.ts +99 -0
- package/app/payments/psp/stripe.ts +6 -2
- package/app/payments/psp/types.ts +72 -6
- package/app/shared/pspReturn.ts +62 -0
- package/i18n/locales/de/account.json +17 -3
- package/i18n/locales/de/cart.json +4 -2
- package/i18n/locales/de/checkout.json +32 -0
- package/i18n/locales/de/editor.json +10 -0
- package/i18n/locales/en/account.json +17 -3
- package/i18n/locales/en/cart.json +4 -2
- package/i18n/locales/en/checkout.json +32 -0
- package/i18n/locales/en/editor.json +10 -0
- package/package.json +3 -2
- package/server/api/account/orders/[id]/pay.post.ts +47 -7
- package/server/api/account/pending-approvals/index.get.ts +16 -12
- package/server/api/account/pending-approvals/orders/[number]/approve.post.ts +6 -0
- package/server/api/account/pending-approvals/orders/[number]/reject.post.ts +6 -0
- package/server/api/account/pending-approvals/orders/[number].get.ts +15 -0
- package/server/api/checkout/payment-return.post.ts +30 -0
- package/server/api/orders/index.post.ts +37 -11
- package/server/api/payment/methods.post.ts +19 -9
- package/server/api/payment/psp-config.get.ts +5 -4
- package/server/services/ApiCartService.ts +6 -0
- package/server/services/ApiProductService.ts +6 -2
- package/server/services/MockCartCalculationService.ts +29 -0
- package/server/utils/cartItemHints.ts +29 -0
- package/server/utils/checkoutSession.ts +16 -0
- package/server/utils/liveCatalog.ts +244 -31
- package/server/utils/liveOrders.ts +33 -0
- package/server/utils/orderPayment.ts +79 -0
- package/server/utils/pendingApprovals.ts +157 -2
- package/server/utils/procurementCheckout.ts +5 -0
- package/server/utils/pspConfig.ts +125 -13
- package/server/utils/pspReturn.ts +267 -0
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { H3Event } from "h3";
|
|
2
|
-
import type {
|
|
2
|
+
import type { PendingOrderApproval, PendingOrderDetail, PendingRequestApproval } from "../../app/interfaces/account/approvals";
|
|
3
|
+
import type { AuthUser } from "../../app/interfaces/auth";
|
|
4
|
+
|
|
5
|
+
import { buyerHolds } from "./buyerIdentity";
|
|
6
|
+
import { mapLiveOrderToAccount, type LiveOrder } from "./liveOrders";
|
|
3
7
|
|
|
4
8
|
/**
|
|
5
9
|
* The approvals waiting on one person.
|
|
@@ -35,7 +39,7 @@ interface LivePurchaseRequest {
|
|
|
35
39
|
export async function listPendingApprovals(
|
|
36
40
|
event: H3Event,
|
|
37
41
|
actor: { contactId?: string; role?: string; organizationId?: string },
|
|
38
|
-
): Promise<
|
|
42
|
+
): Promise<PendingRequestApproval[]> {
|
|
39
43
|
const sdk = useRevenexxSdk();
|
|
40
44
|
|
|
41
45
|
const queries: Array<{ byRole: boolean; query: Record<string, string | number> }> = [];
|
|
@@ -106,6 +110,7 @@ export async function listPendingApprovals(
|
|
|
106
110
|
const request = row.purchase_request_id ? requests.get(row.purchase_request_id) : undefined;
|
|
107
111
|
const total = request?.total == null ? null : Number(request.total);
|
|
108
112
|
return {
|
|
113
|
+
kind: "request" as const,
|
|
109
114
|
id: row.id,
|
|
110
115
|
requestId: row.purchase_request_id ?? "",
|
|
111
116
|
requestNumber: request?.number ?? null,
|
|
@@ -173,3 +178,153 @@ export async function decidePendingApproval(
|
|
|
173
178
|
throw createError({ statusCode: 502, message: "Procurement service unavailable" });
|
|
174
179
|
}
|
|
175
180
|
}
|
|
181
|
+
|
|
182
|
+
/* ---- orders waiting in the orders app (RAD-229) -------------------------- */
|
|
183
|
+
|
|
184
|
+
interface LivePendingOrderRow {
|
|
185
|
+
id: string;
|
|
186
|
+
number: string;
|
|
187
|
+
contact_id?: string | null;
|
|
188
|
+
organization_id?: string | null;
|
|
189
|
+
grand_total?: number | string | null;
|
|
190
|
+
currency?: string | null;
|
|
191
|
+
created_at?: string | null;
|
|
192
|
+
buyer?: { name?: string | null; email?: string | null } | null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Whether this person decides colleagues' orders here at all. Display only —
|
|
197
|
+
* the orders app holds every read and every decision to the same rule — but a
|
|
198
|
+
* person without the permission must not be shown a queue nothing lets them
|
|
199
|
+
* work. Fails closed: the demo personas state no permissions.
|
|
200
|
+
*/
|
|
201
|
+
function approvesOrders(event: H3Event, user: AuthUser | null): user is AuthUser & { organizationId: string } {
|
|
202
|
+
return resolveOrderServiceKey(event) === "api"
|
|
203
|
+
&& !!user?.organizationId
|
|
204
|
+
&& buyerHolds(user, "orders.approve", false);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The orders of this person's company waiting for somebody to approve them,
|
|
209
|
+
* oldest first, never their own.
|
|
210
|
+
*
|
|
211
|
+
* Read with the buyer's principal: the orders app answers an approver with the
|
|
212
|
+
* orders of their own organization and nobody else's (orders 3.9). An older
|
|
213
|
+
* app answers only their own orders, which are then all filtered out — an
|
|
214
|
+
* empty queue rather than a wrong one.
|
|
215
|
+
*/
|
|
216
|
+
export async function listPendingOrderApprovals(event: H3Event, user: AuthUser | null): Promise<PendingOrderApproval[]> {
|
|
217
|
+
if (!approvesOrders(event, user)) {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
try {
|
|
221
|
+
const { items } = await useRevenexxSdk().orders.ordersList({
|
|
222
|
+
organizationId: user.organizationId,
|
|
223
|
+
status: "pending" as never,
|
|
224
|
+
limit: 100,
|
|
225
|
+
order: "created_at.asc",
|
|
226
|
+
}) as unknown as { items: LivePendingOrderRow[] };
|
|
227
|
+
return items
|
|
228
|
+
.filter(row => row.organization_id === user.organizationId && row.contact_id !== user.contactId)
|
|
229
|
+
.map((row) => {
|
|
230
|
+
const total = row.grand_total == null ? null : Number(row.grand_total);
|
|
231
|
+
return {
|
|
232
|
+
kind: "order" as const,
|
|
233
|
+
id: row.number,
|
|
234
|
+
requestedBy: row.buyer?.name || row.buyer?.email || null,
|
|
235
|
+
total: Number.isFinite(total) ? total : null,
|
|
236
|
+
currency: row.currency ?? null,
|
|
237
|
+
at: row.created_at ?? "",
|
|
238
|
+
};
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
getLogService().error("Pending orders unavailable", apiErrorContext(err));
|
|
243
|
+
return [];
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* One colleague's order, as its approver may see it — or a 404.
|
|
249
|
+
*
|
|
250
|
+
* Addressed by number from the URL, so it is held to the same rule as the
|
|
251
|
+
* queue: this person's company, not their own order. A number from another
|
|
252
|
+
* company answers exactly like one that does not exist.
|
|
253
|
+
*/
|
|
254
|
+
async function approversOrder(event: H3Event): Promise<LiveOrder> {
|
|
255
|
+
const user = await getAuthService(event).me(event);
|
|
256
|
+
if (!user) {
|
|
257
|
+
throw createError({ statusCode: 401, message: "Unauthorized" });
|
|
258
|
+
}
|
|
259
|
+
const number = getRouterParam(event, "number") ?? "";
|
|
260
|
+
if (!approvesOrders(event, user) || !number) {
|
|
261
|
+
throw createError({ statusCode: 404, message: "Order not found" });
|
|
262
|
+
}
|
|
263
|
+
const sdk = useRevenexxSdk();
|
|
264
|
+
const { items } = await sdk.orders.ordersList({ number, organizationId: user.organizationId, limit: 1 }) as unknown as { items: Array<{ id: string }> };
|
|
265
|
+
const order = items[0] ? await sdk.orders.ordersGet({ id: items[0].id }) as unknown as LiveOrder & { organization_id?: string | null } : null;
|
|
266
|
+
if (!order || order.organization_id !== user.organizationId || order.contact_id === user.contactId) {
|
|
267
|
+
throw createError({ statusCode: 404, message: "Order not found" });
|
|
268
|
+
}
|
|
269
|
+
return order;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The approver's read of one colleague's order. */
|
|
273
|
+
export async function readPendingOrder(event: H3Event): Promise<PendingOrderDetail> {
|
|
274
|
+
const order = await approversOrder(event);
|
|
275
|
+
const buyer = (order as LiveOrder & { buyer?: LivePendingOrderRow["buyer"] }).buyer;
|
|
276
|
+
return {
|
|
277
|
+
order: mapLiveOrderToAccount(order),
|
|
278
|
+
requestedBy: buyer?.name || buyer?.email || null,
|
|
279
|
+
pending: order.status === "pending",
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* An approver's yes or no on a colleague's order.
|
|
285
|
+
*
|
|
286
|
+
* The no always carries a reason: it is the one thing the requester learns, and
|
|
287
|
+
* the orders app refuses a rejection without one. Who decided is not sent — the
|
|
288
|
+
* orders app takes it from the principal.
|
|
289
|
+
*/
|
|
290
|
+
export async function decidePendingOrder(event: H3Event, decision: "approve" | "reject"): Promise<{ ok: true }> {
|
|
291
|
+
const body = await readBody<{ reason?: string }>(event).catch(() => ({} as { reason?: string }));
|
|
292
|
+
const reason = body?.reason?.trim() ?? "";
|
|
293
|
+
if (decision === "reject" && !reason) {
|
|
294
|
+
throw createError({ statusCode: 400, message: "A reason is required to reject an order" });
|
|
295
|
+
}
|
|
296
|
+
if (resolveOrderServiceKey(event) !== "api") {
|
|
297
|
+
throw createError({ statusCode: 501, message: "This storefront does not decide orders on demo data" });
|
|
298
|
+
}
|
|
299
|
+
let order: LiveOrder;
|
|
300
|
+
try {
|
|
301
|
+
order = await approversOrder(event);
|
|
302
|
+
}
|
|
303
|
+
catch (err) {
|
|
304
|
+
if (isError(err)) {
|
|
305
|
+
throw err;
|
|
306
|
+
}
|
|
307
|
+
getLogService().error("Order to decide unavailable", apiErrorContext(err));
|
|
308
|
+
throw createError({ statusCode: 502, message: "Order service unavailable" });
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const orders = useRevenexxSdk().orders;
|
|
312
|
+
if (decision === "reject") {
|
|
313
|
+
await orders.ordersReject({ id: order.id, reason });
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
await orders.ordersApprove({ id: order.id });
|
|
317
|
+
}
|
|
318
|
+
return { ok: true };
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
// 422 is the order having been decided since the page was drawn — by a
|
|
322
|
+
// colleague, or in another tab. 403 is the orders app's own rule, which
|
|
323
|
+
// the shop checked the same way and can only meet on a stale grant.
|
|
324
|
+
if (err instanceof RevenexxException && [400, 403, 404, 422].includes(err.code)) {
|
|
325
|
+
throw createError({ statusCode: 422, message: err.message });
|
|
326
|
+
}
|
|
327
|
+
getLogService().error(`Deciding order ${order.number} failed`, apiErrorContext(err));
|
|
328
|
+
throw createError({ statusCode: 502, message: "Order service unavailable" });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
@@ -55,6 +55,8 @@ interface OrderLikePayload {
|
|
|
55
55
|
payment?: { method: string };
|
|
56
56
|
shipping?: { method: string; price: number; tax_rate: number };
|
|
57
57
|
items: Array<Record<string, unknown>>;
|
|
58
|
+
/** The promotions evaluated and reserved for this cart, in the orders app's own shape. */
|
|
59
|
+
discounts?: Array<Record<string, unknown>>;
|
|
58
60
|
userData?: Record<string, unknown>;
|
|
59
61
|
}
|
|
60
62
|
|
|
@@ -82,6 +84,9 @@ export async function submitThroughProcurement(payload: OrderLikePayload): Promi
|
|
|
82
84
|
...(payload.payment ? { payment: payload.payment } : {}),
|
|
83
85
|
...(payload.shipping ? { shipping: payload.shipping } : {}),
|
|
84
86
|
...(payload.userData ? { user_data: payload.userData } : {}),
|
|
87
|
+
// Without them a direct order was placed at the undiscounted price while
|
|
88
|
+
// the promotion's use was committed (procurement forwards them to orders).
|
|
89
|
+
...(payload.discounts?.length ? { discounts: payload.discounts } : {}),
|
|
85
90
|
items: payload.items,
|
|
86
91
|
},
|
|
87
92
|
});
|
|
@@ -1,25 +1,123 @@
|
|
|
1
|
-
|
|
1
|
+
import type { PaymentCheckout } from "../../app/interfaces/payment";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A row of `GET /v1/payments/providers`, as far as the checkout config reads it.
|
|
5
|
+
*
|
|
6
|
+
* RAD-364 serves the checkout's view of a PSP on the row itself —
|
|
7
|
+
* `checkout_mode`, `public_key`, `test_mode` — and the same keys are accepted
|
|
8
|
+
* in `options`, where the merchant keeps non-secret configuration. Stripe's
|
|
9
|
+
* older `options.publishable_key` is still read while tenants move over.
|
|
10
|
+
*/
|
|
2
11
|
export interface PspProviderRow {
|
|
3
12
|
provider: string;
|
|
4
13
|
enabled?: boolean;
|
|
5
14
|
test_mode?: boolean;
|
|
15
|
+
checkout_mode?: string | null;
|
|
16
|
+
public_key?: string | null;
|
|
17
|
+
/** The modes the provider's connector supports (RAD-364); absent from an older payments app. */
|
|
18
|
+
checkout_modes?: string[] | null;
|
|
6
19
|
options?: Record<string, unknown> | null;
|
|
7
20
|
}
|
|
8
21
|
|
|
9
|
-
|
|
22
|
+
/**
|
|
23
|
+
* How a PSP takes the buyer's instrument (FE-5): `embedded` mounts the PSP's
|
|
24
|
+
* own secure field in the checkout, `hosted` sends the buyer to the PSP's page.
|
|
25
|
+
*/
|
|
26
|
+
export type PspCheckoutMode = "embedded" | "hosted";
|
|
27
|
+
|
|
28
|
+
export interface PspPublicProvider {
|
|
29
|
+
checkoutMode: PspCheckoutMode;
|
|
30
|
+
/** The PSP's public key for its field (Stripe publishable key, Novalnet client key). Empty for hosted. */
|
|
31
|
+
publicKey: string;
|
|
32
|
+
/** Legacy name of `publicKey`, kept for themes and code that read it. */
|
|
33
|
+
publishableKey: string;
|
|
34
|
+
testMode: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Whether a field that cannot be used may give way to the hosted page: the
|
|
37
|
+
* provider supports `hosted` (`checkout_modes`), or — from an older payments
|
|
38
|
+
* app that does not say — the merchant chose the mode. False for the legacy
|
|
39
|
+
* Stripe setup and for any embedded-only provider.
|
|
40
|
+
*/
|
|
41
|
+
hostedFallback: boolean;
|
|
42
|
+
/** The modes the provider supports, when the payments app says. */
|
|
43
|
+
checkoutModes?: Array<"embedded" | "hosted">;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type PspPublicConfig = Record<string, PspPublicProvider>;
|
|
10
47
|
|
|
11
48
|
// Stripe's secret and restricted keys. Pasted into the public slot by mistake,
|
|
12
49
|
// either would be handed to every browser that opens the checkout.
|
|
13
50
|
const SECRET_KEY = /^(sk|rk)_/;
|
|
14
51
|
|
|
52
|
+
/** The `checkout` block of an eligible method (`POST /v1/payments/methods/eligible`). */
|
|
53
|
+
export interface ApiMethodCheckout {
|
|
54
|
+
provider?: string | null;
|
|
55
|
+
checkout_mode?: string | null;
|
|
56
|
+
public_key?: string | null;
|
|
57
|
+
test_mode?: boolean | null;
|
|
58
|
+
checkout_modes?: string[] | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The modes a provider supports, as answered; undefined when the payments app does not say. */
|
|
62
|
+
export function checkoutModesOf(raw: unknown): Array<"embedded" | "hosted"> | undefined {
|
|
63
|
+
if (!Array.isArray(raw)) {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
return raw.filter((m): m is "embedded" | "hosted" => m === "embedded" || m === "hosted");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* An eligible method's checkout block, for the browser (RAD-364): the provider,
|
|
71
|
+
* its mode, its public key, its environment — nothing else. No block (a
|
|
72
|
+
* self-managed method) is no checkout. A mode the payments app leaves open is
|
|
73
|
+
* the hosted page, and a key shaped like a secret is never handed on: the
|
|
74
|
+
* method then takes the hosted page, which needs no key.
|
|
75
|
+
*/
|
|
76
|
+
export function paymentCheckoutOf(raw: ApiMethodCheckout | null | undefined): PaymentCheckout | undefined {
|
|
77
|
+
const provider = typeof raw?.provider === "string" ? raw.provider.trim() : "";
|
|
78
|
+
if (!raw || !provider) {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
let publicKey = typeof raw.public_key === "string" ? raw.public_key.trim() : "";
|
|
82
|
+
let checkoutMode: PaymentCheckout["checkoutMode"] = raw.checkout_mode === "embedded" ? "embedded" : "hosted";
|
|
83
|
+
if (publicKey && SECRET_KEY.test(publicKey)) {
|
|
84
|
+
getLogService().error("Secret key answered as public_key — not published", { provider });
|
|
85
|
+
publicKey = "";
|
|
86
|
+
checkoutMode = "hosted";
|
|
87
|
+
}
|
|
88
|
+
const checkoutModes = checkoutModesOf(raw.checkout_modes);
|
|
89
|
+
return { provider, checkoutMode, publicKey, testMode: raw.test_mode !== false, ...(checkoutModes ? { checkoutModes } : {}) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function text(value: unknown): string {
|
|
93
|
+
return typeof value === "string" ? value.trim() : "";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The PSP's public key: the row's own, else the merchant's option, else a legacy name. */
|
|
97
|
+
function publicKeyOf(row: PspProviderRow): { key: string; legacy: boolean } {
|
|
98
|
+
const own = text(row.public_key) || text(row.options?.public_key) || text(row.options?.client_key);
|
|
99
|
+
if (own) {
|
|
100
|
+
return { key: own, legacy: false };
|
|
101
|
+
}
|
|
102
|
+
return { key: text(row.options?.publishable_key), legacy: true };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function declaredModeOf(row: PspProviderRow): PspCheckoutMode | null {
|
|
106
|
+
const mode = text(row.checkout_mode) || text(row.options?.checkout_mode);
|
|
107
|
+
return mode === "embedded" || mode === "hosted" ? mode : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
15
110
|
/**
|
|
16
|
-
* The
|
|
17
|
-
*
|
|
111
|
+
* The checkout's view of the enabled PSPs (RAD-171, FE-5) — how each takes the
|
|
112
|
+
* instrument and the public key its field needs, and nothing else from the row.
|
|
18
113
|
*
|
|
19
|
-
* The payments app never reads `credentials` back, so
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
114
|
+
* The payments app never reads `credentials` back, so a key can only come from
|
|
115
|
+
* the non-secret part of the row. A value shaped like a secret key is dropped
|
|
116
|
+
* rather than published, and the provider is then left out entirely.
|
|
117
|
+
*
|
|
118
|
+
* Without a declared mode a PSP is `hosted`, which works without anything
|
|
119
|
+
* mounted in the shop — except one configured the pre-FE-5 way, with a
|
|
120
|
+
* `publishable_key` only (Stripe), which stays `embedded` as it always was.
|
|
23
121
|
*/
|
|
24
122
|
export function pspPublicConfig(rows: PspProviderRow[]): { providers: PspPublicConfig; refused: string[] } {
|
|
25
123
|
const providers: PspPublicConfig = {};
|
|
@@ -28,15 +126,29 @@ export function pspPublicConfig(rows: PspProviderRow[]): { providers: PspPublicC
|
|
|
28
126
|
if (!row.enabled) {
|
|
29
127
|
continue;
|
|
30
128
|
}
|
|
31
|
-
const key = row
|
|
32
|
-
if (
|
|
129
|
+
const { key, legacy } = publicKeyOf(row);
|
|
130
|
+
if (key && SECRET_KEY.test(key)) {
|
|
131
|
+
refused.push(row.provider);
|
|
33
132
|
continue;
|
|
34
133
|
}
|
|
35
|
-
|
|
36
|
-
|
|
134
|
+
const declared = declaredModeOf(row);
|
|
135
|
+
// Nothing declared and no key: the checkout has nothing to do for this
|
|
136
|
+
// PSP beyond following its redirect, which needs no entry here.
|
|
137
|
+
if (!declared && !key) {
|
|
37
138
|
continue;
|
|
38
139
|
}
|
|
39
|
-
|
|
140
|
+
const checkoutMode: PspCheckoutMode = declared ?? (legacy && key ? "embedded" : "hosted");
|
|
141
|
+
// A declared embedded PSP without a key mounts nothing and falls back to
|
|
142
|
+
// its hosted page — the checkout decides that from the empty key.
|
|
143
|
+
const checkoutModes = checkoutModesOf(row.checkout_modes);
|
|
144
|
+
providers[row.provider] = {
|
|
145
|
+
checkoutMode,
|
|
146
|
+
publicKey: key,
|
|
147
|
+
publishableKey: key,
|
|
148
|
+
testMode: (row.test_mode ?? true) !== false,
|
|
149
|
+
hostedFallback: checkoutModes ? checkoutModes.includes("hosted") : declared !== null,
|
|
150
|
+
...(checkoutModes ? { checkoutModes } : {}),
|
|
151
|
+
};
|
|
40
152
|
}
|
|
41
153
|
return { providers, refused };
|
|
42
154
|
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import type { H3Event } from "h3";
|
|
2
|
+
|
|
3
|
+
import { checkoutSignature, signaturesMatch } from "./checkoutSession";
|
|
4
|
+
import { punchoutLocalePath } from "./punchoutLanding";
|
|
5
|
+
import { PSP_RETURN_ORDER_PARAM, PSP_RETURN_PAYMENT_PARAM, type PspReturnOutcome, pspReturnOutcome } from "../../app/shared/pspReturn";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A buyer the checkout sent to a payment provider comes back to this shop
|
|
9
|
+
* (FE-5), whichever provider it was.
|
|
10
|
+
*
|
|
11
|
+
* The way out: every PSP payment from the checkout carries a return address
|
|
12
|
+
* built HERE, on this request's own host, in the buyer's language —
|
|
13
|
+
* `/<locale>/checkout/payment-return?order=<number>`. The payments app appends
|
|
14
|
+
* `rx_payment=<payment id>`, the provider its own parameters.
|
|
15
|
+
*
|
|
16
|
+
* The way back: the return page posts what it was given to
|
|
17
|
+
* `/api/checkout/payment-return`, which confirms the payment with the payments
|
|
18
|
+
* app — but only a payment of this buyer's order. A guest has no account to
|
|
19
|
+
* prove that with, so the order placement leaves a signed, short-lived cookie
|
|
20
|
+
* naming the payment and the order; a signed-in buyer may instead show the
|
|
21
|
+
* order is theirs (another device, a cleared cookie).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export const PSP_RETURN_COOKIE = "cover-psp-return";
|
|
25
|
+
const PSP_RETURN_TTL_S = 2 * 60 * 60;
|
|
26
|
+
const PURPOSE = "psp-return";
|
|
27
|
+
export const PSP_RETURN_PATH = "/checkout/payment-return";
|
|
28
|
+
|
|
29
|
+
/** What the cookie holds: the payment the browser was sent off for. */
|
|
30
|
+
export interface PspReturnClaim {
|
|
31
|
+
paymentId: string;
|
|
32
|
+
orderRef: string;
|
|
33
|
+
orderUuid?: string | null;
|
|
34
|
+
/** Epoch ms. */
|
|
35
|
+
expiresAt: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function encode(claim: PspReturnClaim): string {
|
|
39
|
+
const payload = Buffer.from(JSON.stringify(claim), "utf8").toString("base64url");
|
|
40
|
+
return `${payload}.${checkoutSignature(PURPOSE, payload)}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The claim a cookie value carries, or null if it is not ours, altered or expired. */
|
|
44
|
+
export function decodePspReturnClaim(value: string | undefined | null, now = Date.now()): PspReturnClaim | null {
|
|
45
|
+
if (!value) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const [payload, signature, ...rest] = value.split(".");
|
|
49
|
+
if (!payload || !signature || rest.length) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
if (!signaturesMatch(signature, checkoutSignature(PURPOSE, payload))) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const claim = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as PspReturnClaim;
|
|
57
|
+
if (typeof claim?.paymentId !== "string" || typeof claim.orderRef !== "string" || !(claim.expiresAt > now)) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return claim;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function encodePspReturnClaim(claim: Omit<PspReturnClaim, "expiresAt">, now = Date.now()): string {
|
|
68
|
+
return encode({ ...claim, expiresAt: now + PSP_RETURN_TTL_S * 1000 });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isHttps(event: H3Event): boolean {
|
|
72
|
+
return getRequestURL(event, { xForwardedProto: true }).protocol === "https:";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Called where the checkout hands the buyer to the provider. */
|
|
76
|
+
export function rememberPspReturn(event: H3Event, claim: Omit<PspReturnClaim, "expiresAt">): void {
|
|
77
|
+
setCookie(event, PSP_RETURN_COOKIE, encodePspReturnClaim(claim), {
|
|
78
|
+
httpOnly: true,
|
|
79
|
+
// Lax: the provider returns the buyer with a top-level GET from its own
|
|
80
|
+
// site, and the return page then calls the BFF same-site.
|
|
81
|
+
sameSite: "lax",
|
|
82
|
+
secure: isHttps(event),
|
|
83
|
+
path: "/",
|
|
84
|
+
maxAge: PSP_RETURN_TTL_S,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function readPspReturnClaim(event: H3Event): PspReturnClaim | null {
|
|
89
|
+
return decodePspReturnClaim(getCookie(event, PSP_RETURN_COOKIE));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function forgetPspReturn(event: H3Event): void {
|
|
93
|
+
deleteCookie(event, PSP_RETURN_COOKIE, { path: "/" });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The absolute return address for an order's PSP payment. The host is this
|
|
98
|
+
* request's own (the edge's forwarded host and scheme, which a browser cannot
|
|
99
|
+
* set), never one a client names; the path is the localized return page.
|
|
100
|
+
*/
|
|
101
|
+
export function pspReturnUrl(event: H3Event, orderRef: string): string {
|
|
102
|
+
const origin = getRequestURL(event, { xForwardedHost: true, xForwardedProto: true }).origin;
|
|
103
|
+
const punchoutConfig = (useRuntimeConfig(event).punchout ?? {}) as { localeStrategy?: string; defaultLocale?: string };
|
|
104
|
+
const path = punchoutLocalePath(
|
|
105
|
+
PSP_RETURN_PATH,
|
|
106
|
+
resolveLocale(event),
|
|
107
|
+
String(punchoutConfig.localeStrategy ?? "no_prefix"),
|
|
108
|
+
String(punchoutConfig.defaultLocale ?? ""),
|
|
109
|
+
);
|
|
110
|
+
const url = new URL(path, origin);
|
|
111
|
+
url.searchParams.set(PSP_RETURN_ORDER_PARAM, orderRef);
|
|
112
|
+
// The payments app refuses a relative return address (422
|
|
113
|
+
// return_url_required, not_absolute). `new URL` against an origin cannot
|
|
114
|
+
// produce one, but a request without a usable host could leave no scheme
|
|
115
|
+
// worth sending a buyer back to — fail here rather than at the provider.
|
|
116
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
117
|
+
throw createError({ statusCode: 500, message: "No absolute return address for this request" });
|
|
118
|
+
}
|
|
119
|
+
return url.toString();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A provider address the buyer may be sent back to: absolute http(s) only. */
|
|
123
|
+
export function pspRetryUrl(nextAction: PspReturnPayment["next_action"]): string | undefined {
|
|
124
|
+
const raw = nextAction?.url;
|
|
125
|
+
if (typeof raw !== "string" || !raw) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const url = new URL(raw);
|
|
130
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.toString() : undefined;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The payment as the payments app describes it, as far as the return reads it. */
|
|
138
|
+
export interface PspReturnPayment {
|
|
139
|
+
id: string;
|
|
140
|
+
status: string;
|
|
141
|
+
order_ref?: string | null;
|
|
142
|
+
order_id?: string | null;
|
|
143
|
+
next_action?: { type?: string; url?: string } | null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Whether this browser may confirm this payment: it must be the payment of the
|
|
148
|
+
* order the return names, and the browser must either hold the claim the
|
|
149
|
+
* checkout left for exactly that payment and order, or be signed in as the
|
|
150
|
+
* buyer whose order it is.
|
|
151
|
+
*/
|
|
152
|
+
export function pspReturnAllowed(input: {
|
|
153
|
+
paymentId: string;
|
|
154
|
+
orderRef: string;
|
|
155
|
+
payment: Pick<PspReturnPayment, "id" | "order_ref"> | null;
|
|
156
|
+
claim: PspReturnClaim | null;
|
|
157
|
+
ownsOrder: boolean;
|
|
158
|
+
}): boolean {
|
|
159
|
+
const { paymentId, orderRef, payment, claim, ownsOrder } = input;
|
|
160
|
+
if (!paymentId || !orderRef || !payment || payment.id !== paymentId || payment.order_ref !== orderRef) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
const claimed = claim !== null && claim.paymentId === paymentId && claim.orderRef === orderRef;
|
|
164
|
+
return claimed || ownsOrder;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Statuses after which a confirm has nothing left to do. */
|
|
168
|
+
const SETTLED = new Set(["authorized", "captured", "succeeded", "paid", "failed", "cancelled", "canceled", "expired", "refunded"]);
|
|
169
|
+
|
|
170
|
+
export interface PspReturnAnswer {
|
|
171
|
+
outcome: PspReturnOutcome;
|
|
172
|
+
/** The order's number, for the confirmation and the "pay again" link. */
|
|
173
|
+
orderId: string;
|
|
174
|
+
/** Whether the buyer can pay the order again from their account. */
|
|
175
|
+
canRetryFromAccount: boolean;
|
|
176
|
+
/** With `retry`: the provider's page, still valid, to pay this same payment. */
|
|
177
|
+
retryUrl?: string;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const notFound = () => createError({ statusCode: 404, message: "Payment not found" });
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* The return route's work: check access, confirm with the payments app,
|
|
184
|
+
* record the outcome on the order, and say what the buyer is told.
|
|
185
|
+
*/
|
|
186
|
+
export async function confirmPspReturn(event: H3Event, input: { order: string; params: Record<string, string> }): Promise<PspReturnAnswer> {
|
|
187
|
+
const orderRef = input.order.trim();
|
|
188
|
+
const paymentId = (input.params[PSP_RETURN_PAYMENT_PARAM] ?? "").trim();
|
|
189
|
+
if (!orderRef || !/^[A-Za-z0-9_-]{1,128}$/.test(paymentId)) {
|
|
190
|
+
throw createError({ statusCode: 400, message: "Return without a payment" });
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Read as the merchant's system: a guest's payment is made out to nobody,
|
|
194
|
+
// and the buyer's own read would hide it. Nothing of it leaves this route
|
|
195
|
+
// before access is settled.
|
|
196
|
+
let payment: PspReturnPayment | null;
|
|
197
|
+
try {
|
|
198
|
+
payment = await useTenantSdk().call<PspReturnPayment>("GET", `/v1/payments/${encodeURIComponent(paymentId)}`);
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
if (err instanceof RevenexxException && err.code === 404) {
|
|
202
|
+
throw notFound();
|
|
203
|
+
}
|
|
204
|
+
getLogService().error("Payment read on return failed", apiErrorContext(err));
|
|
205
|
+
throw createError({ statusCode: 502, message: "Payment service unavailable" });
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const claim = readPspReturnClaim(event);
|
|
209
|
+
const user = await getAuthService(event).me(event);
|
|
210
|
+
const claimed = claim !== null && claim.paymentId === paymentId && claim.orderRef === orderRef;
|
|
211
|
+
// Only asked when the cookie does not settle it — one orders call saved.
|
|
212
|
+
const ownedOrder = !claimed && user?.contactId
|
|
213
|
+
? await getLiveOrderByNumber(orderRef, user.contactId).catch(() => null)
|
|
214
|
+
: null;
|
|
215
|
+
if (!pspReturnAllowed({ paymentId, orderRef, payment, claim, ownsOrder: ownedOrder !== null })) {
|
|
216
|
+
// Somebody else's payment answers exactly like one that does not exist.
|
|
217
|
+
throw notFound();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
let status = payment!.status;
|
|
221
|
+
let nextAction = payment!.next_action ?? null;
|
|
222
|
+
let orderUuid = payment!.order_id ?? ownedOrder?.id ?? (claimed ? claim!.orderUuid : null) ?? null;
|
|
223
|
+
const canRetryFromAccount = Boolean(user);
|
|
224
|
+
// A reload of the return page, or a webhook that was quicker: the payment
|
|
225
|
+
// already says how it ended, and asking again would only ask the provider twice.
|
|
226
|
+
if (!SETTLED.has(status)) {
|
|
227
|
+
try {
|
|
228
|
+
const confirmed = await useRevenexxSdk().call<PspReturnPayment>(
|
|
229
|
+
"POST",
|
|
230
|
+
`/v1/payments/${encodeURIComponent(paymentId)}/confirm`,
|
|
231
|
+
{ body: { return_params: input.params } },
|
|
232
|
+
);
|
|
233
|
+
status = confirmed.status;
|
|
234
|
+
nextAction = confirmed.next_action ?? null;
|
|
235
|
+
orderUuid = confirmed.order_id ?? orderUuid;
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
// The payments app refused what came back — return_checksum_invalid,
|
|
239
|
+
// return_unverified, return_mismatch, amount_mismatch (RAD-364). The
|
|
240
|
+
// payment keeps its status, so nothing is recorded on the order and
|
|
241
|
+
// the claim stays: the buyer is told it could not be verified, never
|
|
242
|
+
// that it was paid, and never that it failed.
|
|
243
|
+
if (err instanceof RevenexxException && [400, 409, 422].includes(err.code)) {
|
|
244
|
+
getLogService().error(`Payment ${paymentId} return not verified`, apiErrorContext(err));
|
|
245
|
+
return { outcome: "unverified", orderId: orderRef, canRetryFromAccount };
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
getLogService().error(`Payment ${paymentId} confirm failed`, apiErrorContext(err));
|
|
249
|
+
throw createError({ statusCode: 502, message: "Payment service unavailable" });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Back from the provider's page without paying (Novalnet: cancelled there,
|
|
255
|
+
// RAD-364): the payment still waits for the buyer, and its page is still
|
|
256
|
+
// valid. That is a second try at the same payment, not "being processed" —
|
|
257
|
+
// and the claim stays, so the next return is confirmed like this one.
|
|
258
|
+
const retryUrl = status === "requires_action" ? pspRetryUrl(nextAction) : undefined;
|
|
259
|
+
const outcome = retryUrl ? "retry" : pspReturnOutcome(status);
|
|
260
|
+
if (orderUuid) {
|
|
261
|
+
await recordOrderPaymentStatus(orderUuid, status);
|
|
262
|
+
}
|
|
263
|
+
if (outcome !== "pending" && outcome !== "retry") {
|
|
264
|
+
forgetPspReturn(event);
|
|
265
|
+
}
|
|
266
|
+
return { outcome, orderId: orderRef, canRetryFromAccount, ...(retryUrl ? { retryUrl } : {}) };
|
|
267
|
+
}
|