第4项:对页面、表单及两版共享规则启用严格类型检查

This commit is contained in:
黄健铭 committed 2026-12-05 08:01:17 -08:00
1 parent 389952f31c
commit f570929cfe
77 files changed
+7629 -2981

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
import{n as e,t}from"./rolldown-runtime-Dl_DZoUm.js";import{A as n,B as r,C as i,D as a,E as o,F as s,H as c,I as l,L as u,M as d,N as f,O as p,P as m,R as h,S as g,T as _,_ as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L,v as R,w as z,x as B,y as V,z as H}from"./antd-Bh8pVx-K.js";import{n as U,t as ee}from"./react-BvkltZ40.js";var W=t(((e,t,n)=>{var r;(function(n,i){typeof e==`object`&&t!==void 0?t.exports=i():typeof r==`function`&&r.amd?r(i):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=i()})(n,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,l),a=n-i<0,o=t.clone().add(r+(a?-1:1),l);return+(-(r+(n-i)/(a?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:l,y:d,w:c,d:s,D:f,h:o,m:a,s:i,ms:r,Q:u}[e]||String(e||``).toLowerCase().replace(/s$/,``)},u:function(e){return e===void 0}},y=`en`,b={};b[y]=g;var x=`$isDayjsObject`,S=function(e){return e instanceof E||!(!e||!e[x])},C=function e(t,n,r){var i;if(!t)return y;if(typeof t==`string`){var a=t.toLowerCase();b[a]&&(i=a),n&&(b[a]=n,i=a);var o=t.split(`-`);if(!i&&o.length>1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e)<this.startOf(t)},_.isBefore=function(e,t){return this.endOf(t)<w(e)},_.$g=function(e,t,n){return T.u(e)?this[t]:this.set(n,e)},_.unix=function(){return Math.floor(this.valueOf()/1e3)},_.valueOf=function(){return this.$d.getTime()},_.startOf=function(e,t){var n=this,r=!!T.u(t)||t,u=T.p(e),p=function(e,t){var i=T.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(s)},m=function(e,t){return T.w(n.toDate()[e].apply(n.toDate(`s`),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},h=this.$W,g=this.$M,_=this.$D,v=`set`+(this.$u?`UTC`:``);switch(u){case d:return r?p(1,0):p(31,11);case l:return r?p(1,g):p(0,g+1);case c:var y=this.$locale().weekStart||0,b=(h<y?h+7:h)-y;return p(r?_-b:_+(6-b),g);case s:case f:return m(v+`Hours`,0);case o:return m(v+`Minutes`,1);case a:return m(v+`Seconds`,2);case i:return m(v+`Milliseconds`,3);default:return this.clone()}},_.endOf=function(e){return this.startOf(e,!1)},_.$set=function(e,t){var n,c=T.p(e),u=`set`+(this.$u?`UTC`:``),p=(n={},n[s]=u+`Date`,n[f]=u+`Date`,n[l]=u+`Month`,n[d]=u+`FullYear`,n[o]=u+`Hours`,n[a]=u+`Minutes`,n[i]=u+`Seconds`,n[r]=u+`Milliseconds`,n)[c],m=c===s?this.$D+(t-this.$W):t;if(c===l||c===d){var h=this.clone().set(f,1);h.$d[p](m),h.init(),this.$d=h.set(f,Math.min(this.$D,h.daysInMonth())).$d}else p&&this.$d[p](m);return this.init(),this},_.set=function(e,t){return this.clone().$set(e,t)},_.get=function(e){return this[T.p(e)]()},_.add=function(r,u){var f,p=this;r=Number(r);var m=T.p(u),h=function(e){var t=w(p);return T.w(t.date(t.date()+Math.round(e*r)),p)};if(m===l)return this.set(l,this.$M+r);if(m===d)return this.set(d,this.$y+r);if(m===s)return h(1);if(m===c)reLine truncated
0.58×(822+45)+55=558
769+558=1327`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&r.trim()&&(e.preventDefault(),s(!1))}}),(0,q.jsxs)(_,{wrap:!0,style:{marginTop:8},children:[(0,q.jsx)(l,{type:`primary`,onClick:()=>s(!1),children:`识别并预填`}),a?.kind===`warning`&&(0,q.jsx)(l,{onClick:()=>s(!0),children:`按计算金额预填`}),r&&(0,q.jsx)(l,{onClick:()=>{i(``),o(null)},children:`清空公式`})]}),(0,q.jsx)(`p`,{className:`small muted`,children:`括号内是克工费;金价乘克重后加的是一件工费,再加的金额记为附加费。合计行只校验,不增加商品。客户、货盘及内部成本仍按实际填写。`}),a&&(0,q.jsx)(h,{role:`status`,type:a.kind===`note`?`success`:a.kind,message:a.title||(a.kind===`error`?a.lines[0]:``),description:a.kind===`error`?void 0:(0,q.jsx)(`div`,{children:a.lines.filter(Boolean).map((e,t)=>(0,q.jsx)(`p`,{children:e},t))})})]})}function $t({order:e,error:t,onRetry:r,onPreview:i,onNew:a}){let{message:o}=s.useApp(),[c,u]=(0,G.useState)(!1),f=e.total!==void 0;async function p(){if(e.paper_number)try{await navigator.clipboard.writeText(e.paper_number),u(!0),o.success(`已复制纸单号 `+e.paper_number),window.setTimeout(()=>u(!1),1800)}catch{u(!1),o.info(`请手动选择纸单号复制`)}}return(0,q.jsx)(`div`,{className:`issued-page`,children:(0,q.jsx)(O,{className:`issued-card`,children:(0,q.jsx)(w,{status:`success`,title:`销售单据已生成`,subTitle:f?e.materialCostPending?`收款、费用和出库已记账;料费待补,补足购料后自动核算利润。`:`收款、费用、出库和利润已记账。`:t||`正在读取已生成的销售单…`,extra:(0,q.jsxs)(_,{direction:`vertical`,size:`large`,style:{width:`100%`},children:[f&&(0,q.jsxs)(`dl`,{className:`issued-summary`,"data-testid":`issued-summary`,children:[(0,q.jsxs)(`div`,{className:`issued-item`,children:[(0,q.jsx)(`dt`,{children:(0,q.jsx)(S.Text,{type:`secondary`,children:`纸单号`})}),(0,q.jsxs)(`dd`,{className:`issued-value-row`,children:[(0,q.jsx)(`span`,{className:`issued-value num`,"data-testid":`issued-paper-number`,children:e.paper_number||`未分配`}),e.paper_number&&(0,q.jsx)(d,{title:c?`已复制`:`复制纸单号`,children:(0,q.jsx)(l,{type:`text`,size:`small`,className:`issued-copy-btn`,"aria-label":`复制纸单号`,icon:c?(0,q.jsx)(m,{}):(0,q.jsx)(C,{}),onClick:()=>void p()})})]})]}),(0,q.jsxs)(`div`,{className:`issued-item`,children:[(0,q.jsx)(`dt`,{children:(0,q.jsx)(S.Text,{type:`secondary`,children:`成交合计`})}),(0,q.jsx)(`dd`,{className:`issued-value issued-total num`,"data-testid":`issued-total`,children:dt(e.total??null,e.rounding_mode||`cent`)})]}),e.customer&&(0,q.jsxs)(`div`,{className:`issued-item`,children:[(0,q.jsx)(`dt`,{children:(0,q.jsx)(S.Text,{type:`secondary`,children:`客户`})}),(0,q.jsx)(`dd`,{className:`issued-value small`,children:e.customer})]})]}),(0,q.jsxs)(`div`,{className:`issued-actions`,children:[(0,q.jsx)(l,{type:`primary`,size:`large`,icon:(0,q.jsx)(P,{}),href:`/print/`+encodeURIComponent(e.id)+`?mode=full`,onClick:()=>{i().catch(e=>o.error(e.message))},target:`_blank`,rel:`noopener`,"data-action":`print-preview`,children:`打开打印预览`}),(0,q.jsx)(l,{size:`large`,icon:(0,q.jsx)(n,{}),onClick:a,"data-action":`new-order`,children:`开始新的一单`}),!f&&(0,q.jsx)(l,{size:`large`,onClick:r,children:`重新读取订单`})]}),(0,q.jsx)(l,{href:be(`orders`)+`?order=`+encodeURIComponent(e.id),onClick:t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),K(`orders`,{search:`?order=`+encodeURIComponent(e.id)}))},type:`link`,icon:(0,q.jsx)(z,{}),children:`查看订单详情`})]})})})})}function en(e){let{client:t,state:n}=e,r=Ae(`draft`),[i,a]=(0,G.useState)(r?null:{draft:oe(window.localStorage,n.user.id),note:``});return(0,G.useEffect)(()=>{if(!r)return;let e=!0;return(async()=>{try{if(n.user.role!==`owner`)throw Error(`已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。`);let i=await t.api(`/api/orders/`+encodeURIComponent(r));if(i.status!==`draft`)throw Error(`这张订单不是未开单的旧草稿,请在订单页查看。`);e&&a({draft:Y.draftInputs(i),note:`正在继续填写旧草稿,生成销售单据后完成记账。`})}catch(t){e&&a({draft:oe(window.localStorage,n.user.id),note:`旧草稿未能打开:`+t.message})}})(),()=>{e=!1}},[t,r,n.user.id,n.user.role]),i?(0,q.jsx)(tn,{...e,initialDraft:i.draft,initialNote:i.note}):(0,q.jsx)(`div`,{className:`page-loading`,children:(0,q.jsx)(b,{tip:`正在读取旧草稿…`,children:(0,q.jsx)(`div`,{style:{height:60}})})})}function tn({client:e,state:t,session:n,refreshState:r,onAccountChanged:i,onRecoverOther:a,initialDraft:o,initialNote:c}){let{message:u}=s.useApp();je(e);let{store:d,update:f,reset:p,ctx:m,poolError:g,loadPools:_}=_t({client:e,state:t,session:n,initialDraft:o}),{form:v,summary:y}=d,[b,C]=(0,G.useState)(``),[w,T]=(0,G.useState)(!1),[E,D]=(0,G.useState)(null),O=E!==null,k Line truncated
`),u=e=>e?.exchange?.fee_items.map(e=>`${e.note}:${e.amount}元 · ${o(e.payer)}付款`).join(`
`)||`无`,d=e=>e?.exchange?.charges.map(e=>`${e.name}:${e.amount}元`).join(`
`)||`无`,f=n.exchange||{},p=r?.exchange||{},m=e=>e?.mode===`pool`?`料池 `+e.poolId:e?`手填 `+e.rate+`元/克`:`无补金差重`,h=e=>e?e.mode===`gram`?e.rate+`元/克`:e.amount+`元总工费`:`未提供`;if(i.push(a(`业务日期`,n.date,r?.date||`取消原记录`),a(`客户`,n.customer,r?.customer),a(`开单人`,n.salesperson,r?.salesperson),a(`归属`,o(n.member),r?o(r.member):`沿用原身份留档`),a(`旧料逐项称重`,l(n),r?l(r):`冲正原库存及关联购料`),a(`旧料入库货盘`,s(n.old_pocket??`回收旧料`),r?s(r.old_pocket??`回收旧料`):`冲回原入库货盘`),a(`旧料入库数量(对)`,Tn(n.old_stock_count==null?null:Number(n.old_stock_count)),r?Tn(r.old_stock_count==null?null:Number(r.old_stock_count)):`冲回原入库数量`),a(`回收单价(元/克)`,n.buy_rate,r?.buy_rate),a(`回收结算额(元)`,n.buy_total,r?.buy_total),a(`实际收付款账户`,c(n.payment_account),r?c(r.payment_account):`冲正原收付记录`),a(`付款人`,o(n.payer),r?o(r.payer):`原付款流水保留`),a(`备注`,n.note,r?.note)),(n.surplus_mode===`deposit`||r?.surplus_mode===`deposit`)&&i.push(a(`余料处理`,n.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`,r?r.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`:`撤回本单寄存余料`)),(n.old_source===`deposit`||r?.old_source===`deposit`)&&i.push(a(`使用客户寄存料`,n.old_source===`deposit`?n.deposit_id+` · `+n.deposit_weight+`g`:`本次交来旧料`,r?.old_source===`deposit`?r.deposit_id+` · `+r.deposit_weight+`g`:r?`本次交来旧料`:`退回寄存账户`)),n.exchange?.items||r?.exchange?.items){let e=e=>(e?.exchange?.items||[]).map((e,t)=>t+1+` · `+e.exchange.name+(e.old_source===`deposit`?` · 寄存记录 `+e.deposit_id+` 使用 `+e.deposit_weight+`g`:``)+(e.surplus_mode===`deposit`?` · 余料寄存,暂不结算`:``)+` · 旧料 `+e.old_lines.map(e=>e.melted_weight+`g × `+e.purity+`%`).join(`+`)+` 入`+s(e.old_pocket)+` · 新货 `+e.exchange.quantity+`g `+(s(e.exchange.pocket)||`外配`)+` · 补金 `+e.exchange.gold_price+`元/g · 折旧 `+e.exchange.depreciation_weight+`g × `+e.exchange.depreciation_rate+`元/g · 回收 `+e.buy_rate+`元/g,`+e.buy_total+`元 · 料费 `+JSON.stringify(e.exchange.cost_material)+` · 料费付款 `+o(e.exchange.cost_material_payer)+` · 进货工费 `+JSON.stringify(e.exchange.cost_labor)+`,`+o(e.exchange.cost_labor_payer)).join(`;`);i.push(a(`逐件置换完整资料`,e(n),r?e(r):`全部冲回`))}if(n.exchange?.products||r?.exchange?.products){let e=e=>(e?.products??(e?[e]:[])).map((e,t)=>t+1+` · `+e.name+` · `+e.quantity+`g · `+(s(e.pocket)||`外配`)+` · 销售工费 `+e.labor_rate+(e.labor_mode===`total`?`元`:`元/克`)+` · 进货工费 `+(e.cost_labor?.rate??e.cost_labor?.amount??`待补`)+` · `+o(e.cost_labor_payer)+(e.stockCount==null?``:` · `+e.stockCount+`对`)).join(`;`);i.push(a(`逐件置换商品`,e(n.exchange),r?e(r.exchange):`冲回全部新货出库`))}n.mode===`exchange`&&i.push(a(`置换新货`,f.name,p.name),a(`新货克重(g)`,f.quantity,p.quantity),a(`实际货盘`,s(f.pocket)||`外配`,r?s(p.pocket)||`外配`:`冲回原出库货盘`),a(`出库数量(对)`,Tn(f.stockCount==null?null:Number(f.stockCount)),Tn(p.stockCount==null?null:Number(p.stockCount))),a(`销售金价(元/克)`,f.gold_price,p.gold_price),a(`销售工费`,f.labor_rate+`元/`+(f.labor_mode===`gram`?`克`:`总额`),r?p.labor_rate+`元/`+(p.labor_mode===`gram`?`克`:`总额`):`取消`),a(`折旧计费克重/单价`,f.depreciation_weight+`g × `+f.depreciation_rate+`元/克`,r?p.depreciation_weight+`g × `+p.depreciation_rate+`元/克`:`取消`),a(`附加收费`,d(n),r?d(r):`取消`),a(`优惠(元)`,f.discount,p.discount),a(`取整方式`,f.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`,r?p.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`:`取消`),a(`补金差重进货来源`,m(f.cost_material),r?m(p.cost_material):`释放原耗用`),a(`料费付款人`,o(f.cost_material_payer),r?o(p.cost_material_payer):`原来源留档`),a(`进货工费`,h(f.cost_labor),r?h(p.cost_labor):`取消`),a(`工费付款人`,o(f.cost_labor_payer),r?o(p.cost_labor_payer):`原来源留档`),a(`实际费用`,u(n),r?u(r):`冲正原费用`));let g=e.summary.before||{},_=e.summary.after||{};return i.push(...[[`实际收客户`,`cashReceipt`],[`实际付客户`,`cashPayment`],[`购料成本`,`purchaseAmount`],[`订单货品成本`,`goodsCost`],[`实际费用`,`directCost`],[`原账利润`,`profit`]].map(([e,t])=>a(e,g[t]==null?`待核实`:`¥`+ut(g[t]),r?_[t]==null?`待核实`:`¥`+ut(_[t]):`取消后冲正`))),(0,q.jsxs)(q.Fragment,{children:[e.summary.legacyCountNotice&&(0,q.jsxs)(`p`,{children:[e.summary.legacyCountNotice,e.summary.legacyCountVerified&&`(申请人已确认)`]}),(0,q.jsx)(`div`,{className:`table-wrap`,children:(0,q.jsxs)(`table`,{"aria-label":`回收更正原值与申请值`,children:[(0,q.jsx) Line truncated
`)||`无已记费用`}function N(e){let t=new Set((e.corrections||[]).filter(e=>e.type===`payment`).map(e=>e.target));return e.payments.filter(e=>e.amount>0&&!t.has(e.id)).map(e=>`${e.date} · ${e.kind===`receipt`?`客户收款`:`客户退款`}\n${H(e.amount)} · ${e.account?fe(e.account):`账户未提供`}`).join(`
`)||`无有效收退款`}function P(e,t,n=`锁价购料成本`){if(!e.priceLockCosts&&!t.priceLockCosts)return``;if(e.priceLockCosts?.lines||t.priceLockCosts?.lines){let n=e.priceLockCosts||{},r=t.priceLockCosts||{},i=n.lines||r.lines;return G.Children.toArray(i.map((e,t)=>{let i=n.lines?.find(t=>t.lineId===e.lineId)||{},a=r.lines?.find(t=>t.lineId===e.lineId)||{};return P({priceLockCosts:{...i,date:n.date}},{priceLockCosts:{...a,date:r.date}},`商品 `+(t+1)+` · 锁价购料成本`)}))}let r=e.priceLockCosts||{},i=t.priceLockCosts||{},a=e=>e===`pool`?`原锁料池`:e===`manual`?`手填原锁料价`:`未提供`;return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`tr`,{className:`change-section-row`,children:(0,q.jsx)(`th`,{colSpan:`3`,scope:`colgroup`,children:n})}),I(`原锁日期`,r.date,i.date),I(`原锁料费来源`,a(r.materialSource),a(i.materialSource)),I(`原锁进货料价(每克)`,H(r.buyRate),H(i.buyRate)),I(`原锁料费付款人`,r.materialSource===`pool`?`按原锁料池分摊`:V(r.buyPayer),i.materialSource===`pool`?`按原锁料池分摊`:V(i.buyPayer)),I(`原锁整批料费`,H(r.materialAmount),H(i.materialAmount)),I(`补重进货料价(每克)`,H(r.extraRate),H(i.extraRate)),I(`补重料费付款人`,r.extraPayer?V(r.extraPayer):`无补重`,i.extraPayer?V(i.extraPayer):`无补重`)]})}function F(e,t){if(!e)return`无此商品`;let n=H;if(t===`name`)return`${e.name||`未填写`}${e.priceNote?`
`+e.priceNote:``}`;if(t===`code`)return e.code||`未填写`;if(t===`quantity`)return e.unit===`g`?Oe(e.quantity)+`g`:String(e.quantity)+`件`;if(t===`sale`)return n(e.sale);if(t===`pricing`)return e.goldPrice==null?`手填基础金额 ${n(e.baseSale??e.sale)}`:`销售金价 ${n(e.goldPrice)}/克\n${e.laborMode===`gram`?`销售克工费`:`销售件工费`} ${n(e.laborRate)}${e.laborMode===`gram`?`/克`:`/件`}\n件数 ${e.pieces??`未填写`}`;if(t===`stockCount`)return Number.isSafeInteger(e.stockCount)||W(e.pocket)?ee(e.stockCount):`不记录对数`;if(t===`pocket`)return te(e.pocket)||`外配/不扣黄金`;if(t===`charges`)return e.charges?.length?e.charges.map(e=>`${e.name}:${n(e.amount)}`).join(`
`):`无附加收费`;if(t===`cost`)return n(e.cost);if(t===`material`){let t=e.costMaterial;return t?.mode===`pool`?`每日购料:${t.poolId}\n本行料费:${n(e.costParts?.material)}${e.materialPool?.allocations?.length?`
`+e.materialPool.allocations.map(e=>V(e.payer)+` `+n(e.amount)).join(`;`):e.costParts?.material==null?`
待补采购后分摊`:``}`:`${t?.mode===`gram`?`每克料价 `+n(t.rate)+`/克`:`料费总额`}\n${n(e.costParts?.material)}`}return t===`labor`?`${e.costLabor?.mode===`gram`?`进货克工费 `+n(e.costLabor.rate)+`/克`:`进货总工费`}\n${n(e.costParts?.labor)}`:t===`extra`?e.costParts?`配件 ${n(e.costParts.accessories)}\n其他 ${n(e.costParts.other)}`:`原货品成本未分项`:t===`payers`?`料费:${e.costMaterial?.mode===`pool`?e.materialPool?.allocations?.map(e=>V(e.payer)+` `+n(e.amount)).join(`;`)||`按真实采购分摊`:V(e.costPayers?.material??e.payer)}\n进货工费:${V(e.costPayers?.labor??e.payer)}\n配件及其他:${V(e.payer)}`:``}function I(e,t,n){let r=String(t??``)!==String(n??``);return(0,q.jsxs)(`tr`,{...r?{className:`order-change-modified`}:{},children:[(0,q.jsxs)(`th`,{scope:`row`,children:[e,r?(0,q.jsx)(`span`,{className:`change-mark`,children:`已修改`}):``]}),(0,q.jsx)(`td`,{children:B(t)}),(0,q.jsx)(`td`,{children:B(n)})]})}function L(e){if(e===void 0)return[];let t=e=>e===null||Number.isSafeInteger(e)&&e>=0,n=e=>e&&t(e.materialAmount)&&[`usedMaterialAmount`,`leftoverCost`].every(n=>!Object.hasOwn(e,n)||t(e[n]))&&Array.isArray(e.allocations)&&e.allocations.every(e=>Be().includes(e.payer)&&Number.isSafeInteger(e.amount)&&e.amount>=0)&&(e.materialAmount===null||e.allocations.reduce((e,t)=>e+t.amount,0)===e.materialAmount);if(!Array.isArray(e)||!e.every(e=>e&&typeof e.id==`string`&&e.id&&je(e.date)&&n(e.before)&&n(e.after)))throw Error(`关联锁价单的成本影响未完整返回,请重新读取后复核。`);return e}function R(e,t){let n=t=>t&&t.id===e.order_id&&Number.isSafeInteger(t.total)&&Array.isArray(t.lines)&&Array.isArray(t.expenses)&&Array.isArray(t.payments),r=e=>e===null||Number.isSafeInteger(e);if(!e||typeof e.id!=`string`||!e.id||typeof e.order_id!=`string`||t&&e.order_id!==t||!Object.hasOwn(oe,e.status)||!Number.isSafeInteger(e.order_revision)||typeof e.reason!=`string`||typeof e.requester_name!=`string`||typeof e.created!=`string`||typeof e.stale!=`boolean`||typeof e.canApprove!=`boolean`||!n(e.before)||!n(e.after)||![`before`,`after`].every(t=>e.summary?.[t]&&[`total`,`netReceived`,`directCost`].every(n=>Number.isSafeInteger(e.summary[t][n]))&&[`goodsCost`,`profit`,`settlementDue`].every(n=>r(e.summary[t][n]))))throw Error(`修改申请资料未完整返回,请重新读取订单后复核。`);if(e.relatedOrders!==void 0){if(!Array.isArray(e.relatedOrders))throw Error(`关联订单的修改影响未完整返回,请重新读取后复核。`);e.relatedOrders.forEach(t=>R({...e,order_id:t.id,before:t.before,after:t.after,summary:t.summary,relatedOrders:[]}))}if(L(e.relatedPriceLocks),e.action!==void 0&&!Object.hasOwn(se,e.action))throw Error(`变更申请类型未完整返回,请重新读取后复核。`);let i=e.summary.inventory;if(i!==void 0&&(!i||![`before`,`after`,`changes`].every(e=>Array.isArray(i[e])&&i[e].every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))))throw Error(`变更申请库存摘要未完整返回,请重新读取后复核。`);return e}function z(e){let t=R(e),n=t.before,r=t.after,i=(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(q.Fragment,{children:[(0,q.jsxs)(q.Fragment,{children:[G.Children.toArray([[`业务日期`,`date`],[`客户称呼/代号`,`customer`],[`开单人`,`salesperson`],[`收款方式与收款人`,`payment_account`],[`客户单备注`,`note`],[`内部备注(客户不可见)`,`internal_note`]].map(([e,t])=>I(e,t===`payment_account`?fe(n[t]):n[t],t===`payment_account`?fe(r[t]):r[t]))),I(`成交取整方式`,n.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`,r.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`)]}),I(`新增费用默认支付日期`,n.fees_date||n.date,r.fees_date||r.date)]}),I(`交付日期`,n.delivered_date,r.delivered_date)]}),a=G.Children.toArray([[`成交金额`,`total`],[`收款净额`,`netReceived`],[`货品成本`,`goodsCost`],[`实际费用合计`,`directCost`],[`利润`,`profit`],[`双方待结净额`,`settlementDue`]].map(([e,n])=>I(e,H(t.summary.before[n]),H(t.summary.after[n])))),o=G.Children.toArray(Array.from({length:Math.max(n.lines.length,r.lines.length)},(e,t)=>(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(`tr`,{className:`change-section-row`,children:(0,q.jsxs)(`th`,{colSpan:`3`,scope:`colgroup`,children:[`商品 `,t+1]})}),G.Children.toArray([[`商品与销售计价说明`,`name`],[`商品编号`,`code`],[`克重/数量`,`quantity`],[`销售金价、工费与件数`,`pricing`],[`成交金额(含附加收费)`,`sale`],[`客户附加收费`,`charges`],[`货盘`,`pocket`],[`出库数量(对)`,`stockCount`],[`货品成本合计`,`cost`],[`进货料价与料费`,`material`],[`进货工费`,`labor`],[`其他货品成本`,`extra`],[`成本付款人`,`payers`]].map(([e,i])=>I(e,F(n.lines[t],i),F(r.lines[t],i))))]}))),s=G.Children.toArray((t.relatedOrders||[]).map(e=>(0,q.jsxs)(`section`,{classNameLine truncated
`).map((e,t)=>(0,q.jsxs)(G.Fragment,{children:[t>0&&(0,q.jsx)(`br`,{}),e]},t))}function V(e){return e?ze(e):`待补齐`}function H(e){return e==null?`待补齐`:`¥`+He(e)}function U(e){try{return H(J.cents(e))}catch{return`金额未提供`}}function ee(e,{signed:t=!1,unknown:n=`未记录对数`}={}){return Number.isSafeInteger(e)?(t&&e>0?`+`:``)+e+`对`:n}function W(t){return!!t&&e?.pocketCatalog?.some(e=>e.key===t&&e.countUnit===`pair`)===!0}function te(t){return e?.pocketCatalog?.find(e=>e.key===t)?.name||String(t??``)}function ne(e){if(!e||!Array.isArray(e.lines)||!e.lines.length||!e.lines.every(e=>[`quantity`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`].every(t=>Number.isSafeInteger(e[t])))||!e.summary||![`refundAmount`,`retainedAmount`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`,`directCost`,`profit`,`profitAdjustment`].every(t=>Number.isSafeInteger(e.summary[t])))throw Error(`售后核算资料未完整返回,请重新读取订单。`);return e}function re(e,{preview:t=!1}={}){let n=ne(e),r=n.summary,i=e=>`¥`+He(e),a=[[`实际退款`,r.refundAmount],[`扣留客户款`,r.retainedAmount],[`回料池原料成本`,r.materialReturnedCost],[`现货保留工费`,r.laborRestockedCost],[`本单货品成本损失`,r.costLoss],[`售后最终利润`,r.profit],[`本次售后利润调整`,r.profitAdjustment]];return(0,q.jsxs)(`section`,{className:`order-after-sale-summary`+(t?` is-preview`:``),"aria-label":t?`售后核对预览`:`已保存售后详情`,children:[(0,q.jsxs)(`div`,{className:`panel-title`,children:[(0,q.jsx)(`h3`,{children:t?`售后核对预览`:`售后处理结果`}),(0,q.jsx)(`span`,{className:`badge`,children:t?`尚未保存`:`已记账`})]}),(0,q.jsx)(`dl`,{className:`order-after-sale-totals`,children:G.Children.toArray(a.map(([e,t])=>(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`dt`,{children:e}),(0,q.jsx)(`dd`,{...t<0?{className:`danger-text`}:{},children:i(t)})]})))}),(0,q.jsx)(`div`,{className:`table-wrap`,children:(0,q.jsxs)(`table`,{"aria-label":`逐件售后回库与成本`,children:[(0,q.jsx)(`thead`,{children:(0,q.jsxs)(`tr`,{children:[(0,q.jsx)(`th`,{children:`商品与实际去向`}),(0,q.jsx)(`th`,{children:`实际退回`}),(0,q.jsx)(`th`,{children:`回料成本`}),(0,q.jsx)(`th`,{children:`保留工费`}),(0,q.jsx)(`th`,{children:`成本损失`})]})}),(0,q.jsx)(`tbody`,{children:G.Children.toArray(n.lines.map(e=>(0,q.jsxs)(`tr`,{children:[(0,q.jsxs)(`td`,{children:[e.name||`商品 `+(e.lineIndex+1),(0,q.jsxs)(`div`,{className:`small muted`,children:[te(e.pocket),` · `,e.disposition===`stock`?`完好现货`:`旧料/损坏`]})]}),(0,q.jsxs)(`td`,{children:[Oe(e.quantity),`g`,e.disposition===`stock`&&W(e.pocket)?(0,q.jsx)(`div`,{className:`small`,children:ee(e.stockCount)}):``]}),(0,q.jsx)(`td`,{children:i(e.materialReturnedCost)}),(0,q.jsx)(`td`,{children:i(e.laborRestockedCost)}),(0,q.jsx)(`td`,{children:i(e.costLoss)})]})))})]})}),(0,q.jsx)(`p`,{className:`small muted`,children:`实退材料按原成本回售后日料池,不新增采购付款。完好现货工费留在退回现货批次;旧料工费与未退回材料成本计损失。原单实际费用继续保留。`})]})}function ie(e){let t=e.action||`edit`,n=e.action_input||e.action_details||{};if(t===`edit`)return``;if(n.afterSale){let t=ve(e.after);return(0,q.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,q.jsx)(`h3`,{children:`本次售后申请`}),(0,q.jsxs)(`p`,{children:[`售后日期:`,n.date,` · 申请原因:`,e.reason]}),re(t,{preview:!0})]})}let r=[[`申请动作`,ce(e)],[`业务日期`,n.date||e.after.returned_date||e.after.date]];return n.amount!==void 0&&r.push([`本次金额`,U(n.amount)]),n.account&&r.push([`退款账户`,fe(n.account)]),n.payer&&r.push([`实际付款人`,V(n.payer)]),n.note&&r.push([`费用项目/说明`,n.note]),n.reference&&r.push([`退款凭据备注`,n.reference]),Array.isArray(n.returnCounts)&&r.push([`实际退回数量(对)`,n.returnCounts.map((e,t)=>`商品 `+(t+1)+`:`+ee(e==null?null:Number(e))).join(`
`)]),Array.isArray(n.returnPockets)&&r.push([`退货实物去向`,n.returnPockets.map((t,n)=>`${e.before.lines[n]?.name||`商品 `+(n+1)}:${te(t)||`退供应商/不留黄金货盘`}`).join(`
`)]),Array.isArray(n.fee_items)&&r.push([`本次旧费用`,n.fee_items.map(e=>`${e.note||`费用`}:${U(e.amount)} · ${V(e.payer)}支付`).join(`
`)]),(0,q.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,q.jsx)(`h3`,{children:`本次申请动作`}),(0,q.jsx)(`dl`,{className:`order-change-action-facts`,children:G.Children.toArray(r.map(([e,t])=>(0,q.jsxs)(`div`,{children:[(0,q.jsx)(`dt`,{children:e}),(0,q.jsx)(`dd`,{children:B(t)})]})))}),(0,q.jsx)(`p`,{className:`small muted`,children:`下方对照为服务器试算;批准后才登记这笔变更,不会由系统发起真实收款、退款或转账。`})]})}function ae(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let oe={pending:`待店主复核`,approved:`已同意变更`,rejected:`已驳回`},se={edit:`修改订单`,expense:`费用补记`,fees:`旧费用核实`,refund:`退款`,return:`退货`,cost:`成本补录`};function ce(e){return(e.action_input||e.action_details)?.afterSale?`处理订单售后`:e.action_label||se[e.action||`edit`]||`订单变更`}let le={pending:`待店主复核`,approved:`已同意取消`,rejected:`已驳回`};function ue(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let de=e=>Ie.accountIdentity(Be(),e);function fe(e){let t=de(e);return t?ze(t.member)+t.channel:e}function pe(e){if(!e||![`total`,`netReceived`,`directCost`].every(t=>Number.isSafeInteger(e[t]))||![`goodsCost`,`profit`,`settlementDue`].every(t=>e[t]===null||Number.isSafeInteger(e[t]))||!Array.isArray(e.inventory)||!e.inventory.every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))throw Error(`取消撤销摘要未完整返回,请重新读取订单。`);return e}function me(e=n){let t=Ee(e)?.data;if(!t?.eligible||t.pending||t.directToday!==!0||!/^\d{4}-\d{2}-\d{2}$/.test(t.directActionDate||``)||e.date!==t.directActionDate||e.price_lock_id||![`draft`,`confirmed`,`delivered`].includes(e.status))return!1;try{return pe(t.summary),!0}catch{return!1}}function he(t,r=e.today,i=n){let a=Ce(i)?.data;return[`expense`,`fees`,`refund`,`return`].includes(t)&&!!a&&!a.pending&&/^\d{4}-\d{2}-\d{2}$/.test(a.directActionDate||``)&&a.actions?.[t]?.directToday===!0&&i.date===a.directActionDate&&r===a.directActionDate&&!(o.action===t&&o.forceApproval)}function ge(t){return e.user.role===`assistant`&&[`expense`,`fees`,`refund`,`return`,`cost`].includes(t)}function _e(t,n=e.today){return ge(t)&&!he(t,n)}function ve(e){return e?.orderAfterSale||null}function ye(){return t?.user?.id||``}function be(e=n){return e&&i?.id===e.id&&i.user===ye()&&i.revision===e.revision?i:null}function xe(e=n){return be(e)?.data?.pending||e?.ownershipPending||null}function Se(){return t?.user?.id||``}function Ce(e=n){return e&&r?.id===e.id&&r.user===Se()&&r.revision===e.revision?r:null}function we(e){return Ce(e)?.data?.pending||e?.changePending||null}function Te(){return t?.user?.id||``}function Ee(e=n){return e&&a?.id===e.id&&a.user===Te()&&a.revision===e.revision?a:null}function De(e){return Ee(e)?.data?.pending||e.cancellationPending||null}function K(e){if([`afterSale`,`orderAfterSale`].includes(e.kind))return``;let t=e.printStatus?.printed;return(0,q.jsx)(`span`,{"data-print-kind":e.printStatus?.kind||(e.kind===`recovery`?`recovery`:`order`),"data-print-id":e.printStatus?.id||e.id,className:`document-print-badge `+(t?`is-printed`:`is-unprinted`),title:t?`已记录打印操作`:`尚未记录打印操作`,children:t?`✓ 已打印`:`未打印`})}let Oe=Ie.grams,ke=e=>String(e??``),Ae=new Intl.DateTimeFormat(`zh-CN`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),je=Ie.validDate;function Me(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(e)||!je(e.slice(0,10)))return`未记录`;let t=new Date(e);if(Number.isNaN(t.getTime()))return`未记录`;let n=Object.fromEntries(Ae.formatToParts(t).map(e=>[e.type,e.value]));return`${n.year}-${n.month}-${n.day} ${n.hour}:${n.minute}`}function Ne(e){return(0,q.jsxs)(`div`,{className:`small muted order-entry-time`,children:[`录入时间(北京时间):`,Me(e.created)]})}function Pe(e){return![`afterSale`,`orderAfterSale`,`recovery`].includes(e.kind)&&Number.isSafeInteger(e.revision)&&e.revision>0&&e.reviewed_revision===e.revision}let Fe={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`},Le=e=>(0,q.jsx)(`span`,{className:`order-status `+([`draft`,`confirmed`].includes(e.status)?`danger-text`:`muted`),children:Fe[e.status]||e.status}),Re=(e,t,n=``,r={})=>(0,q.jsx)(`button`,{type:`button`,"data-action":t,className:n,...r,children:e});function ze(n){return e?.shopSettings?.members?.find(e=>e.member===n)?.label||e?.members?.find(e=>e.member===n)?.label||t?.loginOptions?.find(e=>e.member===n)?.label||{owner:`麦麦`,assistant:`娜娜`,assistant2:`小昊`}[n]||`待确认`}function Be(){return Ie.m Line truncated
`)}function a(){return e?.shopSettings?.storeName||e?.printing?.store||t?.brand?.storeName||`珠宝台账`}function o(e=!1,{historical:t=!1,selected:n=``}={}){let r=(t?V():H()).filter(e=>c()||e!==`assistant2`);e&&(r=[...r.filter(e=>e!==`owner`),...r.filter(e=>e===`owner`)]);let i=r.map(e=>[e,R(e)+(t&&!U(e)?`(已停用)`:``)]);return n&&V().includes(n)&&!r.includes(n)&&i.push([n,R(n)+`(已停用 · 原记录)`]),i}function s(){return e?.user?.member||t?.user?.member||(e?.user?.role===`owner`?`owner`:`assistant`)}function c(){return!!(e?.user?.member||e?.members?.some(e=>e.member===`assistant2`))}let l=Ie.validDate;function u(e){return e==null?`待确认`:`¥`+m(e)}function d(e){let{total:t,complete:n,amounts:r}=Oi.reimbursementAmounts(e,J.cents);return{total:t,complete:n,formula:r.map(e=>`¥`+m(e)).join(` + `)}}function f(e){return[...ee(),`owner`].filter(t=>e&&Object.hasOwn(e,t))}function p(e,t){let n=e.unknownCounts?.[t]||0;return n&&e.knownCounts?.[t]===0&&!e[t]&&!e.afterSaleCount?`待补齐`:(n?`已知 `:``)+`¥`+m(e[t])}let m=e=>e==null?`待补`:Ie.yuan(e);function h(e){return e.from===e.date?e.date:e.from+` 至 `+e.date}function g(e){let t=W(e);return t?R(t.member)+t.channel:e}function _(e,t,n=!1){return e===null?(n?`待核算(已核算 ¥`:`待补齐(已知 ¥`)+m(t)+`)`:`¥`+m(e)}function v(e){let t=e.summary,n=e.receiptsByOrderDate;return[a()+`三人账 · `+h(e),`利润留在店里,按订单归属分别记业绩。经营款各自管理;未导入真实期初经营款。`,...ne(e.peopleCount),`销售净额:`+p(t,`sale`),`本期净利润:`+p(t,`profit`),`本期实收:¥`+m(n.receipt)+`;本期实退:¥`+m(n.refund),...D(e),...O(e),...k(e),...A(e),`按实际付款人核对成本`,...f(e.payerCosts).flatMap(t=>{let n=e.payerCosts[t];return[R(t)+`:实际货品支出 `+y(n.goods,n.missingCount)+`;已付费用 ¥`+m(n.paidFees),...Ai(n).map(e=>e.date+` / `+x(e)+` / `+e.name+` / `+C(e))]}),`订单与售后`,...e.orderRows.map(e=>e.date+` / `+(e.paper_number||e.number||e.project)+` / `+(e.customer||`未填客户`)+` / `+R(e.member)+` / 销售 `+E(e,`sale`)+` / 净利润 `+E(e,`profit`)),`历史两人结算不计入团队新债务。`].join(`
`)}function y(e,t=0){return t&&e===0?`待补齐`:(t?`已知 `:``)+`¥`+m(e)}function b(e){return[e.missingCount?e.missingCount+` 项成本待补齐`:``,e.pendingCount?e.pendingCount+` 项费用未入账,不计合计`:``].filter(Boolean).join(`;`)}function x(e){return e.materialPoolId?e.materialPoolId+` 购料`:e.kind===`afterSale`?`售后 · `+(e.customer||`未填客户`):(e.price_lock_id?`锁价 · `:``)+(e.paper_number||e.number||`锁价记录`)+(e.customer?` · `+e.customer:``)}function S(e){let t=e.calculation;return t?M(t.quantity)+`g × `+(t.rate==null?e.component===`material`?`每克料价待补齐`:`每克工费待补齐`:m(t.rate)+`元/克`)+(e.amount==null?``:` = `+m(e.amount)+`元`):``}function C(e){return e.kind===`pending`?`未入账`+(e.amount==null?`(金额待补)`:`(登记 ¥`+m(e.amount)+`)`):e.amount==null?`待补齐`:`¥`+m(e.amount)}function w(e){return e.costItems?.[0]?.payer?R(e.costItems[0].payer):`付款人待补`}let T={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`};function E(e,t){if(e.status===`draft`)return`未开单`;if(t===`goods`){let t=ji(e);return y(t.goods,t.missing)}return t===`paidFees`?`¥`+m(ji(e).paidFees):e[t]==null?e.known?.[t]?`已知 ¥`+m(e.known[t])+`(待补齐)`:`待补齐`:`¥`+m(e[t])}function D(e){let t=e.dailyProfits,n=e=>`销售净额 ¥${m(e.sales)} / 成本 ${_(e.totalCost,e.knownTotalCost)} / 利润 ${_(e.profit,e.knownProfit,!0)}`;return[`每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)`,...t.rows.length?t.rows.map(e=>`${e.date} / ${e.name} / ${n(e)}`):[`所选范围暂无订单或售后记录。`],`所选范围合计:${n(t.summary)}`,``]}function O(e){return[`按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)`,...ke(e).flatMap(t=>{let n=e.ownershipReceipts[t];return[`${n.name}所属订单净收入:¥${m(n.net)};实收 ¥${m(n.receipt)};实退 ¥${m(n.refund)}`,...n.accounts.map(e=>`${e.recipient===n.member?`本人收款`:`他人代收`} / ${g(e.account)}:实收 ¥${m(e.receipt)},实退 ¥${m(e.refund)},净额 ¥${m(e.net)}`),...re(e.ownershipBusiness[t]),``]})]}function k(e){let t={date:e.date,from:e.from,month:n},r=e.dailyFunds;if(r?.team)return[`每日报销单(按报销日期归集,已批准报销不在当日订单往来重复相加)`,...r.reimbursements.flatMap(e=>[`${e.date} / ${e.requester_name} / ${z[e.status]} / 合计 ¥${m(e.total)}`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]),``];if(!r||r.rangeUnsupported)return[`每天转账核对`,`尚未取得完整转账资料,不输出应转金额。`,``];try{Ee(r,t)}catch{return[`每天转账核对`,`资料未完整返回,不输出应转金额。`,``]}let i=[`每天转账核对(应转合计,未扣已转)`,`${R(`owner`)}实收 ¥${m(r.ownerReceipts.receipt)} − 实退 ¥${m(r.ownerReceipts.refund)} = 净收款 ¥${m(r.ownerReceipts.net)}`];r.ready?i.push(`${R(`owner`)}净收款 ¥${m(r.ownerReceipts.net)} − 确认完整对外支出 ¥${m(r.actualOutlay)} + 已批准报销 ¥${m(r.approvedReimbursements)} = 应转合计 ¥${m(r.transferAmount)}`,r.transferAmount>0?`方向:`+R(`owner`)+`转`+R(`assistant`):r.transferAmount<0?`方向:`+R(`assistant`)+`转`+R(`owner`):`方向:无需转款`):i.push(`当天完整支出尚未全部确认,暂不输出完整应转合计。`,...r.missingDates.length?[`待确认日期:`+r.missingDates.join(`、`)]:[],...r.staleDates.length?[`来源变动待重新确认:`+r.staleDates.join(`、`)]:[]),i.push(`不要与旧按单/剩料待结重复相加;报销与确认不扣订单利润。`,`已批准报销项目(按报销日期归集)`);let a=r.reimbursements.filter(e=>e.status===`approved`);return i.push(...a.length?a.flatMap(e=>[`${e.date} / ${e.requester_name} / 合计 ¥${m(e.total)} / ${e.reviewer_name||R(`owner`)}复核`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]):[`本期暂无已批准报销。`],``),i}function A(e){return[`按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)`,...f(e.recipientReceipts).flatMap(t=>{let n=e.recipientReceipts[t];return[`${n.name}总收款:¥${m(n.receipt)};退款 ¥${m(n.refund)};净收款 ¥${m(n.net)}`,...[`receipt`,`refund`].flatMap(e=>{let t=n.items.filter(t=>t.kind===e),r=e===`receipt`?`收款`:`退款`;return[`${n.name}${r}明细(日期为实际${r}日):`,...t.length?t.map(e=>`${e.date} / ${ie(e)} / ${e.paper_number||e.number||(e.price_lock_id?`锁价记录`:`订单记录`)} / 客户 ${e.customer||`未填客户称呼`} / ${g(e.account)} / ${ae(e)} ¥${m(e.amount)}${e.reference||e.note?` / `+(e.reference||e.note):``}`):[`所选范围没有`+n.name+r+`记录。`],`${r}明细合计:¥${m(n[e])}`]}),``]})]}function j(e){if(!e?.summary?.eventCount)retu Line truncated
+20
View File
@@ -0,0 +1,20 @@
import{n as e,t}from"./rolldown-runtime-Dl_DZoUm.js";import{A as n,B as r,C as i,D as a,E as o,F as s,H as c,I as l,L as u,M as d,N as f,O as p,P as m,R as h,S as g,T as _,_ as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as A,n as j,o as M,p as N,r as P,s as F,t as I,u as L,v as R,w as z,x as B,y as V,z as ee}from"./antd-Bh8pVx-K.js";import{n as H,t as U}from"./react-BvkltZ40.js";var W=t(((e,t,n)=>{var r;(function(n,i){typeof e==`object`&&t!==void 0?t.exports=i():typeof r==`function`&&r.amd?r(i):(n=typeof globalThis<`u`?globalThis:n||self).dayjs=i()})(n,(function(){var e=1e3,t=6e4,n=36e5,r=`millisecond`,i=`second`,a=`minute`,o=`hour`,s=`day`,c=`week`,l=`month`,u=`quarter`,d=`year`,f=`date`,p=`Invalid Date`,m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:`en`,weekdays:`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),months:`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),ordinal:function(e){var t=[`th`,`st`,`nd`,`rd`],n=e%100;return`[`+e+(t[(n-20)%10]||t[n]||t[0])+`]`}},_=function(e,t,n){var r=String(e);return!r||r.length>=t?e:``+Array(t+1-r.length).join(n)+e},v={s:_,z:function(e){var t=-e.utcOffset(),n=Math.abs(t),r=Math.floor(n/60),i=n%60;return(t<=0?`+`:`-`)+_(r,2,`0`)+`:`+_(i,2,`0`)},m:function e(t,n){if(t.date()<n.date())return-e(n,t);var r=12*(n.year()-t.year())+(n.month()-t.month()),i=t.clone().add(r,l),a=n-i<0,o=t.clone().add(r+(a?-1:1),l);return+(-(r+(n-i)/(a?i-o:o-i))||0)},a:function(e){return e<0?Math.ceil(e)||0:Math.floor(e)},p:function(e){return{M:l,y:d,w:c,d:s,D:f,h:o,m:a,s:i,ms:r,Q:u}[e]||String(e||``).toLowerCase().replace(/s$/,``)},u:function(e){return e===void 0}},y=`en`,b={};b[y]=g;var x=`$isDayjsObject`,S=function(e){return e instanceof E||!(!e||!e[x])},C=function e(t,n,r){var i;if(!t)return y;if(typeof t==`string`){var a=t.toLowerCase();b[a]&&(i=a),n&&(b[a]=n,i=a);var o=t.split(`-`);if(!i&&o.length>1)return e(o[0])}else{var s=t.name;b[s]=t,i=s}return!r&&i&&(y=i),i||!r&&y},w=function(e,t){if(S(e))return e.clone();var n=typeof t==`object`?t:{};return n.date=e,n.args=arguments,new E(n)},T=v;T.l=C,T.i=S,T.w=function(e,t){return w(e,{locale:t.$L,utc:t.$u,x:t.$x,$offset:t.$offset})};var E=function(){function g(e){this.$L=C(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[x]=!0}var _=g.prototype;return _.parse=function(e){this.$d=function(e){var t=e.date,n=e.utc;if(t===null)return new Date(NaN);if(T.u(t))return new Date;if(t instanceof Date)return new Date(t);if(typeof t==`string`&&!/Z$/i.test(t)){var r=t.match(m);if(r){var i=r[2]-1||0,a=(r[7]||`0`).substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,a)}}return new Date(t)}(e),this.init()},_.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},_.$utils=function(){return T},_.isValid=function(){return this.$d.toString()!==p},_.isSame=function(e,t){var n=w(e);return this.startOf(t)<=n&&n<=this.endOf(t)},_.isAfter=function(e,t){return w(e)<this.startOf(t)},_.isBefore=function(e,t){return this.endOf(t)<w(e)},_.$g=function(e,t,n){return T.u(e)?this[t]:this.set(n,e)},_.unix=function(){return Math.floor(this.valueOf()/1e3)},_.valueOf=function(){return this.$d.getTime()},_.startOf=function(e,t){var n=this,r=!!T.u(t)||t,u=T.p(e),p=function(e,t){var i=T.w(n.$u?Date.UTC(n.$y,t,e):new Date(n.$y,t,e),n);return r?i:i.endOf(s)},m=function(e,t){return T.w(n.toDate()[e].apply(n.toDate(`s`),(r?[0,0,0,0]:[23,59,59,999]).slice(t)),n)},h=this.$W,g=this.$M,_=this.$D,v=`set`+(this.$u?`UTC`:``);switch(u){case d:return r?p(1,0):p(31,11);case l:return r?p(1,g):p(0,g+1);case c:var y=this.$locale().weekStart||0,b=(h<y?h+7:h)-y;return p(r?_-b:_+(6-b),g);case s:case f:return m(v+`Hours`,0);case o:return m(v+`Minutes`,1);case a:return m(v+`Seconds`,2);case i:return m(v+`Milliseconds`,3);default:return this.clone()}},_.endOf=function(e){return this.startOf(e,!1)},_.$set=function(e,t){var n,c=T.p(e),u=`set`+(this.$u?`UTC`:``),p=(n={},n[s]=u+`Date`,n[f]=u+`Date`,n[l]=u+`Month`,n[d]=u+`FullYear`,n[o]=u+`Hours`,n[a]=u+`Minutes`,n[i]=u+`Seconds`,n[r]=u+`Milliseconds`,n)[c],m=c===s?this.$D+(t-this.$W):t;if(c===l||c===d){var h=this.clone().set(f,1);h.$d[p](m),h.init(),this.$d=h.set(f,Math.min(this.$D,h.daysInMonth())).$d}else p&&this.$d[p](m);return this.init(),this},_.set=function(e,t){return this.clone().$set(e,t)},_.get=function(e){return this[T.p(e)]()},_.add=function(r,u){var f,p=this;r=Number(r);var m=T.p(u),h=function(e){var t=w(p);return T.w(t.date(t.date()+Math.round(e*r)),p)};if(m===l)return this.set(l,this.$M+r);if(m===d)return this.set(d,this.$y+r);if(m===s)return h(1);if(m===c)reLine truncated
0.58×(822+45)+55=558
769+558=1327`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&r.trim()&&(e.preventDefault(),s(!1))}}),(0,J.jsxs)(_,{wrap:!0,style:{marginTop:8},children:[(0,J.jsx)(l,{type:`primary`,onClick:()=>s(!1),children:`识别并预填`}),a?.kind===`warning`&&(0,J.jsx)(l,{onClick:()=>s(!0),children:`按计算金额预填`}),r&&(0,J.jsx)(l,{onClick:()=>{i(``),o(null)},children:`清空公式`})]}),(0,J.jsx)(`p`,{className:`small muted`,children:`括号内是克工费;金价乘克重后加的是一件工费,再加的金额记为附加费。合计行只校验,不增加商品。客户、货盘及内部成本仍按实际填写。`}),a&&(0,J.jsx)(h,{role:`status`,type:a.kind===`note`?`success`:a.kind,message:a.title||(a.kind===`error`?a.lines[0]:``),description:a.kind===`error`?void 0:(0,J.jsx)(`div`,{children:a.lines.filter(Boolean).map((e,t)=>(0,J.jsx)(`p`,{children:e},t))})})]})}function un({order:e,error:t,onRetry:r,onPreview:i,onNew:a}){let{message:o}=s.useApp(),[c,u]=(0,G.useState)(!1),f=e.total!==void 0;async function p(){if(e.paper_number)try{await navigator.clipboard.writeText(e.paper_number),u(!0),o.success(`已复制纸单号 `+e.paper_number),window.setTimeout(()=>u(!1),1800)}catch{u(!1),o.info(`请手动选择纸单号复制`)}}return(0,J.jsx)(`div`,{className:`issued-page`,children:(0,J.jsx)(O,{className:`issued-card`,children:(0,J.jsx)(w,{status:`success`,title:`销售单据已生成`,subTitle:f?e.materialCostPending?`收款、费用和出库已记账;料费待补,补足购料后自动核算利润。`:`收款、费用、出库和利润已记账。`:t||`正在读取已生成的销售单…`,extra:(0,J.jsxs)(_,{direction:`vertical`,size:`large`,style:{width:`100%`},children:[f&&(0,J.jsxs)(`dl`,{className:`issued-summary`,"data-testid":`issued-summary`,children:[(0,J.jsxs)(`div`,{className:`issued-item`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(S.Text,{type:`secondary`,children:`纸单号`})}),(0,J.jsxs)(`dd`,{className:`issued-value-row`,children:[(0,J.jsx)(`span`,{className:`issued-value num`,"data-testid":`issued-paper-number`,children:e.paper_number||`未分配`}),e.paper_number&&(0,J.jsx)(d,{title:c?`已复制`:`复制纸单号`,children:(0,J.jsx)(l,{type:`text`,size:`small`,className:`issued-copy-btn`,"aria-label":`复制纸单号`,icon:c?(0,J.jsx)(m,{}):(0,J.jsx)(C,{}),onClick:()=>void p()})})]})]}),(0,J.jsxs)(`div`,{className:`issued-item`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(S.Text,{type:`secondary`,children:`成交合计`})}),(0,J.jsx)(`dd`,{className:`issued-value issued-total num`,"data-testid":`issued-total`,children:ut(e.total??null,e.rounding_mode||`cent`)})]}),e.customer&&(0,J.jsxs)(`div`,{className:`issued-item`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(S.Text,{type:`secondary`,children:`客户`})}),(0,J.jsx)(`dd`,{className:`issued-value small`,children:e.customer})]})]}),(0,J.jsxs)(`div`,{className:`issued-actions`,children:[(0,J.jsx)(l,{type:`primary`,size:`large`,icon:(0,J.jsx)(P,{}),href:`/print/`+encodeURIComponent(e.id)+`?mode=full`,onClick:()=>{i().catch(e=>o.error(e.message))},target:`_blank`,rel:`noopener`,"data-action":`print-preview`,children:`打开打印预览`}),(0,J.jsx)(l,{size:`large`,icon:(0,J.jsx)(n,{}),onClick:a,"data-action":`new-order`,children:`开始新的一单`}),!f&&(0,J.jsx)(l,{size:`large`,onClick:r,children:`重新读取订单`})]}),(0,J.jsx)(l,{href:ye(`orders`)+`?order=`+encodeURIComponent(e.id),onClick:t=>{t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),q(`orders`,{search:`?order=`+encodeURIComponent(e.id)}))},type:`link`,icon:(0,J.jsx)(z,{}),children:`查看订单详情`})]})})})})}function dn(e){let{client:t,state:n}=e,r=ke(`draft`),[i,a]=(0,G.useState)(r?null:{draft:oe(window.localStorage,n.user.id),note:``});return(0,G.useEffect)(()=>{if(!r)return;let e=!0;return(async()=>{try{if(n.user.role!==`owner`)throw Error(`已有草稿由店主继续填写并开单;无单号的新开单流程照常使用。`);let i=await t.api(`/api/orders/`+encodeURIComponent(r));if(i.status!==`draft`)throw Error(`这张订单不是未开单的旧草稿,请在订单页查看。`);e&&a({draft:X.draftInputs(i),note:`正在继续填写旧草稿,生成销售单据后完成记账。`})}catch(t){e&&a({draft:oe(window.localStorage,n.user.id),note:`旧草稿未能打开:`+t.message})}})(),()=>{e=!1}},[t,r,n.user.id,n.user.role]),i?(0,J.jsx)(fn,{...e,initialDraft:i.draft,initialNote:i.note}):(0,J.jsx)(`div`,{className:`page-loading`,children:(0,J.jsx)(b,{tip:`正在读取旧草稿…`,children:(0,J.jsx)(`div`,{style:{height:60}})})})}function fn({client:e,state:t,session:n,refreshState:r,onAccountChanged:i,onRecoverOther:a,initialDraft:o,initialNote:c}){let{message:u}=s.useApp();Ae(e);let{store:d,update:f,reset:p,ctx:m,poolError:g,loadPools:_}=Dt({client:e,state:t,session:n,initialDraft:o}),{form:v,summary:y}=d,[b,C]=(0,G.useState)(``),[w,T]=(0,G.useState)(!1),[E,D]=(0,G.useState)(null),O=E!==null,k Line truncated
`),u=e=>e?.exchange?.fee_items.map(e=>`${e.note}:${e.amount}元 · ${o(e.payer)}付款`).join(`
`)||`无`,d=e=>e?.exchange?.charges.map(e=>`${e.name}:${e.amount}元`).join(`
`)||`无`,f=n.exchange||{},p=r?.exchange||{},m=e=>e?.mode===`pool`?`料池 `+e.poolId:e?`手填 `+e.rate+`元/克`:`无补金差重`,h=e=>e?e.mode===`gram`?e.rate+`元/克`:e.amount+`元总工费`:`未提供`;if(i.push(a(`业务日期`,n.date,r?.date||`取消原记录`),a(`客户`,n.customer,r?.customer),a(`开单人`,n.salesperson,r?.salesperson),a(`归属`,o(n.member),r?o(r.member):`沿用原身份留档`),a(`旧料逐项称重`,l(n),r?l(r):`冲正原库存及关联购料`),a(`旧料入库货盘`,s(n.old_pocket??`回收旧料`),r?s(r.old_pocket??`回收旧料`):`冲回原入库货盘`),a(`旧料入库数量(对)`,Fn(n.old_stock_count==null?null:Number(n.old_stock_count)),r?Fn(r.old_stock_count==null?null:Number(r.old_stock_count)):`冲回原入库数量`),a(`回收单价(元/克)`,n.buy_rate,r?.buy_rate),a(`回收结算额(元)`,n.buy_total,r?.buy_total),a(`实际收付款账户`,c(n.payment_account),r?c(r.payment_account):`冲正原收付记录`),a(`付款人`,o(n.payer),r?o(r.payer):`原付款流水保留`),a(`备注`,n.note,r?.note)),(n.surplus_mode===`deposit`||r?.surplus_mode===`deposit`)&&i.push(a(`余料处理`,n.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`,r?r.surplus_mode===`deposit`?`寄存,暂不结算`:`按回收价结算`:`撤回本单寄存余料`)),(n.old_source===`deposit`||r?.old_source===`deposit`)&&i.push(a(`使用客户寄存料`,n.old_source===`deposit`?n.deposit_id+` · `+n.deposit_weight+`g`:`本次交来旧料`,r?.old_source===`deposit`?r.deposit_id+` · `+r.deposit_weight+`g`:r?`本次交来旧料`:`退回寄存账户`)),n.exchange?.items||r?.exchange?.items){let e=e=>(e?.exchange?.items||[]).map((e,t)=>t+1+` · `+e.exchange.name+(e.old_source===`deposit`?` · 寄存记录 `+e.deposit_id+` 使用 `+e.deposit_weight+`g`:``)+(e.surplus_mode===`deposit`?` · 余料寄存,暂不结算`:``)+` · 旧料 `+e.old_lines.map(e=>e.melted_weight+`g × `+e.purity+`%`).join(`+`)+` 入`+s(e.old_pocket)+` · 新货 `+e.exchange.quantity+`g `+(s(e.exchange.pocket)||`外配`)+` · 补金 `+e.exchange.gold_price+`元/g · 折旧 `+e.exchange.depreciation_weight+`g × `+e.exchange.depreciation_rate+`元/g · 回收 `+e.buy_rate+`元/g,`+e.buy_total+`元 · 料费 `+JSON.stringify(e.exchange.cost_material)+` · 料费付款 `+o(e.exchange.cost_material_payer)+` · 进货工费 `+JSON.stringify(e.exchange.cost_labor)+`,`+o(e.exchange.cost_labor_payer)).join(`;`);i.push(a(`逐件置换完整资料`,e(n),r?e(r):`全部冲回`))}if(n.exchange?.products||r?.exchange?.products){let e=e=>(e?.products??(e?[e]:[])).map((e,t)=>t+1+` · `+e.name+` · `+e.quantity+`g · `+(s(e.pocket)||`外配`)+` · 销售工费 `+e.labor_rate+(e.labor_mode===`total`?`元`:`元/克`)+` · 进货工费 `+(e.cost_labor?.rate??e.cost_labor?.amount??`待补`)+` · `+o(e.cost_labor_payer)+(e.stockCount==null?``:` · `+e.stockCount+`对`)).join(`;`);i.push(a(`逐件置换商品`,e(n.exchange),r?e(r.exchange):`冲回全部新货出库`))}n.mode===`exchange`&&i.push(a(`置换新货`,f.name,p.name),a(`新货克重(g)`,f.quantity,p.quantity),a(`实际货盘`,s(f.pocket)||`外配`,r?s(p.pocket)||`外配`:`冲回原出库货盘`),a(`出库数量(对)`,Fn(f.stockCount==null?null:Number(f.stockCount)),Fn(p.stockCount==null?null:Number(p.stockCount))),a(`销售金价(元/克)`,f.gold_price,p.gold_price),a(`销售工费`,f.labor_rate+`元/`+(f.labor_mode===`gram`?`克`:`总额`),r?p.labor_rate+`元/`+(p.labor_mode===`gram`?`克`:`总额`):`取消`),a(`折旧计费克重/单价`,f.depreciation_weight+`g × `+f.depreciation_rate+`元/克`,r?p.depreciation_weight+`g × `+p.depreciation_rate+`元/克`:`取消`),a(`附加收费`,d(n),r?d(r):`取消`),a(`优惠(元)`,f.discount,p.discount),a(`取整方式`,f.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`,r?p.rounding_mode===`yuan`?`四舍五入到元`:`保留到分`:`取消`),a(`补金差重进货来源`,m(f.cost_material),r?m(p.cost_material):`释放原耗用`),a(`料费付款人`,o(f.cost_material_payer),r?o(p.cost_material_payer):`原来源留档`),a(`进货工费`,h(f.cost_labor),r?h(p.cost_labor):`取消`),a(`工费付款人`,o(f.cost_labor_payer),r?o(p.cost_labor_payer):`原来源留档`),a(`实际费用`,u(n),r?u(r):`冲正原费用`));let g=e.summary.before||{},_=e.summary.after||{};return i.push(...[[`实际收客户`,`cashReceipt`],[`实际付客户`,`cashPayment`],[`购料成本`,`purchaseAmount`],[`订单货品成本`,`goodsCost`],[`实际费用`,`directCost`],[`原账利润`,`profit`]].map(([e,t])=>a(e,g[t]==null?`待核实`:`¥`+lt(g[t]),r?_[t]==null?`待核实`:`¥`+lt(_[t]):`取消后冲正`))),(0,J.jsxs)(J.Fragment,{children:[e.summary.legacyCountNotice&&(0,J.jsxs)(`p`,{children:[e.summary.legacyCountNotice,e.summary.legacyCountVerified&&`(申请人已确认)`]}),(0,J.jsx)(`div`,{className:`table-wrap`,children:(0,J.jsxs)(`table`,{"aria-label":`回收更正原值与申请值`,children:[(0,J.jsx) Line truncated
`)}function a(){return e?.shopSettings?.storeName||e?.printing?.store||t?.brand?.storeName||`珠宝台账`}function o(e=!1,{historical:t=!1,selected:n=``}={}){let r=(t?V():ee()).filter(e=>c()||e!==`assistant2`);e&&(r=[...r.filter(e=>e!==`owner`),...r.filter(e=>e===`owner`)]);let i=r.map(e=>[e,R(e)+(t&&!H(e)?`(已停用)`:``)]);return n&&V().includes(n)&&!r.includes(n)&&i.push([n,R(n)+`(已停用 · 原记录)`]),i}function s(){return e?.user?.member||t?.user?.member||(e?.user?.role===`owner`?`owner`:`assistant`)}function c(){return!!(e?.user?.member||e?.members?.some(e=>e.member===`assistant2`))}let l=Fe.validDate;function u(e){return e==null?`待确认`:`¥`+m(e)}function d(e){let{total:t,complete:n,amounts:r}=Si.reimbursementAmounts(e,Y.cents);return{total:t,complete:n,formula:r.map(e=>`¥`+m(e)).join(` + `)}}function f(e){return[...U(),`owner`].filter(t=>e&&Object.hasOwn(e,t))}function p(e,t){let n=e.unknownCounts?.[t]||0;return n&&e.knownCounts?.[t]===0&&!e[t]&&!e.afterSaleCount?`待补齐`:(n?`已知 `:``)+`¥`+m(e[t])}let m=e=>e==null?`待补`:Fe.yuan(e);function h(e){return e.from===e.date?e.date:e.from+` 至 `+e.date}function g(e){let t=W(e);return t?R(t.member)+t.channel:e}function _(e,t,n=!1){return e===null?(n?`待核算(已核算 ¥`:`待补齐(已知 ¥`)+m(t)+`)`:`¥`+m(e)}function v(e){let t=e.summary,n=e.receiptsByOrderDate;return[a()+`三人账 · `+h(e),`利润留在店里,按订单归属分别记业绩。经营款各自管理;未导入真实期初经营款。`,...ne(e.peopleCount),`销售净额:`+p(t,`sale`),`本期净利润:`+p(t,`profit`),`本期实收:¥`+m(n.receipt)+`;本期实退:¥`+m(n.refund),...D(e),...O(e),...k(e),...A(e),`按实际付款人核对成本`,...f(e.payerCosts).flatMap(t=>{let n=e.payerCosts[t];return[R(t)+`:实际货品支出 `+y(n.goods,n.missingCount)+`;已付费用 ¥`+m(n.paidFees),...wi(n).map(e=>e.date+` / `+x(e)+` / `+e.name+` / `+C(e))]}),`订单与售后`,...e.orderRows.map(e=>e.date+` / `+(e.paper_number||e.number||e.project)+` / `+(e.customer||`未填客户`)+` / `+R(e.member)+` / 销售 `+E(e,`sale`)+` / 净利润 `+E(e,`profit`)),`历史两人结算不计入团队新债务。`].join(`
`)}function y(e,t=0){return t&&e===0?`待补齐`:(t?`已知 `:``)+`¥`+m(e)}function b(e){return[e.missingCount?e.missingCount+` 项成本待补齐`:``,e.pendingCount?e.pendingCount+` 项费用未入账,不计合计`:``].filter(Boolean).join(`;`)}function x(e){return e.materialPoolId?e.materialPoolId+` 购料`:e.kind===`afterSale`?`售后 · `+(e.customer||`未填客户`):(e.price_lock_id?`锁价 · `:``)+(e.paper_number||e.number||`锁价记录`)+(e.customer?` · `+e.customer:``)}function S(e){let t=e.calculation;return t?M(t.quantity)+`g × `+(t.rate==null?e.component===`material`?`每克料价待补齐`:`每克工费待补齐`:m(t.rate)+`元/克`)+(e.amount==null?``:` = `+m(e.amount)+`元`):``}function C(e){return e.kind===`pending`?`未入账`+(e.amount==null?`(金额待补)`:`(登记 ¥`+m(e.amount)+`)`):e.amount==null?`待补齐`:`¥`+m(e.amount)}function w(e){return e.costItems?.[0]?.payer?R(e.costItems[0].payer):`付款人待补`}let T={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`};function E(e,t){if(e.status===`draft`)return`未开单`;if(t===`goods`){let t=Ti(e);return y(t.goods,t.missing)}return t===`paidFees`?`¥`+m(Ti(e).paidFees):e[t]==null?e.known?.[t]?`已知 ¥`+m(e.known[t])+`(待补齐)`:`待补齐`:`¥`+m(e[t])}function D(e){let t=e.dailyProfits,n=e=>`销售净额 ¥${m(e.sales)} / 成本 ${_(e.totalCost,e.knownTotalCost)} / 利润 ${_(e.profit,e.knownProfit,!0)}`;return[`每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)`,...t.rows.length?t.rows.map(e=>`${e.date} / ${e.name} / ${n(e)}`):[`所选范围暂无订单或售后记录。`],`所选范围合计:${n(t.summary)}`,``]}function O(e){return[`按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)`,...ke(e).flatMap(t=>{let n=e.ownershipReceipts[t];return[`${n.name}所属订单净收入:¥${m(n.net)};实收 ¥${m(n.receipt)};实退 ¥${m(n.refund)}`,...n.accounts.map(e=>`${e.recipient===n.member?`本人收款`:`他人代收`} / ${g(e.account)}:实收 ¥${m(e.receipt)},实退 ¥${m(e.refund)},净额 ¥${m(e.net)}`),...re(e.ownershipBusiness[t]),``]})]}function k(e){let t={date:e.date,from:e.from,month:n},r=e.dailyFunds;if(r?.team)return[`每日报销单(按报销日期归集,已批准报销不在当日订单往来重复相加)`,...r.reimbursements.flatMap(e=>[`${e.date} / ${e.requester_name} / ${z[e.status]} / 合计 ¥${m(e.total)}`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]),``];if(!r||r.rangeUnsupported)return[`每天转账核对`,`尚未取得完整转账资料,不输出应转金额。`,``];try{Ee(r,t)}catch{return[`每天转账核对`,`资料未完整返回,不输出应转金额。`,``]}let i=[`每天转账核对(应转合计,未扣已转)`,`${R(`owner`)}实收 ¥${m(r.ownerReceipts.receipt)} − 实退 ¥${m(r.ownerReceipts.refund)} = 净收款 ¥${m(r.ownerReceipts.net)}`];r.ready?i.push(`${R(`owner`)}净收款 ¥${m(r.ownerReceipts.net)} − 确认完整对外支出 ¥${m(r.actualOutlay)} + 已批准报销 ¥${m(r.approvedReimbursements)} = 应转合计 ¥${m(r.transferAmount)}`,(r.transferAmount??0)>0?`方向:`+R(`owner`)+`转`+R(`assistant`):(r.transferAmount??0)<0?`方向:`+R(`assistant`)+`转`+R(`owner`):`方向:无需转款`):i.push(`当天完整支出尚未全部确认,暂不输出完整应转合计。`,...r.missingDates.length?[`待确认日期:`+r.missingDates.join(`、`)]:[],...r.staleDates.length?[`来源变动待重新确认:`+r.staleDates.join(`、`)]:[]),i.push(`不要与旧按单/剩料待结重复相加;报销与确认不扣订单利润。`,`已批准报销项目(按报销日期归集)`);let a=r.reimbursements.filter(e=>e.status===`approved`);return i.push(...a.length?a.flatMap(e=>[`${e.date} / ${e.requester_name} / 合计 ¥${m(e.total)} / ${e.reviewer_name||R(`owner`)}复核`,...e.items.map(e=>`${e.name}:¥${m(e.amount)}`)]):[`本期暂无已批准报销。`],``),i}function A(e){return[`按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)`,...f(e.recipientReceipts).flatMap(t=>{let n=e.recipientReceipts[t];return[`${n.name}总收款:¥${m(n.receipt)};退款 ¥${m(n.refund)};净收款 ¥${m(n.net)}`,...[`receipt`,`refund`].flatMap(e=>{let t=n.items.filter(t=>t.kind===e),r=e===`receipt`?`收款`:`退款`;return[`${n.name}${r}明细(日期为实际${r}日):`,...t.length?t.map(e=>`${e.date} / ${ie(e)} / ${e.paper_number||e.number||(e.price_lock_id?`锁价记录`:`订单记录`)} / 客户 ${e.customer||`未填客户称呼`} / ${g(e.account)} / ${ae(e)} ¥${m(e.amount)}${e.reference||e.note?` / `+(e.reference||e.note):``}`):[`所选范围没有`+n.name+r+`记录。`],`${r}明细合计:¥${m(n[e])}`]}),``]})]}function j(e){if(!e?.summary?.event Line truncated
`)||`无已记费用`}function M(e){let t=new Set((e.corrections||[]).filter(e=>e.type===`payment`).map(e=>e.target));return e.payments.filter(e=>e.amount>0&&!t.has(e.id)).map(e=>`${e.date} · ${e.kind===`receipt`?`客户收款`:`客户退款`}\n${V(e.amount)} · ${e.account?ue(e.account):`账户未提供`}`).join(`
`)||`无有效收退款`}function N(e,t,n=`锁价购料成本`){if(!e.priceLockCosts&&!t.priceLockCosts)return``;if(e.priceLockCosts?.lines||t.priceLockCosts?.lines){let n=e.priceLockCosts||{},r=t.priceLockCosts||{},i=n.lines||r.lines;return G.Children.toArray(i.map((e,t)=>{let i=n.lines?.find(t=>t.lineId===e.lineId)||{},a=r.lines?.find(t=>t.lineId===e.lineId)||{};return N({priceLockCosts:{...i,date:n.date}},{priceLockCosts:{...a,date:r.date}},`商品 `+(t+1)+` · 锁价购料成本`)}))}let r=e.priceLockCosts||{},i=t.priceLockCosts||{},a=e=>e===`pool`?`原锁料池`:e===`manual`?`手填原锁料价`:`未提供`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`tr`,{className:`change-section-row`,children:(0,J.jsx)(`th`,{colSpan:3,scope:`colgroup`,children:n})}),F(`原锁日期`,r.date,i.date),F(`原锁料费来源`,a(r.materialSource),a(i.materialSource)),F(`原锁进货料价(每克)`,V(r.buyRate),V(i.buyRate)),F(`原锁料费付款人`,r.materialSource===`pool`?`按原锁料池分摊`:B(r.buyPayer),i.materialSource===`pool`?`按原锁料池分摊`:B(i.buyPayer)),F(`原锁整批料费`,V(r.materialAmount),V(i.materialAmount)),F(`补重进货料价(每克)`,V(r.extraRate),V(i.extraRate)),F(`补重料费付款人`,r.extraPayer?B(r.extraPayer):`无补重`,i.extraPayer?B(i.extraPayer):`无补重`)]})}function P(e,t){if(!e)return`无此商品`;let n=V;if(t===`name`)return`${e.name||`未填写`}${e.priceNote?`
`+e.priceNote:``}`;if(t===`code`)return e.code||`未填写`;if(t===`quantity`)return e.unit===`g`?q(e.quantity)+`g`:String(e.quantity)+`件`;if(t===`sale`)return n(e.sale);if(t===`pricing`)return e.goldPrice==null?`手填基础金额 ${n(e.baseSale??e.sale)}`:`销售金价 ${n(e.goldPrice)}/克\n${e.laborMode===`gram`?`销售克工费`:`销售件工费`} ${n(e.laborRate)}${e.laborMode===`gram`?`/克`:`/件`}\n件数 ${e.pieces??`未填写`}`;if(t===`stockCount`)return Number.isSafeInteger(e.stockCount)||U(e.pocket)?H(e.stockCount):`不记录对数`;if(t===`pocket`)return W(e.pocket)||`外配/不扣黄金`;if(t===`charges`)return e.charges?.length?e.charges.map(e=>`${e.name}:${n(e.amount)}`).join(`
`):`无附加收费`;if(t===`cost`)return n(e.cost);if(t===`material`){let t=e.costMaterial;return t?.mode===`pool`?`每日购料:${t.poolId}\n本行料费:${n(e.costParts?.material)}${e.materialPool?.allocations?.length?`
`+e.materialPool.allocations.map(e=>B(e.payer)+` `+n(e.amount)).join(`;`):e.costParts?.material==null?`
待补采购后分摊`:``}`:`${t?.mode===`gram`?`每克料价 `+n(t.rate)+`/克`:`料费总额`}\n${n(e.costParts?.material)}`}return t===`labor`?`${e.costLabor?.mode===`gram`?`进货克工费 `+n(e.costLabor.rate)+`/克`:`进货总工费`}\n${n(e.costParts?.labor)}`:t===`extra`?e.costParts?`配件 ${n(e.costParts.accessories)}\n其他 ${n(e.costParts.other)}`:`原货品成本未分项`:t===`payers`?`料费:${e.costMaterial?.mode===`pool`?e.materialPool?.allocations?.map(e=>B(e.payer)+` `+n(e.amount)).join(`;`)||`按真实采购分摊`:B(e.costPayers?.material??e.payer)}\n进货工费:${B(e.costPayers?.labor??e.payer)}\n配件及其他:${B(e.payer)}`:``}function F(e,t,n){let r=String(t??``)!==String(n??``);return(0,J.jsxs)(`tr`,{...r?{className:`order-change-modified`}:{},children:[(0,J.jsxs)(`th`,{scope:`row`,children:[e,r?(0,J.jsx)(`span`,{className:`change-mark`,children:`已修改`}):``]}),(0,J.jsx)(`td`,{children:z(t)}),(0,J.jsx)(`td`,{children:z(n)})]})}function I(e){if(e===void 0)return[];let t=e=>e===null||Number.isSafeInteger(e)&&e>=0,n=e=>e&&t(e.materialAmount)&&[`usedMaterialAmount`,`leftoverCost`].every(n=>!Object.hasOwn(e,n)||t(e[n]))&&Array.isArray(e.allocations)&&e.allocations.every(e=>Re().includes(e.payer)&&Number.isSafeInteger(e.amount)&&e.amount>=0)&&(e.materialAmount===null||e.allocations.reduce((e,t)=>e+t.amount,0)===e.materialAmount);if(!Array.isArray(e)||!e.every(e=>e&&typeof e.id==`string`&&e.id&&ke(e.date)&&n(e.before)&&n(e.after)))throw Error(`关联锁价单的成本影响未完整返回,请重新读取后复核。`);return e}function L(e,t=void 0){let n=t=>t&&t.id===e.order_id&&Number.isSafeInteger(t.total)&&Array.isArray(t.lines)&&Array.isArray(t.expenses)&&Array.isArray(t.payments),r=e=>e===null||Number.isSafeInteger(e);if(!e||typeof e.id!=`string`||!e.id||typeof e.order_id!=`string`||t&&e.order_id!==t||!Object.hasOwn(ae,e.status)||!Number.isSafeInteger(e.order_revision)||typeof e.reason!=`string`||typeof e.requester_name!=`string`||typeof e.created!=`string`||typeof e.stale!=`boolean`||typeof e.canApprove!=`boolean`||!n(e.before)||!n(e.after)||![`before`,`after`].every(t=>e.summary?.[t]&&[`total`,`netReceived`,`directCost`].every(n=>Number.isSafeInteger(e.summary[t][n]))&&[`goodsCost`,`profit`,`settlementDue`].every(n=>r(e.summary[t][n]))))throw Error(`修改申请资料未完整返回,请重新读取订单后复核。`);if(e.relatedOrders!==void 0){if(!Array.isArray(e.relatedOrders))throw Error(`关联订单的修改影响未完整返回,请重新读取后复核。`);e.relatedOrders.forEach(t=>L({...e,order_id:t.id,before:t.before,after:t.after,summary:t.summary,relatedOrders:[]}))}if(I(e.relatedPriceLocks),e.action!==void 0&&!Object.hasOwn(oe,e.action))throw Error(`变更申请类型未完整返回,请重新读取后复核。`);let i=e.summary.inventory;if(i!==void 0&&(!i||![`before`,`after`,`changes`].every(e=>Array.isArray(i[e])&&i[e].every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))))throw Error(`变更申请库存摘要未完整返回,请重新读取后复核。`);return e}function R(e){let t=L(e),n=t.before,r=t.after,i=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(J.Fragment,{children:[G.Children.toArray([[`业务日期`,`date`],[`客户称呼/代号`,`customer`],[`开单人`,`salesperson`],[`收款方式与收款人`,`payment_account`],[`客户单备注`,`note`],[`内部备注(客户不可见)`,`internal_note`]].map(([e,t])=>F(e,t===`payment_account`?ue(n[t]):n[t],t===`payment_account`?ue(r[t]):r[t]))),F(`成交取整方式`,n.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`,r.rounding_mode===`yuan`?`四舍五入到整数元`:`保留到分`)]}),F(`新增费用默认支付日期`,n.fees_date||n.date,r.fees_date||r.date)]}),F(`交付日期`,n.delivered_date,r.delivered_date)]}),a=G.Children.toArray([[`成交金额`,`total`],[`收款净额`,`netReceived`],[`货品成本`,`goodsCost`],[`实际费用合计`,`directCost`],[`利润`,`profit`],[`双方待结净额`,`settlementDue`]].map(([e,n])=>F(e,V(t.summary.before[n]),V(t.summary.after[n])))),o=G.Children.toArray(Array.from({length:Math.max(n.lines.length,r.lines.length)},(e,t)=>(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`tr`,{className:`change-section-row`,children:(0,J.jsxs)(`th`,{colSpan:3,scope:`colgroup`,children:[`商品 `,t+1]})}),G.Children.toArray([[`商品与销售计价说明`,`name`],[`商品编号`,`code`],[`克重/数量`,`quantity`],[`销售金价、工费与件数`,`pricing`],[`成交金额(含附加收费)`,`sale`],[`客户附加收费`,`charges`],[`货盘`,`pocket`],[`出库数量(对)`,`stockCount`],[`货品成本合计`,`cost`],[`进货料价与料费`,`material`],[`进货工费`,`labor`],[`其他货品成本`,`extra`],[`成本付款人`,`payers`]].map(([e,i])=>F(e,P(n.lines[t],i),P(r.lines[t],i))))]}))),s=G.Children.toArray((t.relatedOrders||[]).map(e=>(0,J.jsxs)(`section`,{clasLine truncated
`).map((e,t)=>(0,J.jsxs)(G.Fragment,{children:[t>0&&(0,J.jsx)(`br`,{}),e]},t))}function B(e){return e?Le(e):`待补齐`}function V(e){return e==null?`待补齐`:`¥`+Ve(e)}function ee(e){try{return V(Y.cents(e))}catch{return`金额未提供`}}function H(e,{signed:t=!1,unknown:n=`未记录对数`}={}){return Number.isSafeInteger(e)?(t&&Number(e)>0?`+`:``)+e+`对`:n}function U(t){return!!t&&e?.pocketCatalog?.some(e=>e.key===t&&e.countUnit===`pair`)===!0}function W(t){return e?.pocketCatalog?.find(e=>e.key===t)?.name||String(t??``)}function te(e){if(!e||!Array.isArray(e.lines)||!e.lines.length||!e.lines.every(e=>[`quantity`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`].every(t=>Number.isSafeInteger(e[t])))||!e.summary||![`refundAmount`,`retainedAmount`,`materialReturnedCost`,`laborRestockedCost`,`costLoss`,`directCost`,`profit`,`profitAdjustment`].every(t=>Number.isSafeInteger(e.summary[t])))throw Error(`售后核算资料未完整返回,请重新读取订单。`);return e}function ne(e,{preview:t=!1}={}){let n=te(e),r=n.summary,i=e=>`¥`+Ve(e),a=[[`实际退款`,r.refundAmount],[`扣留客户款`,r.retainedAmount],[`回料池原料成本`,r.materialReturnedCost],[`现货保留工费`,r.laborRestockedCost],[`本单货品成本损失`,r.costLoss],[`售后最终利润`,r.profit],[`本次售后利润调整`,r.profitAdjustment]];return(0,J.jsxs)(`section`,{className:`order-after-sale-summary`+(t?` is-preview`:``),"aria-label":t?`售后核对预览`:`已保存售后详情`,children:[(0,J.jsxs)(`div`,{className:`panel-title`,children:[(0,J.jsx)(`h3`,{children:t?`售后核对预览`:`售后处理结果`}),(0,J.jsx)(`span`,{className:`badge`,children:t?`尚未保存`:`已记账`})]}),(0,J.jsx)(`dl`,{className:`order-after-sale-totals`,children:G.Children.toArray(a.map(([e,t])=>(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:e}),(0,J.jsx)(`dd`,{...t<0?{className:`danger-text`}:{},children:i(t)})]})))}),(0,J.jsx)(`div`,{className:`table-wrap`,children:(0,J.jsxs)(`table`,{"aria-label":`逐件售后回库与成本`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:`商品与实际去向`}),(0,J.jsx)(`th`,{children:`实际退回`}),(0,J.jsx)(`th`,{children:`回料成本`}),(0,J.jsx)(`th`,{children:`保留工费`}),(0,J.jsx)(`th`,{children:`成本损失`})]})}),(0,J.jsx)(`tbody`,{children:G.Children.toArray(n.lines.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsxs)(`td`,{children:[e.name||`商品 `+(e.lineIndex+1),(0,J.jsxs)(`div`,{className:`small muted`,children:[W(e.pocket),` · `,e.disposition===`stock`?`完好现货`:`旧料/损坏`]})]}),(0,J.jsxs)(`td`,{children:[q(e.quantity),`g`,e.disposition===`stock`&&U(e.pocket)?(0,J.jsx)(`div`,{className:`small`,children:H(e.stockCount)}):``]}),(0,J.jsx)(`td`,{children:i(e.materialReturnedCost)}),(0,J.jsx)(`td`,{children:i(e.laborRestockedCost)}),(0,J.jsx)(`td`,{children:i(e.costLoss)})]})))})]})}),(0,J.jsx)(`p`,{className:`small muted`,children:`实退材料按原成本回售后日料池,不新增采购付款。完好现货工费留在退回现货批次;旧料工费与未退回材料成本计损失。原单实际费用继续保留。`})]})}function re(e){let t=e.action||`edit`,n=e.action_input||e.action_details||{};if(t===`edit`)return``;if(n.afterSale){let t=ge(e.after);return(0,J.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,J.jsx)(`h3`,{children:`本次售后申请`}),(0,J.jsxs)(`p`,{children:[`售后日期:`,n.date,` · 申请原因:`,e.reason]}),ne(t,{preview:!0})]})}let r=[[`申请动作`,se(e)],[`业务日期`,n.date||e.after.returned_date||e.after.date]];return n.amount!==void 0&&r.push([`本次金额`,ee(n.amount)]),n.account&&r.push([`退款账户`,ue(n.account)]),n.payer&&r.push([`实际付款人`,B(n.payer)]),n.note&&r.push([`费用项目/说明`,n.note]),n.reference&&r.push([`退款凭据备注`,n.reference]),Array.isArray(n.returnCounts)&&r.push([`实际退回数量(对)`,n.returnCounts.map((e,t)=>`商品 `+(t+1)+`:`+H(e==null?null:Number(e))).join(`
`)]),Array.isArray(n.returnPockets)&&r.push([`退货实物去向`,n.returnPockets.map((t,n)=>`${e.before.lines[n]?.name||`商品 `+(n+1)}:${W(t)||`退供应商/不留黄金货盘`}`).join(`
`)]),Array.isArray(n.fee_items)&&r.push([`本次旧费用`,n.fee_items.map(e=>`${e.note||`费用`}:${ee(e.amount)} · ${B(e.payer)}支付`).join(`
`)]),(0,J.jsxs)(`section`,{className:`order-change-action-summary`,children:[(0,J.jsx)(`h3`,{children:`本次申请动作`}),(0,J.jsx)(`dl`,{className:`order-change-action-facts`,children:G.Children.toArray(r.map(([e,t])=>(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:e}),(0,J.jsx)(`dd`,{children:z(t)})]})))}),(0,J.jsx)(`p`,{className:`small muted`,children:`下方对照为服务器试算;批准后才登记这笔变更,不会由系统发起真实收款、退款或转账。`})]})}function ie(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let ae={pending:`待店主复核`,approved:`已同意变更`,rejected:`已驳回`},oe={edit:`修改订单`,expense:`费用补记`,fees:`旧费用核实`,refund:`退款`,return:`退货`,cost:`成本补录`};function se(e){return(e.action_input||e.action_details)?.afterSale?`处理订单售后`:e.action_label||oe[e.action||`edit`]||`订单变更`}let K={pending:`待店主复核`,approved:`已同意取消`,rejected:`已驳回`};function ce(e){let t=new Date(e);return Number.isNaN(t.getTime())?`时间未提供`:t.toLocaleString(`zh-CN`)}let le=e=>Fe.accountIdentity(Re(),e);function ue(e){let t=le(e);return t?Le(t.member)+t.channel:e}function de(e){if(!e||![`total`,`netReceived`,`directCost`].every(t=>Number.isSafeInteger(e[t]))||![`goodsCost`,`profit`,`settlementDue`].every(t=>e[t]===null||Number.isSafeInteger(e[t]))||!Array.isArray(e.inventory)||!e.inventory.every(e=>typeof e.date==`string`&&typeof e.pocket==`string`&&Number.isSafeInteger(e.mg)))throw Error(`取消撤销摘要未完整返回,请重新读取订单。`);return e}function fe(e=n){let t=we(e)?.data;if(!t?.eligible||t.pending||t.directToday!==!0||!/^\d{4}-\d{2}-\d{2}$/.test(t.directActionDate||``)||e?.date!==t.directActionDate||e?.price_lock_id||![`draft`,`confirmed`,`delivered`].includes(e?.status||``))return!1;try{return de(t.summary),!0}catch{return!1}}function pe(t,r=e.today,i=n){let a=xe(i)?.data;return[`expense`,`fees`,`refund`,`return`].includes(t)&&!!a&&!a.pending&&/^\d{4}-\d{2}-\d{2}$/.test(a.directActionDate||``)&&a.actions?.[t]?.directToday===!0&&i?.date===a.directActionDate&&r===a.directActionDate&&!(o.action===t&&o.forceApproval)}function me(t){return e.user.role===`assistant`&&[`expense`,`fees`,`refund`,`return`,`cost`].includes(t)}function he(t,n=e.today){return me(t)&&!pe(t,n)}function ge(e){return e?.orderAfterSale||null}function _e(){return t?.user?.id||``}function ve(e=n){return e&&i?.id===e.id&&i.user===_e()&&i.revision===e.revision?i:null}function ye(e=n){return ve(e)?.data?.pending||e?.ownershipPending||null}function be(){return t?.user?.id||``}function xe(e=n){return e&&r?.id===e.id&&r.user===be()&&r.revision===e.revision?r:null}function Se(e){return xe(e)?.data?.pending||e?.changePending||null}function Ce(){return t?.user?.id||``}function we(e=n){return e&&a?.id===e.id&&a.user===Ce()&&a.revision===e.revision?a:null}function Te(e){return we(e)?.data?.pending||e.cancellationPending||null}function Ee(e){if([`afterSale`,`orderAfterSale`].includes(e.kind??``))return``;let t=e.printStatus?.printed;return(0,J.jsx)(`span`,{"data-print-kind":e.printStatus?.kind||(e.kind===`recovery`?`recovery`:`order`),"data-print-id":e.printStatus?.id||e.id,className:`document-print-badge `+(t?`is-printed`:`is-unprinted`),title:t?`已记录打印操作`:`尚未记录打印操作`,children:t?`✓ 已打印`:`未打印`})}let q=Fe.grams,De=e=>String(e??``),Oe=new Intl.DateTimeFormat(`zh-CN`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),ke=Fe.validDate;function Ae(e){if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(e)||!ke(e.slice(0,10)))return`未记录`;let t=new Date(e);if(Number.isNaN(t.getTime()))return`未记录`;let n=Object.fromEntries(Oe.formatToParts(t).map(e=>[e.type,e.value]));return`${n.year}-${n.month}-${n.day} ${n.hour}:${n.minute}`}function je(e){return(0,J.jsxs)(`div`,{className:`small muted order-entry-time`,children:[`录入时间(北京时间):`,Ae(e.created)]})}function Me(e){return![`afterSale`,`orderAfterSale`,`recovery`].includes(e.kind??``)&&Number.isSafeInteger(e.revision)&&e.revision>0&&e.reviewed_revision===e.revision}let Ne={draft:`旧草稿`,confirmed:`旧单待补齐`,delivered:`已完成`,returned:`已退货`,cancelled:`已取消`,after_sale:`售后`,recovery:`回收`},Pe=e=>(0,J.jsx)(`span`,{className:`order-status `+([`draft`,`confirmed`].includes(e.status)?`danger-text`:`muted`),children:Ne[e.status]||e.status}),Ie=(e,t,n=``,r={})=>(0,J.jsx)(`button`,{type:`button`,"data-action":t,className:n,...r,children:e});function Le(n){return e?.shopSettings?.members?.find(e=>e.member===n)?.label||e?.members?.find(e=>e.member===n)?.label||t?.loginOptions?.find(e=>e.member===n)?.label||{owner:`麦麦`,assistant:`娜娜`,assistant2:`小昊`}[n??``]||`待确认`}let Re Line truncated
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
<title>珠宝台账 · 新账系统</title>
<script type="module" crossorigin src="/next/assets/index-DZWLfWyz.js"></script>
<script type="module" crossorigin src="/next/assets/index-YO0PLbVu.js"></script>
<link rel="modulepreload" crossorigin href="/next/assets/rolldown-runtime-Dl_DZoUm.js">
<link rel="modulepreload" crossorigin href="/next/assets/antd-Bh8pVx-K.js">
<link rel="modulepreload" crossorigin href="/next/assets/react-BvkltZ40.js">
+8 -7
View File
@@ -14,18 +14,19 @@ export default tseslint.config(
plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh },
rules: {
...reactHooks.configs.recommended.rules,
'react-hooks/exhaustive-deps': 'error',
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
},
},
{ files: ['src/**/*.{js,jsx}'], languageOptions: { globals: { ...globals.browser } } },
// TypeScript requires var for declarations installed as properties of globalThis by classic scripts.
{ files: ['src/shared/browserGlobals.d.ts'], rules: { 'no-var': 'off' } },
{
files: ['**/*.jsx'],
languageOptions: {
parserOptions: { ecmaFeatures: { jsx: true } },
},
plugins: { 'react-hooks': reactHooks },
files: ['src/**/*.{ts,tsx}'],
rules: {
'react-hooks/rules-of-hooks': 'error',
'@typescript-eslint/ban-ts-comment': [
'error',
{ 'ts-check': false, 'ts-expect-error': true, 'ts-ignore': true, 'ts-nocheck': true },
],
},
},
{
+2 -2
View File
@@ -5,10 +5,10 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"build": "npm run typecheck && vite build",
"test": "vitest run",
"lint": "eslint .",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit && node scripts/check-type-coverage.mjs"
},
"dependencies": {
"@ant-design/icons": "^5.6.1",
@@ -0,0 +1,32 @@
// 检查实际编译文件和共享 JS 的 JSDoc,避免新页面再次掉出严格检查。
import process from 'node:process';
import console from 'node:console';
import fs from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
const config = ts.readConfigFile('tsconfig.json', ts.sys.readFile);
const { options, fileNames } = ts.parseJsonConfigFileContent(config.config, ts.sys, process.cwd());
const inputs = new Set(fileNames.map(file => path.resolve(file)));
const errors = [];
if (!options.strict || !options.noImplicitAny || !options.checkJs) errors.push('严格类型检查未启用');
for (const name of fs.readdirSync('src', { recursive: true })) {
if (!/\.[jt]sx?$/.test(name)) continue;
if (!inputs.has(path.resolve('src', name))) errors.push('未检查 src/' + name);
if (/\.jsx?$/.test(name)) errors.push('React 业务代码需使用 TS/TSX:' + name);
}
for (const file of inputs) {
const local = path.relative(process.cwd(), file);
if (!local.startsWith('src/') && !local.startsWith('../public/')) continue;
const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
if (/@ts-(?:ignore|expect-error|nocheck)\b/.test(source.text)) errors.push(local + ' 有类型检查豁免');
function visit(node) {
if (node.kind === ts.SyntaxKind.AnyKeyword || node.kind === ts.SyntaxKind.JSDocAllType) {
errors.push(local + ':' + (source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1) + ' 显式 any');
}
for (const doc of node.jsDoc ?? []) visit(doc);
ts.forEachChild(node, visit);
}
visit(source);
}
if (errors.length) throw new Error(errors.join('\n'));
console.log('前端类型覆盖与禁止豁免检查通过');
-90
View File
@@ -1,90 +0,0 @@
import { grams, yuan } from './format';
export function validateMaterialQuote(result, input, memberKeys) {
const integer = value => Number.isSafeInteger(value) && value >= 0,
amount = value => value === null || integer(value);
if (
!result ||
result.date !== input.date ||
result.member !== input.member ||
!Array.isArray(result.entries) ||
result.entries.length !== input.entries.length ||
!Array.isArray(result.pools)
)
throw new Error('分来源料费未完整返回,请刷新料价。');
for (const original of input.entries) {
const row = result.entries.find(row => row.lineIndex === original.lineIndex);
if (
!row ||
row.poolId !== original.poolId ||
row.mg !== original.mg ||
!amount(row.amount) ||
!Array.isArray(row.allocations) ||
!Array.isArray(row.materialSources) ||
row.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== row.mg
)
throw new Error('分来源料费与当前商品不一致,请重新核对。');
for (const source of row.materialSources)
if (
!['personal_recovery', 'public'].includes(source.kind) ||
(source.kind === 'personal_recovery' && source.member !== input.member) ||
!integer(source.quantity) ||
!amount(source.amount) ||
!Array.isArray(source.allocations) ||
source.allocations.some(part => !memberKeys.includes(part.payer) || !integer(part.amount)) ||
(source.amount !== null && source.allocations.reduce((sum, part) => sum + part.amount, 0) !== source.amount)
)
throw new Error('个人回收料或付款来源不完整,请重新读取。');
if (
row.amount !== null &&
(row.materialSources.some(source => source.amount === null) ||
row.materialSources.reduce((sum, source) => sum + source.amount, 0) !== row.amount ||
row.allocations.reduce((sum, part) => sum + part.amount, 0) !== row.amount)
)
throw new Error('分来源料费合计不一致,请重新读取。');
}
if (
result.pools.length !== new Set(input.entries.map(row => row.poolId)).size ||
result.pools.some(
pool =>
!input.entries.some(row => row.poolId === pool.poolId) ||
!['personalRemainingMg', 'publicRemainingMg', 'eligibleRemainingMg'].every(key => integer(pool[key])) ||
!amount(pool.personalRemainingAmount) ||
!amount(pool.publicRemainingAmount),
)
)
throw new Error('个人与公共可用克重未完整返回,请重新读取。');
return result;
}
export function describeMaterialSources(sources = [], memberName) {
return sources
.map(source => {
const label =
source.kind === 'personal_recovery'
? (source.member ? memberName(source.member) : '待补') + '个人回收料'
: '公共料';
const amount = source.amount == null ? '料费待补' : '¥' + yuan(source.amount);
const rate = source.averageRate == null ? '' : '(加权约 ¥' + yuan(source.averageRate) + '/克)';
return label + ' ' + grams(source.quantity) + 'g · ' + amount + rate;
})
.join(';');
}
export function describeMaterialBalance(pool) {
const before = pool.before
? '本次前可用:个人 ' +
grams(pool.before.personalRemainingMg) +
'g,公共 ' +
grams(pool.before.publicRemainingMg) +
'g;'
: '';
return (
before +
'本次后余:个人回收料 ' +
grams(pool.personalRemainingMg) +
'g,公共料 ' +
grams(pool.publicRemainingMg) +
'g。'
);
}
+172
View File
@@ -0,0 +1,172 @@
import { grams, yuan } from './format';
import type { Allocation } from '../pages/MaterialPools/model';
export interface QuoteEntry {
lineIndex: number;
poolId: string;
mg: number;
lineId?: string;
}
export interface QuoteRequest {
date: string;
member: string;
entries: QuoteEntry[];
orderId?: string;
priceLockId?: string;
}
export interface SourceDescription {
kind: string;
member?: string | null;
quantity: number;
amount: number | null;
averageRate?: number | null;
}
export interface QuoteSource extends SourceDescription {
allocations: Allocation[];
}
export interface QuoteRow extends QuoteEntry {
amount: number | null;
materialSources: QuoteSource[];
allocations: Allocation[];
}
interface Remaining {
personalRemainingMg: number;
publicRemainingMg: number;
eligibleRemainingMg: number;
}
export interface QuoteBalance extends Remaining {
poolId: string;
revision: string;
before?: Remaining;
}
interface Quote {
date: string;
member: string;
entries: QuoteRow[];
pools: QuoteBalance[];
}
const record = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null;
const integer = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const amount = (v: unknown): v is number | null => v === null || integer(v);
function allocation(v: unknown): v is Allocation {
return record(v) && typeof v.payer === 'string' && integer(v.amount);
}
function source(v: unknown): v is QuoteSource {
return (
record(v) &&
(v.kind === 'personal_recovery' || v.kind === 'public') &&
(v.member == null || typeof v.member === 'string') &&
integer(v.quantity) &&
amount(v.amount) &&
(v.averageRate == null || integer(v.averageRate)) &&
Array.isArray(v.allocations) &&
v.allocations.every(allocation)
);
}
function row(v: unknown): v is QuoteRow {
return (
record(v) &&
integer(v.lineIndex) &&
typeof v.poolId === 'string' &&
integer(v.mg) &&
amount(v.amount) &&
Array.isArray(v.allocations) &&
v.allocations.every(allocation) &&
Array.isArray(v.materialSources) &&
v.materialSources.every(source)
);
}
function remaining(v: unknown): v is Remaining {
return record(v) && integer(v.personalRemainingMg) && integer(v.publicRemainingMg) && integer(v.eligibleRemainingMg);
}
function balance(v: unknown): v is QuoteBalance {
return (
record(v) &&
typeof v.poolId === 'string' &&
typeof v.revision === 'string' &&
amount(v.personalRemainingAmount) &&
amount(v.publicRemainingAmount) &&
(!v.before || remaining(v.before)) &&
remaining(v)
);
}
export function validateMaterialQuote(result: unknown, input: QuoteRequest, memberKeys: string[]): Quote {
if (
!record(result) ||
result.date !== input.date ||
result.member !== input.member ||
!Array.isArray(result.entries) ||
result.entries.length !== input.entries.length ||
!Array.isArray(result.pools)
)
throw new Error('分来源料费未完整返回,请刷新料价。');
const entries: unknown[] = result.entries;
if (!entries.every(row)) throw new Error('分来源料费与当前商品不一致,请重新核对。');
for (const original of input.entries) {
const item = entries.find(v => v.lineIndex === original.lineIndex);
if (
!item ||
item.poolId !== original.poolId ||
item.mg !== original.mg ||
item.materialSources.reduce((sum, s) => sum + s.quantity, 0) !== item.mg
)
throw new Error('分来源料费与当前商品不一致,请重新核对。');
for (const s of item.materialSources)
if (
(s.kind === 'personal_recovery' && s.member !== input.member) ||
s.allocations.some(p => !memberKeys.includes(p.payer)) ||
(s.amount !== null && s.allocations.reduce((sum, p) => sum + p.amount, 0) !== s.amount)
)
throw new Error('个人回收料或付款来源不完整,请重新读取。');
if (
item.amount !== null &&
(item.materialSources.some(s => s.amount === null) ||
item.materialSources.reduce((sum, s) => sum + (s.amount ?? 0), 0) !== item.amount ||
item.allocations.reduce((sum, p) => sum + p.amount, 0) !== item.amount)
)
throw new Error('分来源料费合计不一致,请重新读取。');
}
const pools: unknown[] = result.pools;
if (
!pools.every(balance) ||
pools.length !== new Set(input.entries.map(e => e.poolId)).size ||
pools.some(p => !input.entries.some(e => e.poolId === p.poolId))
)
throw new Error('个人与公共可用克重未完整返回,请重新读取。');
return { date: input.date, member: input.member, entries, pools };
}
export function describeMaterialSources(
sources: readonly SourceDescription[] = [],
memberName: (key: string) => string,
) {
return sources
.map(source => {
const label =
source.kind === 'personal_recovery'
? (source.member ? memberName(source.member) : '待补') + '个人回收料'
: '公共料';
const amount = source.amount == null ? '料费待补' : '¥' + yuan(source.amount);
const rate = source.averageRate == null ? '' : '(加权约 ¥' + yuan(source.averageRate) + '/克)';
return label + ' ' + grams(source.quantity) + 'g · ' + amount + rate;
})
.join(';');
}
export function describeMaterialBalance(pool: QuoteBalance) {
const before = pool.before
? '本次前可用:个人 ' +
grams(pool.before.personalRemainingMg) +
'g,公共 ' +
grams(pool.before.publicRemainingMg) +
'g;'
: '';
return (
before +
'本次后余:个人回收料 ' +
grams(pool.personalRemainingMg) +
'g,公共料 ' +
grams(pool.publicRemainingMg) +
'g。'
);
}
@@ -38,67 +38,67 @@ export function ChargeList({ index, line, update }: { index: number; line: LineS
</Button>
</div>
{line.charges.length > 0 && (
<div className="charge-list">
{line.charges.map((charge, j) => (
<div className="charge-row" key={charge.id} data-charge={j}>
<ChoiceField
label="附加项目"
field="chargeType"
value={charge.type}
options={[...Model.chargeNames, '其他'].map(name => [name, name] as [string, string])}
onChange={type => setCharge(j, c => Model.changeChargeType(c, type))}
/>
<TextField
label="附加项目名称"
field="chargeName"
hidden={charge.type !== '其他'}
value={charge.customName}
maxLength={40}
onChange={value => setCharge(j, c => ({ ...c, customName: value }))}
/>
<TextField
label="附加金额(元)"
field="chargeAmount"
numeric
value={charge.amount}
placeholder="没有收费填0,可修改金额"
onChange={value => setCharge(j, c => Model.setChargeAmount(c, value))}
/>
<div className="charge-actions">
<Button
type="text"
size="small"
icon={<CloseOutlined />}
data-action="remove-charge"
onClick={() =>
update(form => {
const current = form.lines[index];
return Model.updateLine(form, index, {
...current,
charges: current.charges.filter((_, k) => k !== j),
});
})
}
>
移除附加项
</Button>
{charge.costRemoved && (
<small className="muted">
内部成本已移除{' '}
<Button
type="link"
size="small"
data-action="restore-charge-cost"
onClick={() => update(form => Model.restoreChargeCost(form, index, j))}
>
恢复内部成本
</Button>
</small>
)}
<div className="charge-list">
{line.charges.map((charge, j) => (
<div className="charge-row" key={charge.id} data-charge={j}>
<ChoiceField
label="附加项目"
field="chargeType"
value={charge.type}
options={[...Model.chargeNames, '其他'].map(name => [name, name] as [string, string])}
onChange={type => setCharge(j, c => Model.changeChargeType(c, type))}
/>
<TextField
label="附加项目名称"
field="chargeName"
hidden={charge.type !== '其他'}
value={charge.customName ?? ''}
maxLength={40}
onChange={value => setCharge(j, c => ({ ...c, customName: value }))}
/>
<TextField
label="附加金额(元)"
field="chargeAmount"
numeric
value={charge.amount}
placeholder="没有收费填0,可修改金额"
onChange={value => setCharge(j, c => Model.setChargeAmount(c, value))}
/>
<div className="charge-actions">
<Button
type="text"
size="small"
icon={<CloseOutlined />}
data-action="remove-charge"
onClick={() =>
update(form => {
const current = form.lines[index];
return Model.updateLine(form, index, {
...current,
charges: current.charges.filter((_, k) => k !== j),
});
})
}
>
移除附加项
</Button>
{charge.costRemoved && (
<small className="muted">
内部成本已移除{' '}
<Button
type="link"
size="small"
data-action="restore-charge-cost"
onClick={() => update(form => Model.restoreChargeCost(form, index, j))}
>
恢复内部成本
</Button>
</small>
)}
</div>
</div>
</div>
))}
</div>
))}
</div>
)}
</div>
);
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { LedgerClient } from '../../lib/api';
import { Model } from '../../shared';
import { validateMaterialQuote, type QuoteRequest } from '../../lib/materialQuote';
import type {
FormSummary,
LedgerState,
@@ -98,7 +99,7 @@ export function useOrderForm({
const input = Model.poolQuoteInput(store.form, ctx);
const rows = (pools?.rows || []) as { id: string; personalPools?: unknown }[];
const personal = input.entries.some(entry =>
rows.some(row => row.id === (entry as { poolId: string }).poolId && row.personalPools !== undefined),
rows.some(row => row.id === entry.poolId && row.personalPools !== undefined),
);
return personal ? JSON.stringify(input) : '';
}, [store.form, ctx, pools]);
@@ -106,9 +107,13 @@ export function useOrderForm({
if (!quoteInput || (quote && JSON.stringify(quote.input) === quoteInput)) return;
let current = true;
const timer = window.setTimeout(async () => {
const input = JSON.parse(quoteInput);
const input: QuoteRequest = JSON.parse(quoteInput);
try {
const result = await client.api('/api/material-pools/quote', input);
const result = validateMaterialQuote(
await client.api('/api/material-pools/quote', input),
input,
Model.memberKeys(state),
);
if (current) setQuote({ input, result, error: '' });
} catch (err) {
if (current) setQuote({ input, result: null, error: (err as Error).message });
@@ -118,7 +123,7 @@ export function useOrderForm({
current = false;
window.clearTimeout(timer);
};
}, [quoteInput, quote, client]);
}, [quoteInput, quote, client, state]);
return { store, update, reset, ctx, pools, poolError, loadPools };
}
@@ -9,6 +9,7 @@ export interface Purchase {
revision: number;
note: string;
payer?: string;
allocations?: Allocation[];
actualpayer?: string;
actualPayer?: string;
sourceKind?: string;
@@ -0,0 +1,39 @@
import { useRef, useEffect, type ReactNode } from 'react';
export function Dialog({
id,
label,
close,
children,
ownClose = false,
}: {
id: string;
label: string;
close: () => void;
children: ReactNode;
ownClose?: boolean;
}) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
const node = ref.current!;
node.showModal();
return () => node.close();
}, []);
return (
<dialog
id={id}
ref={ref}
aria-label={label}
onCancel={event => {
event.preventDefault();
close();
}}
>
{!ownClose && (
<button type="button" className="dialog-close" data-action="close-dialog" aria-label={label} onClick={close}>
×
</button>
)}
{children}
</dialog>
);
}
@@ -1,8 +1,24 @@
import { Fragment } from 'react';
import { Fragment, type InputHTMLAttributes, type SelectHTMLAttributes, type ReactNode } from 'react';
import type { ChargeState, OrderForm, LineState, PurchaseState, SyncContext, LedgerState } from '../../shared';
import type { FormStore } from '../CreateOrder/useOrderForm';
interface FieldProps {
label: ReactNode;
help?: ReactNode;
onChange?: (value: string) => void;
value?: string | number | null;
}
type InputProps = FieldProps & Omit<InputHTMLAttributes<HTMLInputElement>, keyof FieldProps>;
type Option = string | readonly [string, string, boolean?];
type ChoiceProps = FieldProps &
Omit<SelectHTMLAttributes<HTMLSelectElement>, keyof FieldProps> & { options: readonly Option[] };
type UpdateForm = (change: (form: OrderForm) => OrderForm) => void;
type TextKey<T> = { [K in keyof T]-?: T[K] extends string ? K : never }[keyof T];
import { Fees, Model } from '../../shared';
import { uuid } from '../CreateOrder/useOrderForm';
export function Input({ label, name, value, type = 'text', hidden, help, onChange, ...props }) {
export function Input({ label, name, value, type = 'text', hidden, help, onChange, ...props }: InputProps) {
return (
<label hidden={hidden}>
{label}
@@ -18,7 +34,7 @@ export function Input({ label, name, value, type = 'text', hidden, help, onChang
</label>
);
}
export function Choice({ label, name, value, options, hidden, help, onChange, ...props }) {
export function Choice({ label, name, value, options, hidden, help, onChange, ...props }: ChoiceProps) {
return (
<label hidden={hidden}>
{label}
@@ -26,11 +42,11 @@ export function Choice({ label, name, value, options, hidden, help, onChange, ..
{...props}
name={name}
value={value ?? ''}
onChange={e => onChange(e.target.value)}
onChange={e => onChange?.(e.target.value)}
disabled={hidden || props.disabled}
>
{options.map(option => {
const [key, name, disabled] = Array.isArray(option) ? option : [option, option];
const [key, name, disabled] = typeof option === 'string' ? [option, option] : option;
return (
<option key={key} value={key} disabled={!!disabled}>
{name}
@@ -43,27 +59,52 @@ export function Choice({ label, name, value, options, hidden, help, onChange, ..
);
}
const money = { type: 'number', step: '0.01', min: '0' };
const categories: Record<string, string> = {
jd: 'shipping',
yt: 'shipping',
box: 'box',
steel: 'braiding',
silver: 'silverChain',
};
const amountPlaceholder = '开单前必填,没有填0';
export function EditLine({ index, line, state, ctx, form, update, reloadPools, error }) {
export function EditLine({
index,
line,
state,
ctx,
form,
update,
reloadPools,
error,
}: {
index: number;
line: LineState;
state: LedgerState;
ctx: SyncContext;
form: OrderForm;
update: UpdateForm;
reloadPools: () => void;
error: (message: string) => void;
}) {
const v = Model.lineVisibility(line, state),
p = line.purchase,
pool = line.pool,
pooled = pool?.source === 'pool',
prefix = 'cost-';
const change = fn => update(f => Model.updateLine(f, index, fn(f.lines[index])));
const prop = name => ({
const change = (fn: (line: LineState) => LineState) => update(f => Model.updateLine(f, index, fn(f.lines[index])));
const prop = (name: TextKey<LineState>) => ({
name,
value: line[name],
onChange: value => change(l => Model.setLineField(l, name, value)),
onChange: (value: string) => change(l => Model.setLineField(l, name, value)),
});
const cost = name => ({
const cost = (name: TextKey<PurchaseState>) => ({
name: prefix + name,
value: p[name],
onChange: value => change(l => Model.setPurchaseField(l, name, value)),
value: p![name],
onChange: (value: string) => change(l => Model.setPurchaseField(l, name, value)),
});
const laborFunding = p?.costFundings?.labor;
const members = value => Model.memberOptions(state, false, { selected: value });
function updateCharge(i, fn) {
const members = (value: string) => Model.memberOptions(state, false, { selected: value });
function updateCharge(i: number, fn: (charge: ChargeState) => ChargeState) {
change(l => ({ ...l, charges: l.charges.map((c, j) => (j === i ? fn(c) : c)) }));
}
return (
@@ -77,7 +118,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
try {
update(f => Model.removeLine(f, index));
} catch (err) {
error(err.message);
error(err instanceof Error ? err.message : String(err));
}
}}
>
@@ -226,7 +267,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
]}
value={pool.source}
disabled={!v.poolAllowed}
onChange={source => change(l => Model.setPoolSource(l, source))}
onChange={source => change(l => Model.setPoolSource(l, source as 'manual' | 'pool'))}
/>
<Choice
label="料价日期"
@@ -234,7 +275,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
value={pool.poolId}
options={pool.options.map(x => [x.value, x.label])}
hidden={!pooled}
onChange={poolId => change(l => ({ ...l, pool: { ...l.pool, poolId, defaultDate: false } }))}
onChange={poolId => change(l => ({ ...l, pool: { ...l.pool!, poolId, defaultDate: false } }))}
/>
<button type="button" onClick={reloadPools}>
刷新料价
@@ -272,7 +313,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
label="料费付款人"
{...cost('materialPayer')}
required
options={members(p.materialPayer)}
options={members(p!.materialPayer)}
hidden={!v.materialPayer}
/>
</div>
@@ -308,7 +349,7 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
{...cost('laborPayer')}
required
disabled={!!laborFunding}
options={members(p.laborPayer)}
options={members(p!.laborPayer)}
/>
{laborFunding && (
<input
@@ -329,8 +370,8 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
</details>
) : (
<>
{['accessories', 'other'].map(key => (
<input key={key} type="hidden" name={prefix + key} value={p[key]} />
{(['accessories', 'other'] as const).map(key => (
<input key={key} type="hidden" name={prefix + key} value={p![key]} />
))}
<input type="hidden" name="payer" value={line.payer} />
</>
@@ -341,16 +382,12 @@ export function EditLine({ index, line, state, ctx, form, update, reloadPools, e
</div>
);
}
export function EditFees({ store, state, update }) {
export function EditFees({ store, state, update }: { store: FormStore; state: LedgerState; update: UpdateForm }) {
const { form, summary } = store,
presets = form.presets;
const hasLinkedCost = kind =>
const hasLinkedCost = (kind: string) =>
form.feeRows.some(
row =>
row.funding &&
(row.key === Fees.presetKey(kind) ||
Fees.checkboxCategory(row.note) ===
{ jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' }[kind]),
row => row.funding && (row.key === Fees.presetKey(kind) || Fees.checkboxCategory(row.note) === categories[kind]),
);
return (
<section className="panel internal">
@@ -406,7 +443,8 @@ export function EditFees({ store, state, update }) {
)}
<div id="fee-rows">
{form.feeRows.map((row, i) => {
const edit = (key, value) => update(f => Model.editFeeRow(f, i, key, value));
const edit = (key: 'note' | 'payer' | 'amount' | 'date', value: string) =>
update(f => Model.editFeeRow(f, i, key, value));
const ref = row.funding;
return (
<div key={row.key} className="fee-row grid four">
@@ -0,0 +1,310 @@
import { App as AntApp } from 'antd';
import { useEffect, useRef, useState, type FormEvent, type MouseEvent } from 'react';
import { Calc, type LedgerState, type SessionInfo } from '../../shared';
import type { LedgerClient } from '../../lib/api';
import { orderViews } from './orderViews';
import { Dialog } from './Dialog';
import { useRead } from './orderReads';
import type { IndependentRequest } from './orderData';
interface SaleProps {
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
sale: { action: string; id?: string };
refreshState: () => Promise<unknown>;
refreshBook: () => void;
openList: () => void;
close: () => void;
saved: (date?: string) => void;
}
const object = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === 'object';
const messageOf = (err: unknown) => (err instanceof Error ? err.message : String(err));
const staleError = (err: unknown) => object(err) && (err.status === 403 || err.status === 404 || err.status === 409);
export function IndependentAfterSale({
client,
state,
session,
sale,
refreshState,
refreshBook,
openList,
close,
saved,
}: SaleProps) {
const { message } = AntApp.useApp();
const [review, setReview] = useState(sale.action === 'after-sale-change-open' ? sale.id || '' : '');
const [kind, setKind] = useState('');
const [error, setError] = useState('');
const [invalid, setInvalid] = useState(false);
const [date, setDate] = useState<string | null>(null);
const [savedRequest, setSavedRequest] = useState<IndependentRequest | null>(null);
const [receipt, setReceipt] = useState('');
const [generation, reload] = useState(0);
const version = useRef(0);
useEffect(
() => () => {
version.current++;
},
[],
);
const id = review || sale.id;
const path = review
? '/api/after-sales/changes/' + encodeURIComponent(review)
: sale.id
? '/api/after-sales/' + encodeURIComponent(sale.id)
: '';
const views = orderViews({ state, session });
const read = useRead(
async () => {
if (!review) await refreshState();
const data = await client.api(path);
if (!review) return { kind: 'record' as const, data: views.validateAfterSaleDetail(data, sale.id || '') };
const request = views.validateAfterSaleRequest(data);
if (request.id !== review) throw new Error('申请编号不一致,请重新读取。');
return { kind: 'request' as const, data: request };
},
path && state.user.id + '/' + path + '/' + generation,
);
const detail = read.value?.kind === 'record' ? read.value.data : undefined;
const request = savedRequest ?? (read.value?.kind === 'request' ? read.value.data : undefined);
const approval =
!!detail?.permissions &&
(detail.permissions.requiresApproval ||
!detail.permissions.canDirectEdit ||
(state.user.role !== 'owner' &&
(detail.record.date !== state.today || (date ?? detail.record.date) !== state.today)));
const blocked = !!(invalid || client.busy || client.pending());
function reset() {
version.current++;
setKind('');
setError('');
setDate(null);
setSavedRequest(null);
setReceipt('');
setInvalid(false);
reload(value => value + 1);
}
function dismiss() {
version.current++;
close();
}
function fail(err: unknown) {
const text = messageOf(err).replace('不要重新开单', id ? '不要重复提交售后修改' : '不要重复新增售后');
if (staleError(err) && id) setInvalid(true);
setError(text);
message.error(text);
}
async function finish(url: string, input: unknown, result: unknown, at: number) {
if (client.user !== state.user.id) return;
const savedDate = object(input) && typeof input.date === 'string' ? input.date : undefined;
const active = () => version.current === at && client.user === state.user.id;
if (url === '/api/after-sales') {
if (active()) saved(savedDate);
else refreshBook();
message.success('售后已保存,已计入 ' + savedDate + ' 的费用与利润');
await refreshState();
return;
}
const update = url.endsWith('/update');
const applied = update && object(result) && result.applied === true;
const text = update
? applied
? '售后修改已保存'
: '售后修改申请已提交,待店主审批'
: url.endsWith('/approve')
? '已同意售后修改'
: '已驳回售后修改申请';
if (active()) {
setKind('');
setError('');
setReceipt(text);
}
try {
await refreshState();
if (client.user !== state.user.id) return;
if (active() && applied)
saved(
object(result.record) && object(result.record.record) && typeof result.record.record.date === 'string'
? result.record.record.date
: savedDate,
);
else {
refreshBook();
if (active() && update) reset();
if (active() && !update) {
const finalRequest = views.validateAfterSaleRequest(result);
if (finalRequest.id !== review) throw new Error('申请编号不一致,请重新读取。');
setSavedRequest(finalRequest);
setReceipt('');
}
}
message.success(text);
} catch (err) {
if (active()) setError('结果已保存,刷新失败:' + messageOf(err) + '。请重新读取查看结果。');
}
}
async function handle(event: MouseEvent<HTMLDivElement>) {
const button = event.target instanceof Element && event.target.closest<HTMLElement>('[data-action]');
if (!button) return;
event.stopPropagation();
const { action, id: requestedId, kind: choice } = button.dataset;
if (action === 'close-after-sale' || action === 'after-sale-changes-close') return dismiss();
if (action === 'after-sale-changes-reload') {
version.current++;
openList();
return;
}
if (action === 'after-sale-change-open' || action === 'after-sale-edit') {
if (client.busy) return;
if (action === 'after-sale-change-open' && requestedId) setReview(requestedId);
reset();
return;
}
if (action === 'after-sale-review-decision') {
if (invalid || request?.status !== 'pending') return fail(new Error('请重新读取申请后再复核。'));
if (choice === 'approve' || choice === 'reject') setKind(choice);
setError('');
return;
}
if (action === 'after-sale-review-cancel') {
setKind('');
setError('');
return;
}
if (action === 'retry') {
const at = version.current;
try {
const restored = await client.retryPending();
if (restored) await finish(restored.job.url, restored.job.data, restored.result, at);
} catch (err) {
if (at === version.current) fail(err);
}
}
}
async function submit(event: FormEvent<HTMLDivElement>) {
event.stopPropagation();
event.preventDefault();
const node = event.target;
if (!(node instanceof HTMLFormElement)) return;
const values = Object.fromEntries(Array.from(new FormData(node), ([key, value]) => [key, String(value)]));
const at = version.current;
try {
let url, input;
if (review) {
if (state.user.role !== 'owner') throw new Error('请使用店主账号复核。');
if (blocked || request?.status !== 'pending' || node.dataset.id !== request.id || node.dataset.kind !== kind)
throw new Error('请重新读取申请后再复核。');
const note = values.note.trim();
if (kind === 'approve' && (!request.canApprove || request.stale))
throw new Error('原记录已有变动,请重新读取并核对。');
if (kind === 'reject' && !note) throw new Error('请填写驳回意见。');
if (note.length > 200) throw new Error('复核意见最多200字。');
if (kind === 'approve' && !values.verified) throw new Error('请核对修改前后内容并勾选确认。');
url = path + '/' + kind;
input = { revision: request.revision, note, ...(kind === 'approve' ? { verified: true } : {}) };
} else {
if (id && (blocked || !detail || !detail.permissions.canEdit || detail.pending || node.dataset.id !== id))
throw new Error('请重新读取售后记录后再修改。');
input = {
date: values.date,
project: values.project.trim(),
customer: values.customer.trim(),
amount: values.amount.trim(),
payer: values.payer,
};
if (!views.validOrderDate(input.date) || input.date > state.today)
throw new Error('售后日期请选择今天或之前的有效日期。');
if (!input.project || input.project.length > 100) throw new Error('售后项目请填写1~100字。');
if (!input.customer || input.customer.length > 60) throw new Error('客户请填写1~60字的称呼或代号。');
if (!views.teamMemberKeys().includes(input.payer)) throw new Error('请选择这笔售后由谁支付。');
Calc.cents(input.amount, '售后金额');
if (id && detail) {
const reason = values.reason.trim();
if (reason.length > 200) throw new Error('修改说明最多200字。');
url = path + '/update';
input = { revision: detail.revision, ...input, reason };
} else {
url = '/api/after-sales';
if (views.teamMode()) Object.assign(input, { member: values.member || views.currentMember() });
}
}
setError('');
const result = await client.mutate(url, input);
await finish(url, input, result, at);
} catch (err) {
if (at !== version.current) return;
const verified = node.elements.namedItem('verified');
if (staleError(err) && verified instanceof HTMLInputElement) verified.checked = false;
fail(err);
}
}
const reread = (
<button
type="button"
disabled={client.busy}
data-action={review ? 'after-sale-change-open' : 'after-sale-edit'}
data-id={id}
>
{review ? '重新读取申请并复核' : '重新读取售后'}
</button>
);
const feedback = error && (
<div className="error" role="alert">
{error}{' '}
{id &&
(client.pending() ? (
<button type="button" data-action="retry" disabled={client.busy}>
恢复原操作
</button>
) : (
reread
))}
</div>
);
const ui = { approval, blocked, busy: client.busy, feedback };
const panel = orderViews({ state, session, ui });
let content;
if (receipt || (path && (review ? !request : !detail))) {
content = (
<>
<button
className="dialog-close"
data-action={review ? 'after-sale-changes-close' : 'close-after-sale'}
aria-label={review ? '关闭售后修改复核' : '关闭售后记录'}
>
×
</button>
<h2>{receipt || (review ? '售后修改复核' : '修改售后')}</h2>
{read.error || error ? (
<div className="error" role="alert">
{read.error || error} {reread}
{review && <button data-action="after-sale-changes-reload">返回申请列表</button>}
</div>
) : (
<p role="status">{receipt ? '正在刷新…' : review ? '正在读取申请…' : '正在读取售后记录…'}</p>
)}
</>
);
} else if (review && request) content = panel.independentReview(request, kind);
else content = id && detail ? panel.editIndependentSale(detail) : panel.newIndependentSale();
return (
<Dialog
id={review ? 'after-sale-changes-dialog' : 'after-sale-dialog'}
ownClose
label={review ? '售后修改复核' : '售后记录'}
close={dismiss}
>
<div
onClick={handle}
onSubmit={submit}
onChange={event => {
if (event.target instanceof HTMLInputElement && event.target.name === 'date') setDate(event.target.value);
}}
>
{content}
</div>
</Dialog>
);
}
@@ -1,29 +1,70 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState, type FormEvent } from 'react';
import type { EditInputs, EditFee, EditItem, LockMaterial, LockEntry, LockEditorProps } from './editTypes';
import type { LedgerState, PresetState } from '../../shared';
type CostKey = 'material' | 'labor' | 'accessories' | 'other';
type Preview = Record<CostKey | 'total' | 'profit' | 'fees', number>;
interface CostForm {
presets: PresetState;
originals: Record<string, EditFee>;
rows: EditFee[];
originalChecked: Record<string, boolean>;
}
type FinancialInput = Pick<EditInputs, 'lines' | 'fee_items' | 'price_lock_material' | 'price_lock_extra_material'> &
Partial<Pick<EditInputs, 'date' | 'fees_date' | 'fee_cost_mode'>>;
type FeeSnapshot = {
key: string;
expense_id: string;
date?: string;
note: string;
payer: string;
amount: string | number;
funding: Record<string, unknown> | null;
};
interface FinancialSnapshot {
fees: FeeSnapshot[];
date?: string;
fees_date?: string;
fee_cost_mode: string;
lines?: (FinancialSnapshot & { lineId?: string })[];
material?: object;
extra?: object | null;
costs?: object;
}
type UpdateInput = (fields: Partial<EditInputs>) => void;
import { Calc as LedgerCalc, Fees, Model, Values } from '../../shared';
import { Button } from '../Settings/controls';
import { Input, Choice } from './EditFields';
const { yuan, grams, validateOrderIdentity } = Model;
const feeCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' };
const feeCategories: Record<string, string> = {
jd: 'shipping',
yt: 'shipping',
box: 'box',
steel: 'braiding',
silver: 'silverChain',
};
const validOrderDate = Values.validDate;
function priceLockEditAmount(value) {
function priceLockEditAmount(value: unknown) {
try {
return LedgerCalc.cents(String(value), '成本');
} catch {
return String(value ?? '');
}
}
function priceLockOrderEditMeta(entry, index) {
function priceLockOrderEditMeta(entry: LockEntry, index: number) {
return entry.priceLock.lines?.[index] || entry.priceLock;
}
function priceLockOrderEditMaterial(input, index) {
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : null);
function priceLockOrderEditMaterial(input: FinancialInput, index: number) {
return input.lines[index].price_lock_material || (input.lines.length === 1 ? input.price_lock_material : undefined);
}
function priceLockOrderEditExtra(input, index) {
function priceLockOrderEditExtra(input: FinancialInput, index: number) {
return (
input.lines[index].price_lock_extra_material || (input.lines.length === 1 ? input.price_lock_extra_material : null)
input.lines[index].price_lock_extra_material ||
(input.lines.length === 1 ? input.price_lock_extra_material : undefined)
);
}
function priceLockEditFinancialValue(input) {
function priceLockEditFinancialValue(input: FinancialInput): FinancialSnapshot {
if (input?.lines?.length > 1)
return {
date: input.date,
@@ -40,8 +81,8 @@ function priceLockEditFinancialValue(input) {
})),
fees: priceLockEditFinancialValue({ ...input, lines: [] }).fees,
};
const line = input?.lines?.[0] || {},
material = input?.price_lock_material || {},
const line: Partial<EditItem> = input?.lines?.[0] || {},
material: Partial<LockMaterial> = input?.price_lock_material || {},
extra = input?.price_lock_extra_material;
return {
date: input?.date,
@@ -80,22 +121,22 @@ function priceLockEditFinancialValue(input) {
.sort((a, b) => String(a.key).localeCompare(String(b.key))),
};
}
function priceLockEditFinancialChanged(entry, input = entry?.inputs) {
function priceLockEditFinancialChanged(entry: LockEntry, input: EditInputs = entry.inputs) {
return (
JSON.stringify(priceLockEditFinancialValue(input)) !==
JSON.stringify(priceLockEditFinancialValue(entry?.originalInputs))
);
}
function priceLockEditGramCost(mg, rate) {
function priceLockEditGramCost(mg: number, rate: string) {
return LedgerCalc.purchaseCosts({
unit: 'g',
quantity: grams(mg),
costParts: { material: '0', labor: '0', accessories: '0', other: '0' },
costMaterial: { mode: 'gram', rate },
costLabor: { mode: 'total' },
}).parts.material;
}).parts.material!;
}
function priceLockOrderEditPreview(input, entry) {
function priceLockOrderEditPreview(input: EditInputs, entry: LockEntry): Preview {
if (input.lines.length > 1) {
const costs = {
material: 0,
@@ -126,29 +167,28 @@ function priceLockOrderEditPreview(input, entry) {
order: { ...entry.order, lines: [entry.order.lines[index]] },
};
const value = priceLockOrderEditPreview(singleInput, singleEntry);
for (const key of ['material', 'labor', 'accessories', 'other']) costs[key] += value[key];
for (const key of ['material', 'labor', 'accessories', 'other'] as const) costs[key] += value[key];
});
costs.total = Object.values(costs).reduce((sum, value) => sum + value, 0);
costs.profit = entry.order.total - costs.total;
return costs;
const total = Object.values(costs).reduce((sum, value) => sum + value, 0);
return { ...costs, total, profit: entry.order.total - total };
}
const original = entry.originalInputs,
line = input.lines[0],
extraMg = entry.priceLock.extraMg,
usedMg = entry.order.lines[0].quantity - extraMg,
oldExtra = extraMg
? original.price_lock_extra_material.source === 'pool'
? original.price_lock_extra_material.amount
: priceLockEditGramCost(extraMg, original.price_lock_extra_material.rate)
? original.price_lock_extra_material!.source === 'pool'
? original.price_lock_extra_material!.amount!
: priceLockEditGramCost(extraMg, original.price_lock_extra_material!.rate)
: 0;
const originalMaterial =
input.price_lock_material.source === 'pool'
input.price_lock_material!.source === 'pool'
? LedgerCalc.cents(original.lines[0].costParts.material, '原料费') - oldExtra
: priceLockEditGramCost(usedMg, input.price_lock_material.rate),
: priceLockEditGramCost(usedMg, input.price_lock_material!.rate),
extra = extraMg
? input.price_lock_extra_material.source === 'pool'
? original.price_lock_extra_material.amount
: priceLockEditGramCost(extraMg, input.price_lock_extra_material.rate)
? input.price_lock_extra_material!.source === 'pool'
? original.price_lock_extra_material!.amount!
: priceLockEditGramCost(extraMg, input.price_lock_extra_material!.rate)
: 0;
if (!Number.isSafeInteger(originalMaterial) || originalMaterial < 0 || !Number.isSafeInteger(extra))
throw new Error('原锁料费尚未完整,请核对原料价与补重料价。');
@@ -159,14 +199,13 @@ function priceLockOrderEditPreview(input, entry) {
other: LedgerCalc.cents(line.costParts.other, '其他货品成本'),
fees: input.fee_items.reduce((total, fee) => total + LedgerCalc.cents(fee.amount, '实际费用'), 0),
};
costs.total = Object.values(costs).reduce((total, amount) => total + amount, 0);
costs.profit = entry.order.total - costs.total;
return costs;
const total = Object.values(costs).reduce((sum, amount) => sum + amount, 0);
return { ...costs, total, profit: entry.order.total - total };
}
function materialPoolRate(value) {
function materialPoolRate(value: number | null | undefined) {
return value == null ? '待补采购' : yuan(value);
}
function validatePriceLockOrderEdit(input, entry, state) {
function validatePriceLockOrderEdit(input: EditInputs, entry: LockEntry, state: LedgerState): EditInputs {
if (input.lines.length > 1) {
if (input.lines.length !== entry.order.lines.length) throw new Error('商品成本资料未完整读到,请重新读取订单。');
input.lines.forEach((line, index) => {
@@ -205,7 +244,7 @@ function validatePriceLockOrderEdit(input, entry, state) {
line = input.lines[0];
if (
!material ||
!['pool', 'manual'].includes(material.source) ||
!['pool', 'manual'].includes(material.source || '') ||
(material.source === 'pool' && entry.priceLock.materialSource !== 'pool') ||
(material.source === 'manual' && entry.priceLock.materialSource === 'pool' && !entry.priceLock.canSwitchToManual)
)
@@ -229,7 +268,7 @@ function validatePriceLockOrderEdit(input, entry, state) {
['labor', '进货总工费'],
['accessories', '配件成本'],
['other', '其他货品成本'],
])
] as const)
LedgerCalc.cents(line.costParts[key], name);
for (const fee of input.fee_items) {
LedgerCalc.cents(fee.amount, '实际费用');
@@ -247,18 +286,18 @@ function validatePriceLockOrderEdit(input, entry, state) {
}
const moneyProps = { type: 'number', min: '0', step: '0.01', required: true };
const automaticFee = fee => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
const categoryOf = kind => feeCategories[kind] || kind;
function feeCategory(fee, config) {
const automaticFee = (fee: EditFee) => fee?.system === 'credit_card' || String(fee?.key || '').startsWith('card_fee:');
const categoryOf = (kind: string) => feeCategories[kind] || kind;
function feeCategory(fee: EditFee, config: Record<string, unknown>) {
if (fee.key.startsWith('manual:') && config['custom_' + fee.key.slice(7)]) return 'custom_' + fee.key.slice(7);
if (fee.key === 'shipping' || fee.key === 'box') return fee.key;
if (String(fee.note || '').trim() === '编绳') return '';
return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName);
return Fees.checkboxCategory(fee.note) || Fees.checkboxCategory(fee.sourceName ?? '');
}
function costSetup(input, state) {
function costSetup(input: EditInputs, state: LedgerState): CostForm {
const config = Model.costConfig(state),
presets = Model.newPresets(state, input.fee_items, true),
originals = {},
originals: Record<string, EditFee> = {},
rows = [];
for (const raw of input.fee_items || []) {
const fee = { ...raw, note: raw.note || Model.feeLabels[raw.key], edited: raw.edited ?? true };
@@ -268,7 +307,7 @@ function costSetup(input, state) {
}
return { presets, originals, rows, originalChecked: { ...presets.checked } };
}
function feeTotals(cost, input, state) {
function feeTotals(cost: CostForm, input: EditInputs, state: LedgerState) {
const { items, notes } = Model.readPresets({ presets: cost.presets, member: input.member }, state);
const config = Model.costConfig(state);
const presets = items.map(item => {
@@ -294,7 +333,21 @@ function feeTotals(cost, input, state) {
});
return { items: [...others, ...presets], notes };
}
function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
function EditableFees({
input,
state,
cost,
update,
inputChange,
removeFee,
}: {
input: EditInputs;
state: LedgerState;
cost: CostForm;
update: (cost: CostForm) => void;
inputChange: UpdateInput;
removeFee: (index: number) => void;
}) {
const config = Model.costConfig(state),
catalog = Fees.presetCatalog(config),
{ presets, rows, originals } = cost,
@@ -302,11 +355,11 @@ function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
const { notes } = feeTotals(cost, input, state),
own = Model.formMember(input, state);
// 交付后改单沿用已入账项目的付款流水和日期。数量控件保留打开本单时的录入状态。
const setPreset = (kind, quantity, value) => {
const setPreset = (kind: string, quantity: boolean, value: string | boolean) => {
const name = quantity ? 'quantity' : 'checked';
update({ ...cost, presets: { ...presets, [name]: { ...presets[name], [kind]: value } } });
};
const patchRow = (index, patch) =>
const patchRow = (index: number, patch: Partial<EditFee>) =>
update({ ...cost, rows: rows.map((row, i) => (i === index ? { ...row, ...patch, edited: true } : row)) });
return (
<section className="panel internal">
@@ -511,7 +564,7 @@ function EditableFees({ input, state, cost, update, inputChange, removeFee }) {
);
}
function editPayload(input, fees, state, entry) {
function editPayload(input: EditInputs, fees: CostForm, state: LedgerState, entry: LockEntry): EditInputs {
const lines = input.lines.map(line => ({
...line,
costLabor: line.costLabor?.mode === 'gram' ? line.costLabor : { mode: 'total' },
@@ -523,17 +576,34 @@ function editPayload(input, fees, state, entry) {
fee_items: feeTotals(fees, { ...input, member: entry.order.member }, state).items,
};
}
function LockLine({ entry, state, input, multi, index, update }) {
function LockLine({
entry,
state,
input,
multi,
index,
update,
}: {
entry: LockEntry;
state: LedgerState;
input: EditInputs;
multi: boolean;
index: number;
update: UpdateInput;
}) {
const line = input.lines[index],
raw = entry.order.lines[index],
meta = priceLockOrderEditMeta(entry, index);
const mat = multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material,
const mat = (multi ? priceLockOrderEditMaterial(input, index) : input.price_lock_material)!,
extra = multi ? priceLockOrderEditExtra(input, index) : input.price_lock_extra_material,
manual = mat.source === 'manual',
pooledExtra = extra?.source === 'pool' && !!raw.priceLockExtraPool;
const gram = line.costLabor?.mode === 'gram',
payers = value => [['', '请选择'], ...Model.memberOptions(state, false, { selected: value })];
function change(linePatch = {}, material = mat, extraCost = extra) {
payers = (value: string): [string, string][] => [
['', '请选择'],
...Model.memberOptions(state, false, { selected: value }),
];
function change(linePatch: Partial<EditItem> = {}, material = mat, extraCost = extra) {
const next = { ...line, ...linePatch };
const lines = input.lines.map((r, i) =>
i === index
@@ -549,7 +619,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
: {}),
});
}
function labor(mode, value) {
function labor(mode: string, value?: string) {
const costLabor = { mode, ...(mode === 'gram' ? { rate: value ?? line.costLabor?.rate ?? '' } : {}) };
let total = line.costParts.labor;
if (mode === 'gram') {
@@ -601,7 +671,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
value={mat.source}
options={
meta.materialSource === 'pool'
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价']] : [])]
? [['pool', '保留原锁料池'], ...(meta.canSwitchToManual ? [['manual', '改为手填原锁料价'] as const] : [])]
: [['manual', '手填原锁料价']]
}
onChange={source =>
@@ -630,7 +700,7 @@ function LockLine({ entry, state, input, multi, index, update }) {
sources
.map(
s =>
(s.kind === 'personal_recovery' ? Model.memberName(state, s.member) + '个人回收料' : '公共料') +
(s.kind === 'personal_recovery' ? Model.memberName(state, s.member!) + '个人回收料' : '公共料') +
' ' +
grams(s.quantity) +
'g · ' +
@@ -792,24 +862,33 @@ function LockLine({ entry, state, input, multi, index, update }) {
);
}
export function LockOrderEditor({ client, state, session, entry, serverFeedback, onDraft, onSave, onCancel }) {
export function LockOrderEditor({
client,
state,
session,
entry,
serverFeedback,
onDraft,
onSave,
onCancel,
}: LockEditorProps) {
const [input, setInput] = useState(() => entry.inputs),
[fees, setFees] = useState(() => costSetup(entry.inputs, state));
const [reason, setReason] = useState(entry.reason || ''),
[verified, setVerified] = useState(!!entry.verified),
[error, setError] = useState(''),
[tags, setTags] = useState([]);
const textarea = useRef(null),
[tags, setTags] = useState<string[]>([]);
const textarea = useRef<HTMLTextAreaElement>(null),
lastEntry = useRef(entry.id);
useEffect(() => {
let active = true;
client
.api('/api/order-note-tags')
.api<{ tags: string[] }>('/api/order-note-tags')
.then(r => {
if (active) setTags(r.tags);
})
.catch(err => {
if (active) setError(err.message);
if (active) setError(err instanceof Error ? err.message : String(err));
});
return () => {
active = false;
@@ -819,30 +898,30 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
const wire = editPayload(input, fees, state, entry);
const approvedFinance = entry.priceLock.financeRequiresApproval && priceLockEditFinancialChanged(entry, wire);
const approval =
session.user.role === 'assistant' &&
session.user?.role === 'assistant' &&
(!entry.sameDayDirectEdit ||
!entry.directEditDate ||
entry.order.date !== entry.directEditDate ||
wire.date !== entry.directEditDate ||
approvedFinance);
function persist(next, nextFees, newReason, checked) {
function persist(next: EditInputs, nextFees: CostForm, newReason: string, checked: boolean) {
const draft = editPayload(next, nextFees, state, entry);
onDraft(draft, newReason, checked);
}
function update(fields) {
function update(fields: Partial<EditInputs>) {
const next = { ...input, ...fields };
setInput(next);
setVerified(false);
setError('');
persist(next, fees, reason, false);
}
function updateFees(value) {
function updateFees(value: CostForm) {
setFees(value);
setVerified(false);
setError('');
persist(input, value, reason, false);
}
function removeFee(index) {
function removeFee(index: number) {
const key = fees.rows[index].key;
const next = {
...input,
@@ -851,7 +930,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
...(line.charges
? {
charges: line.charges.map(charge =>
key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name) === '快递')
key === 'charge:' + charge.id || (key === 'shipping' && Fees.normalize(charge.name ?? '') === '快递')
? { ...charge, costRemoved: true }
: charge,
),
@@ -866,21 +945,22 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
setError('');
persist(next, nextFees, reason, false);
}
function editReason(value) {
function editReason(value: string) {
setReason(value);
persist(input, fees, value, verified);
}
function verify(value) {
function verify(value: boolean) {
setVerified(value);
persist(input, fees, reason, value);
}
let costs, previewError;
let costs: Preview | undefined,
previewError = '';
try {
costs = priceLockOrderEditPreview(wire, entry);
} catch (err) {
previewError = err.message;
previewError = err instanceof Error ? err.message : String(err);
}
async function save(event) {
async function save(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
try {
if (entry.user !== client.user || lastEntry.current !== entry.id)
@@ -892,7 +972,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
setError('');
await onSave(payload, reason.trim(), true, approval);
} catch (err) {
setError(err.message);
setError(err instanceof Error ? err.message : String(err));
}
}
const filteredTags = Model.filterNoteTags(tags, input.internal_note || '');
@@ -1015,7 +1095,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
update({ internal_note: Model.insertNoteTag(input.internal_note, tag) });
textarea.current?.focus();
} catch (err) {
setError(err.message);
setError(err instanceof Error ? err.message : String(err));
}
}}
>
@@ -1052,14 +1132,16 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
aria-live="polite"
>
{costs
? [
['料费', costs.material],
['进货工费', costs.labor],
['配件及其他', costs.accessories + costs.other],
['实际费用', costs.fees],
['成本合计', costs.total],
['利润预览', costs.profit],
].map(([text, value]) => (
? (
[
['料费', costs.material],
['进货工费', costs.labor],
['配件及其他', costs.accessories + costs.other],
['实际费用', costs.fees],
['成本合计', costs.total],
['利润预览', costs.profit],
] as const
).map(([text, value]) => (
<span key={text}>
{text} <strong>¥{yuan(value)}</strong>
</span>
@@ -1069,7 +1151,7 @@ export function LockOrderEditor({ client, state, session, entry, serverFeedback,
{!multi && <p className="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p>}
</section>
<section className="panel">
<div className="note" data-order-edit-approval-note hidden={session.user.role !== 'assistant'}>
<div className="note" data-order-edit-approval-note hidden={state.user.role !== 'assistant'}>
{approval
? approvedFinance
? entry.priceLock.approvalReason || entry.approvalReason || '涉及历史锁价购料或料池,请提交店主复核。'
@@ -1,18 +1,60 @@
import { App as AntApp } from 'antd';
import type { FormEvent, MouseEvent, SyntheticEvent } from 'react';
import type { LedgerState, SessionInfo } from '../../shared';
import type { LedgerClient } from '../../lib/api';
import type { usePrintStatuses } from '../../lib/printStatus';
import type {
ChangeData,
OwnershipData,
CancellationData,
ChangeRequest,
OwnershipRequest,
CancellationRequest,
DetailEntry,
OrderRecord,
OrderAfterSaleData,
OrderAfterSale,
} from './orderData';
import type { OrderUi } from './viewTypes';
import { readOrderRecord, errorStatus, errorMessage as messageOf } from './readOrder';
interface DialogProps {
selected: string;
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
refresh: () => void;
refreshState: () => Promise<unknown>;
listIds: string[] | null;
openOrder: (id: string) => void;
close: () => void;
onLost: (message: string) => void;
printStatuses: ReturnType<typeof usePrintStatuses>;
}
type FormKind = { type: 'after' } | { type: 'action' | 'change' | 'ownership' | 'cancellation'; kind: string };
type DetailForm = HTMLFormElement & { elements: HTMLFormControlsCollection & Record<string, HTMLInputElement> };
import { useOrderAccess } from './useOrderAccess';
import { useEffect, useRef, useState } from 'react';
import { Calc } from '../../shared';
import { navigate } from '../../lib/router';
import { orderViews } from './orderViews';
import { Dialog, queues, useRead } from './OrdersPage';
import { Dialog } from './Dialog';
import { queues, useRead } from './orderReads';
const stop = e => {
const stop = (e: SyntheticEvent) => {
e.stopPropagation();
e.preventDefault();
};
const messageOf = err => (err instanceof Error ? err.message : String(err));
const readForm = form => Object.fromEntries(new FormData(form));
function DetailNavigation({ ids, id, open, blocked }) {
const readForm = (form: HTMLFormElement) => Object.fromEntries(new FormData(form)) as Record<string, string>;
function DetailNavigation({
ids,
id,
open,
blocked,
}: {
ids: string[] | null;
id: string;
open: (id: string) => void;
blocked: boolean;
}) {
if (!ids) return null;
const i = ids.indexOf(id);
return (
@@ -47,13 +89,13 @@ export function OrderActionDialog({
close,
onLost,
printStatuses,
}) {
}: DialogProps) {
const base = '/api/orders/' + encodeURIComponent(id);
const [generation, reload] = useState(0),
[form, setForm] = useState(null),
[form, setForm] = useState<FormKind | null>(null),
[error, setError] = useState('');
const [ui, setUi] = useState({}),
[expenses, setExpenses] = useState([]);
const [ui, setUi] = useState<OrderUi>({}),
[expenses, setExpenses] = useState<string[]>([]);
const current = useRef(0);
useEffect(
() => () => {
@@ -62,37 +104,43 @@ export function OrderActionDialog({
[],
);
const details = useRead(async () => {
const [order, ...results] = await Promise.allSettled(
['', '/change', '/ownership', '/cancellation'].map(path => client.api(base + path)),
);
if (order.status === 'rejected') {
access.revoke(order.reason);
throw order.reason;
const [detail, change, ownership, cancellation] = await Promise.allSettled([
client.api<unknown>(base),
client.api<ChangeData>(base + '/change'),
client.api<OwnershipData>(base + '/ownership'),
client.api<CancellationData>(base + '/cancellation'),
]);
if (detail.status === 'rejected') {
access.revoke(detail.reason);
throw detail.reason;
}
if (order.value.id !== id) throw new Error('返回的订单与所选订单不一致,请重试读取。');
const order = readOrderRecord(detail.value, id);
const checks = orderViews({ state, session });
const validators = [
checks.validateOrderChangeRequest,
checks.validateOrderOwnershipRequest,
checks.validateOrderCancellationRequest,
];
const entries = results.map((r, i) => {
const entry = { id, user: state.user.id, revision: order.value.revision };
if (r.status === 'rejected') {
if (access.revoke(r.reason)) throw r.reason;
return { ...entry, error: r.reason.message };
function entry<Request, T extends { revision: number; requests: Request[] }>(
result: PromiseSettledResult<T>,
validate: (request: Request, id: string) => unknown,
): DetailEntry<T> {
const identity = { id, user: state.user.id, revision: order!.revision };
if (result.status === 'rejected') {
if (access.revoke(result.reason)) throw result.reason;
return { ...identity, error: messageOf(result.reason) };
}
try {
const data = r.value;
if (data.revision !== order.value.revision || !Array.isArray(data.requests))
const data = result.value;
if (data.revision !== order!.revision || !Array.isArray(data.requests))
throw new Error('订单已有新记录,请重新读取订单后复核。');
data.requests.forEach(request => validators[i](request, id));
return { ...entry, data };
data.requests.forEach(request => validate(request, id));
return { ...identity, data };
} catch (err) {
return { ...entry, error: err.message };
return { ...identity, error: messageOf(err) };
}
});
return { order: order.value, entries };
}
const entries = [
entry<ChangeRequest, ChangeData>(change, checks.validateOrderChangeRequest),
entry<OwnershipRequest, OwnershipData>(ownership, checks.validateOrderOwnershipRequest),
entry<CancellationRequest, CancellationData>(cancellation, checks.validateOrderCancellationRequest),
] as const;
return { order, entries };
}, [id, generation, state.user.id].join('/'));
const original = details.value?.order;
const access = useOrderAccess({ client, state, id, watch: !!original, onLost });
@@ -109,7 +157,7 @@ export function OrderActionDialog({
orderCancellationDetail: cancellation,
orderAfterSaleFormEntry: order && {
id,
revision: order.revision,
revision: order!.revision,
user: state.user.id,
forceApproval: ui.forceApproval,
},
@@ -131,7 +179,10 @@ export function OrderActionDialog({
setExpenses([]);
setUi({});
}
const loadAfter = useRead(() => client.api(base + '/after-sale'), form?.type === 'after' && id + '/' + generation);
const loadAfter = useRead(
() => client.api<OrderAfterSaleData>(base + '/after-sale'),
form?.type === 'after' && id + '/' + generation,
);
let panel,
visibleError = error;
try {
@@ -140,11 +191,11 @@ export function OrderActionDialog({
else if (!loadAfter.value) panel = <p role="status">正在读取售后资料…</p>;
else if (
loadAfter.value.orderId !== id ||
loadAfter.value.revision !== order.revision ||
loadAfter.value.revision !== order!.revision ||
!loadAfter.value.eligible ||
loadAfter.value.record ||
!views.orderAfterSalePocketKeys().length ||
order.lines.some(
order!.lines.some(
l => l.unit !== 'g' || !l.costParts || l.costParts.material == null || l.costParts.labor == null,
)
)
@@ -160,7 +211,7 @@ export function OrderActionDialog({
</div>
)),
},
}).orderAfterSaleFormHTML(order);
}).orderAfterSaleFormHTML(order!);
} else if (form?.type === 'action') panel = views.showAction(form.kind);
else if (form)
panel = {
@@ -176,11 +227,12 @@ export function OrderActionDialog({
reload(v => v + 1);
refresh();
}
async function onClick(event) {
const target = event.target.closest('[data-action]');
async function onClick(event: MouseEvent<HTMLDivElement>) {
if (!(event.target instanceof Element)) return;
const target = event.target.closest<HTMLButtonElement>('[data-action]');
if (!target) return;
event.stopPropagation();
const { action, id: targetId } = target.dataset;
const { action = '', id: targetId = '' } = target.dataset;
try {
if (action === 'close-dialog' || action === 'order-detail-prev' || action === 'order-detail-next') return;
if (action === 'print') {
@@ -201,7 +253,7 @@ export function OrderActionDialog({
if (action.includes('close') || action === 'hide-action') return clearForm();
if (client.busy || client.pending()) throw new Error('请先恢复原操作。');
if (action === 'order-after-sale-preview') {
const node = target.form;
const node = target.form as DetailForm;
const input = views.orderAfterSaleInput(node);
const version = ++current.current;
const signature = JSON.stringify(input);
@@ -216,15 +268,18 @@ export function OrderActionDialog({
}));
let result;
try {
result = await client.api(base + '/after-sale-preview', input);
result = await client.api<{ before: OrderRecord; after: OrderRecord; afterSale?: OrderAfterSale }>(
base + '/after-sale-preview',
input,
);
} catch (err) {
if (current.current === version) throw err;
return;
}
if (current.current !== version) return;
if (result.before?.id !== id || result.after?.id !== id || result.before.revision !== order.revision)
if (result.before?.id !== id || result.after?.id !== id || result.before.revision !== order!.revision)
throw new Error('售后预览与当前订单不一致,请重新读取。');
const record = result.afterSale || result.after.orderAfterSale;
const record = result.afterSale || result.after.orderAfterSale!;
views.orderAfterSaleSummaryHTML(record, { preview: true });
setUi(old => ({
...old,
@@ -236,7 +291,8 @@ export function OrderActionDialog({
}
if (action === 'order-after-sale-add-expense' || action === 'order-after-sale-remove-expense') {
current.current++;
if (target.form?.elements.verified) target.form.elements.verified.checked = false;
const form = target.form as DetailForm | null;
if (form?.elements.verified) form.elements.verified.checked = false;
setUi(v => ({
...v,
preview: null,
@@ -244,7 +300,7 @@ export function OrderActionDialog({
verified: false,
previewStatus: '资料已修改,请重新核对售后预览。',
}));
const key = target.closest('[data-expense-id]')?.dataset.expenseId;
const key = target.closest<HTMLElement>('[data-expense-id]')?.dataset.expenseId;
setExpenses(items =>
action.endsWith('add-expense') ? [...items, crypto.randomUUID()] : items.filter(x => x !== key),
);
@@ -262,7 +318,7 @@ export function OrderActionDialog({
const data = change?.data;
if (!data || change.error) throw new Error('请重新读取订单并核对修改申请。');
const eligibility = data.actions?.[kind] || data;
if (!eligibility.eligible || data.pending || order.cancellationPending)
if (!eligibility.eligible || data.pending || order!.cancellationPending)
throw new Error(eligibility.reason || '本单暂不能提交变更申请,请重新读取。');
}
setUi({ action: kind, formKey: current.current });
@@ -275,16 +331,22 @@ export function OrderActionDialog({
preview: null,
previewLoading: false,
verified: false,
stale: [403, 404, 409].includes(err.status),
stale: [403, 404, 409].includes(errorStatus(err)),
afterError: messageOf(err),
previewStatus: '预览未完成,请核对提示后重新预览。',
}));
else setError(messageOf(err));
}
}
function onChange(e) {
const target = e.target,
node = target.form;
function onChange(e: FormEvent<HTMLDivElement>) {
const target = e.target;
if (!(
target instanceof HTMLInputElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLTextAreaElement
))
return;
const node = target.form as DetailForm | null;
if (!node) return;
if (form?.type === 'action') {
const values = readForm(node);
@@ -310,14 +372,14 @@ export function OrderActionDialog({
}
if (form?.type !== 'after') return;
if (target.name === 'verified') {
setUi(old => ({ ...old, verified: target.checked }));
setUi(old => ({ ...old, verified: (target as HTMLInputElement).checked }));
return;
}
current.current++;
const data = readForm(node);
let cents = null;
try {
cents = order.netReceived - Calc.cents(data.refund_amount);
cents = order!.netReceived - Calc.cents(data.refund_amount);
} catch {
/* 未填写时保留待填写提示。 */
}
@@ -325,8 +387,8 @@ export function OrderActionDialog({
node.elements.refund_payer.value = views.orderAfterSaleAccountPayer(target.value);
node.elements.verified.checked = false;
const lines = Array.from(node.querySelectorAll('[data-after-sale-line]'), row => ({
pocket: row.querySelector('[name=return_pocket]').value,
disposition: row.querySelector('[name=return_disposition]').value,
pocket: row.querySelector<HTMLSelectElement>('[name=return_pocket]')!.value,
disposition: row.querySelector<HTMLSelectElement>('[name=return_disposition]')!.value,
}));
setUi(old => ({
...old,
@@ -336,18 +398,19 @@ export function OrderActionDialog({
verified: false,
date: data.date,
previewStatus: '资料已修改,请重新核对售后预览。',
reasonRequired: cents > 0,
reasonRequired: cents !== null && cents > 0,
retained: cents === null ? '待填写退款金额' : cents < 0 ? '退款超出净实收' : '¥' + (cents / 100).toFixed(2),
}));
}
async function submit(e) {
async function submit(e: FormEvent<HTMLDivElement>) {
stop(e);
const node = e.target,
if (!form || !(e.target instanceof HTMLFormElement)) return;
const node = e.target as DetailForm,
data = readForm(node),
kind = node.dataset.kind;
kind = node.dataset.kind!;
let submittedDirect = false;
let submittedKey;
const retryKey = e.nativeEvent.submitter?.dataset.retryKey;
let submittedKey: string | undefined;
const retryKey = ((e.nativeEvent as SubmitEvent).submitter as HTMLElement | null)?.dataset.retryKey;
try {
if (client.busy) return;
if (retryKey) {
@@ -363,15 +426,16 @@ export function OrderActionDialog({
if (client.pending()) return;
let url, payload;
if (form.type === 'after') {
payload = views.orderAfterSaleInput(node);
const input = views.orderAfterSaleInput(node);
payload = input;
if (ui.stale || ui.previewLoading || ui.preview?.signature !== JSON.stringify(payload))
throw new Error('请先重新核对本次售后预览。');
if (change?.data?.pending || order.cancellationPending || views.orderAfterSaleRecord(order))
if (change?.data?.pending || order!.cancellationPending || views.orderAfterSaleRecord(order))
throw new Error('本单已变动或有待复核申请,请重新读取。');
if (!ui.verified) throw new Error('请核对售后预览,并勾选实物、实际退款和成本确认。');
const approve = views.orderAfterSaleApproval(payload.date);
submittedDirect = !approve;
if (approve) payload.action = 'return';
if (approve) payload = { ...input, action: 'return' };
url = base + (approve ? '/change' : '/return');
} else if (form.type === 'action') {
payload = views.actionInput(node);
@@ -382,7 +446,7 @@ export function OrderActionDialog({
payload = {
...payload,
...(approve ? { action: kind } : {}),
revision: order.revision,
revision: order!.revision,
verified: data.verified === 'on',
reason: (data.change_reason || data.reason || '').trim(),
};
@@ -393,32 +457,32 @@ export function OrderActionDialog({
if (approve) url = base + '/change';
}
} else {
const info = { change, ownership, cancellation }[form.type].data,
const info = { change, ownership, cancellation }[form.type]!.data!,
req = info.pending;
if (kind === 'approve' || kind === 'reject') {
if (!req || req.status !== 'pending' || !info.canApprove) throw new Error('请重新读取后复核。');
if (
kind === 'approve' &&
(!req.canApprove || req.stale || req.order_revision !== order.revision || !data.verified)
(!req.canApprove || req.stale || req.order_revision !== order!.revision || !data.verified)
)
throw new Error('订单已有变动,请重新读取后复核。');
url = queues.find(([type]) => type === form.type)[1] + '/' + encodeURIComponent(req.id) + '/' + kind;
url = queues.find(([type]) => type === form.type)![1] + '/' + encodeURIComponent(req.id) + '/' + kind;
payload = {
...(kind === 'approve' ? { revision: req.order_revision, verified: true } : {}),
note: data.note.trim(),
};
} else if (form.type === 'ownership') {
payload = { member: data.member, revision: order.revision, reason: data.reason.trim(), verified: true };
payload = { member: data.member, revision: order!.revision, reason: data.reason.trim(), verified: true };
url = base + '/ownership';
} else {
payload = {
revision: order.revision,
revision: order!.revision,
reason: data.reason.trim(),
...(kind === 'direct' ? { date: info.directActionDate, verified: true } : {}),
...(kind === 'direct' ? { date: cancellation!.data!.directActionDate, verified: true } : {}),
};
url = base + (kind === 'direct' ? '/canceltoday' : '/cancellation');
}
if (data.legacyCountVerified) payload.legacyCountVerified = true;
if (data.legacyCountVerified) payload = { ...payload, legacyCountVerified: true };
}
const saving = client.mutate(url, payload);
submittedKey = client.pending()?.key;
@@ -428,8 +492,8 @@ export function OrderActionDialog({
} catch (err) {
if (await access.checkFailure(err)) return;
if (form.type === 'after') {
const forceApproval = err.status === 403 && submittedDirect && !client.pending();
const stale = !forceApproval && [403, 404, 409].includes(err.status);
const forceApproval = errorStatus(err) === 403 && submittedDirect && !client.pending();
const stale = !forceApproval && [403, 404, 409].includes(errorStatus(err));
if (forceApproval || stale) node.elements.verified.checked = false;
setUi(old => ({
...old,
@@ -443,10 +507,10 @@ export function OrderActionDialog({
} else if (
form.type === 'action' &&
views.orderActionUsesChangeForm(kind) &&
([403, 404, 409].includes(err.status) || (submittedKey && submittedKey === client.pending()?.key))
([403, 404, 409].includes(errorStatus(err)) || (submittedKey && submittedKey === client.pending()?.key))
) {
const forceApproval = err.status === 403 && submittedDirect && !client.pending();
const rejected = [403, 404, 409].includes(err.status);
const forceApproval = errorStatus(err) === 403 && submittedDirect && !client.pending();
const rejected = [403, 404, 409].includes(errorStatus(err));
if (rejected && node.elements.verified) node.elements.verified.checked = false;
setUi(old => ({
...old,
@@ -487,281 +551,4 @@ export function OrderActionDialog({
);
}
export function IndependentAfterSale({
client,
state,
session,
sale,
refreshState,
refreshBook,
openList,
close,
saved,
}) {
const { message } = AntApp.useApp();
const [review, setReview] = useState(sale.action === 'after-sale-change-open' ? sale.id : '');
const [kind, setKind] = useState('');
const [error, setError] = useState('');
const [invalid, setInvalid] = useState(false);
const [date, setDate] = useState(null);
const [savedRequest, setSavedRequest] = useState(null);
const [receipt, setReceipt] = useState('');
const [generation, reload] = useState(0);
const version = useRef(0);
useEffect(
() => () => {
version.current++;
},
[],
);
const id = review || sale.id;
const path = review
? '/api/after-sales/changes/' + encodeURIComponent(review)
: sale.id
? '/api/after-sales/' + encodeURIComponent(sale.id)
: '';
const views = orderViews({ state, session });
const read = useRead(
async () => {
if (!review) await refreshState();
const data = await client.api(path);
if (!review) return views.validateAfterSaleDetail(data, sale.id);
const request = views.validateAfterSaleRequest(data);
if (request.id !== review) throw new Error('申请编号不一致,请重新读取。');
return request;
},
path && state.user.id + '/' + path + '/' + generation,
);
const detail = read.value;
const request = review && (savedRequest || detail);
const approval =
!!detail?.permissions &&
(detail.permissions.requiresApproval ||
!detail.permissions.canDirectEdit ||
(state.user.role !== 'owner' &&
(detail.record.date !== state.today || (date ?? detail.record.date) !== state.today)));
const blocked = !!(invalid || client.busy || client.pending());
function reset() {
version.current++;
setKind('');
setError('');
setDate(null);
setSavedRequest(null);
setReceipt('');
setInvalid(false);
reload(value => value + 1);
}
function dismiss() {
version.current++;
close();
}
function fail(err) {
const text = messageOf(err).replace('不要重新开单', id ? '不要重复提交售后修改' : '不要重复新增售后');
if ([403, 404, 409].includes(err.status) && id) setInvalid(true);
setError(text);
message.error(text);
}
async function finish(url, input, result, at) {
if (client.user !== state.user.id) return;
const active = () => version.current === at && client.user === state.user.id;
if (url === '/api/after-sales') {
if (active()) saved(input.date);
else refreshBook();
message.success('售后已保存,已计入 ' + input.date + ' 的费用与利润');
await refreshState();
return;
}
const update = url.endsWith('/update');
const applied = update && result.applied === true;
const text = update
? applied
? '售后修改已保存'
: '售后修改申请已提交,待店主审批'
: url.endsWith('/approve')
? '已同意售后修改'
: '已驳回售后修改申请';
if (active()) {
setKind('');
setError('');
setReceipt(text);
}
try {
await refreshState();
if (client.user !== state.user.id) return;
if (active() && applied) saved(result.record?.record?.date || input.date);
else {
refreshBook();
if (active() && update) reset();
if (active() && !update) {
const finalRequest = views.validateAfterSaleRequest(result);
if (finalRequest.id !== review) throw new Error('申请编号不一致,请重新读取。');
setSavedRequest(finalRequest);
setReceipt('');
}
}
message.success(text);
} catch (err) {
if (active()) setError('结果已保存,刷新失败:' + messageOf(err) + '。请重新读取查看结果。');
}
}
async function handle(event) {
const button = event.target.closest('[data-action]');
if (!button) return;
event.stopPropagation();
const { action, id: requestedId, kind: choice } = button.dataset;
if (action === 'close-after-sale' || action === 'after-sale-changes-close') return dismiss();
if (action === 'after-sale-changes-reload') {
version.current++;
openList();
return;
}
if (action === 'after-sale-change-open' || action === 'after-sale-edit') {
if (client.busy) return;
if (action === 'after-sale-change-open') setReview(requestedId);
reset();
return;
}
if (action === 'after-sale-review-decision') {
if (invalid || request?.status !== 'pending') return fail(new Error('请重新读取申请后再复核。'));
setKind(choice);
setError('');
return;
}
if (action === 'after-sale-review-cancel') {
setKind('');
setError('');
return;
}
if (action === 'retry') {
const at = version.current;
try {
const restored = await client.retryPending();
if (restored) await finish(restored.job.url, restored.job.data, restored.result, at);
} catch (err) {
if (at === version.current) fail(err);
}
}
}
async function submit(event) {
stop(event);
const node = event.target;
const values = readForm(node);
const at = version.current;
try {
let url, input;
if (review) {
if (state.user.role !== 'owner') throw new Error('请使用店主账号复核。');
if (blocked || request?.status !== 'pending' || node.dataset.id !== request.id || node.dataset.kind !== kind)
throw new Error('请重新读取申请后再复核。');
const note = values.note.trim();
if (kind === 'approve' && (!request.canApprove || request.stale))
throw new Error('原记录已有变动,请重新读取并核对。');
if (kind === 'reject' && !note) throw new Error('请填写驳回意见。');
if (note.length > 200) throw new Error('复核意见最多200字。');
if (kind === 'approve' && !values.verified) throw new Error('请核对修改前后内容并勾选确认。');
url = path + '/' + kind;
input = { revision: request.revision, note, ...(kind === 'approve' ? { verified: true } : {}) };
} else {
if (id && (blocked || !detail.permissions.canEdit || detail.pending || node.dataset.id !== id))
throw new Error('请重新读取售后记录后再修改。');
input = {
date: values.date,
project: values.project.trim(),
customer: values.customer.trim(),
amount: values.amount.trim(),
payer: values.payer,
};
if (!views.validOrderDate(input.date) || input.date > state.today)
throw new Error('售后日期请选择今天或之前的有效日期。');
if (!input.project || input.project.length > 100) throw new Error('售后项目请填写1~100字。');
if (!input.customer || input.customer.length > 60) throw new Error('客户请填写1~60字的称呼或代号。');
if (!views.teamMemberKeys().includes(input.payer)) throw new Error('请选择这笔售后由谁支付。');
Calc.cents(input.amount, '售后金额');
if (id) {
const reason = values.reason.trim();
if (reason.length > 200) throw new Error('修改说明最多200字。');
url = path + '/update';
input = { revision: detail.revision, ...input, reason };
} else {
url = '/api/after-sales';
if (views.teamMode()) input.member = values.member || views.currentMember();
}
}
setError('');
const result = await client.mutate(url, input);
await finish(url, input, result, at);
} catch (err) {
if (at !== version.current) return;
if ([403, 404, 409].includes(err.status) && node.elements.verified) node.elements.verified.checked = false;
fail(err);
}
}
const reread = (
<button
type="button"
disabled={client.busy}
data-action={review ? 'after-sale-change-open' : 'after-sale-edit'}
data-id={id}
>
{review ? '重新读取申请并复核' : '重新读取售后'}
</button>
);
const feedback = error && (
<div className="error" role="alert">
{error}{' '}
{id &&
(client.pending() ? (
<button type="button" data-action="retry" disabled={client.busy}>
恢复原操作
</button>
) : (
reread
))}
</div>
);
const ui = { approval, blocked, busy: client.busy, feedback };
const panel = orderViews({ state, session, ui });
let content;
if (receipt || (path && !detail)) {
content = (
<>
<button
className="dialog-close"
data-action={review ? 'after-sale-changes-close' : 'close-after-sale'}
aria-label={review ? '关闭售后修改复核' : '关闭售后记录'}
>
×
</button>
<h2>{receipt || (review ? '售后修改复核' : '修改售后')}</h2>
{read.error || error ? (
<div className="error" role="alert">
{read.error || error} {reread}
{review && <button data-action="after-sale-changes-reload">返回申请列表</button>}
</div>
) : (
<p role="status">{receipt ? '正在刷新…' : review ? '正在读取申请…' : '正在读取售后记录…'}</p>
)}
</>
);
} else if (review) content = panel.independentReview(request, kind);
else content = id ? panel.editIndependentSale(detail) : panel.newIndependentSale();
return (
<Dialog
id={review ? 'after-sale-changes-dialog' : 'after-sale-dialog'}
ownClose
label={review ? '售后修改复核' : '售后记录'}
close={dismiss}
>
<div
onClick={handle}
onSubmit={submit}
onChange={event => {
if (event.target.name === 'date') setDate(event.target.value);
}}
>
{content}
</div>
</Dialog>
);
}
export { IndependentAfterSale } from './IndependentAfterSale';
@@ -1,21 +1,66 @@
import { useOrderAccess, ownershipNoticeKey } from './useOrderAccess';
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
import type { ReactNode, FormEvent, ComponentType } from 'react';
import type { LedgerClient } from '../../lib/api';
import type {
EditEntry,
EditInputs,
EditResponse,
EditPayload,
LockEditorProps,
SaveDraft,
SaveOrder,
} from './editTypes';
import type { LedgerState, OrderForm, SessionInfo } from '../../shared';
import { Model } from '../../shared';
import { navigate, searchParam } from '../../lib/router';
import { useOrderForm } from '../CreateOrder/useOrderForm';
import { EditLine, EditFees, Input, Choice } from './EditFields';
import { useRead } from './OrdersPage';
import { isRecord, errorMessage, errorStatus } from './readOrder';
import { useRead } from './orderReads';
function storedDraft(key, id) {
let saved;
interface SavedEdit {
id: string;
revision: number;
inputs: EditInputs;
reason?: string;
verified?: boolean;
}
type DraftMode = 'open' | 'reset' | 'keep' | 'review';
interface PageProps {
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
refreshState: () => Promise<LedgerState>;
registerLeaveGuard: (check: () => boolean) => () => void;
LockEditor: ComponentType<LockEditorProps>;
}
function storedDraft(key: string, id: string): SavedEdit | null {
let saved: unknown;
try {
saved = JSON.parse(localStorage.getItem(key));
saved = JSON.parse(localStorage.getItem(key) || 'null');
} catch {
return null;
}
return saved?.id === id && Number.isSafeInteger(saved.revision) && Array.isArray(saved.inputs?.lines) ? saved : null;
if (
!isRecord(saved) ||
saved.id !== id ||
typeof saved.revision !== 'number' ||
!Number.isSafeInteger(saved.revision) ||
!isRecord(saved.inputs) ||
!Array.isArray(saved.inputs.lines)
)
return null;
// Older local drafts can omit item metadata. The form loads its normal defaults when restoring those drafts.
return {
id,
revision: saved.revision,
inputs: saved.inputs as EditInputs,
...(typeof saved.reason === 'string' ? { reason: saved.reason } : {}),
verified: saved.verified === true,
};
}
function makeEntry(result, id, saved, state) {
function makeEntry(result: EditResponse, id: string, saved: SavedEdit | null, state: LedgerState): EditEntry {
if (result.eligible !== true) throw new Error(result.reason || '这张订单暂不能修改,请重新读取订单后核对。');
if (
result.order?.id !== id ||
@@ -42,13 +87,16 @@ function makeEntry(result, id, saved, state) {
for (const [index, line] of lines.entries()) {
const meta = metas[index],
lineId = meta?.lineId || meta?.id;
const material = line.price_lock_material || (lines.length === 1 && result.inputs.price_lock_material);
const extra = line.price_lock_extra_material || (lines.length === 1 && result.inputs.price_lock_extra_material);
const material = line.price_lock_material || (lines.length === 1 ? result.inputs.price_lock_material : undefined);
const extra =
line.price_lock_extra_material || (lines.length === 1 ? result.inputs.price_lock_extra_material : undefined);
if (
!['pool', 'manual'].includes(meta?.materialSource) ||
!meta ||
!['pool', 'manual'].includes(meta.materialSource) ||
!Number.isSafeInteger(meta.extraMg) ||
meta.extraMg < 0 ||
!['pool', 'manual'].includes(material?.source) ||
!material?.source ||
!['pool', 'manual'].includes(material.source) ||
(meta.extraMg > 0 && !extra) ||
(lines.length > 1 && (!line.lineId || line.lineId !== lineId || seen.has(lineId)))
)
@@ -89,7 +137,15 @@ function makeEntry(result, id, saved, state) {
};
}
function ConflictPanel({ entry, read, disabled }) {
function ConflictPanel({
entry,
read,
disabled,
}: {
entry: EditEntry;
read: (mode: DraftMode) => void;
disabled: boolean;
}) {
const order = entry.latest?.order;
return (
<section className="panel" id="order-edit-conflict" role="status">
@@ -147,18 +203,18 @@ function ConflictPanel({ entry, read, disabled }) {
);
}
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }) {
export function OrderEditPage({ client, state, session, refreshState, registerLeaveGuard, LockEditor }: PageProps) {
const activeKey = 'mm-order-edit-active-' + state.user.id;
const id = searchParam('order') || searchParam('id') || localStorage.getItem(activeKey) || '';
const key = 'mm-order-edit-' + state.user.id + '-' + id;
const [entry, setEntry] = useState(null),
const [entry, setEntry] = useState<EditEntry | null>(null),
[epoch, reset] = useState(0),
[error, setError] = useState(''),
[success, setSuccess] = useState(false),
[reading, setReading] = useState(false);
const live = useRef(false),
generation = useRef(0);
const onDraft = useCallback(
const onDraft = useCallback<SaveDraft>(
(inputs, reason, verified) => {
if (!live.current || client.user !== state.user.id) return;
localStorage.setItem(key, JSON.stringify({ id, revision: inputs.revision, inputs, reason, verified }));
@@ -166,7 +222,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
},
[id, key, activeKey, client, state.user.id],
);
const lost = message => {
const lost = (message: string) => {
live.current = false;
sessionStorage.setItem(ownershipNoticeKey(state.user.id), message);
navigate('orders', { replace: true, fromPage: true });
@@ -177,13 +233,13 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
};
const { checkFailure } = useOrderAccess({ client, state, id, watch: !!entry && !reading, onLost: lost });
const active = () => live.current && client.user === state.user.id;
async function read(mode = 'open') {
async function read(mode: DraftMode = 'open') {
if (!id || (mode !== 'open' && (client.busy || client.pending() || reading))) return;
if (mode === 'reset' && !window.confirm('改用当前已保存的订单内容?这张订单尚未保存的修改草稿将被替换。')) return;
const request = ++generation.current;
setReading(true);
try {
const result = await client.api('/api/orders/' + encodeURIComponent(id) + '/edit');
const result = await client.api<EditResponse>('/api/orders/' + encodeURIComponent(id) + '/edit');
if (!active() || request !== generation.current) return;
let draft = storedDraft(key, id);
if (mode === 'reset') draft = null;
@@ -195,7 +251,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
inputs: { ...draft.inputs, revision: result.revision },
};
const fresh = makeEntry(result, id, draft, state);
if (mode === 'review' || (mode === 'keep' && result.revision !== entry.latest?.revision)) {
if (mode === 'review' || (mode === 'keep' && result.revision !== entry?.latest?.revision)) {
fresh.conflicted = true;
fresh.verified = false;
}
@@ -205,23 +261,32 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
reset(n => n + 1);
setError('');
} catch (err) {
if (active() && request === generation.current && !(await checkFailure(err)) && active()) setError(err.message);
if (active() && request === generation.current && !(await checkFailure(err)) && active())
setError(err instanceof Error ? err.message : String(err));
} finally {
if (active() && request === generation.current) setReading(false);
}
}
const firstRead = useEffectEvent(() => read());
const cancelRead = useEffectEvent(() => {
live.current = false;
generation.current++;
});
useEffect(() => {
let disposed = false;
live.current = true;
void firstRead();
void Promise.resolve().then(() => {
if (!disposed) return firstRead();
});
return () => {
live.current = false;
generation.current++;
disposed = true;
cancelRead();
if (localStorage.getItem(activeKey) === id) localStorage.removeItem(activeKey);
};
}, [id, activeKey]);
const go = () => navigate('orders', { search: '?order=' + encodeURIComponent(id) });
async function save(inputs, reason, verified, approval) {
async function save(inputs: EditPayload, reason: string, verified: boolean, approval: boolean) {
if (!entry) return;
try {
if (entry.conflicted) throw new Error('订单已有新记录,请先读取最新订单并核对,填写内容已经保留。');
if (!reason.trim() || reason.trim().length > 200) throw new Error('请填写1~200字的修改原因。');
@@ -234,9 +299,9 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
});
} catch (err) {
if (!active() || (await checkFailure(err)) || !active()) return;
let message = err.message.replace('不要重新开单', '不要重复保存修改');
const forceApproval = err.status === 403 && session.user.role === 'assistant';
if (forceApproval || err.status === 409) {
let message = errorMessage(err).replace('不要重新开单', '不要重复保存修改');
const forceApproval = errorStatus(err) === 403 && state.user.role === 'assistant';
if (forceApproval || errorStatus(err) === 409) {
const saved = storedDraft(key, id);
const next = {
...entry,
@@ -244,7 +309,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
reason: saved?.reason ?? reason,
verified: false,
sameDayDirectEdit: forceApproval ? false : entry.sameDayDirectEdit,
conflicted: err.status === 409,
conflicted: errorStatus(err) === 409,
latest: null,
};
if (forceApproval) message += '。填写内容已保留,请重新核对并勾选后提交修改申请。';
@@ -262,7 +327,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
if (approval) navigate('orders', { search: '?order=' + encodeURIComponent(id), fromPage: true });
else {
setSuccess(true);
const date = inputs.date || entry.order.date;
const date = ('date' in inputs && inputs.date) || entry.order.date;
const bookKey = 'mm-order-book-' + state.user.id;
let before = {};
try {
@@ -275,7 +340,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
try {
await refreshState();
} catch (err) {
setError('修改已保存,最新订单暂未读到。' + err.message);
setError('修改已保存,最新订单暂未读到。' + (err instanceof Error ? err.message : String(err)));
}
}
if (success)
@@ -327,7 +392,7 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
client,
state,
session,
entry,
entry: { ...entry, priceLock: entry.priceLock },
serverFeedback,
onDraft,
onSave: save,
@@ -347,7 +412,27 @@ export function OrderEditPage({ client, state, session, refreshState, registerLe
);
}
function EditForm({ client, state, session, entry, serverFeedback, onDraft, save, go, blocked }) {
function EditForm({
client,
state,
session,
entry,
serverFeedback,
onDraft,
save,
go,
blocked,
}: {
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
entry: EditEntry;
serverFeedback: ReactNode;
onDraft: SaveDraft;
save: SaveOrder;
go: () => void;
blocked: boolean;
}) {
const { store, update, ctx, loadPools, poolError } = useOrderForm({
client,
state,
@@ -360,9 +445,9 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
const [reason, setReason] = useState(entry.reason),
[verified, setVerified] = useState(entry.verified),
[error, setError] = useState('');
const tags = useRead(() => client.api('/api/order-note-tags'), state.user.id);
const set = key => value => change(f => ({ ...f, [key]: value }));
const change = fn => {
const tags = useRead(() => client.api<{ tags: string[] }>('/api/order-note-tags'), state.user.id);
const set = (key: keyof OrderForm) => (value: string) => change(f => ({ ...f, [key]: value }));
const change = (fn: (form: OrderForm) => OrderForm) => {
setVerified(false);
update(fn);
};
@@ -375,7 +460,7 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
!entry.directEditDate ||
entry.order.date !== entry.directEditDate ||
(finance ? form.date : entry.order.date) !== entry.directEditDate);
function submit(event) {
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
try {
let input;
@@ -386,7 +471,9 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
input = {
...input,
lines: input.lines.map((line, index) => {
const controls = Array.from(rows[index].querySelectorAll('input[name],select[name]')).filter(
const controls = Array.from(
rows[index].querySelectorAll<HTMLInputElement | HTMLSelectElement>('input[name],select[name]'),
).filter(
field =>
!field.closest('.charge-row') && (field.name !== 'stockCount' || Object.hasOwn(line, 'stockCount')),
);
@@ -406,7 +493,7 @@ function EditForm({ client, state, session, entry, serverFeedback, onDraft, save
setError('');
void save(input, reason, verified, approval);
} catch (err) {
setError(err.message);
setError(err instanceof Error ? err.message : String(err));
}
}
const card = form.payment.method === '信用卡';
@@ -1,90 +1,64 @@
import { Dialog } from './Dialog';
import { useRead, queues, type Queue } from './orderReads';
import type { MouseEvent } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState, SessionInfo } from '../../shared';
import type {
BookData,
BookRow,
Filters,
ReviewList,
ChangeRequest,
OwnershipRequest,
CancellationRequest,
IndependentRequest,
} from './orderData';
interface OrdersProps {
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
refreshState: () => Promise<unknown>;
saleListStatus: string;
setSaleListStatus: (status: string) => void;
}
import { ownershipNoticeKey } from './useOrderAccess';
import { usePrintStatuses } from '../../lib/printStatus';
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { navigate, searchParam } from '../../lib/router';
import { orderViews } from './orderViews';
import { OrderActionDialog, IndependentAfterSale } from './OrderDialogs';
export const queues = [
['change', '/api/order-changes', '待变更复核', 'open-order-changes', 'order-changes-entry'],
['ownership', '/api/order-ownership-changes', '归属复核', 'order-ownership-open-list', 'order-ownership-entry'],
['cancellation', '/api/order-cancellations', '待取消复核', 'open-order-cancellations', 'order-cancellations-entry'],
['after-sale', '/api/after-sales/changes', '售后修改', 'after-sale-changes-open', 'after-sale-changes-entry'],
];
export function Dialog({ id, label, close, children, ownClose = false }) {
const ref = useRef(null);
useEffect(() => {
const node = ref.current;
node.showModal();
return () => node.close();
}, []);
return (
<dialog
id={id}
ref={ref}
aria-label={label}
onCancel={event => {
event.preventDefault();
close();
}}
>
{!ownClose && (
<button type="button" className="dialog-close" data-action="close-dialog" aria-label={label} onClick={close}>
×
</button>
)}
{children}
</dialog>
);
}
export function useRead(read, key) {
const [entry, set] = useState(null);
const task = useEffectEvent(read);
useEffect(() => {
if (!key) return;
let active = true;
Promise.resolve()
.then(() => task())
.then(
value => {
if (active) set({ key, value });
},
error => {
if (active) set({ key, error: error.message });
},
);
return () => {
active = false;
};
}, [key]);
return entry?.key === key ? entry : {};
}
function initialFilters(state) {
let saved;
function initialFilters(state: LedgerState): Filters {
const defaults: Filters = { mode: 'today', date: '', from: '', to: '', q: '', status: '', member: '', pocket: '' };
const raw = sessionStorage.getItem('mm-order-book-' + state.user.id);
if (!raw) return defaults;
let values: unknown;
try {
saved = JSON.parse(sessionStorage.getItem('mm-order-book-' + state.user.id));
values = JSON.parse(raw);
} catch {
saved = null;
return defaults;
}
return { mode: 'today', date: '', from: '', to: '', q: '', status: '', member: '', pocket: '', ...saved };
if (!values || typeof values !== 'object') return defaults;
for (const key of Object.keys(defaults) as (keyof Filters)[]) {
const value: unknown = Reflect.get(values, key);
if (typeof value === 'string') defaults[key] = value;
}
return defaults;
}
const options = rows =>
const options = (rows: readonly (readonly string[])[]) =>
rows.map(([value, name]) => (
<option key={value} value={value}>
{name}
</option>
));
export function OrdersPage({ client, state, session, refreshState, saleListStatus, setSaleListStatus }) {
export function OrdersPage({ client, state, session, refreshState, saleListStatus, setSaleListStatus }: OrdersProps) {
const [filters, setFilters] = useState(() => initialFilters(state));
const noticeKey = ownershipNoticeKey(state.user.id);
const [error, setError] = useState(() => sessionStorage.getItem(noticeKey) || '');
useEffect(() => {
sessionStorage.removeItem(noticeKey);
const failed = event => setError(previous => previous + ' ' + event.detail);
const failed = (event: Event) => setError(previous => previous + ' ' + (event as CustomEvent<string>).detail);
window.addEventListener('order-access-refresh-error', failed);
return () => window.removeEventListener('order-access-refresh-error', failed);
}, [noticeKey]);
@@ -96,10 +70,10 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
if (document.hidden || checking || client.busy) return;
checking = true;
try {
const latest = await client.api('/api/state');
const latest = await client.api<LedgerState>('/api/state');
if (active && latest.user.id === state.user.id && latest.today !== state.today) await refreshState();
} catch (err) {
if (active) setError(err.message);
if (active) setError(err instanceof Error ? err.message : String(err));
} finally {
checking = false;
}
@@ -114,19 +88,15 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
}, [client, state.user.id, state.today, refreshState]);
const [generation, reload] = useState(0);
const [selected, setSelected] = useState(searchParam('order'));
const [listIds, setListIds] = useState(null);
const [queue, setQueue] = useState('');
const [listIds, setListIds] = useState<string[] | null>(null);
const [queue, setQueue] = useState<Queue | ''>('');
const [orderStatus, setOrderStatus] = useState('pending');
const status = queue === 'after-sale' ? saleListStatus : orderStatus;
const [sale, setSale] = useState(() =>
const [sale, setSale] = useState<{ action: string; id?: string } | null>(() =>
searchParam('afterSale') ? { action: 'after-sale-edit', id: searchParam('afterSale') } : null,
);
const refresh = useCallback(() => reload(i => i + 1), []);
const currentQuery = searchParam('order');
useEffect(() => {
setSelected(currentQuery);
}, [currentQuery]);
function filter(values) {
function filter(values: Partial<Filters>) {
const next = { ...filters, ...values };
setFilters(next);
sessionStorage.setItem('mm-order-book-' + state.user.id, JSON.stringify(next));
@@ -140,11 +110,11 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
orderCancellationListStatus: status,
afterSaleChangesStatus: status,
});
let range, invalid;
let range: ReturnType<typeof views.orderBookRange> | undefined, invalid: string | undefined;
try {
range = views.orderBookRange();
} catch (err) {
invalid = err.message;
invalid = err instanceof Error ? err.message : String(err);
}
const params =
range &&
@@ -158,8 +128,8 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
});
const book = useRead(
async () => {
const data = await client.api('/api/order-book?' + params);
if (data.from !== range.from || data.date !== range.date || (data.pocket ?? '') !== filters.pocket)
const data = await client.api<BookData>('/api/order-book?' + params);
if (data.from !== range!.from || data.date !== range!.date || (data.pocket ?? '') !== filters.pocket)
throw new Error('返回账本与所选日期或货盘不一致,请重新读取。');
return data;
},
@@ -170,7 +140,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
Promise.all(
queues.map(async ([, url]) => {
try {
return (await client.api(url + '?status=pending')).counts.pending;
return (await client.api<ReviewList<unknown>>(url + '?status=pending')).counts.pending;
} catch {
return '读取失败';
}
@@ -179,21 +149,28 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
state.user.id + '/' + generation,
);
const qdef = queues.find(([kind]) => kind === queue);
const list = useRead(() => client.api(qdef[1] + '?status=' + status), queue && [queue, status, generation].join('/'));
const review =
qdef &&
list.value &&
{
change: views.orderChangeListHTML,
ownership: views.orderOwnershipListHTML,
cancellation: views.orderCancellationListHTML,
'after-sale': views.afterSaleChangeListHTML,
}[queue](list.value);
const list = useRead(
async () => {
const url = qdef![1] + '?status=' + status;
switch (queue) {
case 'change':
return views.orderChangeListHTML(await client.api<ReviewList<ChangeRequest>>(url));
case 'ownership':
return views.orderOwnershipListHTML(await client.api<ReviewList<OwnershipRequest>>(url));
case 'cancellation':
return views.orderCancellationListHTML(await client.api<ReviewList<CancellationRequest>>(url));
case 'after-sale':
return views.afterSaleChangeListHTML(await client.api<ReviewList<IndependentRequest>>(url));
}
},
queue && [queue, status, generation].join('/'),
);
const review = list.value;
let content,
bookError = invalid || book.error;
if (book.value) {
try {
const withPrint = rows =>
const withPrint = (rows: BookRow[]) =>
rows.map(row =>
printStatuses[row.printStatus?.id || row.id]
? { ...row, printStatus: printStatuses[row.printStatus?.id || row.id] }
@@ -205,20 +182,22 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
rows: withPrint(book.value.rows),
...(book.value.displayRows ? { displayRows: withPrint(book.value.displayRows) } : {}),
},
range,
range!,
);
} catch (err) {
bookError = err.message;
bookError = err instanceof Error ? err.message : String(err);
}
}
const openOrder = (id, fromList = false) => {
const openOrder = (id: string, fromList = false) => {
setQueue('');
setError('');
setListIds(
fromList
? [
...new Set(
book.value.rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind)).map(row => row.id),
book
.value!.rows.filter(row => !['afterSale', 'orderAfterSale'].includes(row.kind ?? ''))
.map(row => row.id),
),
]
: null,
@@ -229,7 +208,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
setSelected('');
if (searchParam('order')) navigate('orders', { replace: true, fromPage: true });
}
function lostAccess(message) {
function lostAccess(message: string) {
setListIds(null);
setQueue('');
setSelected('');
@@ -239,12 +218,13 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
navigate('orders', { replace: true, fromPage: true });
}
refresh();
void refreshState().catch(err => setError(message + ' ' + err.message));
void refreshState().catch(err => setError(message + ' ' + (err instanceof Error ? err.message : String(err))));
}
function click(event) {
const node = event.target.closest('[data-action]');
if (!node || event.defaultPrevented) return;
const { action, id, period, status: newStatus } = node.dataset;
function click(event: MouseEvent<HTMLElement>) {
if (!(event.target instanceof Element)) return;
const node = event.target.closest<HTMLElement>('[data-action]');
if (!node || !node.dataset.action || event.defaultPrevented) return;
const { action = '', id = '', period, status: newStatus } = node.dataset;
const match = queues.find(row => row[3] === action);
if (match) {
setQueue(match[0]);
@@ -273,7 +253,9 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
});
if (action === 'refresh' || action.includes('retry') || action.includes('reload')) refresh();
}
const countSum = counts.value?.every(Number.isInteger) ? counts.value.reduce((acc, n) => acc + n, 0) : null;
const countSum = counts.value?.every((n): n is number => typeof n === 'number' && Number.isInteger(n))
? counts.value.reduce((acc, n) => acc + n, 0)
: null;
const memberOptions = (state.members || []).map(m => [
m.member,
views.teamMemberName(m.member) + (m.enabled === false ? '(已停用)' : ''),
@@ -306,7 +288,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
(state.user.role === 'owner' ? '跨日期查看售后修改,核对原值与申请值后复核。' : '查看自己归属售后的修改申请。') +
'待审批期间仍按原记录计账。',
],
}[queue];
}[queue || 'change'];
return (
<div className="business-pages" onClick={click}>
<div className="page-heading">
@@ -365,7 +347,7 @@ export function OrdersPage({ client, state, session, refreshState, saleListStatu
/>
</label>
<div id="order-range-fields" hidden={filters.mode !== 'range'}>
{['from', 'to'].map((key, i) => (
{(['from', 'to'] as const).map((key, i) => (
<label key={key}>
{i ? '结束' : '开始'}日期
<input
@@ -0,0 +1,152 @@
import type { ReactNode } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState, OrderDraft, SessionInfo } from '../../shared';
export interface EditFee extends Record<string, unknown> {
key: string;
note: string;
payer: string;
amount: string;
status?: string;
date?: string;
edited?: boolean;
funding?: Record<string, unknown>;
sourceName?: string;
lineNumber?: number;
system?: string;
expense_id?: string;
chargeId?: string;
source_kind?: string;
source_id?: string;
}
export interface LockMaterial {
source?: string;
rate: string;
payer: string;
amount?: number;
verified: boolean;
}
export interface EditItem extends Record<string, unknown> {
lineId?: string;
name: string;
unit: string;
quantity: string;
payer: string;
costParts: { material: string; labor: string; accessories: string; other: string };
costPayers: { material: string; labor: string };
costLabor: { mode: string; rate?: string };
charges?: { id?: string; costRemoved?: boolean; name?: string }[];
costFundings?: { labor?: Record<string, unknown> };
price_lock_material?: LockMaterial;
price_lock_extra_material?: LockMaterial;
}
export interface EditInputs extends OrderDraft {
note: string;
date: string;
fees_date: string;
fee_cost_mode: string;
member?: string;
customer_type?: string;
lines: EditItem[];
fee_items: EditFee[];
price_lock_material?: LockMaterial;
price_lock_extra_material?: LockMaterial;
}
export interface LockLineMeta {
id: string;
lineId?: string;
line_index?: number;
lockedMg: number;
materialSource: string;
materialLocked: boolean;
canSwitchToManual: boolean;
extraMg: number;
}
export interface LockEditMeta extends LockLineMeta {
date: string;
lines?: LockLineMeta[];
financeRequiresApproval: boolean;
approvalReason?: string;
}
export interface PoolCost {
poolId: string;
date: string;
amount: number | null;
averageRate: number | null;
allocations: { payer: string; amount: number }[];
materialSources?: {
kind: string;
quantity: number;
amount: number | null;
averageRate?: number | null;
member?: string;
}[];
}
export interface EditOrderRecord {
id: string;
number: string;
date: string;
paper_date: string;
paper_number: string;
member: string;
customer: string;
salesperson: string;
note: string;
internal_note?: string;
payment_account: string;
total: number;
directCost: number;
rounding_mode: string;
price_lock_id?: string;
lines: {
name: string;
unit: string;
quantity: number;
sale: number;
cost: number | null;
pocket: string;
goldPrice?: number;
priceLockPool?: PoolCost;
materialPool?: PoolCost;
priceLockExtraPool?: PoolCost;
}[];
}
export interface EditResponse {
eligible: boolean;
reason: string;
revision: number;
inputs: EditInputs;
order: EditOrderRecord;
priceLock?: LockEditMeta | null;
requiresApproval?: boolean;
financialEditable: boolean;
directEditDate?: string;
approvalReason?: string;
requiresLegacyCountVerified?: boolean;
legacyCountNotice?: string;
}
export interface EditEntry extends EditResponse {
id: string;
user: string;
reason: string;
verified: boolean;
originalInputs: EditInputs;
sameDayDirectEdit: boolean;
conflicted: boolean;
latest?: EditResponse | null;
}
export type LockEntry = EditEntry & { priceLock: LockEditMeta };
export type SaveDraft = (inputs: OrderDraft, reason: string, verified: boolean) => void;
export type EditPayload =
OrderDraft | { customer: string; salesperson: string; customer_type?: string; note: string; internal_note: string };
export type SaveOrder = (inputs: EditPayload, reason: string, verified: boolean, approval: boolean) => Promise<void>;
export interface LockEditorProps {
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
entry: LockEntry;
serverFeedback: ReactNode;
onDraft: SaveDraft;
onSave: SaveOrder;
onCancel: () => void;
}
@@ -0,0 +1,774 @@
export interface OrderRecord {
id: string;
number: string;
date: string;
customer: string;
salesperson: string;
note: string;
paper_number: string;
status: string;
lines: OrderLine[];
discount: number;
total: number;
revision: number;
reviewed_revision: number;
created: string;
delivered_date: null | string;
returned_date: null | string;
paper_date: string;
payment_account: string;
fee_items: Fee[];
fees_date: string;
rounding_mode: string;
internal_note: string;
fee_cost_mode: string;
customer_type: string;
member: string;
cancellationPending?: CancellationRequest | null;
cancellationApproved?: null | CancellationRequest;
changePending?: ChangeRequest | null;
ownershipPending: OwnershipRequest | null;
payments: Payment[];
expenses: Expense[];
settlements: Settlement[];
corrections: Correction[];
netReceived: number;
balance: number;
rounding_adjustment: number;
goodsCost: number | null;
directCost: number;
materialCostPending: boolean;
knownGoodsCost: number;
pendingFees: Fee[];
profit: number | null;
ownerCost: number;
ownerDirect: number;
ownerCredit: number;
costTransferred: number;
profitTransferred: number;
costDue: number;
profitDue: number;
settlementDue: number | null;
audit?: OrderRecordAudit[];
funds_mode: string;
credit_card_rate_permille?: number;
printStatus?: PrintStatus;
orderAfterSale?: OrderAfterSale;
assistantInventoryCredit?: number;
assistantInventoryCreditExplanation?: string;
kind?: string;
price_lock_id?: string;
recovery_id?: string;
recovery_mode?: string;
priceLockCosts?: LockCosts;
}
export interface BookData {
from: string;
date: string;
pocket: string;
rows: BookRow[];
displayRows?: BookRow[];
recoveryCount: number;
summary: BookSummary;
priceLockActivity: LockActivity;
summaryWithoutCancelled: BookSummary;
receiptsWithoutCancelled: ReceiptSummary;
}
export interface ChangeRequest {
id: string;
order_id: string;
order_revision: number;
action: string;
reason: string;
status: 'pending' | 'approved' | 'rejected';
requester_name: string;
created: string;
reviewer_name: null | string;
reviewed: null | string;
note: string;
action_label: string;
order_number?: string;
order_date?: string;
stale?: boolean;
canApprove?: boolean;
before: OrderRecord;
after: OrderRecord;
summary: ChangeSummary;
relatedOrders?: RelatedOrder[];
action_details?: ChangeActionInput;
action_input?: ChangeActionInput;
relatedPriceLocks?: RelatedLock[];
}
export interface OwnershipRequest {
id: string;
order_id: string;
order_revision: number;
reason: string;
status: 'pending' | 'approved' | 'rejected';
direct: boolean;
requester_name: string;
created: string;
reviewer_name: null | string;
reviewed: null | string;
note: string;
before: Member;
after: Member;
order_number?: string;
order_customer?: string;
order_date?: string;
stale?: boolean;
canApprove?: boolean;
}
export interface CancellationRequest {
executedAt?: string;
operator_name?: string;
id: string;
order_id: string;
order_revision: number;
reason: string;
status: 'pending' | 'approved' | 'rejected';
requester_name: string;
created: string;
reviewer_name: null | string;
reviewed: null | string;
note: string;
order_number?: string;
order_date?: string;
requiresLegacyCountVerified?: boolean;
legacyCountNotice?: string;
stale?: boolean;
canApprove?: boolean;
summary: CancelSummary;
direct?: boolean;
}
export interface ChangeData {
eligible: boolean;
reason: string;
actions: ActionRules;
directActionDate: string;
revision: number;
pending: ChangeRequest | null;
requests: ChangeRequest[];
canApprove: boolean;
}
export interface OwnershipData {
eligible: boolean;
reason: string;
revision: number;
member: string;
members: Member[];
requiresApproval: boolean;
canDirect: boolean;
canApprove: boolean;
pending: OwnershipRequest | null;
requests: OwnershipRequest[];
}
export interface CancellationData {
eligible: boolean;
reason: string;
revision: number;
requiresLegacyCountVerified: boolean;
legacyCountNotice: string;
directActionDate: string;
directToday: boolean;
pending: CancellationRequest | null;
requests: CancellationRequest[];
canApprove: boolean;
summary?: CancelSummary;
}
export interface OrderAfterSaleData {
orderId: string;
revision: number;
eligible: boolean;
blockedReason: string;
record: null | OrderAfterSale;
}
export interface IndependentDetail {
id: string;
revision: number;
record: IndependentRecord;
values: IndependentValues;
permissions: AfterPermissions;
pending: IndependentRequest | null;
history: IndependentRequest[];
}
export interface IndependentRequest {
id: string;
afterSaleId: string;
revision: number;
recordRevision: number;
status: 'pending' | 'approved' | 'rejected';
reason: string;
before: IndependentValues;
after: IndependentValues;
member: string;
requesterName: string;
created: string;
reviewerName: string | null;
reviewed: string | null;
note: string;
stale: boolean;
staleReason: string;
canApprove: boolean;
}
export interface OrderLine {
name: string;
code: string;
unit: string;
quantity: number;
pocket: string;
payer: string;
cost: number;
sale: number;
baseSale: number;
charges: Charge[];
pricingMode: string;
priceNote: string;
costPayers?: OrderLineCostPayers;
costParts?: CostParts;
costMaterial?: CostMode;
costLabor?: CostMode;
goldPrice?: number;
laborRate?: number;
laborMode?: string;
pieces?: number;
materialPool?: LinePool;
stockCount?: number | null;
priceLockPool?: LinePool;
priceLockExtraPool?: LinePool;
}
export interface OrderRecordAudit {
action: string;
actor: string;
detail: { reason?: string };
created: string;
}
export interface PrintStatus {
kind: string;
id: string;
printed: boolean;
revision?: number;
actor?: string | null;
}
export interface Fee {
key: string;
system?: string;
source_kind?: string;
source_id?: string;
date?: string;
amount: number;
payer: string;
note: string;
status: string;
expense_id?: string;
edited?: boolean;
lineNumber?: number;
sourceName?: string;
}
export interface Payment {
price_lock_event_id?: string;
id: string;
order_id: string;
date: string;
kind: string;
amount: number;
account: string;
reference: string;
actor: string;
created: string;
}
export interface Expense {
id: string;
order_id: string;
date: string;
amount: number;
payer: string;
note: string;
actor: string;
created: string;
}
export interface Correction {
target: string;
type: string;
reason: string;
actor: string;
created: string;
}
export interface BookRow {
[key: `${string}Cost`]: number | null | undefined;
assistant2Cost?: number;
id: string;
order_id?: string;
kind?: string;
orderAfterSale?: OrderAfterSale;
member?: string;
number: string;
paper_number: string;
date: string;
order_date?: string;
created: string;
customer: string;
salesperson: string;
status: string;
note: string;
project?: string;
types: string[];
mg: number;
pieces: number;
originalSale?: number;
sale?: number;
material?: number | null;
laborAndFees?: number | null;
unallocated?: number;
totalCost?: number;
profit?: number;
ownerCost?: number;
assistantCost?: number;
known?: Known;
costItems?: BookCost[];
laborAndFeeItems?: BookCost[];
pendingCosts?: number;
unknownCosts?: number;
legacyUnallocated?: boolean;
incomplete?: boolean;
costHint: string;
balance?: number;
revision?: number;
reviewed_revision?: number;
funds_mode?: string;
price_lock_id?: string;
recovery_id?: string;
recovery_mode?: string;
cancellationApproved?: CancellationRequest | null;
materialCostPending?: boolean;
printStatus?: PrintStatus;
after_sale_id?: string;
amount?: number;
payer?: string;
cashPayment?: number;
}
export interface BookSummary {
[key: `${string}Cost`]: number;
assistant2Cost: number;
orderCount: number;
completedCount: number;
draftCount: number;
cancelledCount: number;
incompleteCount: number;
pendingCosts: number;
unknownCosts: number;
unknownCostCount: number;
unknownProfitCount: number;
sale: number;
material: number;
laborAndFees: number;
unallocated: number;
totalCost: number;
profit: number;
ownerCost: number;
assistantCost: number;
mg: number;
pieces: number;
knownCounts: Counts;
unknownCounts: Counts;
afterSaleCount: number;
recordCount: number;
}
export interface LockActivity {
basis: string;
from: string;
date: string;
customerCash: LockActivityRow[];
orderPayments: LockActivityRow[];
materialOutlays: LockActivityRow[];
directOutlays: LockActivityRow[];
deliveryGoodsOutlays: LockActivityRow[];
summary: LockActivitySummary;
}
export interface ReceiptSummary {
basis: string;
filterScope: string;
from: string;
date: string;
receipt: number;
refund: number;
net: number;
channels: ReceiptSummaryChannels[];
orderCount: number;
}
export interface ChangeSummary {
before: CostSummary;
after: CostSummary;
inventory: InventoryChange;
}
export interface Member {
member: string;
label: string;
enabled?: boolean;
}
export interface CancelSummary extends CostSummary {
legacyCountNotice?: string;
requiresLegacyCountVerified?: boolean;
inventory: InventoryRow[];
}
export interface ActionRules {
[kind: string]: ActionRule;
}
export interface OrderAfterSale {
orderId: string;
date: string;
reason: string;
deductionReason: string;
refund: Refund;
expenses: { note: string; amount: number; payer: string }[];
summary: AfterSummary;
lines: AfterSaleLine[];
order_id?: string;
created?: string;
number?: string;
paper_number?: string;
customer?: string;
salesperson?: string;
note?: string;
order_date?: string;
member?: string;
}
export interface IndependentRecord {
id: string;
date: string;
project: string;
customer: string;
amount: number;
payer: string;
actor: string;
created: string;
member: string;
revision: number;
}
export interface IndependentValues {
date: string;
project: string;
customer: string;
amount: string | number;
payer: string;
}
export interface AfterPermissions {
canEdit: boolean;
canDirectEdit: boolean;
requiresApproval: boolean;
reason: string;
}
export interface OrderLineCostPayers {
[component: string]: string;
material: string;
labor: string;
accessories: string;
other: string;
}
export interface CostParts {
[component: string]: number | null;
material: number | null;
labor: number | null;
accessories: number | null;
other: number | null;
}
export interface CostMode {
mode: string;
rate?: number | null;
poolId?: string;
}
export interface Charge {
id: string;
name: string;
amount: number;
}
export interface LinePool {
poolId: string;
date: string;
status: string;
amount: number;
quantity: number;
averageRate: number;
allocations: LinePoolAllocations[];
revision: string;
}
export interface Known {
[key: `${string}Cost`]: number | undefined;
assistant2Cost?: number;
sale: number;
material: number;
laborAndFees: number;
unallocated: number;
totalCost: number;
profit: number;
ownerCost: number;
assistantCost: number;
}
export interface BookCost {
kind: string;
component: string;
name: string;
source: string;
amount: number;
payer: string;
materialPoolId?: string;
calculation?: BookCostCalculation;
excluded?: boolean;
priceLockSource?: string;
after_sale_id?: string;
}
export interface Counts {
[key: `${string}Cost`]: number;
assistant2Cost: number;
sale: number;
material: number;
laborAndFees: number;
unallocated: number;
totalCost: number;
profit: number;
ownerCost: number;
assistantCost: number;
}
export interface LockActivityRow {
id: string;
price_lock_id: string;
date: string;
kind: string;
amount: number;
account?: string;
number: string;
customer: string;
product?: string;
actor?: string;
created?: string;
line_index?: null | number;
voided?: number;
payer?: string;
source?: string;
quantity?: number;
rate?: number;
component?: string;
order_id?: string;
note?: string;
name?: string;
excluded?: boolean;
calculation?: null;
paper_number?: string;
}
export interface LockActivitySummary {
receipt: number;
refund: number;
net: number;
ownerOutlay: number;
assistantOutlay: number;
eventCount: number;
}
export interface ReceiptSummaryChannels {
channel: string;
name: string;
receipt: number;
refund: number;
net: number;
}
export interface CostSummary {
total: number;
netReceived: number;
directCost: number;
goodsCost: number | null;
profit: number | null;
settlementDue: number | null;
}
export interface InventoryChange {
legacyCountNotice?: string;
before: InventoryRow[];
after: InventoryRow[];
changes: InventoryRow[];
}
export interface InventoryRow {
stockCount?: number | null;
date: string;
pocket: string;
mg: number;
kind?: string;
}
export interface ActionRule {
eligible: boolean;
reason: string;
directToday?: boolean;
}
export interface Refund {
amount: number;
account: string;
payer: string;
reference: string;
}
export interface AfterSummary {
refundAmount: number;
retainedAmount: number;
materialReturnedCost: number;
laborRestockedCost: number;
costLoss: number;
directCost: number;
profit: number;
profitAdjustment: number;
}
export interface AfterSaleLine {
lineIndex: number;
name: string;
code: string;
quantity: number;
pocket: string;
disposition: string;
stockCount: null;
materialReturnedCost: number;
laborRestockedCost: number;
laborPayer: string;
costLoss: number;
}
export interface LinePoolAllocations {
payer: string;
amount: number;
}
export interface BookCostCalculation {
rate: number;
quantity: number;
weighted?: boolean;
}
export interface Settlement {
bucket: string;
id: string;
date: string;
amount: number;
kind: string;
note: string;
actor: string;
}
export interface RelatedOrder {
id: string;
number: string;
date: string;
customer: string;
before: OrderRecord;
after: OrderRecord;
summary: ChangeSummary;
}
export interface LockImpact {
materialAmount: number | null;
usedMaterialAmount?: number | null;
leftoverCost?: number | null;
allocations: { payer: string; amount: number }[];
}
export interface RelatedLock {
id: string;
number: string;
date: string;
customer: string;
before: LockImpact;
after: LockImpact;
}
export interface LockCosts {
date?: string;
lines?: LockCosts[];
lineId?: string;
materialSource?: string;
buyRate?: number;
buyPayer?: string;
materialAmount?: number | null;
extraRate?: number;
extraPayer?: string;
}
export interface Filters {
mode: string;
date: string;
from: string;
to: string;
q: string;
status: string;
member: string;
pocket: string;
}
export interface ReviewList<T> {
requests: T[];
counts: Record<string, number>;
canApprove?: boolean;
}
export interface DetailEntry<T> {
id: string;
revision: number;
user: string;
data?: T;
error?: string;
}
export type MoneyKey =
| 'sale'
| 'material'
| 'laborAndFees'
| 'unallocated'
| 'totalCost'
| 'profit'
| 'ownerCost'
| 'assistantCost'
| `${string}Cost`;
export interface ChangeActionInput {
date?: string;
amount?: string;
account?: string;
payer?: string;
note?: string;
reference?: string;
afterSale?: object;
returnCounts?: (string | number | null)[];
returnPockets?: string[];
fee_items?: { note: string; amount: string; payer: string }[];
}
@@ -0,0 +1,34 @@
import { useState, useEffect, useEffectEvent } from 'react';
export type Queue = 'change' | 'ownership' | 'cancellation' | 'after-sale';
export const queues: readonly (readonly [Queue, string, string, string, string])[] = [
['change', '/api/order-changes', '待变更复核', 'open-order-changes', 'order-changes-entry'],
['ownership', '/api/order-ownership-changes', '归属复核', 'order-ownership-open-list', 'order-ownership-entry'],
['cancellation', '/api/order-cancellations', '待取消复核', 'open-order-cancellations', 'order-cancellations-entry'],
['after-sale', '/api/after-sales/changes', '售后修改', 'after-sale-changes-open', 'after-sale-changes-entry'],
];
export function useRead<T>(
read: () => Promise<T>,
key: string | false | null | undefined,
): { value?: T; error?: string } {
const [entry, set] = useState<{ key: string; value?: T; error?: string } | null>(null);
const task = useEffectEvent(read);
useEffect(() => {
if (!key) return;
let active = true;
Promise.resolve()
.then(() => task())
.then(
value => {
if (active) set({ key, value });
},
error => {
if (active) set({ key, error: error.message });
},
);
return () => {
active = false;
};
}, [key]);
return entry && entry.key === key ? entry : {};
}
@@ -1,10 +1,11 @@
import type { OrderContext } from './viewTypes';
import { sharedViews } from './views/sharedViews';
import { orderBook } from './views/orderBook';
import { orderDetail } from './views/orderDetail';
import { orderActions } from './views/orderActions';
import { orderReviews } from './views/orderReviews';
import { afterSales } from './views/afterSales';
export function orderViews(context) {
export function orderViews(context: OrderContext) {
const shared = sharedViews(context);
return {
...shared,
@@ -0,0 +1,21 @@
import type { OrderRecord } from './orderData';
export const isRecord = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === 'object';
export const errorStatus = (error: unknown) => (isRecord(error) && typeof error.status === 'number' ? error.status : 0);
export const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));
function isOrderDetail(value: Record<string, unknown>): value is Record<string, unknown> & OrderRecord {
return (
['date', 'number', 'status', 'member'].every(key => typeof value[key] === 'string') &&
['revision', 'total', 'balance', 'netReceived'].every(key => Number.isSafeInteger(value[key])) &&
['lines', 'payments', 'expenses', 'settlements', 'corrections', 'fee_items', 'pendingFees', 'audit'].every(key =>
Array.isArray(value[key]),
)
);
}
export function readOrderRecord(value: unknown, id: string): OrderRecord {
if (!isRecord(value) || value.id !== id) throw new Error('返回的订单与所选订单不一致,请重试读取。');
if (!isOrderDetail(value)) throw new Error('订单详情未完整返回,请重新读取订单。');
return value;
}
@@ -1,13 +1,29 @@
import { useCallback, useEffect, useRef } from 'react';
import type { LedgerState } from '../../shared';
interface OrderAccess {
client: { user: string; busy: boolean; pending: () => unknown; api: (url: string) => Promise<unknown> };
state: { user: Pick<LedgerState['user'], 'id' | 'role'> };
id: string;
watch: boolean;
onLost: (message: string) => void;
}
interface ActiveOrder {
user: string;
id: string;
request: number;
}
export const ownershipNotice = '订单归属或权限已更新,本账号已不能查看这张订单。';
export const ownershipNoticeKey = user => 'mm-order-access-notice-' + user;
const denied = error => [403, 404].includes(error?.status);
export const ownershipNoticeKey = (user: string) => 'mm-order-access-notice-' + user;
const denied = (error: unknown) =>
!!error && typeof error === 'object' && 'status' in error && (error.status === 403 || error.status === 404);
// 同一账号可以从“当天直接修改”降为“须申请”。只有订单归属查询也拒绝访问,才清除该账号的该单草稿。
export function useOrderAccess({ client, state, id, watch, onLost }) {
export function useOrderAccess({ client, state, id, watch, onLost }: OrderAccess) {
const user = state.user.id;
const scope = useRef(null);
const scope = useRef<ActiveOrder | null>(null);
const lost = useRef(onLost);
useEffect(() => {
lost.current = onLost;
@@ -20,7 +36,7 @@ export function useOrderAccess({ client, state, id, watch, onLost }) {
};
}, [user, id]);
const revoke = useCallback(
(error, current = scope.current) => {
(error: unknown, current = scope.current) => {
if (state.user.role !== 'assistant' || !denied(error)) return false;
if (!current || scope.current !== current || client.user !== current.user) return true;
localStorage.removeItem('mm-order-edit-' + user + '-' + id);
@@ -45,7 +61,7 @@ export function useOrderAccess({ client, state, id, watch, onLost }) {
}
return scope.current !== current || client.user !== user || request !== current.request;
}, [client, id, state.user.role, user, revoke]);
const checkFailure = useCallback(error => (denied(error) ? check() : Promise.resolve(false)), [check]);
const checkFailure = useCallback((error: unknown) => (denied(error) ? check() : Promise.resolve(false)), [check]);
useEffect(() => {
if (!watch || state.user.role !== 'assistant') return;
const focus = () => {
@@ -0,0 +1,62 @@
import type { ReactNode } from 'react';
import type { LedgerState, SessionInfo } from '../../shared';
import type {
CancellationData,
ChangeData,
DetailEntry,
Filters,
OrderAfterSale,
OrderRecord,
OwnershipData,
} from './orderData';
import type { sharedViews } from './views/sharedViews';
export type SharedViews = ReturnType<typeof sharedViews>;
export type Options = ReadonlyArray<string | readonly [string, string, boolean?]>;
export interface OrderUi {
action?: string;
forceApproval?: boolean;
actionBlocked?: boolean;
retryBusy?: boolean;
retryKey?: string | null;
pendingKey?: string;
actionError?: string;
stale?: boolean;
formKey?: string | number;
date?: string;
lastCardBasis?: string;
values?: Record<string, string>;
paymentMethod?: string;
recipient?: string;
afterError?: string;
busy?: boolean;
approval?: boolean;
blocked?: boolean;
lines?: { pocket: string; disposition: string }[];
reasonRequired?: boolean;
retained?: string;
previewLoading?: boolean;
previewStatus?: string;
expenses?: ReactNode;
feedback?: ReactNode;
verified?: boolean;
preview?: { record: OrderAfterSale; signature?: string } | null;
}
export interface OrderContext {
state: LedgerState;
session: SessionInfo;
currentOrder?: OrderRecord;
orderBookFilters?: Filters;
detailForm?: ReactNode;
navigation?: ReactNode;
error?: string;
orderChangeDetail?: DetailEntry<ChangeData>;
orderCancellationDetail?: DetailEntry<CancellationData>;
orderOwnershipDetail?: DetailEntry<OwnershipData>;
orderAfterSaleFormEntry?: { id: string; revision: number; user: string; forceApproval?: boolean };
ui?: OrderUi;
orderChangeListStatus?: string;
orderOwnershipListStatus?: string;
orderCancellationListStatus?: string;
afterSaleChangesStatus?: string;
}
@@ -0,0 +1,201 @@
import { useState } from 'react';
import { Calc as LedgerCalc } from '../../../shared';
import type { OrderLine } from '../orderData';
import type { SharedViews } from '../viewTypes';
type CostModeKey = 'material' | 'labor';
type CostInputs = Record<string, string>;
type LineProps = { line: OrderLine; index: number; members: SharedViews['teamMemberOptions']; fallback: string } & Pick<
SharedViews,
'choice' | 'opts' | 'grams' | 'yuan'
>;
const asMoney = (value?: number | null) => (value == null ? '' : (value / 100).toFixed(2));
const costKeys = Object.keys(LedgerCalc.costLabels);
function costBreakdown(
line: OrderLine,
quantity: string | number,
parts: CostInputs,
modes: CostInputs,
rates: CostInputs,
) {
const input: {
unit: string;
quantity: string | number;
costParts: CostInputs;
costMaterial?: { mode: string; rate?: string };
costLabor?: { mode: string; rate?: string };
} = { unit: line.unit, quantity, costParts: parts };
for (const [key, property] of [
['material', 'costMaterial'],
['labor', 'costLabor'],
] as const) {
input[property] = modes[key] === 'gram' ? { mode: 'gram', rate: rates[key] } : { mode: 'total' };
}
return LedgerCalc.purchaseCosts(input);
}
export function LegacyCostRow({ line, index, members, fallback, choice, opts, grams, yuan }: LineProps) {
const prefix = 'cost-' + index + '-';
const quantity = line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity;
const initialParts = Object.fromEntries(
costKeys.map(key => [
key,
line.costParts ? asMoney(line.costParts[key]) : ['accessories', 'other'].includes(key) ? '0' : '',
]),
);
const originalMode = ['gram', 'total'].includes(line.costMaterial?.mode ?? '')
? line.costMaterial!.mode
: initialParts.material === ''
? 'gram'
: 'total';
const [parts, setParts] = useState(initialParts);
const [modes, setModes] = useState({
material: line.unit === 'g' ? originalMode : 'total',
labor: line.unit === 'g' ? line.costLabor?.mode || 'total' : 'total',
});
const [rates, setRates] = useState({
material: asMoney(line.costMaterial?.rate),
labor: asMoney(line.costLabor?.rate),
});
const originalTotal = line.unit !== 'g' || originalMode === 'total' ? initialParts.material : '';
const changePart = (key: string, value: string) => setParts(old => ({ ...old, [key]: value }));
const updateMode = (key: CostModeKey, value: string, computed: string) => {
if (value === 'total' && (key === 'labor' || parts.material === '')) changePart(key, computed);
setModes(old => ({ ...old, [key]: value }));
};
const amount = (key: string, title: string, value: string, gram = false) => (
<label>
{title}
<input
type="number"
name={prefix + key}
min="0"
step="0.01"
placeholder="开单前必填,没有填0"
required={!gram}
readOnly={gram}
value={value}
onChange={event => changePart(key, event.target.value)}
/>
</label>
);
function group(key: CostModeKey) {
const material = key === 'material',
gram = modes[key] === 'gram';
const payer = line.costPayers?.[key] ?? line.payer ?? fallback;
let value = parts[key],
formula;
if (gram) {
try {
const result = costBreakdown(
line,
quantity,
{ material: '0', labor: '0', accessories: '0', other: '0' },
{ material: 'total', labor: 'total', [key]: 'gram' },
rates,
).parts[key];
value = asMoney(result);
formula =
result == null
? material
? '填写每克进货料价后,系统自动乘以本行克重。'
: '填写每克工费后自动乘以克重。'
: quantity + 'g × ' + rates[key] + '元/克 = ' + yuan(result) + '元';
} catch (err) {
value = '';
formula = err instanceof Error ? err.message : String(err);
}
} else {
formula = material
? line.unit === 'g'
? '直接填写本行料费合计,不再乘以克重。'
: '按件商品请填写本行料费合计' + (rates.material ? ';每克料价已保留,切回g可恢复' : '') + '。'
: '直接填写本行总工费。';
}
const options = members(false, { selected: payer });
return (
<div className={'purchase-' + key} data-prefix={prefix} data-mode={modes[key]}>
<div className="grid purchase-cost-grid">
<label>
{material ? '进货料费方式' : '进货工费方式'}
<select
name={prefix + key + 'Mode'}
value={modes[key]}
onChange={event => updateMode(key, event.target.value, value)}
>
<option value="gram" disabled={line.unit !== 'g'}>
{material ? '按克料价' : '克工费'}
</option>
<option value="total">{material ? '直接填总料费' : '总工费'}</option>
</select>
</label>
<label hidden={!gram}>
{material ? '进货料价(元/克)' : '进货克工费(元/克)'}
<input
type="number"
name={prefix + key + 'Rate'}
min="0"
step="0.01"
value={rates[key]}
placeholder={material ? '填写每克进货料价' : '填写每克工费'}
disabled={!gram}
required={gram}
onChange={event => setRates(old => ({ ...old, [key]: event.target.value }))}
/>
</label>
{amount(key, material ? '料费成本合计(元)' : '进货总工费(元)', value, gram)}
<label className="purchase-payer">
{material ? '料费付款人' : '进货工费付款人'}
<select
required
name={prefix + key + 'Payer'}
defaultValue={options.some(([id]) => id === payer) ? payer : ''}
>
{options.some(([id]) => id === payer) ? null : (
<option value="" disabled>
请选择
</option>
)}
{opts(options)}
</select>
</label>
</div>
<p className="purchase-formula small muted" aria-live="polite">
{formula}
</p>
{material && (
<p className="purchase-original small muted" hidden={!originalTotal}>
{originalTotal &&
'已保留原料费合计 ' + originalTotal + '元。原金额不会当成每克料价;切换按克后请填写实际进货料价。'}
</p>
)}
</div>
);
}
let summary;
try {
summary = costBreakdown(line, quantity, parts, modes, rates).total;
} catch {
summary = null;
}
return (
<div className="internal cost-editor">
<h3>
{line.name} · {line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件'}
</h3>
<div className="cost-fallback-payer">
{choice('配件及其他成本付款人', 'goodsPayer', members(), line.payer || 'owner')}
</div>
{!line.costParts && line.cost !== null && (
<p className="small">原记录未分项,总额 ¥{yuan(line.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>
)}
<div className="cost-fields grid">
{group('material')}
{group('labor')}
{amount('accessories', '配件成本(元,本行合计)', parts.accessories)}
{amount('other', '其他货品成本(元,本行合计)', parts.other)}
</div>
<div className="cost-summary small">
本行货品成本合计:{summary == null ? '请补齐(没有的项目填0)' : '¥' + yuan(summary)}
</div>
</div>
);
}
@@ -1,7 +1,23 @@
import type {
IndependentDetail,
IndependentRecord,
IndependentRequest,
IndependentValues,
OrderRecord,
OrderLine,
ReviewList,
} from '../orderData';
import type { OrderContext, SharedViews } from '../viewTypes';
import { Children } from 'react';
import { Calc as LedgerCalc, Values } from '../../../shared';
function object(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function revision(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
}
export function afterSales(
{ afterSaleChangesStatus, state, ui, orderAfterSaleFormEntry, currentOrder },
{ afterSaleChangesStatus, state, ui = {}, orderAfterSaleFormEntry, currentOrder }: OrderContext,
{
button,
validOrderDate,
@@ -28,39 +44,47 @@ export function afterSales(
activePocketKeys,
orderChangeUser,
stockCountValue,
},
}: SharedViews,
) {
function validateAfterSaleDetail(detail, id) {
const record = detail?.record,
permissions = detail?.permissions;
if (
!record ||
detail.id !== id ||
record.id !== id ||
!Number.isSafeInteger(detail.revision) ||
detail.revision < 1 ||
record.revision !== detail.revision ||
!afterSaleValuesValid(record) ||
!teamMemberKeys().includes(record.member) ||
typeof permissions?.canEdit !== 'boolean' ||
typeof permissions.canDirectEdit !== 'boolean' ||
typeof permissions.requiresApproval !== 'boolean' ||
!Array.isArray(detail.history)
)
throw new Error('售后记录资料未完整返回,请重新读取后再修改。');
if (detail.pending && (validateAfterSaleRequest(detail.pending).afterSaleId !== id || permissions.canEdit))
function readAfterSaleDetail(detail: unknown, id: string): detail is IndependentDetail {
if (!object(detail) || detail.id !== id || !revision(detail.revision) || !object(detail.record)) return false;
const record = detail.record,
permissions = detail.permissions;
return (
record.id === id &&
record.revision === detail.revision &&
typeof record.actor === 'string' &&
typeof record.created === 'string' &&
typeof record.member === 'string' &&
teamMemberKeys().includes(record.member) &&
afterSaleValuesValid(record) &&
object(permissions) &&
typeof permissions.canEdit === 'boolean' &&
typeof permissions.canDirectEdit === 'boolean' &&
typeof permissions.requiresApproval === 'boolean' &&
typeof permissions.reason === 'string' &&
object(detail.values) &&
typeof detail.values.amount === 'string' &&
Array.isArray(detail.history) &&
detail.history.every(request => validateAfterSaleRequest(request)) &&
(detail.pending === null || !!validateAfterSaleRequest(detail.pending))
);
}
function validateAfterSaleDetail(detail: unknown, id: string) {
if (!readAfterSaleDetail(detail, id)) throw new Error('售后记录资料未完整返回,请重新读取后再修改。');
if (detail.pending && (detail.pending.afterSaleId !== id || detail.permissions.canEdit))
throw new Error('售后修改状态不一致,请重新读取。');
for (const request of detail.history)
if (validateAfterSaleRequest(request).afterSaleId !== id) throw new Error('售后修改历史不一致,请重新读取。');
if (request.afterSaleId !== id) throw new Error('售后修改历史不一致,请重新读取。');
return detail;
}
function independentReviewForm(kind, request) {
function independentReviewForm(kind: string, request: IndependentRequest) {
return (
<form id="after-sale-review-form" data-id={request.id} data-kind={kind}>
<h3>{kind === 'approve' ? '同意售后修改' : '驳回售后修改'}</h3>
<label>
{kind === 'approve' ? '复核备注(选填)' : '驳回意见'}
<textarea disabled={ui.blocked} name="note" rows="2" maxLength="200" required={kind === 'reject'}></textarea>
<textarea disabled={ui.blocked} name="note" rows={2} maxLength={200} required={kind === 'reject'}></textarea>
</label>
{kind === 'approve' ? (
<label className="check">
@@ -79,7 +103,7 @@ export function afterSales(
</form>
);
}
function independentReview(request, kind) {
function independentReview(request: IndependentRequest, kind?: string | null) {
const canReview = state.user.role === 'owner' && request.status === 'pending';
return (
<>
@@ -144,7 +168,7 @@ export function afterSales(
</>
);
}
function afterSaleHistoryHTML(request) {
function afterSaleHistoryHTML(request: IndependentRequest) {
return (
<li>
<strong>{afterSaleStatus(request)}</strong>
@@ -175,7 +199,7 @@ export function afterSales(
</li>
);
}
function afterSaleRecordHTML(record) {
function afterSaleRecordHTML(record: IndependentRecord) {
return (
<dl className="after-sale-facts">
{Children.toArray(
@@ -196,9 +220,13 @@ export function afterSales(
</dl>
);
}
function afterSaleComparisonHTML(raw) {
function afterSaleComparisonHTML(raw: IndependentRequest) {
const request = validateAfterSaleRequest(raw),
pair = (title, key, format = value => value) => {
pair = <K extends keyof IndependentValues>(
title: string,
key: K,
format: (value: IndependentValues[K]) => string | number = value => value,
) => {
const changed = request.before[key] !== request.after[key];
return (
<tr
@@ -231,14 +259,14 @@ export function afterSales(
{pair('售后日期', 'date')}
{pair('售后项目', 'project')}
{pair('客户', 'customer')}
{pair('金额', 'amount', value => '¥' + yuan(value))}
{pair('金额', 'amount', value => '¥' + yuan(Number(value)))}
{pair('谁支付', 'payer', teamMemberName)}
</tbody>
</table>
</div>
);
}
function editIndependentSale(detail) {
function editIndependentSale(detail: IndependentDetail) {
const record = detail.record,
request = detail.pending;
const pendingHTML = request ? (
@@ -274,11 +302,11 @@ export function afterSales(
})}
{field('售后项目', 'project', record.project, 'text', {
required: true,
maxLength: '100',
maxLength: 100,
})}
{field('客户', 'customer', record.customer, 'text', {
required: true,
maxLength: '60',
maxLength: 60,
})}
{moneyField('金额(元)', 'amount', (record.amount / 100).toFixed(2))}
{orderMemberField(record.member, true)}
@@ -293,7 +321,7 @@ export function afterSales(
</div>
<label>
修改说明(选填)
<textarea name="reason" rows="2" maxLength="200" placeholder="例如:售后金额或付款人录错。"></textarea>
<textarea name="reason" rows={2} maxLength={200} placeholder="例如:售后金额或付款人录错。"></textarea>
</label>
</fieldset>
<div id="after-sale-edit-error" aria-live="polite">
@@ -357,12 +385,12 @@ export function afterSales(
})}
{field('售后项目', 'project', '', 'text', {
required: true,
maxLength: '100',
maxLength: 100,
placeholder: '例如:维修、补寄快递',
})}
{field('客户', 'customer', '', 'text', {
required: true,
maxLength: '60',
maxLength: 60,
placeholder: '客户称呼或代号',
})}
{moneyField('金额(元)', 'amount', '')}
@@ -373,7 +401,7 @@ export function afterSales(
<option value="" disabled>
请选择
</option>
{opts(teamMemberOptions(), '')}
{opts(teamMemberOptions())}
</select>
</label>
</div>
@@ -393,16 +421,21 @@ export function afterSales(
</>
);
}
function orderAfterSaleAccountPayer(account) {
function orderAfterSaleAccountPayer(account: string) {
return accountIdentity(account)?.member || currentMember();
}
const materialPoolMg = Values.positiveMg;
function orderAfterSaleInput(form) {
function orderAfterSaleInput(form: HTMLFormElement) {
const order = currentOrder,
entry = orderAfterSaleFormEntry,
get = name => String(form.querySelector(`[name="${name}"]`)?.value ?? '').trim();
get = (name: string) =>
String(
form.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
'',
).trim();
if (
!entry ||
!order ||
entry.id !== order?.id ||
entry.user !== orderChangeUser() ||
entry.revision !== order.revision ||
@@ -417,7 +450,11 @@ export function afterSales(
const rows = [...form.querySelectorAll('[data-after-sale-line]')];
if (rows.length !== order.lines.length) throw new Error('请核对全部退回商品后再提交。');
const lines = rows.map((row, lineIndex) => {
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
const read = (name: string) =>
String(
row.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
'',
).trim(),
original = order.lines[lineIndex],
quantity = read('return_quantity'),
mg = materialPoolMg(quantity),
@@ -436,7 +473,12 @@ export function afterSales(
title: '商品 ' + (lineIndex + 1) + '实际退回数量(对)',
})
: null;
if (Number.isSafeInteger(original.stockCount) && stockCount > original.stockCount)
if (
original.stockCount != null &&
stockCount != null &&
Number.isSafeInteger(original.stockCount) &&
stockCount > original.stockCount
)
throw new Error('商品 ' + (lineIndex + 1) + '实际退回对数不能超过原出库对数。');
return {
lineIndex,
@@ -459,7 +501,11 @@ export function afterSales(
const reference = get('refund_reference');
if (reference.length > 100) throw new Error('退款凭据备注最多100字。');
const expenses = [...form.querySelectorAll('.order-after-sale-expense')].map(row => {
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
const read = (name: string) =>
String(
row.querySelector<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(`[name="${name}"]`)?.value ??
'',
).trim(),
amount = read('expense_amount'),
note = read('expense_note'),
payer = read('expense_payer');
@@ -491,12 +537,12 @@ export function afterSales(
},
};
}
function orderAfterSaleExpenseHTML(value = {}) {
function orderAfterSaleExpenseHTML(value: Partial<{ amount: string; note: string; payer: string }> = {}) {
return (
<div className="order-after-sale-expense grid four">
{field('售后成本项目', 'expense_note', value.note || '', 'text', {
required: true,
maxLength: '150',
maxLength: 150,
placeholder: '如寄件费、重新编绳',
})}
{moneyField('实际成本(元)', 'expense_amount', value.amount ?? '')}
@@ -508,7 +554,7 @@ export function afterSales(
function orderAfterSalePocketKeys() {
return activePocketKeys().filter(key => state.pocketCatalog?.some(row => row.key === key && row.self === true));
}
function orderAfterSaleLineHTML(line, index) {
function orderAfterSaleLineHTML(line: OrderLine, index: number) {
const pockets = orderAfterSalePocketKeys();
const pocket = ui.lines?.[index]?.pocket ?? (pockets.includes(line.pocket) ? line.pocket : pockets[0] || '');
const disposition = ui.lines?.[index]?.disposition || 'stock';
@@ -550,7 +596,7 @@ export function afterSales(
pockets.map(key => [key, pocketLabel(key)]),
pocket,
)}
{stockCountField(pocket, line.stockCount, {
{stockCountField(pocket, String(line.stockCount ?? ''), {
name: 'return_count',
visible: disposition === 'stock' && pocketCountsEnabled(pocket),
title: '实际退回数量(对)',
@@ -576,7 +622,7 @@ export function afterSales(
? '本次提交原订单售后申请,店主同意后一次登记退货、退款、费用与利润调整。复核前原账保持原值。'
: '核实后一次登记退货、实际退款与售后成本。系统只记账,退款须已在实际账户完成。';
}
function orderAfterSaleFormHTML(order) {
function orderAfterSaleFormHTML(order: OrderRecord) {
const receipts = order.payments?.filter(row => row.kind === 'receipt') || [],
account =
receipts.find(
@@ -604,8 +650,8 @@ export function afterSales(
售后原因
<textarea
name="reason"
rows="2"
maxLength="200"
rows={2}
maxLength={200}
required
placeholder="填写客户实际退货退款原因。"
></textarea>
@@ -623,7 +669,7 @@ export function afterSales(
{choice('实际退款付款人', 'refund_payer', teamMemberOptions(), payer)}
</div>
{field('退款凭据备注(选填)', 'refund_reference', '', 'text', {
maxLength: '100',
maxLength: 100,
})}
<div className="order-after-sale-retained">
<span>本次扣留客户款(系统计算)</span>
@@ -635,8 +681,8 @@ export function afterSales(
<textarea
name="deduction_reason"
required={ui.reasonRequired}
rows="2"
maxLength="200"
rows={2}
maxLength={200}
placeholder="有扣留款时填写,如约定扣除不可退工费或实际损耗。"
></textarea>
</label>
@@ -687,7 +733,7 @@ export function afterSales(
</form>
);
}
function afterSaleStatus(request) {
function afterSaleStatus(request: IndependentRequest) {
return (
{
pending: '待店主审批',
@@ -696,47 +742,58 @@ export function afterSales(
}[request.status] || '状态待确认'
);
}
function afterSaleTime(value) {
function afterSaleTime(value: string | null) {
return String(value || '未提供')
.replace('T', ' ')
.replace(/\.\d{3}Z$/, ' UTC')
.replace(/Z$/, ' UTC');
}
function afterSaleValuesValid(record) {
function afterSaleValuesValid(record: unknown): record is IndependentValues & { amount: number } {
return (
record &&
object(record) &&
validOrderDate(record.date) &&
typeof record.project === 'string' &&
record.project.trim() &&
!!record.project.trim() &&
record.project.length <= 100 &&
typeof record.customer === 'string' &&
record.customer.trim() &&
!!record.customer.trim() &&
record.customer.length <= 60 &&
typeof record.amount === 'number' &&
Number.isSafeInteger(record.amount) &&
record.amount >= 0 &&
typeof record.payer === 'string' &&
teamMemberKeys().includes(record.payer)
);
}
function validateAfterSaleRequest(request) {
if (
!request ||
typeof request.id !== 'string' ||
!request.id ||
typeof request.afterSaleId !== 'string' ||
!request.afterSaleId ||
!Number.isSafeInteger(request.revision) ||
request.revision < 1 ||
!Number.isSafeInteger(request.recordRevision) ||
request.recordRevision < 1 ||
!['pending', 'approved', 'rejected'].includes(request.status) ||
!afterSaleValuesValid(request.before) ||
!afterSaleValuesValid(request.after) ||
typeof request.canApprove !== 'boolean'
)
throw new Error('售后修改申请资料未完整返回,请重新读取。');
function isRequest(request: unknown): request is IndependentRequest {
return (
object(request) &&
typeof request.id === 'string' &&
!!request.id &&
typeof request.afterSaleId === 'string' &&
!!request.afterSaleId &&
revision(request.revision) &&
revision(request.recordRevision) &&
(request.status === 'pending' || request.status === 'approved' || request.status === 'rejected') &&
afterSaleValuesValid(request.before) &&
afterSaleValuesValid(request.after) &&
typeof request.canApprove === 'boolean' &&
typeof request.stale === 'boolean' &&
typeof request.staleReason === 'string' &&
typeof request.member === 'string' &&
typeof request.created === 'string' &&
typeof request.requesterName === 'string' &&
(request.reviewed == null || typeof request.reviewed === 'string') &&
(request.reviewerName == null || typeof request.reviewerName === 'string') &&
(request.note == null || typeof request.note === 'string') &&
typeof request.reason === 'string'
);
}
function validateAfterSaleRequest(request: unknown) {
if (!isRequest(request)) throw new Error('售后修改申请资料未完整返回,请重新读取。');
return request;
}
function afterSaleChangeListHTML(data) {
function afterSaleChangeListHTML(data: ReviewList<IndependentRequest>) {
if (
!Array.isArray(data.requests) ||
!data.counts ||
@@ -1,187 +1,20 @@
import { Children, useState } from 'react';
import type { ReactNode } from 'react';
import { LegacyCostRow } from './LegacyCostRow';
interface ActionInput extends Record<string, unknown> {
date: string;
verified: boolean;
feesVerified: boolean;
account?: string;
revision?: number;
returnPockets?: string[];
returnCounts?: (number | null)[];
stockCounts?: Record<number, number | null>;
}
import type { OrderContext, SharedViews } from '../viewTypes';
import { Children } from 'react';
import { Cards as CreditCardFees, Calc as LedgerCalc } from '../../../shared';
const asMoney = value => (value == null ? '' : (value / 100).toFixed(2));
const costKeys = ['material', 'labor', 'accessories', 'other'];
function costBreakdown(line, quantity, parts, modes, rates) {
const input = { unit: line.unit, quantity, costParts: parts };
for (const [key, property] of [
['material', 'costMaterial'],
['labor', 'costLabor'],
]) {
input[property] = modes[key] === 'gram' ? { mode: 'gram', rate: rates[key] } : { mode: 'total' };
}
return LedgerCalc.purchaseCosts(input);
}
function LegacyCostRow({ line, index, members, fallback, choice, opts, grams, yuan }) {
const prefix = 'cost-' + index + '-';
const quantity = line.unit === 'g' ? (line.quantity / 1000).toFixed(3) : line.quantity;
const initialParts = Object.fromEntries(
costKeys.map(key => [
key,
line.costParts ? asMoney(line.costParts[key]) : ['accessories', 'other'].includes(key) ? '0' : '',
]),
);
const originalMode = ['gram', 'total'].includes(line.costMaterial?.mode)
? line.costMaterial.mode
: initialParts.material === ''
? 'gram'
: 'total';
const [parts, setParts] = useState(initialParts);
const [modes, setModes] = useState({
material: line.unit === 'g' ? originalMode : 'total',
labor: line.unit === 'g' ? line.costLabor?.mode || 'total' : 'total',
});
const [rates, setRates] = useState({
material: asMoney(line.costMaterial?.rate),
labor: asMoney(line.costLabor?.rate),
});
const originalTotal = line.unit !== 'g' || originalMode === 'total' ? initialParts.material : '';
const changePart = (key, value) => setParts(old => ({ ...old, [key]: value }));
const updateMode = (key, value, computed) => {
if (value === 'total' && (key === 'labor' || parts.material === '')) changePart(key, computed);
setModes(old => ({ ...old, [key]: value }));
};
const amount = (key, title, value, gram = false) => (
<label>
{title}
<input
type="number"
name={prefix + key}
min="0"
step="0.01"
placeholder="开单前必填,没有填0"
required={!gram}
readOnly={gram}
value={value}
onChange={event => changePart(key, event.target.value)}
/>
</label>
);
function group(key) {
const material = key === 'material',
gram = modes[key] === 'gram';
const payer = line.costPayers?.[key] ?? line.payer ?? fallback;
let value = parts[key],
formula;
if (gram) {
try {
const result = costBreakdown(
line,
quantity,
{ material: '0', labor: '0', accessories: '0', other: '0' },
{ material: 'total', labor: 'total', [key]: 'gram' },
rates,
).parts[key];
value = asMoney(result);
formula =
result == null
? material
? '填写每克进货料价后,系统自动乘以本行克重。'
: '填写每克工费后自动乘以克重。'
: quantity + 'g × ' + rates[key] + '元/克 = ' + yuan(result) + '元';
} catch (err) {
value = '';
formula = err.message;
}
} else {
formula = material
? line.unit === 'g'
? '直接填写本行料费合计,不再乘以克重。'
: '按件商品请填写本行料费合计' + (rates.material ? ';每克料价已保留,切回g可恢复' : '') + '。'
: '直接填写本行总工费。';
}
const options = members(false, { selected: payer });
return (
<div className={'purchase-' + key} data-prefix={prefix} data-mode={modes[key]}>
<div className="grid purchase-cost-grid">
<label>
{material ? '进货料费方式' : '进货工费方式'}
<select
name={prefix + key + 'Mode'}
value={modes[key]}
onChange={event => updateMode(key, event.target.value, value)}
>
<option value="gram" disabled={line.unit !== 'g'}>
{material ? '按克料价' : '克工费'}
</option>
<option value="total">{material ? '直接填总料费' : '总工费'}</option>
</select>
</label>
<label hidden={!gram}>
{material ? '进货料价(元/克)' : '进货克工费(元/克)'}
<input
type="number"
name={prefix + key + 'Rate'}
min="0"
step="0.01"
value={rates[key]}
placeholder={material ? '填写每克进货料价' : '填写每克工费'}
disabled={!gram}
required={gram}
onChange={event => setRates(old => ({ ...old, [key]: event.target.value }))}
/>
</label>
{amount(key, material ? '料费成本合计(元)' : '进货总工费(元)', value, gram)}
<label className="purchase-payer">
{material ? '料费付款人' : '进货工费付款人'}
<select
required
name={prefix + key + 'Payer'}
defaultValue={options.some(([id]) => id === payer) ? payer : ''}
>
{options.some(([id]) => id === payer) ? null : (
<option value="" disabled>
请选择
</option>
)}
{opts(options)}
</select>
</label>
</div>
<p className="purchase-formula small muted" aria-live="polite">
{formula}
</p>
{material && (
<p className="purchase-original small muted" hidden={!originalTotal}>
{originalTotal &&
'已保留原料费合计 ' + originalTotal + '元。原金额不会当成每克料价;切换按克后请填写实际进货料价。'}
</p>
)}
</div>
);
}
let summary;
try {
summary = costBreakdown(line, quantity, parts, modes, rates).total;
} catch {
summary = null;
}
return (
<div className="internal cost-editor">
<h3>
{line.name} · {line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件'}
</h3>
<div className="cost-fallback-payer">
{choice('配件及其他成本付款人', 'goodsPayer', members(), line.payer || 'owner')}
</div>
{!line.costParts && line.cost !== null && (
<p className="small">原记录未分项,总额 ¥{yuan(line.cost)};请按凭据拆分,不要把总额再填入每个项目。</p>
)}
<div className="cost-fields grid">
{group('material')}
{group('labor')}
{amount('accessories', '配件成本(元,本行合计)', parts.accessories)}
{amount('other', '其他货品成本(元,本行合计)', parts.other)}
</div>
<div className="cost-summary small">
本行货品成本合计:{summary == null ? '请补齐(没有的项目填0)' : '¥' + yuan(summary)}
</div>
</div>
);
}
export function orderActions(
{ currentOrder, ui, state },
{ currentOrder, ui = {}, state }: OrderContext,
{
orderActionUsesChangeForm,
orderActionRequiresApproval,
@@ -213,12 +46,12 @@ export function orderActions(
activePocketKeys,
pocketLabel,
stockCountValue,
},
}: SharedViews,
) {
function readReturnCounts(form, pockets) {
function readReturnCounts(form: HTMLFormElement, pockets: string[]) {
return pockets.map((pocket, index) => {
if (!pocketCountsEnabled(pocket)) return null;
const count = stockCountValue(form.querySelector('[name="returnCount-' + index + '"]')?.value, {
const count = stockCountValue(form.querySelector<HTMLInputElement>('[name="returnCount-' + index + '"]')?.value, {
title: '商品 ' + (index + 1) + '实际退回数量(对)',
}),
original = currentOrder?.lines?.[index]?.stockCount;
@@ -227,28 +60,28 @@ export function orderActions(
return count;
});
}
function readPaymentAccount(form) {
function readPaymentAccount(form: HTMLFormElement) {
return normalizePaymentAccount(
(form?.querySelector?.('[name="payment_recipient"]')?.value || '') +
(form?.querySelector?.('[name="payment_method"]')?.value || ''),
(form?.querySelector?.<HTMLInputElement>('[name="payment_recipient"]')?.value || '') +
(form?.querySelector?.<HTMLInputElement>('[name="payment_method"]')?.value || ''),
);
}
function actionInput(form) {
const data = Object.fromEntries(new FormData(form));
const kind = form.dataset.kind;
const input = {
function actionInput(form: HTMLFormElement) {
const data = Object.fromEntries(new FormData(form)) as Record<string, string>;
const kind = form.dataset.kind!;
const input: ActionInput = {
...data,
date: data.date || state.today,
verified: data.verified === 'on',
feesVerified: data.feesVerified === 'on',
};
if (kind === 'fees') {
input.revision = currentOrder.revision;
input.fee_items = [...form.querySelectorAll('.fee-verify-row')].map(row => ({
...currentOrder.pendingFees.find(f => f.key === row.dataset.key),
input.revision = currentOrder!.revision;
input.fee_items = [...form.querySelectorAll<HTMLElement>('.fee-verify-row')].map(row => ({
...currentOrder!.pendingFees.find(f => f.key === row.dataset.key),
status: 'estimated',
amount: row.querySelector('[name="verifiedAmount"]').value,
payer: row.querySelector('[name="verifiedPayer"]').value,
amount: row.querySelector<HTMLInputElement>('[name="verifiedAmount"]')!.value,
payer: row.querySelector<HTMLInputElement>('[name="verifiedPayer"]')!.value,
}));
}
if (kind === 'correct') {
@@ -257,47 +90,48 @@ export function orderActions(
input.target = target;
}
if (kind === 'cost')
input.costs = Array.from(form.querySelectorAll('.cost-editor'), (row, index) => {
const get = key => row.querySelector('[name="cost-' + index + '-' + key + '"]').value;
const mode = key =>
input.costs = Array.from(form.querySelectorAll<HTMLElement>('.cost-editor'), (row, index) => {
const get = (key: string) =>
row.querySelector<HTMLInputElement>('[name="cost-' + index + '-' + key + '"]')!.value;
const mode = (key: string) =>
get(key + 'Mode') === 'gram' ? { mode: 'gram', rate: get(key + 'Rate') } : { mode: 'total' };
return {
parts: Object.fromEntries(costKeys.map(key => [key, get(key)])),
parts: Object.fromEntries(Object.keys(LedgerCalc.costLabels).map(key => [key, get(key)])),
costMaterial: mode('material'),
costLabor: mode('labor'),
costPayers: { material: get('materialPayer'), labor: get('laborPayer') },
payer: row.querySelector('[name="goodsPayer"]').value,
payer: row.querySelector<HTMLInputElement>('[name="goodsPayer"]')!.value,
};
});
if (kind === 'receipt' || kind === 'refund') input.account = readPaymentAccount(form);
if (kind === 'correct' && input.account) input.account = normalizePaymentAccount(input.account);
if (kind === 'return') {
input.returnPockets = currentOrder.lines.map(
(_, i) => form.querySelector('[name="return-' + i + '"]')?.value ?? data['return-' + i],
input.returnPockets = currentOrder!.lines.map(
(_, i) => form.querySelector<HTMLInputElement>('[name="return-' + i + '"]')?.value ?? data['return-' + i],
);
input.returnCounts = readReturnCounts(form, input.returnPockets);
}
if (kind === 'complete') {
input.stockCounts = {};
currentOrder.lines.forEach((line, index) => {
currentOrder!.lines.forEach((line, index) => {
if (line.unit === 'g' && pocketCountsEnabled(line.pocket) && line.stockCount == null)
input.stockCounts[index] = stockCountValue(
form.querySelector('[name="completeCount-' + index + '"]')?.value,
input.stockCounts![index] = stockCountValue(
form.querySelector<HTMLInputElement>('[name="completeCount-' + index + '"]')?.value,
{
title: '商品 ' + (index + 1) + '实际出库数量(对)',
},
);
});
}
if (['review', 'complete'].includes(kind)) input.revision = currentOrder.revision;
if (['review', 'complete'].includes(kind)) input.revision = currentOrder!.revision;
return input;
}
function orderActionModeText(kind, approval) {
function orderActionModeText(kind: string, approval: boolean) {
return approval
? `本次提交${orderChangeActionLabels[kind]}申请。店主同意后才记账;待批期间原订单、收退款、费用、库存和利润均不变。系统不会发起真实付款。`
: '原单与本次业务日期均为今天,核实后直接记账,无需店主审批。改为其他业务日期须提交申请。系统不会发起真实付款。';
}
function orderActionChangeReviewHTML(kind) {
function orderActionChangeReviewHTML(kind: string) {
const approval = orderActionRequiresApproval(kind, ui.date);
return (
<>
@@ -311,8 +145,8 @@ export function orderActions(
<span id="order-action-reason-label">{approval ? '申请原因' : '登记原因'}</span>
<textarea
name="change_reason"
maxLength="200"
rows="2"
maxLength={200}
rows={2}
required
placeholder="写清本次需要登记或更正的原因。"
></textarea>
@@ -329,19 +163,19 @@ export function orderActions(
</>
);
}
function creditCardPreviewHTML(id, payer = 'owner', basis = '客户付款金额') {
function creditCardPreviewHTML(id: string, payer = 'owner', basis = '客户付款金额') {
const values = ui.values || {};
const original = currentOrder.payment_account;
const original = currentOrder!.payment_account;
const method = ui.paymentMethod ?? accountIdentity(original)?.channel;
const corrected = currentOrder.payments.find(p => p.id === (values.entry || '').split(':')[1]);
const corrected = currentOrder!.payments.find(p => p.id === (values.entry || '').split(':')[1]);
const correction = ui.action === 'correct';
const visible = correction
? corrected?.kind === 'receipt' && isCreditCardAccount(values.account)
: method === '信用卡' && ui.action === 'receipt';
const rate = currentOrder.credit_card_rate_permille ?? state.shopSettings?.creditCardRatePermille;
const rate = currentOrder!.credit_card_rate_permille ?? state.shopSettings?.creditCardRatePermille;
let amount, formula;
if (visible || ui.lastCardBasis !== undefined) {
const basisAmount = visible ? (values.amount ?? (currentOrder.balance / 100).toFixed(2)) : ui.lastCardBasis;
const basisAmount = visible ? (values.amount ?? (currentOrder!.balance / 100).toFixed(2)) : ui.lastCardBasis;
let cents, fee;
try {
cents = LedgerCalc.cents(basisAmount);
@@ -406,12 +240,12 @@ export function orderActions(
</div>
);
}
function isAutomaticCardFee(item) {
function isAutomaticCardFee(item: { system?: string; key?: string; id?: string }) {
return item?.system === 'credit_card' || String(item?.key || '').startsWith('card_fee:');
}
function pocketOptions(selected = '', historical = false) {
const keys = activePocketKeys(),
options = keys.map(key => [key, pocketLabel(key)]);
options = keys.map((key): [string, string, boolean?] => [key, pocketLabel(key)]);
if (selected && !keys.includes(selected))
options.push([
selected,
@@ -420,10 +254,10 @@ export function orderActions(
]);
return options;
}
function isCreditCardAccount(account) {
function isCreditCardAccount(account: string | undefined) {
return typeof CreditCardFees === 'object' && typeof CreditCardFees.isAccount === 'function'
? CreditCardFees.isAccount(account)
: ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account);
? CreditCardFees.isAccount(account ?? '')
: ['助理信用卡', '助理1信用卡', '麦麦信用卡', '助理2信用卡'].includes(account ?? '');
}
const orderFormMember = () => currentOrder?.member || currentMember();
function defaultPaymentRecipient() {
@@ -433,13 +267,16 @@ export function orderActions(
function creditCardAvailable() {
return typeof CreditCardFees === 'object' && state?.accounts?.includes('麦麦信用卡');
}
function accountFields(account) {
function accountFields(account: string) {
const methods = ['微信', '支付宝', '现金', ...(creditCardAvailable() ? ['信用卡'] : [])];
account = normalizePaymentAccount(account || defaultPaymentRecipient() + '微信');
const card = ui.paymentMethod ? ui.paymentMethod === '信用卡' : isCreditCardAccount(account),
identity = accountIdentity(account),
prefix = identity ? memberAccountPrefix(identity.member) : defaultPaymentRecipient();
const recipients = teamMemberOptions(!teamMode()).map(([member, name]) => [memberAccountPrefix(member), name]);
const recipients = teamMemberOptions(!teamMode()).map(([member, name]): [string, string] => [
memberAccountPrefix(member),
name,
]);
if (identity && !teamMemberEnabled(identity.member))
recipients.push([prefix, teamMemberName(identity.member) + '(已停用 · 原记录)']);
return (
@@ -455,7 +292,7 @@ export function orderActions(
data-card-locked={card}
disabled={card}
>
{opts(recipients, card ? '麦麦' : prefix)}
{opts(recipients)}
</select>
{creditCardAvailable() ? (
<small className="small muted payment-account-note" hidden={!card}>
@@ -468,14 +305,14 @@ export function orderActions(
</>
);
}
const dateField = (name = 'date', value) =>
const dateField = (name = 'date', value?: string) =>
field('业务日期', name, value || state.today, 'date', {
max: state.today,
required: true,
});
function showAction(action) {
const o = currentOrder;
let html = '';
function showAction(action: string) {
const o = currentOrder!;
let html: ReactNode = '';
const dt = dateField(),
changeForm = orderActionUsesChangeForm(action),
requiresApproval = orderActionRequiresApproval(action, ui.date);
@@ -537,7 +374,7 @@ export function orderActions(
)}
</div>
{field('凭据备注(选填)', 'reference', '', 'text', {
maxLength: '100',
maxLength: 100,
placeholder: '交易凭据末几位或说明',
})}
<label className="check">
@@ -564,7 +401,7 @@ export function orderActions(
</div>
{field('费用项目与说明', 'note', '', 'text', {
required: true,
maxLength: '150',
maxLength: 150,
})}
</>
);
@@ -619,7 +456,7 @@ export function orderActions(
{dt}
{field('退货原因', 'reason', '', 'text', {
required: true,
maxLength: '200',
maxLength: 200,
})}
<div className="grid two">
{Children.toArray(
@@ -630,15 +467,17 @@ export function orderActions(
'return-' + i,
l.unit === 'g'
? [
...(l.pocket || l.costMaterial?.mode === 'pool' ? [] : [['', '已退供应商,不留店内']]),
...(l.pocket || l.costMaterial?.mode === 'pool'
? []
: [['', '已退供应商,不留店内'] as const]),
...pocketOptions(l.pocket, true),
]
: [['', '按件商品,不记黄金货盘']],
l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets[0] : ''),
l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets![0] : ''),
)}
{stockCountField(
ui.values?.['return-' + i] ??
(l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets[0] : '')),
(l.pocket || (l.costMaterial?.mode === 'pool' ? state.pockets![0] : '')),
l.stockCount,
{
readOnly: Number.isSafeInteger(l.stockCount),
@@ -675,7 +514,7 @@ export function orderActions(
['toOwner', teamMemberName('assistant') + ' → ' + teamMemberName('owner')],
['toAssistant', teamMemberName('owner') + ' → ' + teamMemberName('assistant')],
],
o.settlementDue < 0 ? 'toAssistant' : 'toOwner',
o.settlementDue! < 0 ? 'toAssistant' : 'toOwner',
)}
{choice(
'本笔归属',
@@ -691,7 +530,7 @@ export function orderActions(
{moneyField('实际转账金额', 'amount')}
{field('转账凭据/说明', 'note', '', 'text', {
required: true,
maxLength: '150',
maxLength: 150,
})}
</div>
<p className="small muted">
@@ -706,29 +545,31 @@ export function orderActions(
</>
);
if (action === 'correct') {
const valid = r =>
const valid = (r: { id: string; price_lock_event_id?: string; note?: string; reference?: string }) =>
!r.price_lock_event_id &&
!o.corrections.some(c => c.target === r.id) &&
!String(r.note || r.reference || '').startsWith('更正冲回:');
const cardExpenseIds = new Set((o.fee_items || []).filter(isAutomaticCardFee).map(item => item.expense_id));
const entries = [
...(o.cancellationApproved || orderAfterSaleRecord(o) ? [] : o.payments.filter(valid)).map(r => [
'payment:' + r.id,
r.date +
' ' +
(r.kind === 'receipt' ? '客户收款' : '客户退款') +
' ' +
yuan(r.amount) +
'元 ' +
accountDisplayName(r.account),
]),
...(o.cancellationApproved || orderAfterSaleRecord(o) ? [] : o.payments.filter(valid)).map(
(r): [string, string] => [
'payment:' + r.id,
r.date +
' ' +
(r.kind === 'receipt' ? '客户收款' : '客户退款') +
' ' +
yuan(r.amount) +
'元 ' +
accountDisplayName(r.account),
],
),
...(o.cancellationApproved || orderAfterSaleRecord(o)
? []
: o.expenses.filter(r => valid(r) && !isAutomaticCardFee(r) && !cardExpenseIds.has(r.id))
).map(r => ['expense:' + r.id, r.date + ' 直接费用 ' + yuan(r.amount) + '元 ' + r.note]),
).map((r): [string, string] => ['expense:' + r.id, r.date + ' 直接费用 ' + yuan(r.amount) + '元 ' + r.note]),
...o.settlements
.filter(valid)
.map(r => [
.map((r): [string, string] => [
'settlement:' + r.id,
r.date +
' ' +
@@ -778,7 +619,7 @@ export function orderActions(
</div>
{field('更正原因', 'reason', '', 'text', {
required: true,
maxLength: '200',
maxLength: 200,
})}
<label className="check">
<input type="checkbox" name="verified" required />
@@ -1,7 +1,10 @@
import type { ReactNode } from 'react';
import type { BookData, BookRow, BookSummary, LockActivity, MoneyKey } from '../orderData';
import type { OrderContext, SharedViews } from '../viewTypes';
import { Children, Fragment } from 'react';
import { Values } from '../../../shared';
export function orderBook(
{ orderBookFilters, state },
{ orderBookFilters, state }: OrderContext,
{
yuan,
teamMode,
@@ -19,16 +22,16 @@ export function orderBook(
activePocketKeys,
pocketLabel,
accountDisplayName,
},
}: SharedViews,
) {
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
function priceLockActivityRows(activity) {
const priceLockPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
function priceLockActivityRows(activity: LockActivity) {
if (!activity) return [];
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
.map(item => ({
...item,
activityType: item.kind === 'receipt' ? '客户收款' : '客户退款',
who: accountDisplayName(item.account),
who: accountDisplayName(item.account!),
activityName: item.product || '客户收退款',
}))
.concat(
@@ -36,24 +39,24 @@ export function orderBook(
...item,
activityType: item.source === 'extra' ? '补重料费付款' : '原锁料费付款',
who: priceLockPayerName(item.payer),
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity) + 'g × ' + yuan(item.rate) + '元/克',
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity!) + 'g × ' + yuan(item.rate) + '元/克',
})),
(activity.deliveryGoodsOutlays || []).map(item => ({
...item,
activityType: '交付货品支出',
who: priceLockPayerName(item.payer),
activityName: item.name,
activityName: item.name!,
})),
(activity.directOutlays || []).map(item => ({
...item,
activityType: '实际费用',
who: priceLockPayerName(item.payer),
activityName: item.note,
activityName: item.note!,
})),
)
.sort((a, b) => a.date.localeCompare(b.date));
}
function priceLockActivityHTML(activity) {
function priceLockActivityHTML(activity: LockActivity) {
if (!activity?.summary?.eventCount) return '';
const s = activity.summary,
rows = priceLockActivityRows(activity);
@@ -136,7 +139,7 @@ export function orderBook(
return '销售与利润按开单/交付日期,售后与回收按记录日期筛选。普通订单收款显示当前累计;锁价收退款按实际发生日期计入,待交付不计销售和利润。已取消订单不计本页销售汇总;直接回收付款计入每日购料,不计销售和利润。';
}
const previousOrderDate = Values.previousDate;
const getOrderBookFilters = () => orderBookFilters;
const getOrderBookFilters = () => orderBookFilters!;
function orderBookRange() {
const f = getOrderBookFilters(),
today = state.today;
@@ -193,7 +196,7 @@ export function orderBook(
...historical.map(pocket => [pocket, pocketLabel(pocket) + '(已停用 · 历史)']),
];
}
function orderBookMobileCards(rows, version, showCopy) {
function orderBookMobileCards(rows: BookRow[], version: number, showCopy: boolean) {
return (
<div className="order-mobile-list">
{Children.toArray(
@@ -218,7 +221,7 @@ export function orderBook(
</div>
</div>
{row.status === 'cancelled' ? <p className="small muted">已取消,未计入汇总</p> : ''}
{row.balance < 0 ? <p className="small danger-text">退款待处理</p> : ''}
{(row.balance ?? 0) < 0 ? <p className="small danger-text">退款待处理</p> : ''}
<details className="order-mobile-breakdown">
<summary>成本、利润与备注</summary>
<dl>
@@ -263,8 +266,8 @@ export function orderBook(
) : (
''
)}
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) ? orderEntryTimeHTML(row) : ''}
{showCopy && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind)
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') ? orderEntryTimeHTML(row) : ''}
{showCopy && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
? button('复制新增', 'copy-order', 'order-copy-button', {
'data-id': row.id,
})
@@ -276,7 +279,7 @@ export function orderBook(
</div>
);
}
function orderBookSummaryQuantity(summary) {
function orderBookSummaryQuantity(summary: BookSummary) {
return (
<>
{grams(summary.mg) + 'g' + (summary.pieces ? ' / ' + summary.pieces + '件' : '')}
@@ -284,10 +287,10 @@ export function orderBook(
</>
);
}
function afterSalePayerName(row) {
function afterSalePayerName(row: BookRow) {
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
}
function orderBookFeeParts(row) {
function orderBookFeeParts(row: BookRow) {
if (row.kind === 'recovery') return '';
if (row.status === 'draft') return '';
if (row.kind === 'afterSale')
@@ -302,7 +305,7 @@ export function orderBook(
<span>原单售后成本调整</span>
</div>
);
const grouped = new Map();
const grouped = new Map<string, { name: string; amount: number; missing: boolean }>();
for (const item of row.laborAndFeeItems || []) {
const key = item.component + ':' + item.name,
previous = grouped.get(key);
@@ -332,7 +335,7 @@ export function orderBook(
''
);
}
function orderBookMoney(row, key) {
function orderBookMoney(row: BookRow, key: MoneyKey) {
if (row.kind === 'recovery') return <span className="muted">—</span>;
if (row.status === 'draft')
return (
@@ -362,22 +365,22 @@ export function orderBook(
</>
);
}
function orderBookQuantity(value) {
function orderBookQuantity(value: Pick<BookRow, 'mg' | 'pieces'>) {
return (
[value.mg ? grams(value.mg) + 'g' : '', value.pieces ? value.pieces + '件' : ''].filter(Boolean).join(' / ') ||
'—'
);
}
function orderReviewBadge(row) {
function orderReviewBadge(row: BookRow) {
return orderIsReviewed(row) ? <span className="order-review-status">已复核</span> : '';
}
function afterSaleEditButton(row) {
function afterSaleEditButton(row: BookRow) {
return button('修改', 'after-sale-edit', 'after-sale-edit-button', {
'data-id': row.after_sale_id || row.id,
'aria-label': '修改 ' + row.customer + ' 的售后记录',
});
}
function orderBookIdentity(row, version) {
function orderBookIdentity(row: BookRow, version: number | undefined = undefined) {
if (row.kind === 'orderAfterSale')
return (
<button
@@ -462,14 +465,14 @@ export function orderBook(
</button>
);
}
const card = (title, value, hint = '', emphasis = false) => (
const card = (title: string, value: ReactNode, hint: ReactNode = '', emphasis = false) => (
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
<small>{title}</small>
<strong>{value}</strong>
<div className="hint">{hint}</div>
</div>
);
function orderBookSummaryAmount(summary, key) {
function orderBookSummaryAmount(summary: BookSummary, key: MoneyKey) {
const missing = summary.unknownCounts?.[key] || 0,
known = summary.knownCounts?.[key];
if (missing && known === 0 && !summary[key] && !summary.afterSaleCount)
@@ -480,7 +483,7 @@ export function orderBook(
);
return (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
}
function validateOrderBook(book) {
function validateOrderBook(book: BookData) {
const s = book?.summaryWithoutCancelled,
r = book?.receiptsWithoutCancelled;
const amounts = [
@@ -492,7 +495,7 @@ export function orderBook(
'profit',
'ownerCost',
'assistantCost',
];
] as const;
const counts = [
'orderCount',
'completedCount',
@@ -505,7 +508,7 @@ export function orderBook(
'unknownCosts',
'unknownCostCount',
'unknownProfitCount',
];
] as const;
if (
!Array.isArray(book?.rows) ||
(book.displayRows !== undefined && !Array.isArray(book.displayRows)) ||
@@ -525,20 +528,20 @@ export function orderBook(
s.unknownCounts[key] >= 0,
) ||
!counts.every(key => Number.isSafeInteger(s[key]) && s[key] >= 0) ||
!['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(r[key])) ||
!(['receipt', 'refund', 'net'] as const).every(key => Number.isSafeInteger(r[key])) ||
!Array.isArray(r.channels) ||
!r.channels.every(
channel =>
channel &&
typeof channel.name === 'string' &&
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(channel[key])),
(['receipt', 'refund', 'net'] as const).every(key => Number.isSafeInteger(channel[key])),
) ||
!['wechat', 'alipay', 'cash'].every(channel => r.channels.some(item => item.channel === channel))
!(['wechat', 'alipay', 'cash'] as const).every(channel => r.channels.some(item => item.channel === channel))
)
throw new Error('订单汇总数据尚未完整返回,请刷新后重新读取。');
return book;
}
function renderOrderBook(book, range) {
function renderOrderBook(book: BookData, range: { from: string; date: string; name: string }) {
validateOrderBook(book);
const s = book.summaryWithoutCancelled,
receipts = book.receiptsWithoutCancelled,
@@ -598,7 +601,7 @@ export function orderBook(
(teamMode() ? teamMemberKeys() : ['owner', 'assistant']).map(member => (
<span>
<b>{teamMemberName(member)}</b>
<span>{orderBookSummaryAmount(s, member + 'Cost')}</span>
<span>{orderBookSummaryAmount(s, `${member}Cost`)}</span>
</span>
)),
)}
@@ -640,7 +643,7 @@ export function orderBook(
{card(range.name + '成本' + (costPartial ? '(已知部分)' : ''), costValue, costDetails)}
</>
);
const count = `${range.name} · 汇总 ${s.orderCount} 单${recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : ''}${s.afterSaleCount ? ' · 售后 ' + s.afterSaleCount + ' 笔' : ''}${cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : ''}${orderBookFilters.q || orderBookFilters.status || orderBookFilters.pocket || orderBookFilters.member ? '(已筛选)' : ''}`;
const count = `${range.name} · 汇总 ${s.orderCount} 单${recoveryCount ? ' · 回收 ' + recoveryCount + ' 笔' : ''}${s.afterSaleCount ? ' · 售后 ' + s.afterSaleCount + ' 笔' : ''}${cancelledCount ? ',另有 ' + cancelledCount + ' 单取消未计' : ''}${orderBookFilters!.q || orderBookFilters!.status || orderBookFilters!.pocket || orderBookFilters!.member ? '(已筛选)' : ''}`;
const rows = book.displayRows ?? book.rows;
if (!rows.length) {
const list = (
@@ -677,7 +680,7 @@ export function orderBook(
rows.map((row, i) => (
<tr
className={
['afterSale', 'orderAfterSale'].includes(row.kind)
['afterSale', 'orderAfterSale'].includes(row.kind ?? '')
? 'order-after-sale'
: row.kind === 'recovery'
? 'order-recovery'
@@ -696,8 +699,10 @@ export function orderBook(
{row.kind === 'recovery' ? <span className="order-status muted">已记录</span> : badge(row)}
{orderReviewBadge(row)}
</div>
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) ? orderEntryTimeHTML(row) : ''}
{showOrderCopyEntry && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind)
{!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
? orderEntryTimeHTML(row)
: ''}
{showOrderCopyEntry && !['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '')
? button(
<>
<span aria-hidden="true">+</span>复制新增
@@ -711,7 +716,7 @@ export function orderBook(
)
: ''}
{row.status === 'cancelled' ? <div className="small muted">未计入汇总</div> : ''}
{row.balance < 0 ? <div className="small danger-text">退款待处理</div> : ''}
{(row.balance ?? 0) < 0 ? <div className="small danger-text">退款待处理</div> : ''}
</td>
<td className="order-type">
{row.types.map(e).map((part, i) => (
@@ -758,7 +763,7 @@ export function orderBook(
</tbody>
<tfoot>
<tr>
<td colSpan="2">
<td colSpan={2}>
汇总 {s.orderCount} 单
{recoveryCount ? (
<>
@@ -1,7 +1,13 @@
import type { ReactNode } from 'react';
import type { OrderRecord, OrderLine, OwnershipRequest, ChangeRequest, CancellationRequest } from '../orderData';
type CostRow = ReturnType<typeof import('../../../../../public/calculations.js').orderCosts>['rows'][number] & {
allocations?: { payer: string; amount: number | null }[];
};
import type { OrderContext, SharedViews } from '../viewTypes';
import { Children, Fragment } from 'react';
import { Calc as LedgerCalc } from '../../../shared';
export function orderDetail(
{ currentOrder, state, detailForm, error, navigation },
{ currentOrder, state, detailForm, error, navigation }: OrderContext,
{
orderCancellationPending,
orderChangePending,
@@ -41,9 +47,9 @@ export function orderDetail(
stockCountText,
pocketCountsEnabled,
teamMemberKeys,
},
}: SharedViews,
) {
function transactionTable(o) {
function transactionTable(o: OrderRecord) {
const rows = [
...o.payments.map(p => ({
date: p.date,
@@ -107,7 +113,7 @@ export function orderDetail(
<p className="muted">还没有收退款、费用或交款记录。</p>
);
}
function priceLockInventoryCreditHTML(order) {
function priceLockInventoryCreditHTML(order: OrderRecord) {
if (!order.assistantInventoryCredit) return '';
return (
<div className="note">
@@ -125,7 +131,7 @@ export function orderDetail(
</div>
);
}
function orderTeamFundsHTML(order) {
function orderTeamFundsHTML(order: OrderRecord) {
return (
<section className="panel">
<h2>{teamMemberName(order.member)}的经营订单</h2>
@@ -134,7 +140,7 @@ export function orderDetail(
</section>
);
}
function orderProductTraceHTML(o) {
function orderProductTraceHTML(o: OrderRecord) {
return (
<details className="panel detail-product-trace">
<summary>商品来源与原始说明</summary>
@@ -158,8 +164,8 @@ export function orderDetail(
</details>
);
}
function orderAfterSaleProfitHTML(order) {
const summary = orderAfterSaleRecord(order).summary,
function orderAfterSaleProfitHTML(order: OrderRecord) {
const summary = orderAfterSaleRecord(order)!.summary,
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost;
return (
<section className="panel detail-profit detail-profit-known" aria-label="售后最终利润">
@@ -177,7 +183,11 @@ export function orderDetail(
</section>
);
}
function orderProfitHTML(o, summary, { voided = false } = {}) {
function orderProfitHTML(
o: OrderRecord,
summary: ReturnType<typeof orderDetailCostSummary>,
{ voided = false } = {},
) {
if (orderAfterSaleRecord(o)) return orderAfterSaleProfitHTML(o);
const { total, missing } = summary,
done = ['delivered', 'returned', 'cancelled'].includes(o.status),
@@ -197,7 +207,7 @@ export function orderDetail(
: !known
? `成交金额 ¥${yuan(o.total)} − 完整成本待补,利润暂不确认。`
: `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)} − ${historical ? '保留成本' : '成本合计'} ¥${yuan(total)} = ${title} ¥${yuan(o.profit)}`;
if (known && sale - total !== o.profit)
if (known && sale - total! !== o.profit)
equation = `${historical ? '销售净额' : '成交金额'} ¥${yuan(sale)};成本合计 ¥${yuan(total)}。利润沿用已记账金额,历史差异请核对下方流水。`;
return (
<section className={'panel detail-profit' + (known ? ' detail-profit-known' : '')} aria-label={title}>
@@ -210,7 +220,7 @@ export function orderDetail(
</section>
);
}
function orderCostRowsHTML(rows, label) {
function orderCostRowsHTML(rows: CostRow[], label: string) {
const names = Object.fromEntries(teamMemberKeys().map(member => [member, teamMemberName(member)]));
return (
<div className="table-wrap">
@@ -229,8 +239,8 @@ export function orderDetail(
weighted = calculation?.weighted;
const formula = calculation
? weighted
? `耗用 ${grams(calculation.quantity)}g${calculation.rate == null ? '' : ' · 加权均价约 ' + yuan(calculation.rate) + '元/克'};按实际购料分摊`
: `${grams(calculation.quantity)}g × ${calculation.rate == null ? '单价待补' : yuan(calculation.rate) + '元/克'}`
? `耗用 ${grams(calculation.quantity!)}g${calculation.rate == null ? '' : ' · 加权均价约 ' + yuan(calculation.rate) + '元/克'};按实际购料分摊`
: `${grams(calculation.quantity!)}g × ${calculation.rate == null ? '单价待补' : yuan(calculation.rate) + '元/克'}`
: '';
const payer = row.poolPending
? '待补采购后分摊'
@@ -278,9 +288,9 @@ export function orderDetail(
</div>
);
}
function orderAfterSaleCostsHTML(order) {
function orderAfterSaleCostsHTML(order: OrderRecord) {
const record = orderAfterSaleRecord(order),
summary = record.summary,
summary = record!.summary,
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost,
total = summary.costLoss + direct;
return (
@@ -312,13 +322,13 @@ export function orderDetail(
</section>
);
}
function orderCostsHTML(o, summary = orderDetailCostSummary(o), { voided = false } = {}) {
function orderCostsHTML(o: OrderRecord, summary = orderDetailCostSummary(o), { voided = false } = {}) {
if (orderAfterSaleRecord(o)) return orderAfterSaleCostsHTML(o);
const { costs, rows, knownTotal, missing, knownGoods, paidFees } = summary;
const actual = rows.filter(row => !row.excluded && row.kind !== 'pending' && row.amount !== 0),
pending = rows.filter(row => row.kind === 'pending' && row.amount !== 0),
historical = rows.filter(row => row.excluded && row.amount !== 0);
const numbers = actual.filter(row => row.amount != null).map(row => row.amount),
const numbers = actual.filter(row => row.amount != null).map(row => row.amount!),
rowTotal = numbers.reduce((sum, amount) => sum + amount, 0);
const terms = rowTotal === knownTotal ? numbers : [knownGoods, paidFees].filter(amount => amount !== 0);
const equation = (terms.length ? terms : [0]).map(amount => '¥' + yuan(amount)).join(' + ');
@@ -395,7 +405,7 @@ export function orderDetail(
</section>
);
}
function orderAmount(value, mode) {
function orderAmount(value: number | null, mode: string) {
return value == null
? '待补'
: '¥' +
@@ -406,7 +416,7 @@ export function orderDetail(
})
: yuan(value));
}
function orderLinePocketHTML(order, line) {
function orderLinePocketHTML(order: OrderRecord, line: OrderLine) {
const pocket = pocketLabel(String(line.pocket || '').trim()) || '配货';
const title =
order.status === 'delivered'
@@ -429,7 +439,7 @@ export function orderDetail(
</span>
);
}
function orderSalesHTML(o, { voided = false } = {}) {
function orderSalesHTML(o: OrderRecord, { voided = false } = {}) {
const historical = voided || ['returned', 'cancelled'].includes(o.status),
unbooked = ['draft', 'confirmed'].includes(o.status);
const subtotal = o.lines.reduce((sum, line) => sum + line.sale, 0),
@@ -461,8 +471,8 @@ export function orderDetail(
line.unit === 'g' &&
Number.isSafeInteger(line.goldPrice) &&
Number.isSafeInteger(line.laborRate) &&
['gram', 'piece'].includes(line.laborMode) &&
(line.laborMode !== 'piece' || (Number.isSafeInteger(line.pieces) && line.pieces > 0));
['gram', 'piece'].includes(line.laborMode ?? '') &&
(line.laborMode !== 'piece' || (Number.isSafeInteger(line.pieces) && line.pieces! > 0));
const quantity = line.unit === 'g' ? grams(line.quantity) + 'g' : line.quantity + '件';
const formula = auto
? line.laborMode === 'gram'
@@ -553,7 +563,7 @@ export function orderDetail(
</section>
);
}
function orderAfterSaleDetailHTML(order) {
function orderAfterSaleDetailHTML(order: OrderRecord) {
const record = orderAfterSaleRecord(order);
if (!record) return '';
try {
@@ -611,7 +621,7 @@ export function orderDetail(
return (
<section className="panel">
<h2>已处理售后</h2>
<p className="danger-text">{err.message}</p>
<p className="danger-text">{err instanceof Error ? err.message : String(err)}</p>
{button('重新读取订单', 'reload-order-change', '', {
'data-id': order.id,
})}
@@ -619,7 +629,7 @@ export function orderDetail(
);
}
}
function orderOwnershipHistoryHTML(request) {
function orderOwnershipHistoryHTML(request: OwnershipRequest) {
return (
<li>
<div className="change-record-title">
@@ -651,7 +661,7 @@ export function orderDetail(
</li>
);
}
function orderOwnershipDetailHTML(order) {
function orderOwnershipDetailHTML(order: OrderRecord) {
const entry = currentOrderOwnership(order),
data = entry?.data,
request = orderOwnershipPending(order);
@@ -730,14 +740,14 @@ export function orderDetail(
) : (
''
)}
<details open={request}>
<details open={!!request}>
<summary>归属修改与复核记录({data.requests.length})</summary>
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderOwnershipHistoryHTML))}</ul>
</details>
</section>
);
}
function orderChangeHistoryHTML(request) {
function orderChangeHistoryHTML(request: ChangeRequest) {
return (
<li>
<div className="change-record-title">
@@ -771,7 +781,7 @@ export function orderDetail(
</li>
);
}
function orderChangeDetailHTML(order) {
function orderChangeDetailHTML(order: OrderRecord) {
const entry = currentOrderChange(order),
data = entry?.data,
request = orderChangePending(order);
@@ -826,14 +836,14 @@ export function orderDetail(
) : (
''
)}
<details open={request}>
<details open={!!request}>
<summary>变更申请与复核记录({data.requests.length})</summary>
<ul className="timeline change-history">{Children.toArray(data.requests.map(orderChangeHistoryHTML))}</ul>
</details>
</section>
);
}
function orderCancellationHistoryHTML(request) {
function orderCancellationHistoryHTML(request: CancellationRequest) {
if (request.direct === true)
return (
<li>
@@ -875,7 +885,7 @@ export function orderDetail(
</li>
);
}
function orderCancellationDetailHTML(order) {
function orderCancellationDetailHTML(order: OrderRecord) {
if (order.price_lock_id) return '';
const entry = currentOrderCancellation(order),
data = entry?.data,
@@ -939,7 +949,7 @@ export function orderDetail(
) : (
''
)}
<details open={request}>
<details open={!!request}>
<summary>取消申请与处理记录({data.requests.length})</summary>
<ul className="timeline cancellation-history">
{Children.toArray(data.requests.map(orderCancellationHistoryHTML))}
@@ -948,7 +958,7 @@ export function orderDetail(
</section>
);
}
function printStatusControls(value) {
function printStatusControls(value: OrderRecord) {
return (
<div className="document-print-controls">
{printStatusBadge(value)}
@@ -956,7 +966,7 @@ export function orderDetail(
</div>
);
}
function recoveryLinkedOrderNoticeHTML(order) {
function recoveryLinkedOrderNoticeHTML(order: OrderRecord) {
return order.recovery_id ? (
<div className="note">
这张销售单由置换结算自动生成。重量、抵扣与收付款请在关联置换单核对;修改或取消请从关联置换单进入,整套收付款、购料与库存一起更正。
@@ -965,10 +975,10 @@ export function orderDetail(
''
);
}
function materialPoolOrderNoticeHTML(order) {
function materialPoolOrderNoticeHTML(order: OrderRecord) {
if (!order.materialCostPending) return '';
const dates = [
...new Set(order.lines.filter(line => line.costMaterial?.mode === 'pool').map(line => line.costMaterial.poolId)),
...new Set(order.lines.filter(line => line.costMaterial?.mode === 'pool').map(line => line.costMaterial!.poolId)),
];
return (
<div className="note material-order-pending">
@@ -978,10 +988,10 @@ export function orderDetail(
</div>
);
}
function orderOwnershipOtherPending(order) {
function orderOwnershipOtherPending(order: OrderRecord) {
return orderChangePending(order) || orderCancellationPending(order);
}
function orderOwnershipActionHTML(order) {
function orderOwnershipActionHTML(order: OrderRecord) {
const data = currentOrderOwnership(order)?.data;
if (!data?.eligible || data.pending || orderOwnershipPending(order) || orderOwnershipOtherPending(order)) return '';
const direct = state.user.role === 'owner' && data.canDirect;
@@ -989,7 +999,7 @@ export function orderDetail(
'data-id': order.id,
});
}
function orderInternalNoteHTML(order) {
function orderInternalNoteHTML(order: OrderRecord) {
return (
<aside className="detail-internal-note" aria-label="内部备注(客户不可见)">
<span className="detail-internal-note-label">内部备注 · 客户不可见</span>
@@ -1008,16 +1018,16 @@ export function orderDetail(
</aside>
);
}
function orderDetailCostSummary(o) {
function orderDetailCostSummary(o: OrderRecord) {
const costs = LedgerCalc.orderCosts(o),
rows = [],
pools = new Map();
rows: CostRow[] = [],
pools = new Map<string, CostRow & { allocations: { payer: string; amount: number | null }[] }>();
for (const row of costs.rows) {
if ((row.materialPoolId || row.priceLockSource) && row.calculation?.weighted) {
const key = row.source,
existing = pools.get(key);
if (existing) {
existing.amount += row.amount;
existing.amount = Number(existing.amount) + Number(row.amount);
existing.allocations.push({
payer: row.payer,
amount: row.amount,
@@ -1051,7 +1061,7 @@ export function orderDetail(
knownGoods = costs.goodsExcluded
? 0
: Number.isSafeInteger(goods)
? goods
? goods!
: Number.isSafeInteger(o.knownGoodsCost)
? o.knownGoodsCost
: costs.total.goods;
@@ -1070,7 +1080,7 @@ export function orderDetail(
total: missing ? null : knownGoods + paidFees,
};
}
function recoveryLinkedOrderActionsHTML(order, { reviewAllowed = false } = {}) {
function recoveryLinkedOrderActionsHTML(order: OrderRecord, { reviewAllowed = false } = {}) {
return (
<>
{button('查看置换结算单', 'recovery-open', 'primary', {
@@ -1083,7 +1093,7 @@ export function orderDetail(
</>
);
}
function orderAfterSaleLegacyActionHTML(order, needsApproval) {
function orderAfterSaleLegacyActionHTML(order: OrderRecord, needsApproval: boolean) {
if (order.lines.some(line => line.priceLockPool)) return '';
const action = button(needsApproval ? '申请整单退货' : '整单退货', 'show-return', 'quiet', {
title: '旧入口:仅登记退货,实际退款另行登记',
@@ -1099,7 +1109,7 @@ export function orderDetail(
</details>
);
}
function orderAfterSaleActionHTML(order, { blocked = false } = {}) {
function orderAfterSaleActionHTML(order: OrderRecord, { blocked = false } = {}) {
if (
order.status !== 'delivered' ||
blocked ||
@@ -1112,7 +1122,7 @@ export function orderDetail(
'data-id': order.id,
});
}
function orderCancellationActionHTML(order) {
function orderCancellationActionHTML(order: OrderRecord) {
const entry = currentOrderCancellation(order),
data = entry?.data;
if (orderOwnershipPending(order)) return '';
@@ -1128,7 +1138,7 @@ export function orderDetail(
'data-id': order.id,
});
}
function orderCancellationApproved(order) {
function orderCancellationApproved(order: OrderRecord) {
return (
order.cancellationApproved ||
currentOrderCancellation(order)?.data?.requests.find(request => request.status === 'approved') ||
@@ -1136,17 +1146,17 @@ export function orderDetail(
);
}
function renderDetail() {
const o = currentOrder,
const o = currentOrder!,
done = ['delivered', 'returned', 'cancelled'].includes(o.status);
const cancellationPending = orderCancellationPending(o),
changePending = orderChangePending(o),
ownershipPending = orderOwnershipPending(o),
approvalPending = !!cancellationPending || !!changePending || !!ownershipPending,
afterSaleDone = !!orderAfterSaleRecord(o),
voided = orderCancellationApproved(o),
voided = !!orderCancellationApproved(o),
financialBlocked = approvalPending || !!voided || afterSaleDone,
owner = state.user.role === 'owner';
let actions = (
let actions: ReactNode = (
<>
{button('客户预览/打印', 'print', 'primary', {
'data-id': o.id,
@@ -1176,7 +1186,7 @@ export function orderDetail(
);
if (o.status === 'draft' && owner && !financialBlocked)
actions = Children.toArray([actions, button('继续填写并开单', 'edit')]);
const needsApproval = kind => orderActionRequiresApproval(kind);
const needsApproval = (kind: string) => orderActionRequiresApproval(kind);
if (o.status === 'confirmed' && !financialBlocked) {
if (o.pendingFees.length)
actions = Children.toArray([
@@ -1335,7 +1345,7 @@ export function orderDetail(
<small className="muted">实际已交净额 ¥{yuan(o.profitTransferred)}</small>
</div>
<div>
{o.settlementDue < 0
{Number(o.settlementDue) < 0
? teamMemberName('owner') + '待转回' + teamMemberName('assistant')
: teamMemberName('assistant') + '待交' + teamMemberName('owner')}{' '}
<strong>{o.settlementDue == null ? '料费待补' : '¥' + yuan(Math.abs(o.settlementDue))}</strong>
@@ -1386,7 +1396,7 @@ export function orderDetail(
<summary>操作记录</summary>
<ul className="timeline">
{Children.toArray(
o.audit.map(a => (
o.audit!.map(a => (
<li>
{actionName[a.action] || a.action} · {a.actor}
<small>{new Date(a.created).toLocaleString('zh-CN')}</small>
@@ -1,3 +1,5 @@
import type { CancellationRequest, OwnershipRequest, ChangeRequest, ReviewList, CancelSummary } from '../orderData';
import type { OrderContext, SharedViews } from '../viewTypes';
import { Children } from 'react';
export function orderReviews(
{
@@ -9,7 +11,7 @@ export function orderReviews(
orderChangeListStatus,
orderOwnershipListStatus,
orderCancellationListStatus,
},
}: OrderContext,
{
orderChangeActionLabel,
orderChangeTime,
@@ -34,12 +36,12 @@ export function orderReviews(
orderOwnershipStatus,
validateOrderChangeRequest,
validateOrderOwnershipRequest,
},
}: SharedViews,
) {
function orderCancellationRecordStatus(request) {
function orderCancellationRecordStatus(request: CancellationRequest) {
return request.direct === true ? '当天直接取消' : orderCancellationStatus[request.status];
}
function orderCancellationListHTML(result) {
function orderCancellationListHTML(result: ReviewList<CancellationRequest>) {
const owner = state.user.role === 'owner' && result.canApprove;
return (
<>
@@ -130,7 +132,7 @@ export function orderReviews(
</>
);
}
function orderOwnershipListHTML(result) {
function orderOwnershipListHTML(result: ReviewList<OwnershipRequest>) {
const owner = state.user.role === 'owner' && result.canApprove;
return (
<>
@@ -222,7 +224,7 @@ export function orderReviews(
</>
);
}
function orderChangeListHTML(result) {
function orderChangeListHTML(result: ReviewList<ChangeRequest>) {
const owner = state.user.role === 'owner' && result.canApprove;
return (
<>
@@ -318,7 +320,9 @@ export function orderReviews(
</>
);
}
function legacyCountConfirmationHTML(value) {
function legacyCountConfirmationHTML(
value: { requiresLegacyCountVerified?: boolean; legacyCountNotice?: string } | undefined,
) {
return value?.requiresLegacyCountVerified ? (
<>
<div className="note">
@@ -334,9 +338,9 @@ export function orderReviews(
''
);
}
function validateOrderCancellationRequest(request, orderId) {
function validateOrderCancellationRequest(request: CancellationRequest, orderId: string | undefined = undefined) {
const summary = request?.summary,
nullable = value => value === null || Number.isSafeInteger(value);
nullable = (value: unknown) => value === null || Number.isSafeInteger(value);
if (
!request ||
typeof request.id !== 'string' ||
@@ -351,8 +355,8 @@ export function orderReviews(
typeof request.stale !== 'boolean' ||
typeof request.canApprove !== 'boolean' ||
!summary ||
!['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) ||
!['goodsCost', 'profit', 'settlementDue'].every(key => nullable(summary[key])) ||
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
!(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(summary[key])) ||
!Array.isArray(summary.inventory) ||
!summary.inventory.every(
item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg),
@@ -361,12 +365,12 @@ export function orderReviews(
throw new Error('取消申请资料未完整返回,请重新读取订单后复核。');
return request;
}
function orderCancellationSummaryHTML(request) {
function orderCancellationSummaryHTML(request: CancellationRequest) {
return orderCancellationSummaryDataHTML(validateOrderCancellationRequest(request).summary);
}
function orderCancellationSummaryDataHTML(value) {
function orderCancellationSummaryDataHTML(value: CancelSummary | undefined) {
const summary = validateOrderCancellationSummary(value),
amount = value => (value === null ? '待补齐' : '¥' + yuan(value));
amount = (value: number | null) => (value === null ? '待补齐' : '¥' + yuan(value));
return (
<>
<div className="note">本次按“录错作废”撤销本单记账,不是实际退货退款。原单和冲回明细保留,不会向客户付款。</div>
@@ -437,12 +441,12 @@ export function orderReviews(
);
}
const requireOrderCancellationDetail = () => ({
order: currentOrder,
data: orderCancellationDetail.data,
order: currentOrder!,
data: orderCancellationDetail!.data!,
});
function showOrderCancellationForm(kind) {
function showOrderCancellationForm(kind: string) {
const { order, data } = requireOrderCancellationDetail(),
request = data.pending;
request = data.pending!;
if (kind === 'request' && orderCancellationCanDirect(order)) kind = 'direct';
if (
['request', 'direct'].includes(kind) &&
@@ -473,9 +477,9 @@ export function orderReviews(
取消原因
<textarea
name="reason"
rows="3"
rows={3}
required
maxLength="200"
maxLength={200}
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
></textarea>
</label>
@@ -498,9 +502,9 @@ export function orderReviews(
取消原因
<textarea
name="reason"
rows="3"
rows={3}
required
maxLength="200"
maxLength={200}
placeholder="写清这张单录错的原因,例如:同一笔销售重复录入。"
></textarea>
</label>
@@ -517,7 +521,7 @@ export function orderReviews(
<p className="cancellation-reason">取消原因:{request.reason}</p>
{orderCancellationSummaryHTML(request)}
<label>
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
</label>
<label className="check">
<input type="checkbox" name="verified" required />
@@ -536,9 +540,9 @@ export function orderReviews(
驳回意见
<textarea
name="note"
rows="3"
rows={3}
required
maxLength="200"
maxLength={200}
placeholder="写清需要补充或重新核对的地方。"
></textarea>
</label>
@@ -573,12 +577,12 @@ export function orderReviews(
);
}
const requireOrderOwnershipDetail = () => ({
order: currentOrder,
data: orderOwnershipDetail.data,
order: currentOrder!,
data: orderOwnershipDetail!.data!,
});
function showOrderOwnershipForm(kind = 'request') {
const { order, data } = requireOrderOwnershipDetail(),
request = data.pending;
request = data.pending!;
if (!['request', 'approve', 'reject'].includes(kind)) throw new Error('归属修改操作无效,请重新读取。');
if (kind === 'request' && (!data.eligible || request)) throw new Error(data.reason || '本单当前不能重复修改归属。');
if (kind !== 'request' && (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending'))
@@ -592,7 +596,7 @@ export function orderReviews(
if (kind === 'request') {
title = direct ? '修改订单归属' : '申请修改订单归属';
submit = direct ? '确认修改归属' : '提交归属申请';
const before = data.members.find(member => member.member === data.member),
const before = data.members.find(member => member.member === data.member)!,
members = data.members.filter(
member => member.member !== data.member && member.enabled !== false && teamMemberEnabled(member.member),
);
@@ -609,7 +613,10 @@ export function orderReviews(
<label>
修改为
<select name="member" required defaultValue="">
{opts([['', '请选择新归属'], ...members.map(member => [member.member, member.label])])}
{opts([
['', '请选择新归属'],
...members.map((member): [string, string] => [member.member, member.label]),
])}
</select>
</label>
</div>
@@ -622,8 +629,8 @@ export function orderReviews(
<textarea
name="reason"
required
maxLength="200"
rows="3"
maxLength={200}
rows={3}
placeholder="写清原归属录错的原因及正确归属。"
></textarea>
</label>
@@ -647,7 +654,7 @@ export function orderReviews(
<>
{orderOwnershipEffectHTML(request.before.member)}
<label>
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
</label>
<label className="check">
<input type="checkbox" name="verified" required />
@@ -662,8 +669,8 @@ export function orderReviews(
<textarea
name="note"
required
maxLength="200"
rows="3"
maxLength={200}
rows={3}
placeholder="写清需要重新核对的地方。"
></textarea>
</label>
@@ -687,12 +694,12 @@ export function orderReviews(
);
}
const requireOrderChangeDetail = () => ({
order: currentOrder,
data: orderChangeDetail.data,
order: currentOrder!,
data: orderChangeDetail!.data!,
});
function showOrderChangeForm(kind) {
function showOrderChangeForm(kind: string) {
const { order, data } = requireOrderChangeDetail(),
request = data.pending;
request = data.pending!;
if (!['approve', 'reject'].includes(kind)) throw new Error('修改复核操作无效,请重新读取订单。');
if (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending')
throw new Error('修改申请由店主账号复核。');
@@ -716,7 +723,7 @@ export function orderReviews(
{orderChangeActionSummaryHTML(request)}
{orderChangeComparisonHTML(request)}
<label>
复核备注(选填)<textarea name="note" maxLength="200" rows="2"></textarea>
复核备注(选填)<textarea name="note" maxLength={200} rows={2}></textarea>
</label>
<label className="check">
<input type="checkbox" name="verified" required />
@@ -732,8 +739,8 @@ export function orderReviews(
<textarea
name="note"
required
maxLength="200"
rows="3"
maxLength={200}
rows={3}
placeholder="写清需要重新核对或补充的地方。"
></textarea>
</label>
@@ -1,3 +1,21 @@
import type { ReactNode, ButtonHTMLAttributes, InputHTMLAttributes } from 'react';
import type { OrderContext, Options } from '../viewTypes';
import type {
OrderRecord,
OrderLine,
OwnershipRequest,
ChangeRequest,
CancelSummary,
Member,
RelatedLock,
LockImpact,
InventoryRow,
InventoryChange,
LockCosts,
OrderAfterSale,
BookRow,
PrintStatus,
} from '../orderData';
import { Children, Fragment } from 'react';
import { Calc as LedgerCalc, Cards as CreditCardFees, Values } from '../../../shared';
export function sharedViews({
@@ -8,8 +26,11 @@ export function sharedViews({
orderOwnershipDetail,
orderCancellationDetail,
ui = {},
}) {
function stockCountValue(value, { zero = false, optional = false, signed = false, title = '库存数量(对)' } = {}) {
}: OrderContext) {
function stockCountValue(
value: unknown,
{ zero = false, optional = false, signed = false, title = '库存数量(对)' } = {},
) {
const text = String(value ?? '').trim();
if (!text && optional) return null;
if (signed) {
@@ -44,8 +65,8 @@ export function sharedViews({
return Array.isArray(state?.pockets) ? state.pockets : defaultPocketKeys;
}
function stockCountField(
pocket,
value = '',
pocket: string,
value: string | number | null | undefined = '',
{
name = 'stockCount',
title = '出库数量(对)',
@@ -53,7 +74,7 @@ export function sharedViews({
readOnly = false,
visible = pocketCountsEnabled(pocket),
help,
} = {},
}: { name?: string; title?: string; optional?: boolean; readOnly?: boolean; visible?: boolean; help?: string } = {},
) {
const hint = help ?? (optional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。');
return (
@@ -79,7 +100,7 @@ export function sharedViews({
function currentMember() {
return state?.user?.member || session?.user?.member || (state?.user?.role === 'owner' ? 'owner' : 'assistant');
}
function normalizePaymentAccount(account) {
function normalizePaymentAccount(account: string) {
return typeof CreditCardFees === 'object' && typeof CreditCardFees.normalizeAccount === 'function'
? CreditCardFees.normalizeAccount(account)
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
@@ -95,7 +116,7 @@ export function sharedViews({
);
if (assistantFirst)
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
const options = keys.map(member => [
const options = keys.map((member): [string, string] => [
member,
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
]);
@@ -103,7 +124,7 @@ export function sharedViews({
options.push([selected, teamMemberName(selected) + '(已停用 · 原记录)']);
return options;
}
const choice = (title, name, values, selected) => {
const choice = (title: string, name: string, values: Options, selected?: string) => {
if (
selected &&
teamMemberKeys().includes(selected) &&
@@ -121,19 +142,25 @@ export function sharedViews({
</label>
);
};
const moneyField = (title, name, value = '') =>
const moneyField = (title: string, name: string, value: string | number = '') =>
field(title, name, value, 'number', {
min: '0',
step: '0.01',
required: true,
});
const field = (title, name, value = '', type = 'text', props = {}) => (
const field = (
title: string,
name: string,
value: string | number = '',
type = 'text',
props: InputHTMLAttributes<HTMLInputElement> = {},
) => (
<label>
{title}
<input type={type} name={name} defaultValue={value} {...props} />
</label>
);
const opts = values =>
const opts = (values: Options) =>
values.map(v => {
const [value, name, disabled] = Array.isArray(v) ? v : [v, v];
return (
@@ -142,10 +169,7 @@ export function sharedViews({
</option>
);
});
function teamMemberEnabled(member) {
return Values.memberEnabled(state, member);
}
const actionName = {
const actionName: Record<string, string> = {
confirm: '确认订单',
receipt: '登记收款',
refund: '登记退款',
@@ -161,7 +185,7 @@ export function sharedViews({
correct: '更正流水',
ownership: '修改订单归属',
};
function orderOwnershipEffectHTML(before) {
function orderOwnershipEffectHTML(before: string) {
return (
<>
<p className="small muted">
@@ -177,11 +201,11 @@ export function sharedViews({
</>
);
}
function orderOwnershipTime(value) {
const date = new Date(value);
function orderOwnershipTime(value: string | null) {
const date = new Date(value!);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
function validOrderOwnershipMember(value) {
function validOrderOwnershipMember(value: Member) {
return value && teamMemberKeys().includes(value.member) && typeof value.label === 'string' && !!value.label;
}
const orderOwnershipStatus = {
@@ -189,7 +213,7 @@ export function sharedViews({
approved: '已修改归属',
rejected: '已驳回',
};
function validateOrderOwnershipRequest(request, orderId) {
function validateOrderOwnershipRequest(request: OwnershipRequest, orderId: string | undefined = undefined) {
if (
!request ||
typeof request.id !== 'string' ||
@@ -211,7 +235,7 @@ export function sharedViews({
throw new Error('归属修改资料未完整返回,请重新读取订单后复核。');
return request;
}
function orderOwnershipPairHTML(request) {
function orderOwnershipPairHTML(request: OwnershipRequest) {
validateOrderOwnershipRequest(request);
return (
<div className="order-ownership-pair" aria-label="订单归属原值与新值">
@@ -227,17 +251,17 @@ export function sharedViews({
</div>
);
}
function relatedPriceLocksHTML(items) {
function relatedPriceLocksHTML(items: RelatedLock[] | undefined) {
const locks = validateRelatedPriceLocks(items);
if (!locks.length) return '';
const money = value => (value === null ? '待补齐' : '¥' + yuan(value)),
sources = value =>
const money = (value?: number | null) => (value === null ? '待补齐' : '¥' + yuan(value)),
sources = (value: LockImpact) =>
value.allocations.length
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
: value.materialAmount === null
? '待补齐后分摊'
: '无分摊金额';
const pair = (name, before, after) => (
const pair = (name: string, before: ReactNode, after: ReactNode) => (
<tr>
<th scope="row">{name}</th>
<td>{before}</td>
@@ -266,7 +290,7 @@ export function sharedViews({
</thead>
<tbody>
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
? pair(
'交付耗用原锁料费',
Object.hasOwn(lock.before, 'usedMaterialAmount')
@@ -277,7 +301,7 @@ export function sharedViews({
: '未交付',
)
: ''}
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'leftoverCost'))
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'leftoverCost'))
? pair(
'少重回池成本',
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
@@ -294,7 +318,7 @@ export function sharedViews({
</section>
);
}
function inventoryCountHTML(item, { signed = false } = {}) {
function inventoryCountHTML(item: InventoryRow, { signed = false } = {}) {
return Number.isSafeInteger(item?.stockCount) ? (
<div className="small stock-count-number">
{stockCountText(item.stockCount, {
@@ -307,9 +331,9 @@ export function sharedViews({
''
);
}
function orderChangeInventoryHTML(inventory) {
function orderChangeInventoryHTML(inventory: InventoryChange | undefined) {
if (!inventory) return '';
const table = (title, rows, changes = false) => (
const table = (title: string, rows: InventoryRow[], changes = false) => (
<>
<h3>{title}</h3>
{rows.length ? (
@@ -361,11 +385,11 @@ export function sharedViews({
</section>
);
}
function orderChangeEffectiveExpenses(order) {
function orderChangeEffectiveExpenses(order: OrderRecord) {
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
return order.expenses.filter(row => row.amount > 0 && !corrected.has(row.id));
}
function orderChangeExpensesValue(order) {
function orderChangeExpensesValue(order: OrderRecord) {
return (
orderChangeEffectiveExpenses(order)
.map(
@@ -375,7 +399,7 @@ export function sharedViews({
.join('\n\n') || '无已记费用'
);
}
function orderChangePaymentsValue(order) {
function orderChangePaymentsValue(order: OrderRecord) {
const corrected = new Set((order.corrections || []).filter(row => row.type === 'payment').map(row => row.target));
return (
order.payments
@@ -387,12 +411,16 @@ export function sharedViews({
.join('\n\n') || '无有效收退款'
);
}
function orderChangePriceLockCostsHTML(before, after, title = '锁价购料成本') {
function orderChangePriceLockCostsHTML(
before: { priceLockCosts?: LockCosts },
after: { priceLockCosts?: LockCosts },
title = '锁价购料成本',
): ReactNode {
if (!before.priceLockCosts && !after.priceLockCosts) return '';
if (before.priceLockCosts?.lines || after.priceLockCosts?.lines) {
const a = before.priceLockCosts || {},
b = after.priceLockCosts || {},
rows = a.lines || b.lines;
rows = a.lines || b.lines!;
return Children.toArray(
rows.map((row, index) => {
const left = a.lines?.find(item => item.lineId === row.lineId) || {},
@@ -417,11 +445,11 @@ export function sharedViews({
}
const a = before.priceLockCosts || {},
b = after.priceLockCosts || {},
source = value => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
source = (value?: string) => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
return (
<>
<tr className="change-section-row">
<th colSpan="3" scope="colgroup">
<th colSpan={3} scope="colgroup">
{title}
</th>
</tr>
@@ -443,7 +471,7 @@ export function sharedViews({
</>
);
}
function orderChangeLineValue(line, kind) {
function orderChangeLineValue(line: OrderLine | undefined, kind: string) {
if (!line) return '无此商品';
const money = orderChangeMoney;
if (kind === 'name') return `${line.name || '未填写'}${line.priceNote ? '\n' + line.priceNote : ''}`;
@@ -480,7 +508,7 @@ export function sharedViews({
return `料费:${line.costMaterial?.mode === 'pool' ? line.materialPool?.allocations?.map(item => orderChangePayer(item.payer) + ' ' + money(item.amount)).join(';') || '按真实采购分摊' : orderChangePayer(line.costPayers?.material ?? line.payer)}\n进货工费:${orderChangePayer(line.costPayers?.labor ?? line.payer)}\n配件及其他:${orderChangePayer(line.payer)}`;
return '';
}
function orderChangePair(title, before, after) {
function orderChangePair(title: string, before: ReactNode, after: ReactNode) {
const changed = String(before ?? '') !== String(after ?? '');
return (
<tr
@@ -499,13 +527,15 @@ export function sharedViews({
</tr>
);
}
function validateRelatedPriceLocks(items) {
function validateRelatedPriceLocks(items: RelatedLock[] | undefined) {
if (items === undefined) return [];
const amount = value => value === null || (Number.isSafeInteger(value) && value >= 0);
const snapshot = value =>
const amount = (value?: number | null) => value === null || (Number.isSafeInteger(value) && value! >= 0);
const snapshot = (value: LockImpact) =>
value &&
amount(value.materialAmount) &&
['usedMaterialAmount', 'leftoverCost'].every(key => !Object.hasOwn(value, key) || amount(value[key])) &&
(['usedMaterialAmount', 'leftoverCost'] as const).every(
key => !Object.hasOwn(value, key) || amount(value[key]),
) &&
Array.isArray(value.allocations) &&
value.allocations.every(
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
@@ -527,15 +557,15 @@ export function sharedViews({
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
return items;
}
function validateOrderChangeRequest(request, orderId) {
const validSnapshot = order =>
function validateOrderChangeRequest(request: ChangeRequest, orderId: string | undefined = undefined) {
const validSnapshot = (order: OrderRecord) =>
order &&
order.id === request.order_id &&
Number.isSafeInteger(order.total) &&
Array.isArray(order.lines) &&
Array.isArray(order.expenses) &&
Array.isArray(order.payments);
const nullable = value => value === null || Number.isSafeInteger(value);
const nullable = (value?: number | null) => value === null || Number.isSafeInteger(value);
if (
!request ||
typeof request.id !== 'string' ||
@@ -551,11 +581,13 @@ export function sharedViews({
typeof request.canApprove !== 'boolean' ||
!validSnapshot(request.before) ||
!validSnapshot(request.after) ||
!['before', 'after'].every(
!(['before', 'after'] as const).every(
side =>
request.summary?.[side] &&
['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(request.summary[side][key])) &&
['goodsCost', 'profit', 'settlementDue'].every(key => nullable(request.summary[side][key])),
(['total', 'netReceived', 'directCost'] as const).every(key =>
Number.isSafeInteger(request.summary[side][key]),
) &&
(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(request.summary[side][key])),
)
)
throw new Error('修改申请资料未完整返回,请重新读取订单后复核。');
@@ -579,7 +611,7 @@ export function sharedViews({
if (
inventory !== undefined &&
(!inventory ||
!['before', 'after', 'changes'].every(
!(['before', 'after', 'changes'] as const).every(
key =>
Array.isArray(inventory[key]) &&
inventory[key].every(
@@ -590,7 +622,7 @@ export function sharedViews({
throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。');
return request;
}
function orderChangeComparisonHTML(raw) {
function orderChangeComparisonHTML(raw: ChangeRequest) {
const request = validateOrderChangeRequest(raw),
before = request.before,
after = request.after;
@@ -601,14 +633,16 @@ export function sharedViews({
{
<>
{Children.toArray(
[
['业务日期', 'date'],
['客户称呼/代号', 'customer'],
['开单人', 'salesperson'],
['收款方式与收款人', 'payment_account'],
['客户单备注', 'note'],
['内部备注(客户不可见)', 'internal_note'],
].map(([title, key]) =>
(
[
['业务日期', 'date'],
['客户称呼/代号', 'customer'],
['开单人', 'salesperson'],
['收款方式与收款人', 'payment_account'],
['客户单备注', 'note'],
['内部备注(客户不可见)', 'internal_note'],
] as const
).map(([title, key]) =>
orderChangePair(
title,
key === 'payment_account' ? accountDisplayName(before[key]) : before[key],
@@ -630,14 +664,16 @@ export function sharedViews({
</>
);
const summary = Children.toArray(
[
['成交金额', 'total'],
['收款净额', 'netReceived'],
['货品成本', 'goodsCost'],
['实际费用合计', 'directCost'],
['利润', 'profit'],
['双方待结净额', 'settlementDue'],
].map(([title, key]) =>
(
[
['成交金额', 'total'],
['收款净额', 'netReceived'],
['货品成本', 'goodsCost'],
['实际费用合计', 'directCost'],
['利润', 'profit'],
['双方待结净额', 'settlementDue'],
] as const
).map(([title, key]) =>
orderChangePair(
title,
orderChangeMoney(request.summary.before[key]),
@@ -653,7 +689,7 @@ export function sharedViews({
(_, index) => (
<>
<tr className="change-section-row">
<th colSpan="3" scope="colgroup">
<th colSpan={3} scope="colgroup">
商品 {index + 1}
</th>
</tr>
@@ -726,7 +762,7 @@ export function sharedViews({
{summary}
{lines}
<tr className="change-section-row">
<th colSpan="3" scope="colgroup">
<th colSpan={3} scope="colgroup">
逐笔收退款与实际费用
</th>
</tr>
@@ -752,7 +788,7 @@ export function sharedViews({
</div>
);
}
function orderChangeCell(value) {
function orderChangeCell(value: ReactNode) {
return String(value == null || value === '' ? '未填写' : value)
.split('\n')
.map((line, index) => (
@@ -762,58 +798,60 @@ export function sharedViews({
</Fragment>
));
}
function orderChangePayer(value) {
function orderChangePayer(value: string | undefined) {
return value ? teamMemberName(value) : '待补齐';
}
function orderChangeMoney(value) {
function orderChangeMoney(value: number | null | undefined) {
return value == null ? '待补齐' : '¥' + yuan(value);
}
function orderChangeInputMoney(value) {
function orderChangeInputMoney(value: unknown) {
try {
return orderChangeMoney(LedgerCalc.cents(value));
} catch {
return '金额未提供';
}
}
function stockCountText(value, { signed = false, unknown = '未记录对数' } = {}) {
return Number.isSafeInteger(value) ? (signed && value > 0 ? '+' : '') + value + '对' : unknown;
function stockCountText(value: unknown, { signed = false, unknown = '未记录对数' } = {}) {
return Number.isSafeInteger(value) ? (signed && Number(value) > 0 ? '+' : '') + value + '对' : unknown;
}
function pocketCountsEnabled(key) {
function pocketCountsEnabled(key: string) {
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
}
function pocketLabel(key) {
function pocketLabel(key: string) {
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
}
function validateOrderAfterSaleRecord(record) {
function validateOrderAfterSaleRecord(record: OrderAfterSale | null) {
if (
!record ||
!Array.isArray(record.lines) ||
!record.lines.length ||
!record.lines.every(line =>
['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'].every(key =>
(['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'] as const).every(key =>
Number.isSafeInteger(line[key]),
),
) ||
!record.summary ||
![
'refundAmount',
'retainedAmount',
'materialReturnedCost',
'laborRestockedCost',
'costLoss',
'directCost',
'profit',
'profitAdjustment',
].every(key => Number.isSafeInteger(record.summary[key]))
!(
[
'refundAmount',
'retainedAmount',
'materialReturnedCost',
'laborRestockedCost',
'costLoss',
'directCost',
'profit',
'profitAdjustment',
] as const
).every(key => Number.isSafeInteger(record.summary[key]))
)
throw new Error('售后核算资料未完整返回,请重新读取订单。');
return record;
}
function orderAfterSaleSummaryHTML(raw, { preview = false } = {}) {
function orderAfterSaleSummaryHTML(raw: OrderAfterSale | null, { preview = false } = {}) {
const record = validateOrderAfterSaleRecord(raw),
summary = record.summary,
money = value => '¥' + yuan(value),
facts = [
money = (value: number) => '¥' + yuan(value),
facts: [string, number][] = [
['实际退款', summary.refundAmount],
['扣留客户款', summary.retainedAmount],
['回料池原料成本', summary.materialReturnedCost],
@@ -893,7 +931,7 @@ export function sharedViews({
</section>
);
}
function orderChangeActionSummaryHTML(request) {
function orderChangeActionSummaryHTML(request: ChangeRequest) {
const action = request.action || 'edit',
input = request.action_input || request.action_details || {};
if (action === 'edit') return '';
@@ -964,8 +1002,8 @@ export function sharedViews({
</section>
);
}
function orderChangeTime(value) {
const date = new Date(value);
function orderChangeTime(value: string | null) {
const date = new Date(value!);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
const orderChangeStatus = {
@@ -973,7 +1011,7 @@ export function sharedViews({
approved: '已同意变更',
rejected: '已驳回',
};
const orderChangeActionLabels = {
const orderChangeActionLabels: Record<string, string> = {
edit: '修改订单',
expense: '费用补记',
fees: '旧费用核实',
@@ -981,7 +1019,7 @@ export function sharedViews({
return: '退货',
cost: '成本补录',
};
function orderChangeActionLabel(request) {
function orderChangeActionLabel(request: ChangeRequest) {
if ((request.action_input || request.action_details)?.afterSale) return '处理订单售后';
return request.action_label || orderChangeActionLabels[request.action || 'edit'] || '订单变更';
}
@@ -990,20 +1028,20 @@ export function sharedViews({
approved: '已同意取消',
rejected: '已驳回',
};
function orderCancellationTime(value) {
const date = new Date(value);
function orderCancellationTime(value: string | null) {
const date = new Date(value!);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
const accountIdentity = value => Values.accountIdentity(teamMemberKeys(), value);
function accountDisplayName(value) {
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
function accountDisplayName(value: string) {
const account = accountIdentity(value);
return account ? teamMemberName(account.member) + account.channel : value;
}
function validateOrderCancellationSummary(summary) {
function validateOrderCancellationSummary(summary: CancelSummary | undefined) {
if (
!summary ||
!['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) ||
!['goodsCost', 'profit', 'settlementDue'].every(
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
!(['goodsCost', 'profit', 'settlementDue'] as const).every(
key => summary[key] === null || Number.isSafeInteger(summary[key]),
) ||
!Array.isArray(summary.inventory) ||
@@ -1021,9 +1059,9 @@ export function sharedViews({
data.pending ||
data.directToday !== true ||
!/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') ||
order.date !== data.directActionDate ||
order.price_lock_id ||
!['draft', 'confirmed', 'delivered'].includes(order.status)
order?.date !== data.directActionDate ||
order?.price_lock_id ||
!['draft', 'confirmed', 'delivered'].includes(order?.status || '')
)
return false;
try {
@@ -1033,7 +1071,7 @@ export function sharedViews({
return false;
}
}
function orderActionCanDirect(kind, date = state.today, order = currentOrder) {
function orderActionCanDirect(kind: string, date = state.today, order = currentOrder) {
const data = currentOrderChange(order)?.data;
return (
['expense', 'fees', 'refund', 'return'].includes(kind) &&
@@ -1041,18 +1079,18 @@ export function sharedViews({
!data.pending &&
/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') &&
data.actions?.[kind]?.directToday === true &&
order.date === data.directActionDate &&
order?.date === data.directActionDate &&
date === data.directActionDate &&
!(ui.action === kind && ui.forceApproval)
);
}
function orderActionUsesChangeForm(kind) {
function orderActionUsesChangeForm(kind: string) {
return state.user.role === 'assistant' && ['expense', 'fees', 'refund', 'return', 'cost'].includes(kind);
}
function orderActionRequiresApproval(kind, date = state.today) {
function orderActionRequiresApproval(kind: string, date = state.today) {
return orderActionUsesChangeForm(kind) && !orderActionCanDirect(kind, date);
}
function orderAfterSaleRecord(order) {
function orderAfterSaleRecord(order: OrderRecord | undefined) {
return order?.orderAfterSale || null;
}
function orderOwnershipUser() {
@@ -1080,7 +1118,7 @@ export function sharedViews({
? orderChangeDetail
: null;
}
function orderChangePending(order) {
function orderChangePending(order: OrderRecord) {
return currentOrderChange(order)?.data?.pending || order?.changePending || null;
}
function orderCancellationUser() {
@@ -1094,11 +1132,11 @@ export function sharedViews({
? orderCancellationDetail
: null;
}
function orderCancellationPending(order) {
function orderCancellationPending(order: OrderRecord) {
return currentOrderCancellation(order)?.data?.pending || order.cancellationPending || null;
}
function printStatusBadge(value) {
if (['afterSale', 'orderAfterSale'].includes(value.kind)) return '';
function printStatusBadge(value: { id: string; kind?: string; printStatus?: PrintStatus }) {
if (['afterSale', 'orderAfterSale'].includes(value.kind ?? '')) return '';
const printed = value.printStatus?.printed;
return (
<span
@@ -1112,7 +1150,7 @@ export function sharedViews({
);
}
const grams = Values.grams;
const e = value => String(value ?? '');
const e = (value: unknown) => String(value ?? '');
const showOrderCopyEntry = false;
const orderEntryTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
@@ -1124,7 +1162,7 @@ export function sharedViews({
hourCycle: 'h23',
});
const validOrderDate = Values.validDate;
function orderEntryTime(value) {
function orderEntryTime(value: unknown) {
if (
typeof value !== 'string' ||
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
@@ -1133,23 +1171,23 @@ export function sharedViews({
!validOrderDate(value.slice(0, 10))
)
return '未记录';
const date = new Date(value);
const date = new Date(value!);
if (Number.isNaN(date.getTime())) return '未记录';
const parts = Object.fromEntries(orderEntryTimeFormatter.formatToParts(date).map(part => [part.type, part.value]));
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
}
function orderEntryTimeHTML(order) {
function orderEntryTimeHTML(order: { created: string }) {
return <div className="small muted order-entry-time">录入时间(北京时间):{orderEntryTime(order.created)}</div>;
}
function orderIsReviewed(row) {
function orderIsReviewed(row: Pick<BookRow, 'kind' | 'revision' | 'reviewed_revision'>) {
return (
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind) &&
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') &&
Number.isSafeInteger(row.revision) &&
row.revision > 0 &&
row.revision! > 0 &&
row.reviewed_revision === row.revision
);
}
const label = {
const label: Record<string, string> = {
draft: '旧草稿',
confirmed: '旧单待补齐',
delivered: '已完成',
@@ -1158,36 +1196,44 @@ export function sharedViews({
after_sale: '售后',
recovery: '回收',
};
const badge = o => (
const badge = (o: { status: string }) => (
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
{label[o.status] || o.status}
</span>
);
const button = (text, action, cls = '', props = {}) => (
const button = (
text: ReactNode,
action: string,
cls = '',
props: ButtonHTMLAttributes<HTMLButtonElement> & {
[key: `data-${string}`]: string | number | boolean | undefined;
} = {},
) => (
<button type="button" data-action={action} className={cls} {...props}>
{text}
</button>
);
function teamMemberName(member) {
function teamMemberName(member: string | undefined) {
return (
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
state?.members?.find(row => row.member === member)?.label ||
session?.loginOptions?.find(row => row.member === member)?.label ||
{
owner: '麦麦',
assistant: '娜娜',
assistant2: '小昊',
}[member] ||
(
{
owner: '麦麦',
assistant: '娜娜',
assistant2: '小昊',
} as Record<string, string>
)[member ?? ''] ||
'待确认'
);
}
function teamMemberKeys() {
return Values.memberKeys(state);
}
const teamMemberKeys = () => Values.memberKeys(state);
const teamMemberEnabled = (member: string) => Values.memberEnabled(state, member);
function teamMode() {
return !!(state?.user?.member || state?.members?.some(member => member.member === 'assistant2'));
}
const yuan = n => (n == null ? '待补' : Values.yuan(n));
const yuan = (n?: number | null) => (n == null ? '待补' : Values.yuan(n));
return {
yuan,
teamMode,
@@ -1,9 +1,35 @@
import type { LedgerState, LineState, OrderForm } from '../../shared';
import type { LockViews, LockRecord, DeliveryCost } from './types';
import type { StockSelection, EditLine } from './deliveryTypes';
import type { useLockPool } from './useLockPool';
import { Model } from '../../shared';
import { Act, Field, Money, Choice, Check, Charges } from './formParts';
export function DeliveryFields({ views, state, item, line, index, stock, cost, quote, update, changeStock }) {
const field = (k, v) => update(Model.setLineField(line, k, v)),
buy = (k, v) => update(Model.setPurchaseField(line, k, v));
const p = line.purchase,
export function DeliveryFields({
views,
state,
item,
line,
index,
stock,
cost,
quote,
update,
changeStock,
}: {
views: LockViews;
state: LedgerState;
item: LockRecord;
line: LineState;
index: number;
stock: StockSelection;
cost?: DeliveryCost;
quote: ReturnType<typeof useLockPool>;
update: EditLine;
changeStock<K extends keyof StockSelection>(key: K, value: StockSelection[K]): void;
}) {
const field = (k: keyof LineState, v: string) => update(Model.setLineField(line, k, v)),
buy = (k: keyof NonNullable<LineState['purchase']>, v: string) => update(Model.setPurchaseField(line, k, v));
const p = line.purchase!,
piece = line.laborMode === 'piece',
gram = p.laborMode === 'gram',
custom = line.nameType === '其他',
@@ -11,14 +37,14 @@ export function DeliveryFields({ views, state, item, line, index, stock, cost, q
pool = item.material_source === 'pool',
extra = !!(Number(line.quantity) * 1000 > item.locked_mg),
extraPool = extra && stock.extra_source === 'pool',
members = k => Model.memberOptions(state, false, { selected: k });
members = (k: string) => Model.memberOptions(state, false, { selected: k });
const materialFormula = cost?.extraPool
? '原锁耗用 ' +
Model.grams(cost.originalUsedMg) +
'g,料费 ¥' +
Model.yuan(cost.originalUsedCost) +
';补重 ' +
views.materialSourceSegmentsText(cost.extraPool.materialSources) +
views.materialSourceSegmentsText(cost.extraPool.materialSources ?? []) +
';合计 ¥' +
Model.yuan(cost.materialCost)
: cost
@@ -37,7 +63,7 @@ export function DeliveryFields({ views, state, item, line, index, stock, cost, q
cost && stock.original_stock && line.pocket
? `${pool ? '原锁金料已在料池预留,不重复入库;' : stock.original_stock === 'receive' ? '原锁 ' + Model.grams(item.locked_mg) + 'g 先入库;' : '原锁金料此前已入库;'}${cost.extraMg ? (extraPool ? '补重从交付当日料池耗用,不重复入库;' : stock.extra_stock === 'receive' ? '补重 ' + Model.grams(cost.extraMg) + 'g 先入库;' : stock.extra_stock === 'stocked' ? '补重金料此前已入库;' : '请选择补重金料是否已入库;') : ''}从「${Model.pocketLabel(state, line.pocket)}」出库 ${Model.grams(cost.finalMg)}g${count ? ' / ' + (Number(line.stockCount) ? line.stockCount + '对' : '未记录对数') : ''}。${cost.leftoverMg ? (pool ? '少重 ' + Model.grams(cost.leftoverMg) + 'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。' : '余料 ' + Model.grams(cost.leftoverMg) + 'g 留在该货盘,按原进货价计成本,不重复入库。') : ''}`
: '选择本件实际货盘和金料入库情况后,显示库存动作。';
const sources = [
const sources: [string, string][] = [
['', '请选择'],
['receive', '尚未记入,交付时先入库'],
['stocked', '此前已记入,只出库'],
@@ -376,8 +402,18 @@ export function DeliveryFields({ views, state, item, line, index, stock, cost, q
</section>
);
}
export function FeeFields({ state, form, update, cardFee }) {
const edit = (i, key, v) => update(Model.editFeeRow(form, i, key, v));
export function FeeFields({
state,
form,
update,
cardFee,
}: {
state: LedgerState;
form: OrderForm;
update(form: OrderForm): void;
cardFee: number;
}) {
const edit = (i: number, key: 'amount' | 'payer' | 'note', v: string) => update(Model.editFeeRow(form, i, key, v));
return (
<section className="panel internal">
<div className="panel-title">
@@ -1,3 +1,8 @@
import { savedCreate } from './draftInput';
import type { FormEvent } from 'react';
import type { LedgerState, SessionInfo } from '../../shared';
import type { LockPayment } from './formParts';
import type { InputLine, LockEdit, LockProps, LockViews, PreviewRow, SaveLock, InputMaterial } from './types';
import { useEffect, useState } from 'react';
import { Model, Calc } from '../../shared';
import { navigate } from '../../lib/router';
@@ -20,7 +25,19 @@ import {
} from './formParts';
import { useLockPool } from './useLockPool';
function PoolQuote({ q, error, date, member, state }) {
function PoolQuote({
q,
error,
date,
member,
state,
}: {
q?: PreviewRow;
error: string;
date: string;
member: string;
state: LedgerState;
}) {
const grams = Model.grams,
name = Model.memberName(state, member),
balance = q?.balance;
@@ -47,9 +64,9 @@ function PoolQuote({ q, error, date, member, state }) {
'g。'
: date +
' 料池 ' +
grams(q.totalMg) +
grams(Number(q.totalMg)) +
'g,已用/预留 ' +
grams(q.usedMg) +
grams(Number(q.usedMg)) +
'g,可用 ' +
grams(q.remainingMg) +
'g;本行预留 ' +
@@ -77,7 +94,9 @@ function PoolQuote({ q, error, date, member, state }) {
{q.materialSources.map((s, i) => (
<div key={i}>
<strong>
{s.kind === 'personal_recovery' ? Model.memberName(state, s.member) + '个人回收料' : '公共料'}
{s.kind === 'personal_recovery'
? Model.memberName(state, s.member ?? '') + '个人回收料'
: '公共料'}
</strong>
<span>{grams(s.quantity)}g</span>
<b>{s.amount == null ? '料费待补' : '¥' + Model.yuan(s.amount)}</b>
@@ -94,7 +113,7 @@ function PoolQuote({ q, error, date, member, state }) {
</>
);
}
function lineInput(src = {}) {
function lineInput(src: InputLine = {}) {
const material = src.material || {},
manual = material.manual || material;
return {
@@ -114,7 +133,7 @@ function lineInput(src = {}) {
verified: !!manual.verified,
};
}
function packLine(r, date, quote, draft) {
function packLine(r: ReturnType<typeof lineInput>, date: string, quote: PreviewRow | undefined, draft: boolean) {
const manual = { rate: r.rate, payer: r.payer, verified: r.verified };
return {
...(r.lineId ? { lineId: r.lineId } : {}),
@@ -128,31 +147,39 @@ function packLine(r, date, quote, draft) {
laborMode: r.laborMode,
pieces: r.pieces,
charges: saleCharges(r.charges),
material:
r.source === 'pool'
? { source: 'pool', poolId: date, revision: quote?.revision || '', ...(draft ? { manual } : {}) }
: manual,
material: (r.source === 'pool'
? { source: 'pool', poolId: date, revision: quote?.revision || '', ...(draft ? { manual } : {}) }
: manual) satisfies InputMaterial,
};
}
function initial(state, session, edit, key) {
const saved = readDraft(key),
function initial(state: LedgerState, session: SessionInfo, edit: LockEdit | null, key: string) {
const saved = readDraft(key, savedCreate),
d = edit ? saved?.inputs || edit.inputs : saved || {};
const member = d.member || Model.currentMember(state);
return {
date: d.date || state.today,
member,
customer: d.customer || '',
salesperson: d.salesperson || (edit ? session.user.name : Model.defaultSalesperson(state, session)),
salesperson: d.salesperson || (edit ? state.user.name : Model.defaultSalesperson(state, session)),
note: d.note || '',
discount: d.discount ?? '0',
payment: initialPayment(state, d.payment, member),
lines: (d.lines?.length ? d.lines : [{ ...d.line, material: d.material }]).map(lineInput),
reason: edit ? saved?.reason || '' : '',
revision: edit ? (saved?.revision ?? edit.revision) : undefined,
conflicted: edit && saved && saved.revision !== edit.revision,
conflicted: !!(edit && saved && saved.revision !== edit.revision),
};
}
export function LockCreate({ client, state, session, views, edit, save, blocked, reset }) {
export function LockCreate({
client,
state,
session,
views,
edit,
save,
blocked,
reset,
}: LockProps & { views: LockViews; edit: LockEdit | null; save: SaveLock; blocked: boolean; reset: () => void }) {
const key = edit
? 'mm-price-lock-edit-' + state.user.id + '-' + edit.lock.id
: 'mm-price-lock-draft-' + state.user.id;
@@ -166,7 +193,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
: [];
});
const quote = useLockPool({ client, state, views, date: d.date, member: d.member, entries, editId: edit?.lock.id });
function pack(draft) {
function pack(draft: boolean) {
return {
...(Model.teamMode(state) ? { member: d.member } : {}),
date: d.date,
@@ -191,11 +218,12 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
useEffect(() => {
localStorage.setItem(key, stored);
}, [key, stored]);
const update = changes => {
const update = (changes: Partial<typeof d>) => {
set(prev => ({ ...prev, ...changes }));
setVerified(false);
};
const line = (index, changes) => update({ lines: d.lines.map((r, i) => (index === i ? { ...r, ...changes } : r)) });
const line = (index: number, changes: Partial<ReturnType<typeof lineInput>>) =>
update({ lines: d.lines.map((r, i) => (index === i ? { ...r, ...changes } : r)) });
const approval =
edit && state.user.role === 'assistant' && (edit.requiresApproval !== false || d.date !== state.today);
function add() {
@@ -205,7 +233,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
}
update({ lines: [...d.lines, lineInput()] });
}
function remove(i) {
function remove(i: number) {
if (d.lines.length <= 1) {
setError('请至少保留一件锁价商品。');
return;
@@ -219,7 +247,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
'yuan',
),
).result;
async function submit(event) {
async function submit(event: FormEvent) {
event.preventDefault();
setError('');
try {
@@ -229,7 +257,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
if (Calc.isSilver(r.name)) throw new Error('锁价仅支持按克黄金,银饰请直接开单。');
views.lockQuantityMg(r.quantity);
if (Calc.cents(r.goldPrice) <= 0) throw new Error('销售金价须大于0。');
if (r.material.source === 'pool') {
if ('source' in r.material) {
if (d.date !== state.today && (!edit || d.date !== edit.lock.date))
throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
const q = quote.rows.find(q => q.lineIndex === i);
@@ -267,14 +295,14 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
}
await save(url, input);
} catch (err) {
if (edit && err.status === 409) {
if (edit && err instanceof Error && 'status' in err && err.status === 409) {
set(prev => ({ ...prev, conflicted: true }));
setVerified(false);
}
setError(err.message);
setError(err instanceof Error ? err.message : String(err));
}
}
const pay = payment => update({ payment }),
const pay = (payment: LockPayment) => update({ payment }),
leave = () => navigate('price-locks');
return (
<>
@@ -351,7 +379,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
</section>
<div id="lock-create-lines">
{d.lines.map((r, i) => {
const set = (key, v) => line(i, { [key]: v }),
const set = <K extends keyof typeof r>(key: K, v: (typeof r)[K]) => line(i, { [key]: v }),
pooled = r.source === 'pool',
q = quote.rows.find(v => v.lineIndex === i),
sale = safeEstimate(() => Calc.sale(packLine(r, d.date, q, false)).sale).result,
@@ -499,7 +527,7 @@ export function LockCreate({ client, state, session, views, edit, save, blocked,
.map(
s =>
(s.kind === 'personal_recovery'
? Model.memberName(state, s.member) + '个人回收料'
? Model.memberName(state, s.member ?? '') + '个人回收料'
: '公共料') +
' ' +
(s.averageRate == null ? '待补' : (s.averageRate / 100).toFixed(2)),
@@ -1,3 +1,9 @@
import { savedDelivery } from './draftInput';
import type { FormEvent } from 'react';
import type { OrderForm, SyncContext } from '../../shared';
import type { LockRecord, LockProps, LockViews, SaveLock, DeliveryCost } from './types';
import type { LockPayment } from './formParts';
import type { DeliveryForm, DeliveryLine, SavedLine } from './deliveryTypes';
import { useEffect, useState } from 'react';
import { Model, Calc, Cards } from '../../shared';
import { navigate } from '../../lib/router';
@@ -18,11 +24,13 @@ import { DeliveryFields, FeeFields } from './DeliveryFields';
import { useLockPool } from './useLockPool';
const uuid = () => crypto.randomUUID();
function initialize(lock, views, ctx, key) {
const stored = readDraft(key),
function initialize(lock: LockRecord, views: LockViews, ctx: SyncContext, key: string): DeliveryForm {
const stored = readDraft(key, savedDelivery),
d = stored?.revision === lock.revision ? stored : {},
items = views.priceLockLines(lock),
rows = items.map(item => d.lines?.find(r => r.lineId === item.id) || (items.length === 1 && d.line ? d : {}));
rows: SavedLine[] = items.map(
item => d.lines?.find(r => r.lineId === item.id) || (items.length === 1 && d.line ? d : {}),
);
const owner = Model.teamMode(ctx.st) ? Model.currentMember(ctx.st) : 'assistant',
member = lock.member || owner;
const lines = rows.map(
@@ -71,7 +79,15 @@ function initialize(lock, views, ctx, key) {
verified: false,
};
}
export function LockDelivery({ client, state, session, views, lock, save, blocked }) {
export function LockDelivery({
client,
state,
session,
views,
lock,
save,
blocked,
}: LockProps & { views: LockViews; lock: LockRecord; save: SaveLock; blocked: boolean }) {
const key = 'mm-price-lock-delivery-' + state.user.id + '-' + lock.id,
ctx = { st: state, session, uuid };
const [d, set] = useState(() => initialize(lock, views, ctx, key)),
@@ -91,7 +107,7 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
delivery: true,
});
const costs = d.form.lines.map((r, i) =>
safeEstimate(() => {
safeEstimate<DeliveryCost>(() => {
const stock = d.stock[i],
pooled = stock.extra_source === 'pool' && views.lockQuantityMg(r.quantity) > items[i].locked_mg;
const c = views.priceLockDeliveryCost(items[i], r.quantity, pooled ? '1' : stock.extra_rate);
@@ -108,17 +124,18 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
...d.form,
fees_date: d.form.date,
lines: d.form.lines.map((r, i) => {
const amount = costs[i].result ? (costs[i].result.materialCost / 100).toFixed(2) : '';
const amount = costs[i].result ? (costs[i].result!.materialCost / 100).toFixed(2) : '';
return {
...r,
purchase: { ...r.purchase, materialMode: 'total', material: amount, total: amount, originalTotal: amount },
purchase: { ...r.purchase!, materialMode: 'total', material: amount, total: amount, originalTotal: amount },
};
}),
},
ctx,
);
const form = calculated.form,
lines = calculated.draft.lines,
// 交付商品已通过普通开单模型同步,沿用其收集出的分项进货成本。
lines = calculated.draft.lines as (DeliveryLine & Record<string, unknown>)[],
order = safeEstimate(() =>
Calc.orderTotal(
lines.map(r => Calc.sale(r).sale),
@@ -131,7 +148,10 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
amount: difference == null ? '' : (Math.abs(difference) / 100).toFixed(2),
...paymentPayload(d.payment),
},
card = d.payment.method === '信用卡' && difference > 0 ? Cards.amount(difference, Model.creditCardRate(state)) : 0;
card =
d.payment.method === '信用卡' && difference !== null && difference > 0
? Cards.amount(difference, Model.creditCardRate(state))
: 0;
const deliveryLines = lines.map((r, i) => {
const s = d.stock[i],
pool = items[i].material_source === 'pool',
@@ -170,9 +190,9 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
useEffect(() => {
localStorage.setItem(key, snapshot);
}, [key, snapshot]);
const setForm = next => set({ ...d, form: next }),
payChanged = payment => set({ ...d, payment });
async function submit(e) {
const setForm = (next: OrderForm) => set({ ...d, form: next }),
payChanged = (payment: LockPayment) => set({ ...d, payment });
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setError('');
try {
@@ -184,10 +204,10 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
);
const actual = deliveryLines.map((r, i) => {
const counts = Model.pocketCountsEnabled(state, r.inventory.pocket),
extra = costs[i].result.extraMg;
extra = costs[i].result!.extraMg;
if (!Model.activePocketKeys(state).includes(r.pocket) || !['receive', 'stocked'].includes(r.inventory.original))
throw new Error('请选择商品 ' + (i + 1) + ' 的实际出库货盘,并确认原锁金料是否已入库。');
if (counts && !['receive', 'stocked'].includes(r.inventory.countSource))
if (counts && !['receive', 'stocked'].includes(r.inventory.countSource ?? ''))
throw new Error('请选择商品 ' + (i + 1) + ' 的成品来源。');
if (
extra &&
@@ -199,7 +219,7 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
throw new Error('请填写商品 ' + (i + 1) + ' 的补重料价、付款人、是否已入库,并确认实际付款。');
return {
quantity: r.quantity,
...(counts ? { stockCount: Model.stockCountValue(r.stockCount) } : {}),
...(counts ? { stockCount: Model.stockCountValue(String(r.stockCount ?? '')) } : {}),
laborRate: r.laborRate,
laborMode: r.laborMode,
pieces: r.pieces,
@@ -234,10 +254,11 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
};
await save('/api/price-locks/' + encodeURIComponent(lock.id) + '/deliver', input);
} catch (err) {
setError(err.message);
setError((err as Error).message);
}
}
const sum = k => costs.reduce((n, c) => n + (c.result?.[k] || 0), 0);
const sum = (k: 'originalUsedMg' | 'originalUsedCost' | 'extraMg' | 'extraCost' | 'leftoverMg' | 'leftoverCost') =>
costs.reduce((n, c) => n + (c.result?.[k] || 0), 0);
return (
<>
<Heading
@@ -390,8 +411,8 @@ export function LockDelivery({ client, state, session, views, lock, save, blocke
change={payChanged}
required={!!difference}
disabled={difference === 0}
methodLabel={difference < 0 ? '退款方式' : '补收款方式'}
recipientLabel={difference < 0 ? '退款账户归属' : '收款人'}
methodLabel={difference !== null && difference < 0 ? '退款方式' : '补收款方式'}
recipientLabel={difference !== null && difference < 0 ? '退款账户归属' : '收款人'}
/>
</div>
<Check
-11
View File
@@ -1,11 +0,0 @@
import { type ComponentType } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState, SessionInfo } from '../../shared';
export const LockPage: ComponentType<{
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
route: 'price-locks' | 'price-lock-create';
onState?: (state: LedgerState) => void;
onRecoverOther?: () => Promise<void>;
}>;
@@ -1,4 +1,9 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent, type ReactNode } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState } from '../../shared';
import { loadState } from '../../lib/session';
import { errorText } from '../Settings/settingsModel';
import type { LockRecord, LockEdit, LockChange, LockProps, ChangeListRow } from './types';
import { navigate, searchParam, useLocation } from '../../lib/router';
import { useClientSnapshot } from '../../lib/useClient';
import { lockViews } from './lockViews';
@@ -6,16 +11,38 @@ import { Act, Heading } from './formParts';
import { LockCreate } from './LockCreate';
import { LockDelivery } from './LockDelivery';
function readDraftFilters(key) {
type DialogKind = 'changes' | 'review' | 'cancel' | 'detail';
type LocalDialog = { kind: DialogKind; id?: string };
type Resource =
| { kind: 'lock'; value: LockRecord }
| { kind: 'changes'; value: { rows: ChangeListRow[] } }
| { kind: 'review'; value: LockChange }
| { kind: 'edit'; value: LockEdit }
| { kind: 'cancel'; value: LockEdit & { lock: LockRecord } };
type PageProps = LockProps & {
route: 'price-locks' | 'price-lock-create';
onState?: (state: LedgerState) => void;
onRecoverOther?: () => Promise<void>;
};
function object(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function readDraftFilters(key: string): Record<string, unknown> {
try {
return JSON.parse(sessionStorage.getItem(key) || '{}') || {};
const saved: unknown = JSON.parse(sessionStorage.getItem(key) || '{}');
return object(saved) ? saved : {};
} catch {
return {};
}
}
function useRead(client, url, seq, validate) {
function useRead<T>(
client: LedgerClient,
url: string,
seq: number,
validate: (value: unknown) => T,
): { result?: T; error?: string } {
const key = [client.user, url, seq].join('|'),
[s, set] = useState(null);
[s, set] = useState<{ key: string; result?: T; error?: string } | null>(null);
useEffect(() => {
if (!url) return;
let active = true;
@@ -26,7 +53,7 @@ function useRead(client, url, seq, validate) {
if (active) set({ key, result });
})
.catch(e => {
if (active) set({ key, error: e.message });
if (active) set({ key, error: errorText(e) });
});
return () => {
active = false;
@@ -34,15 +61,89 @@ function useRead(client, url, seq, validate) {
}, [client, url, key, validate]);
return s?.key === key ? s : {};
}
const rows = r => {
if (!Array.isArray(r?.rows)) throw new Error('记录未完整返回,请重试。');
return r;
};
const modalId = k => (['changes', 'review'].includes(k) ? 'price-lock-changes-dialog' : 'price-lock-dialog');
function Modal({ children, kind, close }) {
const ref = useRef(null);
function lockLine(value: unknown) {
if (!object(value) || !object(value.line)) return false;
const line = value.line;
return (
typeof line.name === 'string' &&
Number.isSafeInteger(line.sale) &&
Number.isSafeInteger(line.laborRate) &&
(line.charges == null ||
(Array.isArray(line.charges) && line.charges.every(c => object(c) && Number.isSafeInteger(c.amount)))) &&
Number.isSafeInteger(value.locked_mg) &&
Number.isSafeInteger(value.sell_rate) &&
(value.buy_rate === null || Number.isSafeInteger(value.buy_rate)) &&
(value.material_amount === null || Number.isSafeInteger(value.material_amount))
);
}
function lockRecord(r: unknown): r is LockRecord {
return (
object(r) &&
typeof r.id === 'string' &&
typeof r.date === 'string' &&
typeof r.customer === 'string' &&
typeof r.number === 'string' &&
typeof r.salesperson === 'string' &&
(r.status === 'pending' || r.status === 'cancelled' || r.status === 'delivered') &&
Number.isSafeInteger(r.revision) &&
Number.isSafeInteger(r.netReceived) &&
Number.isSafeInteger(r.discount) &&
lockLine(r) &&
(r.lines == null || (Array.isArray(r.lines) && r.lines.every(lockLine)))
);
}
function changeRow(r: unknown): r is ChangeListRow {
return (
object(r) &&
typeof (r.requestId || r.id) === 'string' &&
(r.action === 'edit' || r.action === 'cancel') &&
(r.status === 'pending' || r.status === 'approved' || r.status === 'rejected') &&
typeof r.created === 'string'
);
}
function editContext(r: unknown, target: string | undefined, editing: boolean): r is LockEdit {
return (
object(r) &&
r.eligible === true &&
object(r.lock) &&
typeof r.lock.id === 'string' &&
typeof r.lock.date === 'string' &&
typeof r.lock.number === 'string' &&
(r.lock.customer === undefined || typeof r.lock.customer === 'string') &&
r.lock.id === target &&
r.lock.status === 'pending' &&
Number.isSafeInteger(r.revision) &&
typeof r.requiresApproval === 'boolean' &&
object(r.inputs) &&
(!editing || (Array.isArray(r.inputs.lines) && r.inputs.lines.length > 0))
);
}
function changeDetail(r: unknown, id: string | undefined): r is LockChange {
return (
object(r) &&
(r.requestId || r.id) === id &&
(r.action === 'edit' || r.action === 'cancel') &&
Array.isArray(r.changes) &&
lockRecord(r.before) &&
changeRow(r) &&
Number.isSafeInteger(r.revision)
);
}
function readLocks(r: unknown) {
if (!object(r) || !Array.isArray(r.rows) || !r.rows.every(lockRecord)) throw new Error('记录未完整返回,请重试。');
return { rows: r.rows };
}
function readChanges(r: unknown) {
if (!object(r) || !Array.isArray(r.rows) || !r.rows.every(changeRow)) throw new Error('记录未完整返回,请重试。');
return { rows: r.rows };
}
const modalId = (k: DialogKind) =>
['changes', 'review'].includes(k) ? 'price-lock-changes-dialog' : 'price-lock-dialog';
function Modal({ children, kind, close }: { children: ReactNode; kind: DialogKind; close: () => void }) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
const root = ref.current;
if (!root) return;
root.showModal();
return () => root.close();
}, []);
@@ -59,8 +160,8 @@ function Modal({ children, kind, close }) {
</dialog>
);
}
const previousFilters = new WeakMap();
export function LockPage({ client, state, session, route, onState, onRecoverOther }) {
const previousFilters = new WeakMap<LedgerClient, { user: string; list: string; changes: string }>();
export function LockPage({ client, state, session, route, onState, onRecoverOther }: PageProps) {
useClientSnapshot(client);
const location = useLocation();
const create = route === 'price-lock-create',
@@ -71,7 +172,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
const [previousLocation, setPreviousLocation] = useState(location);
const [seq, setSeq] = useState(0),
[listFilter, setFilter] = useState(() => (remembered?.user === state.user.id ? remembered.list : 'pending')),
[local, setLocal] = useState(null),
[local, setLocal] = useState<LocalDialog | null>(null),
[changeFilter, setChangeFilter] = useState(() =>
remembered?.user === state.user.id ? remembered.changes : 'pending',
),
@@ -88,42 +189,33 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
const formPending = !!client.pending(),
blocked = client.busy || formPending,
views = useMemo(() => lockViews(state, session), [state, session]);
const dialog = local || (!deliver && detail ? { kind: 'detail', id: detail } : null),
const dialog: LocalDialog | null = local || (!deliver && detail ? { kind: 'detail', id: detail } : null),
kind = dialog?.kind,
id = dialog?.id;
const target = editId || deliver || id,
readLock = r => {
if (r?.id !== target) throw new Error('锁价单资料未完整返回,请重新读取。');
return r;
};
const target = editId || deliver || id;
const validator = useMemo(
() => r => {
if (editId || kind === 'cancel') {
if (
r?.eligible !== true ||
r.lock?.id !== target ||
r.lock?.status !== 'pending' ||
!Number.isSafeInteger(r.revision) ||
typeof r.requiresApproval !== 'boolean' ||
(editId && (!Array.isArray(r.inputs?.lines) || !r.inputs.lines.length))
)
throw new Error(r.reason || '锁价修改资料未完整返回,请重新读取。');
return r;
}
if (kind === 'review') {
if (
(r.requestId || r.id) !== id ||
!['edit', 'cancel'].includes(r.action) ||
!Array.isArray(r.changes) ||
!r.before
)
throw new Error('锁价申请详情未完整返回,请重新读取。');
return r;
}
if (kind === 'changes') return rows(r);
return readLock(r);
},
[target, editId, kind, id],
() =>
(r: unknown): Resource => {
if (editId || kind === 'cancel') {
if (!editContext(r, target, !!editId))
throw new Error(
(object(r) && typeof r.reason === 'string' && r.reason) || '锁价修改资料未完整返回,请重新读取。',
);
if (kind === 'cancel' && !editId) {
if (!lockRecord(r.lock)) throw new Error('锁价单资料未完整返回,请重新读取。');
return { kind: 'cancel', value: { ...r, lock: r.lock } };
}
return { kind: 'edit', value: r };
}
if (kind === 'review') {
if (!changeDetail(r, id)) throw new Error('锁价申请详情未完整返回,请重新读取。');
return { kind: 'review', value: r };
}
if (kind === 'changes') return { kind: 'changes', value: readChanges(r) };
if (!lockRecord(r) || r.id !== target) throw new Error('锁价单资料未完整返回,请重新读取。');
return { kind: 'lock', value: r };
},
[id, target, kind, editId],
);
const lockUrl = '/api/price-locks/' + encodeURIComponent(target || ''),
detailUrl =
@@ -132,12 +224,18 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
: kind === 'changes'
? '/api/price-lock-changes?status=' + changeFilter
: kind === 'review'
? '/api/price-lock-changes/' + encodeURIComponent(id)
? '/api/price-lock-changes/' + encodeURIComponent(id || '')
: deliver || detail || kind === 'detail'
? lockUrl
: '';
const resource = useRead(client, detailUrl, seq, validator),
list = useRead(client, !create && !deliver ? '/api/price-locks?status=' + listFilter : '', seq, rows);
list = useRead(client, !create && !deliver ? '/api/price-locks?status=' + listFilter : '', seq, readLocks);
const result = resource.result,
edit = result?.kind === 'edit' ? result.value : null,
cancel = result?.kind === 'cancel' ? result.value : null,
lock = result?.kind === 'lock' ? result.value : null,
review = result?.kind === 'review' ? result.value : null,
changes = result?.kind === 'changes' ? result.value : null;
const reload = () => {
setError('');
setStale(false);
@@ -159,11 +257,12 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
reset();
if (detail) navigate('price-locks');
};
function action(e) {
const b = e.target.closest('button[data-action]');
function action(e: MouseEvent<HTMLDivElement>) {
if (!(e.target instanceof Element)) return;
const b = e.target.closest<HTMLButtonElement>('button[data-action]');
if (!b || !e.currentTarget.contains(b)) return;
const k = b.dataset.action,
id = b.dataset.id;
const k = b.dataset.action || '',
id = b.dataset.id || '';
if (['edit-price-lock', 'cancel-price-lock'].includes(k) && blocked) {
setError('请先恢复上次未确认的操作,再修改或作废锁价单。');
return;
@@ -206,16 +305,24 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
close();
break;
case 'price-lock-changes-filter':
previousFilters.set(client, { user: state.user.id, list: listFilter, changes: b.dataset.status });
setChangeFilter(b.dataset.status);
previousFilters.set(client, {
user: state.user.id,
list: listFilter,
changes: b.dataset.status || changeFilter,
});
setChangeFilter(b.dataset.status || changeFilter);
reload();
break;
case 'price-lock-changes-reload':
reload();
break;
case 'price-lock-list-status':
previousFilters.set(client, { user: state.user.id, list: b.dataset.status, changes: changeFilter });
setFilter(b.dataset.status);
previousFilters.set(client, {
user: state.user.id,
list: b.dataset.status || listFilter,
changes: changeFilter,
});
setFilter(b.dataset.status || listFilter);
reload();
break;
case 'refresh-price-locks':
@@ -227,19 +334,26 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
break;
}
}
async function confirmed(url, data, result) {
async function confirmed(url: string, data: unknown, result: unknown) {
if (!object(result) || !object(data)) throw new Error('锁价操作回执未完整返回,请重新读取后核对。');
const request = object(result.request) ? result.request : {},
saved = object(result.lock) ? result.lock : {};
const suffix = url.split('/').at(-1),
lockId =
result.price_lock_id ||
result.request?.price_lock_id ||
result.lock?.id ||
request.price_lock_id ||
saved.id ||
(url === '/api/price-locks' ? result.id : url.split('/')[3]);
if (typeof lockId !== 'string' || !lockId) throw new Error('锁价操作回执未完整返回,请重新读取后核对。');
if (url === '/api/price-locks') {
localStorage.removeItem('mm-price-lock-draft-' + state.user.id);
reset();
navigate('price-locks', { search: '?lock=' + encodeURIComponent(lockId) });
setMessage('锁价已保存到待交付,尚未出入库、不计利润');
} else if (suffix === 'deliver') {
const orderId = result.order_id || result.id;
if (typeof orderId !== 'string' || !orderId || typeof data.date !== 'string')
throw new Error('交付回执未完整返回,请重新读取后核对。');
localStorage.removeItem('mm-price-lock-delivery-' + state.user.id + '-' + url.split('/')[3]);
const filterKey = 'mm-order-book-' + state.user.id;
const filters = readDraftFilters(filterKey);
@@ -247,7 +361,6 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
filterKey,
JSON.stringify({ ...filters, mode: 'date', date: data.date, q: '', status: '' }),
);
const orderId = result.order_id || result.id;
navigate('orders', { search: '?order=' + encodeURIComponent(orderId) });
} else {
setSavedLockId(lockId);
@@ -269,13 +382,13 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
}
reload();
try {
const fresh = await client.api('/api/state');
const fresh = await loadState(client);
if (client.user === fresh.user.id) onState?.(fresh);
} catch {
setMessage('操作已保存,最新记录暂未读到。请重新读取,不要重复提交。');
}
}
async function save(url, data) {
async function save(url: string, data: Record<string, unknown>) {
const result = await client.mutate(url, data);
await confirmed(url, data, result);
}
@@ -287,21 +400,23 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
const r = await client.retryPending();
if (r) await confirmed(r.job.url, r.job.data, r.result);
} catch (err) {
setError(err.message);
if (err.status === 409) setStale(true);
setError(errorText(err));
if (err instanceof Error && 'status' in err && err.status === 409) setStale(true);
}
}
async function modalSubmit(e) {
async function modalSubmit(e: FormEvent<HTMLDivElement>) {
const form = e.target;
if (!['price-lock-cancel-form', 'price-lock-review-form'].includes(form.id)) return;
if (!(form instanceof HTMLFormElement) || !['price-lock-cancel-form', 'price-lock-review-form'].includes(form.id))
return;
e.preventDefault();
if (blocked || stale) return;
setError('');
try {
const r = resource.result,
values = new FormData(form),
const values = new FormData(form),
verified = values.get('verified') === 'on';
if (kind === 'cancel') {
const r = cancel;
if (!r) throw new Error('锁价修改资料未完整返回,请重新读取。');
const reason = String(values.get('reason') || '').trim();
if (!reason) throw new Error('请填写作废原因。');
if (!verified) throw new Error('请核实录错单据并勾选整单作废。');
@@ -314,9 +429,11 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
...(approval ? { action: 'cancel' } : {}),
});
} else {
const decision = e.nativeEvent.submitter?.value,
const r = review;
const submitter = e.nativeEvent instanceof SubmitEvent ? e.nativeEvent.submitter : null;
const decision = submitter instanceof HTMLButtonElement ? submitter.value : '',
note = String(values.get('review_note') || '').trim();
if (state.user.role !== 'owner' || r.status !== 'pending' || !['approve', 'reject'].includes(decision))
if (!r || state.user.role !== 'owner' || r.status !== 'pending' || !['approve', 'reject'].includes(decision))
throw new Error('请重新读取待复核申请。');
if (decision === 'approve' && (r.stale || !verified))
throw new Error(
@@ -331,8 +448,8 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
);
}
} catch (err) {
setError(err.message);
if (err.status === 409) setStale(true);
setError(errorText(err));
if (err instanceof Error && 'status' in err && err.status === 409) setStale(true);
}
}
const waiting = resource.error ? (
@@ -376,7 +493,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
</p>
)}
{create ? (
editId && !resource.result ? (
editId && !edit ? (
waiting
) : (
<LockCreate
@@ -385,22 +502,22 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
state={state}
session={session}
views={views}
edit={editId ? resource.result : null}
edit={editId ? edit : null}
save={save}
blocked={blocked}
reset={reload}
/>
)
) : deliver ? (
resource.result ? (
resource.result.status === 'pending' ? (
lock ? (
lock.status === 'pending' ? (
<LockDelivery
key={deliver}
client={client}
state={state}
session={session}
views={views}
lock={resource.result}
lock={lock}
save={save}
blocked={blocked}
/>
@@ -409,9 +526,9 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
<Heading kicker="LOCK DELIVERED" title="这张锁价单已交付" desc="请查看已生成的销售单,不要重复交付。">
<Act name="refresh-price-locks">返回待交付</Act>
</Heading>
{views.priceLockFacts(resource.result)}
{resource.result.final_order_id && (
<Act name="open-lock-order" data-id={resource.result.final_order_id}>
{views.priceLockFacts(lock)}
{lock.final_order_id && (
<Act name="open-lock-order" data-id={lock.final_order_id}>
查看销售单
</Act>
)}
@@ -465,7 +582,7 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
</>
)}
{dialog && !deliver && !create && (
<Modal key={kind + '-' + id} kind={kind} close={close}>
<Modal key={kind + '-' + id} kind={dialog.kind} close={close}>
{kind === 'changes' ? (
<>
<button type="button" className="dialog-close" data-action="price-lock-changes-close" aria-label="关闭">
@@ -484,28 +601,27 @@ export function LockPage({ client, state, session, route, onState, onRecoverOthe
</Act>
))}
</div>
<div id="price-lock-changes-content">
{resource.result ? views.changeRows(resource.result) : waiting}
</div>
<div id="price-lock-changes-content">{changes ? views.changeRows(changes) : waiting}</div>
</>
) : kind === 'detail' ? (
<>
<button type="button" className="dialog-close" data-action="close-price-lock" aria-label="关闭锁价记录">
×
</button>
<div id="price-lock-detail">{resource.result ? views.detailView(resource.result) : waiting}</div>
<div id="price-lock-detail">{lock ? views.detailView(lock) : waiting}</div>
</>
) : resource.result ? (
) : (kind === 'cancel' ? cancel : review) ? (
<fieldset style={{ display: 'contents' }} disabled={blocked || stale}>
{kind === 'cancel'
{kind === 'cancel' && cancel
? views.cancelView(
resource.result,
cancel,
state.user.role === 'assistant' &&
(resource.result.requiresApproval !== false || resource.result.inputs.date !== state.today),
(cancel.requiresApproval !== false || cancel.inputs.date !== state.today),
)
: views.changeDetail(
resource.result,
state.user.role === 'owner' && resource.result.status === 'pending' && !resource.result.stale,
: review &&
views.changeDetail(
review,
state.user.role === 'owner' && review.status === 'pending' && !review.stale,
)}
</fieldset>
) : (
@@ -0,0 +1,51 @@
import type { LineState, OrderForm } from '../../shared';
import type { LockPayment, SavedPayment } from './formParts';
// 锁价交付在本地保存可提交的商品行。早期单件草稿将商品放在顶层的 line。
export interface DeliveryLine {
quantity: string;
pocket: string;
laborRate: string;
laborMode: string;
pieces: string;
stockCount?: string | null;
charges: { name: string; amount: string }[];
payer: string;
costParts: { labor: string; accessories: string; other: string };
costLabor: { mode: string; rate?: string; amount?: string };
costPayers: Record<string, string>;
}
export interface SavedLine extends Partial<DeliveryLine> {
lineId?: string;
line?: Partial<DeliveryLine>;
inventory?: { original?: string; countSource?: string; extra?: string };
extraMaterial?: { source?: string; rate?: string; payer?: string; verified?: boolean };
}
export interface DeliveryDraft extends SavedLine {
revision?: number;
lines?: SavedLine[];
date?: string;
customer_type?: string;
note?: string;
discount?: string;
fee_items?: Record<string, unknown>[];
settlement?: SavedPayment;
}
export interface StockSelection {
original_stock: string;
count_source: string;
extra_source: string;
extra_rate: string;
extra_payer: string;
extra_stock: string;
extra_verified: boolean;
}
export interface DeliveryForm {
form: OrderForm;
stock: StockSelection[];
customer_type: string;
note: string;
payment: LockPayment;
verified: boolean;
}
export type EditLine = (line: LineState) => void;
@@ -0,0 +1,73 @@
import type { LockCreateDraft, InputLine } from './types';
import type { SavedPayment } from './formParts';
import type { DeliveryDraft, SavedLine } from './deliveryTypes';
const record = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === 'object' && !Array.isArray(value);
const optional = (value: unknown, predicate: (v: unknown) => boolean) => value == null || predicate(value);
const text = (v: unknown) => typeof v === 'string';
const scalar = (v: unknown) => text(v) || typeof v === 'number';
function payment(v: unknown): v is SavedPayment {
return (
record(v) &&
optional(v.account, text) &&
optional(v.credit_card_fee_payer, text) &&
optional(v.amount, scalar) &&
optional(v.verified, x => typeof x === 'boolean')
);
}
function charges(v: unknown) {
return Array.isArray(v) && v.every(row => record(row) && optional(row.name, text) && optional(row.amount, scalar));
}
function createLine(v: unknown): v is InputLine {
return (
record(v) &&
['name', 'code', 'lineId', 'laborMode'].every(k => optional(v[k], text)) &&
['quantity', 'goldPrice', 'laborRate', 'pieces'].every(k => optional(v[k], scalar)) &&
optional(v.charges, charges) &&
optional(v.material, record)
);
}
function createDraft(v: unknown): v is LockCreateDraft {
return (
record(v) &&
['member', 'date', 'customer', 'salesperson', 'note'].every(k => optional(v[k], text)) &&
optional(v.discount, scalar) &&
optional(v.payment, payment) &&
optional(v.line, createLine) &&
optional(v.material, record) &&
optional(v.lines, x => Array.isArray(x) && x.every(createLine))
);
}
export type SavedCreate = LockCreateDraft & { inputs?: LockCreateDraft; reason?: string; revision?: number };
export function savedCreate(v: unknown): v is SavedCreate {
return (
record(v) &&
optional(v.inputs, createDraft) &&
optional(v.revision, Number.isSafeInteger) &&
optional(v.reason, text) &&
createDraft(v)
);
}
function deliveryLine(v: unknown): v is SavedLine {
return (
record(v) &&
optional(v.lineId, text) &&
optional(v.quantity, scalar) &&
optional(v.pocket, text) &&
optional(v.line, record) &&
optional(v.charges, charges) &&
optional(v.inventory, record) &&
optional(v.extraMaterial, record)
);
}
export function savedDelivery(v: unknown): v is DeliveryDraft {
return (
record(v) &&
optional(v.revision, Number.isSafeInteger) &&
optional(v.lines, x => Array.isArray(x) && x.every(deliveryLine)) &&
optional(v.fee_items, x => Array.isArray(x) && x.every(record)) &&
optional(v.settlement, payment) &&
deliveryLine(v)
);
}
@@ -1,6 +1,52 @@
import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from 'react';
import type { ChargeState, LedgerState } from '../../shared';
interface TextField extends Omit<InputHTMLAttributes<HTMLInputElement>, 'name' | 'value'> {
label: ReactNode;
name: string;
value?: string | number | null;
update?: (value: string) => void;
}
type Option = string | readonly [string, string, boolean?];
interface ChoiceProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'value'> {
label: ReactNode;
value?: string | null;
options: readonly Option[];
update?: (value: string) => void;
}
interface CheckProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value'> {
value?: boolean;
update: (v: boolean) => void;
}
export interface LockPayment {
method: string;
recipient: string;
payer: string;
verified: boolean;
amount: string;
}
export interface SavedPayment {
account?: string;
credit_card_fee_payer?: string;
verified?: boolean;
amount?: string;
}
interface PaymentProps {
state: LedgerState;
payment: LockPayment;
change: (p: LockPayment) => void;
}
import { Model, Cards, Calc } from '../../shared';
export function Field({ label, name, value = '', type = 'text', update, hidden = false, children, ...props }) {
export function Field({
label,
name,
value = '',
type = 'text',
update,
hidden = false,
children,
...props
}: TextField) {
return (
<label hidden={hidden}>
{label}
@@ -15,16 +61,16 @@ export function Field({ label, name, value = '', type = 'text', update, hidden =
</label>
);
}
export function Money(props) {
export function Money(props: TextField) {
return <Field type="number" min="0" step="0.01" required {...props} />;
}
export function Choice({ label, name, value, options, update, children, hidden, ...props }) {
export function Choice({ label, name, value, options, update, children, hidden, ...props }: ChoiceProps) {
return (
<label hidden={hidden}>
{label}
<select name={name} value={value ?? ''} {...props} onChange={update ? e => update(e.target.value) : undefined}>
{options.map(v => {
const [k, title, disabled] = Array.isArray(v) ? v : [v, v];
const [k, title, disabled] = typeof v === 'string' ? [v, v] : v;
return (
<option key={k} value={k} disabled={!!disabled}>
{title}
@@ -36,7 +82,7 @@ export function Choice({ label, name, value, options, update, children, hidden,
</label>
);
}
export function Check({ name, value, update, children, hidden, ...props }) {
export function Check({ name, value, update, children, hidden, ...props }: CheckProps) {
return (
<label className="check" hidden={hidden}>
<input type="checkbox" name={name} checked={!!value} onChange={e => update(e.target.checked)} {...props} />
@@ -44,14 +90,24 @@ export function Check({ name, value, update, children, hidden, ...props }) {
</label>
);
}
export function Act({ name, onClick, children, className = '', ...props }) {
export function Act({ name, onClick, children, className = '', ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {
return (
<button type="button" className={className} data-action={name} onClick={onClick} {...props}>
{children}
</button>
);
}
export function Heading({ title, kicker, desc, children }) {
export function Heading({
title,
kicker,
desc,
children,
}: {
title: string;
kicker: string;
desc: string;
children?: ReactNode;
}) {
return (
<div className="page-heading">
<div>
@@ -63,8 +119,18 @@ export function Heading({ title, kicker, desc, children }) {
</div>
);
}
export function Charges({ rows, change, title = '客户附加项目(选填)', restore }) {
const set = (i, charge) => change(rows.map((r, n) => (n === i ? charge : r)));
export function Charges({
rows,
change,
title = '客户附加项目(选填)',
restore,
}: {
rows: ChargeState[];
change: (rows: ChargeState[]) => void;
title?: string;
restore?: (i: number) => void;
}) {
const set = (i: number, charge: ChargeState) => change(rows.map((r, n) => (n === i ? charge : r)));
return (
<div className="sale-charges">
<div className="panel-title">
@@ -128,7 +194,7 @@ export function AccountFields({
recipientLabel = '收款人',
disabled = false,
required = false,
}) {
}: PaymentProps & { methodLabel?: string; recipientLabel?: string; disabled?: boolean; required?: boolean }) {
const card = payment.method === '信用卡';
return (
<>
@@ -159,11 +225,18 @@ export function AccountFields({
</>
);
}
export function CardPreview({ id, state, payment, cents, change, enabled = true }) {
export function CardPreview({
id,
state,
payment,
cents,
change,
enabled = true,
}: PaymentProps & { id: string; cents: number | null; enabled?: boolean }) {
const visible = enabled && payment.method === '信用卡',
rate = Model.creditCardRate(state);
let amount = null;
if (visible && Number.isSafeInteger(cents) && cents >= 0) amount = Cards.amount(cents, rate);
if (visible && cents !== null && Number.isSafeInteger(cents) && cents >= 0) amount = Cards.amount(cents, rate);
return (
<div className="credit-card-preview" id={id} hidden={!visible}>
<div className="credit-card-heading">
@@ -211,28 +284,29 @@ export function CardPreview({ id, state, payment, cents, change, enabled = true
</div>
);
}
export function amountPreview(raw) {
export function amountPreview(raw: string) {
try {
return Calc.cents(raw);
} catch {
return null;
}
}
export function safeEstimate(fn) {
export function safeEstimate<T>(fn: () => T): { result: T; error?: undefined } | { result?: undefined; error: string } {
try {
return { result: fn() };
} catch (error) {
return { error: error.message };
return { error: error instanceof Error ? error.message : String(error) };
}
}
export function readDraft(key) {
export function readDraft<T>(key: string, valid: (v: unknown) => v is T): T | null {
try {
return JSON.parse(localStorage.getItem(key) || 'null');
const value: unknown = JSON.parse(localStorage.getItem(key) || 'null');
return valid(value) ? value : null;
} catch {
return null;
}
}
export function saleCharges(charges) {
export function saleCharges(charges: ChargeState[]) {
return charges.map(r => ({
id: r.id,
nameType: r.type,
@@ -243,7 +317,7 @@ export function saleCharges(charges) {
...(r.costRemoved ? { costRemoved: true } : {}),
}));
}
export function initialPayment(state, p, member) {
export function initialPayment(state: LedgerState, p: SavedPayment | undefined, member: string): LockPayment {
const id = Model.accountIdentity(state, p?.account || '');
return {
method: id?.channel || '微信',
@@ -253,7 +327,7 @@ export function initialPayment(state, p, member) {
amount: p?.amount ?? '',
};
}
export function paymentPayload(payment) {
export function paymentPayload(payment: LockPayment) {
return {
account: Cards.normalizeAccount((payment.method === '信用卡' ? '麦麦' : payment.recipient) + payment.method),
credit_card_fee_payer: payment.payer,
@@ -1,12 +1,32 @@
import type { ReactNode } from 'react';
import type { LedgerState, SessionInfo } from '../../shared';
import type { QuoteRequest, SourceDescription } from '../../lib/materialQuote';
import type { Impact, LockCost, Allocation } from '../MaterialPools/model';
import type {
LockRecord,
LockEdit,
LockChange,
ChangeListRow,
LockCreateDraft,
LockedSource,
ReservedMaterial,
DeliveryCost,
ChangeSnapshot,
} from './types';
import { Children, Fragment } from 'react';
import { describeMaterialSources, validateMaterialQuote as checkMaterialQuote } from '../../lib/materialQuote';
import { Model, Calc as LedgerCalc, Values } from '../../shared';
export function lockViews(state, session) {
const validateMaterialQuote = (result, input) => checkMaterialQuote(result, input, Model.memberKeys(state));
function priceLockSplitMaterialSources(pool, mg) {
function isInputSnapshot(value: LockRecord | LockCreateDraft): value is LockCreateDraft {
const first = value.lines?.[0];
return !!first && !('line' in first);
}
export function lockViews(state: LedgerState, session: SessionInfo) {
const validateMaterialQuote = (result: unknown, input: QuoteRequest) =>
checkMaterialQuote(result, input, Model.memberKeys(state));
function priceLockSplitMaterialSources(pool: ReservedMaterial, mg: number) {
let left = mg;
const taken = [],
rest = [];
const taken: LockedSource[] = [],
rest: LockedSource[] = [];
if (
!Array.isArray(pool.materialSources) ||
pool.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== pool.quantity ||
@@ -15,7 +35,7 @@ export function lockViews(state, session) {
throw new Error('原锁分来源克重或成本未完整读到,请重新读取。');
for (const source of pool.materialSources) {
if (
!['quantity', 'amount', 'basisAmount', 'basisMg', 'prefixMg', 'prefixAmount'].every(
!(['quantity', 'amount', 'basisAmount', 'basisMg', 'prefixMg', 'prefixAmount'] as const).every(
key => Number.isSafeInteger(source[key]) && source[key] >= 0,
) ||
!source.basisMg ||
@@ -102,7 +122,7 @@ export function lockViews(state, session) {
rest,
};
}
function lockQuantityMg(value) {
function lockQuantityMg(value: string) {
const text = String(value ?? '').trim();
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) throw new Error('克重请填写正数,最多3位小数。');
const [whole, part = ''] = text.split('.'),
@@ -110,12 +130,12 @@ export function lockViews(state, session) {
if (!Number.isSafeInteger(mg) || mg <= 0) throw new Error('克重请填写大于0的有效数字。');
return mg;
}
function priceLockDeliveryCost(lock, quantity, extraBuyRate) {
function priceLockDeliveryCost(lock: LockRecord, quantity: string, extraBuyRate: string): DeliveryCost {
if (!priceLockUsesPool(lock))
return LedgerCalc.priceLockCost({
lockedQuantity: grams(lock.locked_mg),
quantity,
buyRate: (lock.buy_rate / 100).toFixed(2),
buyRate: (Number(lock.buy_rate) / 100).toFixed(2),
extraBuyRate,
});
const pool = lock.materialPool,
@@ -125,8 +145,9 @@ export function lockViews(state, session) {
leftoverMg = lock.locked_mg - originalUsedMg;
if (
!pool ||
!['basisAmount', 'basisMg', 'prefixMg', 'prefixAmount', 'amount'].every(
key => Number.isSafeInteger(pool[key]) && pool[key] >= 0,
typeof pool.amount !== 'number' ||
!(['basisAmount', 'basisMg', 'prefixMg', 'prefixAmount', 'amount'] as const).every(
key => typeof pool[key] === 'number' && Number.isSafeInteger(pool[key]) && pool[key] >= 0,
) ||
!pool.basisMg
)
@@ -172,7 +193,7 @@ export function lockViews(state, session) {
: {}),
};
}
function priceLockLineInputs(lock) {
function priceLockLineInputs(lock: LockRecord) {
const line = lock.line,
payer = priceLockMaterialAllocations(lock)[0]?.payer || lock.buy_payer || 'owner';
return {
@@ -188,7 +209,7 @@ export function lockViews(state, session) {
})),
payer,
costParts: {
material: (lock.material_amount / 100).toFixed(2),
material: (Number(lock.material_amount) / 100).toFixed(2),
labor: '',
accessories: '0',
other: '0',
@@ -205,7 +226,7 @@ export function lockViews(state, session) {
},
};
}
function detailView(lock) {
function detailView(lock: LockRecord) {
return (
<>
<div className={'order-header'}>
@@ -256,12 +277,12 @@ export function lockViews(state, session) {
</>
);
}
function priceLockCardFeeTotal(lock) {
return Number.isSafeInteger(lock.credit_card_fee_total)
function priceLockCardFeeTotal(lock: LockRecord) {
return lock.credit_card_fee_total !== undefined && Number.isSafeInteger(lock.credit_card_fee_total)
? lock.credit_card_fee_total
: (lock.credit_card_fees || []).reduce((sum, item) => sum + item.amount, 0);
}
function renderPriceLockCardFees(lock) {
function renderPriceLockCardFees(lock: LockRecord) {
const fees = lock.credit_card_fees || [];
if (!fees.length && !priceLockCardFeeTotal(lock)) return '';
return (
@@ -289,7 +310,7 @@ export function lockViews(state, session) {
</>
);
}
function priceLockFacts(lock) {
function priceLockFacts(lock: LockRecord) {
const voided =
lock.status === 'cancelled' ? (
<>
@@ -417,7 +438,7 @@ export function lockViews(state, session) {
</>
);
}
function cancelView(result, approval) {
function cancelView(result: LockEdit & { lock: LockRecord }, approval: boolean) {
const id = result.lock.id;
return (
<>
@@ -440,7 +461,7 @@ export function lockViews(state, session) {
</div>
<form id={'price-lock-cancel-form'}>
<label>
作废原因<textarea name={'reason'} required={true} maxLength={'200'} rows={'2'}></textarea>
作废原因<textarea name={'reason'} required={true} maxLength={200} rows={2}></textarea>
</label>
<label className={'check'}>
<input name={'verified'} type={'checkbox'} required={true} />
@@ -466,8 +487,9 @@ export function lockViews(state, session) {
</>
);
}
function renderPriceLockRelatedOrders(rows) {
const money = value => (value === null ? '待核算' : Number.isSafeInteger(value) ? '¥' + yuan(value) : '未提供');
function renderPriceLockRelatedOrders(rows: Impact['relatedOrders']) {
const money = (value: number | null | undefined) =>
value === null ? '待核算' : Number.isSafeInteger(value) ? '¥' + yuan(value) : '未提供';
return (
<>
<section className={'lock-related-orders'}>
@@ -508,13 +530,16 @@ export function lockViews(state, session) {
}
const validOrderDate = Values.validDate;
const teamMemberKeys = () => Model.memberKeys(state);
function validateRelatedPriceLocks(items) {
function validateRelatedPriceLocks(items: Impact['relatedPriceLocks']) {
if (items === undefined) return [];
const amount = value => value === null || (Number.isSafeInteger(value) && value >= 0);
const snapshot = value =>
const amount = (value: number | null | undefined) =>
value === null || (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0);
const snapshot = (value: LockCost) =>
value &&
amount(value.materialAmount) &&
['usedMaterialAmount', 'leftoverCost'].every(key => !Object.hasOwn(value, key) || amount(value[key])) &&
(['usedMaterialAmount', 'leftoverCost'] as const).every(
key => !Object.hasOwn(value, key) || amount(value[key]),
) &&
Array.isArray(value.allocations) &&
value.allocations.every(
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
@@ -536,17 +561,17 @@ export function lockViews(state, session) {
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
return items;
}
function renderRelatedPriceLocks(items) {
function renderRelatedPriceLocks(items: Impact['relatedPriceLocks']) {
const locks = validateRelatedPriceLocks(items);
if (!locks.length) return '';
const money = value => (value === null ? '待补齐' : '¥' + yuan(value)),
sources = value =>
const money = (value: number | null | undefined) => (value === null ? '待补齐' : '¥' + yuan(value)),
sources = (value: LockCost) =>
value.allocations.length
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
: value.materialAmount === null
? '待补齐后分摊'
: '无分摊金额';
const pair = (name, before, after) => (
const pair = (name: string, before: ReactNode, after: ReactNode) => (
<>
<tr>
<th scope={'row'}>{name}</th>
@@ -581,7 +606,7 @@ export function lockViews(state, session) {
</thead>
<tbody>
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
? pair(
'交付耗用原锁料费',
Object.hasOwn(lock.before, 'usedMaterialAmount')
@@ -592,7 +617,7 @@ export function lockViews(state, session) {
: '未交付',
)
: ''}
{['before', 'after'].some(side => Object.hasOwn(lock[side], 'leftoverCost'))
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'leftoverCost'))
? pair(
'少重回池成本',
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
@@ -610,14 +635,14 @@ export function lockViews(state, session) {
</>
);
}
const accountDisplayName = value => {
const accountDisplayName = (value: string) => {
const id = Model.accountIdentity(state, value);
return id ? Model.memberName(state, id.member) + id.channel : value;
};
function pocketLabel(key) {
function pocketLabel(key: string) {
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
}
function renderPriceLockItems(lock) {
function renderPriceLockItems(lock: LockRecord) {
const rows = priceLockLines(lock);
return (
<>
@@ -679,7 +704,7 @@ export function lockViews(state, session) {
(delivery.extraMg ?? delivery.extra_mg) ? (
<>
<br />
补重 {grams(delivery.extraMg ?? delivery.extra_mg)}g
补重 {grams(delivery.extraMg ?? delivery.extra_mg ?? 0)}g
</>
) : (
''
@@ -689,7 +714,7 @@ export function lockViews(state, session) {
<>
<br />
{priceLockUsesPool(row) ? '解除预留回池 ' : '剩料留盘 '}
{grams(delivery.leftoverMg ?? delivery.leftover_mg)}g
{grams(delivery.leftoverMg ?? delivery.leftover_mg ?? 0)}g
</>
) : (
''
@@ -726,7 +751,7 @@ export function lockViews(state, session) {
</>
);
}
function renderPriceLockChangeSnapshot(snapshot, title) {
function renderPriceLockChangeSnapshot(snapshot: ChangeSnapshot | undefined, title: string) {
if (!snapshot)
return (
<>
@@ -736,10 +761,8 @@ export function lockViews(state, session) {
</div>
</>
);
const value = snapshot.lock || snapshot,
rows = value.lines || [],
inputRows = rows[0] && !rows[0].line;
if (!inputRows)
const value = 'lock' in snapshot ? snapshot.lock : snapshot;
if (!isInputSnapshot(value))
return (
<>
<div className={'lock-change-snapshot'}>
@@ -763,6 +786,7 @@ export function lockViews(state, session) {
</div>
</>
);
const rows = value.lines || [];
return (
<>
<div className={'lock-change-snapshot'}>
@@ -834,7 +858,7 @@ export function lockViews(state, session) {
</>
);
}
function changeDetail(result, canReview) {
function changeDetail(result: LockChange, canReview: boolean) {
return (
<>
<button className={'dialog-close'} data-action={'price-lock-changes-close'} aria-label={'关闭'}>
@@ -883,12 +907,12 @@ export function lockViews(state, session) {
'data-id': result.price_lock_id,
})}
</div>
{session.user.role === 'owner' && result.status === 'pending' ? (
{state.user.role === 'owner' && result.status === 'pending' ? (
<>
<form id={'price-lock-review-form'}>
<label>
复核备注
<textarea name={'review_note'} maxLength={'240'} rows={'2'} placeholder={'驳回时必填'}></textarea>
<textarea name={'review_note'} maxLength={240} rows={2} placeholder={'驳回时必填'}></textarea>
</label>
{canReview ? (
<>
@@ -923,7 +947,7 @@ export function lockViews(state, session) {
</>
);
}
function changeRows(result) {
function changeRows(result: { rows: ChangeListRow[] }) {
return result.rows.length ? (
<>
<div className={'table-wrap'}>
@@ -980,8 +1004,8 @@ export function lockViews(state, session) {
</>
);
}
function renderPriceLockPendingButtons(lock) {
return ['owner', 'assistant'].includes(session.user.role) ? (
function renderPriceLockPendingButtons(lock: LockRecord) {
return ['owner', 'assistant'].includes(state.user.role) ? (
<>
{button('修改', 'edit-price-lock', 'quiet', {
'data-id': lock.id,
@@ -994,13 +1018,13 @@ export function lockViews(state, session) {
''
);
}
const button = (text, action, cls = '', props = {}) => (
const button = (text: string, action: string, cls = '', props: Record<string, string | boolean | null> = {}) => (
<button type="button" data-action={action} className={cls} {...props}>
{text}
</button>
);
const materialSourceSegmentsText = sources => describeMaterialSources(sources, teamMemberName);
function priceLockMaterialAllocations(lock) {
const materialSourceSegmentsText = (sources: SourceDescription[]) => describeMaterialSources(sources, teamMemberName);
function priceLockMaterialAllocations(lock: LockRecord) {
return priceLockMaterialPending(lock)
? []
: priceLockUsesPool(lock)
@@ -1008,27 +1032,27 @@ export function lockViews(state, session) {
: [
{
payer: lock.buy_payer,
amount: lock.material_amount,
amount: Number(lock.material_amount),
},
];
}
const teamMemberName = key => Model.memberName(state, key, session);
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
function priceLockAllocationText(allocations) {
const teamMemberName = (key: string) => Model.memberName(state, key, session);
const priceLockPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
function priceLockAllocationText(allocations: Allocation[]) {
return allocations.map(part => priceLockPayerName(part.payer) + ' ¥' + yuan(part.amount)).join(';');
}
function priceLockMaterialAmountText(lock) {
function priceLockMaterialAmountText(lock: LockRecord) {
const amount =
priceLockUsesPool(lock) && Number.isSafeInteger(lock.materialPool?.amount)
? lock.materialPool.amount
? lock.materialPool?.amount
: lock.material_amount;
return priceLockMaterialPending(lock) || !Number.isSafeInteger(amount) ? '料费待补' : '¥' + yuan(amount);
}
const priceLockMaterialPending = lock =>
const priceLockMaterialPending = (lock: LockRecord) =>
lock?.material_amount === null ||
(priceLockUsesPool(lock) && (lock.materialPool?.status === 'pending' || lock.materialPool?.amount === null));
const priceLockUsesPool = lock => lock?.material_source === 'pool';
function renderPriceLockItemFacts(lock) {
const priceLockUsesPool = (lock: LockRecord) => lock?.material_source === 'pool';
function renderPriceLockItemFacts(lock: LockRecord) {
const pool = priceLockUsesPool(lock),
material = lock.materialPool,
pendingMaterial = priceLockMaterialPending(lock);
@@ -1077,13 +1101,13 @@ export function lockViews(state, session) {
}
const yuan = Model.yuan;
const grams = Model.grams;
function priceLockLines(lock) {
function priceLockLines(lock: LockRecord): LockRecord[] {
if (!Array.isArray(lock?.lines) || !lock.lines.length) return lock ? [lock] : [];
return lock.lines.map((item, index) => {
const row = {
...lock,
...item,
id: item.id || item.lineId || item.price_lock_line_id,
id: item.id || item.lineId || item.price_lock_line_id || item.id,
line: item.line || item,
line_index: index,
parent_id: lock.id,
@@ -1092,7 +1116,7 @@ export function lockViews(state, session) {
return row;
});
}
function listRecords(result, status) {
function listRecords(result: { rows: LockRecord[] }, status: string) {
return result.rows.length ? (
<>
<div className={'table-wrap'}>
@@ -0,0 +1,183 @@
import type { LedgerClient } from '../../lib/api';
import type { LedgerState, SessionInfo, LockCostEstimate } from '../../shared';
import type { Allocation, Impact } from '../MaterialPools/model';
import type { QuoteBalance, QuoteEntry, QuoteSource } from '../../lib/materialQuote';
import type { SavedPayment } from './formParts';
import type { lockViews } from './lockViews';
export interface LockProps {
client: LedgerClient;
state: LedgerState;
session: SessionInfo;
}
export type LockViews = ReturnType<typeof lockViews>;
export type SaveLock = (url: string, input: Record<string, unknown>) => Promise<void>;
export interface PreviewRow extends QuoteEntry {
amount: number | null;
allocations: Allocation[];
materialSources?: QuoteSource[];
balance?: QuoteBalance;
averageRate?: number | null;
revision?: number | string;
remainingMg: number;
covered: boolean;
shortageMg: number;
totalMg?: number;
usedMg?: number;
wantedMg?: number;
}
export interface LockedSource extends QuoteSource {
amount: number;
basisAmount: number;
basisMg: number;
prefixMg: number;
prefixAmount: number;
batches?: { mg: number; purchaseId?: string; recoveryId?: string }[];
}
export interface ReservedMaterial {
date: string;
status: string;
quantity: number;
amount: number | null;
averageRate: number | null;
frozen?: boolean;
basisAmount: number;
basisMg: number;
prefixMg: number;
prefixAmount: number;
allocations: Allocation[];
materialSources?: LockedSource[];
}
export interface DeliveryCost extends LockCostEstimate {
allocations?: Allocation[];
materialSources?: LockedSource[];
leftoverMaterialSources?: LockedSource[];
extraPool?: PreviewRow;
}
interface DeliveryRecord {
finalMg?: number;
quantity?: number;
extraMg?: number;
extra_mg?: number;
leftoverMg?: number;
leftover_mg?: number;
inventory?: { pocket: string };
pocket?: string;
}
interface StoredLine {
name: string;
code: string;
unit: string;
pocket: string;
laborMode: string;
pieces: number;
laborRate: number;
sale: number;
baseSale?: number;
charges: { name: string; amount: number }[];
}
export interface LockItem {
id: string;
lineId?: string;
price_lock_line_id?: string;
line: StoredLine;
locked_mg: number;
sell_rate: number;
buy_rate: number | null;
buy_payer: string;
material_amount: number | null;
material_source: string;
material_pool_id?: string;
materialPool?: ReservedMaterial;
delivery?: DeliveryRecord | null;
}
export interface LockRecord extends LockItem {
date: string;
status: string;
number: string;
customer: string;
salesperson: string;
note: string;
discount: number;
member?: string;
revision: number;
netReceived: number;
estimated_total: number;
final_order_id: string | null;
cancelled_reason?: string;
cancelled_at?: string;
credit_card_fee_total?: number;
cash_events?: { kind: string; account: string }[];
credit_card_fees?: { amount: number; payer: string; date: string; note?: string }[];
cancellationReturns?: { line_index: number; date: string; mg: number; amount: number; origin_pool_id: string }[];
lines?: LockItem[];
}
export interface ManualMaterial {
rate?: string;
payer?: string;
verified?: boolean;
}
export interface InputMaterial extends ManualMaterial {
poolId?: string;
source?: string;
manual?: ManualMaterial;
revision?: string | number;
}
export interface InputLine {
name?: string;
code?: string;
lineId?: string;
quantity?: string;
goldPrice?: string;
laborRate?: string;
laborMode?: string;
pieces?: number | string;
charges?: { name?: string; amount?: string }[];
material?: InputMaterial;
}
export interface LockCreateDraft {
member?: string;
date?: string;
customer?: string;
salesperson?: string;
note?: string;
discount?: string;
payment?: SavedPayment;
lines?: InputLine[];
line?: InputLine;
material?: InputMaterial;
}
export interface LockEdit {
lock: Pick<LockRecord, 'id' | 'date' | 'number' | 'status'> & { customer?: string };
revision: number;
eligible: boolean;
requiresApproval: boolean;
reason?: string;
inputs: LockCreateDraft & { date: string };
}
export interface ChangeListRow {
id: string;
requestId?: string;
requester_name: string;
requester?: string;
created: string;
action: 'edit' | 'cancel';
status: 'pending' | 'approved' | 'rejected';
reason: string;
number?: string;
customer?: string;
before?: { number?: string; customer?: string };
}
export type ChangeSnapshot = LockRecord | LockCreateDraft | { lock: LockRecord };
export interface LockChange extends ChangeListRow {
before: LockRecord;
after?: ChangeSnapshot;
price_lock_id: string;
price_lock_revision: number;
revision: number;
stale: boolean;
note?: string;
changes: { field: string; before: unknown; after: unknown }[];
relatedOrders?: Impact['relatedOrders'];
relatedPriceLocks?: Impact['relatedPriceLocks'];
}
@@ -1,12 +1,18 @@
import type { LedgerState } from '../../shared';
import type { LedgerClient } from '../../lib/api';
import type { QuoteEntry, QuoteRequest, validateMaterialQuote } from '../../lib/materialQuote';
import type { Allocation, Pool, PoolResult } from '../MaterialPools/model';
import type { LockViews, PreviewRow } from './types';
import { useEffect, useState } from 'react';
import { Calc, Model } from '../../shared';
import { validatePools, poolRows } from '../MaterialPools/model';
import { safeEstimate } from './formParts';
// 公共料池以采购付款顺序分摊。先扣已用与本单前序行,余款才归本行。
function publicQuote(pool, entries, all, state) {
function publicQuote(pool: Pool | undefined, entries: QuoteEntry[], all: Pool[], state: LedgerState): PreviewRow[] {
if (!pool || !pool.totalMg) throw new Error('当日尚无可用材料。请先登记购料,再保存锁价。');
if (pool.totalAmount == null) throw new Error('料池成本尚未补齐,请先核对材料记录,再保存锁价。');
const totalAmount = pool.totalAmount;
const preview = Calc.poolMaterialPreview(pool, entries, { allUsages: all.flatMap(r => r.usages || []) });
let used = preview.usedMg;
const available = Math.max(0, pool.totalMg - used),
@@ -14,15 +20,20 @@ function publicQuote(pool, entries, all, state) {
const funds = pool.purchases.flatMap(p => p.allocations || [{ payer: p.payer, amount: p.amount }]);
return entries.map(r => {
const amount = preview.amounts[r.lineIndex],
allocations = [],
allocations: Allocation[] = [],
covered = preview.covered && !shortageMg && amount != null;
let skip = Calc.poolMaterialAmount(pool.totalAmount, pool.totalMg, used),
left = amount,
let skip = Calc.poolMaterialAmount(totalAmount, pool.totalMg, used),
left = amount ?? 0,
zero = '';
used += r.mg;
if (covered) {
for (const part of funds) {
if (!Model.memberKeys(state).includes(part.payer) || !Number.isSafeInteger(part.amount) || part.amount <= 0)
if (
!part.payer ||
!Model.memberKeys(state).includes(part.payer) ||
!Number.isSafeInteger(part.amount) ||
part.amount <= 0
)
throw new Error('料池付款来源未完整读到,请刷新料池。');
if (skip >= part.amount) {
skip -= part.amount;
@@ -47,7 +58,7 @@ function publicQuote(pool, entries, all, state) {
amount: covered ? amount : null,
allocations,
revision: pool.revision,
covered,
covered: !!covered,
shortageMg,
averageRate: pool.averageRate,
remainingMg: available,
@@ -57,15 +68,38 @@ function publicQuote(pool, entries, all, state) {
};
});
}
export function useLockPool({ client, state, views, date, member, entries, editId = '', delivery = false }) {
interface PoolParams {
client: LedgerClient;
state: LedgerState;
views: LockViews;
date: string;
member: string;
entries: QuoteEntry[];
editId?: string;
delivery?: boolean;
}
type PoolResponse = { seq: number } & ({ data: PoolResult; error?: undefined } | { data?: undefined; error: string });
type RemoteQuote = { seq: number; key: string } & (
{ value: ReturnType<typeof validateMaterialQuote>; error?: undefined } | { value?: undefined; error: string }
);
export function useLockPool({
client,
state,
views,
date,
member,
entries,
editId = '',
delivery = false,
}: PoolParams) {
const [seq, setSeq] = useState(0),
[loaded, setLoaded] = useState(null),
[remote, setRemote] = useState(null);
[loaded, setLoaded] = useState<PoolResponse | null>(null),
[remote, setRemote] = useState<RemoteQuote | null>(null);
useEffect(() => {
if (delivery) return;
let active = true;
client
.api('/api/material-pools')
.api<PoolResult>('/api/material-pools')
.then(validatePools)
.then(data => {
if (active) setLoaded({ seq, data });
@@ -86,7 +120,7 @@ export function useLockPool({ client, state, views, date, member, entries, editI
useEffect(() => {
if (!shouldQuote) return;
let active = true;
const request = JSON.parse(key);
const request: QuoteRequest = JSON.parse(key);
client
.api('/api/material-pools/quote', request)
.then(r => views.validateMaterialQuote(r, request))
@@ -100,14 +134,14 @@ export function useLockPool({ client, state, views, date, member, entries, editI
active = false;
};
}, [client, key, seq, shouldQuote, views]);
let rows = [],
let rows: PreviewRow[] = [],
error = (!delivery && loaded?.seq === seq && loaded.error) || '';
if (entries.length && !error) {
if (!delivery && !data) error = '正在读取每日料池,请稍候。';
else if (!delivery && !data.rolling?.enabled) error = '请先启用统一料池,再选择当日加权料价。';
else if (!delivery && !data?.rolling?.enabled) error = '请先启用统一料池,再选择当日加权料价。';
else if (shouldQuote) {
if (remote?.key !== key || remote?.seq !== seq) error = '正在按订单归属核对个人回收料与公共补足,请稍候。';
else if (remote.error) error = remote.error;
else if (remote.value === undefined) error = remote.error;
else {
const balance = remote.value.pools.find(p => p.poolId === date),
available = balance?.before?.eligibleRemainingMg ?? 0,
@@ -1,33 +1,37 @@
import type { LedgerState } from '../../shared';
import type { ChangeRequest, Input, Exchange, Labor, Material, MoneySummary } from './types';
type Cell = string | number | null | undefined;
import { Model } from '../../shared';
import { yuan } from '../../lib/format';
import { count as stockCountText } from '../Inventory/data';
import { rowLabel } from './controls';
export function Comparison({ request, state }) {
export function Comparison({ request, state }: { request: ChangeRequest; state: LedgerState }) {
const before = request.before,
after = request.after,
rows = [],
pair = (title, a, b) => [title, a, b];
const teamMemberName = k => Model.memberName(state, k),
pocketLabel = k => rowLabel(state, k),
accountDisplayName = v =>
rows: [string, Cell, Cell][] = [],
pair = (title: string, a: Cell, b: Cell): [string, Cell, Cell] => [title, a, b];
const teamMemberName = (k?: string) => Model.memberName(state, k ?? ''),
pocketLabel = (k?: string) => rowLabel(state, k),
accountDisplayName = (v: string) =>
String(v || '')
.replace(/^助理2/, Model.memberName(state, 'assistant2'))
.replace(/^助理1?/, Model.memberName(state, 'assistant'))
.replace(/^麦麦/, Model.memberName(state, 'owner'));
const old = input =>
const old = (input: Input) =>
input?.old_lines
.map(row => `${row.name}:来料 ${row.incoming_weight}g,熔后 ${row.melted_weight}g,成色 ${row.purity}%`)
.join('\n'),
fees = input =>
fees = (input: Input) =>
input?.exchange?.fee_items
.map(row => `${row.note}:${row.amount}元 · ${teamMemberName(row.payer)}付款`)
.join('\n') || '无',
charges = input => input?.exchange?.charges.map(row => `${row.name}:${row.amount}元`).join('\n') || '无';
const x = before.exchange || {},
y = after?.exchange || {},
material = value =>
charges = (input: Input) => input?.exchange?.charges.map(row => `${row.name}:${row.amount}元`).join('\n') || '无';
const x: Partial<Exchange> = before.exchange || {},
y: Partial<Exchange> = after?.exchange || {},
material = (value?: Material) =>
value?.mode === 'pool' ? '料池 ' + value.poolId : value ? '手填 ' + value.rate + '元/克' : '无补金差重',
labor = value => (value ? (value.mode === 'gram' ? value.rate + '元/克' : value.amount + '元总工费') : '未提供');
labor = (value?: Labor) =>
value ? (value.mode === 'gram' ? value.rate + '元/克' : value.amount + '元总工费') : '未提供';
rows.push(
pair('业务日期', before.date, after?.date || '取消原记录'),
pair('客户', before.customer, after?.customer),
@@ -75,7 +79,7 @@ export function Comparison({ request, state }) {
),
);
if (before.exchange?.items || after?.exchange?.items) {
const items = v =>
const items = (v: Input) =>
(v?.exchange?.items || [])
.map(
(p, i) =>
@@ -116,7 +120,7 @@ export function Comparison({ request, state }) {
rows.push(pair('逐件置换完整资料', items(before), after ? items(after) : '全部冲回'));
}
if (before.exchange?.products || after?.exchange?.products) {
const items = x =>
const items = (x?: Exchange) =>
(x?.products ?? (x ? [x] : []))
.map(
(p, i) =>
@@ -178,17 +182,19 @@ export function Comparison({ request, state }) {
pair('工费付款人', teamMemberName(x.cost_labor_payer), after ? teamMemberName(y.cost_labor_payer) : '原来源留档'),
pair('实际费用', fees(before), after ? fees(after) : '冲正原费用'),
);
const a = request.summary.before || {},
b = request.summary.after || {};
const a: MoneySummary = request.summary.before || {},
b: MoneySummary = request.summary.after || {};
rows.push(
...[
['实际收客户', 'cashReceipt'],
['实际付客户', 'cashPayment'],
['购料成本', 'purchaseAmount'],
['订单货品成本', 'goodsCost'],
['实际费用', 'directCost'],
['原账利润', 'profit'],
].map(([title, key]) =>
...(
[
['实际收客户', 'cashReceipt'],
['实际付客户', 'cashPayment'],
['购料成本', 'purchaseAmount'],
['订单货品成本', 'goodsCost'],
['实际费用', 'directCost'],
['原账利润', 'profit'],
] as const
).map(([title, key]) =>
pair(
title,
a[key] == null ? '待核实' : '¥' + yuan(a[key]),
@@ -1,7 +1,9 @@
import type { FormEvent } from 'react';
import type { PageProps, RecoveryModel, DepositListData } from './types';
import { useState } from 'react';
import { grams } from '../../lib/format';
import { loadDraft } from './controls';
export function validateDeposits(r) {
export function validateDeposits(r: DepositListData) {
if (
!Array.isArray(r.rows) ||
!Number.isSafeInteger(r.remainingMg) ||
@@ -9,7 +11,17 @@ export function validateDeposits(r) {
)
throw new Error('寄存资料未完整返回');
}
export function DepositList({ data, error, start, refresh }) {
export function DepositList({
data,
error,
start,
refresh,
}: {
data?: DepositListData;
error?: string;
start(): void;
refresh(): void;
}) {
return (
<section className="panel" id="customer-material-panel">
<div className="panel-title">
@@ -91,29 +103,36 @@ export function DepositList({ data, error, start, refresh }) {
</section>
);
}
export function DepositForm({ client, state, model, saved }) {
export function DepositForm({ client, state, model, saved }: PageProps & { model: RecoveryModel; saved(): void }) {
const key = 'mm-customer-material-' + state.user.id,
[draft, setDraft] = useState(() => loadDraft(key) || {}),
[draft, setDraft] = useState(
() => loadDraft<Partial<Record<'date' | 'grams' | 'memo' | 'verified', string>>>(key) || {},
),
[error, setError] = useState('');
const change = e => {
const change = (e: FormEvent<HTMLFormElement>) => {
const form = e.currentTarget,
next = Object.fromEntries(new FormData(form));
next = Object.fromEntries(Array.from(new FormData(form), ([key, value]) => [key, String(value)]));
setDraft(next);
localStorage.setItem(key, JSON.stringify(next));
};
async function submit(e) {
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const f = new FormData(e.currentTarget),
input = { date: f.get('date'), grams: f.get('grams'), memo: f.get('memo').trim(), verified: f.has('verified') };
input = {
date: f.get('date'),
grams: f.get('grams'),
memo: String(f.get('memo') ?? '').trim(),
verified: f.has('verified'),
};
try {
model.units(input.grams, 3, '寄存克重', { zero: false });
if (!input.memo) throw new Error('请填写备忘');
const result = await client.mutate('/api/customer-materials', input);
const result = await client.mutate<{ id: string }>('/api/customer-materials', input);
if (!result.id) throw new Error('寄存保存结果未完整返回,请核对后再操作');
localStorage.removeItem(key);
saved();
} catch (err) {
setError(err.message);
setError((err as Error).message);
}
}
return (
@@ -1,3 +1,30 @@
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes } from 'react';
import type {
EditDetail,
Draft,
Derived,
TextField,
PageProps,
Deposit,
QuoteItem,
MaterialPool,
ExtraFields,
ExtraKinds,
PoolChoice,
} from './types';
import type { Choice } from './controls';
interface Fields {
text(title: string, key: TextField, limit: number, props?: InputHTMLAttributes<HTMLInputElement>): ReactNode;
num(title: string, key: TextField, places?: number, props?: InputHTMLAttributes<HTMLInputElement>): ReactNode;
select(
title: string,
key: TextField,
choices: readonly Choice[],
props?: SelectHTMLAttributes<HTMLSelectElement>,
): ReactNode;
rateField(title: string, key: TextField, use?: boolean, props?: InputHTMLAttributes<HTMLInputElement>): ReactNode;
pairs(title: string, key: TextField, pocket: string, visible?: boolean, optional?: boolean): ReactNode;
}
import { Model } from '../../shared';
import { grams } from '../../lib/format';
import { pocketOptions, Settlement, money } from './controls';
@@ -17,6 +44,19 @@ export function IndependentItems({
remove,
setField,
extras,
}: {
parts: Derived[];
quotedItems?: QuoteItem[];
draft: Draft;
edit: EditDetail;
state: PageProps['state'];
materials: Deposit[];
pools: MaterialPool[];
fields(row?: Draft, index?: number): Fields;
add(): void;
remove(index: number): void;
setField<K extends keyof Draft>(key: K, value: Draft[K], index?: number): void;
extras<K extends keyof ExtraKinds>(kind: K, rows: ExtraKinds[K][], keys: ExtraFields<K>, caption: string): ReactNode;
}) {
const common = fields(),
members = Model.memberOptions(state);
@@ -28,12 +68,12 @@ export function IndependentItems({
{parts.map(({ draft: row, old, hasBuy, diff, q, input, error }, i) => {
const index = i - 1,
f = fields(row, index),
original = edit.inputs.exchange.items[i],
original = edit.inputs.exchange!.items![i],
item = quotedItems?.[i],
deposit = row.old_source === 'deposit',
saveSurplus = row.surplus_mode === 'deposit',
today = draft.date;
const poolList = pools.filter(
const poolList: (Pick<PoolChoice, 'id' | 'date'> & Partial<PoolChoice>)[] = pools.filter(
p =>
p.date <= today &&
(p.id === row.material_pool_id ||
@@ -196,10 +236,10 @@ export function IndependentItems({
? '个人余 ' +
grams(p.personalPools[draft.member]?.remainingMg || 0) +
'g/公共余 ' +
grams(p.remainingMg) +
grams(p.remainingMg ?? 0) +
'g'
: p.totalMg
? '余 ' + grams(p.remainingMg) + 'g'
? '余 ' + grams(p.remainingMg ?? 0) + 'g'
: '待补采购'),
]),
{ disabled: !diff || row.material_source !== 'pool' },
@@ -231,9 +271,9 @@ export function IndependentItems({
money(item.materialCost) +
';进货工费 ' +
money(item.laborCost) +
(item.exchange.costMaterial.materialSources
(item.exchange!.costMaterial!.materialSources
? ';' +
describeMaterialSources(item.exchange.costMaterial.materialSources, key =>
describeMaterialSources(item.exchange!.costMaterial!.materialSources, (key: string) =>
Model.memberName(state, key),
)
: '')}
@@ -1,23 +1,38 @@
import { useCallback, useEffect, useState } from 'react';
import type { FormEvent } from 'react';
import type { usePrintStatuses } from '../../lib/printStatus';
import type { ApiError } from '../../lib/api';
import type {
PageProps,
Filters,
SummaryRow,
EditDetail,
RecoveryModel,
ChangeRequest,
Selection,
ChangeList,
Saved,
} from './types';
type PrintStatuses = ReturnType<typeof usePrintStatuses>;
import { useCallback, useState } from 'react';
import { Model } from '../../shared';
import { grams } from '../../lib/format';
import { useRead, dateValid, count } from '../Inventory/data';
import { LegacyCount, Modal, Settlement, money, options, rowLabel } from './controls';
import { Comparison } from './Comparison';
const modes = { direct: '直接回收', exchange: '置换' };
const status = r =>
const status = (r: ChangeRequest) =>
({ pending: '待店主复核', approved: r.action === 'cancel' ? '已同意取消' : '已同意修改', rejected: '已驳回' })[
r.status
] || '状态待核对';
const print = id => window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
export function PrintButton({ id, title = '客户预览/打印' }) {
const print = (id: string) => window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
export function PrintButton({ id, title = '客户预览/打印' }: { id: string; title?: string }) {
return (
<button data-action="recovery-print" data-id={id} onClick={() => print(id)}>
{title}
</button>
);
}
function PrintBadge({ row, statuses }) {
function PrintBadge({ row, statuses }: { row: SummaryRow; statuses: PrintStatuses }) {
const id = row.printStatus?.id || row.id;
const printed = (statuses[id] || row.printStatus)?.printed;
return (
@@ -31,22 +46,37 @@ function PrintBadge({ row, statuses }) {
</span>
);
}
export function Records({ client, state, version, filters, query, detail, printStatuses }) {
const [draft, setDraft] = useState(filters),
function checkRecordRows(result: { rows: SummaryRow[] }) {
if (!result || !Array.isArray(result.rows) || result.rows.some(row => !row.id || !Object.hasOwn(modes, row.mode)))
throw new Error('记录与查询范围不一致,请重新读取。');
}
export function Records({
client,
state,
version,
filters,
query,
detail,
printStatuses,
}: PageProps & {
version: number;
filters: Filters;
query(filters: Filters): void;
detail(id: string): void;
printStatuses: PrintStatuses;
}) {
const [editing, setEditing] = useState({ applied: filters, value: filters }),
[attempt, retry] = useState(0);
useEffect(() => {
setDraft(filters);
}, [filters]);
const check = useCallback(
r => {
if (!r || !Array.isArray(r.rows) || r.rows.some(v => !v.id || !Object.hasOwn(modes, v.mode)))
throw new Error('记录与查询范围不一致,请重新读取。');
},
[filters],
);
const draft = editing.applied === filters ? editing.value : filters;
const setDraft = (value: Filters) => setEditing({ applied: filters, value });
const valid =
dateValid(filters.from) && dateValid(filters.date) && filters.from <= filters.date && filters.date <= state.today,
r = useRead(client, valid ? '/api/recoveries?' + new URLSearchParams(filters) : null, version + attempt, check);
r = useRead(
client,
valid ? '/api/recoveries?' + new URLSearchParams(filters) : null,
version + attempt,
checkRecordRows,
);
return (
<section className="panel" id="recovery-history">
<div className="panel-title">
@@ -63,10 +93,12 @@ export function Records({ client, state, version, filters, query, detail, printS
query({ ...draft });
}}
>
{[
['from', '开始日期'],
['date', '结束日期'],
].map(([k, t]) => (
{(
[
['from', '开始日期'],
['date', '结束日期'],
] as const
).map(([k, t]) => (
<label key={k}>
{t}
<input
@@ -103,7 +135,7 @@ export function Records({ client, state, version, filters, query, detail, printS
</div>
) : !r ? (
'正在读取回收/置换记录…'
) : !r.value.rows.length ? (
) : !r.value!.rows.length ? (
<p>
<strong>这个日期范围还没有回收/置换单</strong>保存后可在这里查看和打印。
</p>
@@ -118,7 +150,7 @@ export function Records({ client, state, version, filters, query, detail, printS
</tr>
</thead>
<tbody>
{r.value.rows.map(v => (
{r.value!.rows.map(v => (
<tr key={v.id}>
<td>
{v.date}
@@ -155,7 +187,15 @@ export function Records({ client, state, version, filters, query, detail, printS
</section>
);
}
function MaterialFacts({ data, state, cancel = false }) {
function MaterialFacts({
data,
state,
cancel = false,
}: {
data: EditDetail;
state: PageProps['state'];
cancel?: boolean;
}) {
const b = data.record.materialBatch;
return (
<>
@@ -193,9 +233,29 @@ function MaterialFacts({ data, state, cancel = false }) {
</>
);
}
export function Detail({ client, state, model, id, version, close, edit, review, cancel, printStatuses }) {
export function Detail({
client,
state,
model,
id,
version,
close,
edit,
review,
cancel,
printStatuses,
}: PageProps & {
model: RecoveryModel;
id: string;
version: number;
close(): void;
edit(id: string): void;
review(id: string): void;
cancel(id: string): void;
printStatuses: PrintStatuses;
}) {
const [attempt, retry] = useState(0),
check = useCallback(r => model.checkEdit(r, id), [model, id]),
check = useCallback((r: EditDetail) => model.checkEdit(r, id), [model, id]),
response = useRead(client, '/api/recoveries/' + encodeURIComponent(id) + '/edit', version + attempt, check),
v = response?.value?.record,
data = response?.value;
@@ -205,7 +265,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
<div>
{response.error} <button onClick={() => retry(n => n + 1)}>重新读取</button>
</div>
) : !v ? (
) : !v || !data ? (
<p>正在读取单据…</p>
) : (
<>
@@ -238,7 +298,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
.filter(r => r.customerDeposit)
.map((r, i) => (
<p key={i}>
使用寄存记录 {r.customerDeposit.number} · {grams(r.customerDeposit.mg)}g
使用寄存记录 {r.customerDeposit!.number} · {grams(r.customerDeposit!.mg)}g
</p>
))}
<div className="table-wrap">
@@ -266,7 +326,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
</section>
<section className="panel">
{v.mode === 'exchange' &&
(v.newProducts || [v.newProduct]).map((r, i) => (
(v.newProducts || [v.newProduct!]).map((r, i) => (
<div key={i}>
<h3>
新货 {i + 1}:{r.name} · {grams(r.quantity)}g
@@ -314,7 +374,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
补金差重料费:{money(i.materialCost)} ·{' '}
{i.exchange?.costMaterial?.mode === 'pool'
? '按每日料池购料顺序核算付款人'
: Model.memberName(state, i.exchange?.costPayers?.material) + '支付'}
: Model.memberName(state, i.exchange?.costPayers?.material ?? '') + '支付'}
</p>
))}
{(
@@ -323,7 +383,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
.filter(i => i.laborCost !== 0)
.map((i, n) => (
<p key={n}>
{i.name}进货工费:{money(i.laborCost)} · {Model.memberName(state, i.laborPayer)}支付
{i.name}进货工费:{money(i.laborCost)} · {Model.memberName(state, i.laborPayer ?? '')}支付
</p>
))}
{v.exchange?.fee_items
@@ -353,7 +413,7 @@ export function Detail({ client, state, model, id, version, close, edit, review,
<h3>待店主复核</h3>
<p>原记录仍生效,申请尚未记账。</p>
<Comparison request={data.pending} state={state} />
<button data-action="recovery-change-open" onClick={() => review(data.pending.id)}>
<button data-action="recovery-change-open" onClick={() => review(data.pending!.id)}>
{state.user.role === 'owner' ? '查看并复核' : '查看申请'}
</button>
</section>
@@ -376,7 +436,21 @@ export function Detail({ client, state, model, id, version, close, edit, review,
</Modal>
);
}
export function ChangeDialog({ client, state, model, selection, select, close, saved }) {
export function ChangeDialog({
client,
state,
model,
selection,
select,
close,
saved,
}: PageProps & {
model: RecoveryModel;
selection: Selection;
select(value: Selection): void;
close(): void;
saved(result: Saved, id: string): void;
}) {
const owner = state.user.role === 'owner',
[filter, setFilter] = useState('pending'),
[attempt, retry] = useState(0),
@@ -392,21 +466,23 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
? '/api/recoveries/' + encodeURIComponent(id) + '/edit'
: '/api/recovery-changes/' + encodeURIComponent(id);
const check = useCallback(
r => {
(r: ChangeList | EditDetail | ChangeRequest) => {
if (list) {
if (
!('requests' in r) ||
!Array.isArray(r.requests) ||
!['pending', 'approved', 'rejected'].every(k => Number.isSafeInteger(r.counts?.[k]) && r.counts[k] >= 0)
!(['pending', 'approved', 'rejected'] as const).every(
k => Number.isSafeInteger(r.counts?.[k]) && r.counts[k] >= 0,
)
)
throw new Error('申请列表未完整返回');
r.requests.forEach(model.checkRequest);
} else if (cancel) {
model.checkEdit(r, id);
if (!r.permissions.canCancel || r.pending)
throw new Error(r.permissions.reason || '记录已取消或有待审批申请,当前不能取消。');
const data = model.checkEdit(r, id);
if (!data.permissions.canCancel || data.pending)
throw new Error(data.permissions.reason || '记录已取消或有待审批申请,当前不能取消。');
} else {
model.checkRequest(r);
if (r.id !== id) throw new Error('申请身份不一致,请重新读取。');
if (model.checkRequest(r).id !== id) throw new Error('申请身份不一致,请重新读取。');
}
},
[model, list, cancel, id],
@@ -419,9 +495,10 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
setStale(false);
retry(n => n + 1);
}
async function submit(e) {
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const f = new FormData(e.currentTarget);
if (!r || !('revision' in r) || !id) return;
try {
const verified = f.has('verified'),
reason = String(f.get('reason') || '').trim(),
@@ -434,19 +511,21 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
revision: r.revision,
reason,
verified: true,
...(r.permissions.requiresLegacyCountVerified ? { legacyCountVerified: f.has('legacyCountVerified') } : {}),
...('permissions' in r && r.permissions.requiresLegacyCountVerified
? { legacyCountVerified: f.has('legacyCountVerified') }
: {}),
}
: { revision: r.revision, note, ...(decision === 'approve' ? { verified: true } : {}) };
const res = await client.mutate(
const res = await client.mutate<Saved>(
cancel
? '/api/recoveries/' + encodeURIComponent(id) + '/cancel'
: '/api/recovery-changes/' + encodeURIComponent(id) + '/' + decision,
payload,
);
saved(res, cancel ? id : r.recoveryId);
saved(res, 'recoveryId' in r ? r.recoveryId : id);
} catch (e) {
setMessage(e.message);
if ([403, 404, 409].includes(e.status)) setStale(true);
setMessage((e as Error).message);
if ([403, 404, 409].includes((e as ApiError).status ?? 0)) setStale(true);
}
}
return (
@@ -456,8 +535,8 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
list
? '回收更正' + (owner ? '复核' : '申请')
: cancel
? '取消这笔' + (r ? modes[r.inputs.mode] : '回收/置换') + '记录'
: (r?.action === 'cancel' ? '取消' : '修改') + '回收/置换记录'
? '取消这笔' + (r && 'inputs' in r ? modes[r.inputs.mode] : '回收/置换') + '记录'
: (r && 'action' in r && r.action === 'cancel' ? '取消' : '修改') + '回收/置换记录'
}
action="recovery-changes-close"
close={close}
@@ -468,15 +547,17 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
</div>
) : !r ? (
'正在读取…'
) : list ? (
) : 'requests' in r ? (
<div id="recovery-change-list">
<div>
{[
['pending', '待复核'],
['approved', '已同意'],
['rejected', '已驳回'],
['all', '全部'],
].map(([k, t]) => (
{(
[
['pending', '待复核'],
['approved', '已同意'],
['rejected', '已驳回'],
['all', '全部'],
] as const
).map(([k, t]) => (
<button
key={k}
data-action="recovery-changes-filter"
@@ -521,7 +602,7 @@ export function ChangeDialog({ client, state, model, selection, select, close, s
</tbody>
</table>
</div>
) : cancel ? (
) : 'permissions' in r ? (
<>
<p>
{r.record.number} · {r.inputs.date} · {r.inputs.customer}
@@ -1,4 +0,0 @@
import type { ReactElement } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState } from '../../shared';
export function RecoveriesPage(props: { client: LedgerClient; state: LedgerState; search?: string }): ReactElement;
@@ -1,3 +1,5 @@
import type { LedgerClient } from '../../lib/api';
import type { ChangeList, EditDetail, Filters, Input, PageProps, Saved, Selection } from './types';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRead } from '../Inventory/data';
import { useClientSnapshot } from '../../lib/useClient';
@@ -9,40 +11,42 @@ import { DepositForm, DepositList, validateDeposits } from './Deposit';
import { Records, Detail, ChangeDialog, PrintButton } from './Records';
import './recoveries.css';
const lastQuery = new WeakMap();
export function RecoveriesPage({ client, state, search = window.location.search }) {
const lastQuery = new WeakMap<LedgerClient, { user: string; value: Filters }>();
export function RecoveriesPage({ client, state, search = window.location.search }: PageProps & { search?: string }) {
useClientSnapshot(client);
const model = useMemo(() => recoveryModel(state), [state]),
deep = new URLSearchParams(search).get('recovery'),
[detail, setDetail] = useState(deep || ''),
[selection, select] = useState(null),
[edit, setEdit] = useState(null),
[previousDeep, setPreviousDeep] = useState(deep),
[selection, select] = useState<Selection | null>(null),
[edit, setEdit] = useState<EditDetail | null>(null),
[page, setPage] = useState('new'),
[version, reload] = useState(0),
[result, setResult] = useState(null),
[result, setResult] = useState<{ payload: Input; r: Saved } | null>(null),
[notice, setNotice] = useState(''),
[formKey, resetForm] = useState(0);
const [filters, setFilters] = useState(() => {
const old = lastQuery.get(client);
return old?.user === state.user.id ? old.value : { from: state.today, date: state.today, mode: '', member: '' };
});
const historyRef = useRef(null),
const historyRef = useRef<HTMLDivElement>(null),
editingRequest = useRef(0);
useEffect(() => {
if (previousDeep !== deep) {
setPreviousDeep(deep);
setDetail(deep || '');
}, [deep]);
}
useEffect(
() => () => {
editingRequest.current++;
},
[],
);
const query = f => {
const query = (f: Filters) => {
lastQuery.set(client, { user: state.user.id, value: f });
setFilters(f);
};
const deposits = useRead(client, page === 'saved' ? null : '/api/customer-materials', version, validateDeposits);
const checkCount = useCallback(r => {
const checkCount = useCallback((r: ChangeList) => {
if (!Number.isSafeInteger(r.counts?.pending) || r.counts.pending < 0) throw new Error('数量未完整返回');
}, []);
const count = useRead(
@@ -62,12 +66,12 @@ export function RecoveriesPage({ client, state, search = window.location.search
window.dispatchEvent(new Event('next-route'));
}
}
async function getEdit(id) {
async function getEdit(id: string) {
const r = model.checkEdit(await client.api('/api/recoveries/' + encodeURIComponent(id) + '/edit'), id);
if (!r.permissions.canEdit || r.pending) throw new Error(r.permissions.reason || '这笔记录当前不能修改。');
return r;
}
async function begin(id) {
async function begin(id: string) {
const request = ++editingRequest.current;
try {
const r = await getEdit(id);
@@ -77,10 +81,10 @@ export function RecoveriesPage({ client, state, search = window.location.search
setPage('new');
setNotice('');
} catch (e) {
setNotice(e.message);
setNotice((e as Error).message);
}
}
function changeSaved(res, id) {
function changeSaved(res: Saved, id: string) {
select(null);
setEdit(null);
setPage('new');
@@ -88,7 +92,7 @@ export function RecoveriesPage({ client, state, search = window.location.search
setNotice(res.pending && !res.applied ? '回收更正申请已提交,待店主复核' : '回收更正已保存');
reload(n => n + 1);
}
function saved(payload, r) {
function saved(payload: Input, r: Saved) {
if (edit) {
changeSaved(r, edit.id);
return;
@@ -211,10 +215,10 @@ export function RecoveriesPage({ client, state, search = window.location.search
deposit={depositPage}
saved={saved}
exitEdit={() => {
setDetail(edit.id);
setDetail(edit!.id);
setEdit(null);
}}
refreshEdit={() => getEdit(edit.id)}
refreshEdit={() => getEdit(edit!.id)}
/>
{!edit && list}
</>
@@ -1,3 +1,23 @@
import type { ChangeEvent, FormEvent, InputHTMLAttributes, SelectHTMLAttributes } from 'react';
import type { ApiError } from '../../lib/api';
import type { Choice } from './controls';
import type {
EditDetail,
Draft,
RecoveryModel,
Derived,
TextField,
PageProps,
Deposit,
Input,
Saved,
QuoteItem,
MaterialPool,
ExtraKinds,
ExtraFields,
ProductDraft,
PoolChoice,
} from './types';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Model, Cards } from '../../shared';
import { grams } from '../../lib/format';
@@ -7,9 +27,10 @@ import { IndependentItems } from './IndependentItems';
import { localMaterialNote, quotedMaterialNote } from './materialPreview';
import { useRead } from '../Inventory/data';
function normalize(draft) {
function normalize(draft: Draft) {
const result = { ...draft, customer_type: draft.mode === 'direct' ? '' : draft.customer_type };
for (const k in result) if (typeof result[k] === 'string') result[k] = result[k].trim();
for (const [key, value] of Object.entries(result))
if (typeof value === 'string') Object.assign(result, { [key]: value.trim() });
if (draft.old_lines?.length)
result.old_lines = [
{
@@ -45,7 +66,7 @@ function normalize(draft) {
];
return result;
}
function derive(model, raw) {
function derive(model: RecoveryModel, raw: Draft): Derived {
if (raw.independent_products && raw.mode === 'exchange') {
const parts = [raw, ...(raw.extra_products || [])].map((item, index) =>
derive(model, {
@@ -78,7 +99,7 @@ function derive(model, raw) {
const input = model.input(draft, { quote: true });
return { draft, parts, input, q: model.calculate(input), error: '' };
} catch (error) {
return { draft, parts, input: null, q: null, error: error.message };
return { draft, parts, input: null, q: null, error: (error as Error).message };
}
}
@@ -134,11 +155,11 @@ function derive(model, raw) {
error = '';
if (!draft.buy_total_manual) draft = { ...draft, buy_total: (q.defaultPurchaseAmount / 100).toFixed(2) };
} catch (e) {
error = e.message;
error = (e as Error).message;
}
return { draft, old, newMg, q, input, error, hasBuy, diff };
}
function RecoveryCardFee({ state, edit, net }) {
function RecoveryCardFee({ state, edit, net }: { state: PageProps['state']; edit: EditDetail | null; net: number }) {
const rate = edit ? edit.record.credit_card_rate_permille : state.shopSettings?.creditCardRatePermille;
const unavailable = <p role="status">信用卡手续费率未能确认,请重新读取后核对。</p>;
if (rate == null) return unavailable;
@@ -157,17 +178,33 @@ function RecoveryCardFee({ state, edit, net }) {
}
const basicMethods = ['微信', '支付宝', '现金'];
export function RecoveryForm({ client, state, edit, materials = [], deposit, saved, exitEdit, refreshEdit }) {
export function RecoveryForm({
client,
state,
edit,
materials = [],
deposit,
saved,
exitEdit,
refreshEdit,
}: PageProps & {
edit: EditDetail | null;
materials?: Deposit[];
deposit(): void;
saved(input: Input, result: Saved): void;
exitEdit(): void;
refreshEdit(): Promise<EditDetail>;
}) {
const model = useMemo(() => recoveryModel(state, edit), [state, edit]),
key = 'mm-recovery-draft-' + state.user.id;
const editKey = edit ? 'mm-recovery-edit-' + state.user.id + '-' + edit.id : null;
const existing = useMemo(() => {
const v = editKey && loadDraft(editKey);
const v = editKey ? loadDraft<{ id: string; draft: Draft; revision: number; reason?: string }>(editKey) : null;
return v?.id === edit?.id && v?.draft?.mode === edit?.inputs?.mode && v?.draft?.member === edit?.inputs?.member
? v
: null;
}, [edit, editKey]);
const [raw, setRaw] = useState(() => {
const [raw, setRaw] = useState<Draft>(() => {
if (edit)
return {
...(existing?.draft || model.forEdit(edit.inputs)),
@@ -175,7 +212,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
change_reason: existing?.reason || '',
verified: false,
};
const stored = loadDraft(key);
const stored = loadDraft<Partial<Draft>>(key);
if (stored?.independent_products && !localStorage.getItem(key + '-before-shared-old'))
localStorage.setItem(key + '-before-shared-old', JSON.stringify(stored));
const d = model.sharedDraft({
@@ -189,9 +226,11 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
return d;
});
const [error, setError] = useState(''),
[quote, setQuote] = useState({}),
[rate, setRate] = useState({}),
[conflict, setConflict] = useState(existing && existing.revision !== edit?.revision ? {} : null),
[quote, setQuote] = useState<{ signature?: string; text?: string; materialText?: string; value?: QuoteItem }>({}),
[rate, setRate] = useState<{ name?: TextField; index?: number; text?: string }>({}),
[conflict, setConflict] = useState<{ latest?: EditDetail } | null>(
existing && existing.revision !== edit?.revision ? {} : null,
),
[revision, setRevision] = useState(existing?.revision ?? edit?.revision);
const { draft: d, old, newMg, q, input, error: calcError, hasBuy, diff, parts } = derive(model, raw),
exchange = d.mode === 'exchange',
@@ -199,12 +238,12 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
net = q?.netSettlement ?? (exchange ? 0 : -1),
card = net > 0 && d.payment_method === '信用卡';
const signature = input && q ? JSON.stringify(edit ? { ...input, revision } : input) : '',
live = useRef(raw);
live = useRef<Draft | null>(raw);
useEffect(() => {
live.current = raw;
if (edit)
localStorage.setItem(
editKey,
editKey!,
JSON.stringify({ id: edit.id, revision, draft: raw, reason: raw.change_reason || '' }),
);
else localStorage.setItem(key, JSON.stringify(raw));
@@ -220,18 +259,21 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
let valid = true;
const timer = setTimeout(async () => {
try {
const payload = JSON.parse(signature),
value = await client.api(quoteUrl, payload);
const payload: Input = JSON.parse(signature),
value = await client.api<QuoteItem>(quoteUrl, payload);
if (!Number.isSafeInteger(value.netSettlement) || value.netSettlement !== expected)
throw new Error('结算规则已更新,请重新读取页面再核对。');
if (!valid) return;
const materialText = await quotedMaterialNote(client, state, payload, value, differenceMg, edit);
const materialText = await quotedMaterialNote(client, state, payload, value, differenceMg!, edit);
if (valid) setQuote({ signature, text: '结算已核对;保存时按最新账务记录确认。', materialText, value });
} catch (e) {
if (valid)
setQuote({
signature,
text: e.name === 'AbortError' ? '结算核对超时,保存时将再次核验。' : '结算核对:' + e.message,
text:
(e as Error).name === 'AbortError'
? '结算核对超时,保存时将再次核验。'
: '结算核对:' + (e as Error).message,
});
}
}, 350);
@@ -240,16 +282,17 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
clearTimeout(timer);
};
}, [client, state, signature, expected, differenceMg, quoteUrl, edit, conflict]);
const pools = useRead(client, exchange ? '/api/material-pools' : null, 0)?.value?.rows || [],
const pools =
useRead<{ rows: MaterialPool[] }>(client, exchange ? '/api/material-pools' : null, 0)?.value?.rows || [],
members = Model.memberOptions(state),
recipients = members.map(([k, t]) => [memberAccountPrefix(k), t]);
function setField(k, v, index = -1) {
function setField<K extends keyof Draft>(k: K, v: Draft[K], index = -1) {
setError('');
setRaw(previous => {
const next = { ...previous },
row = index < 0 ? next : { ...previous.extra_products[index] };
row = index < 0 ? next : { ...previous.extra_products![index] };
row[k] = v;
if (k === 'incoming_weight' && !row.melted_manual) row.melted_weight = v;
if (k === 'incoming_weight' && !row.melted_manual) row.melted_weight = String(v);
if (k === 'melted_weight') row.melted_manual = true;
if (k === 'buy_total') row.buy_total_manual = true;
if (k === 'depreciation_weight') row.depreciation_manual = true;
@@ -259,10 +302,10 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
material_payer: v,
labor_payer: v,
fee_payer: v,
payment_recipient: memberAccountPrefix(v),
payment_recipient: memberAccountPrefix(String(v)),
});
if (k === 'date' && (!row.material_pool_id || row.material_pool_id > v)) row.material_pool_id = v;
if (index >= 0) next.extra_products = next.extra_products.map((item, i) => (i === index ? row : item));
if (k === 'date' && (!row.material_pool_id || row.material_pool_id > String(v))) row.material_pool_id = String(v);
if (index >= 0) next.extra_products = next.extra_products!.map((item, i) => (i === index ? row : item));
return next;
});
}
@@ -279,14 +322,14 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
],
});
}
function remove(i) {
setRaw({ ...d, extra_products: d.extra_products.filter((_, index) => index !== i) });
function remove(i: number) {
setRaw({ ...d, extra_products: d.extra_products!.filter((_, index) => index !== i) });
}
async function daily(name, index = -1) {
async function daily(name: TextField, index = -1) {
const target = live.current;
setRate({ name, index, text: '正在读取当日加权料价…' });
try {
const v = await client.api(
const v = await client.api<MaterialPool & { averageRate: number; totalAmount: number }>(
'/api/material-pools/' + encodeURIComponent(d.date) + '?member=' + encodeURIComponent(d.member),
);
if (!live.current) return;
@@ -307,32 +350,36 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
if (name === 'buy_rate') setField('buy_total_manual', false, index);
setRate({ name, index, text: '已带入 ' + d.date + ' 公共加权 ¥' + value + '/克,可继续手改。' });
} catch (e) {
setRate({ name, index, text: e.message });
setRate({ name, index, text: (e as Error).message });
}
}
const signed = (prefix, k) => prefix + k;
function fields(row = d, index = -1, off = false) {
function fields(row: ProductDraft = d, index = -1, off = false) {
const prefix = index < 0 ? '' : 'extra_',
attrs = (name, props = {}) => ({
name: signed(prefix, name),
attrs = (name: TextField) => ({
name: prefix + name,
value: row[name] ?? '',
onChange: e => setField(name, e.target.value, index),
onChange: (e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
setField(name, e.target.value, index),
disabled: off,
...props,
});
const text = (title, k, limit, attrsMore = {}) => (
const text = (
title: string,
k: TextField,
limit: number,
attrsMore: InputHTMLAttributes<HTMLInputElement> = {},
) => (
<label>
{title}
<input
type="text"
{...attrs(k)}
value={(index < 0 ? raw : raw.extra_products[index])[k] ?? ''}
value={(index < 0 ? raw : raw.extra_products![index])[k] ?? ''}
maxLength={limit}
{...attrsMore}
/>
</label>
);
const num = (title, k, places = 2, props = {}) => (
const num = (title: string, k: TextField, places = 2, props: InputHTMLAttributes<HTMLInputElement> = {}) => (
<label>
{title}
<input
@@ -345,7 +392,12 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
/>
</label>
);
const select = (title, k, choices, props = {}) => (
const select = (
title: string,
k: TextField,
choices: readonly Choice[],
props: SelectHTMLAttributes<HTMLSelectElement> = {},
) => (
<label>
{title}
<select {...attrs(k)} {...props}>
@@ -353,7 +405,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
</select>
</label>
);
const pairs = (title, k, pocket, visible = true, optional = false) => (
const pairs = (title: string, k: TextField, pocket: string, visible = true, optional = false) => (
<label hidden={!visible || !Model.pocketCountsEnabled(state, pocket)}>
{title}
<input
@@ -369,7 +421,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
/>
</label>
);
const rateField = (title, k, use = true, props = {}) => (
const rateField = (title: string, k: TextField, use = true, props: InputHTMLAttributes<HTMLInputElement> = {}) => (
<div className="recovery-customer-rate">
{num(title, k, 2, { required: true, ...props })}
{use && (
@@ -391,7 +443,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
return { attrs, text, num, select, pairs, rateField };
}
const { attrs, text, num, select, pairs } = fields();
function product(row, index) {
function product(row: ProductDraft, index: number) {
const f = fields(row, index, !exchange),
original =
edit?.inputs.exchange?.products?.[index + 1] ||
@@ -443,7 +495,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
</section>
);
}
const available = pools.filter(
const available: PoolChoice[] = pools.filter(
p =>
p.date <= d.date &&
(p.id === d.date ||
@@ -459,7 +511,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
(!edit.permissions.canDirect ||
edit.permissions.requiresApproval ||
(state.user.role !== 'owner' && (edit.inputs.date !== state.today || d.date !== state.today)));
async function submit(e) {
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
try {
const payload = model.validate(model.input(d));
@@ -476,31 +528,31 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
: {}),
});
}
const result = await client.mutate(
const result = await client.mutate<Saved>(
edit ? '/api/recoveries/' + encodeURIComponent(edit.id) + '/update' : '/api/recoveries',
payload,
);
localStorage.removeItem(editKey || key);
saved(payload, result);
} catch (err) {
setError(err.message);
if (edit && [403, 404, 409].includes(err.status)) setConflict({});
setError((err as Error).message);
if (edit && [403, 404, 409].includes((err as ApiError).status ?? 0)) setConflict({});
}
}
function extras(kind, rows, keys, caption) {
function extras<K extends keyof ExtraKinds>(kind: K, rows: ExtraKinds[K][], keys: ExtraFields<K>, caption: string) {
if (!edit) return null;
const prop = kind === 'old' ? 'old_lines' : kind === 'fee' ? 'fee_items' : 'charges',
defaults =
kind === 'old'
? { name: 'Au旧料', incoming_weight: '', melted_weight: '', purity: '100' }
: kind === 'fee'
? { key: 'other', note: '其他费用', amount: '0', payer: d.member }
: { name: '其他收费', amount: '0' };
const change = (i, key, v) =>
setField(
prop,
rows.map((r, num) => (num === i ? { ...r, [key]: v } : r)),
);
defaults: ExtraKinds[K] = {
old: { name: 'Au旧料', incoming_weight: '', melted_weight: '', purity: '100' },
fee: { key: 'other', note: '其他费用', amount: '0', payer: d.member },
charge: { name: '其他收费', amount: '0' },
}[kind];
function updateRows(value: ExtraKinds[K][]) {
setError('');
setRaw(previous => ({ ...previous, [prop]: value }));
}
const change = (i: number, key: keyof ExtraKinds[K], value: string) =>
updateRows(rows.map((r, num) => (num === i ? { ...r, [key]: value } : r)));
return (
<>
{rows.slice(1).map((r, i) => (
@@ -523,7 +575,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
: '费用名称'
: t}
{k === 'payer' ? (
<select name={name} value={r[k] || ''} onChange={e => change(i + 1, k, e.target.value)}>
<select name={name} value={String(r[k] || '')} onChange={e => change(i + 1, k, e.target.value)}>
{options(members)}
</select>
) : (
@@ -536,7 +588,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
step={number ? (kind === 'old' ? '0.001' : '0.01') : undefined}
inputMode={number ? 'decimal' : undefined}
maxLength={number ? undefined : k === 'note' ? 100 : 60}
value={r[k] || ''}
value={String(r[k] || '')}
onChange={e => change(i + 1, k, e.target.value)}
/>
)}
@@ -548,12 +600,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
data-action="recovery-edit-remove-row"
data-kind={kind}
data-index={i + 1}
onClick={() =>
setField(
prop,
rows.filter((_, j) => j !== i + 1),
)
}
onClick={() => updateRows(rows.filter((_, j) => j !== i + 1))}
>
移除这项
</button>
@@ -563,7 +610,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
type="button"
data-action="recovery-edit-add-row"
data-kind={kind}
onClick={() => setField(prop, [...(rows.length ? rows : [defaults]), { ...defaults }])}
onClick={() => updateRows([...(rows.length ? rows : [defaults]), { ...defaults }])}
>
+ 添加{caption}
</button>
@@ -576,10 +623,12 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
<input type="hidden" name="shared_old_notice" value={d.shared_old_notice || ''} />
{!edit && (
<div className="actions">
{[
['direct', '直接回收'],
['exchange', '置换'],
].map(([mode, name]) => (
{(
[
['direct', '直接回收'],
['exchange', '置换'],
] as const
).map(([mode, name]) => (
<button
type="button"
key={mode}
@@ -643,7 +692,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
parts={parts}
quotedItems={quote.signature === signature ? quote.value?.exchangeItems : undefined}
draft={d}
edit={edit}
edit={edit!}
state={state}
fields={fields}
materials={materials}
@@ -738,7 +787,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
<p>每件新货分别填写工费、成本和货盘</p>
<p>上方旧料只录一次,供下面所有新货共同抵扣。补金、折旧和余料按整单统一结算。</p>
<p id="recovery-new-total">
新货共 {1 + (d.extra_products?.length || 0)} 件 · 合计 {newMg === null ? '待填写' : grams(newMg) + 'g'}
新货共 {1 + (d.extra_products?.length || 0)} 件 · 合计 {newMg == null ? '待填写' : grams(newMg) + 'g'}
{old && ' · 共用折后旧料 ' + grams(old.oldMg) + 'g'}
</p>
<datalist id="recovery-product-names">
@@ -959,7 +1008,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
try {
setConflict({ latest: await refreshEdit() });
} catch (e) {
setError(e.message);
setError((e as Error).message);
}
}}
>
@@ -970,7 +1019,7 @@ export function RecoveryForm({ client, state, edit, materials = [], deposit, sav
type="button"
data-action="recovery-edit-keep"
onClick={() => {
setRevision(conflict.latest.revision);
setRevision(conflict.latest!.revision);
setConflict(null);
setField('verified', false);
}}
@@ -1,19 +1,23 @@
import type { ReactNode } from 'react';
import type { LedgerState } from '../../shared';
import type { Draft, Input, Totals, Permission } from './types';
export type Choice = string | readonly (string | boolean)[];
import { useEffect, useRef } from 'react';
import { Model } from '../../shared';
import { grams, yuan } from '../../lib/format';
export const money = value => (value == null ? '待填写' : '¥' + yuan(value));
export const rowLabel = (s, key) => s.pocketCatalog?.find(p => p.key === key)?.name || key;
export function options(pairs) {
export const money = (value?: number | null) => (value == null ? '待填写' : '¥' + yuan(value));
export const rowLabel = (s: LedgerState, key?: string) => s.pocketCatalog?.find(p => p.key === key)?.name || key;
export function options(pairs: readonly Choice[]) {
return pairs.map(opt => {
const [value, text, disabled] = Array.isArray(opt) ? opt : [opt, opt];
const [value, text, disabled] = typeof opt === 'string' ? [opt, opt] : opt;
return (
<option key={value} value={value} disabled={!!disabled}>
<option key={String(value)} value={String(value)} disabled={!!disabled}>
{text}
</option>
);
});
}
export function Head({ eye, title, sub, children }) {
export function Head({ eye, title, sub, children }: { eye: string; title: string; sub: string; children?: ReactNode }) {
return (
<header className="page-heading">
<div>
@@ -25,10 +29,22 @@ export function Head({ eye, title, sub, children }) {
</header>
);
}
export function Modal({ id, title, close, action, children }) {
const ref = useRef(null);
export function Modal({
id,
title,
close,
action,
children,
}: {
id: string;
title: string;
close(): void;
action: string;
children: ReactNode;
}) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
const d = ref.current;
const d = ref.current!;
d.showModal();
return () => d.close();
}, []);
@@ -49,7 +65,7 @@ export function Modal({ id, title, close, action, children }) {
</dialog>
);
}
export function Settlement({ q, draft, input }) {
export function Settlement({ q, draft, input }: { q?: Totals | null; draft?: Draft; input?: Partial<Input> | null }) {
if (!q) return null;
const direct = input?.mode === 'direct' || draft?.mode === 'direct' || q.mode === 'direct',
def = q.defaultPurchaseAmount ?? q.calculatedPurchaseAmount ?? q.purchaseAmount;
@@ -141,9 +157,9 @@ export function Settlement({ q, draft, input }) {
</>
);
}
export function pocketOptions(state, key, historical, blank) {
export function pocketOptions(state: LedgerState, key: string, historical: boolean, blank?: string) {
const active = Model.activePocketKeys(state),
result = active.map(p => [p, rowLabel(state, p)]);
result: (string | boolean)[][] = active.map(p => [p, rowLabel(state, p) || p]);
if (key && !active.includes(key))
result.push([
key,
@@ -152,14 +168,14 @@ export function pocketOptions(state, key, historical, blank) {
]);
return blank ? [['', blank], ...result] : result;
}
export function loadDraft(key) {
export function loadDraft<T>(key: string): T | null {
try {
return JSON.parse(localStorage.getItem(key) || 'null');
} catch {
return null;
}
}
export function LegacyCount({ value }) {
export function LegacyCount({ value }: { value?: Permission }) {
return value?.requiresLegacyCountVerified ? (
<>
<p>{value.legacyCountNotice || '这笔历史记录未记录对数,当前对数按实际盘点基准保留。'}</p>
@@ -1,10 +1,20 @@
import type { LedgerClient } from '../../lib/api';
import type { LedgerState } from '../../shared';
import type { Input, Draft, EditDetail, Calculation, QuoteItem, MaterialPool, RecoveryModel } from './types';
import { Calc, Model } from '../../shared';
import { grams } from '../../lib/format';
import { describeMaterialBalance, describeMaterialSources, validateMaterialQuote } from '../../lib/materialQuote';
import { money } from './controls';
// 与结算报价分开读取料池余额。余额暂不可用时仍可核对已算出的来源、成本和结算。
export async function quotedMaterialNote(client, state, input, result, differenceMg, edit) {
export async function quotedMaterialNote(
client: LedgerClient,
state: LedgerState,
input: Input,
result: QuoteItem,
differenceMg: number,
edit: EditDetail | null,
) {
const material = input.exchange?.cost_material;
if (material?.mode !== 'pool') return '';
const sources = result.exchange?.costMaterial?.materialSources;
@@ -25,7 +35,7 @@ export async function quotedMaterialNote(client, state, input, result, differenc
result.member !== input.member ||
sources.some(s => s.kind === 'personal_recovery' && s.member !== input.member) ||
sources.reduce((sum, s) => sum + s.quantity, 0) !== differenceMg ||
(result.materialCost !== null && sources.reduce((sum, s) => sum + s.amount, 0) !== result.materialCost)
(result.materialCost !== null && sources.reduce((sum, s) => sum + (s.amount ?? 0), 0) !== result.materialCost)
)
throw new Error('置换用料来源与当前归属不一致,请重新核对。');
const request = {
@@ -43,14 +53,21 @@ export async function quotedMaterialNote(client, state, input, result, differenc
balance = '个人与公共余量暂未读到,请刷新核对。';
}
return (
describeMaterialSources(sources, key => Model.memberName(state, key)) +
describeMaterialSources(sources, (key: string) => Model.memberName(state, key)) +
';' +
balance +
(edit ? '原单耗用已排除。' : '')
);
}
export function localMaterialNote(draft, calculation, pools, state, model, edit) {
export function localMaterialNote(
draft: Draft,
calculation: Calculation | null,
pools: MaterialPool[],
state: LedgerState,
model: RecoveryModel,
edit: EditDetail | null,
) {
if (!calculation || draft.mode !== 'exchange') return '填写新旧克重后显示差重料费。';
const { differenceMg, matchedMg } = calculation;
if (!differenceMg) return '等重交换 ' + grams(matchedMg) + 'g,只记实物;无补金差重,不耗用每日料池。';
@@ -1,10 +1,12 @@
import type { LedgerState } from '../../shared';
import type { EditDetail } from './types';
import RecoveryRules from '@public/recovery-rules.js';
import { Model, Calc, Values } from '../../shared';
import { countValue, dateValid as validOrderDate } from '../Inventory/data';
export const memberAccountPrefix = Values.memberAccountPrefix;
export function recoveryModel(state, editData = null) {
export function recoveryModel(state: LedgerState, editData: EditDetail | null = null) {
return RecoveryRules.createModel({
state,
originalInput: editData?.inputs,
@@ -0,0 +1,366 @@
import type { LedgerClient } from '../../lib/api';
import type { LedgerState } from '../../shared';
export interface PageProps {
client: LedgerClient;
state: LedgerState;
}
export type Mode = 'direct' | 'exchange';
export type Filters = { from: string; date: string; mode: string; member: string };
export interface OldLine {
name: string;
incoming_weight: string;
melted_weight: string;
purity: string;
}
export interface Charge {
name: string;
amount: string;
}
export interface Fee {
key: string;
note: string;
amount: string;
payer: string;
}
export type ExtraRow = OldLine | Charge | Fee;
export type ProductDraft = Pick<
Draft,
| 'new_name'
| 'new_quantity'
| 'pocket'
| 'stockCount'
| 'labor_mode'
| 'labor_rate'
| 'cost_labor_mode'
| 'cost_labor_value'
| 'labor_payer'
> &
Partial<Draft>;
export interface Draft {
mode: Mode;
date: string;
customer: string;
customer_type?: string;
salesperson: string;
member: string;
note: string;
old_name: string;
incoming_weight: string;
melted_weight: string;
purity: string;
old_pocket: string;
old_stock_count: string | number;
old_source: string;
deposit_id: string;
deposit_weight: string;
surplus_mode: string;
surplus_memo: string;
buy_rate: string;
buy_total: string;
new_name: string;
new_quantity: string;
pocket: string;
stockCount: string | number;
gold_price: string;
labor_mode: string;
labor_rate: string;
depreciation_weight: string;
depreciation_rate: string;
discount: string;
rounding_mode: string;
material_source: string;
material_pool_id: string;
material_rate: string;
material_payer: string;
labor_payer: string;
cost_payer?: string;
cost_labor_mode: string;
cost_labor_value: string;
fee_note: string;
fee_amount: string;
fee_payer: string;
charge_name: string;
charge_amount: string;
payment_method: string;
payment_recipient: string;
payout_method: string;
payer: string;
buy_total_manual: boolean;
depreciation_manual: boolean;
melted_manual: boolean;
independent_products: boolean;
verified?: boolean;
change_reason?: string;
shared_old_notice?: string;
folded_weight?: string;
extra_products?: ProductDraft[];
old_lines?: OldLine[];
charges?: Charge[];
fee_items?: Fee[];
}
export type TextField = {
[K in keyof Draft]-?: NonNullable<Draft[K]> extends string | number ? K : never;
}[keyof Draft];
export type Labor = { mode: 'gram'; rate: string; amount?: never } | { mode: 'total'; amount: string; rate?: never };
export type Material = { mode: 'pool'; poolId: string; rate?: never } | { mode: 'gram'; rate: string; poolId?: never };
export interface Product {
name: string;
pocket: string;
quantity: string;
labor_rate: string;
labor_mode: string;
stockCount?: number | string | null;
cost_labor?: Labor;
cost_labor_payer: string;
}
export interface Exchange extends Partial<Product> {
gold_price?: string;
depreciation_rate?: string;
depreciation_weight?: string;
discount: string;
rounding_mode: string;
cost_payer?: string;
cost_material?: Material;
cost_material_payer?: string;
charges: Charge[];
fee_items: Fee[];
items?: ItemInput[];
products?: Product[];
}
export interface ItemInput {
old_source?: string;
deposit_id?: string;
deposit_weight?: string;
old_lines: OldLine[];
old_pocket: string;
old_stock_count?: string | number | null;
surplus_mode?: string;
surplus_memo?: string;
buy_rate: string;
buy_total?: string;
exchange: Exchange;
}
export interface Input extends Omit<ItemInput, 'exchange'> {
mode: Mode;
date: string;
customer: string;
customer_type?: string;
salesperson: string;
member: string;
note: string;
payer: string;
payment_account: string;
verified: boolean;
exchange?: Exchange;
}
export interface Totals {
mode: Mode;
oldMg: number;
newMg: number;
matchedMg: number;
surplusMg: number;
depositMg: number;
differenceMg: number;
depreciationMg: number;
depreciationAmount: number;
chargesAmount: number;
discount: number;
receivable: number;
purchaseAmount: number;
goldAmount: number;
laborAmount: number;
roundingAdjustment: number;
netSettlement: number;
cashReceipt: number;
cashPayment: number;
defaultPurchaseAmount?: number;
calculatedPurchaseAmount?: number;
old_lines: { name: string; incomingMg: number; meltedMg: number; foldedMg: number; purity: number }[];
newProduct?: { name: string };
exchangeItems?: Totals[];
}
export interface Calculation extends Totals {
defaultPurchaseAmount: number;
purchaseMg: number;
}
export interface Source {
kind: 'personal_recovery' | 'public';
member?: string;
quantity: number;
amount: number | null;
averageRate?: number | null;
allocations: { payer: string; amount: number }[];
}
export interface QuoteItem extends Totals {
member: string;
materialCost: number | null;
laborCost: number | null;
exchange?: {
costMaterial?: { mode: string; materialSources?: Source[] };
costPayers?: { labor: string; material: string };
fee_items?: { note: string; amount: number; payer: string }[];
};
customerDeposit?: { number: string; mg: number };
exchangeItems?: QuoteItem[];
}
export interface SummaryRow {
id: string;
mode: Mode;
number: string;
date: string;
customer: string;
salesperson: string;
member: string;
oldMg: number;
newMg: number;
netSettlement: number;
printStatus?: { id: string; printed: boolean };
}
interface SavedProduct {
name: string;
quantity: number;
pocket: string;
stockCount?: number | null;
laborAmount?: number;
laborCost: number | null;
laborPayer: string;
}
export interface RecoveryRecord extends SummaryRow, QuoteItem {
status: string;
order_id?: string;
purchase_id?: string;
credit_card_rate_permille?: number | null;
payment_account: string;
payer: string;
note: string;
oldPocket: string;
newProduct?: SavedProduct;
newProducts?: SavedProduct[];
profit: number | null;
materialCostPending?: boolean;
cardFee?: number;
materialBatch?: { member: string; mg: number; usedMg: number; remainingMg: number };
}
export interface Permission {
canCancel: boolean;
canEdit: boolean;
canDirect: boolean;
requiresApproval: boolean;
reason?: string;
requiresLegacyCountVerified?: boolean;
legacyCountNotice?: string;
}
export interface EditDetail {
id: string;
revision: number;
status: string;
record: RecoveryRecord;
inputs: Input;
permissions: Permission;
pending: ChangeRequest | null;
history: ChangeRequest[];
blockedUsages: { anonymous?: boolean; number?: string; mg: number; priceLockId?: string; orderId?: string }[];
}
export type ChangeStatus = 'pending' | 'approved' | 'rejected';
export type MoneySummary = Partial<
Record<'cashReceipt' | 'cashPayment' | 'purchaseAmount' | 'goodsCost' | 'directCost' | 'profit', number | null>
>;
export interface ChangeRequest {
id: string;
recoveryId: string;
member: string;
recoveryRevision: number;
revision: number;
status: ChangeStatus;
action: 'cancel' | 'update';
before: Input;
after: Input | null;
requesterName: string;
reviewerName?: string;
reason: string;
note?: string;
canApprove: boolean;
stale: boolean;
summary: { before?: MoneySummary; after?: MoneySummary; legacyCountNotice?: string; legacyCountVerified?: boolean };
}
export interface ChangeList {
requests: ChangeRequest[];
counts: Record<ChangeStatus, number>;
}
export type Selection = { kind: 'list'; id?: undefined } | { kind: 'request' | 'cancel'; id: string };
export interface Saved {
id: string;
number?: string;
pending?: boolean;
applied?: boolean;
}
export interface Deposit {
id: string;
date: string;
number: string;
memo: string;
mg: number;
usedMg: number;
remainingMg: number;
voided?: boolean;
actor: string;
events: { date: string; memo: string; deltaMg: number; actor: string }[];
}
export interface DepositListData {
rows: Deposit[];
remainingMg: number;
totalMg: number;
usedMg: number;
}
export interface MaterialPool {
id: string;
date: string;
remainingMg: number;
totalMg: number;
totalAmount: number | null;
usages: { active: boolean; mg: number; order_id?: string; line_index: number }[];
personalPools?: Record<string, { remainingMg: number }>;
}
export type PoolChoice = Pick<MaterialPool, 'id' | 'date' | 'totalMg' | 'remainingMg' | 'personalPools'>;
export interface RecoveryContext {
state: LedgerState;
originalInput?: Input | null;
currentMember(): string;
defaultSalesperson(): string;
teamMemberKeys(): string[];
activePocketKeys(): string[];
pocketCountsEnabled(pocket: string): boolean;
stockCountValue(value: unknown, options?: { optional?: boolean; title?: string }): number | null;
validOrderDate(value: string): boolean;
isCreditCardAccount(account: string): boolean;
memberAccountPrefix(member: string): string;
accountIdentity(account: string): { member: string; channel: string } | null;
isSilver(name: string): boolean;
}
export interface RecoveryModel {
defaults(mode?: Mode): Draft;
sharedDraft(draft: Draft): Draft;
forEdit(input: Input): Draft;
input(draft: Draft, options?: { quote?: boolean }): Input;
calculate(input: Input): Calculation;
validate(input: Input): Input;
newWeight(draft: Draft): number;
units(value: unknown, places: number, title: string, options?: { zero?: boolean }): number;
multiply(weight: number, rate: number): number;
checkEdit(data: unknown, id: string): EditDetail;
checkRequest(data: unknown): ChangeRequest;
}
export interface Derived {
draft: Draft;
parts?: Derived[];
input: Input | null;
q: Calculation | null;
error: string;
old?: Calculation | null;
newMg?: number | null;
hasBuy?: boolean;
diff?: boolean;
}
export type ExtraKinds = { old: OldLine; charge: Charge; fee: Fee };
export type ExtraFields<K extends keyof ExtraKinds> = [Extract<keyof ExtraKinds[K], string>, string][];
@@ -1,28 +1,96 @@
import { useEffect, useRef, useState } from 'react';
import type { FormEvent, RefObject } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState } from '../../shared';
import type {
DailyFunds,
ReportQuery,
Range,
ReportAction,
ReimbursementList,
Reimbursement,
ReimbursementItem,
Confirmation,
} from './contracts';
import type { reportPresentation } from './presentation';
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react';
import { Calc, Model } from '../../shared';
import { Button, Choice, Dialog, Field } from '../Settings/controls';
import { errorText } from '../Settings/settingsModel';
const draftsByClient = new WeakMap();
function draftsFor(client, user) {
type View = ReturnType<typeof reportPresentation>;
type DraftItem = Omit<ReimbursementItem, 'amount'> & { amount: string };
interface Draft {
id: string;
revision?: number;
date: string;
items: DraftItem[];
payer?: string;
note: string;
}
interface Review {
id: string;
revision: number;
kind: 'approve' | 'reject';
note: string;
verified: boolean;
}
interface Outlay {
amount: string;
note: string;
verified: boolean;
editing: boolean;
revision: number;
sourceRevision: string;
}
interface Drafts {
user: string;
forms: Map<string, Draft>;
editors: Map<string, string>;
reviews: Map<string, Review>;
outlays: Map<string, Outlay>;
}
interface Props {
client: LedgerClient;
state: LedgerState;
view: View;
data: DailyFunds;
query: ReportQuery & Range;
changeDate: (date: string, reviewId?: string) => void;
reload: () => void;
notify: (text: string, error?: boolean) => void;
actionRef: RefObject<((data: ReportAction) => void) | null>;
}
interface PageReply {
query: { offset: number };
list?: ReimbursementList;
error?: string;
}
type FormKind = 'outlay' | 'draft' | 'review';
type FormError = { kind: FormKind; text: string; conflict?: boolean };
const draftsByClient = new WeakMap<LedgerClient, Drafts>();
function draftsFor(client: LedgerClient, user: string) {
const current = draftsByClient.get(client);
if (current?.user === user) return current;
const drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
const drafts: Drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
draftsByClient.set(client, drafts);
return drafts;
}
function newItem(team) {
function newItem(team: boolean): DraftItem {
return {
name: '',
amount: '',
...(team ? { member: 'owner', sourceType: 'independent', sourceKey: crypto.randomUUID() } : {}),
};
}
function PendingList({ client, view, close, openDate }) {
function PendingList({
client,
view,
close,
openDate,
}: Pick<Props, 'client' | 'view'> & { close: () => void; openDate: (row: Reimbursement) => void }) {
const [query, setQuery] = useState({ offset: 0 }),
[result, setResult] = useState(null);
const validate = useRef(view.validateDailyReimbursements);
validate.current = view.validateDailyReimbursements;
[result, setResult] = useState<PageReply | null>(null);
const validate = useEffectEvent((data: unknown) => view.validateDailyReimbursements(data));
useEffect(() => {
let current = true;
client
@@ -30,7 +98,7 @@ function PendingList({ client, view, close, openDate }) {
'/api/reimbursements?' + new URLSearchParams({ status: 'pending', limit: '50', offset: String(query.offset) }),
)
.then(data => {
const list = validate.current(data);
const list = validate(data);
if (current) setResult({ query, list });
})
.catch(error => {
@@ -134,27 +202,29 @@ function PendingList({ client, view, close, openDate }) {
</Dialog>
);
}
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }) {
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }: Props) {
const cache = draftsFor(client, state.user.id),
key = [state.user.id, query.from, query.date, query.month].join('|');
const [, setTick] = useState(0),
[list, setList] = useState(false),
[error, setError] = useState(null);
[error, setError] = useState<FormError | null>(null);
const redraw = () => setTick(v => v + 1);
const team = view.teamMode(),
owner = state.user.role === 'owner',
month = query.month || data?.readOnly;
const blocked = client.busy || !!client.pending() || !data;
const formKey = cache.editors.get(key),
draft = cache.forms.get(formKey),
draft = formKey ? cache.forms.get(formKey) : undefined,
review = cache.reviews.get(key);
const row = data?.reimbursements.find(r => r.id === review?.id),
active = state.user.member || view.currentMember();
const memberOptions = view.teamMemberOptions(),
memberName = id => (state.members || []).find(m => m.member === id)?.label || id;
memberName = (id?: string) => (state.members || []).find(m => m.member === id)?.label || id;
const period = query.month ? query.from + ' 至 ' + query.date : query.date;
const currentView = useRef(key);
currentView.current = key;
useLayoutEffect(() => {
currentView.current = key;
}, [key]);
const out = cache.outlays.get(key);
useEffect(() => {
if (!data) return;
@@ -187,9 +257,9 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
}
redraw();
}, [data, key, cache, owner, query.month, query.reviewId]);
function action({ action, id, date }) {
function action({ action, id, date }: ReportAction) {
if (action === 'daily-funds-open-date') {
changeDate(date);
if (date) changeDate(date);
return;
}
if (action === 'reimbursement-open-list') {
@@ -223,7 +293,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
if (action === 'reimbursement-approve' || action === 'reimbursement-reject') {
if (!owner || !record?.canApprove || record.status !== 'pending') return;
cache.reviews.set(key, {
id,
id: record.id,
revision: record.revision,
kind: action === 'reimbursement-approve' ? 'approve' : 'reject',
note: '',
@@ -243,14 +313,24 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
actionRef.current = null;
};
});
function set(obj, field, value) {
function set<O, K extends keyof O>(obj: O, field: K, value: O[K]) {
obj[field] = value;
redraw();
}
async function submit(event, kind) {
async function submit(event: FormEvent, kind: FormKind) {
event.preventDefault();
if (blocked || month) return;
let url, input, notice;
let url: string, notice: string;
let input: {
date?: string;
revision?: number;
note: string;
verified?: boolean;
amount?: string;
sourceRevision?: string;
payer?: string;
items?: DraftItem[];
};
try {
if (kind === 'outlay') {
if (!owner || !out) throw new Error('完整支出由店主确认。');
@@ -305,7 +385,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
};
notice = '报销单已提交,等待店主复核';
} else {
if (!owner || !row?.canApprove || row.status !== 'pending' || row.revision !== review.revision)
if (!review || !owner || !row?.canApprove || row.status !== 'pending' || row.revision !== review.revision)
throw new Error('报销单已变化,请重新读取后复核。');
const note = review.note.trim();
if (note.length > 300 || (review.kind === 'reject' && !note))
@@ -321,13 +401,23 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
: '报销已批准,已计入报销日期的应转合计';
}
setError(null);
const result = await client.mutate(url, input);
if (kind === 'draft') {
const result = await client.mutate<{
confirmation?: Pick<Confirmation, 'revision' | 'sourceRevision'>;
reimbursement?: { date: string };
date?: string;
}>(url, input);
if (kind === 'draft' && formKey) {
cache.forms.delete(formKey);
cache.editors.delete(key);
}
if (kind === 'review') cache.reviews.delete(key);
if (kind === 'outlay') {
if (kind === 'outlay' && out) {
if (
!result.confirmation ||
!Number.isSafeInteger(result.confirmation.revision) ||
typeof result.confirmation.sourceRevision !== 'string'
)
throw new Error('实际支出已提交,确认回执未完整返回,请重新读取后核对。');
out.editing = false;
out.verified = false;
out.revision = result.confirmation.revision;
@@ -338,15 +428,16 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
notify(notice + (date && date !== query.date ? '(' + date + ')' : ''));
} catch (err) {
if (currentView.current !== key) return;
setError({ kind, text: errorText(err), conflict: err.status === 409 });
const conflict = err instanceof Error && 'status' in err && err.status === 409;
setError({ kind, text: errorText(err), conflict });
notify(errorText(err), true);
if (err.status === 409) {
if (conflict) {
if (review) review.verified = false;
reload();
}
}
}
const errBox = (id, kind) => (
const errBox = (id: string, kind: FormKind) => (
<div id={id} aria-live="polite">
{error?.kind === kind && (
<div className="error">
@@ -357,7 +448,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
onClick={async () => {
try {
await client.retryPending();
if (kind === 'draft') {
if (kind === 'draft' && formKey) {
cache.forms.delete(formKey);
cache.editors.delete(key);
}
@@ -382,7 +473,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
)}
</div>
);
const btn = (text, name, primary = false) => (
const btn = (text: string, name: string, primary = false) => (
<Button
className={primary ? 'primary' : 'quiet'}
action={name}
@@ -392,7 +483,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
{text}
</Button>
);
const total = draft ? view.reimbursementDraftTotal(draft.items) : null;
const total = view.reimbursementDraftTotal(draft?.items ?? []);
return (
<>
{!team && (
-5
View File
@@ -1,5 +0,0 @@
import type { JSX } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { LedgerState, SessionInfo } from '../../shared';
export function ReportPage(props: { client: LedgerClient; state: LedgerState; session: SessionInfo }): JSX.Element;
export default ReportPage;
@@ -1,4 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { LedgerClient } from '../../lib/api';
import type { ReportContext, ReportQuery, ReportAction, Report, Range } from './contracts';
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react';
import { navigate } from '../../lib/router';
import { useClientSnapshot } from '../../lib/useClient';
import { Button, Choice } from '../Settings/controls';
@@ -7,20 +9,24 @@ import { reportPresentation } from './presentation';
import { Reimbursements } from './Reimbursements';
import './report.css';
const savedQueries = new WeakMap();
export function ReportPage({ client, state, session }) {
type ReportProps = Pick<ReportContext, 'state' | 'session'> & { client: LedgerClient };
type Reply = { query: ReportQuery; version: number } & (
{ error: string; data?: never; fundsError?: never } | { data: Report; fundsError: string; error?: never }
);
const savedQueries = new WeakMap<LedgerClient, Map<string, ReportQuery>>();
export function ReportPage({ client, state, session }: ReportProps) {
useClientSnapshot(client);
const user = state.user.id;
const [query, setQuery] = useState(
const [query, setQuery] = useState<ReportQuery>(
() => savedQueries.get(client)?.get(user) || { date: state.today, month: false, member: '' },
);
const [version, setVersion] = useState(0),
[reply, setReply] = useState(null),
[notice, setNotice] = useState(null);
const daily = useRef(null),
actions = useRef(null);
[reply, setReply] = useState<Reply | null>(null),
[notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
const daily = useRef<((value: ReportAction) => void) | null>(null),
actions = useRef<((value: ReportAction) => void) | null>(null);
const reload = useCallback(() => setVersion(v => v + 1), []);
const dispatch = useCallback(data => actions.current(data), []);
const dispatch = useCallback((data: ReportAction) => actions.current?.(data), []);
const view = reportPresentation({
state,
session,
@@ -28,16 +34,16 @@ export function ReportPage({ client, state, session }) {
reportMember: query.member,
onAction: dispatch,
});
const viewRef = useRef(view);
viewRef.current = view;
const currentModel = useEffectEvent(() => view);
const from = query.month ? query.date.slice(0, 7) + '-01' : query.date;
const range = { ...query, from };
const ready = reply?.query === query && reply.version === version ? reply : null;
const notify = (text, error = false) => setNotice({ text, error });
const change = d => {
const notify = (text: string, error = false) => setNotice({ text, error });
const change = (d: Partial<ReportQuery>) => {
const n = { ...query, reviewId: undefined, ...d };
if (!savedQueries.has(client)) savedQueries.set(client, new Map());
savedQueries.get(client).set(user, n);
const queries = savedQueries.get(client) ?? new Map<string, ReportQuery>();
queries.set(user, n);
savedQueries.set(client, queries);
setQuery(n);
setNotice(null);
};
@@ -45,7 +51,7 @@ export function ReportPage({ client, state, session }) {
let active = true;
async function load() {
try {
const model = viewRef.current;
const model: ReturnType<typeof reportPresentation> = currentModel();
if (!model.validOrderDate(query.date)) throw new Error('请选择有效的对账日期。');
if (query.date > state.today) throw new Error('请选择今天或之前的日期。');
const data = await client.api(
@@ -58,7 +64,8 @@ export function ReportPage({ client, state, session }) {
}),
);
if (!active) return;
model.validateReport(data, { from, date: query.date });
const validate: (input: unknown, range: Range) => asserts input is Report = model.validateReport;
validate(data, { from, date: query.date });
let fundsError = '';
try {
model.validateDailyFunds(data.dailyFunds, { ...query, from });
@@ -68,7 +75,11 @@ export function ReportPage({ client, state, session }) {
setReply({ data, fundsError, query, version });
} catch (err) {
if (active)
setReply({ error: err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err), query, version });
setReply({
error: err instanceof Error && err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err),
query,
version,
});
}
}
void load();
@@ -76,20 +87,23 @@ export function ReportPage({ client, state, session }) {
active = false;
};
}, [client, state.today, state.user.role, user, from, query, version]);
async function action({ action, id, date }) {
async function action({ action, id, date }: ReportAction) {
try {
if (action === 'report-retry' || action === 'daily-funds-retry') {
reload();
return;
}
if (action === 'open-order') return navigate('orders', { search: '?order=' + encodeURIComponent(id) });
if (action === 'after-sale-edit') return navigate('orders', { search: '?afterSale=' + encodeURIComponent(id) });
if (action === 'open-price-lock') return navigate('price-locks', { search: '?lock=' + encodeURIComponent(id) });
if (action === 'recovery-open') return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(id) });
if (action === 'open-order') return navigate('orders', { search: '?order=' + encodeURIComponent(String(id)) });
if (action === 'after-sale-edit')
return navigate('orders', { search: '?afterSale=' + encodeURIComponent(String(id)) });
if (action === 'open-price-lock')
return navigate('price-locks', { search: '?lock=' + encodeURIComponent(String(id)) });
if (action === 'recovery-open')
return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(String(id)) });
if (action === 'goto-material-pools')
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(id) : '' });
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(String(id)) : '' });
if (action === 'recovery-print') {
window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
window.open('/print/recoveries/' + encodeURIComponent(String(id)), '_blank', 'noopener');
notify('客户打印页已打开;若未出现,请允许此网站打开新窗口');
return;
}
@@ -116,7 +130,9 @@ export function ReportPage({ client, state, session }) {
notify(errorText(err), true);
}
}
actions.current = action;
useLayoutEffect(() => {
actions.current = action;
});
return (
<div
className="report-page"
@@ -0,0 +1,604 @@
import type { LedgerState, SessionInfo } from '../../shared';
export interface Range {
date: string;
from: string;
month?: boolean;
}
export interface ReportQuery {
date: string;
month: boolean;
member: string;
reviewId?: string;
}
export interface ReportContext {
state: LedgerState;
session: SessionInfo;
reportMonth: boolean;
reportMember: string;
}
export interface RuleContext {
state: Pick<LedgerState, 'user'>;
reportMember: string;
teamDataKeys: (data: object) => string[];
teamMode: () => boolean;
currentMember: () => string;
teamMemberKeys: () => string[];
isReimbursementStatus: (status: string) => boolean;
validOrderDate: (value: unknown) => boolean;
}
export interface ReportAction {
action?: string;
id?: string;
date?: string;
}
export type Amount = number | null;
export interface Receipts {
receipt: number;
refund: number;
net: number;
}
export interface Account extends Receipts {
account: string;
recipient: string;
channel: string;
entryCount: number;
}
export interface ReceiptItem {
id: string;
kind: string;
amount: number;
account: string;
date: string;
order_id: string | null;
order_date: string | null;
price_lock_id: string | null;
order_after_sale?: boolean;
note?: string;
paper_number?: string | null;
number: string;
reference?: string;
customer: string;
product?: string;
}
export interface MemberReceipts extends Receipts {
name: string;
items: ReceiptItem[];
}
export interface RecipientReceipts extends MemberReceipts {
recipient: string;
}
export interface OwnershipReceipts extends MemberReceipts {
member: string;
accounts: Account[];
}
export interface CostItem {
id: string;
kind: string;
name: string;
source: string;
amount: Amount;
payer: string;
date: string;
number: string;
paper_number?: string;
customer: string;
order_id?: string;
price_lock_id?: string;
component: string;
materialPoolId?: string | null;
nonCash?: boolean;
afterSaleExpense?: boolean;
paidDate?: string;
after_sale_id?: string;
pool_id?: string;
product?: string;
quantity?: number;
calculation?: { rate: number; quantity: number; weighted?: boolean } | null;
}
export interface PayerCosts {
name: string;
goods: number;
paidFees: number;
total: number;
missingCount: number;
pendingCount: number;
items: CostItem[];
}
export interface Allocation {
payer: string;
amount: number;
}
export interface ReturnedLine {
lineIndex: number;
name: string;
materialAllocations: Allocation[];
restockedLaborAllocations: Allocation[];
materialReturnedCost: number;
laborRestockedCost: number;
}
export interface OrderAfterSale {
date: string;
order_id?: string;
orderId?: string;
original: { total: number };
originalOrder?: { total: number };
summary: {
lines: ReturnedLine[];
materialReturnedCost: number;
laborRestockedCost: number;
retainedAmount: number;
profitAdjustment: number;
};
}
export interface Row {
id: string;
kind: string;
member: string;
date: string;
status: string;
order_date?: string;
orderAfterSale: OrderAfterSale;
sale: Amount;
totalCost: Amount;
profit: Amount;
known: Record<string, number>;
costItems: CostItem[];
material: Amount;
laborAndFees: Amount;
number: string;
paper_number?: string;
customer: string;
costHint?: string;
note?: string;
project?: string;
order_id?: string;
recovery_id?: string;
recovery_mode?: string;
cashPayment: number;
payer?: string;
after_sale_id?: string;
price_lock_id?: string;
}
export interface Summary {
orderCount: number;
completedCount: number;
returnedCount: number;
cancelledCount: number;
draftCount: number;
afterSaleCount: number;
sale: number;
totalCost: number;
profit: number;
missingCosts: number;
pendingCosts: number;
unknownProfitCount: number;
unknownCostCount: number;
knownCounts: Record<string, number>;
unknownCounts: Record<string, number>;
}
export interface Profit {
recordCount: number;
orderCount: number;
afterSaleCount: number;
draftCount: number;
unknownCostCount: number;
unknownProfitCount: number;
sales: number;
knownTotalCost: number;
knownProfit: number;
incomplete: boolean;
totalCost: Amount;
profit: Amount;
}
export interface ProfitRow extends Profit {
name: string;
member: string;
date: string;
}
export interface ProfitTable extends Range {
basis: string;
rows: ProfitRow[];
summary: Profit;
}
export interface BusinessCost {
member: string;
name: string;
totalCost: Amount;
knownTotalCost: number;
missingCount: number;
pendingCount: number;
}
export interface MaterialValue {
amount: Amount;
knownAmount: number;
}
export interface MaterialSource extends MaterialValue {
kind: string;
member: string;
priceLocked: boolean;
mg: number;
averageRate: Amount;
missingCount: number;
}
export interface PoolDay extends MaterialValue {
date: string;
poolId: string;
mg: number;
averageRate: Amount;
missingCount: number;
byPayer: Record<string, MaterialValue>;
sources?: MaterialSource[];
}
export interface PoolMaterial extends MaterialValue {
mg: number;
missingCount: number;
byPayer: Record<string, MaterialValue>;
hasPriceLocks: boolean;
days: PoolDay[];
otherCosts: MaterialValue;
}
export interface AdvanceItem {
id: string;
date: string;
kind: string;
number: string;
paperNumber: string;
customer: string;
name: string;
source: string;
component: string;
poolMaterial: boolean;
poolId: string | null;
allocationPending: boolean;
nonCash?: boolean;
status: 'recorded' | 'missing' | 'pending';
amount: Amount;
estimatedAmount: Amount;
}
export interface AdvanceDay {
date: string;
items: AdvanceItem[];
amount: Amount;
knownAmount: number;
missingCount: number;
pendingCount: number;
poolAmount: Amount;
knownPoolAmount: number;
otherAmount: Amount;
knownOtherAmount: number;
}
export interface CurrentDay {
date: string;
recordCount: number;
knownMaterialCost: number;
knownOtherCost: number;
knownProfit: number;
ownerNetReceipts: number;
missingCostCount: number;
pendingCostCount: number;
unknownProfitCount: number;
incomplete: boolean;
materialCost: Amount;
otherCost: Amount;
profit: Amount;
knownAmount: number;
amount: Amount;
}
export interface Counterpart {
member: string;
name: string;
dueOut: number;
dueIn: number;
offset: number;
openingDue: number;
periodNew: number;
periodTransferred: number;
closingDue: number;
period: { obligationNet: number; transferred: number; receivedForNet: number; advancedNet: number };
}
export interface Business extends Range {
member: string;
name: string;
basis: string;
recordCount: number;
orderCount: number;
afterSaleCount: number;
draftCount: number;
sales: number;
netReceipts: number;
totalCost: Amount;
knownTotalCost: number;
selfCost: Amount;
knownSelfCost: number;
otherCost: Amount;
knownOtherCost: number;
profit: Amount;
knownProfit: number;
missingCostCount: number;
pendingCostCount: number;
unknownProfitCount: number;
incomplete: boolean;
hasActivity: boolean;
costByPayer: Record<string, BusinessCost>;
poolMaterial: PoolMaterial;
ownerAdvances: Range & { basis: string; days: AdvanceDay[] };
currentAccount: Range & { basis: string; days: CurrentDay[] };
difference: { amount: number; reconciled: boolean; reasons: { code: string; text: string }[] };
equation: { basis: string; revenue: number; totalCost: Amount; profit: Amount; complete: boolean };
settlement: Range & {
available: boolean;
basis: string;
partial: boolean;
pendingCount: number;
legacyCount: number;
notice: string;
counterparts: Counterpart[];
dueIn: Amount;
dueOut: Amount;
};
}
export interface DailySource {
id: string;
date: string;
sourceType: string;
sourceId: string;
payer: string;
name: string;
note: string;
amount: number;
}
export interface Sources {
revision: string;
total: number;
items: DailySource[];
}
export interface Confirmation {
date: string;
amount: number;
revision: number;
sourceRevision: string;
note: string;
actor: string;
stale: boolean;
}
export interface FundsDay {
date: string;
ownerReceipts: Receipts;
approvedReimbursements: number;
actualOutlay: Amount;
confirmation: Confirmation | null;
sources: Sources;
ready: boolean;
transferAmount: Amount;
direction: string | null;
hasActivity: boolean;
}
export interface ReimbursementItem {
id?: string;
availableAmount?: number;
name: string;
amount: number;
member?: string;
sourceType?: string;
sourceKey?: string;
usedAmount?: number;
remainingAmount?: number;
}
export type ReimbursementStatus = 'pending' | 'approved' | 'rejected';
export interface Reimbursement {
id: string;
date: string;
status: ReimbursementStatus;
revision: number;
canEdit: boolean;
canApprove: boolean;
items: ReimbursementItem[];
total: number;
note: string;
requester_name: string;
reviewer_name: string;
review_note: string;
payer?: string;
member?: string;
}
export interface ReimbursementList {
requests: Reimbursement[];
total: number;
offset: number;
limit: number;
hasMore: boolean;
counts: Record<ReimbursementStatus, number>;
}
export interface TeamPair {
members: string[];
net: number;
obligationNet: number;
transferred: number;
due: number;
entries: unknown[];
}
export interface Team {
from: string;
to: string;
revision: string | number;
pairs: TeamPair[];
balances: unknown[];
transfers: unknown[];
}
export interface DailyFunds extends Range, FundsDay {
team?: Team;
readOnly: boolean;
hasRecords: boolean;
pendingCount: number;
reimbursements: Reimbursement[];
missingDates: string[];
staleDates: string[];
days: FundsDay[];
transfersNotDeducted: boolean;
rangeUnsupported?: boolean;
}
export interface PriceActivityItem {
id: string;
date: string;
kind: string;
amount: number;
account: string;
payer: string;
quantity: number;
rate: number;
product: string;
customer: string;
note: string;
name: string;
source: string;
price_lock_id: string;
order_id: string;
number: string;
paper_number: string;
component: string;
actor: string;
line_index: number;
}
export interface PriceActivity extends Range {
customerCash: PriceActivityItem[];
orderPayments: PriceActivityItem[];
materialOutlays: PriceActivityItem[];
deliveryGoodsOutlays: PriceActivityItem[];
directOutlays: PriceActivityItem[];
summary: {
eventCount: number;
receipt: number;
refund: number;
net: number;
materialOutlay: number;
goodsOutlay: number;
feeOutlay: number;
totalOutlay: number;
ownerOutlay: number;
assistantOutlay: number;
};
}
export interface MaterialPurchase {
id: string;
pool_id: string;
date: string;
mg: number;
amount: number;
payer?: string;
actualpayer?: string;
actualPayer?: string;
note: string;
}
export interface PoolActivity extends Range {
purchases: MaterialPurchase[];
summary: {
eventCount: number;
purchaseCount: number;
poolCount: number;
mg: number;
materialOutlay: number;
purchaseValue: number;
ownerOutlay: number;
assistantOutlay: number;
};
}
export interface PoolSettlement {
legacyReadOnly?: boolean;
assistantInventoryCredit: Amount;
knownAssistantInventoryCredit: number;
transferred: number;
settlementDue: Amount;
knownSettlementDue: number;
pendingCount: number;
pools: {
id: string;
date: string;
assistantInventoryCredit: Amount;
transferred: number;
settlementDue: Amount;
pending: boolean;
}[];
}
export interface InventoryBalance {
pocket: string;
mg: number;
reserved: number;
available: number;
countUnit?: string;
count?: number | null;
}
export interface PeoplePart {
total: Amount;
endTotal: Amount;
baselineTotal: Amount;
baselineDate: string;
netChange: Amount;
netChangeReason: string;
recordedDays: number;
}
export type PeopleCount = Range &
PeoplePart & { [key: string]: string | number | boolean | null | PeoplePart | undefined };
export interface Report extends Range {
basis: string;
summary: Summary;
orderRows: Row[];
accounts: Account[];
payerCosts: Record<string, PayerCosts>;
recipientReceipts: Record<string, RecipientReceipts>;
ownershipReceipts: Record<string, OwnershipReceipts>;
ownershipBusiness: Record<string, Business>;
receiptsByOrderDate: Receipts & {
channels: (Receipts & { name: string; channel: string })[];
accounts: Account[];
paymentCount: number;
orderCount: number;
};
dailyProfits: ProfitTable;
dailyFunds: DailyFunds;
peopleCount: PeopleCount;
priceLockActivity: PriceActivity | null;
materialPoolActivity: PoolActivity | null;
materialPoolSettlement: PoolSettlement | null;
goods: number;
expense: number;
outlayGoods: number;
outlayExpense: number;
outlayTotal: number;
customerBalance: number;
settlementDue: Amount;
knownSettlementDue: number;
pendingMaterialCount: number;
inventory: InventoryBalance[];
warnings: { id: string; number: string; message: string }[];
unsettled: {
id: string;
number: string;
customer: string;
costDue: Amount;
profitDue: Amount;
ownerGoods: Amount;
ownerDirect: number;
total: Amount;
}[];
close: { date: string; actor: string; created: string; stale: boolean; staleReason: string } | null;
}
export type Metric = 'sale' | 'totalCost' | 'profit';
export type RowMetric = Metric | 'goods' | 'paidFees' | 'material' | 'laborAndFees';
export type CurrentDisplayDay = Pick<
CurrentDay,
| 'date'
| 'materialCost'
| 'knownMaterialCost'
| 'otherCost'
| 'knownOtherCost'
| 'profit'
| 'knownProfit'
| 'ownerNetReceipts'
| 'amount'
| 'incomplete'
>;
export interface RecoveryCosts {
byPayer: Record<string, number>;
items: CostItem[];
}
@@ -1,9 +1,18 @@
import type { ReactNode } from 'react';
import type * as T from './contracts';
import { Children } from 'react';
import { reportData } from './reportData';
const withKeys = Children.toArray;
const fallback = (rows, empty) => (rows.length ? rows : empty);
const e = value => (value == null ? '' : String(value));
export function reportPresentation({ state, session, reportMonth, reportMember, onAction, dailyFundsLoading = false }) {
const fallback = (rows: ReactNode[], empty: ReactNode) => (rows.length ? rows : empty);
const e = (value: unknown) => (value == null ? '' : String(value));
export function reportPresentation({
state,
session,
reportMonth,
reportMember,
onAction,
dailyFundsLoading = false,
}: T.ReportContext & { onAction: (data: T.ReportAction) => void; dailyFundsLoading?: boolean }) {
const model = reportData({ state, session, reportMonth, reportMember });
const {
reportSummaryAmount,
@@ -51,7 +60,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
reportPoolMaterialFormula,
reportPoolMaterialSourceLabel,
} = model;
function renderReportContent(r, range) {
function renderReportContent(r: T.Report, range: T.Range) {
const s = r.summary,
receipts = r.receiptsByOrderDate,
profitMissing = s.unknownProfitCount || 0;
@@ -116,7 +125,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="4" className="muted">
<td colSpan={4} className="muted">
所选范围没有收退款活动账户。
</td>
</tr>,
@@ -228,9 +237,9 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportDailyProfits(r) {
function renderReportDailyProfits(r: T.Report) {
const table = r.dailyProfits,
amounts = row => (
amounts = (row: T.Profit) => (
<>
<td className="number">¥{yuan(row.sales)}</td>
<td className="number">{reportDailyProfitAmount(row.totalCost, row.knownTotalCost)}</td>
@@ -280,7 +289,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="5" className="muted">
<td colSpan={5} className="muted">
所选范围暂无订单或售后记录。
</td>
</tr>,
@@ -288,7 +297,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
</tbody>
<tfoot>
<tr>
<td colSpan="2">所选范围合计</td>
<td colSpan={2}>所选范围合计</td>
{amounts(table.summary)}
</tr>
</tfoot>
@@ -302,7 +311,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReimbursementRows(data, readOnly) {
function renderReimbursementRows(data: T.DailyFunds, readOnly: boolean) {
return (
<div className="reimbursement-records">
{fallback(
@@ -389,7 +398,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderDailyFundsMonth(data) {
function renderDailyFundsMonth(data: T.DailyFunds) {
return (
<>
<p className="small muted">月汇总只读。按每张报销单的报销日期归集,跨日批准仍回到原日期。</p>
@@ -440,7 +449,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="6" className="muted">
<td colSpan={6} className="muted">
所选范围暂无需核对的记录。可切换单日确认。
</td>
</tr>,
@@ -452,7 +461,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderDailyFundsSources(data) {
function renderDailyFundsSources(data: T.DailyFunds) {
return (
<details className="daily-funds-sources">
<summary>
@@ -487,7 +496,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="3" className="muted">
<td colSpan={3} className="muted">
暂无已记录付款;这不代表当天完整支出一定为 0。
</td>
</tr>,
@@ -499,12 +508,12 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderDailyTransferResult(data, month = false) {
function renderDailyTransferResult(data: T.DailyFunds, month = false) {
const ready = data.ready && !dailyFundsLoading;
const direction =
data.transferAmount > 0
(data.transferAmount ?? 0) > 0
? teamMemberName('owner') + '转' + teamMemberName('assistant')
: data.transferAmount < 0
: (data.transferAmount ?? 0) < 0
? teamMemberName('assistant') + '转' + teamMemberName('owner')
: '无需转款';
return (
@@ -535,7 +544,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
<span>
{month ? '本期' : '本日'}应转合计 · {direction}
</span>
<strong>¥{yuan(Math.abs(data.transferAmount))}</strong>
<strong>¥{yuan(Math.abs(data.transferAmount ?? 0))}</strong>
<p>
{teamMemberName('owner')}净收款 ¥{yuan(data.ownerReceipts.net)} − 确认对外支出 ¥{yuan(data.actualOutlay)}{' '}
+ 已批准报销 ¥{yuan(data.approvedReimbursements)} = <b>¥{yuan(data.transferAmount)}</b>
@@ -555,7 +564,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReimbursementItems(row) {
function renderReimbursementItems(row: T.Reimbursement) {
return (
<ul className="reimbursement-items-read">
{withKeys(
@@ -581,7 +590,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnershipReceipts(r, range) {
function renderReportOwnershipReceipts(r: T.Report, range: T.Range) {
const keys = reportOwnershipKeys(r);
return (
<section className="report-receipts report-ownership-receipts" aria-label="按订单归属汇总净收入">
@@ -638,7 +647,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
const card = (title, value, hint = '', emphasis = false) => (
const card = (title: ReactNode, value: ReactNode, hint: ReactNode = '', emphasis = false) => (
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
<small>{title}</small>
<strong>{value}</strong>
@@ -646,7 +655,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
</div>
);
function renderReportPayerCosts(r) {
function renderReportPayerCosts(r: T.Report) {
const people = teamDataKeys(r.payerCosts).map(key => r.payerCosts[key]),
missing = people.reduce((sum, c) => sum + c.missingCount, 0),
pending = people.reduce((sum, c) => sum + c.pendingCount, 0);
@@ -713,7 +722,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderPriceLockActivity(activity) {
function renderPriceLockActivity(activity: T.PriceActivity | null) {
if (!activity?.summary?.eventCount) return '';
const s = activity.summary,
rows = priceLockActivityRows(activity);
@@ -783,7 +792,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderMaterialPoolActivity(activity) {
function renderMaterialPoolActivity(activity: T.PoolActivity | null) {
if (!activity?.purchases?.length) return '';
return (
<section className="panel material-report-activity">
@@ -830,7 +839,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOrderNet(r, range) {
function renderReportOrderNet(r: T.Report, range: T.Range) {
const s = r.summary;
return (
<section className="panel report-order-net">
@@ -870,7 +879,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
</td>
<td>{badge(row)}</td>
{withKeys(
['sale', 'goods', 'paidFees', 'totalCost', 'profit'].map(key => (
(['sale', 'goods', 'paidFees', 'totalCost', 'profit'] as const).map(key => (
<td className="number">{reportRowAmount(row, key)}</td>
)),
)}
@@ -878,7 +887,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="7" className="muted">
<td colSpan={7} className="muted">
所选日期没有订单或售后记录。
</td>
</tr>,
@@ -886,7 +895,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
</tbody>
<tfoot>
<tr>
<td colSpan="2">
<td colSpan={2}>
销售 {s.orderCount} 单 · 售后 {s.afterSaleCount || 0} 笔
</td>
<td className="number">{reportSummaryAmount(s, 'sale')}</td>
@@ -902,7 +911,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportGlobal(r) {
function renderReportGlobal(r: T.Report) {
if (teamMode())
return (
<section className="panel">
@@ -960,7 +969,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportUnsettled(r) {
function renderReportUnsettled(r: T.Report) {
return (
<section className="panel report-unsettled">
<h2>逐单交款与返款(截至现在)</h2>
@@ -1002,7 +1011,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="5">目前没有待结款项。</td>
<td colSpan={5}>目前没有待结款项。</td>
</tr>,
)}
</tbody>
@@ -1012,7 +1021,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderMaterialPoolGlobalSettlement(value) {
function renderMaterialPoolGlobalSettlement(value: T.PoolSettlement | null) {
if (!value?.pools?.length) return '';
return (
<section className="panel material-report-settlement">
@@ -1048,7 +1057,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
<td className="number">¥{yuan(item.transferred)}</td>
<td className="number">
{materialReportMoney(item.settlementDue)}
{item.settlementDue < 0 ? (
{(item.settlementDue ?? 0) < 0 ? (
<>
<>
<>
@@ -1062,7 +1071,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
</>
{'</div>'}
</>
) : item.settlementDue > 0 ? (
) : (item.settlementDue ?? 0) > 0 ? (
<>
<>
<>
@@ -1099,11 +1108,11 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnershipAccounts(person) {
function renderReportOwnershipAccounts(person: T.OwnershipReceipts) {
const ownAccounts = person.accounts.filter(account => account.recipient === person.member),
otherAccounts = person.accounts.filter(account => account.recipient !== person.member),
net = accounts => accounts.reduce((total, account) => total + account.net, 0);
const group = (title, rows) => (
net = (accounts: T.Account[]) => accounts.reduce((total, account) => total + account.net, 0);
const group = (title: string, rows: T.Account[]) => (
<section className="report-ownership-account-group">
<h3>{title}</h3>
{rows.length ? (
@@ -1149,7 +1158,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnershipBusiness(business, range) {
function renderReportOwnershipBusiness(business: T.Business, range: T.Range) {
return (
<>
<>
@@ -1164,7 +1173,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportRecipientDetails(person, kind = 'receipt') {
function renderReportRecipientDetails(person: T.MemberReceipts, kind: 'receipt' | 'refund' = 'receipt') {
const items = person.items.filter(item => item.kind === kind),
name = kind === 'receipt' ? '收款' : '退款';
return (
@@ -1175,7 +1184,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
{items.length} 笔{items.some(item => item.amount < 0) ? ',含冲回' : ''}
</span>
</summary>
<div className="table-wrap" tabIndex="0" role="region" aria-label={person.name + name + '明细表'}>
<div className="table-wrap" tabIndex={0} role="region" aria-label={person.name + name + '明细表'}>
<table className="report-receipt-table" aria-label={person.name + name + '逐笔明细'}>
<thead>
<tr>
@@ -1211,7 +1220,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="4" className="muted">
<td colSpan={4} className="muted">
所选范围没有{person.name}
{name}记录。
</td>
@@ -1220,7 +1229,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
</tbody>
<tfoot>
<tr>
<td colSpan="3">{name}明细合计</td>
<td colSpan={3}>{name}明细合计</td>
<td className="number">¥{yuan(person[kind])}</td>
</tr>
</tfoot>
@@ -1230,7 +1239,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function reportAfterSaleHint(cost) {
function reportAfterSaleHint(cost: T.PayerCosts) {
return cost.items.some(item => item.kind === 'afterSale') ? (
<div className="small muted">其中售后 ¥{yuan(reportAfterSaleAmount(cost))}</div>
) : (
@@ -1238,7 +1247,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function reportCostDetails(cost) {
function reportCostDetails(cost: T.PayerCosts) {
const items = reportCostItems(cost);
return (
<details className="report-cost-detail">
@@ -1297,7 +1306,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
)),
),
<tr>
<td colSpan="3" className="muted">
<td colSpan={3} className="muted">
没有需逐项核对的成本。货品成本为 0 的分项已省略。
</td>
</tr>,
@@ -1309,7 +1318,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function orderBookIdentity(row, version) {
function orderBookIdentity(row: T.Row, version?: string) {
if (row.kind === 'orderAfterSale')
return (
<button
@@ -1405,13 +1414,13 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
const badge = o => (
const badge = (o: T.Row) => (
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
{label[o.status] || o.status}
</span>
);
function renderInventoryBalanceCount(item) {
function renderInventoryBalanceCount(item: T.InventoryBalance) {
return item?.countUnit === 'pair' || pocketCountsEnabled(item?.pocket) ? (
<div className="stock-count-number">{stockCountText(item?.count)}</div>
) : (
@@ -1419,7 +1428,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnershipCost(business) {
function renderReportOwnershipCost(business: T.Business) {
const showPayers = business.knownTotalCost !== 0 || business.totalCost === null,
others = teamMemberKeys()
.filter(key => key !== business.member)
@@ -1461,7 +1470,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnerAdvances(business) {
function renderReportOwnerAdvances(business: T.Business) {
const advances = business.ownerAdvances,
single = advances.from === advances.date,
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
@@ -1561,7 +1570,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnershipProfit(business, range) {
function renderReportOwnershipProfit(business: T.Business, range: T.Range) {
const equation = business.equation,
title = reportMonth || range.from !== range.date ? '本期利润' : '当日利润',
complete = equation.complete && !business.incomplete && business.totalCost !== null && business.profit !== null,
@@ -1580,7 +1589,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
订单总成本 <b>¥{yuan(equation.totalCost)}</b>
</span>
<span aria-hidden="true">=</span>
<strong className={business.profit < 0 ? 'danger-text' : ''}>¥{yuan(business.profit)}</strong>
<strong className={(business.profit ?? 0) < 0 ? 'danger-text' : ''}>¥{yuan(business.profit)}</strong>
</p>
) : (
<>
@@ -1607,7 +1616,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportOwnershipCurrentAccount(business) {
function renderReportOwnershipCurrentAccount(business: T.Business) {
if (business.member === 'owner') return '';
const account = business.currentAccount,
days = reportCurrentAccountDays(business);
@@ -1649,7 +1658,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportReceiptIdentity(item) {
function renderReportReceiptIdentity(item: T.ReceiptItem) {
const number = item.paper_number || item.number || (item.price_lock_id ? '锁价记录' : '订单记录');
const identity = item.order_id ? (
<button
@@ -1699,7 +1708,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function materialReportCostLink(item) {
function materialReportCostLink(item: T.CostItem) {
return item.materialPoolId ? (
<button
className="link-button"
@@ -1714,7 +1723,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function afterSaleEditButton(row) {
function afterSaleEditButton(row: T.Row) {
return (
<button
type="button"
@@ -1729,7 +1738,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportPoolMaterial(business) {
function renderReportPoolMaterial(business: T.Business) {
const pool = business.poolMaterial;
if (!pool?.days.length) return '';
const owner = pool.byPayer.owner;
@@ -1764,7 +1773,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function reportOwnerAdvanceIdentity(item) {
function reportOwnerAdvanceIdentity(item: T.AdvanceItem) {
return item.kind === 'order' ? (
<>
<button
@@ -1785,7 +1794,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function priceLockCostLink(item) {
function priceLockCostLink(item: T.CostItem) {
if (item.kind === 'afterSale') return reportCostIdentity(item);
if (item.price_lock_id)
return (
@@ -1813,7 +1822,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
);
}
function renderReportPoolMaterialDay(day) {
function renderReportPoolMaterialDay(day: T.PoolDay) {
if (!day.sources)
return (
<li>
@@ -1,8 +1,9 @@
import type * as T from './contracts';
import { Calc as LedgerCalc, Values } from '../../shared';
import ReportRules from '@public/report-rules.js';
const { reportAfterSaleAmount, reportCostItems, reportRowCost, reportCurrentAccountDays } = ReportRules;
export function reportData({ state, session, reportMonth, reportMember }) {
function reportDownloadText(r) {
export function reportData({ state, session, reportMonth, reportMember }: T.ReportContext) {
function reportDownloadText(r: T.Report) {
if (teamMode() && typeof reportTeamDownloadText === 'function') return reportTeamDownloadText(r);
const s = r.summary,
receipts = r.receiptsByOrderDate,
@@ -113,7 +114,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
);
if (assistantFirst)
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
const options = keys.map(member => [
const options = keys.map((member): [string, string] => [
member,
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
]);
@@ -132,42 +133,42 @@ export function reportData({ state, session, reportMonth, reportMember }) {
const validOrderDate = Values.validDate;
function dailyFundsMoney(value) {
function dailyFundsMoney(value: T.Amount | undefined) {
return value == null ? '待确认' : '¥' + yuan(value);
}
function reimbursementDraftTotal(items) {
function reimbursementDraftTotal(items: { amount: string }[]) {
const { total, complete, amounts } = ReportRules.reimbursementAmounts(items, LedgerCalc.cents);
return { total, complete, formula: amounts.map(amount => '¥' + yuan(amount)).join(' + ') };
}
function teamDataKeys(data) {
function teamDataKeys(data: object) {
return [...assistantMemberKeys(), 'owner'].filter(member => data && Object.hasOwn(data, member));
}
function reportSummaryAmount(summary, key) {
function reportSummaryAmount(summary: T.Summary, key: T.Metric) {
const missing = summary.unknownCounts?.[key] || 0;
return missing && summary.knownCounts?.[key] === 0 && !summary[key] && !summary.afterSaleCount
? '待补齐'
: (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
}
const yuan = n => (n == null ? '待补' : Values.yuan(n));
const yuan = (n: T.Amount | undefined) => (n == null ? '待补' : Values.yuan(n));
function reportPeriod(range) {
function reportPeriod(range: T.Range) {
return range.from === range.date ? range.date : range.from + ' 至 ' + range.date;
}
function accountDisplayName(value) {
function accountDisplayName(value: string) {
const account = accountIdentity(value);
return account ? teamMemberName(account.member) + account.channel : value;
}
function reportDailyProfitAmount(value, known, profit = false) {
function reportDailyProfitAmount(value: T.Amount, known: number, profit = false) {
return value === null ? (profit ? '待核算(已核算 ¥' : '待补齐(已知 ¥') + yuan(known) + ')' : '¥' + yuan(value);
}
function reportTeamDownloadText(report) {
function reportTeamDownloadText(report: T.Report) {
const summary = report.summary,
receipts = report.receiptsByOrderDate;
return [
@@ -215,11 +216,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
].join('\n');
}
function reportCostAmount(value, partial = 0) {
function reportCostAmount(value: T.Amount | undefined, partial = 0) {
return partial && value === 0 ? '待补齐' : (partial ? '已知 ' : '') + '¥' + yuan(value);
}
function reportPayerHints(cost) {
function reportPayerHints(cost: T.PayerCosts) {
return [
cost.missingCount ? cost.missingCount + ' 项成本待补齐' : '',
cost.pendingCount ? cost.pendingCount + ' 项费用未入账,不计合计' : '',
@@ -228,7 +229,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
.join(';');
}
function reportCostIdentity(item) {
function reportCostIdentity(item: T.CostItem) {
if (item.materialPoolId) return item.materialPoolId + ' 购料';
return item.kind === 'afterSale'
? '售后 · ' + (item.customer || '未填客户')
@@ -237,7 +238,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
(item.customer ? ' · ' + item.customer : '');
}
function reportCostFormula(item) {
function reportCostFormula(item: T.CostItem) {
const c = item.calculation;
if (!c) return '';
return (
@@ -252,17 +253,17 @@ export function reportData({ state, session, reportMonth, reportMember }) {
);
}
function reportCostItemAmount(item) {
function reportCostItemAmount(item: T.CostItem) {
if (item.kind === 'pending')
return '未入账' + (item.amount == null ? '(金额待补)' : '(登记 ¥' + yuan(item.amount) + ')');
return item.amount == null ? '待补齐' : '¥' + yuan(item.amount);
}
function afterSalePayerName(row) {
function afterSalePayerName(row: T.Row) {
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
}
const label = {
const label: Record<string, string> = {
draft: '旧草稿',
confirmed: '旧单待补齐',
delivered: '已完成',
@@ -272,7 +273,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
recovery: '回收',
};
function reportRowAmount(row, key) {
function reportRowAmount(row: T.Row, key: T.RowMetric) {
if (row.status === 'draft') return '未开单';
if (key === 'goods') {
const c = reportRowCost(row);
@@ -283,9 +284,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
return row.known?.[key] ? '已知 ¥' + yuan(row.known[key]) + '(待补齐)' : '待补齐';
}
function reportDailyProfitsText(r) {
function reportDailyProfitsText(r: T.Report) {
const table = r.dailyProfits,
rowText = row =>
rowText = (row: T.Profit) =>
`销售净额 ¥${yuan(row.sales)} / 成本 ${reportDailyProfitAmount(row.totalCost, row.knownTotalCost)} / 利润 ${reportDailyProfitAmount(row.profit, row.knownProfit, true)}`;
return [
'每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)',
@@ -297,7 +298,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function reportOwnershipReceiptsText(r) {
function reportOwnershipReceiptsText(r: T.Report) {
return [
'按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)',
...reportOwnershipKeys(r).flatMap(key => {
@@ -315,7 +316,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function dailyFundsDownloadText(report) {
function dailyFundsDownloadText(report: T.Report) {
const range = {
date: report.date,
from: report.from,
@@ -344,9 +345,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
if (data.ready)
result.push(
`${teamMemberName('owner')}净收款 ¥${yuan(data.ownerReceipts.net)} − 确认完整对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = 应转合计 ¥${yuan(data.transferAmount)}`,
data.transferAmount > 0
(data.transferAmount ?? 0) > 0
? '方向:' + teamMemberName('owner') + '转' + teamMemberName('assistant')
: data.transferAmount < 0
: (data.transferAmount ?? 0) < 0
? '方向:' + teamMemberName('assistant') + '转' + teamMemberName('owner')
: '方向:无需转款',
);
@@ -370,14 +371,14 @@ export function reportData({ state, session, reportMonth, reportMember }) {
return result;
}
function reportRecipientReceiptsText(r) {
function reportRecipientReceiptsText(r: T.Report) {
return [
'按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)',
...teamDataKeys(r.recipientReceipts).flatMap(key => {
const person = r.recipientReceipts[key];
return [
`${person.name}总收款:¥${yuan(person.receipt)};退款 ¥${yuan(person.refund)};净收款 ¥${yuan(person.net)}`,
...['receipt', 'refund'].flatMap(kind => {
...(['receipt', 'refund'] as const).flatMap(kind => {
const items = person.items.filter(item => item.kind === kind),
name = kind === 'receipt' ? '收款' : '退款';
return [
@@ -397,7 +398,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function priceLockActivityText(activity) {
function priceLockActivityText(activity: T.PriceActivity | null) {
if (!activity?.summary?.eventCount) return [];
const s = activity.summary;
return [
@@ -413,25 +414,27 @@ export function reportData({ state, session, reportMonth, reportMember }) {
const grams = Values.grams;
const materialPayerName = payer => (payer ? teamMemberName(payer) : '待补');
const materialPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
function pocketLabel(key) {
function pocketLabel(key: string) {
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
}
function pocketCountsEnabled(key) {
function pocketCountsEnabled(key: string) {
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
}
function stockCountText(value, { signed = false, unknown = '未记录对数' } = {}) {
return Number.isSafeInteger(value) ? (signed && value > 0 ? '+' : '') + value + '对' : unknown;
function stockCountText(value: number | null | undefined, { signed = false, unknown = '未记录对数' } = {}) {
return typeof value === 'number' && Number.isSafeInteger(value)
? (signed && value > 0 ? '+' : '') + value + '对'
: unknown;
}
function materialReportMoney(value) {
function materialReportMoney(value: T.Amount | undefined) {
return value == null ? '料费待补' : '¥' + yuan(value);
}
function teamMemberName(member) {
function teamMemberName(member: string) {
return (
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
state?.members?.find(row => row.member === member)?.label ||
@@ -463,7 +466,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
return teamMemberKeys().filter(teamMemberEnabled);
}
function teamMemberEnabled(member) {
function teamMemberEnabled(member: string) {
return Values.memberEnabled(state, member);
}
@@ -471,9 +474,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
return teamMemberKeys().filter(member => member !== 'owner');
}
const accountIdentity = value => Values.accountIdentity(teamMemberKeys(), value);
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
function priceLockActivityRows(activity) {
function priceLockActivityRows(activity: T.PriceActivity | null) {
if (!activity) return [];
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
.map(item => ({
@@ -505,17 +508,18 @@ export function reportData({ state, session, reportMonth, reportMember }) {
.sort((a, b) => a.date.localeCompare(b.date));
}
const materialPurchasePayer = purchase => purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
const materialPurchasePayer = (purchase: T.MaterialPurchase) =>
purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
function peopleCountReportLines(count) {
function peopleCountReportLines(count: T.PeopleCount) {
const period = count?.from !== count?.date;
return peopleParts(true).map(
([part, name]) =>
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (count?.[part]?.baselineDate || '暂无') + ')' : ''}`,
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (countForPart(count, part)?.baselineDate || '暂无') + ')' : ''}`,
);
}
function reportOwnershipBusinessText(business) {
function reportOwnershipBusinessText(business: T.Business) {
return [
`所属订单总成本:${reportBusinessAmount(business.totalCost, business.knownTotalCost)};本人付款 ${reportBusinessAmount(business.selfCost, business.knownSelfCost)};他人付款 ${reportBusinessAmount(business.otherCost, business.knownOtherCost)}`,
...reportPoolMaterialText(business),
@@ -531,7 +535,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function reportReceiptBasis(item) {
function reportReceiptBasis(item: T.ReceiptItem) {
return item.order_after_sale
? '订单售后 · 按实际收付日'
: item.price_lock_id
@@ -539,13 +543,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
: '普通订单 · 开单 ' + (item.order_date || '日期未提供');
}
function reportReceiptLabel(item) {
function reportReceiptLabel(item: T.ReceiptItem) {
return (item.kind === 'receipt' ? '收款' : '退款') + (item.amount < 0 ? '冲回' : '');
}
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
const priceLockPayerName = (payer: string) => (payer ? teamMemberName(payer) : '待补');
function peopleParts(historical = false) {
const keys = assistantMemberKeys().filter(member => historical || teamMemberEnabled(member)),
@@ -555,12 +557,16 @@ export function reportData({ state, session, reportMonth, reportMember }) {
: parts;
}
function peopleCountDisplayName(name, period = false) {
function peopleCountDisplayName(name: string, period = false) {
return name.replace('人数', period ? '结束日总人数' : '当日总人数');
}
function peopleCountText(count, part = null) {
const value = part ? count?.[part] : count;
function countForPart(count: T.PeopleCount, part: string) {
const value = count?.[part];
return value && typeof value === 'object' ? value : undefined;
}
function peopleCountText(count: T.PeopleCount, part: string | null = null) {
const value = part ? countForPart(count, part) : count;
if (!value || !Object.hasOwn(value, 'endTotal') || !Object.hasOwn(value, 'netChange')) return '尚未取得总人数';
const period = count.from !== count.date,
total = value.endTotal === null ? (period ? '结束日未记录' : '当日未记录') : value.endTotal + ' 人(已记录)';
@@ -583,11 +589,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
);
}
function reportBusinessAmount(value, known) {
function reportBusinessAmount(value: T.Amount, known: number) {
return (value === null ? '已知 ' : '') + '¥' + yuan(value === null ? known : value);
}
function reportPoolMaterialText(business) {
function reportPoolMaterialText(business: T.Business) {
const pool = business.poolMaterial;
if (!pool?.days.length) return [];
const owner = pool.byPayer.owner;
@@ -603,7 +609,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function reportOwnerAdvancesText(business) {
function reportOwnerAdvancesText(business: T.Business) {
const advances = business.ownerAdvances,
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
return [
@@ -625,7 +631,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function reportCurrentAccountText(business) {
function reportCurrentAccountText(business: T.Business) {
if (business.member === 'owner') return [];
return [
'当日往来账(逐日核对,不含历史余额,未扣实际转账)',
@@ -637,16 +643,15 @@ export function reportData({ state, session, reportMonth, reportMember }) {
];
}
function reportOwnerAdvanceAmount(value, known) {
function reportOwnerAdvanceAmount(value: T.Amount | undefined, known?: number) {
return value === null ? '待补(已知 ¥' + yuan(known) + ')' : '¥' + yuan(value);
}
function reportOwnerAdvanceFormula(business, day) {
function reportOwnerAdvanceFormula(business: T.Business, day: Partial<T.AdvanceDay>) {
return `${business.member === 'owner' ? teamMemberName('owner') + '付款合计' : teamMemberName('owner') + '垫付合计'}:料池料费 ${reportOwnerAdvanceAmount(day.poolAmount, day.knownPoolAmount)} + 其他成本 ${reportOwnerAdvanceAmount(day.otherAmount, day.knownOtherAmount)} = ${reportOwnerAdvanceAmount(day.amount, day.knownAmount)}`;
}
function reportOwnerAdvanceItemAmount(item) {
function reportOwnerAdvanceItemAmount(item: T.AdvanceItem) {
if (item.status === 'pending')
return (
'待核对' +
@@ -656,7 +661,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
return item.amount === null ? '待补齐' : '¥' + yuan(item.amount);
}
function reportCurrentAccountDirection(business, day) {
function reportCurrentAccountDirection(business: T.Business, day: T.CurrentDisplayDay) {
return day.amount === null
? '应转金额待核算'
: day.amount > 0
@@ -666,15 +671,15 @@ export function reportData({ state, session, reportMonth, reportMember }) {
: '当日无需转款';
}
function reportCurrentAccountFormula(day) {
function reportCurrentAccountFormula(day: T.CurrentDisplayDay) {
return `${teamMemberName('owner')}垫付已用料费 ${reportOwnerAdvanceAmount(day.materialCost, day.knownMaterialCost)} + ${teamMemberName('owner')}垫付其他订单成本 ${reportOwnerAdvanceAmount(day.otherCost, day.knownOtherCost)} + 本人当日订单净利润 ${reportDailyProfitAmount(day.profit, day.knownProfit, true)} − ${teamMemberName('owner')}代收净额 ¥${yuan(day.ownerNetReceipts)} = ${day.amount === null ? '待核算' : '¥' + yuan(day.amount)}`;
}
function peoplePartMember(part) {
function peoplePartMember(part: string) {
return part === 'assistant1' ? 'assistant' : part;
}
function peopleCountUnknownReason(reason, period = false) {
function peopleCountUnknownReason(reason: string, period = false) {
return (
{
'missing-current': period ? '结束日未记录' : '当日未记录',
@@ -684,15 +689,17 @@ export function reportData({ state, session, reportMonth, reportMember }) {
);
}
function peopleCountSignedText(value) {
function peopleCountSignedText(value: number) {
return (value > 0 ? '+' : '') + value + ' 人';
}
function peopleCountDeltaText(value) {
function peopleCountDeltaText(value: number) {
return value > 0 ? '新增 ' + value + ' 人' : value < 0 ? '减少 ' + Math.abs(value) + ' 人' : '无变化(0 人)';
}
function reportPoolMaterialFormula(day) {
function reportPoolMaterialFormula(
day: Pick<T.PoolDay, 'mg' | 'averageRate' | 'amount' | 'knownAmount' | 'sources'>,
) {
if (day.sources)
return (
day.sources
@@ -706,7 +713,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
return `${grams(day.mg)}g × ${day.averageRate === null ? '待补料价' : '¥' + yuan(day.averageRate) + '/g'} = ${day.amount === null ? '料费待补(已知 ¥' + yuan(day.knownAmount) + ')' : '¥' + yuan(day.amount)}`;
}
function reportPoolMaterialPendingNote(pool) {
function reportPoolMaterialPendingNote(pool: T.PoolMaterial) {
return pool.days.some(
day => day.sources && day.sources.reduce((total, source) => total + source.knownAmount, 0) > day.knownAmount,
)
@@ -714,22 +721,23 @@ export function reportData({ state, session, reportMonth, reportMember }) {
: '';
}
function reportPoolMaterialSourceLabel(source) {
function reportPoolMaterialSourceLabel(source: T.MaterialSource) {
return (
(source.kind === 'personal_recovery' ? teamMemberName(source.member) + '个人回收料' : '公共料') +
(source.priceLocked ? '(含锁价原料)' : '')
);
}
const { validateDailyFunds, validateReport, validateDailyReimbursements, reportActiveAccounts, reportOwnershipKeys } = ReportRules.forContext({
teamDataKeys,
validOrderDate,
teamMode,
currentMember,
teamMemberKeys,
isReimbursementStatus: value => Object.hasOwn(reimbursementStatusNames, value),
state,
reportMember,
});
const { validateDailyFunds, validateReport, validateDailyReimbursements, reportActiveAccounts, reportOwnershipKeys } =
ReportRules.forContext({
teamDataKeys,
validOrderDate,
teamMode,
currentMember,
teamMemberKeys,
isReimbursementStatus: value => Object.hasOwn(reimbursementStatusNames, value),
state,
reportMember,
});
return {
validateReport,
validateDailyFunds,
+9
View File
@@ -0,0 +1,9 @@
// Classic scripts install these names in the browser. Node tests and Vite use the same CommonJS exports.
declare var LedgerCalc: typeof import('../../../public/calculations.js');
declare var CreditCardFees: typeof import('../../../public/credit-card-fees.js');
declare var FeeEstimates: typeof import('../../../public/fee-estimates.js');
declare var OrderFormula: typeof import('../../../public/order-formula.js');
declare var OrderTemplates: typeof import('../../../public/order-templates.js');
declare var OrderCopy: typeof import('../../../public/order-copy.js');
declare var OrderEntryModel: typeof import('../../../public/order-entry-model.js');
declare var LedgerValues: typeof import('../../../public/ledger-values.js');
@@ -0,0 +1,159 @@
import type { SyncContext, LineState, OrderForm } from './types';
import type { Pool, Allocation } from '../pages/MaterialPools/model';
import type { QuoteBalance, QuoteSource } from '../lib/materialQuote';
export type Uuid = () => string;
export type LineContext = Pick<SyncContext, 'st' | 'uuid'> & { member?: string; historicalPocket?: boolean };
export type MoneyMode = 'gram' | 'total';
export interface ManualMaterial {
mode: MoneyMode;
rate: string;
total: string;
originalTotal: string;
payer: string;
}
export interface PoolChoice {
id: string;
date: string;
totalMg: number;
usedMg: number;
remainingMg: number;
availableMg: number;
status: string;
personalPools?: Pool['personalPools'];
usages?: Pool['usages'];
}
export interface PoolPreview {
amount: number | null;
covered: boolean;
wantedMg: number;
usedMg?: number;
allocations?: Allocation[];
materialSources?: QuoteSource[];
balance?: QuoteBalance;
quoteError?: string;
quoteReady?: boolean;
}
export interface LinePoolPreview {
amount: number | null;
poolId?: string;
date?: string;
status?: string;
revision?: string | number;
quantity?: number | null;
averageRate?: number | null;
allocations?: Allocation[];
materialSources?: QuoteSource[];
}
export interface ChargeInput<T = string> {
id?: string;
nameType?: string;
customName?: string;
name?: string;
amount?: T | null;
chargePrices?: Record<string, string>;
costRemoved?: boolean;
}
export interface FeeInput<T = string> {
key: string;
note: string;
amount: T | null;
payer: string;
sourceName?: string;
status?: string;
edited?: boolean;
expense_id?: string;
date?: string;
lineNumber?: number;
funding?: Record<string, unknown>;
system?: string;
}
export type CostParts<T = string> = Partial<Record<'material' | 'labor' | 'accessories' | 'other', T | null>>;
export interface LineInput<T = string> {
id?: string;
name?: string;
nameType?: string;
customName?: string;
code?: string;
unit?: LineState['unit'];
pricingMode?: LineState['pricingMode'];
quantity?: T;
goldPrice?: T;
laborMode?: LineState['laborMode'];
laborRate?: T;
pieces?: string | number;
priceNote?: string;
baseSale?: T;
sale?: T;
cost?: T | null;
pocket?: string;
stockCount?: string | number | null;
historicalUnknown?: boolean;
returnedStockId?: string;
payer?: string;
charges?: ChargeInput<T>[];
costParts?: CostParts<T>;
costPayers?: { labor?: string; material?: string };
costLabor?: { mode?: MoneyMode; rate?: T | null };
costMaterial?: { mode?: MoneyMode | 'pool'; rate?: T | null; poolId?: string };
costMaterialDraft?: Partial<ManualMaterial>;
materialPoolDraft?: { poolId?: string; defaultDate?: boolean; manual?: Partial<ManualMaterial> };
costFundings?: { labor?: Record<string, unknown> };
materialPool?: LinePoolPreview;
}
export interface EntryDraft<T = string> {
id?: string;
revision?: number;
copy_kind?: string;
paper_date?: string;
paper_number?: string;
rounding_mode?: OrderForm['rounding_mode'];
member?: string;
date?: string;
customer?: string;
customer_type?: string;
salesperson?: string;
internal_note?: string;
note?: string;
payment_account?: string;
credit_card_fee_payer?: string;
fees_date?: string;
discount?: T;
fee_cost_mode?: string;
fee_items?: FeeInput<T>[];
lines?: LineInput<T>[];
}
export interface IssuedOrder extends EntryDraft<number> {
discount: number;
fee_items: FeeInput<number>[];
lines: (Omit<LineInput<number>, 'charges'> & {
charges?: (ChargeInput<number> & { amount: number | null })[];
sale: number;
quantity: number;
cost: number | null;
goldPrice: number;
laborRate: number;
})[];
}
export type FormLine = LineInput & {
name: string;
pocket: string;
quantity: string;
stockCount?: string | number | null;
sale: string;
charges: ChargeInput[];
};
export type OrderInput = Required<Pick<EntryDraft, 'date' | 'discount' | 'rounding_mode'>> &
Omit<EntryDraft, 'lines' | 'fee_items'> & { lines: FormLine[]; fee_items: FeeInput[] };
export type FormulaLine = Pick<
LineState,
'unit' | 'pricingMode' | 'quantity' | 'goldPrice' | 'laborMode' | 'laborRate' | 'pieces'
> & {
charges: { name: string; amount: string }[];
};
export type CostCatalog = Record<
string,
{ amount: string; payer: string; name?: string; enabled?: boolean; byQuantity?: boolean }
>;
export type EditableLine = LineState & { purchase: NonNullable<LineState['purchase']> };
export type EditablePresetForm = OrderForm & { presets: NonNullable<OrderForm['presets']> };
+113
View File
@@ -0,0 +1,113 @@
// 持久化订单按分、毫克保存;复制与模板表单保留字符串。
export interface CostMode<T> {
mode?: string;
rate?: T;
poolId?: string;
}
export interface ProductAmounts<T> {
unit: string;
quantity: T;
name: string;
nameType?: string;
customName?: string;
stockCount?: number | string;
pocket?: string;
payer?: string;
pricingMode?: string;
goldPrice?: T;
laborRate?: T;
laborMode?: string;
pieces?: string | number;
priceNote?: string;
sale: T;
baseSale?: T;
cost?: T | null;
costMaterial?: CostMode<T>;
costLabor?: CostMode<T>;
costParts?: Record<string, T | null>;
costPayers?: Record<string, string>;
charges: { id?: string; name: string; amount: T; costRemoved?: boolean }[];
}
export interface SavedFee {
key: string;
amount: number;
payer: string;
note: string;
status: string;
sourceName?: string;
expense_id?: string;
system?: string;
}
export interface Expense {
id: string;
amount: number;
payer: string;
note: string;
system?: string;
key?: string;
}
export interface CopySource {
date: string;
status: string;
salesperson: string;
payment_account: string;
discount: number;
note?: string;
rounding_mode?: string;
fee_items: SavedFee[];
expenses: Expense[];
corrections?: { type: string; target: string }[];
pendingFees?: { key: string }[];
lines: (ProductAmounts<number> & { materialAllocations?: unknown[] })[];
price_lock_id?: string;
}
export interface ManualCost {
mode?: string;
rate?: string;
total?: string;
originalTotal?: string;
payer?: string;
}
export interface DraftProduct extends Partial<Omit<ProductAmounts<string>, 'quantity' | 'costMaterial' | 'costParts'>> {
costMaterial?: CostMode<string | number>;
costParts?: Record<string, number | string | null>;
quantity?: number | string;
materialPoolDraft?: { defaultDate: boolean; poolId?: string; manual?: ManualCost };
costMaterialDraft?: ManualCost;
}
export interface TemplateProduct extends DraftProduct {
nameType: string;
customName: string;
unit: string;
payer: string;
charges: NonNullable<DraftProduct['charges']>;
}
export interface TemplateFee {
key: string;
note: string;
payer: string;
amount: string;
edited?: boolean;
status?: string;
sourceName?: string;
lineNumber?: number;
}
export interface CopyDraft {
lines: DraftProduct[];
date?: string;
id?: string;
copy_kind?: string;
customer?: string;
note?: string;
internal_note?: string;
discount?: string;
salesperson?: string;
payment_account?: string;
fee_items?: TemplateFee[];
}
export interface TemplateOptions {
newId?: () => string;
pocketKeys?: string[];
today?: string;
salesperson?: string;
}
+100 -21
View File
@@ -1,3 +1,6 @@
import type { ManualMaterial, FeeInput, LinePoolPreview, CostCatalog, FormulaLine } from './orderEntryTypes';
import type { Pool } from '../pages/MaterialPools/model';
import type { QuoteRequest, QuoteRow, QuoteBalance } from '../lib/materialQuote';
// 共用 UMD 模块(../public/*.js)与服务端接口的类型描述。只描述新版界面用到的部分。
export interface MemberRow {
@@ -24,11 +27,14 @@ export interface SessionInfo {
}
export interface PocketRow {
key: string;
self?: boolean;
name?: string;
countUnit?: 'pair' | null;
countSince?: string | null;
active?: boolean;
}
export interface LedgerState {
orders?: { id?: string; lines?: { pocket: string }[] }[];
today: string;
mode: string;
user: SessionUser;
@@ -37,7 +43,7 @@ export interface LedgerState {
storeName?: string;
members?: MemberRow[];
feeDefaults?: Record<string, string>;
costPresets?: Record<string, unknown>;
costPresets?: CostCatalog;
creditCardRatePermille?: number;
};
pockets?: string[];
@@ -49,7 +55,7 @@ export interface LedgerState {
export interface ChargeState {
id: string;
type: string;
customName: string;
customName?: string;
amount: string;
prices: Record<string, string>;
costRemoved?: boolean;
@@ -66,10 +72,11 @@ export interface PurchaseState {
accessories: string;
other: string;
dataMode: string;
preferredMode: string;
preferredMode: 'gram' | 'total';
dataUnit: string;
total: string;
originalTotal: string;
costFundings?: { labor?: Record<string, unknown> };
}
export interface PoolState {
source: 'manual' | 'pool';
@@ -83,7 +90,9 @@ export interface PoolState {
help?: string;
payerText?: string;
personal?: boolean;
preview: { amount: number | null } | null;
preview: LinePoolPreview | null;
manual: ManualMaterial;
unified?: boolean;
}
export interface LineView {
calculation: string;
@@ -110,6 +119,9 @@ export interface ReturnedStockLot {
materialPoolNotice?: string;
}
export interface LineState {
countHistoricalUnknown?: boolean;
countOriginalPocket?: string;
countOriginalQuantity?: string;
returnedStockId?: string;
returnedStockCode?: string;
returnedStockLot?: ReturnedStockLot;
@@ -148,10 +160,14 @@ export interface FeeRowState {
sourceName: string;
edited: boolean;
status: string;
funding?: Record<string, unknown>;
date?: string;
lineNumber?: number;
automatic?: unknown;
automatic?: FeeInput;
expense_id?: string;
}
export interface PresetState {
originals?: Record<string, FeeInput>;
configured: boolean;
checked: Record<string, boolean>;
quantity: Record<string, string>;
@@ -163,6 +179,8 @@ export interface PaymentState {
cardLocked: boolean;
}
export interface OrderForm {
editing?: boolean;
original_customer_type?: string;
returnedLots?: { date: string; member: string; lots: ReturnedStockLot[] };
copy_kind: string;
id: string;
@@ -212,13 +230,13 @@ export interface FormSummary {
presetNotes: Record<string, string>;
}
export interface MaterialPools {
rows: unknown[];
rolling?: { enabled?: boolean; cutover?: string };
current?: unknown;
rows: Pool[];
rolling?: { enabled?: boolean; cutover: string };
current?: Pool;
}
export interface QuoteState {
input: unknown;
result: unknown;
input: QuoteRequest;
result: { entries: QuoteRow[]; pools: QuoteBalance[] } | null;
error: string;
}
export interface SyncContext {
@@ -257,7 +275,38 @@ export interface PresetCatalogItem {
shipping?: boolean;
}
interface MaterialUsage {
active: boolean;
mg: number;
order_id?: string;
line_index: number;
}
export interface LockCostEstimate {
lockedMg: number;
finalMg: number;
originalUsedMg: number;
extraMg: number;
leftoverMg: number;
originalPurchase: number;
originalUsedCost: number;
extraCost: number;
materialCost: number;
leftoverCost: number;
}
export interface LedgerCalcApi {
orderCosts: (typeof import('../../../public/calculations.js'))['orderCosts'];
poolMaterialAmount(amount: number, mg: number, quantity: number): number;
poolMaterialPreview(
pool: { totalAmount: number | null; totalMg: number; usages: MaterialUsage[] },
entries: { lineIndex: number; mg: number }[],
options?: { orderId?: string | null; allUsages?: MaterialUsage[] },
): { usedMg: number; wantedMg: number; covered: boolean; amounts: Record<number, number | null> };
priceLockCost(input: {
lockedQuantity: string;
quantity: string;
buyRate: string;
extraBuyRate: string;
}): LockCostEstimate;
cents(value: unknown, name?: string): number;
isSilver(name: string): boolean;
sale(line: unknown): { sale: number; baseSale: number; chargesTotal: number; charges: unknown[] };
@@ -270,12 +319,18 @@ export interface LedgerCalcApi {
costLabels: Record<string, string>;
}
export interface CreditCardFeesApi {
isFee(item: { key?: string; system?: string }): boolean;
isAccount(account: string): boolean;
amount(cents: number, rate?: number): number;
normalizeAccount(account: string): string;
ratePermille: number;
}
export interface FeeEstimatesApi {
presetCatalog(
values?: unknown,
): Record<string, { enabled: boolean; name: string; amount: string; payer: string; byQuantity: boolean }>;
presetKind(item: unknown, options?: { presets?: unknown; recorded?: boolean }): string;
presetKey(kind: string): string;
presets(values?: unknown): Record<string, { amount: string; payer: string }>;
checkboxCategory(name: string): string;
normalize(name: string): string;
@@ -285,8 +340,8 @@ export interface OrderFormulaApi {
input: string,
options: { roundingMode: string },
): {
items: { line: Record<string, string> & { charges: { amount: string }[] }; subtotal: number }[];
lines: (Record<string, string> & { charges: { name: string; amount: string }[] })[];
items: { line: FormulaLine; subtotal: number }[];
lines: FormulaLine[];
subtotal: number;
total: number;
roundingMode: string;
@@ -302,6 +357,29 @@ export interface OrderTemplatesApi {
): Record<string, unknown> & { member?: string; salesperson?: string };
}
export interface OrderEntryModelApi {
validateOrderIdentity<T extends { customer: string; salesperson: string; internal_note?: string }>(
input: T,
options?: { requireInternalNote?: boolean },
): T;
accountIdentity(st: LedgerState, account: string): { member: string; channel: string } | null;
memberAccountPrefix(member: string): string;
pocketLabel(st: LedgerState, key: string): string;
stockCountValue(value: string, options?: { optional?: boolean; title?: string }): number | null;
creditCardRate(st: LedgerState): number;
shopFeeDefaults(st: LedgerState): Record<string, string>;
orderRoundingHint(total: ReturnType<LedgerCalcApi['orderTotal']>): string;
costConfig(st: LedgerState): ReturnType<FeeEstimatesApi['presets']>;
newPresets(st: LedgerState, items?: readonly unknown[], recorded?: boolean): PresetState;
readPresets(
form: { presets: PresetState | null; member?: string },
st: LedgerState,
): {
items: { key: string; note: string; amount: string; payer: string; status: string; edited: boolean }[];
notes: Record<string, string>;
};
feeLabels: Record<string, string>;
formMember(form: { member?: string }, st: LedgerState): string;
noteTagQuery(text: string): string;
productNames: string[];
chargeNames: string[];
yuan(cents: number | null | undefined): string;
@@ -310,7 +388,7 @@ export interface OrderEntryModelApi {
teamMode(st: LedgerState): boolean;
currentMember(st: LedgerState, session?: SessionInfo | null): string;
memberKeys(st: LedgerState): string[];
memberName(st: LedgerState, member: string): string;
memberName(st: LedgerState, member: string, session?: SessionInfo | null): string;
memberOptions(st: LedgerState, assistantFirst?: boolean, options?: { selected?: string }): [string, string][];
defaultSalesperson(st: LedgerState, session?: SessionInfo | null): string;
activePocketKeys(st: LedgerState): string[];
@@ -325,9 +403,9 @@ export interface OrderEntryModelApi {
setPurchaseField(line: LineState, field: string, value: string): LineState;
setPoolSource(line: LineState, source: 'manual' | 'pool'): LineState;
lineVisibility(line: LineState, st: LedgerState): LineVisibility;
poolQuoteInput(form: OrderForm, ctx: SyncContext): { date: string; member: string; entries: unknown[] };
poolQuoteInput(form: OrderForm, ctx: SyncContext): QuoteRequest;
feeSourceText(row: FeeRowState): string;
editFeeRow(form: OrderForm, index: number, field: 'amount' | 'payer' | 'note', value: string): OrderForm;
editFeeRow(form: OrderForm, index: number, field: 'amount' | 'payer' | 'note' | 'date', value: string): OrderForm;
addManualFee(form: OrderForm, st: LedgerState, uuid: () => string): OrderForm;
removeFeeRow(form: OrderForm, index: number): OrderForm;
restoreChargeCost(form: OrderForm, lineIndex: number, chargeIndex: number): OrderForm;
@@ -335,7 +413,7 @@ export interface OrderEntryModelApi {
setPresetQuantity(form: OrderForm, kind: string, value: string): OrderForm;
presetCatalogView(form: OrderForm, st: LedgerState): PresetCatalogItem[];
paymentMethods(st: LedgerState): string[];
recipientOptions(st: LedgerState, payment: PaymentState): [string, string][];
recipientOptions(st: LedgerState, payment: Pick<PaymentState, 'recipient' | 'method'>): [string, string][];
readPaymentAccount(form: OrderForm): string;
changeMember(form: OrderForm, member: string, st: LedgerState): OrderForm;
isBlankDraft(draft: unknown): boolean;
@@ -348,6 +426,11 @@ export interface OrderEntryModelApi {
syncForm(form: OrderForm, ctx: SyncContext): { form: OrderForm; draft: OrderDraft; summary: FormSummary };
canUseReturnedLot(lot: ReturnedStockLot, st: LedgerState, date: string): boolean;
validateFormFields(form: OrderForm, st: LedgerState): void;
validateIssueDraft<T extends Pick<OrderDraft, 'lines' | 'fee_items' | 'discount' | 'rounding_mode'>>(
draft: T,
st: LedgerState,
options: { requireIdentity: false },
): T;
validateIssueDraft(draft: OrderDraft, st: LedgerState): OrderDraft;
draftInputs(order: unknown): Record<string, unknown>;
filterNoteTags(tags: string[], text: string): string[];
@@ -355,11 +438,7 @@ export interface OrderEntryModelApi {
}
export interface OrderEntryModelApi {
isFormulaBlank(line: LineState): boolean;
applyFormulaLines(
form: OrderForm,
lines: Record<string, unknown>[],
ctx: SyncContext,
): { form: OrderForm; filled: number[] };
applyFormulaLines(form: OrderForm, lines: FormulaLine[], ctx: SyncContext): { form: OrderForm; filled: number[] };
}
export interface OrderCopyApi {
hasDraftContent(draft: unknown, options: { today: string; salesperson: string }): boolean;
+22 -2
View File
@@ -1,3 +1,5 @@
import transcriptJson from '../../e2e/baseline/golden/transcript.json?raw';
import { readOrderRecord } from '../src/pages/Orders/readOrder';
import { render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { orderViews } from '../src/pages/Orders/orderViews';
@@ -5,6 +7,11 @@ import { Cards, type LedgerState } from '../src/shared';
const date = '2026-11-20';
const account = '麦麦信用卡';
const transcript: { method?: string; path?: string; status?: number; body?: unknown }[] = JSON.parse(transcriptJson);
const saved = transcript.find(
step => step.method === 'GET' && step.path === '/api/orders/<id26>' && step.status === 200,
);
const order = readOrderRecord(saved?.body, '<id26>');
function renderPayment(action: 'receipt' | 'correct', orderRate?: number, shopRate?: number) {
const state: LedgerState = {
@@ -16,14 +23,27 @@ function renderPayment(action: 'receipt' | 'correct', orderRate?: number, shopRa
};
const views = orderViews({
state,
session: { user: state.user },
session: { user: state.user, setup: true, mode: 'trial', today: date },
currentOrder: {
...order,
id: 'order-1',
date,
balance: 25000,
payment_account: account,
credit_card_rate_permille: orderRate,
payments: [{ id: 'receipt-1', kind: 'receipt', date, account, amount: 25000 }],
payments: [
{
id: 'receipt-1',
kind: 'receipt',
date,
account,
amount: 25000,
reference: '',
order_id: 'order-1',
actor: '店主',
created: date,
},
],
corrections: [],
expenses: [],
settlements: [],
+20 -2
View File
@@ -6,6 +6,7 @@
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
@@ -15,7 +16,24 @@
"allowJs": true,
"noEmit": true,
"types": ["vitest/globals", "@testing-library/jest-dom", "node"],
"paths": { "@public/*": ["../public/*"] }
"paths": {
"@public/*": ["../public/*"]
},
"checkJs": true
},
"include": ["src", "test", "vite.config.ts"]
"include": [
"src",
"test",
"vite.config.ts",
"../public/calculations.js",
"../public/credit-card-fees.js",
"../public/fee-estimates.js",
"../public/order-copy.js",
"../public/order-templates.js",
"../public/order-entry-model.js",
"../public/order-formula.js",
"../public/ledger-values.js",
"../public/report-rules.js",
"../public/recovery-rules.js"
]
}