'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.OrderCopy=api; })(typeof globalThis==='object'?globalThis:this,function(Fees,Cards){ const money=value=>value==null?'':(value/100).toFixed(2); const nonblank=value=>value!=null&&String(value).trim()!==''; 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:'); function inputs(order){ return {...order,rounding_mode:order.rounding_mode||'cent',discount:money(order.discount),fee_items:(order.fee_items||[]).map(item=>({...item,amount:money(item.amount)})),lines:order.lines.map(line=>({ ...line,quantity:line.unit==='g'?(line.quantity/1000).toFixed(3):line.quantity,sale:money(line.sale),baseSale:money(line.baseSale??line.sale),cost:money(line.cost), costMaterial:line.costMaterial?.mode==='pool'?{...line.costMaterial}:{mode:line.costMaterial?.mode||((line.unit||'g')==='g'&&line.costParts?.material==null?'gram':'total'),...(line.costMaterial?.mode==='gram'?{rate:money(line.costMaterial.rate)}:{})}, costLabor:{mode:line.costLabor?.mode||'total',rate:money(line.costLabor?.rate)}, charges:(line.charges||[]).map(charge=>({...charge,amount:money(charge.amount)})), ...(line.pricingMode==='auto'?{goldPrice:money(line.goldPrice),laborRate:money(line.laborRate)}:{}), ...(line.costParts?{costParts:Object.fromEntries(Object.entries(line.costParts).map(([key,value])=>[key,money(value)]))}:{}) }))}; } function copyFees(order,lines,chargeIds,newId){ const corrected=new Set((order.corrections||[]).filter(row=>row.type==='expense').map(row=>row.target)); const cardExpenseIds=new Set(order.fee_items.filter(cardFee).map(fee=>fee.expense_id).filter(Boolean)); const positives=order.expenses.filter(row=>row.amount>0&&!String(row.note||'').startsWith('更正冲回:')&&!cardFee(row)&&!cardExpenseIds.has(row.id)); const active=positives.filter(row=>!corrected.has(row.id)),matched=new Set(),used=new Set(),items=[]; const pending=new Set((order.pendingFees||[]).map(item=>item.key)); const same=(expense,fee)=>expense.amount===fee.amount&&expense.payer===fee.payer&&Fees.normalize(expense.note)===Fees.normalize(fee.note); for(const fee of order.fee_items){ if(cardFee(fee)||fee.expense_id&&cardExpenseIds.has(fee.expense_id))continue; const linked=chargeIds.get(String(fee.key).replace(/^charge:/,'')); const key=linked?'charge:'+linked:fee.key==='shipping'?'shipping':'manual:'+newId(); let amount=fee.amount,payer=fee.payer; // 已入账模板仍保留旧金额;实际流水和更正结果才是当前支出的依据。 if(fee.status!=='estimated'&&!pending.has(fee.key)){ const source=positives.find(expense=>!matched.has(expense.id)&&same(expense,fee)); if(source){matched.add(source.id);if(corrected.has(source.id))amount=0;else used.add(source.id);} else amount=0; } items.push({key,note:fee.note,amount:money(amount),payer,status:'estimated',edited:true,...(linked?{sourceName:fee.sourceName||fee.note}:{})}); } for(const expense of active){ if(used.has(expense.id))continue; const key=Fees.normalize(expense.note)==='快递'&&!items.some(item=>item.key==='shipping')?'shipping':'manual:'+newId(); items.push({key,note:expense.note,amount:money(expense.amount),payer:expense.payer,status:'estimated',edited:true}); } const completed=['delivered','returned','cancelled'].includes(order.status); for(const [index,line] of lines.entries())for(const charge of line.charges){ if(charge.costRemoved===true)continue; const shipping=Fees.normalize(charge.name)==='快递',key=shipping?'shipping':'charge:'+charge.id; if(items.some(item=>item.key===key))continue; const found=items.find(item=>item.key.startsWith('manual:')&&Fees.normalize(item.note)===Fees.normalize(charge.name)); if(found)found.key=key; else items.push({key,note:shipping?'快递费':charge.name,amount:completed?'0.00':'',payer:Fees.normalize(charge.name)==='包装'?'owner':'assistant',status:'estimated',edited:true}); if(!shipping)Object.assign(items.find(item=>item.key===key),{sourceName:charge.name,lineNumber:index+1}); } // 所有项都标记手填,后续同步项目名称时不重新套用默认成本。 return Fees.sync(items,lines); } function fromOrder(order,{today,newId=()=>globalThis.crypto.randomUUID()}={}){ if(!/^\d{4}-\d{2}-\d{2}$/.test(today||''))throw new Error('未取得系统日期,请刷新后再复制。'); if(!order||!Array.isArray(order.lines)||!Array.isArray(order.fee_items)||!Array.isArray(order.expenses))throw new Error('订单详情未完整返回,请重新读取后再复制。'); const source=inputs(order),chargeIds=new Map(),locked=!!order.price_lock_id||order.lines.some(line=>line.materialAllocations?.length); const lines=source.lines.map(line=>{ const result=Object.fromEntries(['name','nameType','customName','unit','quantity','pocket','stockCount','payer','pricingMode','goldPrice','laborMode','laborRate','pieces','priceNote','sale','baseSale'].filter(key=>Object.hasOwn(line,key)).map(key=>[key,line[key]])); result.charges=line.charges.map(charge=>{const id=newId();if(charge.id)chargeIds.set(charge.id,id);return {id,name:charge.name,amount:charge.amount,...(charge.costRemoved===true?{costRemoved:true}:{})};}); if(line.costParts){ result.costParts={...line.costParts};result.costMaterial={...line.costMaterial};result.costLabor={...line.costLabor}; result.costPayers={material:line.costPayers?.material??line.payer??'owner',labor:line.costPayers?.labor??line.payer??'owner'}; if(line.costMaterial?.mode==='pool'){ // 同日池随新业务日期走;已经跨日选用的旧池保留选择,耗用快照必须重读。 const defaultDate=line.costMaterial.poolId===order.date,poolId=defaultDate?today:line.costMaterial.poolId; result.costMaterial={mode:'pool',poolId};result.costParts.material=''; result.materialPoolDraft={poolId,defaultDate,manual:{mode:'gram',rate:'',total:'',originalTotal:'',payer:result.costPayers.material}}; } if(locked){ result.costParts.material='';result.costMaterial={mode:'total'};result.costPayers.material='';delete result.materialPoolDraft; } }else result.cost=line.cost; return result; }); return {date:today,fees_date:today,customer:'',salesperson:source.salesperson||'',payment_account:normalizeAccount(source.payment_account||'助理微信'),discount:source.discount,note:locked?String(source.note||'').replace(/;?锁价单 [^;]*;按原锁定金价 [^;]*元\/克结算$/,''):source.note||'',rounding_mode:'yuan', copy_kind:locked?'price-lock':'ordinary',fee_auto_initialized:true,lines,fee_items:copyFees(order,lines,chargeIds,newId)}; } function hasDraftContent(draft,{today,salesperson}={}){ if(!draft||typeof draft!=='object'||!Array.isArray(draft.lines))return !!draft; if(draft.id||draft.copy_kind||nonblank(draft.customer)||nonblank(draft.note)||nonblank(draft.internal_note)||Number(draft.discount)||draft.date&&today&&draft.date!==today||draft.salesperson&&salesperson&&draft.salesperson!==salesperson||draft.payment_account&&draft.payment_account!=='助理微信')return true; if((draft.fee_items||[]).some(item=>item.key!=='shipping'||item.edited||item.status!=='estimated'||Number(item.amount)!==6||item.payer!=='assistant'))return true; return draft.lines.length!==1||draft.lines.some(line=>{ if(line.charges?.length||line.name&&line.name!=='足金999'||line.customName||line.unit&&line.unit!=='g'||line.pocket!=null&&line.pocket!=='现货'||line.payer&&line.payer!=='owner'||line.costMaterial?.mode==='pool')return true; if(['quantity','stockCount','sale','baseSale','goldPrice','laborRate','priceNote','cost'].some(key=>nonblank(line[key])))return true; if(['material','labor'].some(key=>nonblank(line.costParts?.[key])||nonblank(line[key==='material'?'costMaterial':'costLabor']?.rate)||line.costPayers?.[key]&&line.costPayers[key]!=='owner'))return true; return ['accessories','other'].some(key=>Number(line.costParts?.[key])); }); } return {inputs,fromOrder,hasDraftContent}; });