Files
weiguang-jewelry-ledger/新账系统/public/shop-settings-ui.js
T

73 lines
9.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// 店铺配置管理品牌、费用及分成;成员与登录账号沿用现有固定设置。
let shopSettingsSaving=false;
function applyShopBrand(){
const name=shopBrandName();document.title=name+' · 新账系统';
const title=document.querySelector('[data-shop-name]'),mark=document.querySelector('[data-shop-mark]');
if(title)title.textContent=name;if(mark)mark.textContent=Array.from(name)[0]||'店';
}
function shopNextMonth(){
const date=state.today||new Date().toISOString().slice(0,10),[year,month]=date.slice(0,7).split('-').map(Number);
return String(month===12?year+1:year)+'-'+String(month===12?1:month+1).padStart(2,'0');
}
function shopSettingsValues(settings=state.shopSettings){
const values={storeName:settings.storeName,receiptSubtitle:settings.receiptSubtitle||'',contact:settings.contact||'',creditCardRatePermille:String(settings.creditCardRatePermille),profitSharePercent:String(settings.profitSharePercent),profitShareEffectiveMonth:settings.profitShareEffectiveMonth>=state.today.slice(0,7)?settings.profitShareEffectiveMonth:shopNextMonth(),certificate:settings.feeDefaults.certificate,packaging:settings.feeDefaults.packaging,shipping:settings.feeDefaults.shipping,packagingPayer:settings.feeDefaults.packagingPayer};
return values;
}
function shopSettingsFormValues(form){return Object.fromEntries(Object.keys(JSON.parse(form.dataset.baseline)).map(key=>[key,form.elements.namedItem(key)?.value??'']));}
function shopSettingsDirty(form=document.querySelector('#shop-settings-form')){
if(!form)return false;const baseline=JSON.parse(form.dataset.baseline),current=shopSettingsFormValues(form);
return Object.keys(baseline).some(key=>String(baseline[key]??'')!==current[key]);
}
function syncShopSettingsStatus(saved=false){
const form=document.querySelector('#shop-settings-form');if(!form)return;
if(saved)form.dataset.saved='true';const dirty=shopSettingsDirty(form),status=document.querySelector('#shop-settings-status');
if(status){status.className='small '+(dirty?'danger-text':'muted');status.textContent=shopSettingsSaving?'正在保存店铺配置…':dirty?'修改尚未保存。':form.dataset.saved==='true'?'已保存,后续开单使用当前配置。':'当前生效配置;仅店主可以修改。';}
form.querySelector('button[type="submit"]').disabled=shopSettingsSaving||busy||!!pending();
}
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></section>`;
}
function shopSettingsInput(form){
if(state.user.role!=='owner')throw new Error('店铺配置由店主账号修改。');
const values=shopSettingsFormValues(form),integer=(name,max,title)=>{if(!/^\d+$/.test(values[name])||Number(values[name])>max)throw new Error(title+'请填写0~'+max+'之间的整数。');return Number(values[name]);};
if(!values.storeName.trim()||values.storeName.trim().length>80)throw new Error('店名请填写1~80字。');
for(const name of ['certificate','packaging','shipping']){if(LedgerCalc.cents(values[name],'默认费用')>100000000)throw new Error('默认费用最多1000000元。');}
if(!teamMemberKeys.includes(values.packagingPayer))throw new Error('请选择包装默认付款人。');
if(!/^\d{4}-(0[1-9]|1[0-2])$/.test(values.profitShareEffectiveMonth)||values.profitShareEffectiveMonth<state.today.slice(0,7))throw new Error('分成生效月份请选择本月或以后。');
return {revision:Number(form.dataset.revision),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?{profitSharePercent:integer('profitSharePercent',100,'利润分成比例'),profitShareEffectiveMonth:values.profitShareEffectiveMonth}:{}),feeDefaults:{certificate:values.certificate,packaging:values.packaging,shipping:values.shipping,packagingPayer:values.packagingPayer}};
}
async function saveShopSettings(form){
if(shopSettingsSaving||printSettingsSaving||busy||pending())throw new Error('请先等当前操作完成,再保存店铺配置。');
if(form!==document.querySelector('#shop-settings-form'))throw new Error('配置页面已变化,请重新打开设置。');
const input=shopSettingsInput(form),user=state.user.id,fields=form.querySelector('fieldset');let committed=false;
shopSettingsSaving=true;fields.disabled=true;document.querySelector('#shop-settings-error').replaceChildren();syncShopSettingsStatus();
try{
const result=await mutate('/api/shop-settings',input);committed=true;
if(user!==state.user.id)throw accountChangedError();
state.shopSettings=result.shopSettings;state.printing=result.printing||state.printing;
applyShopBrand();
// 只更新店铺表单,打印偏移等尚未保存的输入留在当前页面。
const panel=document.querySelector('#shop-settings-panel');if(panel)panel.outerHTML=shopSettingsHTML();
const printing=document.querySelector('#print-settings');for(const key of ['store','subtitle','contact']){const target=printing?.elements.namedItem(key);if(target)target.value=state.printing[key]||'';}
syncPrintSettingsPreview();syncShopSettingsStatus(true);
toast('店铺配置已保存');
}catch(error){if(committed)error.message='店铺配置已保存,页面更新未完成,请刷新后核对。';throw error;}
finally{shopSettingsSaving=false;if(form===document.querySelector('#shop-settings-form'))fields.disabled=false;syncShopSettingsStatus();}
}
function shopSettingsError(error){
const target=document.querySelector('#shop-settings-error');if(target){target.className='error';target.textContent=error.message+(error.status===409?' 已填写内容已保留,请刷新读取最新配置后再修改。':'');}
toast(error.message,true);
}
for(const type of ['input','change'])document.addEventListener(type,event=>{if(event.target.closest?.('#shop-settings-form'))syncShopSettingsStatus();});
// 页面跳转与刷新前保护配置;不监听或替换任何业务正文。
document.addEventListener('click',event=>{
const node=event.target.closest?.('button');if(!node||!document.querySelector('#shop-settings-form'))return;
const leaving=!!node.dataset.tab||node.dataset.action==='logout'||node.dataset.action?.startsWith('demo-')||['refresh','sync'].includes(node.dataset.action);if(!leaving)return;
const saving=shopSettingsSaving||printSettingsSaving,dirty=shopSettingsDirty()||printSettingsDirty();
if(saving||dirty&&!window.confirm('店铺或打印设置尚未保存,离开会丢弃这些修改。继续离开?')){event.preventDefault();event.stopImmediatePropagation();if(saving)toast('设置正在保存,请稍候。',true);}
},true);
window.addEventListener('beforeunload',event=>{if(shopSettingsSaving||shopSettingsDirty()||printSettingsDirty()){event.preventDefault();event.returnValue='';}});