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

127 lines
17 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>${shopCostManagerHTML()}</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();
const previousMembers=state.members||[];state.shopSettings=result.shopSettings;state.printing=result.printing||state.printing;state.members=result.shopSettings.members.map(row=>({...previousMembers.find(old=>old.member===row.member),...row}));
const member=result.shopSettings.members.find(row=>row.member===currentMember());if(member){state.user.label=member.label;session.user.label=member.label;}
applyShopBrand();document.querySelector('#identity').textContent=state.user.label||state.user.name;
// 只更新店铺表单,打印偏移等尚未保存的输入留在当前页面。
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);
await loadTeamMembers();if(typeof loadEmployees==='function'&&document.querySelector('#employee-list'))await loadEmployees();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()||shopCostDirty();
if(saving||dirty&&!window.confirm('店铺或打印设置尚未保存,离开会丢弃这些修改。继续离开?')){event.preventDefault();event.stopImmediatePropagation();if(saving)toast('设置正在保存,请稍候。',true);}else if(shopCostEditor)closeShopCost(true);
},true);
window.addEventListener('beforeunload',event=>{if(shopSettingsSaving||shopSettingsDirty()||printSettingsDirty()||shopCostDirty()){event.preventDefault();event.returnValue='';}});
let shopCostSearch='',shopCostEditor=null;
function shopCostManagerHTML(){
return `<section id="shop-cost-manager" class="shop-cost-manager"><div class="panel-title"><div><h3>勾选成本管理</h3><p class="small muted">自行添加需要的项目。删除后不再用于新单,历史订单成本保留。</p></div>${button('+ 新增成本','shop-cost-add','primary')}</div><label class="shop-cost-search">搜索成本<input type="search" id="shop-cost-search" placeholder="输入成本名称" value="${e(shopCostSearch)}" autocomplete="off"></label><div id="shop-cost-list">${shopCostListHTML()}</div></section>`;
}
function shopCostListHTML(){
const rows=Object.entries(FeeEstimates.presetCatalog(state.shopSettings.costPresets)),needle=shopCostSearch.trim().toLocaleLowerCase(),visible=rows.filter(([,row])=>row.name.toLocaleLowerCase().includes(needle));
if(!visible.length)return `<p class="empty">${rows.length?'没有匹配的成本项目。':'还没有勾选成本,点击“新增成本”添加。'}</p>`;
return `<div class="table-wrap"><table class="shop-cost-table"><thead><tr><th>成本名称</th><th>金额/单价</th><th>付款人</th><th>计费方式</th><th>状态</th><th>操作</th></tr></thead><tbody>${visible.map(([kind,row])=>`<tr data-cost-row="${e(kind)}"><td><strong>${e(row.name)}</strong></td><td>¥${e(row.amount)}</td><td>${row.payer==='order'?'订单归属人':e(teamMemberName(row.payer))}</td><td>${row.byQuantity?'单价 × 数量':'每单一次'}</td><td>${row.enabled?'启用':'停用'}</td><td><div class="actions">${button('编辑','shop-cost-edit','quiet',`data-kind="${e(kind)}"`)}${button('删除','shop-cost-delete','danger',`data-kind="${e(kind)}"`)}</div></td></tr>`).join('')}</tbody></table></div>`;
}
function shopCostValues(form=document.querySelector('#shop-cost-form')){
const read=name=>String(form?.elements.namedItem(name)?.value??'');return {name:read('name'),amount:read('amount'),payer:read('payer'),enabled:read('enabled')==='true',byQuantity:read('byQuantity')==='true'};
}
function shopCostDirty(){return !!shopCostEditor&&shopCostEditor.action!=='delete'&&JSON.stringify(shopCostValues())!==JSON.stringify(shopCostEditor.baseline);}
function closeShopCost(discard=false){
if(shopSettingsSaving)return false;if(!discard&&shopCostDirty()&&!window.confirm('成本修改尚未保存,放弃修改?'))return false;
shopCostEditor=null;document.querySelector('#shop-cost-dialog')?.close();return true;
}
function openShopCost(action,kind=''){
if(state.user.role!=='owner'||shopSettingsSaving||busy||pending())return;
if(!closeShopCost())return;
const row=FeeEstimates.presetCatalog(state.shopSettings.costPresets)[kind];if(action!=='add'&&!row)throw new Error('成本项目已变动,请刷新后重试');
const value=row||{name:'',amount:'0',payer:'order',enabled:true,byQuantity:false};
shopCostEditor={action,kind:kind||'custom_'+crypto.randomUUID(),revision:state.shopSettings.revision,user:state.user.id,baseline:{name:value.name,amount:value.amount,payer:value.payer,enabled:value.enabled,byQuantity:value.byQuantity}};
let dialog=document.querySelector('#shop-cost-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='shop-cost-dialog';document.body.append(dialog);dialog.addEventListener('cancel',event=>{event.preventDefault();closeShopCost();});}
dialog.innerHTML=`<button class="dialog-close" type="button" data-action="shop-cost-close" aria-label="关闭成本编辑">×</button><h2>${action==='add'?'新增成本':action==='delete'?'删除成本':'编辑成本'}</h2><form id="shop-cost-form">${action==='delete'?`<p>删除“<strong>${e(row.name)}</strong>”?</p><p class="muted">删除后不会再出现在新单勾选项里,已开订单、成本和流水保留。</p>`:`<div class="grid two">${field('成本名称','name',value.name,'text','required maxlength="40"')}${field('金额/单价(元)','amount',value.amount,'number','required min="0" max="1000000" step="0.01"')}${choice('付款人','payer',[['order','订单归属人'],...teamMemberOptions()],value.payer)}${choice('计费方式','byQuantity',[['false','每单一次'],['true','单价 × 数量']],String(value.byQuantity))}${choice('状态','enabled',[['true','启用'],['false','停用']],String(value.enabled))}</div>`}<div id="shop-cost-error" role="alert"></div><div class="form-actions">${button('取消','shop-cost-close','quiet')}<button type="submit" class="${action==='delete'?'danger':'primary'}">${action==='delete'?'确认删除':'保存成本'}</button></div></form>`;
dialog.showModal();dialog.querySelector('input')?.focus();
}
async function saveShopCost(form){
const entry=shopCostEditor;if(!entry||entry.user!==state.user.id||state.user.role!=='owner')throw new Error('账号已变化,请重新打开成本管理');
if(shopSettingsSaving||busy||pending())throw new Error('请先确认当前操作,再保存成本');
const value=entry.action==='delete'?null:shopCostValues(form);
if(value){value.name=value.name.trim();if(!value.name||value.name.length>40)throw new Error('成本名称请填写1~40字');if(LedgerCalc.cents(value.amount,'成本')>100000000)throw new Error('成本最多1000000元');}
shopSettingsSaving=true;form.querySelectorAll('input,select,button').forEach(node=>node.disabled=true);let committed=false;
try{
const result=await mutate('/api/shop-settings',{revision:entry.revision,costPresets:{[entry.kind]:value}});committed=true;
if(state.user.id!==entry.user)throw accountChangedError();state.shopSettings=result.shopSettings;
// 目录单独保存,不覆盖其他尚未保存的店铺配置输入。
const settings=document.querySelector('#shop-settings-form');if(settings)settings.dataset.revision=String(result.shopSettings.revision);
const manager=document.querySelector('#shop-cost-manager');if(manager)manager.outerHTML=shopCostManagerHTML();
shopCostEditor=null;document.querySelector('#shop-cost-dialog')?.close();syncShopSettingsStatus();toast(entry.action==='delete'?'成本项目已删除':'成本项目已保存');
}catch(error){if(committed)error.message='成本已经保存,请刷新页面核对';throw error;}
finally{shopSettingsSaving=false;form.querySelectorAll('input,select,button').forEach(node=>node.disabled=false);syncShopSettingsStatus();}
}
document.addEventListener('input',event=>{if(event.target.id==='shop-cost-search'){shopCostSearch=event.target.value;document.querySelector('#shop-cost-list').innerHTML=shopCostListHTML();}});
document.addEventListener('click',event=>{
const node=event.target.closest?.('button'),action=node?.dataset.action;if(!action?.startsWith('shop-cost-'))return;event.preventDefault();
try{if(action==='shop-cost-close')return closeShopCost();openShopCost(action.slice(10),node.dataset.kind);}catch(error){toast(error.message,true);}
});
document.addEventListener('submit',async event=>{
if(event.target.id!=='shop-cost-form')return;event.preventDefault();event.stopImmediatePropagation();
try{await saveShopCost(event.target);}catch(error){const target=document.querySelector('#shop-cost-error');if(target){target.className='error';target.textContent=error.message;}toast(error.message,true);}
});