'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 `

店铺配置

当前生效配置;仅店主可以修改。

${field('店名','storeName',values.storeName,'text','required maxlength="80"')}${field('单据标题','receiptSubtitle',values.receiptSubtitle,'text','maxlength="80"')}${field('联系电话/客户联系信息(选填)','contact',values.contact,'text','maxlength="80"')}

开单默认费用

${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)}

默认费用只用于新增项目。已有订单、模板和草稿里已经填写的费用及付款人按原值保留,开单时仍可按实际修改。

手续费与利润分成

${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))}"`)}

新建订单使用当前信用卡费率;修改旧单沿用原费率。分成按生效月份统计,历史月份保留原口径。

${shopCostManagerHTML()}
`; } 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({...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 `

勾选成本管理

自行添加需要的项目。删除后不再用于新单,历史订单成本保留。

${button('+ 新增成本','shop-cost-add','primary')}
${shopCostListHTML()}
`; } 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 `

${rows.length?'没有匹配的成本项目。':'还没有勾选成本,点击“新增成本”添加。'}

`; return `
${visible.map(([kind,row])=>``).join('')}
成本名称金额/单价付款人计费方式状态操作
${e(row.name)}¥${e(row.amount)}${row.payer==='order'?'订单归属人':e(teamMemberName(row.payer))}${row.byQuantity?'单价 × 数量':'每单一次'}${row.enabled?'启用':'停用'}
${button('编辑','shop-cost-edit','quiet',`data-kind="${e(kind)}"`)}${button('删除','shop-cost-delete','danger',`data-kind="${e(kind)}"`)}
`; } 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=`

${action==='add'?'新增成本':action==='delete'?'删除成本':'编辑成本'}

${action==='delete'?`

删除“${e(row.name)}”?

删除后不会再出现在新单勾选项里,已开订单、成本和流水保留。

`:`
${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))}
`}
${button('取消','shop-cost-close','quiet')}
`; 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);} });