成本配置改用紧凑列表增删查改,空目录不恢复固定项目

This commit is contained in:
summer committed 2026-12-04 01:24:14 +08:00
1 parent ba67ba790d
commit 13382e4d49
7 files changed
+88 -28

No files matched your search

+54 -23
View File
@@ -12,7 +12,6 @@ function shopNextMonth(){
}
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};
for(const [kind,row] of Object.entries(FeeEstimates.presetCatalog(settings.costPresets))){for(const key of ['amount','payer','name','enabled','byQuantity'])values['preset_'+kind+'_'+key]=String(row[key]);}
return values;
}
function shopSettingsFormValues(form){return Object.fromEntries(Object.keys(JSON.parse(form.dataset.baseline)).map(key=>[key,form.elements.namedItem(key)?.value??'']));}
@@ -29,23 +28,16 @@ function syncShopSettingsStatus(saved=false){
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 id="shop-cost-cards" class="grid two">${Object.keys(FeeEstimates.presetCatalog(settings.costPresets)).map(kind=>shopCostCard(kind,values)).join('')}</div><p class="small muted">${button('+ 新增勾选成本','shop-cost-add')} 只影响新勾选的费用;已有订单的金额、付款人和支付日期保持原记录。</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>`;
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字。');
const costPresets={};for(const kind of Object.keys(values).filter(key=>/^preset_.+_amount$/.test(key)).map(key=>key.slice(7,-7))){
const amount=values['preset_'+kind+'_amount'],payer=values['preset_'+kind+'_payer'],name=values['preset_'+kind+'_name'].trim();
if(!name||name.length>40)throw new Error('成本名称请填写1~40字');
if(LedgerCalc.cents(amount,'常用成本')>100000000)throw new Error('常用成本最多1000000元');if(payer!=='order'&&!activeTeamMemberKeys().includes(payer))throw new Error('请选择有效付款人');
costPresets[kind]={amount,payer,name,enabled:values['preset_'+kind+'_enabled']==='true',byQuantity:values['preset_'+kind+'_byQuantity']==='true'};
}
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),costPresets,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}};
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('请先等当前操作完成,再保存店铺配置。');
@@ -75,21 +67,60 @@ for(const type of ['input','change'])document.addEventListener(type,event=>{if(e
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);}
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()){event.preventDefault();event.returnValue='';}});
window.addEventListener('beforeunload',event=>{if(shopSettingsSaving||shopSettingsDirty()||printSettingsDirty()||shopCostDirty()){event.preventDefault();event.returnValue='';}});
function shopCostCard(kind,values){
const key=name=>'preset_'+kind+'_'+name;
return `<div class="panel shop-cost-card" data-preset="${e(kind)}">${field('成本名称',key('name'),values[key('name')],'text','required maxlength="40"')}${field('成本/单价(元)',key('amount'),values[key('amount')],'number','required min="0" max="1000000" step="0.01"')}${choice('默认付款人',key('payer'),[['order','订单归属人'],...teamMemberOptions()],values[key('payer')])}${choice('计费方式',key('byQuantity'),[['false','每单一次'],['true','单价 × 数量']],values[key('byQuantity')])}${choice('状态',key('enabled'),[['true','启用'],['false','停用']],values[key('enabled')])}</div>`;
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=>{
if(event.target.closest?.('[data-action="shop-cost-add"]')){
event.preventDefault();if(shopSettingsSaving||busy||pending()||state.user.role!=='owner')return;
const form=document.querySelector('#shop-settings-form'),baseline=JSON.parse(form.dataset.baseline),kind='custom_'+crypto.randomUUID(),values={};
if(Object.keys(baseline).filter(key=>/^preset_.+_amount$/.test(key)).length>=100)return toast('常用成本最多100项',true);
for(const [key,value] of Object.entries({name:'',amount:'0',payer:'order',enabled:'true',byQuantity:'false'})){values['preset_'+kind+'_'+key]=value;baseline['preset_'+kind+'_'+key]='';}
form.dataset.baseline=JSON.stringify(baseline);document.querySelector('#shop-cost-cards').insertAdjacentHTML('beforeend',shopCostCard(kind,values));syncShopSettingsStatus();
}
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);}
});