// The server tracks the cart per account and settles it with a single request. 'use strict'; function createStoreCheckout(refreshAccount) { const dialog = $('checkout'); const cartButton = $('cartBtn'); let active; let products = new Map(); let accountLoading = true; let processing = false; let directProductId = ''; let complete = false; let opener; const cartIds = () => active?.cartProductIds || []; const locked = () => processing || accountLoading || !active?.activeUserId; const showsAccount = (userId) => active?.activeUserId === userId && $('accountSelect').value === userId; function syncProductButton(button, product) { const adding = button.dataset.cartAction === 'add'; const inCart = adding && cartIds().includes(product.id); const buyLabel = product.owned ? 'owned' : (active?.activeUserId ? 'buy' : 'pickAccount'); button.disabled = locked() || (product.owned && !inCart); button.textContent = t(adding ? (inCart ? 'inCart' : 'addCart') : buyLabel); button.classList.toggle('in-cart', inCart); button.setAttribute('aria-haspopup', !adding || inCart ? 'dialog' : 'false'); } function syncControls() { cartButton.disabled = locked(); $('cartCount').textContent = WtoUi.num(cartIds().length); for (const button of document.querySelectorAll('[data-cart-action]')) { const product = products.get(button.dataset.product); if (product) syncProductButton(button, product); } if (dialog.open) renderCheckout(); } function setState(next) { active = next; products = new Map(next.products.map((product) => [product.id, product])); syncControls(); } function setAccountLoading(value) { accountLoading = value; syncControls(); } function setProcessing(value) { processing = value; syncControls(); } function productButtons(product, layout) { const buy = storeButton(layout === 'detail' ? 'btn-main' : 'card-buy'); const add = storeButton(layout === 'detail' ? 'btn-outline' : 'card-add'); buy.dataset.cartAction = 'buy'; add.dataset.cartAction = 'add'; for (const button of [buy, add]) { button.dataset.product = product.id; syncProductButton(button, product); } buy.onclick = () => open(product.id); add.onclick = () => { if (cartIds().includes(product.id)) open(); else void changeCart(product.id, 'add'); }; return [buy, add]; } function productRow(id) { const product = products.get(id); const row = makeElement('li', 'checkout-item'); const title = product ? WtoUi.text(product.title) : id; const info = makeElement('div', 'checkout-item-copy'); info.append(makeElement('strong', '', title)); if (!product || product.owned) { info.append(makeElement('span', 'checkout-item-status', t(product ? 'owned' : 'unavailable'))); } const amounts = makeElement('div', 'checkout-item-actions'); if (product) amounts.append(makeElement('strong', '', storePrice(product.gjnCostCents))); if (!directProductId) { const remove = storeButton('checkout-remove', t('remove')); remove.disabled = locked(); remove.setAttribute('aria-label', t('removeItem', { name: title })); remove.onclick = () => changeCart(id, 'remove'); amounts.append(remove); } const art = makeElement('div', 'checkout-art'); if (product) art.append(productImage(product)); row.append(art, info, amounts); return row; } function renderCheckout() { const ids = complete ? [] : (directProductId ? [directProductId] : cartIds()); $('checkoutList').replaceChildren(...ids.map(productRow)); $('checkoutTitle').textContent = t(directProductId ? 'confirmPurchase' : 'cart'); $('checkoutClose').disabled = processing; $('checkoutEmpty').hidden = complete || ids.length > 0; $('checkoutDone').hidden = !complete; $('checkoutDone').disabled = processing; $('checkoutTotals').hidden = ids.length === 0; if (!ids.length) return; const items = ids.map((id) => products.get(id)); const total = items.reduce((sum, product) => sum + (product?.gjnCostCents || 0), 0); const balance = active.balance.gjnCents; const unavailable = items.some((product) => !product || product.owned); const hint = unavailable ? t(directProductId ? 'owned' : 'cartBlocked') : (balance < total ? t('lowBalance') : ''); $('checkoutTotal').textContent = storePrice(total); $('checkoutBalance').textContent = storePrice(balance); $('checkoutHint').textContent = hint; $('checkoutHint').hidden = !hint; $('payGjn').disabled = locked() || unavailable || balance < total; $('payFree').disabled = locked() || unavailable; } function open(productId = '') { if (locked()) return; directProductId = productId; complete = false; $('checkoutNotice').className = 'notice'; opener = document.activeElement; renderCheckout(); dialog.showModal(); } function applyCart(result) { if (Array.isArray(result.cartProductIds)) active.cartProductIds = result.cartProductIds; } async function changeCart(productId, action) { if (locked()) return; const userId = active.activeUserId; const notice = dialog.open ? $('checkoutNotice') : $('notice'); setProcessing(true); try { const result = await WtoUi.postJson('/store/api/cart', { userId, productId, action }); if (!showsAccount(userId)) return; applyCart(result); if (result.ok) notice.className = 'notice'; else WtoUi.showNotice(notice, WtoUi.text(result.message) || t('buyFailed'), false); } catch (error) { if (!showsAccount(userId)) return; WtoUi.showNotice(notice, t('buyFailed'), false); await refreshAccount(userId); } finally { setProcessing(false); } } async function pay(payMethod) { if (locked()) return; const userId = active.activeUserId; const body = directProductId ? { productId: directProductId } : { productIds: cartIds().slice() }; const route = directProductId ? 'buy' : 'checkout'; const notice = $('checkoutNotice'); setProcessing(true); try { const result = await WtoUi.postJson('/store/api/' + route, { userId, payMethod, ...body }); if (!showsAccount(userId)) return; applyCart(result); complete = result.ok; WtoUi.showNotice(notice, WtoUi.text(result.message) || t('buyFailed'), result.ok); } catch (error) { WtoUi.showNotice(notice, t('buyFailed'), false); } finally { if (showsAccount(userId)) await refreshAccount(userId); setProcessing(false); if (complete) $('checkoutDone').focus(); } } cartButton.onclick = () => open(); $('checkoutClose').onclick = $('checkoutDone').onclick = () => dialog.close(); $('payGjn').onclick = () => pay('gjn'); $('payFree').onclick = () => pay('free'); dialog.oncancel = (event) => { if (processing) event.preventDefault(); }; dialog.onclose = () => { if (opener?.isConnected && !opener.disabled) opener.focus(); else cartButton.focus(); }; return { productButtons, setState, setAccountLoading }; }