@aglyn/plugins-commerce 1.31.0 → 1.32.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/README.md +4 -0
- package/package.json +13 -13
- package/src/lib/components/cart.js +35 -15
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/console/currencies-card.component.d.ts +21 -0
- package/src/lib/components/console/currencies-card.component.js +408 -0
- package/src/lib/components/console/currencies-card.component.js.map +1 -0
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +42 -1
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
- package/src/lib/components/console/reservations-card.component.js +32 -15
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +100 -1
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +1 -1
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/use-currency-setup.d.ts +20 -0
- package/src/lib/components/console/use-currency-setup.js +61 -0
- package/src/lib/components/console/use-currency-setup.js.map +1 -0
- package/src/lib/components/currency-selector.d.ts +36 -0
- package/src/lib/components/currency-selector.js +157 -0
- package/src/lib/components/currency-selector.js.map +1 -0
- package/src/lib/components/product-add-ons.d.ts +9 -1
- package/src/lib/components/product-add-ons.js +8 -4
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-choice-cards.d.ts +13 -1
- package/src/lib/components/product-choice-cards.js +5 -4
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.d.ts +8 -0
- package/src/lib/components/product-detail.js +38 -11
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +2 -0
- package/src/lib/components/product-grid.js +22 -9
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +6 -2
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/shopper-currency.d.ts +108 -0
- package/src/lib/components/shopper-currency.js +262 -0
- package/src/lib/components/shopper-currency.js.map +1 -0
- package/src/lib/components/wishlist.js +7 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.server.js +39 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/commerce-currency-setup.d.ts +79 -0
- package/src/lib/model/commerce-currency-setup.js +124 -0
- package/src/lib/model/commerce-currency-setup.js.map +1 -0
- package/src/lib/model/commerce-currency.d.ts +215 -0
- package/src/lib/model/commerce-currency.js +511 -0
- package/src/lib/model/commerce-currency.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +17 -0
- package/src/lib/model/commerce-orders.js +10 -5
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-record-routes.js +26 -1
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-reservations.d.ts +6 -0
- package/src/lib/model/commerce-reservations.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +22 -1
- package/src/lib/model/commerce-shipping.js +31 -2
- package/src/lib/model/commerce-shipping.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +2 -0
- package/src/lib/model/index.js +2 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/order-figures.js +9 -2
- package/src/lib/model/order-figures.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/server/billing-webhook.js +37 -24
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +67 -11
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.d.ts +12 -0
- package/src/lib/server/cart.js +50 -4
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.d.ts +5 -0
- package/src/lib/server/catalog.js +7 -0
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout.js +48 -12
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/currency.d.ts +93 -0
- package/src/lib/server/currency.js +182 -0
- package/src/lib/server/currency.js.map +1 -0
- package/src/lib/server/order-notifications.js +4 -2
- package/src/lib/server/order-notifications.js.map +1 -1
- package/src/lib/server/product.d.ts +9 -0
- package/src/lib/server/product.js +12 -0
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/refund.js +3 -3
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/site-chat-tools.d.ts +22 -0
- package/src/lib/server/site-chat-tools.js +369 -0
- package/src/lib/server/site-chat-tools.js.map +1 -0
- package/src/lib/server/site-chat-visitor.d.ts +24 -0
- package/src/lib/server/site-chat-visitor.js +39 -0
- package/src/lib/server/site-chat-visitor.js.map +1 -0
- package/src/lib/server/site-offers.d.ts +31 -0
- package/src/lib/server/site-offers.js +91 -0
- package/src/lib/server/site-offers.js.map +1 -0
- package/src/lib/server/stays-site-search.d.ts +20 -0
- package/src/lib/server/stays-site-search.js +78 -0
- package/src/lib/server/stays-site-search.js.map +1 -0
- package/src/lib/server.js +20 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site-chat-tool-definitions.d.ts +26 -0
- package/src/lib/site-chat-tool-definitions.js +141 -0
- package/src/lib/site-chat-tool-definitions.js.map +1 -0
- package/src/lib/site.js +8 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/subprocessors.js +7 -0
- package/src/lib/subprocessors.js.map +1 -1
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import type { PluginApiHandler } from '@aglyn/aglyn/server';
|
|
18
|
+
import * as CommerceModel from '../model';
|
|
19
|
+
/**
|
|
20
|
+
* Multi-currency on the server (AGL-4248): the daily reference rates, one
|
|
21
|
+
* platform document every store reads, and the shopper-currency context a
|
|
22
|
+
* checkout prices in.
|
|
23
|
+
*/
|
|
24
|
+
/** The ECB's daily reference rates (free, no key), defined beside the parser. */
|
|
25
|
+
export declare const ECB_DAILY_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
|
|
26
|
+
/** The stored rates, cached in memory for ten minutes. */
|
|
27
|
+
export declare function loadFxRates(nowMs?: number): Promise<CommerceModel.FxRates | undefined>;
|
|
28
|
+
/** Test seam. */
|
|
29
|
+
export declare function resetFxRatesCache(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Fetch the ECB file and store it when it is newer than what is stored.
|
|
32
|
+
* Returns what is stored afterwards.
|
|
33
|
+
*/
|
|
34
|
+
export declare function refreshFxRates(fetchImpl?: typeof fetch): Promise<CommerceModel.FxRates | undefined>;
|
|
35
|
+
/** What a store sells in, read once per request from `settings/store`. */
|
|
36
|
+
export interface StoreCurrencyContext {
|
|
37
|
+
base: string;
|
|
38
|
+
settings: CommerceModel.StoreCurrencySettings | undefined;
|
|
39
|
+
rates: CommerceModel.FxRates | undefined;
|
|
40
|
+
}
|
|
41
|
+
export declare function storeCurrencyContextFrom(store: Record<string, unknown> | undefined, rates: CommerceModel.FxRates | undefined): StoreCurrencyContext;
|
|
42
|
+
/**
|
|
43
|
+
* The currency a checkout charges in, from what the storefront asked for:
|
|
44
|
+
* the store currency unless the store sells in the requested one AND fresh
|
|
45
|
+
* rates cover it. Never throws; a stale rate charges the store currency.
|
|
46
|
+
*/
|
|
47
|
+
export interface CheckoutCurrency {
|
|
48
|
+
/** Upper case, as stored on the order. */
|
|
49
|
+
code: string;
|
|
50
|
+
base: string;
|
|
51
|
+
/** The currency's settings (rounding, buffer, tax-inclusive). */
|
|
52
|
+
entry: CommerceModel.StoreCurrency;
|
|
53
|
+
/** Units of `code` per unit of `base`, before any buffer. 1 for the store currency. */
|
|
54
|
+
rate: number;
|
|
55
|
+
rates: CommerceModel.FxRates | undefined;
|
|
56
|
+
/** Whether this checkout charges in another currency than the store's. */
|
|
57
|
+
foreign: boolean;
|
|
58
|
+
}
|
|
59
|
+
export declare function resolveCheckoutCurrency(context: StoreCurrencyContext, requested: unknown, nowMs?: number): CheckoutCurrency;
|
|
60
|
+
/** A store-currency price (major, `priceUsd`) for a variant in the checkout currency, minor units. */
|
|
61
|
+
export declare function checkoutVariantMinor(currency: CheckoutCurrency, variant: {
|
|
62
|
+
priceUsd?: number;
|
|
63
|
+
fixedPrices?: Record<string, number>;
|
|
64
|
+
}): number;
|
|
65
|
+
/** A store-currency amount (minor) for an add-on, fee or shipping in the checkout currency. */
|
|
66
|
+
export declare function checkoutAmountMinor(currency: CheckoutCurrency, baseMinor: number, fixedMinor?: Record<string, number>): number;
|
|
67
|
+
/**
|
|
68
|
+
* One line's unit in the checkout currency: the variant (its fixed price or
|
|
69
|
+
* converted) plus each add-on sold with it (its fixed amount or converted).
|
|
70
|
+
*/
|
|
71
|
+
export declare function checkoutLineMinor(currency: CheckoutCurrency, product: {
|
|
72
|
+
modifierGroups?: unknown;
|
|
73
|
+
}, variant: {
|
|
74
|
+
id?: string;
|
|
75
|
+
priceUsd?: number;
|
|
76
|
+
fixedPrices?: Record<string, number>;
|
|
77
|
+
}, modifiers: readonly {
|
|
78
|
+
groupId?: string;
|
|
79
|
+
optionId?: string;
|
|
80
|
+
priceCents: number;
|
|
81
|
+
}[]): number;
|
|
82
|
+
/** A checkout-currency amount back in the store currency (minor), for the merchant's figures. */
|
|
83
|
+
export declare function toBaseMinor(currency: CheckoutCurrency, minor: number): number;
|
|
84
|
+
/** The Stripe-side code (lower case). */
|
|
85
|
+
export declare function stripeCurrency(currency: CheckoutCurrency): string;
|
|
86
|
+
/**
|
|
87
|
+
* `GET commerce/currency?hostId=` — the public answer a storefront prices
|
|
88
|
+
* from: which currencies the store sells in, its rounding rules, and the
|
|
89
|
+
* day's rates for exactly those. CDN-cached ten minutes: it changes daily.
|
|
90
|
+
* With `setup=1`, the console's setup answer instead: the stored settings
|
|
91
|
+
* and every rate (all public: the ECB publishes them), never cached.
|
|
92
|
+
*/
|
|
93
|
+
export declare const currencyHandler: PluginApiHandler;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import * as CommerceModel from "../model/index.js";
|
|
19
|
+
/**
|
|
20
|
+
* Multi-currency on the server (AGL-4248): the daily reference rates, one
|
|
21
|
+
* platform document every store reads, and the shopper-currency context a
|
|
22
|
+
* checkout prices in.
|
|
23
|
+
*/ /** The ECB's daily reference rates (free, no key), defined beside the parser. */ export const ECB_DAILY_URL = CommerceModel.ECB_DAILY_URL;
|
|
24
|
+
const RATES_DOC = [
|
|
25
|
+
'platform',
|
|
26
|
+
'fxRates'
|
|
27
|
+
];
|
|
28
|
+
let cached;
|
|
29
|
+
const CACHE_MS = 10 * 60 * 1000;
|
|
30
|
+
function ratesRef() {
|
|
31
|
+
return firebaseAdmin.app().firestore().collection(RATES_DOC[0]).doc(RATES_DOC[1]);
|
|
32
|
+
}
|
|
33
|
+
/** The stored rates, cached in memory for ten minutes. */ export async function loadFxRates(nowMs = Date.now()) {
|
|
34
|
+
if (cached && nowMs - cached.atMs < CACHE_MS) return cached.rates;
|
|
35
|
+
try {
|
|
36
|
+
const snap = await ratesRef().get();
|
|
37
|
+
const data = snap.data();
|
|
38
|
+
const rates = (data == null ? void 0 : data.rates) && data.base ? data : undefined;
|
|
39
|
+
cached = {
|
|
40
|
+
rates,
|
|
41
|
+
atMs: nowMs
|
|
42
|
+
};
|
|
43
|
+
return rates;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
console.error('commerce: fx rates read failed', error);
|
|
46
|
+
return cached == null ? void 0 : cached.rates;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Test seam. */ export function resetFxRatesCache() {
|
|
50
|
+
cached = undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Fetch the ECB file and store it when it is newer than what is stored.
|
|
54
|
+
* Returns what is stored afterwards.
|
|
55
|
+
*/ export async function refreshFxRates(fetchImpl = fetch) {
|
|
56
|
+
const response = await fetchImpl(ECB_DAILY_URL, {
|
|
57
|
+
signal: AbortSignal.timeout(10000)
|
|
58
|
+
});
|
|
59
|
+
if (!response.ok) throw new Error(`ECB rates answered ${response.status}`);
|
|
60
|
+
const parsed = CommerceModel.parseEcbDailyXml(await response.text());
|
|
61
|
+
if (!parsed) throw new Error('ECB rates file had no rates');
|
|
62
|
+
const current = await loadFxRates(0);
|
|
63
|
+
if (current && current.asOfMs >= parsed.asOfMs) return current;
|
|
64
|
+
await ratesRef().set(_extends({}, parsed, {
|
|
65
|
+
fetchedAtMs: Date.now()
|
|
66
|
+
}));
|
|
67
|
+
cached = {
|
|
68
|
+
rates: parsed,
|
|
69
|
+
atMs: Date.now()
|
|
70
|
+
};
|
|
71
|
+
return parsed;
|
|
72
|
+
}
|
|
73
|
+
export function storeCurrencyContextFrom(store, rates) {
|
|
74
|
+
return {
|
|
75
|
+
base: CommerceModel.storeBaseCurrency(store),
|
|
76
|
+
settings: store == null ? void 0 : store['currencies'],
|
|
77
|
+
rates
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export function resolveCheckoutCurrency(context, requested, nowMs = Date.now()) {
|
|
81
|
+
const base = context.base;
|
|
82
|
+
const baseEntry = {
|
|
83
|
+
code: base,
|
|
84
|
+
rounding: 'none'
|
|
85
|
+
};
|
|
86
|
+
const entry = CommerceModel.storeSellsIn(context.settings, base, requested);
|
|
87
|
+
const rate = entry ? CommerceModel.currencyRate(context.rates, base, entry) : undefined;
|
|
88
|
+
if (!entry || entry.code === base || rate == null || // A manual rate never goes stale; a daily one does.
|
|
89
|
+
!entry.manualRate && !CommerceModel.ratesAreFresh(context.rates, nowMs)) {
|
|
90
|
+
return {
|
|
91
|
+
code: base,
|
|
92
|
+
base,
|
|
93
|
+
entry: baseEntry,
|
|
94
|
+
rate: 1,
|
|
95
|
+
rates: context.rates,
|
|
96
|
+
foreign: false
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
code: entry.code,
|
|
101
|
+
base,
|
|
102
|
+
entry,
|
|
103
|
+
rate,
|
|
104
|
+
rates: context.rates,
|
|
105
|
+
foreign: true
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** A store-currency price (major, `priceUsd`) for a variant in the checkout currency, minor units. */ export function checkoutVariantMinor(currency, variant) {
|
|
109
|
+
var _variant_priceUsd, _CommerceModel_variantPriceMinor, _variant_priceUsd1;
|
|
110
|
+
if (!currency.foreign) return Math.round(Number((_variant_priceUsd = variant.priceUsd) != null ? _variant_priceUsd : 0) * 100);
|
|
111
|
+
return (_CommerceModel_variantPriceMinor = CommerceModel.variantPriceMinor(variant, currency.base, currency.entry, currency.rates)) != null ? _CommerceModel_variantPriceMinor : Math.round(Number((_variant_priceUsd1 = variant.priceUsd) != null ? _variant_priceUsd1 : 0) * 100);
|
|
112
|
+
}
|
|
113
|
+
/** A store-currency amount (minor) for an add-on, fee or shipping in the checkout currency. */ export function checkoutAmountMinor(currency, baseMinor, fixedMinor) {
|
|
114
|
+
var _CommerceModel_amountMinorIn;
|
|
115
|
+
if (!currency.foreign) return Math.round(baseMinor);
|
|
116
|
+
return (_CommerceModel_amountMinorIn = CommerceModel.amountMinorIn(baseMinor, currency.base, currency.entry, currency.rates, fixedMinor)) != null ? _CommerceModel_amountMinorIn : Math.round(baseMinor);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* One line's unit in the checkout currency: the variant (its fixed price or
|
|
120
|
+
* converted) plus each add-on sold with it (its fixed amount or converted).
|
|
121
|
+
*/ export function checkoutLineMinor(currency, product, variant, modifiers) {
|
|
122
|
+
const groups = CommerceModel.productModifierGroups(product);
|
|
123
|
+
let unit = checkoutVariantMinor(currency, variant);
|
|
124
|
+
for (const modifier of modifiers){
|
|
125
|
+
var _groups_find;
|
|
126
|
+
const option = (_groups_find = groups.find((group)=>group.id === modifier.groupId)) == null ? void 0 : _groups_find.options.find((entry)=>entry.id === modifier.optionId);
|
|
127
|
+
unit += checkoutAmountMinor(currency, modifier.priceCents, option == null ? void 0 : option.fixedPriceCents);
|
|
128
|
+
}
|
|
129
|
+
return unit;
|
|
130
|
+
}
|
|
131
|
+
/** A checkout-currency amount back in the store currency (minor), for the merchant's figures. */ export function toBaseMinor(currency, minor) {
|
|
132
|
+
if (!currency.foreign) return Math.round(minor);
|
|
133
|
+
const factorFrom = CommerceModel.currencyMinorFactor(currency.code);
|
|
134
|
+
const factorTo = CommerceModel.currencyMinorFactor(currency.base);
|
|
135
|
+
return Math.round(minor / factorFrom / currency.rate * factorTo);
|
|
136
|
+
}
|
|
137
|
+
/** The Stripe-side code (lower case). */ export function stripeCurrency(currency) {
|
|
138
|
+
return currency.code.toLowerCase();
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* `GET commerce/currency?hostId=` — the public answer a storefront prices
|
|
142
|
+
* from: which currencies the store sells in, its rounding rules, and the
|
|
143
|
+
* day's rates for exactly those. CDN-cached ten minutes: it changes daily.
|
|
144
|
+
* With `setup=1`, the console's setup answer instead: the stored settings
|
|
145
|
+
* and every rate (all public: the ECB publishes them), never cached.
|
|
146
|
+
*/ export const currencyHandler = async (req, res)=>{
|
|
147
|
+
var _req_query_hostId;
|
|
148
|
+
const hostId = String((_req_query_hostId = req.query.hostId) != null ? _req_query_hostId : '');
|
|
149
|
+
if (!hostId) return res.status(400).json({
|
|
150
|
+
error: 'Missing hostId'
|
|
151
|
+
});
|
|
152
|
+
try {
|
|
153
|
+
var _req_query_setup;
|
|
154
|
+
const [storeSnap, rates] = await Promise.all([
|
|
155
|
+
firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('settings').doc('store').get(),
|
|
156
|
+
loadFxRates()
|
|
157
|
+
]);
|
|
158
|
+
const context = storeCurrencyContextFrom(storeSnap.data(), rates);
|
|
159
|
+
if (String((_req_query_setup = req.query.setup) != null ? _req_query_setup : '') === '1') {
|
|
160
|
+
var _context_settings;
|
|
161
|
+
// The console's Currencies card previews a currency before it is
|
|
162
|
+
// saved, so it reads every rate and the settings as stored, uncached:
|
|
163
|
+
// a change made a moment ago shows at once.
|
|
164
|
+
const setup = {
|
|
165
|
+
base: context.base,
|
|
166
|
+
settings: (_context_settings = context.settings) != null ? _context_settings : null,
|
|
167
|
+
allRates: rates != null ? rates : null
|
|
168
|
+
};
|
|
169
|
+
res.setHeader('Cache-Control', 'private, no-store');
|
|
170
|
+
return res.status(200).json(setup);
|
|
171
|
+
}
|
|
172
|
+
res.setHeader('Cache-Control', 'public, s-maxage=600, stale-while-revalidate=3600');
|
|
173
|
+
return res.status(200).json(CommerceModel.publicCurrencyAnswer(context, Date.now()));
|
|
174
|
+
} catch (error) {
|
|
175
|
+
console.error(error);
|
|
176
|
+
return res.status(500).json({
|
|
177
|
+
error: 'Currencies unavailable'
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
//# sourceMappingURL=currency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/currency.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\n\n/**\n * Multi-currency on the server (AGL-4248): the daily reference rates, one\n * platform document every store reads, and the shopper-currency context a\n * checkout prices in.\n */\n\n/** The ECB's daily reference rates (free, no key), defined beside the parser. */\nexport const ECB_DAILY_URL = CommerceModel.ECB_DAILY_URL\n\nconst RATES_DOC = ['platform', 'fxRates'] as const\n\nlet cached: { rates: CommerceModel.FxRates | undefined; atMs: number } | undefined\nconst CACHE_MS = 10 * 60 * 1000\n\nfunction ratesRef() {\n return firebaseAdmin.app().firestore().collection(RATES_DOC[0]).doc(RATES_DOC[1])\n}\n\n/** The stored rates, cached in memory for ten minutes. */\nexport async function loadFxRates(nowMs = Date.now()): Promise<CommerceModel.FxRates | undefined> {\n if (cached && nowMs - cached.atMs < CACHE_MS) return cached.rates\n try {\n const snap = await ratesRef().get()\n const data = snap.data() as CommerceModel.FxRates | undefined\n const rates = data?.rates && data.base ? data : undefined\n cached = { rates, atMs: nowMs }\n return rates\n } catch (error) {\n console.error('commerce: fx rates read failed', error)\n return cached?.rates\n }\n}\n\n/** Test seam. */\nexport function resetFxRatesCache(): void {\n cached = undefined\n}\n\n/**\n * Fetch the ECB file and store it when it is newer than what is stored.\n * Returns what is stored afterwards.\n */\nexport async function refreshFxRates(\n fetchImpl: typeof fetch = fetch,\n): Promise<CommerceModel.FxRates | undefined> {\n const response = await fetchImpl(ECB_DAILY_URL, { signal: AbortSignal.timeout(10_000) })\n if (!response.ok) throw new Error(`ECB rates answered ${response.status}`)\n const parsed = CommerceModel.parseEcbDailyXml(await response.text())\n if (!parsed) throw new Error('ECB rates file had no rates')\n const current = await loadFxRates(0)\n if (current && current.asOfMs >= parsed.asOfMs) return current\n await ratesRef().set({ ...parsed, fetchedAtMs: Date.now() })\n cached = { rates: parsed, atMs: Date.now() }\n return parsed\n}\n\n/** What a store sells in, read once per request from `settings/store`. */\nexport interface StoreCurrencyContext {\n base: string\n settings: CommerceModel.StoreCurrencySettings | undefined\n rates: CommerceModel.FxRates | undefined\n}\n\nexport function storeCurrencyContextFrom(\n store: Record<string, unknown> | undefined,\n rates: CommerceModel.FxRates | undefined,\n): StoreCurrencyContext {\n return {\n base: CommerceModel.storeBaseCurrency(store as { currency?: unknown }),\n settings: store?.['currencies'] as CommerceModel.StoreCurrencySettings | undefined,\n rates,\n }\n}\n\n/**\n * The currency a checkout charges in, from what the storefront asked for:\n * the store currency unless the store sells in the requested one AND fresh\n * rates cover it. Never throws; a stale rate charges the store currency.\n */\nexport interface CheckoutCurrency {\n /** Upper case, as stored on the order. */\n code: string\n base: string\n /** The currency's settings (rounding, buffer, tax-inclusive). */\n entry: CommerceModel.StoreCurrency\n /** Units of `code` per unit of `base`, before any buffer. 1 for the store currency. */\n rate: number\n rates: CommerceModel.FxRates | undefined\n /** Whether this checkout charges in another currency than the store's. */\n foreign: boolean\n}\n\nexport function resolveCheckoutCurrency(\n context: StoreCurrencyContext,\n requested: unknown,\n nowMs = Date.now(),\n): CheckoutCurrency {\n const base = context.base\n const baseEntry: CommerceModel.StoreCurrency = { code: base, rounding: 'none' }\n const entry = CommerceModel.storeSellsIn(context.settings, base, requested)\n const rate = entry ? CommerceModel.currencyRate(context.rates, base, entry) : undefined\n if (\n !entry ||\n entry.code === base ||\n rate == null ||\n // A manual rate never goes stale; a daily one does.\n (!entry.manualRate && !CommerceModel.ratesAreFresh(context.rates, nowMs))\n ) {\n return { code: base, base, entry: baseEntry, rate: 1, rates: context.rates, foreign: false }\n }\n return { code: entry.code, base, entry, rate, rates: context.rates, foreign: true }\n}\n\n/** A store-currency price (major, `priceUsd`) for a variant in the checkout currency, minor units. */\nexport function checkoutVariantMinor(\n currency: CheckoutCurrency,\n variant: { priceUsd?: number; fixedPrices?: Record<string, number> },\n): number {\n if (!currency.foreign) return Math.round(Number(variant.priceUsd ?? 0) * 100)\n return (\n CommerceModel.variantPriceMinor(variant, currency.base, currency.entry, currency.rates) ??\n Math.round(Number(variant.priceUsd ?? 0) * 100)\n )\n}\n\n/** A store-currency amount (minor) for an add-on, fee or shipping in the checkout currency. */\nexport function checkoutAmountMinor(\n currency: CheckoutCurrency,\n baseMinor: number,\n fixedMinor?: Record<string, number>,\n): number {\n if (!currency.foreign) return Math.round(baseMinor)\n return (\n CommerceModel.amountMinorIn(baseMinor, currency.base, currency.entry, currency.rates, fixedMinor) ??\n Math.round(baseMinor)\n )\n}\n\n/**\n * One line's unit in the checkout currency: the variant (its fixed price or\n * converted) plus each add-on sold with it (its fixed amount or converted).\n */\nexport function checkoutLineMinor(\n currency: CheckoutCurrency,\n product: { modifierGroups?: unknown },\n variant: { id?: string; priceUsd?: number; fixedPrices?: Record<string, number> },\n modifiers: readonly { groupId?: string; optionId?: string; priceCents: number }[],\n): number {\n const groups = CommerceModel.productModifierGroups(product)\n let unit = checkoutVariantMinor(currency, variant)\n for (const modifier of modifiers) {\n const option = groups\n .find((group) => group.id === modifier.groupId)\n ?.options.find((entry) => entry.id === modifier.optionId)\n unit += checkoutAmountMinor(currency, modifier.priceCents, option?.fixedPriceCents)\n }\n return unit\n}\n\n/** A checkout-currency amount back in the store currency (minor), for the merchant's figures. */\nexport function toBaseMinor(currency: CheckoutCurrency, minor: number): number {\n if (!currency.foreign) return Math.round(minor)\n const factorFrom = CommerceModel.currencyMinorFactor(currency.code)\n const factorTo = CommerceModel.currencyMinorFactor(currency.base)\n return Math.round(((minor / factorFrom) / currency.rate) * factorTo)\n}\n\n/** The Stripe-side code (lower case). */\nexport function stripeCurrency(currency: CheckoutCurrency): string {\n return currency.code.toLowerCase()\n}\n\n/**\n * `GET commerce/currency?hostId=` — the public answer a storefront prices\n * from: which currencies the store sells in, its rounding rules, and the\n * day's rates for exactly those. CDN-cached ten minutes: it changes daily.\n * With `setup=1`, the console's setup answer instead: the stored settings\n * and every rate (all public: the ECB publishes them), never cached.\n */\nexport const currencyHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n try {\n const [storeSnap, rates] = await Promise.all([\n firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('settings').doc('store').get(),\n loadFxRates(),\n ])\n const context = storeCurrencyContextFrom(storeSnap.data(), rates)\n if (String(req.query.setup ?? '') === '1') {\n // The console's Currencies card previews a currency before it is\n // saved, so it reads every rate and the settings as stored, uncached:\n // a change made a moment ago shows at once.\n const setup: CommerceModel.CurrencySetupAnswer = {\n base: context.base,\n settings: context.settings ?? null,\n allRates: rates ?? null,\n }\n res.setHeader('Cache-Control', 'private, no-store')\n return res.status(200).json(setup)\n }\n res.setHeader('Cache-Control', 'public, s-maxage=600, stale-while-revalidate=3600')\n return res.status(200).json(CommerceModel.publicCurrencyAnswer(context, Date.now()))\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Currencies unavailable' })\n }\n}\n"],"names":["firebaseAdmin","CommerceModel","ECB_DAILY_URL","RATES_DOC","cached","CACHE_MS","ratesRef","app","firestore","collection","doc","loadFxRates","nowMs","Date","now","atMs","rates","snap","get","data","base","undefined","error","console","resetFxRatesCache","refreshFxRates","fetchImpl","fetch","response","signal","AbortSignal","timeout","ok","Error","status","parsed","parseEcbDailyXml","text","current","asOfMs","set","fetchedAtMs","storeCurrencyContextFrom","store","storeBaseCurrency","settings","resolveCheckoutCurrency","context","requested","baseEntry","code","rounding","entry","storeSellsIn","rate","currencyRate","manualRate","ratesAreFresh","foreign","checkoutVariantMinor","currency","variant","Math","round","Number","priceUsd","variantPriceMinor","checkoutAmountMinor","baseMinor","fixedMinor","amountMinorIn","checkoutLineMinor","product","modifiers","groups","productModifierGroups","unit","modifier","option","find","group","id","groupId","options","optionId","priceCents","fixedPriceCents","toBaseMinor","minor","factorFrom","currencyMinorFactor","factorTo","stripeCurrency","toLowerCase","currencyHandler","req","res","hostId","String","query","json","storeSnap","Promise","all","setup","allRates","setHeader","publicCurrencyAnswer"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2BAA0B;AACxD,YAAYC,mBAAmB,oBAAU;AAEzC;;;;CAIC,GAED,+EAA+E,GAC/E,OAAO,MAAMC,gBAAgBD,cAAcC,aAAa,CAAA;AAExD,MAAMC,YAAY;IAAC;IAAY;CAAU;AAEzC,IAAIC;AACJ,MAAMC,WAAW,KAAK,KAAK;AAE3B,SAASC;IACP,OAAON,cAAcO,GAAG,GAAGC,SAAS,GAAGC,UA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C;YAAE9E,OAAO;QAAyB;IAChE;AACF,EAAC"}
|
|
@@ -474,7 +474,8 @@ function emailOf(value) {
|
|
|
474
474
|
order,
|
|
475
475
|
orderId: ref.orderId,
|
|
476
476
|
businessName: String((_resolveHostToken = resolveHostToken('businessName', store.host)) != null ? _resolveHostToken : ''),
|
|
477
|
-
currency
|
|
477
|
+
// The currency the order was paid in, when not the store's (AGL-4248).
|
|
478
|
+
currency: order.currency ? order.currency.toUpperCase() : store.currency,
|
|
478
479
|
statusUrl: statusLink(store, ref),
|
|
479
480
|
// A sale of card reader hardware states the terms it is sold under (AGL-4038).
|
|
480
481
|
receiptFooter: withPosHardwareReceiptNotice(String((_store_settings_receiptFooter = store.settings['receiptFooter']) != null ? _store_settings_receiptFooter : ''), order),
|
|
@@ -606,7 +607,8 @@ function emailOf(value) {
|
|
|
606
607
|
order,
|
|
607
608
|
orderId: ref.orderId,
|
|
608
609
|
businessName: String((_resolveHostToken = resolveHostToken('businessName', store.host)) != null ? _resolveHostToken : ''),
|
|
609
|
-
currency
|
|
610
|
+
// The currency the order was paid in, when not the store's (AGL-4248).
|
|
611
|
+
currency: order.currency ? order.currency.toUpperCase() : store.currency,
|
|
610
612
|
statusUrl: statusLink(store, ref),
|
|
611
613
|
// A sale of card reader hardware states the terms it is sold under (AGL-4038).
|
|
612
614
|
receiptFooter: withPosHardwareReceiptNotice(String((_store_settings_receiptFooter = store.settings['receiptFooter']) != null ? _store_settings_receiptFooter : ''), order),
|