Files
weiguang-jewelry-ledger/新账系统/public/order-templates.js
T

90 lines
9.8 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';
// 模板只保存表单预设;金额仍用元、重量仍用克,不继承订单或流水身份。
(function(root,factory){
const api=factory(typeof module==='object'&&module.exports?require('./fee-estimates'):root.FeeEstimates,typeof module==='object'&&module.exports?require('./credit-card-fees'):root.CreditCardFees);
if(typeof module==='object'&&module.exports)module.exports=api;else root.OrderTemplates=api;
})(typeof globalThis==='object'?globalThis:this,function(Fees,Cards){
const products=['足金999','足银999','纯银925'],charges=['编绳','证书','包装','快递','附加费'];
const pockets=['','现货','金料','找金','回收旧料','君宝汇'];
const accounts=['助理2微信','助理2支付宝','助理2现金','助理2信用卡','助理微信','助理支付宝','助理现金','助理信用卡','麦麦微信','麦麦支付宝','麦麦现金','麦麦信用卡'];
const normalizeAccount=account=>Cards?.normalizeAccount?Cards.normalizeAccount(account):(['助理信用卡','助理1信用卡','助理2信用卡','麦麦信用卡'].includes(account)?'麦麦信用卡':account);
const cardFee=item=>item?.system==='credit_card'||String(item?.key||'').startsWith('card_fee:');
const uuid=/^[a-f0-9-]{36}$/;
function object(value,name){if(!value||typeof value!=='object'||Array.isArray(value))throw new Error(name+'格式无效');return value;}
function string(value,name,max=100){
if(value!=null&&!['string','number'].includes(typeof value))throw new Error(name+'格式无效');
const result=String(value??'').trim();if(result.length>max)throw new Error(name+'最多填写'+max+'字');return result;
}
function pick(value,values,name,fallback){const result=value??fallback;if(!values.includes(result))throw new Error(name+'无效');return result;}
function numeric(value,name,places=2){
const result=string(value,name,24);if(!result)return '';
if(!new RegExp('^\\d+(?:\\.\\d{1,'+places+'})?$').test(result))throw new Error(name+'须为非负数字,最多'+places+'位小数');
const [whole,fraction='']=result.split('.');if(BigInt(whole)*10n**BigInt(places)+BigInt(fraction.padEnd(places,'0'))>100000000000n)throw new Error(name+'超出支持范围');return result;
}
function count(value,name){const result=string(value,name,12);if(result&&!/^\d+$/.test(result))throw new Error(name+'须为非负整数');if(Number(result)>1000000000)throw new Error(name+'超出支持范围');return result;}
function payer(value,fallback='owner'){return pick(value,['owner','assistant','assistant2',''],'成本付款人',fallback);}
function manualMaterial(value={},fallback={}){
object(value,'备用料费');return {mode:pick(value.mode,['gram','total'],'备用料费方式',fallback.mode||'gram'),rate:numeric(value.rate??fallback.rate,'备用进货料价'),total:numeric(value.total??fallback.total,'备用料费合计'),originalTotal:'',payer:payer(value.payer,fallback.payer??'owner')};
}
function fromDraft(draft,{newId=()=>globalThis.crypto.randomUUID(),pocketKeys=pockets}={}){
object(draft,'开单预设');
if(!Array.isArray(draft.lines)||!draft.lines.length||draft.lines.length>60)throw new Error('模板需要1~60行商品');
const ids=new Map(),seen=new Set();
const lines=draft.lines.map(raw=>{
const line=object(raw,'模板商品'),unit=pick(line.unit,['g','件'],'商品单位','g');
const name=string(line.name,'商品名称',60),nameType=pick(line.nameType,[...products,'其他'],'商品名称',products.includes(name)?name:name?'其他':'足金999');
const result={nameType,customName:string(line.customName??(nameType==='其他'?name:''),'其他商品名称',60),unit,
quantity:unit==='g'?numeric(line.quantity,'商品克重',3):count(line.quantity,'商品件数'),
pocket:unit==='件'||['足银999','纯银925'].includes(nameType)?'':pick(line.pocket,['',...pocketKeys],'出库货盘',nameType==='足金999'?'现货':''),
payer:pick(line.payer,['owner','assistant','assistant2'],'货品成本付款人','owner'),pricingMode:unit==='件'?'manual':pick(line.pricingMode,['auto','manual'],'计价方式',line.sale!=null?'manual':'auto'),
goldPrice:numeric(line.goldPrice,'销售金价'),laborMode:pick(line.laborMode,['gram','piece'],'销售工费方式','gram'),laborRate:numeric(line.laborRate,'销售工费'),pieces:count(line.pieces??'1','计工费件数'),
priceNote:string(line.priceNote,'销售单价说明',100),sale:numeric(line.sale,'本行销售额'),baseSale:numeric(line.baseSale??line.sale,'商品基础金额')};
result.name=nameType==='其他'?result.customName:nameType;
const rawCharges=line.charges??[];if(!Array.isArray(rawCharges)||rawCharges.length>100)throw new Error('每行最多填写100项附加项目');
result.charges=rawCharges.map(rawCharge=>{
const c=object(rawCharge,'附加项目'),old=string(c.id,'附加项目标识',36);if(old&&(!uuid.test(old)||seen.has(old)))throw new Error('附加项目标识无效或重复');if(old)seen.add(old);
const name=string(c.name,'附加项目名称',40),nameType=pick(c.nameType,[...charges,'其他'],'附加项目',charges.includes(name)?name:name?'其他':'编绳');
const id=newId();if(old)ids.set(old,id);
const customName=string(c.customName??(nameType==='其他'?name:''),'附加项目名称',40),amount=numeric(c.amount,'附加金额');
const prices={};if(c.chargePrices!=null){object(c.chargePrices,'附加项目预设报价');for(const key of [...charges,'其他'])if(Object.hasOwn(c.chargePrices,key))prices[key]=numeric(c.chargePrices[key],'附加项目报价');}
return {id,nameType,customName,name:nameType==='其他'?customName:nameType,amount,chargePrices:{...prices,[nameType]:amount}};
});
if(line.costParts!=null){
object(line.costParts,'分项成本');const parts=Object.fromEntries(['material','labor','accessories','other'].map(key=>[key,numeric(line.costParts[key],'货品成本')]));
const material=object(line.costMaterial??{},'料费方式'),labor=object(line.costLabor??{},'进货工费方式');
const mode=pick(material.mode,['gram','total','pool'],'进货料费方式',unit==='g'&&parts.material===''?'gram':'total');
result.costParts=parts;result.costPayers={material:payer(line.costPayers?.material,result.payer),labor:payer(line.costPayers?.labor,result.payer)};
result.costMaterial={mode:unit==='件'?'total':mode,...(mode==='gram'?{rate:numeric(material.rate,'进货料价')}:{})};
result.costLabor={mode:unit==='件'?'total':pick(labor.mode,['gram','total'],'进货工费方式','total'),rate:numeric(labor.rate,'进货克工费')};
if(result.costMaterial.mode==='pool'){
if(['足银999','纯银925'].includes(nameType))throw new Error('银饰模板请手动填写料费');
parts.material='';result.materialPoolDraft={defaultDate:true,manual:manualMaterial(line.materialPoolDraft?.manual)};
}else if(line.costMaterialDraft){
const remembered=manualMaterial(line.costMaterialDraft,{mode:result.costMaterial.mode,rate:material.rate,total:parts.material,payer:result.costPayers.material});
result.costMaterialDraft={mode:remembered.mode,rate:remembered.rate,total:remembered.total,originalTotal:''};
}
}else if(Object.hasOwn(line,'cost'))result.cost=numeric(line.cost,'货品成本');
return result;
});
const fees=draft.fee_items??[];if(!Array.isArray(fees)||fees.length>6100)throw new Error('模板费用项目过多');
const cardExpenseIds=new Set(fees.filter(cardFee).map(fee=>fee.expense_id).filter(Boolean));
const keys=new Set(),items=fees.map(raw=>{
const fee=object(raw,'模板费用');if(cardFee(fee)||fee.expense_id&&cardExpenseIds.has(fee.expense_id))return null;
const old=string(fee.key,'费用标识',80);
if(!['shipping','box','certificate','braiding','sticker','other'].includes(old)&&! /^(charge|manual):[a-f0-9-]{36}$/.test(old))throw new Error('模板费用项目无效');
if(keys.has(old))throw new Error('模板费用项目不能重复');keys.add(old);
const linked=old.startsWith('charge:')?ids.get(old.slice(7)):null;if(old.startsWith('charge:')&&!linked)return null;
return {key:linked?'charge:'+linked:old==='shipping'?'shipping':'manual:'+newId(),note:string(fee.note,'费用名称',150),amount:numeric(fee.amount,'实际费用'),payer:pick(fee.payer,['owner','assistant','assistant2'],'费用付款人','assistant'),status:'estimated',edited:fee.edited!==false,...(linked?{sourceName:string(fee.sourceName||fee.note,'附加项目名称',40)}:{})};
}).filter(Boolean);
const preset={salesperson:string(draft.salesperson,'开单人',30),payment_account:pick(normalizeAccount(draft.payment_account),accounts,'收款账户','助理微信'),credit_card_fee_payer:pick(draft.credit_card_fee_payer,['owner','assistant','assistant2'],'信用卡手续费付款人','owner'),discount:numeric(draft.discount??'0','整单优惠'),note:string(draft.note,'客户单备注',240),fee_auto_initialized:true,lines,fee_items:Fees.sync(items,lines)};
if(JSON.stringify(preset).length>240000)throw new Error('模板内容过大,请减少商品或附加项目');return preset;
}
function apply(preset,{today,salesperson='',newId,pocketKeys}={}){
if(!/^\d{4}-\d{2}-\d{2}$/.test(today||'')||!Number.isFinite(Date.parse(today+'T00:00:00Z'))||new Date(today+'T00:00:00Z').toISOString().slice(0,10)!==today)throw new Error('未取得有效系统日期,请刷新后再套用模板。');
const draft=fromDraft(preset,{newId,pocketKeys});
for(const line of draft.lines)if(line.costMaterial?.mode==='pool'){line.costMaterial={mode:'pool',poolId:today};line.materialPoolDraft={...line.materialPoolDraft,poolId:today,defaultDate:true};}
return {...draft,date:today,fees_date:today,customer:'',salesperson:draft.salesperson||salesperson,rounding_mode:'yuan'};
}
return {fromDraft,apply};
});