合入主线登录和营业时段策略,对齐旧界面与 React 访问流程
This commit is contained in:
commit
42395de23a
113 files changed
+1915
-558
No files matched your search
+29
-21
@@ -324,6 +324,8 @@ async function api(url, data, operation, retryContext) {
|
||||
try {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
if (!active()) throw accountChangedError();
|
||||
const started = Date.now();
|
||||
let responseStatus;
|
||||
const controller = new AbortController(),
|
||||
timer = setTimeout(() => controller.abort(), 25000);
|
||||
try {
|
||||
@@ -342,6 +344,7 @@ async function api(url, data, operation, retryContext) {
|
||||
...(write ? { body } : {}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
responseStatus = r.status;
|
||||
// 网关可能返回HTML,先按状态识别,不能让JSON解析失败掩盖502等。
|
||||
if ([408, 502, 503, 504].includes(r.status))
|
||||
throw Object.assign(new Error('服务器暂时没有响应(' + r.status + ')'), {
|
||||
@@ -368,6 +371,10 @@ async function api(url, data, operation, retryContext) {
|
||||
result = null;
|
||||
}
|
||||
if (!r.ok) {
|
||||
if (result?.code === 'BUSINESS_HOURS') {
|
||||
document.documentElement.style.visibility = 'hidden';
|
||||
location.replace('/');
|
||||
}
|
||||
const confirmed = !!result && typeof result.error === 'string';
|
||||
throw Object.assign(
|
||||
new Error(confirmed ? result.error : '请求被拒绝(' + r.status + '),服务器未返回可确认的业务结果。'),
|
||||
@@ -380,7 +387,17 @@ async function api(url, data, operation, retryContext) {
|
||||
if (!active() && err.code !== 'ACCOUNT_CHANGED') throw accountChangedError();
|
||||
const transient =
|
||||
err.retryable || (!err.status && ['TypeError', 'AbortError', 'TimeoutError'].includes(err.name));
|
||||
if (!retry || !transient || attempt >= requestBackoffs.length) throw err;
|
||||
if (!retry || !transient || attempt >= requestBackoffs.length) {
|
||||
if (typeof LoginDiagnostics !== 'undefined' && LoginDiagnostics.steps[url])
|
||||
err.loginDiagnostic = {
|
||||
path: url,
|
||||
method: write ? 'POST' : 'GET',
|
||||
status: responseStatus,
|
||||
timedOut: controller.signal.aborted,
|
||||
elapsed: Date.now() - started,
|
||||
};
|
||||
throw err;
|
||||
}
|
||||
showRequestProgress(
|
||||
token,
|
||||
'连接暂时中断,正在自动' + (write ? '确认' : '重连') + '(' + (attempt + 1) + '/2)…',
|
||||
@@ -487,30 +504,25 @@ async function init() {
|
||||
orderBookDetailList = null;
|
||||
++orderBookRequest;
|
||||
clearTimeout(orderBookTimer);
|
||||
let step = '检查登录状态';
|
||||
try {
|
||||
session = await api('/api/session');
|
||||
if (!session.user) return login();
|
||||
if (!session.user) {
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
$('#login').innerHTML = '';
|
||||
$('#shell').hidden = false;
|
||||
step = '打开账本页面';
|
||||
restoreOrderEditTab();
|
||||
await refresh();
|
||||
showPending();
|
||||
} catch (err) {
|
||||
$('#shell').hidden = true;
|
||||
$('#login').innerHTML =
|
||||
`<div class="login-wrap"><h1>系统暂时没有连接上</h1><p>${e(err.message)}</p><p>请保持启动窗口打开,再刷新页面。</p></div>`;
|
||||
`<div class="login-wrap">${loginErrorHTML(err, step)}${button('重新读取', 'retry-login-load')}</div>`;
|
||||
}
|
||||
}
|
||||
function login() {
|
||||
$('#shell').hidden = true;
|
||||
if (typeof applyShopBrand === 'function') applyShopBrand();
|
||||
const intro =
|
||||
session.mode === 'demo'
|
||||
? '用虚构订单练习完整流程,演示数据与新账隔离。'
|
||||
: '先设置账号。当前是本机试用,正式云端开账另行配置。';
|
||||
const options = session.loginOptions || [];
|
||||
$('#login').innerHTML =
|
||||
`<section class="login-wrap"><div class="brand-mark">${e(Array.from(shopBrandName())[0] || '店')}</div><h1>${e(shopBrandName())} · 新账系统</h1><p class="muted">${session.setup || session.mode === 'demo' ? intro : '录入、收款与复核,从同一张订单开始。'}</p><div id="login-error"></div>${session.mode === 'demo' ? options.map(row => button(e('以' + row.label + '身份进入演示'), 'demo-' + row.member, row.member === 'owner' ? 'primary' : '')).join('') : session.setup ? `<form id="setup-form">${field('店铺名称', 'storeName', '', 'text', 'required maxlength="80"')}${field('店主显示名', 'ownerLabel', '店主', 'text', 'required maxlength="30"')}${field('店主登录名', 'ownerLoginName', 'owner', 'text', 'required maxlength="60"')}${field('店主密码(至少12个字符)', 'ownerPassword', '', 'password', 'required minlength="12" autocomplete="new-password"')}<p class="muted">进入系统后,在设置 → 员工管理中添加员工。</p><button class="primary">建立试用账号</button></form>` : `<form id="login-form"><label>登录账号<select name="member" required autocomplete="username">${opts([['', '请选择账号'], ...options.map(row => [row.member, row.label])], '')}</select></label>${field('密码', 'password', '', 'password', 'required autocomplete="current-password"')}<button class="primary">登录</button></form>`}<p class="small muted" style="margin-top:25px">云端数据库和飞书同步的真实状态,会在系统内显示。</p></section>`;
|
||||
}
|
||||
async function refresh(renderPage = true, stillCurrent) {
|
||||
const latest = await api('/api/state');
|
||||
if (stillCurrent && !stillCurrent()) return;
|
||||
@@ -5782,6 +5794,8 @@ document.addEventListener('click', async ev => {
|
||||
const a = b.dataset.action;
|
||||
if (!a) return;
|
||||
try {
|
||||
if (a === 'retry-login-load') return init();
|
||||
if (a === 'copy-login-diagnostic') return copyLoginDiagnostic(b);
|
||||
if (typeof orderAfterSaleAction === 'function' && a.startsWith('order-after-sale-'))
|
||||
return await orderAfterSaleAction(a, b);
|
||||
if (typeof pocketManagerAction === 'function' && a.startsWith('pocket-manager-'))
|
||||
@@ -5970,7 +5984,7 @@ document.addEventListener('click', async ev => {
|
||||
invalidateInventoryMovementViews(true);
|
||||
if (typeof invalidateInventoryChangeViews === 'function') invalidateInventoryChangeViews();
|
||||
await api('/api/demo-login', { member: a.slice('demo-'.length) });
|
||||
return init();
|
||||
return session.accessWindow !== undefined ? location.reload() : init();
|
||||
}
|
||||
if (a === 'logout') {
|
||||
invalidateInventoryMovementViews(true);
|
||||
@@ -6422,10 +6436,6 @@ document.addEventListener('submit', async ev => {
|
||||
if (form.id === 'order-after-sale-form') return await submitOrderAfterSale(form);
|
||||
if (form.id === 'order-change-form') return await submitOrderChange(form);
|
||||
if (form.id === 'order-cancellation-form') return await submitOrderCancellation(form);
|
||||
if (form.id === 'setup-form' || form.id === 'login-form') {
|
||||
await api(form.id === 'setup-form' ? '/api/setup' : '/api/login', data);
|
||||
return init();
|
||||
}
|
||||
if (form.id === 'material-purchase-form') return await submitMaterialPurchase(form);
|
||||
if (form.id === 'material-purchase-edit-form' || form.id === 'material-purchase-delete-form')
|
||||
return await submitMaterialPurchaseChange(form);
|
||||
@@ -6653,8 +6663,6 @@ document.addEventListener('submit', async ev => {
|
||||
$('#after-sale-error').innerHTML = `<div class="error">${e(err.message)}</div>`;
|
||||
else if (form.id === 'print-settings' && $('#print-settings-error'))
|
||||
$('#print-settings-error').innerHTML = `<div class="error">${e(err.message)}</div>`;
|
||||
else if (form.id.endsWith('login-form') || form.id === 'setup-form')
|
||||
$('#login-error').innerHTML = `<div class="error">${e(err.message)}</div>`;
|
||||
else if (form.id === 'order-form') $('#order-error').innerHTML = `<div class="error">${e(err.message)}</div>`;
|
||||
else if (form.id === 'stock-form' && $('#stock-error'))
|
||||
$('#stock-error').innerHTML = `<div class="error">${e(err.message)}</div>`;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
'use strict';
|
||||
(() => {
|
||||
const remaining = Number(document.currentScript.dataset.remaining);
|
||||
if (!Number.isFinite(remaining)) return;
|
||||
let deadline = 0,
|
||||
closeTimer,
|
||||
warningTimer,
|
||||
leaving = false;
|
||||
function leave() {
|
||||
if (leaving) return;
|
||||
leaving = true;
|
||||
document.documentElement.style.visibility = 'hidden';
|
||||
location.replace(location.pathname.startsWith('/next/') ? '/next/' : '/');
|
||||
}
|
||||
function warn() {
|
||||
if (document.getElementById('closing-warning')) return;
|
||||
const node = document.createElement('div');
|
||||
node.id = 'closing-warning';
|
||||
node.className = 'notice';
|
||||
node.setAttribute('role', 'status');
|
||||
node.textContent = '距离停止访问不足 5 分钟,请及时保存。';
|
||||
document.body.prepend(node);
|
||||
}
|
||||
function schedule(ms) {
|
||||
clearTimeout(closeTimer);
|
||||
clearTimeout(warningTimer);
|
||||
deadline = Date.now() + ms;
|
||||
if (ms <= 0) return leave();
|
||||
closeTimer = setTimeout(leave, ms);
|
||||
if (ms > 300000) document.getElementById('closing-warning')?.remove();
|
||||
warningTimer = setTimeout(warn, Math.max(0, ms - 300000));
|
||||
}
|
||||
let checking = false;
|
||||
async function check() {
|
||||
if (Date.now() >= deadline) return leave();
|
||||
if (checking || document.hidden || leaving) return;
|
||||
checking = true;
|
||||
const start = performance.now();
|
||||
try {
|
||||
const res = await fetch('/api/access-window', { cache: 'no-store' });
|
||||
if (res.status === 401 || res.status === 403) return leave();
|
||||
if (!res.ok) return;
|
||||
const { window: period } = await res.json();
|
||||
if (period?.state !== 'open') return leave();
|
||||
schedule(period.closesAt - period.serverTime - (performance.now() - start));
|
||||
} catch {
|
||||
// 离线时继续执行上次服务端给出的截止时间,下一次轮询再核对。
|
||||
} finally {
|
||||
checking = false;
|
||||
}
|
||||
}
|
||||
schedule(remaining - performance.now());
|
||||
window.addEventListener('focus', check);
|
||||
window.addEventListener('pageshow', event => {
|
||||
if (event.persisted) check();
|
||||
});
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!document.hidden) check();
|
||||
});
|
||||
window.addEventListener('ledger-business-hours-changed', check);
|
||||
setInterval(check, 30000);
|
||||
})();
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>珠宝台账 · 新账系统</title><link rel="stylesheet" href="/app.css"><script src="/calculations.js" defer></script><script src="/ledger-values.js" defer></script><script src="/report-rules.js" defer></script><script src="/recovery-rules.js" defer></script><script src="/order-formula.js" defer></script><script src="/fee-estimates.js" defer></script><script src="/order-cost-presets-ui.js" defer></script><script src="/credit-card-fees.js" defer></script><script src="/order-copy.js" defer></script><script src="/order-templates.js" defer></script><script src="/order-templates-ui.js" defer></script><script src="/price-locks-ui.js" defer></script><script src="/price-lock-changes-ui.js" defer></script><script src="/material-pools-ui.js" defer></script><script src="/order-edit-ui.js" defer></script><script src="/order-cancellations-ui.js" defer></script><script src="/order-changes-ui.js" defer></script><script src="/order-after-sales-ui.js" defer></script><script src="/order-ownership-ui.js" defer></script><script src="/daily-funds-ui.js" defer></script><script src="/cost-funding-ui.js" defer></script><script src="/team-funds-ui.js" defer></script><script src="/inventory-changes-ui.js" defer></script><script src="/recoveries-ui.js" defer></script><script src="/recovery-changes-ui.js" defer></script><script src="/pockets-ui.js" defer></script><script src="/shop-settings-ui.js" defer></script><script src="/employees-ui.js" defer></script><script src="/private-operations-ui.js" defer></script><script src="/app.js" defer></script></head>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>珠宝台账 · 新账系统</title><link rel="stylesheet" href="/app.css"><script src="/calculations.js" defer></script><script src="/ledger-values.js" defer></script><script src="/report-rules.js" defer></script><script src="/recovery-rules.js" defer></script><script src="/order-formula.js" defer></script><script src="/fee-estimates.js" defer></script><script src="/order-cost-presets-ui.js" defer></script><script src="/credit-card-fees.js" defer></script><script src="/order-copy.js" defer></script><script src="/order-templates.js" defer></script><script src="/order-templates-ui.js" defer></script><script src="/price-locks-ui.js" defer></script><script src="/price-lock-changes-ui.js" defer></script><script src="/material-pools-ui.js" defer></script><script src="/order-edit-ui.js" defer></script><script src="/order-cancellations-ui.js" defer></script><script src="/order-changes-ui.js" defer></script><script src="/order-after-sales-ui.js" defer></script><script src="/order-ownership-ui.js" defer></script><script src="/daily-funds-ui.js" defer></script><script src="/cost-funding-ui.js" defer></script><script src="/team-funds-ui.js" defer></script><script src="/inventory-changes-ui.js" defer></script><script src="/recoveries-ui.js" defer></script><script src="/recovery-changes-ui.js" defer></script><script src="/pockets-ui.js" defer></script><script src="/shop-settings-ui.js" defer></script><script src="/employees-ui.js" defer></script><script src="/private-operations-ui.js" defer></script><script src="/login-diagnostics.js" defer></script><script src="/login-ui.js" defer></script><script src="/app.js" defer></script></head>
|
||||
<body><div id="toast" role="status" hidden></div><div id="login"></div><div id="shell" hidden>
|
||||
<header class="app-header"><div class="brand"><span class="brand-mark" data-shop-mark>店</span><div><strong data-shop-name>珠宝台账</strong><small>开单 · 库存 · 订单利润</small></div></div><div class="header-right"><span id="mode" class="badge"></span><span id="identity"></span><button class="quiet" data-action="logout">退出</button></div></header>
|
||||
<div id="request-status" class="notice" role="status" aria-live="polite" hidden></div>
|
||||
|
||||
@@ -30,6 +30,27 @@
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** @param {unknown} open @param {unknown} close */
|
||||
function businessHoursError(open, close) {
|
||||
const time = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
|
||||
if (typeof open !== 'string' || typeof close !== 'string' || !time.test(open) || !time.test(close))
|
||||
return '请完整填写开始和结束时间';
|
||||
return open === close ? '开始和结束时间不能相同' : '';
|
||||
}
|
||||
|
||||
/** 将两个 time 输入转为局部更新;清空一组已设置的时间才发送 null。
|
||||
* @param {string} open @param {string} close @param {{businessOpen: string, businessClose: string}} baseline
|
||||
* @returns {{businessHours?: {open: string, close: string} | null}}
|
||||
*/
|
||||
function businessHoursPatch(open, close, baseline) {
|
||||
if (open || close) {
|
||||
const message = businessHoursError(open, close);
|
||||
if (message) throw new Error(message);
|
||||
}
|
||||
if (open === baseline.businessOpen && close === baseline.businessClose) return {};
|
||||
return { businessHours: open ? { open, close } : null };
|
||||
}
|
||||
|
||||
/** @type {Record<string,string>} */
|
||||
const prefixes = { owner: '麦麦', assistant: '助理', assistant2: '助理2' };
|
||||
/** @param {string} member */
|
||||
@@ -82,6 +103,8 @@
|
||||
positiveMg,
|
||||
validDate,
|
||||
previousDate,
|
||||
businessHoursError,
|
||||
businessHoursPatch,
|
||||
memberAccountPrefix,
|
||||
accountIdentity,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
// 轻量登录页、旧版外壳与 React 共用。可复制字段不包含账号、表单或响应正文。
|
||||
(function (root) {
|
||||
/** @type {Readonly<Record<string, string>>} */
|
||||
const steps = {
|
||||
'/api/login': '提交登录',
|
||||
'/api/demo-login': '进入演示',
|
||||
'/api/setup': '建立账号',
|
||||
'/api/session': '检查登录状态',
|
||||
'/api/state': '读取账本',
|
||||
};
|
||||
/** @typedef {{path: string, method: string, status?: number, timedOut: boolean, elapsed: number}} Attempt */
|
||||
/** @param {Error & {status?: number, loginDiagnostic?: Attempt}} error @param {string} fallbackStep */
|
||||
function describe(error, fallbackStep) {
|
||||
const diagnostic = error.loginDiagnostic;
|
||||
const step = diagnostic ? steps[diagnostic.path] : fallbackStep;
|
||||
let message;
|
||||
if (!diagnostic) message = '页面处理出错,请刷新后重试。';
|
||||
else if (error.status) message = error.message;
|
||||
else if (diagnostic.timedOut) message = '等待超过 25 秒,浏览器已停止等待。';
|
||||
else if (diagnostic.status) message = '已收到服务器响应,但未能读取完整的账本系统数据。';
|
||||
else message = '浏览器未收到 HTTP 响应,具体中断原因还需对照服务器日志。';
|
||||
const time = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
|
||||
const lines = ['步骤:' + step, '北京时间:' + time];
|
||||
if (diagnostic) {
|
||||
lines.push('接口:' + diagnostic.method + ' ' + diagnostic.path, 'HTTP 状态:' + (diagnostic.status || '未收到'));
|
||||
lines.push('本次请求耗时:' + (diagnostic.elapsed / 1000).toFixed(1) + ' 秒');
|
||||
}
|
||||
const browserMessages = [
|
||||
'Load failed',
|
||||
'Failed to fetch',
|
||||
'fetch is aborted',
|
||||
'Fetch is aborted',
|
||||
'NetworkError when attempting to fetch resource.',
|
||||
'The operation was aborted.',
|
||||
];
|
||||
if (browserMessages.includes(error.message)) lines.push('浏览器提示:' + error.message);
|
||||
return { step, message, details: lines.join('\n') };
|
||||
}
|
||||
/** @param {string} details */
|
||||
async function copy(details) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(details);
|
||||
return '已复制';
|
||||
} catch {
|
||||
return '请长按或选中上方文字复制';
|
||||
}
|
||||
}
|
||||
const api = { steps, describe, copy };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else Object.assign(root, { LoginDiagnostics: api });
|
||||
})(globalThis);
|
||||
@@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
function escapeLoginText(value) {
|
||||
return String(value ?? '').replace(
|
||||
/[&<>"']/g,
|
||||
c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
|
||||
);
|
||||
}
|
||||
function loginErrorHTML(error, fallbackStep) {
|
||||
const { step, message, details } = LoginDiagnostics.describe(error, fallbackStep);
|
||||
return `<section class="error" role="alert"><strong>${escapeLoginText(step)}失败</strong><p>${escapeLoginText(message)}</p><div data-login-diagnostic style="white-space:pre-line;overflow-wrap:anywhere">${escapeLoginText(details)}</div><button type="button" data-action="copy-login-diagnostic" class="quiet">复制诊断信息</button></section>`;
|
||||
}
|
||||
|
||||
async function copyLoginDiagnostic(button) {
|
||||
const details = button.parentElement.querySelector('[data-login-diagnostic]');
|
||||
button.textContent = await LoginDiagnostics.copy(details.innerText);
|
||||
}
|
||||
|
||||
function bindStandaloneLogin() {
|
||||
const form = document.querySelector('form');
|
||||
if (!form) return;
|
||||
const status = document.getElementById('login-status');
|
||||
const notice = document.getElementById('login-error');
|
||||
const buttons = [...form.querySelectorAll('button[type=submit]')];
|
||||
const url = form.getAttribute('action');
|
||||
let saving = false;
|
||||
buttons.forEach(button => (button.disabled = false));
|
||||
notice.addEventListener('click', event => {
|
||||
const button = event.target.closest('[data-action="copy-login-diagnostic"]');
|
||||
if (button) copyLoginDiagnostic(button);
|
||||
});
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (saving) return;
|
||||
const data = Object.fromEntries(new FormData(form));
|
||||
if (url === '/api/demo-login') data.member = event.submitter.value;
|
||||
saving = true;
|
||||
buttons.forEach(button => (button.disabled = true));
|
||||
notice.replaceChildren();
|
||||
status.textContent = '正在' + LoginDiagnostics.steps[url] + '…';
|
||||
const controller = new AbortController(),
|
||||
started = Date.now();
|
||||
const timer = setTimeout(() => controller.abort(), 25000);
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'maimai-ledger' },
|
||||
body: JSON.stringify(data),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const result = await response.json().catch(() => null);
|
||||
throw Object.assign(new Error(result?.error || '服务器返回了错误,请稍后再试。'), { status: response.status });
|
||||
}
|
||||
const result = await response.json();
|
||||
if (!result?.user?.id) throw new Error('响应缺少登录结果');
|
||||
status.textContent = '已登录,正在打开账本…';
|
||||
location.reload();
|
||||
} catch (error) {
|
||||
error.loginDiagnostic = {
|
||||
path: url,
|
||||
method: 'POST',
|
||||
status: response?.status,
|
||||
timedOut: controller.signal.aborted,
|
||||
elapsed: Date.now() - started,
|
||||
};
|
||||
notice.innerHTML = loginErrorHTML(error, LoginDiagnostics.steps[url]);
|
||||
status.textContent = '';
|
||||
saving = false;
|
||||
buttons.forEach(button => (button.disabled = false));
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (typeof document !== 'undefined' && document.body?.hasAttribute('data-standalone-login')) bindStandaloneLogin();
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = { escapeLoginText };
|
||||
@@ -19,6 +19,8 @@ function shopSettingsValues(settings = state.shopSettings) {
|
||||
storeName: settings.storeName,
|
||||
receiptSubtitle: settings.receiptSubtitle || '',
|
||||
contact: settings.contact || '',
|
||||
businessOpen: settings.businessHours?.open ?? '',
|
||||
businessClose: settings.businessHours?.close ?? '',
|
||||
creditCardRatePermille: String(settings.creditCardRatePermille),
|
||||
profitSharePercent: String(settings.profitSharePercent),
|
||||
profitShareEffectiveMonth:
|
||||
@@ -65,7 +67,7 @@ function shopSettingsHTML() {
|
||||
if (state.user.role !== 'owner' || !state.shopSettings) return '';
|
||||
const settings = state.shopSettings,
|
||||
values = shopSettingsValues(settings);
|
||||
return `<section class="panel shop-settings" id="shop-settings-panel"><div class="panel-title"><div><h2>店铺配置</h2><p id="shop-settings-status" class="small muted" aria-live="polite">当前生效配置;仅店主可以修改。</p></div></div><form id="shop-settings-form" data-revision="${e(settings.revision)}" data-baseline="${e(JSON.stringify(values))}"><fieldset class="shop-settings-fields"><div class="grid three">${field('店名', 'storeName', values.storeName, 'text', 'required maxlength="80"')}${field('单据标题', 'receiptSubtitle', values.receiptSubtitle, 'text', 'maxlength="80"')}${field('联系电话/客户联系信息(选填)', 'contact', values.contact, 'text', 'maxlength="80"')}</div><h3>开单默认费用</h3><div class="grid four">${field('证书成本(元)', 'certificate', values.certificate, 'number', 'required min="0" max="1000000" step="0.01"')}${field('包装成本(元)', 'packaging', values.packaging, 'number', 'required min="0" max="1000000" step="0.01"')}${field('整单快递成本(元)', 'shipping', values.shipping, 'number', 'required min="0" max="1000000" step="0.01"')}${choice('包装默认付款人', 'packagingPayer', teamMemberOptions(), values.packagingPayer)}</div><p class="small muted">默认费用只用于新增项目。已有订单、模板和草稿里已经填写的费用及付款人按原值保留,开单时仍可按实际修改。</p><h3>手续费与利润分成</h3><div class="grid three">${field('信用卡手续费率(‰)', 'creditCardRatePermille', values.creditCardRatePermille, 'number', 'required min="0" max="1000" step="1"')}${field('助理利润分成比例(%)', 'profitSharePercent', values.profitSharePercent, 'number', 'required min="0" max="100" step="1"')}${field('分成生效月份', 'profitShareEffectiveMonth', values.profitShareEffectiveMonth, 'month', `required min="${e(state.today.slice(0, 7))}"`)}</div><p class="small muted">新建订单使用当前信用卡费率;修改旧单沿用原费率。分成按生效月份统计,历史月份保留原口径。</p></fieldset><div id="shop-settings-error" aria-live="polite"></div><div class="form-actions"><button type="submit" class="primary">保存店铺配置</button></div></form>${shopCostManagerHTML()}</section>`;
|
||||
return `<section class="panel shop-settings" id="shop-settings-panel"><div class="panel-title"><div><h2>店铺配置</h2><p id="shop-settings-status" class="small muted" aria-live="polite">当前生效配置;仅店主可以修改。</p></div></div><form id="shop-settings-form" data-revision="${e(settings.revision)}" data-baseline="${e(JSON.stringify(values))}"><fieldset class="shop-settings-fields"><div class="grid three">${field('店名', 'storeName', values.storeName, 'text', 'required maxlength="80"')}${field('单据标题', 'receiptSubtitle', values.receiptSubtitle, 'text', 'maxlength="80"')}${field('联系电话/客户联系信息(选填)', 'contact', values.contact, 'text', 'maxlength="80"')}</div><h3>营业时间(北京时间)</h3><div class="grid two">${field('开始时间', 'businessOpen', values.businessOpen, 'time')}${field('结束时间', 'businessClose', values.businessClose, 'time')}</div><p class="small muted">结束时间早于开始时间,表示营业到次日。两项留空时暂停员工访问。超级管理员可全天登录和使用账本。</p><h3>开单默认费用</h3><div class="grid four">${field('证书成本(元)', 'certificate', values.certificate, 'number', 'required min="0" max="1000000" step="0.01"')}${field('包装成本(元)', 'packaging', values.packaging, 'number', 'required min="0" max="1000000" step="0.01"')}${field('整单快递成本(元)', 'shipping', values.shipping, 'number', 'required min="0" max="1000000" step="0.01"')}${choice('包装默认付款人', 'packagingPayer', teamMemberOptions(), values.packagingPayer)}</div><p class="small muted">默认费用只用于新增项目。已有订单、模板和草稿里已经填写的费用及付款人按原值保留,开单时仍可按实际修改。</p><h3>手续费与利润分成</h3><div class="grid three">${field('信用卡手续费率(‰)', 'creditCardRatePermille', values.creditCardRatePermille, 'number', 'required min="0" max="1000" step="1"')}${field('助理利润分成比例(%)', 'profitSharePercent', values.profitSharePercent, 'number', 'required min="0" max="100" step="1"')}${field('分成生效月份', 'profitShareEffectiveMonth', values.profitShareEffectiveMonth, 'month', `required min="${e(state.today.slice(0, 7))}"`)}</div><p class="small muted">新建订单使用当前信用卡费率;修改旧单沿用原费率。分成按生效月份统计,历史月份保留原口径。</p></fieldset><div id="shop-settings-error" aria-live="polite"></div><div class="form-actions"><button type="submit" class="primary">保存店铺配置</button></div></form>${shopCostManagerHTML()}</section>`;
|
||||
}
|
||||
function shopSettingsInput(form) {
|
||||
if (state.user.role !== 'owner') throw new Error('店铺配置由店主账号修改。');
|
||||
@@ -85,14 +87,16 @@ function shopSettingsInput(form) {
|
||||
values.profitShareEffectiveMonth < state.today.slice(0, 7)
|
||||
)
|
||||
throw new Error('分成生效月份请选择本月或以后。');
|
||||
const baseline = JSON.parse(form.dataset.baseline);
|
||||
return {
|
||||
revision: Number(form.dataset.revision),
|
||||
...LedgerValues.businessHoursPatch(values.businessOpen, values.businessClose, baseline),
|
||||
storeName: values.storeName.trim(),
|
||||
receiptSubtitle: values.receiptSubtitle.trim(),
|
||||
contact: values.contact.trim(),
|
||||
creditCardRatePermille: integer('creditCardRatePermille', 1000, '信用卡费率'),
|
||||
...(values.profitSharePercent !== JSON.parse(form.dataset.baseline).profitSharePercent ||
|
||||
values.profitShareEffectiveMonth !== JSON.parse(form.dataset.baseline).profitShareEffectiveMonth
|
||||
...(values.profitSharePercent !== baseline.profitSharePercent ||
|
||||
values.profitShareEffectiveMonth !== baseline.profitShareEffectiveMonth
|
||||
? {
|
||||
profitSharePercent: integer('profitSharePercent', 100, '利润分成比例'),
|
||||
profitShareEffectiveMonth: values.profitShareEffectiveMonth,
|
||||
@@ -146,6 +150,7 @@ async function saveShopSettings(form) {
|
||||
}
|
||||
syncPrintSettingsPreview();
|
||||
syncShopSettingsStatus(true);
|
||||
if (Object.hasOwn(input, 'businessHours')) window.dispatchEvent(new Event('ledger-business-hours-changed'));
|
||||
await loadTeamMembers();
|
||||
if (typeof loadEmployees === 'function' && document.querySelector('#employee-list')) await loadEmployees();
|
||||
toast('店铺配置已保存');
|
||||
|
||||
Reference in new issue
Block a user