@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,108 @@
|
|
|
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 { FixedPrices, PublicCurrencyAnswer, StoreCurrency } from '../model/commerce-currency';
|
|
18
|
+
/**
|
|
19
|
+
* The conversion model (country map, names, rounding), a chunk of its own:
|
|
20
|
+
* loaded only for a store that sells in more than one currency, so a
|
|
21
|
+
* one-currency store's pages carry none of it (check:plugin-budgets).
|
|
22
|
+
*/
|
|
23
|
+
type CurrencyModel = typeof import('../model/commerce-currency');
|
|
24
|
+
/**
|
|
25
|
+
* The shopper's currency on a storefront (AGL-4248), the way Shopify Markets
|
|
26
|
+
* does it: prices in the visitor's own currency, picked from their country
|
|
27
|
+
* among the currencies the merchant sells in, switchable, and remembered.
|
|
28
|
+
*
|
|
29
|
+
* Tenant pages are ISR-cached (one HTML for everyone), so this resolves on
|
|
30
|
+
* the CLIENT after hydrate: the first render, on the server and in the
|
|
31
|
+
* browser, prints the store currency, and every block re-prices once the
|
|
32
|
+
* store's answer (`commerce/currency`) is in. One fetch per page, shared by
|
|
33
|
+
* every block through a module-level cache; the visitor's country is asked
|
|
34
|
+
* only of a store that sells in more than one currency.
|
|
35
|
+
*/
|
|
36
|
+
/** Blocks re-price when a shopper switches currency anywhere on the page. */
|
|
37
|
+
export declare const SHOPPER_CURRENCY_CHANGED_EVENT = "aglyn:currency-changed";
|
|
38
|
+
/** Where the shopper's own choice is kept, per store. */
|
|
39
|
+
export declare function shopperCurrencyStorageKey(hostId: string): string;
|
|
40
|
+
export declare function readChosenCurrency(hostId: string): string | null;
|
|
41
|
+
/** What a store sells in, plus the visitor's country when it was needed. */
|
|
42
|
+
interface CurrencyLookup {
|
|
43
|
+
answer: PublicCurrencyAnswer | null;
|
|
44
|
+
country: string | null;
|
|
45
|
+
/** Loaded with a store that sells in several currencies; absent otherwise. */
|
|
46
|
+
model?: CurrencyModel;
|
|
47
|
+
}
|
|
48
|
+
/** One lookup per store per page, however many blocks ask. */
|
|
49
|
+
export declare function loadShopperCurrency(hostId: string): Promise<CurrencyLookup>;
|
|
50
|
+
/** Test seam. */
|
|
51
|
+
export declare function resetShopperCurrencyCache(): void;
|
|
52
|
+
/** A variant as the storefront has it: its store price in major units. */
|
|
53
|
+
export interface PricedVariant {
|
|
54
|
+
priceUsd?: number | null;
|
|
55
|
+
fixedPrices?: FixedPrices;
|
|
56
|
+
}
|
|
57
|
+
/** An add-on choice as the storefront has it. */
|
|
58
|
+
export interface PricedAddOn {
|
|
59
|
+
priceCents: number;
|
|
60
|
+
priceCentsByVariant?: Record<string, number>;
|
|
61
|
+
fixedPriceCents?: Record<string, number>;
|
|
62
|
+
}
|
|
63
|
+
export interface ShopperCurrency {
|
|
64
|
+
/** The currency prices print in (upper case). */
|
|
65
|
+
code: string;
|
|
66
|
+
/** The store currency. */
|
|
67
|
+
base: string;
|
|
68
|
+
/** What the store sells in, the store currency first. */
|
|
69
|
+
currencies: StoreCurrency[];
|
|
70
|
+
/** The store's answer is in. Before it, everything prints in the store currency. */
|
|
71
|
+
ready: boolean;
|
|
72
|
+
/** Prices print in another currency than the store's. */
|
|
73
|
+
foreign: boolean;
|
|
74
|
+
setCurrency: (code: string) => void;
|
|
75
|
+
/** A variant's price in the shopper currency, minor units (fixed price wins). */
|
|
76
|
+
variantMinor: (variant: PricedVariant) => number;
|
|
77
|
+
/** A store amount (add-on, fee, delivery) in the shopper currency, minor units. */
|
|
78
|
+
amountMinor: (baseCents: number, fixedMinor?: Record<string, number>) => number;
|
|
79
|
+
/** An add-on's price on a variant in the shopper currency, minor units. */
|
|
80
|
+
addOnMinor: (option: PricedAddOn, variantId?: string | null) => number;
|
|
81
|
+
/** A currency's name ("New Zealand dollar"), once the store's currencies are in. */
|
|
82
|
+
currencyName: (code: string) => string | undefined;
|
|
83
|
+
/** Minor units already in the shopper currency, as money. */
|
|
84
|
+
format: (minor: number) => string;
|
|
85
|
+
/** Minor units in a named currency (a server answer), as money. */
|
|
86
|
+
formatIn: (minor: number, code: string | undefined) => string;
|
|
87
|
+
formatBaseCents: (cents: number) => string;
|
|
88
|
+
formatVariant: (variant: PricedVariant) => string;
|
|
89
|
+
formatAddOn: (option: PricedAddOn, variantId?: string | null) => string;
|
|
90
|
+
}
|
|
91
|
+
/** The pure half: the currency a store's answer and a shopper resolve to. */
|
|
92
|
+
export declare function shopperCurrencyFrom(input: {
|
|
93
|
+
answer: PublicCurrencyAnswer | null;
|
|
94
|
+
country: string | null;
|
|
95
|
+
chosen: string | null;
|
|
96
|
+
model?: CurrencyModel;
|
|
97
|
+
}): {
|
|
98
|
+
code: string;
|
|
99
|
+
base: string;
|
|
100
|
+
currencies: StoreCurrency[];
|
|
101
|
+
entry: StoreCurrency;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* The shopper's currency and its formatters, for any storefront block. Safe
|
|
105
|
+
* on the canvas and in a test with no site: it prints the store currency.
|
|
106
|
+
*/
|
|
107
|
+
export declare function useShopperCurrency(): ShopperCurrency;
|
|
108
|
+
export {};
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import * as Aglyn from "@aglyn/aglyn";
|
|
18
|
+
import { resolveVisitorCountry } from "@aglyn/aglyn/app-utils/visitor-country";
|
|
19
|
+
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
20
|
+
import { formatOrderMoney } from "../model/buyer-notifications.js";
|
|
21
|
+
/**
|
|
22
|
+
* The shopper's currency on a storefront (AGL-4248), the way Shopify Markets
|
|
23
|
+
* does it: prices in the visitor's own currency, picked from their country
|
|
24
|
+
* among the currencies the merchant sells in, switchable, and remembered.
|
|
25
|
+
*
|
|
26
|
+
* Tenant pages are ISR-cached (one HTML for everyone), so this resolves on
|
|
27
|
+
* the CLIENT after hydrate: the first render, on the server and in the
|
|
28
|
+
* browser, prints the store currency, and every block re-prices once the
|
|
29
|
+
* store's answer (`commerce/currency`) is in. One fetch per page, shared by
|
|
30
|
+
* every block through a module-level cache; the visitor's country is asked
|
|
31
|
+
* only of a store that sells in more than one currency.
|
|
32
|
+
*/ /** Blocks re-price when a shopper switches currency anywhere on the page. */ export const SHOPPER_CURRENCY_CHANGED_EVENT = 'aglyn:currency-changed';
|
|
33
|
+
/** Where the shopper's own choice is kept, per store. */ export function shopperCurrencyStorageKey(hostId) {
|
|
34
|
+
return `aglyn.currency.${hostId}`;
|
|
35
|
+
}
|
|
36
|
+
export function readChosenCurrency(hostId) {
|
|
37
|
+
try {
|
|
38
|
+
const value = window.localStorage.getItem(shopperCurrencyStorageKey(hostId));
|
|
39
|
+
return value && /^[A-Z]{3}$/.test(value) ? value : null;
|
|
40
|
+
} catch (unused) {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function writeChosenCurrency(hostId, code) {
|
|
45
|
+
try {
|
|
46
|
+
window.localStorage.setItem(shopperCurrencyStorageKey(hostId), code);
|
|
47
|
+
} catch (unused) {
|
|
48
|
+
// Private-mode storage: the choice lasts this page only.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const lookups = new Map();
|
|
52
|
+
async function lookUpCurrency(hostId) {
|
|
53
|
+
let answer = null;
|
|
54
|
+
try {
|
|
55
|
+
const response = await fetch(`/api/commerce/currency?hostId=${encodeURIComponent(hostId)}`);
|
|
56
|
+
if (response.ok) {
|
|
57
|
+
const payload = await response.json().catch(()=>null);
|
|
58
|
+
if (payload && typeof payload.base === 'string' && Array.isArray(payload.currencies)) {
|
|
59
|
+
answer = payload;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
} catch (unused) {
|
|
63
|
+
// The store currency, as before multi-currency.
|
|
64
|
+
}
|
|
65
|
+
if (!answer || answer.currencies.length < 2) return {
|
|
66
|
+
answer,
|
|
67
|
+
country: null
|
|
68
|
+
};
|
|
69
|
+
// The country is asked only where it can change anything: a store selling
|
|
70
|
+
// in one currency, or one with auto-detect off, never sends the request.
|
|
71
|
+
const [country, model] = await Promise.all([
|
|
72
|
+
answer.autoDetect ? resolveVisitorCountry().catch(()=>null) : null,
|
|
73
|
+
import("../model/commerce-currency.js").catch(()=>undefined)
|
|
74
|
+
]);
|
|
75
|
+
// Without the model nothing can be converted: the store currency it is.
|
|
76
|
+
return model ? {
|
|
77
|
+
answer,
|
|
78
|
+
country,
|
|
79
|
+
model
|
|
80
|
+
} : {
|
|
81
|
+
answer: _extends({}, answer, {
|
|
82
|
+
currencies: answer.currencies.slice(0, 1)
|
|
83
|
+
}),
|
|
84
|
+
country: null
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** One lookup per store per page, however many blocks ask. */ export function loadShopperCurrency(hostId) {
|
|
88
|
+
let pending = lookups.get(hostId);
|
|
89
|
+
if (!pending) {
|
|
90
|
+
pending = lookUpCurrency(hostId);
|
|
91
|
+
lookups.set(hostId, pending);
|
|
92
|
+
// A failed store answer is not pinned: the next page asks again.
|
|
93
|
+
void pending.then((lookup)=>{
|
|
94
|
+
if (!lookup.answer && lookups.get(hostId) === pending) lookups.delete(hostId);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return pending;
|
|
98
|
+
}
|
|
99
|
+
/** Test seam. */ export function resetShopperCurrencyCache() {
|
|
100
|
+
lookups.clear();
|
|
101
|
+
}
|
|
102
|
+
/** The pure half: the currency a store's answer and a shopper resolve to. */ export function shopperCurrencyFrom(input) {
|
|
103
|
+
var _answer_rates;
|
|
104
|
+
const { answer, model } = input;
|
|
105
|
+
if (!answer) {
|
|
106
|
+
return {
|
|
107
|
+
code: 'USD',
|
|
108
|
+
base: 'USD',
|
|
109
|
+
currencies: [],
|
|
110
|
+
entry: {
|
|
111
|
+
code: 'USD',
|
|
112
|
+
rounding: 'none'
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const base = answer.base;
|
|
117
|
+
const currencies = answer.currencies.length ? answer.currencies : [
|
|
118
|
+
{
|
|
119
|
+
code: base,
|
|
120
|
+
rounding: 'none'
|
|
121
|
+
}
|
|
122
|
+
];
|
|
123
|
+
if (!model || currencies.length < 2) {
|
|
124
|
+
return {
|
|
125
|
+
code: base,
|
|
126
|
+
base,
|
|
127
|
+
currencies: currencies.slice(0, 1),
|
|
128
|
+
entry: {
|
|
129
|
+
code: base,
|
|
130
|
+
rounding: 'none'
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const code = model.resolveShopperCurrency({
|
|
135
|
+
settings: {
|
|
136
|
+
enabled: true,
|
|
137
|
+
autoDetect: answer.autoDetect,
|
|
138
|
+
currencies
|
|
139
|
+
},
|
|
140
|
+
base,
|
|
141
|
+
country: input.country,
|
|
142
|
+
chosen: input.chosen
|
|
143
|
+
});
|
|
144
|
+
const entry = currencies.find((item)=>item.code === code);
|
|
145
|
+
// A currency the store cannot price (no daily rate and no rate of the
|
|
146
|
+
// merchant's own) prints in the store currency, as checkout would charge
|
|
147
|
+
// it. Asked through the converter, so it follows however the model rates it.
|
|
148
|
+
if (!entry || code !== base && model.convertMinor(100, base, entry, (_answer_rates = answer.rates) != null ? _answer_rates : undefined) == null) {
|
|
149
|
+
return {
|
|
150
|
+
code: base,
|
|
151
|
+
base,
|
|
152
|
+
currencies,
|
|
153
|
+
entry: {
|
|
154
|
+
code: base,
|
|
155
|
+
rounding: 'none'
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
code,
|
|
161
|
+
base,
|
|
162
|
+
currencies,
|
|
163
|
+
entry
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The shopper's currency and its formatters, for any storefront block. Safe
|
|
168
|
+
* on the canvas and in a test with no site: it prints the store currency.
|
|
169
|
+
*/ export function useShopperCurrency() {
|
|
170
|
+
const { hostId } = Aglyn.useSite();
|
|
171
|
+
const [lookup, setLookup] = useState(null);
|
|
172
|
+
const [chosen, setChosen] = useState(null);
|
|
173
|
+
useEffect(()=>{
|
|
174
|
+
if (!hostId) return;
|
|
175
|
+
let live = true;
|
|
176
|
+
setChosen(readChosenCurrency(hostId));
|
|
177
|
+
void loadShopperCurrency(hostId).then((next)=>{
|
|
178
|
+
if (live) setLookup(next);
|
|
179
|
+
});
|
|
180
|
+
const onChange = ()=>setChosen(readChosenCurrency(hostId));
|
|
181
|
+
window.addEventListener(SHOPPER_CURRENCY_CHANGED_EVENT, onChange);
|
|
182
|
+
return ()=>{
|
|
183
|
+
live = false;
|
|
184
|
+
window.removeEventListener(SHOPPER_CURRENCY_CHANGED_EVENT, onChange);
|
|
185
|
+
};
|
|
186
|
+
}, [
|
|
187
|
+
hostId
|
|
188
|
+
]);
|
|
189
|
+
const setCurrency = useCallback((code)=>{
|
|
190
|
+
if (!hostId) return;
|
|
191
|
+
writeChosenCurrency(hostId, code.toUpperCase());
|
|
192
|
+
setChosen(code.toUpperCase());
|
|
193
|
+
window.dispatchEvent(new Event(SHOPPER_CURRENCY_CHANGED_EVENT));
|
|
194
|
+
}, [
|
|
195
|
+
hostId
|
|
196
|
+
]);
|
|
197
|
+
return useMemo(()=>{
|
|
198
|
+
var _ref, _ref1, _ref2;
|
|
199
|
+
const answer = (_ref = lookup == null ? void 0 : lookup.answer) != null ? _ref : null;
|
|
200
|
+
const ready = Boolean(answer);
|
|
201
|
+
const model = lookup == null ? void 0 : lookup.model;
|
|
202
|
+
const resolved = shopperCurrencyFrom({
|
|
203
|
+
answer,
|
|
204
|
+
country: (_ref1 = lookup == null ? void 0 : lookup.country) != null ? _ref1 : null,
|
|
205
|
+
chosen,
|
|
206
|
+
model
|
|
207
|
+
});
|
|
208
|
+
const { code, base, entry } = resolved;
|
|
209
|
+
const rates = (_ref2 = answer == null ? void 0 : answer.rates) != null ? _ref2 : undefined;
|
|
210
|
+
const foreign = Boolean(model) && ready && code !== base;
|
|
211
|
+
const disambiguate = model ? model.currenciesShareSign(resolved.currencies.map((item)=>item.code)) : false;
|
|
212
|
+
const formatIn = (minor, currency)=>// A one-currency store, and any store before it answers, prints
|
|
213
|
+
// exactly what the page printed before multi-currency.
|
|
214
|
+
model ? model.formatShopperMoney(minor, currency || base, {
|
|
215
|
+
disambiguate
|
|
216
|
+
}) : formatOrderMoney(minor, currency || (ready ? base : 'USD'));
|
|
217
|
+
const variantMinor = (variant)=>{
|
|
218
|
+
var _variant_priceUsd, _ref, _variant_priceUsd1;
|
|
219
|
+
const baseMinor = Math.round(Number((_variant_priceUsd = variant.priceUsd) != null ? _variant_priceUsd : 0) * 100);
|
|
220
|
+
if (!foreign) return baseMinor;
|
|
221
|
+
return (_ref = model == null ? void 0 : model.variantPriceMinor({
|
|
222
|
+
priceUsd: Number((_variant_priceUsd1 = variant.priceUsd) != null ? _variant_priceUsd1 : 0),
|
|
223
|
+
fixedPrices: variant.fixedPrices
|
|
224
|
+
}, base, entry, rates)) != null ? _ref : baseMinor;
|
|
225
|
+
};
|
|
226
|
+
const amountMinor = (baseCents, fixedMinor)=>{
|
|
227
|
+
var _ref;
|
|
228
|
+
return foreign ? (_ref = model == null ? void 0 : model.amountMinorIn(baseCents, base, entry, rates, fixedMinor)) != null ? _ref : baseCents : baseCents;
|
|
229
|
+
};
|
|
230
|
+
const addOnMinor = (option, variantId)=>{
|
|
231
|
+
var _option_priceCentsByVariant;
|
|
232
|
+
const byVariant = variantId ? (_option_priceCentsByVariant = option.priceCentsByVariant) == null ? void 0 : _option_priceCentsByVariant[variantId] : undefined;
|
|
233
|
+
const cents = typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents;
|
|
234
|
+
return amountMinor(cents, option.fixedPriceCents);
|
|
235
|
+
};
|
|
236
|
+
const shown = ready ? code : undefined;
|
|
237
|
+
const format = (minor)=>formatIn(minor, shown);
|
|
238
|
+
return {
|
|
239
|
+
code,
|
|
240
|
+
base,
|
|
241
|
+
currencies: resolved.currencies,
|
|
242
|
+
ready,
|
|
243
|
+
foreign,
|
|
244
|
+
setCurrency,
|
|
245
|
+
currencyName: (currency)=>model == null ? void 0 : model.CURRENCY_NAMES[currency],
|
|
246
|
+
variantMinor,
|
|
247
|
+
amountMinor,
|
|
248
|
+
addOnMinor,
|
|
249
|
+
format,
|
|
250
|
+
formatIn,
|
|
251
|
+
formatBaseCents: (cents)=>format(amountMinor(cents)),
|
|
252
|
+
formatVariant: (variant)=>format(variantMinor(variant)),
|
|
253
|
+
formatAddOn: (option, variantId)=>format(addOnMinor(option, variantId))
|
|
254
|
+
};
|
|
255
|
+
}, [
|
|
256
|
+
lookup,
|
|
257
|
+
chosen,
|
|
258
|
+
setCurrency
|
|
259
|
+
]);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
//# sourceMappingURL=shopper-currency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/shopper-currency.tsx"],"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 * as Aglyn from '@aglyn/aglyn'\nimport { resolveVisitorCountry } from '@aglyn/aglyn/app-utils/visitor-country'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { formatOrderMoney } from '../model/buyer-notifications'\nimport type { FixedPrices, PublicCurrencyAnswer, StoreCurrency } from '../model/commerce-currency'\n\n/**\n * The conversion model (country map, names, rounding), a chunk of its own:\n * loaded only for a store that sells in more than one currency, so a\n * one-currency store's pages carry none of it (check:plugin-budgets).\n */\ntype CurrencyModel = typeof import('../model/commerce-currency')\n\n/**\n * The shopper's currency on a storefront (AGL-4248), the way Shopify Markets\n * does it: prices in the visitor's own currency, picked from their country\n * among the currencies the merchant sells in, switchable, and remembered.\n *\n * Tenant pages are ISR-cached (one HTML for everyone), so this resolves on\n * the CLIENT after hydrate: the first render, on the server and in the\n * browser, prints the store currency, and every block re-prices once the\n * store's answer (`commerce/currency`) is in. One fetch per page, shared by\n * every block through a module-level cache; the visitor's country is asked\n * only of a store that sells in more than one currency.\n */\n\n/** Blocks re-price when a shopper switches currency anywhere on the page. */\nexport const SHOPPER_CURRENCY_CHANGED_EVENT = 'aglyn:currency-changed'\n\n/** Where the shopper's own choice is kept, per store. */\nexport function shopperCurrencyStorageKey(hostId: string): string {\n return `aglyn.currency.${hostId}`\n}\n\nexport function readChosenCurrency(hostId: string): string | null {\n try {\n const value = window.localStorage.getItem(shopperCurrencyStorageKey(hostId))\n return value && /^[A-Z]{3}$/.test(value) ? value : null\n } catch {\n return null\n }\n}\n\nfunction writeChosenCurrency(hostId: string, code: string): void {\n try {\n window.localStorage.setItem(shopperCurrencyStorageKey(hostId), code)\n } catch {\n // Private-mode storage: the choice lasts this page only.\n }\n}\n\n/** What a store sells in, plus the visitor's country when it was needed. */\ninterface CurrencyLookup {\n answer: PublicCurrencyAnswer | null\n country: string | null\n /** Loaded with a store that sells in several currencies; absent otherwise. */\n model?: CurrencyModel\n}\n\nconst lookups = new Map<string, Promise<CurrencyLookup>>()\n\nasync function lookUpCurrency(hostId: string): Promise<CurrencyLookup> {\n let answer: PublicCurrencyAnswer | null = null\n try {\n const response = await fetch(`/api/commerce/currency?hostId=${encodeURIComponent(hostId)}`)\n if (response.ok) {\n const payload = (await response.json().catch(() => null)) as PublicCurrencyAnswer | null\n if (payload && typeof payload.base === 'string' && Array.isArray(payload.currencies)) {\n answer = payload\n }\n }\n } catch {\n // The store currency, as before multi-currency.\n }\n if (!answer || answer.currencies.length < 2) return { answer, country: null }\n // The country is asked only where it can change anything: a store selling\n // in one currency, or one with auto-detect off, never sends the request.\n const [country, model] = await Promise.all([\n answer.autoDetect ? resolveVisitorCountry().catch((): null => null) : null,\n import('../model/commerce-currency').catch((): undefined => undefined),\n ])\n // Without the model nothing can be converted: the store currency it is.\n return model ? { answer, country, model } : { answer: { ...answer, currencies: answer.currencies.slice(0, 1) }, country: null }\n}\n\n/** One lookup per store per page, however many blocks ask. */\nexport function loadShopperCurrency(hostId: string): Promise<CurrencyLookup> {\n let pending = lookups.get(hostId)\n if (!pending) {\n pending = lookUpCurrency(hostId)\n lookups.set(hostId, pending)\n // A failed store answer is not pinned: the next page asks again.\n void pending.then((lookup) => {\n if (!lookup.answer && lookups.get(hostId) === pending) lookups.delete(hostId)\n })\n }\n return pending\n}\n\n/** Test seam. */\nexport function resetShopperCurrencyCache(): void {\n lookups.clear()\n}\n\n/** A variant as the storefront has it: its store price in major units. */\nexport interface PricedVariant {\n priceUsd?: number | null\n fixedPrices?: FixedPrices\n}\n\n/** An add-on choice as the storefront has it. */\nexport interface PricedAddOn {\n priceCents: number\n priceCentsByVariant?: Record<string, number>\n fixedPriceCents?: Record<string, number>\n}\n\nexport interface ShopperCurrency {\n /** The currency prices print in (upper case). */\n code: string\n /** The store currency. */\n base: string\n /** What the store sells in, the store currency first. */\n currencies: StoreCurrency[]\n /** The store's answer is in. Before it, everything prints in the store currency. */\n ready: boolean\n /** Prices print in another currency than the store's. */\n foreign: boolean\n setCurrency: (code: string) => void\n /** A variant's price in the shopper currency, minor units (fixed price wins). */\n variantMinor: (variant: PricedVariant) => number\n /** A store amount (add-on, fee, delivery) in the shopper currency, minor units. */\n amountMinor: (baseCents: number, fixedMinor?: Record<string, number>) => number\n /** An add-on's price on a variant in the shopper currency, minor units. */\n addOnMinor: (option: PricedAddOn, variantId?: string | null) => number\n /** A currency's name (\"New Zealand dollar\"), once the store's currencies are in. */\n currencyName: (code: string) => string | undefined\n /** Minor units already in the shopper currency, as money. */\n format: (minor: number) => string\n /** Minor units in a named currency (a server answer), as money. */\n formatIn: (minor: number, code: string | undefined) => string\n formatBaseCents: (cents: number) => string\n formatVariant: (variant: PricedVariant) => string\n formatAddOn: (option: PricedAddOn, variantId?: string | null) => string\n}\n\n/** The pure half: the currency a store's answer and a shopper resolve to. */\nexport function shopperCurrencyFrom(input: {\n answer: PublicCurrencyAnswer | null\n country: string | null\n chosen: string | null\n model?: CurrencyModel\n}): { code: string; base: string; currencies: StoreCurrency[]; entry: StoreCurrency } {\n const { answer, model } = input\n if (!answer) {\n return { code: 'USD', base: 'USD', currencies: [], entry: { code: 'USD', rounding: 'none' } }\n }\n const base = answer.base\n const currencies = answer.currencies.length\n ? answer.currencies\n : [{ code: base, rounding: 'none' as const }]\n if (!model || currencies.length < 2) {\n return { code: base, base, currencies: currencies.slice(0, 1), entry: { code: base, rounding: 'none' } }\n }\n const code = model.resolveShopperCurrency({\n settings: { enabled: true, autoDetect: answer.autoDetect, currencies },\n base,\n country: input.country,\n chosen: input.chosen,\n })\n const entry = currencies.find((item) => item.code === code)\n // A currency the store cannot price (no daily rate and no rate of the\n // merchant's own) prints in the store currency, as checkout would charge\n // it. Asked through the converter, so it follows however the model rates it.\n if (!entry || (code !== base && model.convertMinor(100, base, entry, answer.rates ?? undefined) == null)) {\n return { code: base, base, currencies, entry: { code: base, rounding: 'none' } }\n }\n return { code, base, currencies, entry }\n}\n\n/**\n * The shopper's currency and its formatters, for any storefront block. Safe\n * on the canvas and in a test with no site: it prints the store currency.\n */\nexport function useShopperCurrency(): ShopperCurrency {\n const { hostId } = Aglyn.useSite()\n const [lookup, setLookup] = useState<CurrencyLookup | null>(null)\n const [chosen, setChosen] = useState<string | null>(null)\n\n useEffect(() => {\n if (!hostId) return\n let live = true\n setChosen(readChosenCurrency(hostId))\n void loadShopperCurrency(hostId).then((next) => {\n if (live) setLookup(next)\n })\n const onChange = () => setChosen(readChosenCurrency(hostId))\n window.addEventListener(SHOPPER_CURRENCY_CHANGED_EVENT, onChange)\n return () => {\n live = false\n window.removeEventListener(SHOPPER_CURRENCY_CHANGED_EVENT, onChange)\n }\n }, [hostId])\n\n const setCurrency = useCallback(\n (code: string) => {\n if (!hostId) return\n writeChosenCurrency(hostId, code.toUpperCase())\n setChosen(code.toUpperCase())\n window.dispatchEvent(new Event(SHOPPER_CURRENCY_CHANGED_EVENT))\n },\n [hostId],\n )\n\n return useMemo(() => {\n const answer = lookup?.answer ?? null\n const ready = Boolean(answer)\n const model = lookup?.model\n const resolved = shopperCurrencyFrom({ answer, country: lookup?.country ?? null, chosen, model })\n const { code, base, entry } = resolved\n const rates = answer?.rates ?? undefined\n const foreign = Boolean(model) && ready && code !== base\n const disambiguate = model\n ? model.currenciesShareSign(resolved.currencies.map((item) => item.code))\n : false\n const formatIn = (minor: number, currency: string | undefined) =>\n // A one-currency store, and any store before it answers, prints\n // exactly what the page printed before multi-currency.\n model\n ? model.formatShopperMoney(minor, currency || base, { disambiguate })\n : formatOrderMoney(minor, currency || (ready ? base : 'USD'))\n const variantMinor = (variant: PricedVariant) => {\n const baseMinor = Math.round(Number(variant.priceUsd ?? 0) * 100)\n if (!foreign) return baseMinor\n return (\n model?.variantPriceMinor(\n { priceUsd: Number(variant.priceUsd ?? 0), fixedPrices: variant.fixedPrices },\n base,\n entry,\n rates,\n ) ?? baseMinor\n )\n }\n const amountMinor = (baseCents: number, fixedMinor?: Record<string, number>) =>\n foreign ? (model?.amountMinorIn(baseCents, base, entry, rates, fixedMinor) ?? baseCents) : baseCents\n const addOnMinor = (option: PricedAddOn, variantId?: string | null) => {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n const cents = typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n return amountMinor(cents, option.fixedPriceCents)\n }\n const shown = ready ? code : undefined\n const format = (minor: number) => formatIn(minor, shown)\n return {\n code,\n base,\n currencies: resolved.currencies,\n ready,\n foreign,\n setCurrency,\n currencyName: (currency: string) => model?.CURRENCY_NAMES[currency],\n variantMinor,\n amountMinor,\n addOnMinor,\n format,\n formatIn,\n formatBaseCents: (cents: number) => format(amountMinor(cents)),\n formatVariant: (variant: PricedVariant) => format(variantMinor(variant)),\n formatAddOn: (option: PricedAddOn, variantId?: string | null) =>\n format(addOnMinor(option, variantId)),\n }\n }, [lookup, chosen, setCurrency])\n}\n"],"names":["Aglyn","resolveVisitorCountry","useCallback","useEffect","useMemo","useState","formatOrderMoney","SHOPPER_CURRENCY_CHANGED_EVENT","shopperCurrencyStorageKey","hostId","readChosenCurrency","value","window","localStorage","getItem","test","writeChosenCurrency","code","setItem","lookups","Map","lookUpCurrency","answer","response","fetch","encodeURIComponent","ok","payload","json","catch","base","Array","isArray","currencies","length","country","model","Promise","all","autoDetect","undefined","slice","loadShopperCurrency","pending","get","set","then","lookup","delete","resetShopperCurrencyCache","clear","shopperCurrencyFrom","input","entry","rounding","resolveShopperCurrency","settings","enabled","chosen","find","item","convertMinor","rates","useShopperCurrency","useSite","setLookup","setChosen","live","next","onChange","addEventListener","removeEventListener","setCurrency","toUpperCase","dispatchEvent","Event","ready","Boolean","resolved","foreign","disambiguate","currenciesShareSign","map","formatIn","minor","currency","formatShopperMoney","variantMinor","variant","baseMinor","Math","round","Number","priceUsd","variantPriceMinor","fixedPrices","amountMinor","baseCents","fixedMinor","amountMinorIn","addOnMinor","option","variantId","byVariant","priceCentsByVariant","cents","isFinite","priceCents","fixedPriceCents","shown","format","currencyName","CURRENCY_NAMES","formatBaseCents","formatVariant","formatAddOn"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SAASC,gBAAgB,QAAQ,kCAA8B;AAU/D;;;;;;;;;;;CAWC,GAED,2EAA2E,GAC3E,OAAO,MAAMC,iCAAiC,yBAAwB;AAEtE,uDAAuD,GACvD,OAAO,SAASC,0BAA0BC,MAAc;IACtD,OAAO,CAAC,eAAe,EAAEA,QAAQ;AACnC;AAEA,OAAO,SAASC,mBAAmBD,MAAc;IAC/C,IAAI;QACF,MAAME,QAAQC,OAAOC,YAAY,CAACC,OAAO,CAACN,0BAA0BC;QACpE,OAAOE,SAAS,aAAaI,IAAI,CAACJ,SAASA,QAAQ;IACrD,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASK,oBAAoBP,MAAc,EAAEQ,IAAY;IACvD,IAAI;QACFL,OAAOC,YAAY,CAACK,OAAO,CAACV,0BAA0BC,SAASQ;IACjE,EAAE,eAAM;IACN,yDAAyD;IAC3D;AACF;AAUA,MAAME,UAAU,IAAIC;AAEpB,eAAeC,eAAeZ,MAAc;IAC1C,IAAIa,SAAsC;IAC1C,IAAI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ACAS;YACAI;YACAU;YACA3B;YACA8B,iBAAiB,CAACR,QAAkBK,OAAOd,YAAYS;YACvDS,eAAe,CAAC1B,UAA2BsB,OAAOvB,aAAaC;YAC/D2B,aAAa,CAACd,QAAqBC,YACjCQ,OAAOV,WAAWC,QAAQC;QAC9B;IACF,GAAG;QAACvD;QAAQW;QAAQc;KAAY;AAClC"}
|
|
@@ -28,6 +28,7 @@ import Typography from "@mui/material/Typography";
|
|
|
28
28
|
import { forwardRef, useCallback, useEffect, useState } from "react";
|
|
29
29
|
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
30
30
|
import { generatePresetId } from "../utils/generate-preset-id.js";
|
|
31
|
+
import { useShopperCurrency } from "./shopper-currency.js";
|
|
31
32
|
// Component ids are persisted in screen documents; never rename.
|
|
32
33
|
export const ID = 'wishlist';
|
|
33
34
|
export const WISHLIST_UPDATED_EVENT = 'aglyn:wishlist-updated';
|
|
@@ -97,6 +98,8 @@ function writeLocalWishlist(hostId, productIds) {
|
|
|
97
98
|
];
|
|
98
99
|
const { hostId } = Aglyn.useSite();
|
|
99
100
|
const siteFetch = Aglyn.useSiteFetch();
|
|
101
|
+
// In the shopper's currency (AGL-4248), like every other price on the store.
|
|
102
|
+
const shopper = useShopperCurrency();
|
|
100
103
|
const [items, setItems] = useState(null);
|
|
101
104
|
const refresh = useCallback(async ()=>{
|
|
102
105
|
if (!hostId) return;
|
|
@@ -224,7 +227,10 @@ function writeLocalWishlist(hostId, productIds) {
|
|
|
224
227
|
/*#__PURE__*/ _jsx(Typography, {
|
|
225
228
|
variant: "caption",
|
|
226
229
|
color: "text.secondary",
|
|
227
|
-
children: item.soldOut ? 'Sold out' : item.priceComingSoon ? 'Price coming soon' :
|
|
230
|
+
children: item.soldOut ? 'Sold out' : item.priceComingSoon ? 'Price coming soon' : shopper.formatVariant({
|
|
231
|
+
priceUsd: item.priceUsd,
|
|
232
|
+
fixedPrices: item.fixedPrices
|
|
233
|
+
})
|
|
228
234
|
})
|
|
229
235
|
]
|
|
230
236
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/wishlist.tsx"],"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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiHeartOutline } from '@aglyn/shared-data-mdi'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useCallback, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'wishlist'\n\nexport const WISHLIST_UPDATED_EVENT = 'aglyn:wishlist-updated'\n\nfunction storageKey(hostId: string): string {\n return `aglyn_wishlist_${hostId}`\n}\n\n/** Guest wishlist ids from localStorage. */\nexport function readLocalWishlist(hostId: string): string[] {\n try {\n const raw = window.localStorage.getItem(storageKey(hostId))\n return raw ? (JSON.parse(raw) as string[]).slice(0, 200) : []\n } catch {\n return []\n }\n}\n\nfunction writeLocalWishlist(hostId: string, productIds: string[]): void {\n try {\n window.localStorage.setItem(\n storageKey(hostId),\n JSON.stringify(productIds.slice(0, 200)),\n )\n } catch {\n // Private-mode storage failures degrade to session-only behavior.\n }\n}\n\n/**\n * Toggles a product on the wishlist (AGL-297): members persist on their\n * doc (guest list merges in on first signed-in call); guests persist in\n * localStorage. Returns whether the product is on the list afterward.\n *\n * Takes its own `fetch` (AGL-1139). This is a plain module function, not a\n * component, so it cannot read the site context that says whether it is\n * running in Preview — and both callers are components that can. Defaulting\n * to the global keeps every other caller unchanged; passing `useSiteFetch()`\n * is what stops a preview click from writing to a real member's wishlist.\n */\nexport async function toggleWishlist(\n hostId: string,\n productId: string,\n siteFetch: typeof fetch = fetch,\n): Promise<boolean> {\n const local = readLocalWishlist(hostId)\n const has = local.includes(productId)\n const next = has\n ? local.filter((id) => id !== productId)\n : [...local, productId]\n writeLocalWishlist(hostId, next)\n // Best-effort member sync — 401 just means guest.\n void siteFetch('/api/membership/wishlist', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n action: has ? 'remove' : 'add',\n productId,\n }),\n }).catch(() => undefined)\n window.dispatchEvent(new Event(WISHLIST_UPDATED_EVENT))\n return !has\n}\n\nexport interface WishlistProps {\n heading?: string\n emptyText?: string\n}\n\ninterface CatalogItem {\n id: string\n name: string\n slug: string\n priceUsd: number\n imageUrl?: string\n soldOut: boolean\n /** Listed before it has a price (AGL-3676). */\n priceComingSoon?: boolean\n}\n\n/**\n * Wishlist block (AGL-297): renders the saved products (member doc when\n * signed in — merging any guest list — else localStorage) as cards\n * linking to their PDPs, with remove buttons.\n */\nconst Wishlist = forwardRef<HTMLDivElement, WishlistProps>((props, ref) => {\n const { heading, emptyText, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [items, setItems] = useState<CatalogItem[] | null>(null)\n\n const refresh = useCallback(async () => {\n if (!hostId) return\n let productIds = readLocalWishlist(hostId)\n try {\n // Merge the guest list into the member doc; response is canonical.\n const response = await siteFetch('/api/membership/wishlist', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, action: 'merge', productIds }),\n })\n if (response.ok) {\n const payload = await response.json()\n productIds = payload?.productIds ?? productIds\n writeLocalWishlist(hostId, productIds)\n }\n } catch {\n // Guest path.\n }\n if (productIds.length === 0) return setItems([])\n try {\n const response = await fetch(\n `/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` +\n `&ids=${encodeURIComponent(productIds.join(','))}&limit=100`,\n )\n const payload = await response.json()\n setItems(payload?.items ?? [])\n } catch {\n setItems([])\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n void refresh()\n const handler = () => void refresh()\n window.addEventListener(WISHLIST_UPDATED_EVENT, handler)\n return () => window.removeEventListener(WISHLIST_UPDATED_EVENT, handler)\n }, [refresh])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n },\n ...nodeSx,\n ]}\n >\n {'Wishlist — saved products render here'}\n </Box>\n )\n }\n\n return (\n <Box ref={ref} {...rest}>\n {heading ? (\n <Typography variant=\"h5\" gutterBottom>\n {heading}\n </Typography>\n ) : null}\n {items && items.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {emptyText || 'Nothing saved yet — tap the heart on any product.'}\n </Typography>\n ) : (\n <Box\n sx={{\n display: 'grid',\n gap: 2,\n gridTemplateColumns: {\n xs: 'repeat(2, 1fr)',\n md: 'repeat(4, 1fr)',\n },\n }}\n >\n {(items ?? []).map((item) => {\n // AGL-1726: resolved BEFORE the guard — see the note in\n // `product-detail.tsx`.\n const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {\n hostId,\n })\n return (\n <Card key={item.id} variant=\"outlined\">\n <CardActionArea href={`/products/${item.slug}`}>\n {imageUrl ? (\n <CardMedia\n component=\"img\"\n image={imageUrl}\n alt={item.name}\n sx={{ height: 120, objectFit: 'cover' }}\n // Deferred (AGL-2486), same reasoning as the product\n // grid: one image per saved item, none of them the lead.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n <Box sx={{ height: 120, bgcolor: 'action.hover' }} />\n )}\n <CardContent sx={{ pb: 1 }}>\n <Typography variant=\"body2\" noWrap>\n {item.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {item.soldOut\n ? 'Sold out'\n : item.priceComingSoon\n ? 'Price coming soon'\n : `$${item.priceUsd}`}\n </Typography>\n </CardContent>\n </CardActionArea>\n <Button\n size=\"small\"\n color=\"error\"\n fullWidth\n onClick={() => void toggleWishlist(hostId, item.id, siteFetch)}\n >\n {'Remove'}\n </Button>\n </Card>\n )\n })}\n </Box>\n )}\n </Box>\n )\n})\nWishlist.displayName = 'AglynWishlist'\n\nexport const schema: Aglyn.ComponentSchema<WishlistProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Wishlist',\n description: 'Products a visitor saved, linking back to their pages.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiHeartOutline.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'heading',\n label: 'Heading',\n description: 'Shown above the saved products.',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n name: 'emptyText',\n label: 'Empty text',\n description: 'Copy when nothing is saved.',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Wishlist',\n pluginId: BUNDLE_ID,\n description: 'Saved products with links back to their pages',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiHeartOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: { heading: 'Your wishlist' },\n },\n },\n]\n\nexport default Wishlist\n"],"names":["Aglyn","mdiHeartOutline","Box","Button","Card","CardActionArea","CardContent","CardMedia","Typography","forwardRef","useCallback","useEffect","useState","BUNDLE_ID","generatePresetId","ID","WISHLIST_UPDATED_EVENT","storageKey","hostId","readLocalWishlist","raw","window","localStorage","getItem","JSON","parse","slice","writeLocalWishlist","productIds","setItem","stringify","toggleWishlist","productId","siteFetch","fetch","local","has","includes","next","filter","id","method","headers","body","action","catch","undefined","dispatchEvent","Event","Wishlist","props","ref","heading","emptyText","rest","nodeSx","Array","isArray","useSite","useSiteFetch","items","setItems","refresh","response","ok","payload","json","length","encodeURIComponent","join","handler","addEventListener","removeEventListener","sx","p","border","borderColor","borderRadius","color","fontSize","fontFamily","variant","gutterBottom","display","gap","gridTemplateColumns","xs","md","map","item","imageUrl","siteRelativeMediaSrc","href","slug","component","image","alt","name","height","objectFit","DEFERRED_IMAGE_ATTRIBUTES","bgcolor","pb","noWrap","soldOut","priceComingSoon","priceUsd","size","fullWidth","onClick","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","label","FieldComponentType","TEXT_FIELD","presets","type","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,eAAe,QAAQ,yBAAwB;AACxD,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,UAAU,EAAEC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AACpE,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,gBAAgB,QAAQ,iCAA6B;AAE9D,iEAAiE;AACjE,OAA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AAK;YACLqB,aAAatH;YACbkG,UAAUpG;YACVqC,OAAO;gBAAEE,SAAS;YAAgB;QACpC;IACF;CACD,CAAA;AAED,eAAeH,SAAQ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/wishlist.tsx"],"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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiHeartOutline } from '@aglyn/shared-data-mdi'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Typography from '@mui/material/Typography'\nimport { forwardRef, useCallback, useEffect, useState } from 'react'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { generatePresetId } from '../utils/generate-preset-id'\nimport { useShopperCurrency } from './shopper-currency'\n\n// Component ids are persisted in screen documents; never rename.\nexport const ID: Aglyn.ComponentId = 'wishlist'\n\nexport const WISHLIST_UPDATED_EVENT = 'aglyn:wishlist-updated'\n\nfunction storageKey(hostId: string): string {\n return `aglyn_wishlist_${hostId}`\n}\n\n/** Guest wishlist ids from localStorage. */\nexport function readLocalWishlist(hostId: string): string[] {\n try {\n const raw = window.localStorage.getItem(storageKey(hostId))\n return raw ? (JSON.parse(raw) as string[]).slice(0, 200) : []\n } catch {\n return []\n }\n}\n\nfunction writeLocalWishlist(hostId: string, productIds: string[]): void {\n try {\n window.localStorage.setItem(\n storageKey(hostId),\n JSON.stringify(productIds.slice(0, 200)),\n )\n } catch {\n // Private-mode storage failures degrade to session-only behavior.\n }\n}\n\n/**\n * Toggles a product on the wishlist (AGL-297): members persist on their\n * doc (guest list merges in on first signed-in call); guests persist in\n * localStorage. Returns whether the product is on the list afterward.\n *\n * Takes its own `fetch` (AGL-1139). This is a plain module function, not a\n * component, so it cannot read the site context that says whether it is\n * running in Preview — and both callers are components that can. Defaulting\n * to the global keeps every other caller unchanged; passing `useSiteFetch()`\n * is what stops a preview click from writing to a real member's wishlist.\n */\nexport async function toggleWishlist(\n hostId: string,\n productId: string,\n siteFetch: typeof fetch = fetch,\n): Promise<boolean> {\n const local = readLocalWishlist(hostId)\n const has = local.includes(productId)\n const next = has\n ? local.filter((id) => id !== productId)\n : [...local, productId]\n writeLocalWishlist(hostId, next)\n // Best-effort member sync — 401 just means guest.\n void siteFetch('/api/membership/wishlist', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n action: has ? 'remove' : 'add',\n productId,\n }),\n }).catch(() => undefined)\n window.dispatchEvent(new Event(WISHLIST_UPDATED_EVENT))\n return !has\n}\n\nexport interface WishlistProps {\n heading?: string\n emptyText?: string\n}\n\ninterface CatalogItem {\n id: string\n name: string\n slug: string\n priceUsd: number\n /** The cheapest variant's own prices per currency (AGL-4248). */\n fixedPrices?: Record<string, number>\n imageUrl?: string\n soldOut: boolean\n /** Listed before it has a price (AGL-3676). */\n priceComingSoon?: boolean\n}\n\n/**\n * Wishlist block (AGL-297): renders the saved products (member doc when\n * signed in — merging any guest list — else localStorage) as cards\n * linking to their PDPs, with remove buttons.\n */\nconst Wishlist = forwardRef<HTMLDivElement, WishlistProps>((props, ref) => {\n const { heading, emptyText, ...rest } = props\n // Node styles ride the renderer-merged sx; recompose (stack.ts pattern).\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n // In the shopper's currency (AGL-4248), like every other price on the store.\n const shopper = useShopperCurrency()\n const [items, setItems] = useState<CatalogItem[] | null>(null)\n\n const refresh = useCallback(async () => {\n if (!hostId) return\n let productIds = readLocalWishlist(hostId)\n try {\n // Merge the guest list into the member doc; response is canonical.\n const response = await siteFetch('/api/membership/wishlist', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, action: 'merge', productIds }),\n })\n if (response.ok) {\n const payload = await response.json()\n productIds = payload?.productIds ?? productIds\n writeLocalWishlist(hostId, productIds)\n }\n } catch {\n // Guest path.\n }\n if (productIds.length === 0) return setItems([])\n try {\n const response = await fetch(\n `/api/commerce/catalog?hostId=${encodeURIComponent(hostId)}` +\n `&ids=${encodeURIComponent(productIds.join(','))}&limit=100`,\n )\n const payload = await response.json()\n setItems(payload?.items ?? [])\n } catch {\n setItems([])\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n void refresh()\n const handler = () => void refresh()\n window.addEventListener(WISHLIST_UPDATED_EVENT, handler)\n return () => window.removeEventListener(WISHLIST_UPDATED_EVENT, handler)\n }, [refresh])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[\n {\n p: 3,\n border: '1px dashed',\n borderColor: 'divider',\n borderRadius: 1,\n color: 'text.secondary',\n fontSize: 13,\n fontFamily: 'system-ui, sans-serif',\n },\n ...nodeSx,\n ]}\n >\n {'Wishlist — saved products render here'}\n </Box>\n )\n }\n\n return (\n <Box ref={ref} {...rest}>\n {heading ? (\n <Typography variant=\"h5\" gutterBottom>\n {heading}\n </Typography>\n ) : null}\n {items && items.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {emptyText || 'Nothing saved yet — tap the heart on any product.'}\n </Typography>\n ) : (\n <Box\n sx={{\n display: 'grid',\n gap: 2,\n gridTemplateColumns: {\n xs: 'repeat(2, 1fr)',\n md: 'repeat(4, 1fr)',\n },\n }}\n >\n {(items ?? []).map((item) => {\n // AGL-1726: resolved BEFORE the guard — see the note in\n // `product-detail.tsx`.\n const imageUrl = Aglyn.siteRelativeMediaSrc(item.imageUrl, {\n hostId,\n })\n return (\n <Card key={item.id} variant=\"outlined\">\n <CardActionArea href={`/products/${item.slug}`}>\n {imageUrl ? (\n <CardMedia\n component=\"img\"\n image={imageUrl}\n alt={item.name}\n sx={{ height: 120, objectFit: 'cover' }}\n // Deferred (AGL-2486), same reasoning as the product\n // grid: one image per saved item, none of them the lead.\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : (\n <Box sx={{ height: 120, bgcolor: 'action.hover' }} />\n )}\n <CardContent sx={{ pb: 1 }}>\n <Typography variant=\"body2\" noWrap>\n {item.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {item.soldOut\n ? 'Sold out'\n : item.priceComingSoon\n ? 'Price coming soon'\n : shopper.formatVariant({ priceUsd: item.priceUsd, fixedPrices: item.fixedPrices })}\n </Typography>\n </CardContent>\n </CardActionArea>\n <Button\n size=\"small\"\n color=\"error\"\n fullWidth\n onClick={() => void toggleWishlist(hostId, item.id, siteFetch)}\n >\n {'Remove'}\n </Button>\n </Card>\n )\n })}\n </Box>\n )}\n </Box>\n )\n})\nWishlist.displayName = 'AglynWishlist'\n\nexport const schema: Aglyn.ComponentSchema<WishlistProps> = {\n $id: ID,\n pluginId: BUNDLE_ID,\n displayName: 'Wishlist',\n description: 'Products a visitor saved, linking back to their pages.',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiHeartOutline.path, sx: { color: '#2e7d32' } },\n flags: { selfClosing: Aglyn.FEATURE_FLAG.ENABLED },\n attributes: [\n {\n name: 'heading',\n label: 'Heading',\n description: 'Shown above the saved products.',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n {\n name: 'emptyText',\n label: 'Empty text',\n description: 'Copy when nothing is saved.',\n component: Aglyn.FieldComponentType.TEXT_FIELD,\n },\n ],\n}\n\nexport const presets: Aglyn.PresetSchema[] = [\n {\n $id: generatePresetId(ID),\n type: Aglyn.NodeType.PRESET,\n displayName: 'Wishlist',\n pluginId: BUNDLE_ID,\n description: 'Saved products with links back to their pages',\n category: Aglyn.ComponentCategory.COMMERCE,\n icon: { path: mdiHeartOutline.path, sx: { color: '#2e7d32' } },\n data: {\n $id: null,\n componentId: ID,\n pluginId: BUNDLE_ID,\n props: { heading: 'Your wishlist' },\n },\n },\n]\n\nexport default Wishlist\n"],"names":["Aglyn","mdiHeartOutline","Box","Button","Card","CardActionArea","CardContent","CardMedia","Typography","forwardRef","useCallback","useEffect","useState","BUNDLE_ID","generatePresetId","useShopperCurrency","ID","WISHLIST_UPDATED_EVENT","storageKey","hostId","readLocalWishlist","raw","window","localStorage","getItem","JSON","parse","slice","writeLocalWishlist","productIds","setItem","stringify","toggleWishlist","productId","siteFetch","fetch","local","has","includes","next","filter","id","method","headers","body","action","catch","undefined","dispatchEvent","Event","Wishlist","props","ref","heading","emptyText","rest","nodeSx","Array","isArray","useSite","useSiteFetch","shopper","items","setItems","refresh","response","ok","payload","json","length","encodeURIComponent","join","handler","addEventListener","removeEventListener","sx","p","border","borderColor","borderRadius","color","fontSize","fontFamily","variant","gutterBottom","display","gap","gridTemplateColumns","xs","md","map","item","imageUrl","siteRelativeMediaSrc","href","slug","component","image","alt","name","height","objectFit","DEFERRED_IMAGE_ATTRIBUTES","bgcolor","pb","noWrap","soldOut","priceComingSoon","formatVariant","priceUsd","fixedPrices","size","fullWidth","onClick","displayName","schema","$id","pluginId","description","category","ComponentCategory","COMMERCE","icon","path","flags","selfClosing","FEATURE_FLAG","ENABLED","attributes","label","FieldComponentType","TEXT_FIELD","presets","type","NodeType","PRESET","data","componentId"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,eAAe,QAAQ,yBAAwB;AACxD,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAA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AM;YACN8B,OAAO;YACPX,aAAa;YACbtB,WAAWhG,MAAMkI,kBAAkB,CAACC,UAAU;QAChD;KACD;AACH,EAAC;AAED,OAAO,MAAMC,UAAgC;IAC3C;QACEhB,KAAKtG,iBAAiBE;QACtBqH,MAAMrI,MAAMsI,QAAQ,CAACC,MAAM;QAC3BrB,aAAa;QACbG,UAAUxG;QACVyG,aAAa;QACbC,UAAUvH,MAAMwH,iBAAiB,CAACC,QAAQ;QAC1CC,MAAM;YAAEC,MAAM1H,gBAAgB0H,IAAI;YAAEhD,IAAI;gBAAEK,OAAO;YAAU;QAAE;QAC7DwD,MAAM;YACJpB,KAAK;YACLqB,aAAazH;YACbqG,UAAUxG;YACVsC,OAAO;gBAAEE,SAAS;YAAgB;QACpC;IACF;CACD,CAAA;AAED,eAAeH,SAAQ"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -22,10 +23,13 @@ import { registerPluginShipmentRecords } from "@aglyn/aglyn/plugin-manager/plugi
|
|
|
22
23
|
import { registerPluginLocalDeliveryRecords } from "@aglyn/aglyn/plugin-manager/plugin-local-deliveries";
|
|
23
24
|
import { registerPluginProductCatalog } from "@aglyn/aglyn/plugin-manager/plugin-product-catalog";
|
|
24
25
|
import { registerPluginSiteSearchSource } from "@aglyn/aglyn/plugin-manager/plugin-site-search";
|
|
26
|
+
import { registerPluginSiteOffer } from "@aglyn/aglyn/plugin-manager/plugin-site-offers";
|
|
25
27
|
import { registerPluginStockLevels } from "@aglyn/aglyn/plugin-manager/plugin-stock-levels";
|
|
26
28
|
import { registerPluginChannelOrders } from "@aglyn/aglyn/plugin-manager/plugin-channel-orders";
|
|
27
29
|
import { registerPluginProductWriter } from "@aglyn/aglyn/plugin-manager/plugin-product-writer";
|
|
30
|
+
import { registerPluginSiteChatTool, registerPluginSiteChatVisitorReader } from "@aglyn/aglyn/plugin-manager/plugin-site-chat-tools";
|
|
28
31
|
import { BUNDLE_ID } from "./constants/bundle-common.js";
|
|
32
|
+
import { COMMERCE_SITE_CHAT_TOOLS } from "./site-chat-tool-definitions.js";
|
|
29
33
|
import { COMMERCE_OPERATOR_ALERTS } from "./constants/operator-alerts.js";
|
|
30
34
|
import { registerCommerceEventTriggers } from "./server/order-event-triggers.js";
|
|
31
35
|
/**
|
|
@@ -89,6 +93,17 @@ import { registerCommerceEventTriggers } from "./server/order-event-triggers.js"
|
|
|
89
93
|
registerPluginSiteSearchSource(lazySiteSearch, {
|
|
90
94
|
pluginId: BUNDLE_ID
|
|
91
95
|
});
|
|
96
|
+
// Its stays (cabins, hookups, tent sites) beside them (AGL-4252), each
|
|
97
|
+
// linked to the page its owner named for it.
|
|
98
|
+
registerPluginSiteSearchSource(lazyStaysSearch, {
|
|
99
|
+
pluginId: BUNDLE_ID
|
|
100
|
+
});
|
|
101
|
+
// A product as another plugin's button sells it (AGL-4252): an events
|
|
102
|
+
// calendar's "Get tickets" puts it in the cart, with the event's day as its
|
|
103
|
+
// use day when the product asks for one.
|
|
104
|
+
registerPluginSiteOffer('product', lazyProductOffer, {
|
|
105
|
+
pluginId: BUNDLE_ID
|
|
106
|
+
});
|
|
92
107
|
// Counts another warehouse keeps, applied as a stock-take (AGL-3634): a
|
|
93
108
|
// fulfillment network says how many it can ship and the products say so.
|
|
94
109
|
registerPluginStockLevels(lazyStockLevels, {
|
|
@@ -104,6 +119,22 @@ import { registerCommerceEventTriggers } from "./server/order-event-triggers.js"
|
|
|
104
119
|
registerPluginChannelOrders(lazyChannelOrders, {
|
|
105
120
|
pluginId: BUNDLE_ID
|
|
106
121
|
});
|
|
122
|
+
// The store's tools for the AI chat on its site (AGL-4250): product
|
|
123
|
+
// details, a stay's dates, and the add-to-cart and reservation cards the
|
|
124
|
+
// visitor confirms; and a signed-in member's first name for its greeting.
|
|
125
|
+
// Definitions only at boot; the reads load with the first call.
|
|
126
|
+
for (const definition of COMMERCE_SITE_CHAT_TOOLS){
|
|
127
|
+
registerPluginSiteChatTool(_extends({}, definition, {
|
|
128
|
+
run: async (request)=>(await import("./server/site-chat-tools.js")).runCommerceSiteChatTool(definition.name, request)
|
|
129
|
+
}), {
|
|
130
|
+
pluginId: BUNDLE_ID
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
registerPluginSiteChatVisitorReader({
|
|
134
|
+
readVisitor: async (request)=>(await import("./server/site-chat-visitor.js")).commerceSiteChatVisitor.readVisitor(request)
|
|
135
|
+
}, {
|
|
136
|
+
pluginId: BUNDLE_ID
|
|
137
|
+
});
|
|
107
138
|
}
|
|
108
139
|
/** Outside orders, with the Admin SDK and the model arriving on the first call. */ const loadChannelOrders = async ()=>(await import("./server/channel-orders.js")).commerceChannelOrders;
|
|
109
140
|
const lazyChannelOrders = {
|
|
@@ -145,5 +176,13 @@ function lazyIndex(name) {
|
|
|
145
176
|
get: async (request)=>(await load()).get(request)
|
|
146
177
|
};
|
|
147
178
|
}
|
|
179
|
+
/** Stays in site search, with the reads arriving on the first search. */ const lazyStaysSearch = {
|
|
180
|
+
key: 'stays',
|
|
181
|
+
label: 'Stays',
|
|
182
|
+
items: async (request)=>(await import("./server/stays-site-search.js")).commerceStaysSiteSearch.items(request)
|
|
183
|
+
};
|
|
184
|
+
/** A product's offer, with the read arriving on the first ask. */ const lazyProductOffer = {
|
|
185
|
+
resolve: async (request)=>(await import("./server/site-offers.js")).commerceProductSiteOffer.resolve(request)
|
|
186
|
+
};
|
|
148
187
|
|
|
149
188
|
//# sourceMappingURL=declarations.server.js.map
|