Files
WT-Offline/apps/server/src/store/web/checkout.js
T
N0VAN0M4LY 930ea07630 refactor(repo)!: move apps, shared packages, and patch definitions
Everything sat in packages/: two programs next to the small libraries
they use, and the patch data loose at the root. The programs now live in
apps/ and the shared libraries in packages/:

  apps/server        the local server (was packages/local-service),
                     package @wto/server
  packages/patcher   builds the game copy (was packages/build),
                     package @wto/patcher
  patches/exe        exe patch definitions (was exe-patches)
  patches/gui        GUI script patches (was gui-patches)

Inside the server, the network layer folder becomes transport/ so it is
not server/server/, the entry module is server.ts, and startLocalService
and its types become startServer, ServerOptions and RunningServer. The
health answer names the app wto-server, and the TLS files in the data
folder are server.key and server.crt (made again on the next start).
Comments, logs and tool texts say "local server".

The patcher no longer reaches into the server's folder. It read the
default tuning/store.jsonc by a relative path to register bundle GUIDs
for the multi-vehicle packs, which also ignored the player's overrides
in <data>/tuning/. It now takes the pack ids from its caller; the
server exports multiVehiclePackIds(dataFolder), which reads them the way
the running server does. rebuildGuiPack takes the patch folder from its
caller as well.

The development build moves out of the patcher to
scripts/build-game-copy.ts, since it uses both the server and the
patcher. It needs --data (the folder the server will run with) and
defaults the patch folders and the hook library to this repository.


Checked with the root typecheck, check-patches, check-gui,
check-offsets, the native build, a run of build-game-copy.ts into a
scratch folder (12 exe patches, 35 GUI patches, 496 bundle GUIDs as
before) and a server start from apps/server answering wto-server.

BREAKING CHANGE: Use @wto/server and @wto/patcher from the new workspace paths. Run the development build with scripts/build-game-copy.ts and pass --data.
2026-11-29 03:20:54 +08:00

185 lines
7.0 KiB
JavaScript

// 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 };
}