1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/firebase-BEuJf_if.js","assets/vendor-B2mwFaEh.js","assets/excel-libs-DENYFglI.js"])))=>i.map(i=>d[i]); 2import{r as u,ae as dt,ad as e}from"./vendor-B2mwFaEh.js";import{S as xs}from"./SalesPdfExport-D_UUmum1.js";import gs from"./Picking-Bh5YRc4M.js";import{_ as ys}from"./pdf-libs-Pu_J_WX0.js";import"./firebase-BEuJf_if.js";import{f as ts}from"./salesUtils-C1DX6Vqi.js";import{r as os,c as is}from"./salesCalculations-CAxGwVtb.js";import{s as M,c as bs}from"./index-3ztlLpng.js";import{n as vs,af as ls,v as cs,X as bt,W as ds,ag as us,a5 as Ot,F as _s,ay as Xt,t as ws,d as Tt,a9 as js,T as Ns,b1 as Ss,b0 as ss,j as ms,_ as Zt,I as Cs,ab as Ds,R as ks,b2 as Ps}from"./icons-od6ehn-l.js";import"./excel-libs-DENYFglI.js";import"./vfs_fonts_ja-CQYrejsA.js";import"./receivableUtils-IUb-ZoqQ.js";import"./pickingExpiry-Dxquu3bW.js";const qt=()=>{const s=new Date,o=s.getTime()+s.getTimezoneOffset()*6e4,x=new Date(o+540*60*1e3),f=x.getFullYear(),a=String(x.getMonth()+1).padStart(2,"0"),l=String(x.getDate()).padStart(2,"0");return`${f}-${a}-${l}`},Is=({order:s,isOpen:o,onClose:x,onApprove:f,T:a,productMap:l,products:w,quotes:d,onMapProduct:j,warehouses:Q,mainWarehouseId:W,inventory:q,onPrev:$,onNext:O,hasPrev:V,hasNext:X,deliveryMethods:S,db:B,companyId:A,purchases:le})=>{const[y,K]=u.useState(null),[F,de]=u.useState(""),[se,Ce]=u.useState(!1),[ce,re]=u.useState({}),[Y,ne]=u.useState({}),[v,J]=u.useState([]),[R,ue]=u.useState({}),[C,P]=u.useState([]),[T,b]=u.useState({});u.useEffect(()=>{if(!A)return;let h=!0;(async()=>{const{data:i,error:m}=await M.from("settings").select("value").eq("company_id",A).eq("key","delivery_schedules").maybeSingle();h&&!m&&b(i?.value||{})})();const n=M.channel(`rt_delivery_schedules_partner_form_${A}`).on("postgres_changes",{event:"*",schema:"public",table:"settings",filter:`company_id=eq.${A}`},i=>{i.new?.key==="delivery_schedules"&&h&&b(i.new.value||{})}).subscribe();return()=>{h=!1,M.removeChannel(n)}},[A]);const E=u.useRef(null),me=u.useRef(null),je=u.useRef(null),oe=u.useRef(null),tt=u.useRef(null),qe=u.useRef(null),[pe,Ee]=u.useState({product:null,query:"",boxQty:"",unitQty:"",cost:"",price:"",profitRate:0}),[ae,xe]=u.useState([]),[ge,De]=u.useState(-1),[Pe,Ae]=u.useState({}),[Re,Ne]=u.useState({}),[Ue,Je]=u.useState({}),[Oe,ye]=u.useState(null),[Qe,Fe]=u.useState(null);u.useEffect(()=>{const h=y?.partnerInfo?.id||y?.customerId||s?.partnerInfo?.id;if(!h||!A)return re({});(async()=>{const{data:n}=await M.from("customer_prices").select("prices").eq("id",h).maybeSingle();re(n?.prices||{})})()},[y?.partnerInfo?.id,y?.customerId,s?.partnerInfo?.id,A]),u.useEffect(()=>{if(!A)return;(async()=>{const{data:t}=await M.from("rebate_promotions").select("*").eq("company_id",A).eq("is_archived",!1).gt("remaining_qty",0);P((t||[]).map(n=>
2({...n,id:n.id,productCode:n.product_code,remainingQty:n.remaining_qty,rebateCost:n.rebate_cost,targetCustomers:n.target_customers})))})()},[A]),u.useEffect(()=>{const h=y?.partnerInfo?.id||y?.customerId||s?.partnerInfo?.id;if(!h||!A)return ne({});(async()=>{const{data:n}=await M.from("customer_reserves").select("*").eq("customer_id",h).gt("remaining_qty",0),i={};(n||[]).forEach(m=>{i[m.product_code]={id:m.id,remainingQty:m.remaining_qty}}),ne(i)})()},[y?.partnerInfo?.id,y?.customerId,s?.partnerInfo?.id,A]),u.useEffect(()=>{const h=y?.partnerInfo?.id||y?.customerId||s?.partnerInfo?.id;if(!h||!A)return J([]);(async()=>{const{data:n}=await M.from("promo_rules").select("*").eq("company_id",A).eq("is_active",!0),i=[],m=qt();(n||[]).forEach(c=>{const p=c.start_date?c.start_date.split("T")[0]:null,r=c.end_date?c.end_date.split("T")[0]:null,_=c.customer_id==="ALL"||c.customer_id===h;(!p||p<=m)&&(!r||r>=m)&&_&&i.push({id:c.id,productCode:c.product_code,buyQty:c.buy_qty,freeQty:c.free_qty,customerId:c.customer_id})}),J(i)})()},[y?.partnerInfo?.id,y?.customerId,s?.partnerInfo?.id,A]),u.useEffect(()=>{const h=y?.partnerInfo?.id||y?.customerId||s?.partnerInfo?.id;if(!h||!A)return ue({});(async()=>{const{data:n}=await M.from("customer_supports").select("*").eq("customer_id",h).gt("remaining_qty",0),i={};(n||[]).forEach(m=>{const c=m.product_code||m.target_product_code;c&&!i[c]&&(i[c]={id:m.id,remainingQty:m.remaining_qty})}),ue(i)})()},[y?.partnerInfo?.id,y?.customerId,s?.partnerInfo?.id,A]);const Be=u.useMemo(()=>{const h=new Map;return(t,n)=>{if(!t)return 0;const i=`${t.code||t.id}__${n||""}`;if(h.has(i))return h.get(i);const m=Number(os(t,le||[],n))||0;return h.set(i,m),m}},[le]),He=s?.partnerInfo?.id||s?.customerId,vt=s?.partnerInfo?.code||s?.partnerId,Ie=u.useCallback(h=>{let t=0,n=0,i=!1,m=null,c=0,p=null,r=null;const _=l.get(h?.toString().toUpperCase());if(_){const N=y?.desiredDeliveryDate||s?.desiredDeliveryDate||qt();n=Be(_,N);const I=C.find(D=>D.productCode!==h?!1:(!D.targetCustomers||D.targetCustomers.length===0||He&&D.targetCustomers.some(L=>L.id===He))&&D.remainingQty>0);I&&(p=Number(I.rebateCost||0),r=I.promotion_code||I.id,i=!0,m=I.id,c=I.remainingQty);let U=null;if(d&&d.length>0&&He){const D=qt(),Z=d.filter(L=>(L.customerId===He||L.customerCode===vt)&&(L.status==="normal"||L.status==="approved")&&L.items&&L.items.some(z=>z.productCode===h)).filter(L=>{const z=L.effectiveDate?.toDate?L.effectiveDate.toDate().toISOString().slice(0,10):L.effectiveDate||"";return z&&z<=D});if(Z.length>0){Z.sort((z,ee)=>{const be=z.effectiveDate?.toDate?z.effectiveDate.toDate().getTime():new Date(z.effectiveDate).getTime();return(ee.effectiveDate?.toDate?ee.effectiveDate.toDate().getTime():new Date(ee.effectiveDate).getTime())-be});const L=Z[0].items.find(z=>z.productCode===h);L&&Number(L.unitPrice)>0&&(U=Number(L.unitPrice))}}if(U!==null)t=U;else{const D=ce[h];D!==void 0&&D>0&&(t=Number(D))}}return{salesPrice:t,costPrice:n,rebateApplied:i,rebateId:m,rebateRemaining:c,actualRebateCost:p,promotionIdToSave:r}},[l,ce,d,He,vt,C,y?.desiredDeliveryDate,s?.desiredDeliveryDate,Be]);u.useEffect(()=>{if(ge>=0&&qe.current){const h=qe.current.children[ge];h&&h.scrollIntoView({block:"center",behavior:"smooth"})}},[ge]),u.useEffect(()=>{if(o&&s&&l.size>0){const h=[],t=[],n={};Object.keys(R).forEach(c=>n[c]={...R[c]});const i={};Object.keys(Y).forEach(c=>i[c]={...Y[c]}),s.products.forEach(c=>{const p=l.get(c.masterCode),{salesPrice:r,costPrice:_,actualRebateCost:N,promotionIdToSave:I,rebateApplied:U,rebateId:D,rebateRemaining:Z}=Ie(c.masterCode);let L=Number(c.qty||0),z=L,ee=c.deliveryPrice!==void 0&&c.deliveryPrice>0?c.deliveryPrice:r;const be=n[c.masterCode],ve=i[c.masterCode];if(be&&be.remainingQty>0){const fe=Math.min(L,be.remainingQty),$e=be.remainingQty-fe,Se=p?.box_qty||1,we=Math.floor($e/Se),Ke=$e%Se;h.push({...c,deliveryPrice:0,unitPrice:0,unitCost:_,current_stock_units:0,is_direct_delivery:p?.is_direct_delivery||!1,qty:fe,unitQty:fe,boxQty:"",isSupportFulfillment:!0,supportDocId:be.id,maxSupportQty:be.remainingQty,isReserveFulfillment:!1,isRebateApplied:!1,isPromoFreebie:!1,note:`[ç¡åæ¯æ´æ®]: ${we}Box / ${Ke} (è¨ ${$e})`}),be.remainingQty-=fe,z-=fe}else if(ve&&ve.remainingQty>0){const fe=Math.min(L,ve.remainingQty),$e=ve.remainingQty-fe,Se=p?.box_qty||1,we=Math.floor($e/Se),Ke=$e%Se;h.push({...c,deliveryPrice:0,unitPrice:0,unitCost:_,current_stock_units:0,is_direct_delivery:p?.is_direct_delivery||!1,qty:fe,unitQty:fe,boxQty:"",isReserveFulfillment:!0,maxReserveQty:ve.remainingQty,isSupportFulfillment:!1,isRebateApplied:!1,isPromoFreebie:!1,note:`[ç´å徿®]: ${we}Box / ${Ke} (è¨ ${$e})`}),ve.remainingQty-=fe,z-=fe}else if(ve&&ve.remainingQty>0){const fe=Math.min(L,ve.remainingQty);h.push({...c,deliveryPrice:0,unitPrice:0,unitCost:_,current_stock_units:0,is_direct_delivery:p?.is_direct_delivery||!1,qty:fe,unitQty:fe,boxQty:"",isReserveFulfillment:!0,maxReserveQty:ve.remainingQty,isSupportFulfillment:!1,isRebateApplied:!1,isPromoFreebie:!1,note:`[ç´å徿®]: ${fe} (è¨ ${ve.remainingQty})`}),ve.remainingQty-=fe,z-=fe}z>0&&h.push({...c,deliveryPrice:ee,unitPrice:ee,unitCost:_,current_stock_units:0,is_direct_delivery:p?.is_direct_delivery||!1,qty:z,unitQty:z,boxQty:"",isReserveFulfillment:!1,isSupportFulfillment:!1,isPromoFreebie:!1,isRebateApplied:U,rebateId:D,rebateRemaining:Z,rebate_cost:N,promotion_id:I,note:c.note||""});const G=v.find(fe=>
2fe.productCode===c.masterCode);if(G){const fe=Number(G.buyQty||1),$e=Number(G.freeQty||1),we=Math.floor(L/fe)*$e;we>0&&t.push({code:c.code,masterCode:c.masterCode,name:a(p?.name_kr||c.name,p?.name_jp||c.name),qty:we,unitQty:we,boxQty:"",deliveryPrice:0,unitPrice:0,unitCost:_,taxRate:c.taxRate||(p?.tax_rate?parseFloat(p.tax_rate):.1),is_direct_delivery:p?.is_direct_delivery||!1,current_stock_units:0,isReserveFulfillment:!1,isSupportFulfillment:!1,isRebateApplied:!1,isPromoFreebie:!0,rebateId:G.id,note:`[${fe}+${$e} ããã¢ã¼ã·ã§ã³è´å]`})}});const m=[...h,...t];K({...s,products:m}),de(W||Q&&Q[0]?.id||""),Ae({}),Ne({}),setTimeout(()=>E.current?.focus(),100)}},[o,s,l,W,Q,S,Y,v,R,a]),u.useEffect(()=>{if(y&&y.products&&y.products.length>0){let h=!1;const t=y.products.map(n=>{if(!n.masterCode)return n;const{salesPrice:i,costPrice:m}=Ie(n.masterCode);let c=n.deliveryPrice,p=n.unitCost;return!n.isReserveFulfillment&&!n.isSupportFulfillment&&!n.isPromoFreebie&&(!c||c===0)&&(c=i),(!p||p===0)&&(p=m),c!==n.deliveryPrice||p!==n.unitCost?(h=!0,{...n,deliveryPrice:c,unitCost:p}):n});h&&K(n=>({...n,products:t}))}},[y?.orderId,Ie]),u.useEffect(()=>{F&&q&&K(h=>{if(!h||!h.products)return h;let t=!1;const n=h.products.map(i=>{const m=l.get(i.masterCode);if(!m)return i;const c=q.find(r=>r.productId===m.id&&r.warehouseId===F),p=c?Number(c.quantity):0;return i.current_stock_units!==p?(t=!0,{...i,current_stock_units:p}):i});return t?{...h,products:n}:h})},[F,q,l]);const{subTotal:Ye,tax8:Ze,tax10:Ve,totalAmount:Xe,totalProfit:Ct,profitRate:Dt,mappedItemsCount:ie,totalItemsCount:_e}=u.useMemo(()=>{if(!y)return{subTotal:0,tax8:0,tax10:0,totalAmount:0,totalProfit:0,profitRate:0,mappedItemsCount:0,totalItemsCount:0};let h=0;const t=y.products.map(m=>{const c=l.get(m.masterCode);c&&h++;let p=.1;const r=m.taxRate!==void 0&&m.taxRate!==null&&m.taxRate!==""?m.taxRate:c?c.tax_rate:void 0;if(r!=null&&r!==""){const _=parseFloat(r);isNaN(_)||(Math.abs(_-.08)<.001?p=.08:Math.abs(_)<.001?p=0:p=.1)}return{unitQty:Number(m.qty||0),unitPrice:Number(m.deliveryPrice||0),unitCost:Number(m.unitCost||0),taxRate:p}}),n=y.desiredDeliveryDate||qt(),i=is(t,n);return{subTotal:i.subTotal,tax8:i.tax8,tax10:i.tax10,totalAmount:i.finalTotal,totalProfit:i.profit,profitRate:i.profitRate,mappedItemsCount:h,totalItemsCount:y.products.length}},[y,l]),Le=u.useCallback(()=>{window.confirm(a("ë«ì¼ìê² ìµëê¹?","éãã¾ããï¼"))&&x()},[x,a]),ze=u.useCallback(async()=>{if(!F)return alert(a("ì¶í ì°½ê³ ë¥¼ ì íí´ì¼ í©ëë¤.","åºåº«å庫ã鏿ãã¦ãã ããã"));if(ie<_e)return alert(a("매íëì§ ìì ìíì´ ììµëë¤.","ãããã³ã°ããã¦ããªãååãããã¾ãã"));Ce(!0);const h=[...y.products],t=[];h.forEach(c=>{const p=l.get(c.masterCode);if(p&&p.linked_container_id){const r=w.find(_=>_.id===p.linked_container_id);if(r){const{salesPrice:_,costPrice:N}=Ie(r.code),I=r.sales_price||0;t.push({code:r.code,name:a(r.name_kr,r.name_jp),masterCode:r.code,qty:c.qty,unitPrice:-Math.abs(I),deliveryPrice:-Math.abs(I),unitCost:N,current_stock_units:0,is_direct_delivery:!1,isContainer:!0,isReserveFulfillment:!1})}}});const n=[...h,...t],i={...y,products:n,totalAmount:Xe,subTotal:Ye,tax8:Ze,tax10:Ve},m=await f(i,F);Ce(!1),m&&(X&&O?O():Le())},[y,ie,_e,l,w,F,a,Ie,f,Xe,Ye,Ze,Ve,X,O,Le]),Te=u.useCallback(async()=>{if(ie<_e)return alert(a("매íëì§ ìì ìíì´ ìì´ ì ì¥í ì ììµëë¤.","ãããã³ã°ããã¦ããªãååãããä¿åã§ãã¾ããã"));Ce(!0);try{const{error:h}=await M.from("partner_orders").update({items:y.products,final_total:Xe,sub_total:Ye,tax_8:Ze,tax_10:Ve,expected_date:y.desiredDeliveryDate||null}).eq("id",y.id).eq("company_id",A);if(h)throw h;if(B&&A&&y.id)try{const{updateDoc:t,doc:n,serverTimestamp:i}=await ys(async()=>{const{updateDoc:c,doc:p,serverTimestamp:r}=await import("./firebase-BEuJf_if.js").then(_=>_.O);return{updateDoc:c,doc:p,serverTimestamp:r}},__vite__mapDeps([0,1,2])),m=n(B,`companies/${A}/partner_orders`,y.id);await t(m,{products:y.products,totalAmount:Xe,subTotal:Ye,tax8:Ze,tax10:Ve,updatedAt:i(),desiredDeliveryDate:y.desiredDeliveryDate||null})}catch(t){console.warn("[PartnerOrderForm] Firestore ë ê±°ì ë기í ê±´ëë:",t?.message||t)}alert(a("ìì ì¬íì´ ì ì¥ëììµëë¤. (매ì¶ë¡ ë³íëì§ ìì)","ä¿®æ£å
容ãä¿åãã
2ã¾ããã(売ä¸ã«ã¯å¤æããã¾ãã)")),Le()}catch(h){console.error("ìì ì ì¥ ì¤í¨:",h),alert(a("ì ì¥ ì¤ ì¤ë¥ê° ë°ìíìµëë¤.","ä¿åä¸ã«ã¨ã©ã¼ãçºçãã¾ããã"))}finally{Ce(!1)}},[y,ie,_e,B,A,Xe,Ye,Ze,Ve,Le,a]),Rt=u.useRef({localOrder:y,isSubmitting:se,selectedWarehouseId:F,productMap:l,handleApproveClick:ze,handleSaveOnlyClick:Te,handleClose:Le,onPrev:$,onNext:O,hasPrev:V,hasNext:X,activeRowIndex:Qe});u.useEffect(()=>{Rt.current={localOrder:y,isSubmitting:se,selectedWarehouseId:F,productMap:l,handleApproveClick:ze,handleSaveOnlyClick:Te,handleClose:Le,onPrev:$,onNext:O,hasPrev:V,hasNext:X,activeRowIndex:Qe}},[y,se,F,l,ze,Te,Le,$,O,V,X,Qe]),u.useEffect(()=>{const h=t=>{const{localOrder:n,isSubmitting:i,selectedWarehouseId:m,productMap:c,handleSaveOnlyClick:p,handleClose:r,onPrev:_,onNext:N,hasPrev:I,hasNext:U,activeRowIndex:D}=Rt.current;if(t.key==="F3")t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),I&&_&&_();else if(t.key==="F4")t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),U&&N&&N();else if(t.key==="F2")t.preventDefault(),t.stopPropagation(),!i&&m&&(n?.status==="pending"||n?.status==="modified_after_approval")&&p();else if(t.key==="Escape")t.preventDefault(),t.stopPropagation(),r();else if(t.key==="F8"&&(t.preventDefault(),t.stopPropagation(),n?.products?.length>0)){let Z=0;const L=document.activeElement;if(L){const ee=L.closest("tr[data-row-index]");if(ee){const be=parseInt(ee.getAttribute("data-row-index"),10);isNaN(be)||(Z=be)}else D!==null&&D>=0&&(Z=D)}else D!==null&&D>=0&&(Z=D);const z=n.products[Z];if(z&&z.masterCode){const ee=c.get(z.masterCode);ee?ye(ee):alert(a("ìí ì 보를 ì°¾ì ì ììµëë¤.","ååæ
å ±ãè¦ã¤ããã¾ããã"))}else alert(a("매íë ìíì´ ìì´ ì´ë ¥ì ì¡°íí ì ììµëë¤.","ãããã³ã°ããã¦ããªãããå±¥æ´ãç
§ä¼ã§ãã¾ããã"))}};return window.addEventListener("keydown",h,{capture:!0}),()=>window.removeEventListener("keydown",h,{capture:!0})},[a]);const zt=h=>{if(Ee(t=>({...t,query:h})),De(-1),h.length>0){const t=ts(w,h).filter(n=>!n.is_archived).slice(0,50);xe(t)}else xe([])},Wt=h=>{if(ae.length===0){h.key==="Enter"&&me.current?.focus();return}if(h.key==="ArrowDown")h.preventDefault(),De(t=>Math.min(t+1,ae.length-1));else if(h.key==="ArrowUp")h.preventDefault(),De(t=>Math.max(t-1,0));else if(h.key==="Enter"){h.preventDefault();const t=ge>=0?ae[ge]:ae[0];Qt(t)}},Qt=h=>{const{salesPrice:t}=Ie(h.code);Ee({...pe,product:h,code:h.code,name:a(h.name_kr,h.name_jp),price:t,query:h.name_kr||h.name_jp,boxQty:"",unitQty:""}),xe([]),De(-1),me.current&&me.current.focus()},Ut=h=>{if(h&&h.preventDefault&&h.preventDefault(),!pe.product){alert(a("ìíì ì íí´ì£¼ì¸ì.","ååã鏿ãã¦ãã ããã"));return}const t=pe.product,n=Number(pe.unitQty)||0;if(n<=0){alert(a("ìëì ì
ë ¥í´ì£¼ì¸ì.","æ°éãå
¥åãã¦ãã ããã"));return}const i=t?.box_qty||1,m=Ie(t.code).costPrice,c=[];let p=n;if(pe.isSupportFulfillment&&pe.maxSupportQty>0){const r=Math.min(p,pe.maxSupportQty),_=pe.maxSupportQty-r,N=Math.floor(_/i),I=_%i;c.push({productCode:t.code,masterCode:t.code,name:a(t.name_kr,t.name_jp),masterProductName:a(t.name_kr,t.name_jp),qty:r,unitQty:r,boxQty:"",unitPrice:0,deliveryPrice:0,unitCost:m,taxRate:parseFloat(t.tax_rate||.1),is_direct_delivery:!!t.is_direct_delivery,isSupportFulfillment:!0,isReserveFulfillment:!1,supportDocId:pe.supportDocId,maxSupportQty:pe.maxSupportQty,note:`[ç¡åæ¯æ´æ®]: ${N}Box / ${I} (è¨ ${_})`,tempId:Date.now()+Math.random()}),p-=r}else if(pe.isReserveFulfillment&&pe.maxReserveQty>0){const r=Math.min(p,pe.maxReserveQty),_=pe.maxReserveQty-r,N=Math.floor(_/i),I=_%i;c.push({productCode:t.code,masterCode:t.code,name:a(t.name_kr,t.name_jp),masterProductName:a(t.name_kr,t.name_jp),qty:r,unitQty:r,boxQty:"",unitPrice:0,deliveryPrice:0,unitCost:m,taxRate:parseFloat(t.tax_rate||.1),is_direct_delivery:!!t.is_direct_delivery,isSupportFulfillment:!1,isReserveFulfillment:!0,maxReserveQty:pe.maxReserveQty,note:`[ç´å徿®]: ${N}Box / ${I} (è¨ ${_})`,tempId:Date.now()+Math.random()+1}),p-=r}if(p>0){const r=Number(pe.price)||0,{actualRebateCost:_,promotionIdToSave:N,rebateApplied:I,rebateId:U,rebateRemaining:D}=Ie(t.code),Z=!!pe.isReserveFulfillment||!!pe.isSupportFulfillment;
2c.push({productCode:t.code,masterCode:t.code,name:a(t.name_kr,t.name_jp),masterProductName:a(t.name_kr,t.name_jp),qty:p,unitQty:p,boxQty:"",unitPrice:r,deliveryPrice:r,unitCost:Z?0:m,taxRate:parseFloat(t.tax_rate||.1),is_direct_delivery:!!t.is_direct_delivery,isSupportFulfillment:!1,isReserveFulfillment:!1,isRebateApplied:I,rebateId:U,rebateRemaining:D,rebate_cost:_,promotion_id:N,note:pe.note?.includes("[ç¡åæ¯æ´æ®]")||pe.note?.includes("[ç´å徿®]")?a("ì´ê³¼ìë ì¼ë°ë¨ê° ì ì©","è¶
éæ°éä¸è¬å価é©ç¨"):"ì¶ê°ë¨",tempId:Date.now()+Math.random()+2})}if(t.linked_container_id&&!pe.isReserveFulfillment){const r=w.find(_=>_.id===t.linked_container_id);if(r){const{costPrice:_}=Ie(r.code),N=r.sales_price||0;c.push({productCode:r.code,masterCode:r.code,name:a(r.name_kr,r.name_jp),unitCost:_,unitPrice:-Math.abs(N),deliveryPrice:-Math.abs(N),boxQty:0,unitQty:n,qty:n,taxRate:r.tax_rate!==void 0?parseFloat(r.tax_rate):.1,current_stock_units:r.current_stock_units||0,boxCapacity:r.box_qty||1,isQuoteApplied:!1,note:a("(ìë í ì¸)","(èªåå²å¼)"),tempId:Date.now()+Math.random()+3})}}if(!pe.isSupportFulfillment){const r=v.find(_=>_.productCode===t.code);if(r){const _=r.buyQty||1,N=r.freeQty||1,I=Math.floor(n/_);if(I>0){const U=I*N;c.push({productCode:t.code,masterCode:t.code,name:a(t.name_kr,t.name_jp),unitPrice:0,deliveryPrice:0,unitCost:m,boxQty:0,unitQty:U,qty:U,taxRate:parseFloat(t.tax_rate||.1),is_direct_delivery:!!t.is_direct_delivery,isReserveFulfillment:!1,isSupportFulfillment:!1,isRebateApplied:!1,isPromoFreebie:!0,rebateId:r.id,note:`[${_}+${N} ããã¢ã¼ã·ã§ã³è´å]`,tempId:Date.now()+Math.random()+4})}}}K(r=>({...r,products:[...c,...r.products||[]]})),Ee({product:null,query:"",boxQty:"",unitQty:"",cost:"",price:"",profitRate:0}),E.current&&setTimeout(()=>E.current.focus(),50)},Ft=u.useCallback(h=>{K(t=>t&&{...t,desiredDeliveryDate:h})},[]),Kt=u.useCallback((h,t,n)=>{let i=String(n!==void 0?n:t).replace(/[ï¼-ï¼]/g,c=>String.fromCharCode(c.charCodeAt(0)-65248)).replace(/[^0-9.-]/g,""),m=parseFloat(i)||0;K(c=>{if(!c)return c;const p=[...c.products],r={...p[h]},N=l.get(r.masterCode)?.box_qty||1;let I=m;t==="boxQty"?(I=m*N,r.boxQty=m):r.boxQty=N>0&&m%N===0&&m!==0?m/N:"";let U=0;if(r.isReserveFulfillment&&I>r.maxReserveQty)U=I-r.maxReserveQty,r.qty=r.maxReserveQty,r.unitQty=r.maxReserveQty,t!=="boxQty"&&(r.boxQty=r.unitQty%N===0&&r.unitQty!==0?r.unitQty/N:""),r.note="[ç´å徿®]: 0Box / 0 (è¨ 0)",alert(a(`ìì½ ìì¬ ìë(${r.maxReserveQty}ê°)ì ì´ê³¼íì¬ ${U}ê°ë ì¼ë° ë¨ê°ë¡ ë¶í ì¶ê°ë©ëë¤.`,`äºç´æ®ä½æ°é(${r.maxReserveQty}å)ãè¶
éããããã${U}åã¯ä¸è¬å価ã§åå²è¿½å ããã¾ãã`));else if(r.isSupportFulfillment&&I>r.maxSupportQty)U=I-r.maxSupportQty,r.qty=r.maxSupportQty,r.unitQty=r.maxSupportQty,t!=="boxQty"&&(r.boxQty=r.unitQty%N===0&&r.unitQty!==0?r.unitQty/N:""),r.note="[ç¡åæ¯æ´æ®]: 0Box / 0 (è¨ 0)",alert(a(`무ìì§ì ìì¬ ìë(${r.maxSupportQty}ê°)ì ì´ê³¼íì¬ ${U}ê°ë ì¼ë° ë¨ê°ë¡ ë¶í ì¶ê°ë©ëë¤.`,`ç¡åæ¯æ´æ®ä½æ°é(${r.maxSupportQty}å)ãè¶
éããããã${U}åã¯ä¸è¬å価ã§åå²è¿½å ããã¾ãã`));else if(r.qty=I,r.unitQty=I,r.isReserveFulfillment){const D=r.maxReserveQty-I,Z=Math.floor(D/N),L=D%N;r.note=`[ç´å徿®]: ${Z}Box / ${L} (è¨ ${D})`}else if(r.isSupportFulfillment){const D=r.maxSupportQty-I,Z=Math.floor(D/N),L=D%N;r.note=`[ç¡åæ¯æ´æ®]: ${Z}Box / ${L} (è¨ ${D})`}if(p[h]=r,U>0){const{salesPrice:D,costPrice:Z}=Ie(r.masterCode),L={...r,qty:U,unitQty:U,boxQty:"",unitPrice:D,deliveryPrice:D,unitCost:Z,isSupportFulfillment:!1,isReserveFulfillment:!1,note:a("ì´ê³¼ìë ì¼ë°ë¨ê° ì ì©","è¶
éæ°éä¸è¬å価é©ç¨"),tempId:Date.now()+Math.random()};p.splice(h+1,0,L)}return{...c,products:p}})},[l,a,Ie]),Jt=u.useCallback((h,t)=>{let n=String(t).replace(/[ï¼-ï¼]/g,m=>String.fromCharCode(m.charCodeAt(0)-65248)).replace(/[^0-9.-]/g,""),i=parseFloat(n)||0;K(m=>{if(!m)return m;const c=[...m.products],p=c[h];return p.isSupportFulfillment||p.isReserveFulfillment||p.isPromoFreebie?m:(c[h]={...p,deliveryPrice:i,unitPrice:i},{...m,products:c})})},[]),Ht=u.useCallback(h=>{K(t=>{if(!t)return t;const n=t.products.filter((i,m)=>m!==h);return{...t,products:n}})},[]);return{localOrder:y,selectedWarehouseId:F,setSelectedWarehouseId:de,isSubmitting:se,newItem:pe,setNewItem:Ee,newItemResults:ae,setNewItemResults:xe,newItemActiveIndex:ge,setNewItemActiveIndex:De,newItemSearchRef:E,newItemBoxRef:me,newItemUnitRef:je,newItemCostRef:oe,newItemPriceRef:tt,newItemDropdownRef:qe,handleNewItemSearch:zt,handleNewItemKeyDown:Wt,handleSelectNewItem:Qt,handleAddNewItem:Ut,handleQtyChange:Kt,handlePriceChange:Jt,handleDeleteItem:Ht,searchQueries:Pe,searchResults:Re,activeIndices:Ue,handleSearchQueryChange:(h,t)=>{if(Ae(n=>({...n,[h]:t})),Je(n=>({...n,[h]:-1})),t.length>0){const n=ts(w,t).filter(i=>!i.is_archived).slice(0,10);Ne(i=>({...i,[h]:n}))}else Ne(n=>({...n,[h]:[]}))},handleSelectMapping:async(h,t)=>{const n=y.products[h];if(await j(n,t)){Ae(D=>({...D,[h]:""})),Ne(D=>({...D,[h]:[]}));const{costPrice:m,salesPrice:c}=Ie(t.code);let p=!1,r=0,_="";const N=Y[t.code];if(N&&N.remainingQty>0){p=!0,r=N.remainingQty;const D=t?.box_qty||1,Z=r-(Number(n.qty)||0),L=Math.floor(Z/D),z=Z%D;_=`[ç´å徿®]: ${L}Box / ${z} (è¨ ${Z})`}const I=[...y.products];I[h]={...I[h],masterCode:t.code,unitCost:m,deliveryPrice:p?0:I[h].deliveryPrice,is_direct_delivery:t.is_direct_delivery,isReserveFulfillment:p,maxReserveQty:r,note:_||I[h].note};let U=0;if(q&&F){const D=q.find(Z=>Z.productId===t.id&&Z.warehouseId===F);U=D?Number(D.quantity):0}I[h].current_stock_units=U,K({...y,products:I})}},historyProduct:Oe,setHistoryProduct:ye,handleApproveClick:ze,handleSaveOnlyClick:Te,handleClose:Le,subTotal:Ye,tax8:Ze,tax10:Ve,totalAmount:Xe,totalProfit:Ct,profitRate:Dt,mappedItemsCount:ie,totalItemsCount:_e,getRecentCost:h=>Ie(h).costPrice,onPrev:$,onNext:O,hasPrev:V,hasNext:X,setActiveRowIndex:Fe,handleDateChange:Ft}},$s=()=>{const s=new Date,o=s.getTime()+s.getTimezoneOffset()*6e4,x=540*60*1e3,f=new Date(o+x),a=f.getFullYear(),l=String(f.getMonth()+1).padStart(2,"0"),w=String(f.getDate()).padStart(2,"0");return`${a}-${l}-${w}`},Gt=({label:s,value:o,readOnly:x=!1,className:f="",type:a="text",onCh
2ange:l})=>e.jsxs("div",{className:"mb-1 w-full",children:[s&&e.jsx("label",{className:"block text-xs font-medium text-gray-700 mb-0.5",children:s}),e.jsx("input",{type:a,value:o||"",onChange:l,readOnly:x,className:`w-full p-1 border text-[14px] rounded focus:ring-1 focus:ring-teal-500 focus:border-teal-500 ${x?"bg-gray-100 text-gray-500 cursor-not-allowed":"bg-white border-gray-300"} ${f}`})]}),Ms=({localOrder:s,displayDate:o,selectedWarehouseId:x,setSelectedWarehouseId:f,warehouses:a,isSubmitting:l,onClose:w,T:d,onPrev:j,onNext:Q,hasPrev:W,hasNext:q,onDateChange:$})=>{const O=s.status==="pending"||s.status==="modified_after_approval";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-3 border-b bg-white shadow-sm sticky top-0 z-30 flex-shrink-0 flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2 text-gray-800",children:[e.jsx(vs,{className:"text-teal-600"}),d("ë°ì£¼ ìì¸ ì¹ì¸","çºæ³¨è©³ç´°æ¿èª"),e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full border ${s.status==="pending"?"bg-blue-50 text-blue-600 border-blue-200":"bg-gray-100 text-gray-600"}`,children:s.status.toUpperCase()})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center bg-gray-100 rounded-lg p-0.5 border border-gray-200",children:[e.jsx("button",{onClick:j,disabled:!W,className:`p-1 rounded-md transition-colors ${W?"hover:bg-white hover:shadow-sm text-gray-700":"text-gray-300 cursor-not-allowed"}`,title:"ì´ì (F3)",children:e.jsx(ls,{size:20})}),e.jsx("div",{className:"w-px h-4 bg-gray-300 mx-1"}),e.jsx("button",{onClick:Q,disabled:!q,className:`p-1 rounded-md transition-colors ${q?"hover:bg-white hover:shadow-sm text-gray-700":"text-gray-300 cursor-not-allowed"}`,title:"ë¤ì (F4)",children:e.jsx(cs,{size:20})})]}),e.jsx("button",{onClick:w,className:"text-gray-400 hover:text-red-600 transition-colors p-1 hover:bg-red-50 rounded-full",children:e.jsx(bt,{size:24})})]})]}),e.jsxs("div",{className:"p-4 bg-white border-b grid grid-cols-12 gap-3 text-sm",children:[e.jsx("div",{className:"col-span-12 md:col-span-2",children:e.jsx(Gt,{label:d("ë°ì£¼ë²í¸","çºæ³¨çªå·"),value:s.orderId,readOnly:!0})}),e.jsx("div",{className:"col-span-12 md:col-span-3",children:e.jsx(Gt,{label:d("ê±°ëì²ëª ","åå¼å å"),value:s.partnerName,readOnly:!0})}),e.jsx("div",{className:"col-span-12 md:col-span-2",children:e.jsx(Gt,{type:"date",label:d("ë°ì£¼ì¼ (ë©íí¬ë§)","çºæ³¨æ¥ (ç´å叿)"),value:o||$s(),onChange:V=>$&&$(V.target.value),readOnly:!O||l})}),e.jsxs("div",{className:"col-span-12 md:col-span-3",children:[e.jsxs("label",{className:"block text-xs font-medium text-gray-700 mb-0.5 flex items-center",children:[e.jsx(ds,{size:12,className:"mr-1 text-teal-600"}),d("ì¶í ì°½ê³ ","åºåº«å庫")," ",e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsxs("select",{value:x,onChange:V=>f(V.target.value),className:"w-full p-1 border text-[14px] bg-white border-gray-300 rounded focus:ring-1 focus:ring-teal-500 focus:border-teal-500",disabled:s.status!=="pending"||l,children:[e.jsx("option",{value:"",children:d("ì°½ê³ ì í","ååº«é¸æ")}),(a||[]).map(V=>e.jsxs("option",{value:V.id,children:[V.name," ",V.is_main?"(Main)":""]},V.id))]})]})]})]})},Rs=dt.memo(Ms),Qs=({localOrder:s,T:o,productMap:x,formatCurrency:f,getRecentCost:a,customerOrderCounts:l,newItem:w,setNewItem:d,newItemResults:j,setNewItemResults:Q,newItemActiveIndex:W,setNewItemActiveIndex:q,newItemSearchRef:$,newItemBoxRef:O,newItemUnitRef:V,newItemCostRef:X,newItemPriceRef:S,newItemDropdownRef:B,handleNewItemSearch:A,handleNewItemKeyDown:le,handleSelectNewItem:y,handleAddNewItem:K,handleQtyChange:F,handlePriceChange:de,handleDeleteItem:se,searchQueries:Ce,searchResults:ce,handleSearchQueryChange:re,handleSelectMapping:Y,setActiveRowIndex:ne})=>e.jsxs("div",{className:"flex-grow p-2 overflow-auto bg-gray-100",children:[e.jsx("div",{className:"bg-white border rounded shadow-sm min-h-[200px]",children:e.jsxs("table",{className:"min-w-full divide-y divide-gray-200",children:[e.jsx("thead",{className:"bg-gray-100 sticky top-0 z-10",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-2 py-2 text-left text-xs font-semibold text-gray-700 w-48",children:o("ë°ì£¼ ìí","çºæ³¨åå")}),e.jsx("th",{className:"px-2 py-2 text-left text-xs font-semibold text-gray-700 w-56",children:o("ìì¤í 매í","ã·ã¹ãã ãããã³ã°")}),e.jsx("th",{className:"px-2 py-2 text-center text-xs font-semibold text-gray-700 w-12 bg-gray-50",children:o("ì ì","å ¥æ°")}),e.jsx("th",{className:"px-2 py-2 text-right text-xs font-semibold text-gray-700 w-16",children:o("ë°ì¤","ç®±æ°")}),e.jsx("th",{className:"px-2 py-2 text-right text-xs font-semibold text-gray-700 w-16",children:o("ë±ê°","åæ°")}),e.jsx("th",{className:"px-2 py-2 text-right text-xs font-semibold text-gray-700 w-20 bg-orange-50",children:o("ìê°","å価")}),e.jsx("th",{className:"px-2 py-2 text-right text-xs font-semibold text-gray-700 w-24",children:o("ë¨ê°","å価")}),e.jsx("th",{className:"px-2 py-2 text-right text-xs font-semibold text-gray-700 w-16",children:o("ì´ìµ","å©ç")}),e.jsx("th",{className:"px-2 py-2 text-right text-xs font-semibold text-gray-700 w-28",children:o("ê¸ì¡","éé¡")}),e.jsx("th",{className:"px-2 py-2 text-center text-xs font-semibold text-gray-700 w-10",children:o("ìì ","åé¤")})]})}),e.jsxs("tbody",{className:"divide-y divide-gray-200",children:[s.status==="pending"&&e.jsxs("tr",{className:"bg-blue-50/50",children:[e.jsxs("td",{colSpan:"2",className:"px-2 py-2 relative align-top",children:[e.jsx("input",{ref:$,type:"text",placeholder:o("ìí ê²ì(F8)...","ååæ¤ç´¢..."),value:w.query,onChange:v=>A(v.target.value),onKeyDown:le,className:"w-full p-1 border rounded text-sm focus:ring-2 focus:ring-blue-500"}),w.isReserveFulfillment&&w.note&&e.jsx("div",{className:"mt-1 text-[11px] font-bold text-indigo-700 bg-indigo-100 px-2 py-0.5 rounded border border-indigo-200 inline-block shadow-sm",children:w.note}),j.length>0&&e.jsx("div",{ref:B,className:"absolute z-20 top-full left-0 w-full bg-white border shadow-lg max-h-40 overflow-y-auto",children:j.map((v,J)=>{const R=l&&l[v.code]?l[v.code]:0;return e.jsxs("div",{className:`p-2 cursor-pointer text-sm flex items-center justify-between ${J===W?"bg-blue-100":"hover:bg-blue-50"}`,onMouseDown:()=>y(v),children:[e.jsxs("div",{className:"truncate",children:[e.jsxs("span",{className:"font-bold",children:["[",v.code,"]"]})," ",o(v.name_kr,v.name_jp)]}),R>0&&e.jsxs("span",{className:"ml-2 text-[10px] font-bold text-blue-600 bg-blue-100 px-1.5 py-0.5 rounded-full shrink-0",children:[R,o("ê±´","ä»¶")]})]},v.id)})})]}),e.jsx("td",{className:"px-2 py-2 text-center text-xs text-gray-600 bg-gray-50 pt-3",children:w.product?.box_qty||"-"}),e.jsx("td",{className:"px-2 py-2 align-top",children:e.jsx("input",{ref:O,type:"number",placeholder:"Box",value:w.boxQty,onChange:v=>{const J=v.target.value,R=parseFloat(J)||0,ue=w.product?.box_qty||1;d(C=>({...C,boxQty:J,unitQty:R*ue}))},onKeyDown:v=>v.key==="Enter"&&V.current?.focus(),className:"w-full p-1 border rounded text-right text-sm"})}),e.jsx("td",{className:"px-2 py-2 align-top",children:e.jsx("input",{ref:V,type:"number",placeholder:"Unit",value:w.unitQty,onChange:v=>{const J=v.target.value,R=parseFloat(J)||0,ue=w.product?.box_qty||1,C=ue>0&&R%ue===0?R/ue:"";d(P=>({...P,unitQty:J,boxQty:C}))},onKeyDown:v=>v.key==="Enter"&&X.current?.focus(),className:"w-full p-1 border rounded text-right text-sm"})}),e.jsx("td",{className:"px-2 py-2 align-top",children:e.jsx("input",{ref:X,type:"number",placeholder:"Cost",value:w.cost,onChange:v=>{const J=v.target.value,R=parseFloat(J)||0,ue=parseFloat(w.price)||0,C=ue>0?(ue-R)/ue*100:0;d(P=>({...P,cost:J,profitRate:C}))},onKeyDown:v=>v.key==="Enter"&&S.current?.focus(),className:"w-full p-1 border rounded text-right text-sm bg-orange-50"})}),e.jsx("td",{className:"px-2 py-2 align-top",children:e.jsx("input",{ref:S,type:"number",placeholder:"Price",value:w.price,onChange:v=>{const J=v.target.value,R=parseFloat(J)||0,ue=parseFloat(w.cost)||0,C=R>0?(R-ue)/R*100:0;d(P=>({...P,price:J,profitRate:C}))},onKeyDown:v=>v.key==="Enter"&&K(),className:"w-full p-1 border rounded text-right text-sm font-bold text-blue-700",disabled:s.status!=="pending"})}),e.jsx("td",{className:"px-2 py-2 align-top text-right text-xs font-bold pt-3",children:e.jsxs("span",{className:w.profitRate<15?"text-red-600":"text-blue-600",children:[w.profitRate?w.profitRate.toFixed(1):0,"%"]})}),e.jsx("td",{className:"text-center align-middle",children:e.jsx("button",{onClick:K,className:"bg-blue-600 hover:bg-blue-700 text-white p-1 rounded transition-colors shadow-sm",children:e.jsx(us,{size:16})})}),e.jsx("td",{})]}),s.products.map((v,J)=>{const R=x.get(v.masterCode),ue=a(v.masterCode),C=ue>0?ue:R?.cost_price||0,P=R?.box_qty||1,T=v.deliveryPrice>0?(v.deliveryPrice-C)/v.deliveryPrice*100:0,b=T<15,E=P>0&&v.qty%P===0?v.qty/P:"",me=R?.tax_rate?parseFloat(R.tax_rate):.1,je=Math.abs(me-.08)<.001;return e.jsxs("tr",{"data-row-index":J,onFocusCapture:()=>ne&&ne(J),onClickCapture:()=>ne&&ne(J),className:`hover:bg-gray-50 3 ${v.isReserveFulfillment?"bg-indigo-50/20":""} 4 ${v.isSupportFulfillment?"bg-pink-50/30":""} 5 ${v.isPromoFreebie?"bg-amber-50/40 border-l-4 border-l-amber-400":""} 6 ${v.isRebateApplied?"bg-blue-50/20":""} 7 `,children:[e.jsxs("td",{className:"px-2 py-2 align-top",children:[e.jsx("div",{className:"text-sm font-medium text-gray-900",children:v.name}),e.jsxs("div",{className:"text-xs text-gray-500 flex gap-1",children:[e.jsx("span",{children:v.code}),v.is_direct_delivery&&e.jsx("span",{className:"bg-purple-100 text-purple-700 px-1 rounded font-bold",children:"ì¬ì "})]})]}),e.jsx("td",{className:"px-2 py-2 align-top relative",children:R?e.jsxs("div",{className:`p-1.5 border rounded text-xs 8 ${v.isReserveFulfillment?"bg-indigo-50 border-indigo-200":v.isSupportFulfillment?"bg-pink-50 border-pink-200":v.isPromoFreebie?"bg-amber-50 border-amber-300":v.isRebateApplied?"bg-blue-50 border-blue-300":"bg-blue-50 border-blue-200"}`,children:[e.jsxs("div",{className:`font-bold flex justify-between 9 ${v.isReserveFulfillment?"text-indigo-800":v.isSupportFulfillment?"text-pink-800":v.isPromoFreebie?"text-amber-800":v.isRebateApplied?"text-blue-800":"text-blue-700"}`,children:[R.code,e.jsxs("span",{className:`font-normal ${v.current_stock_units<v.qty?"text-red-500 font-bold":"text-blue-500"}
9`,children:["Stock: ",Number(v.current_stock_units).toLocaleString()]})]}),e.jsx("div",{className:`truncate 10 ${v.isReserveFulfillment?"text-indigo-700":v.isSupportFulfillment?"text-pink-700":v.isPromoFreebie?"text-amber-700":"text-blue-600"}`,children:o(R.name_kr,R.name_jp)}),v.isReserveFulfillment&&v.note&&e.jsx("div",{className:"mt-1 text-indigo-700 font-bold bg-indigo-200 px-1.5 py-0.5 rounded-sm inline-block shadow-sm",children:v.note}),v.isSupportFulfillment&&e.jsxs("div",{className:"mt-1 flex flex-col gap-0.5",children:[e.jsxs("span",{className:"text-pink-700 font-bold bg-pink-200 px-1.5 py-0.5 rounded-sm inline-block shadow-sm w-fit",children:["ð ",o("ç¡åæ¯æ´ (0å)","ç¡åæ¯æ´ (0å)")]}),v.note&&e.jsx("span",{className:"text-pink-700 font-medium bg-pink-100 px-1.5 py-0.5 rounded-sm inline-block w-fit text-[10px]",children:v.note})]}),v.isRebateApplied&&e.jsx("div",{className:"mt-1",children:e.jsxs("span",{className:"text-blue-700 font-bold bg-blue-200 px-1.5 py-0.5 rounded-sm inline-block shadow-sm",children:["ð ",o("N+M ìëì ì© (ì¬ìí ë³ëí ì¶ê°ë¨)","N+Mèªåé©ç¨ (æ¯åè¡è¿½å )")]})}),v.isPromoFreebie&&e.jsxs("div",{className:"mt-1 flex flex-col gap-0.5",children:[e.jsxs("span",{className:"text-amber-800 font-bold bg-amber-300 px-1.5 py-0.5 rounded-sm inline-block shadow-sm w-fit",children:["ð ",o("N+M ì¬ìí (0å)","N+Mæ¯å (0å)")]}),v.note&&e.jsx("span",{className:"text-amber-800 font-medium bg-amber-100 px-1.5 py-0.5 rounded-sm inline-block w-fit text-[10px]",children:v.note})]})]}):e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"text",placeholder:o("매í ê²ì...","ãããã³ã°æ¤ç´¢..."),value:Ce[J]||"",onChange:oe=>re(J,oe.target.value),className:"w-full p-1 text-xs border border-red-300 bg-red-50 rounded focus:ring-red-500"}),ce[J]?.length>0&&e.jsx("div",{className:"absolute z-10 mt-1 w-full border border-gray-300 rounded-md bg-white shadow-lg max-h-40 overflow-y-auto left-0",children:ce[J].map(oe=>e.jsxs("div",{className:"p-2 hover:bg-teal-50 cursor-pointer text-xs border-b last:border-0",onMouseDown:()=>Y(J,oe),children:[e.jsxs("span",{className:"font-bold text-teal-700",children:["[",oe.code,"]"]})," ",o(oe.name_kr,oe.name_jp)]},oe.id))})]})}),e.jsx("td",{className:"px-2 py-2 text-center text-xs text-gray-500 bg-gray-50 pt-3",children:P}),e.jsx("td",{className:"px-2 py-2 align-top",children:e.jsx("input",{type:"number",value:E,onChange:oe=>F(J,"boxQty",oe.target.value),className:"w-full p-1 border rounded text-right text-sm",disabled:s.status!=="pending"})}),e.jsx("td",{className:"px-2 py-2 align-top",children:e.jsx("input",{type:"number",value:v.qty,onChange:oe=>F(J,"qty",oe.target.value),className:"w-full p-1 border rounded text-right text-sm font-bold",disabled:s.status!=="pending"})}),e.jsx("td",{className:"px-2 py-2 align-top text-right text-sm text-gray-500 bg-orange-50",children:f(C)}),e.jsx("td",{className:"px-2 py-2 align-top text-right",children:e.jsx("input",{type:"number",value:v.deliveryPrice,onChange:oe=>de(J,oe.target.value),className:`w-full p-1 border rounded text-right text-sm font-bold 11 ${v.isReserveFulfillment?"bg-indigo-100 text-indigo-800 border-indigo-400":v.isSupportFulfillment?"bg-pink-100 text-pink-800 border-pink-400":v.isPromoFreebie?"bg-amber-100 text-amber-800 border-amber-400":"text-blue-700"}`,disabled:s.status!=="pending"||v.isSupportFulfillment||v.isReserveFulfillment||v.isPromoFreebie})}),e.jsx("td",{className:"px-2 py-2 align-top text-right",children:e.jsxs("div",{className:`text-[10px] font-bold ${b?"text-red-500":"text-green-600"}`,children:[T.toFixed(1),"%"]})}),e.jsxs("td",{className:"px-2 py-2 align-top text-right text-sm font-bold text-gray-800",children:[f((v.qty||0)*(v.deliveryPrice||0)),e.jsxs("div",{className:"text-[10px] text-gray-400",children:["(Tax: ",je?"8%":"10%",")"]})]}),e.jsx("td",{className:"px-2 py-2 align-top text-center",children:e.jsx("button",{onClick:()=>se(J),className:"text-gray-400 hover:text-red-500",disabled:s.status!=="pending",children:e.jsx(bt,{size:16})})})]},J)})]})]})}),s.modificationReason&&s.status==="pending"&&e.jsxs("div",{className:"mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-900 text-sm shadow-sm",children:[e.jsxs("h5",{className:"font-bold mb-1 flex items-center",children:[e.jsx("span",{className:"mr-2",children:"ð¢"}),o("ë°ì£¼ì ìì²ì¬í","çºæ³¨è ããã®è¦æ")]}),e.jsx("div",{className:"whitespace-pre-wrap leading-relaxed text-gray-700 pl-6",children:s.modificationReason})]})]}),At=({label:s,value:o,isTotal:x=!1,color:f="text-gray-900",size:a="normal",subLabel:l,formatCurrency:w})=>e.jsxs("div",{className:`flex justify-between items-center ${x?"border-t-2 border-teal-500 pt-1 font-bold":"py-0.5"} ${a==="large"?"mt-1":""}`,children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:`text-sm ${x?"text-base":"text-gray-600"}`,children:s}),l&&e.jsx("span",{className:"text-xs text-gray-400",children:l})]}),e.jsx("span",{className:`${a==="large"?"text-lg":"text-base"} ${f} font-mono`,children:w(o||0)})]}),Fs=({actions:s})=>e.jsx("div",{className:"absolute bottom-0 left-0 w-full bg-gray-800 text-white px-4 py-2 flex items-center justify-end space-x-3 shadow-lg z-50 border-t border-gray-600 rounded-b-lg",children:s.map((o,x)=>e.jsxs("button",{onClick:o.handler,disabled:o.disabled,className:`flex items-center px-4 py-1.5 rounded text-sm font-bold border transition-colors shadow-md 12 ${o.disabled?"opacity-50 cursor-not-allowed bg-gray-600 border-gray-500":o.primary?"bg-teal-600 hover:bg-teal-500 border-teal-400":o.warning?"bg-orange-600 hover:bg-orange-500 border-orange-400":"bg-gray-700 hover:bg-gray-600 border-gray-500"}`,children:[o.key&&e.jsxs("span",{className:"text-yellow-400 mr-2",children:["[",o.key,"]"]}),o.icon&&e.jsx("span",{className:"mr-2",children:o.icon}),o.label]},x))}),qs=({subTotal:s,tax8:o,tax10:x,totalAmount:f,profitRate:a,formatCurrency:l,T:w,localOrder:d,isSubmitting:j,selectedWarehouseId:Q,handleApproveClick:W,handleSaveOnlyClick:q,handleClose:$,localOrderProducts:O,productMap:V,setHistoryProduct:X}
12)=>{const S=[];(d.status==="pending"||d.status==="modified_after_approval")&&(S.push({key:"F2",label:j?w("ì ì¥ ì¤...","ä¿åä¸..."):w("ìì ë´ì© ì ì¥ (ë³´ë¥)","ä¿®æ£å
容ãä¿å (ä¿ç)"),icon:e.jsx(Ot,{size:16}),primary:!0,handler:q,disabled:j||!Q}),S.push({key:"F8",label:w("ì´ë ¥ì¡°í","å±¥æ´ç
§ä¼"),icon:e.jsx(_s,{size:16}),handler:()=>{const le=O.find(y=>y.masterCode);if(le){const y=V.get(le.masterCode);y&&X(y)}else alert(w("매íë ìíì´ ììµëë¤.","ãããã³ã°ãããååãããã¾ããã"))}})),S.push({key:"ESC",label:w("ë«ê¸°","éãã"),icon:e.jsx(bt,{size:16}),handler:$,disabled:j});const B=d.memo||d.modificationReason||"",A=B?B.replace(/\[Note\]\n?/g,"").trim():"";return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"bg-white border-t p-2 px-4 shadow-inner mb-12 flex-shrink-0",children:e.jsxs("div",{className:"flex justify-between gap-6 items-end",children:[e.jsxs("div",{className:"flex-1 bg-yellow-50/70 border border-yellow-200 rounded-lg p-3 max-h-[88px] overflow-y-auto shadow-sm",children:[e.jsxs("div",{className:"text-xs font-bold text-yellow-800 mb-1 flex items-center gap-1",children:[e.jsx(Xt,{size:14}),w("ë°ì£¼ì ìì²ì¬í","çºæ³¨è
ããã®è¦æ")]}),e.jsx("div",{className:"text-sm text-gray-700 whitespace-pre-wrap leading-snug",children:A||e.jsx("span",{className:"text-gray-400 italic",children:w("ìì²ì¬íì´ ììµëë¤.","è¦æäºé
ã¯ããã¾ããã")})})]}),e.jsxs("div",{className:"flex justify-end gap-6 items-end shrink-0",children:[e.jsx("div",{className:"w-40",children:e.jsx(At,{label:w("ê³µê¸ê°ì¡","ç¨æéé¡"),value:s,formatCurrency:l})}),e.jsxs("div",{className:"w-40 flex flex-col gap-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-gray-500",children:[e.jsx("span",{children:"8%"}),e.jsx("span",{children:l(o)})]}),e.jsxs("div",{className:"flex justify-between text-xs text-gray-500 border-b pb-1",children:[e.jsx("span",{children:"10%"}),e.jsx("span",{children:l(x)})]}),e.jsx(At,{label:w("ìë¹ì¸ (Total)","æ¶è²»ç¨ (è¨)"),value:o+x,color:"text-amber-600",formatCurrency:l})]}),e.jsxs("div",{className:"w-48",children:[e.jsx("div",{className:"border-b mb-1 pb-1",children:e.jsx(At,{label:w("íê· ì´ìµì¨","å¹³åå©çç"),value:`${a}%`,color:parseFloat(a)<15?"text-red-600":"text-blue-600",formatCurrency:le=>le})}),e.jsx(At,{label:w("ì´ í©ê³ (JPY)","åè¨ (JPY)"),value:f,isTotal:!0,size:"large",color:"text-blue-700",formatCurrency:l})]})]})]})}),e.jsx(Fs,{actions:S})]})},As=({product:s,salesData:o,purchases:x,onClose:f,T:a,formatCurrency:l,currentPartnerName:w,currentPartnerCode:d})=>{const[j,Q]=u.useState("1"),[W,q]=u.useState(30);u.useEffect(()=>{q(30)},[j]),u.useEffect(()=>{const S=B=>{["1","2","3","4"].includes(B.key)?(B.preventDefault(),Q(B.key)):B.key==="Escape"&&(B.preventDefault(),f())};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[f]);const $=u.useMemo(()=>{if(!s)return[];const S=new Date,B=new Date;B.setMonth(S.getMonth()-3);let A=[],le=[];return(j==="1"||j==="2"||j==="3")&&(A=(o||[]).flatMap(y=>(y.items||[]).filter(K=>K.productCode===s.code).map(K=>{let F=null;try{y.date&&(F=y.date.toDate?y.date.toDate():new Date(y.date),isNaN(F.getTime())&&(F=null))}catch{F=null}return{date:F,type:"Sale",partner:y.customerName||y.customerNameJp||"",partnerCode:y.customerCode||y.customerId||"",price:K.unitPrice,qty:K.unitQty,slipNo:y.slipNo}})).filter(y=>y.date&&y.date>=B),j==="1"&&(A=A.filter(y=>{const K=String(y.partnerCode).trim(),F=String(d||"").trim();if(F&&K&&K===F)return!0;const de=String(y.partner||"").trim().toLowerCase(),se=String(w||"").trim().toLowerCase();return!!(se&&de&&(de.includes(se)||se.includes(de)))}))),(j==="3"||j==="4")&&(le=(x||[]).flatMap(y=>(y.items||[]).filter(K=>K.productCode===s.code).map(K=>{let F=null;try{y.purchaseDate&&(F=y.purchaseDate.toDate?y.purchaseDate.toDate():new Date(y.purchaseDate),isNaN(F.getTime())&&(F=null))}catch{F=null}return{date:F,type:"Purchase",partner:y.supplierName||y.supplier,partnerCode:y.supplierCode||"",price:K.unitCost!==void 0?K.unitCost:K.unitPrice,qty:K.unitQty,slipNo:y.docNo||y.slipNo}})).filter(y=>y.date&&y.date>=B)),[...A,...le].sort((y,K)=>K.date-y.date)},[s,o,x,j,w,d]),O=$.slice(0,W),V=()=>{switch(j){case"1":return a(`ë§¤ì¶ ì´ë ¥ (íì¬ ê±°ëì²: ${w})`,`売ä¸å±¥æ´ (ç¾åå¼å
: ${w})`);case"2":return a("ì ì²´ ë§¤ì¶ ì´ë ¥","å
¨å£²ä¸å±¥æ´");case"3":return a("íµí© ì´ë ¥ (매ì¶/매ì
)","çµ±åå±¥æ´ (売ä¸/ä»å
¥)");case"4":return a("매ì
ì´ë ¥ (ìê°)","ä»å
¥å±¥æ´ (å価)");default:return""}},X=S=>{if(!S)return"-";try{return S.toISOString().split("T")[0]}catch{return"-"}};return e.jsx("div",{className:"fixed inset-0 z-[70] bg-black/60 flex items-center justify-center p-4",onClick:S=>{S.stopPropagation(),f()},children:e.jsxs("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-3xl overflow-hidden flex flex-col max-h-[90vh]",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"p-3 border-b bg-gray-50 flex justify-between items-center flex-shrink-0",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-bold text-gray-800 flex items-center gap-2",children:[a("ìí ì´ë ¥ ì¡°í","ååå±¥æ´ç
§ä¼"),e.jsxs("span",{className:"text-sm font-normal text-gray-500",children:["[",s?.code,"] ",a(s?.name_kr,s?.name_jp)]})]}),e.jsxs("div",{className:"flex gap-2 mt-1 text-xs text-gray-500",children:[e.jsxs("span",{className:`curs
12or-pointer transition-colors ${j==="1"?"text-blue-600 font-bold":"hover:text-blue-500"}`,onClick:()=>Q("1"),children:["[1] ",a("í ê±°ëì²","ç¾åå¼å
")]}),e.jsxs("span",{className:`cursor-pointer transition-colors ${j==="2"?"text-blue-600 font-bold":"hover:text-blue-500"}`,onClick:()=>Q("2"),children:["[2] ",a("ì ì²´ 매ì¶","å
¨å£²ä¸")]}),e.jsxs("span",{className:`cursor-pointer transition-colors ${j==="3"?"text-purple-600 font-bold":"hover:text-purple-500"}`,onClick:()=>Q("3"),children:["[3] ",a("íµí©","çµ±å")]}),e.jsxs("span",{className:`cursor-pointer transition-colors ${j==="4"?"text-red-600 font-bold":"hover:text-red-500"}`,onClick:()=>Q("4"),children:["[4] ",a("매ì
","ä»å
¥")]})]})]}),e.jsx("button",{onClick:f,children:e.jsx(bt,{size:20})})]}),e.jsxs("div",{className:"p-2 bg-blue-50 text-xs text-center border-b font-bold text-blue-800 flex-shrink-0",children:[V(),e.jsxs("span",{className:"ml-2 text-blue-600 font-normal",children:["(",a("ìµê·¼ 3ê°ì","ç´è¿3ã¶æ"),")"]})]}),e.jsxs("div",{className:"overflow-y-auto flex-grow",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-100 text-gray-600 sticky top-0 z-10 shadow-sm",children:e.jsxs("tr",{children:[e.jsx("th",{className:"p-2 text-left w-24",children:a("ë ì§","æ¥ä»")}),e.jsx("th",{className:"p-2 text-left w-28",children:a("ì íë²í¸","ä¼ç¥¨çªå·")}),e.jsx("th",{className:"p-2 text-left",children:a("ê±°ëì²/ê³µê¸ì¬","åå¼å
/ä¾çµ¦è
")}),e.jsx("th",{className:"p-2 text-right w-24",children:a("ë¨ê°","å価")}),e.jsx("th",{className:"p-2 text-right w-20",children:a("ìë","æ°é")})]})}),e.jsxs("tbody",{children:[O.map((S,B)=>e.jsxs("tr",{className:"border-b hover:bg-gray-50",children:[e.jsx("td",{className:"p-2 text-gray-500",children:X(S.date)}),e.jsxs("td",{className:"p-2",children:[e.jsx("div",{className:"font-mono text-gray-700",children:S.slipNo}),e.jsx("span",{className:`text-[10px] px-1 rounded ${S.type==="Sale"?"bg-blue-100 text-blue-700":"bg-red-100 text-red-700"}`,children:S.type==="Sale"?a("매ì¶","売ä¸"):a("매ì
","ä»å
¥")})]}),e.jsxs("td",{className:"p-2 text-gray-800",children:[e.jsx("div",{children:S.partner}),S.partnerCode&&e.jsxs("div",{className:"text-xs text-gray-400",children:["(",S.partnerCode,")"]})]}),e.jsx("td",{className:"p-2 text-right font-medium",children:l(S.price)}),e.jsx("td",{className:"p-2 text-right",children:S.qty})]},B)),$.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:"5",className:"p-10 text-center text-gray-400",children:a("í´ë¹ ì¡°ê±´ì ì´ë ¥ì´ ììµëë¤.","該å½ããå±¥æ´ãããã¾ããã")})})]})]}),W<$.length&&e.jsx("div",{className:"p-4 flex justify-center bg-gray-50 border-t",children:e.jsxs("button",{onClick:()=>q(S=>S+30),className:"flex items-center gap-2 px-6 py-2 bg-white border border-gray-300 rounded-full shadow-sm text-sm font-medium text-gray-600 hover:bg-gray-100 hover:text-teal-600 transition-all",children:[e.jsx(ws,{size:16}),a("ë 보기","ãã£ã¨è¦ã")," (",$.length-W,"+)"]})})]})]})})},Es=s=>{const{isOpen:o,T:x,formatCurrency:f,salesData:a,purchases:l,customerOrderCounts:w}=s,{localOrder:d,selectedWarehouseId:j,setSelectedWarehouseId:Q,isSubmitting:W,newItem:q,setNewItem:$,newItemResults:O,setNewItemResults:V,newItemActiveIndex:X,setNewItemActiveIndex:S,newItemSearchRef:B,newItemBoxRef:A,newItemUnitRef:le,newItemCostRef:y,newItemPriceRef:K,newItemDropdownRef:F,handleNewItemSearch:de,handleNewItemKeyDown:se,handleSelectNewItem:Ce,handleAddNewItem:ce,handleQtyChange:re,handlePriceChange:Y,handleDeleteItem:ne,searchQueries:v,searchResults:J,handleSearchQueryChange:R,handleSelectMapping:ue,historyProduct:C,setHistoryProduct:P,handleApproveClick:T,handleClose:b,handleSaveOnlyClick:E,handleDateChange:me,subTotal:je,tax8:oe,tax10:tt,totalAmount:qe,profitRate:pe,getRecentCost:Ee,onPrev:ae,onNext:xe,hasPrev:ge,hasNext:De}=Is(s),[Pe,Ae]=u.useState(!1);u.useEffect(()=>{if(o&&d){Ae(!1),Ne(null);const ye=setTimeout(()=>{Ae(!0)},50);return()=>clearTimeout(ye)}},[o,d?.id]);const[Re,Ne]=u.useState(null),Ue=u.useMemo(()=>
12{if(Re)return Re;if(!d)return"";let ye=d.desiredDeliveryDate||d.expected_date||d.orderDate;if(ye){if(typeof ye=="string"){const Fe=ye.match(/^(\d{4}-\d{2}-\d{2})/);if(Fe)return Fe[1]}try{const Fe=ye.toDate?ye.toDate():new Date(ye);if(!isNaN(Fe.getTime()))return new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Tokyo"}).format(Fe)}catch(Fe){console.error("Date conversion error",Fe)}}return new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Tokyo"}).format(new Date)},[d,Re]),Je=u.useCallback(ye=>{Ne(ye),typeof me=="function"&&me(ye)},[me]),Oe=u.useCallback(()=>{P(null)},[P]);return!o||!d?null:e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4",children:e.jsxs("div",{className:"bg-gray-50 flex flex-col w-[90vw] h-[90vh] max-w-none rounded-lg shadow-2xl overflow-hidden relative border border-gray-300",children:[C&&e.jsx(As,{product:C,salesData:a,purchases:l,onClose:Oe,T:x,formatCurrency:f,currentPartnerName:d.partnerName,currentPartnerCode:d.partnerId}),e.jsx(Rs,{localOrder:d,displayDate:Ue,onDateChange:Je,selectedWarehouseId:j,setSelectedWarehouseId:Q,warehouses:s.warehouses,isSubmitting:W,onClose:b,T:x,onPrev:ae,onNext:xe,hasPrev:ge,hasNext:De}),Pe?e.jsx(Qs,{localOrder:d,T:x,productMap:s.productMap,formatCurrency:f,getRecentCost:Ee,newItem:q,setNewItem:$,newItemResults:O,setNewItemResults:V,newItemActiveIndex:X,setNewItemActiveIndex:S,newItemSearchRef:B,newItemBoxRef:A,newItemUnitRef:le,newItemCostRef:y,newItemPriceRef:K,newItemDropdownRef:F,handleNewItemSearch:de,handleNewItemKeyDown:se,handleSelectNewItem:Ce,handleAddNewItem:ce,handleQtyChange:re,handlePriceChange:Y,handleDeleteItem:ne,searchQueries:v,searchResults:J,handleSearchQueryChange:R,handleSelectMapping:ue,customerOrderCounts:w}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center bg-white",children:[e.jsx(Tt,{className:"w-10 h-10 animate-spin text-teal-500 mb-4"}),e.jsx("p",{className:"text-gray-500 font-bold",children:x("ìí 목ë¡ì ë¶ë¬ì¤ë ì¤...","ååãªã¹ããèªã¿è¾¼ãã§ãã¾ã...")})]}),e.jsx(qs,{subTotal:je,tax8:oe,tax10:tt,totalAmount:qe,profitRate:pe,formatCurrency:f,T:x,localOrder:d,isSubmitting:W,selectedWarehouseId:j,handleApproveClick:T,handleSaveOnlyClick:E,handleClose:b,localOrderProducts:d.products,productMap:s.productMap,setHistoryProduct:P})]})})},Os=dt.memo(Es),lt=()=>{const s=new Date,o=s.getTime()+s.getTimezoneOffset()*6e4,x=540*60*1e3,f=new Date(o+x),a=f.getFullYear(),l=String(f.getMonth()+1).padStart(2,"0"),w=String(f.getDate()).padStart(2,"0");return`${a}-${l}-${w}`},ct=s=>{if(!s)return"";if(typeof s=="string"){const o=s.match(/^(\d{4}-\d{2}-\d{2})/);if(o)return o[1]}try{const o=s.toDate?s.toDate():new Date(s);return isNaN(o.getTime())?"":new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Tokyo"}
12).format(o)}catch{return""}},Yt=async(s,o)=>{const f=new Date(new Date().getTime()+324e5),a=String(f.getUTCFullYear()).slice(-2),l=String(f.getUTCMonth()+1).padStart(2,"0"),w=String(f.getUTCDate()).padStart(2,"0"),d=`${a}${l}${w}`,{data:j,error:Q}=await M.rpc("get_next_order_slip_no",{p_company_id:o,p_date_sign:d,p_prefix:"SL"});if(Q)throw console.error("generateSecureSlipNo Supabase RPC ì¤ë¥:",Q.message),new Error(`ì í ë²í¸ ìì± ì¤ ì¤ë¥ ë°ì: ${Q.message}`);return j},rs=new WeakMap,Bs=s=>{const o=new Map,x=[...s].sort((f,a)=>{const l=f.purchaseDate?.toDate?f.purchaseDate.toDate().getTime():new Date(f.purchaseDate).getTime(),w=a.purchaseDate?.toDate?a.purchaseDate.toDate().getTime():new Date(a.purchaseDate).getTime();if(l!==w)return w-l;const d=f.createdAt?new Date(f.createdAt).getTime():0;return(a.createdAt?new Date(a.createdAt).getTime():0)-d});for(const f of x){if(!f.items)continue;const a=new Set;for(const l of f.items){const w=String(l.productCode).trim();if(a.has(w)||(a.add(w),o.has(w)))continue;const d=l.unitCost!==void 0?l.unitCost:l.unitPrice;d>0&&o.set(w,Math.round(Number(d)))}}return o},Ls=(s,o)=>{if(!s||s.length===0)return null;let x=rs.get(s);x||(x=Bs(s),rs.set(s,x));const f=x.get(String(o).trim());return f!==void 0?f:null},zs=s=>s==null?"Â¥-":new Intl.NumberFormat("ja-JP",{style:"currency",currency:"JPY",maximumFractionDigits:0}).format(s),Ws=s=>{if(!s)return"-";const o=s.replace(/\[Note\]\n?/g,"").trim();return o?o.length>6?o.substring(0,6)+"...":o:"-"},as=new WeakMap,Us=s=>{const o=new Map,x=[...s].sort((f,a)=>{const l=f.date?.toDate?f.date.toDate().getTime():new Date(f.date).getTime();return(a.date?.toDate?a.date.toDate().getTime():new Date(a.date).getTime())-l});for(const f of x){if(!f.items)continue;const a=new Set;for(const l of f.items){const w=l.productCode;if(!a.has(w)&&(a.add(w),l.unitCost!==void 0))for(const d of[f.customerCode,f.customerId]){if(d==null||d==="")continue;const j=`${d}|${w}`;o.has(j)||o.set(j,l.unitCost)}}}return o},Ks=(s,o,x)=>{if(!s||s.length===0)return null;let f=as.get(s);f||(f=Us(s),as.set(s,f));const a=f.get(`${o}|${x}`);return a!==void 0?a:null},Js=s=>{switch(s){case"pending":return"bg-blue-100 text-blue-700 border-blue-200";case"approved":return"bg-green-100 text-green-700 border-green-200";case"modified_after_approval":return"bg-red-100 text-red-700 border-red-400 font-black animate-pulse";case"modified":return"bg-orange-100 text-orange-700 border-orange-200";case"re_order":return"bg-gray-100 text-gray-700 border-gray-200";case"cancelled":return"bg-gray-200 text-gray-600 border-gray-300";default:return"bg-gray-100 text-gray-500 border-gray-200"}},Hs=(s,o)=>{switch(s){case"pending":return o("ì¹ì¸ë기","æ¿èªå¾
ã¡");case"approved":return o("ì¹ì¸ìë£","æ¿èªå®äº");case"modified_after_approval":return o("ê¸´ê¸ ìì ë¨","ç·æ¥ä¿®æ£æ¸ã¿");case"modified":return o("ìì ìì²","ä¿®æ£è¦è«");case"re_order":return o("ì¬ë°ì£¼ìì²","åçºæ³¨è¦è«");case"cancelled":return o("ì·¨ì","ãã£ã³ã»ã«");default:return o("ì ì ìì","䏿")}},Vs=s=>{const{db:o,userId:x,customers:f,T:a,companyId:l,orders:w,products:d,warehouses:j,mainWarehouseId:Q,salesData:W,purchases:q,deliveryMethods:$,currentUser:O,quotes:V}=s,[X,S]=u.useState({}),[B,A]=u.useState([]),[le,y]=u.useState(new Set),[K,F]=u.useState({}),de=u.useCallback((t,n,i)=>{if(V&&V.length>0&&n){const m=lt(),c=V.filter(p=>(p.customerId===n||p.customerCode===i)&&(p.status==="normal"||p.status==="approved")&&p.items&&p.items.some(r=>r.productCode===t)).filter(p=>{const r=p.effectiveDate?.toDate?p.effectiveDate.toDate().toISOString().slice(0,10):p.effectiveDate||"";return r&&r<=m});if(c.length>0){c.sort((r,_)=>{const N=r.effectiveDate?.toDate?r.effectiveDate.toDate().getTime():new Date(r.effectiveDate).getTime();return(_.effectiveDate?.toDate?_.effectiveDate.toDate().getTime():new Date(_.effectiveDate).getTime())-N});const p=c[0].items.find(r=>r.productCode===t);if(p&&Number(p.unitPrice)>0)return Number(p.unitPrice)}}if(n&&X[n]&&X[n][t]!==void 0){const m=Number(X[n][t]);if(m>0)return m}return 0},[V,X]),[se,Ce]=u.useState([]),[ce,re]=u.useState([]),[Y,ne]=u.useState(!1),[v,J]=u.useState(null),[R,ue]=u.useState(null),[C,P]=u.useState(!1),[T,b]=u.useState([]),[E,me]=u.useState(!1),[je,oe]=u.useState(!1),[tt,qe]=u.useState(!1),[pe,Ee]=u.useState(null),[ae,xe]=u.useState(null);lt();const[ge,De]=u.useState({searchTerm:"",startDate:"",endDate:"",viewM
12ode:"pending"}),[Pe,Ae]=u.useState({key:"orderDate",direction:"descending"}),[Re,Ne]=u.useState(1),Ue=30,Je=u.useCallback(()=>{P(!1),ue(null)},[]),Oe=u.useMemo(()=>{const t=new Map;return(f||[]).forEach(n=>{t.set(n.id,n),t.set(String(n.code).trim(),n),t.set(String(n.code).trim().replace(/^0+/,""),n)}),t},[f]),ye=u.useMemo(()=>{const t=new Map;return B.forEach(n=>{const i=`${String(n.partnerId).trim()}-${String(n.partnerProductCode).trim()}`,m=n.masterCode||n.masterProductId;m&&t.set(i,m)}),t},[B]),Qe=u.useMemo(()=>new Map((d||[]).map(t=>[t.code,t])),[d]),Fe=u.useCallback(t=>{const n=t.memo||t.modification_reason||t.modificationReason||"";let i=[];if(Array.isArray(t.items))i=t.items;else if(typeof t.items=="string")try{i=JSON.parse(t.items)}catch{i=[]}return{id:t.id,orderId:t.slip_no||t.id,partnerId:t.partner_id||t.supplier_code||t.customer_code||"",partnerName:t.supplier||t.partner_name||t.customer_name||"",customerId:t.partner_id||t.supplier_code||t.customer_id||"",orderDate:t.date||(t.created_at?t.created_at.slice(0,10):""),desiredDeliveryDate:t.expected_date||"",status:t.status||t.partner_status||"pending",partnerStatus:t.partner_status||t.status||"pending",products:i,totalAmount:Number(t.final_total||t.sub_total||0),subTotal:Number(t.sub_total||0),tax10:Number(t.tax_10||0),tax8:Number(t.tax_8||0),memo:n,modificationReason:n,createdAt:t.created_at,read:t.read!==void 0?t.read:!0,originalRow:t}},[]),Be=u.useCallback(async(t=null)=>{if(l)try{ne(!0);const n=new Date;n.setDate(n.getDate()-10),n.setHours(0,0,0,0);const i=t||n.toISOString(),m=M.from("partner_orders").select("*").eq("company_id",l).or("partner_status.eq.pending,status.eq.pending,partner_status.eq.æªæ¿èª,partner_status.eq.æ¿èªå¾
ã¡").order("created_at",{ascending:!1,nullsFirst:!1}),c=M.from("partner_orders").select("*").eq("company_id",l).neq("partner_status","pending").neq("status","pending").gte("created_at",i).order("created_at",{ascending:!1,nullsFirst:!1}).limit(1e3),[p,r]=await Promise.all([m,c]),_=p.data||[],N=r.data||[],I=new Map;_.forEach(z=>I.set(z.id,z)),N.forEach(z=>{I.has(z.id)||I.set(z.id,z)});const D=Array.from(I.values()).map(Fe),Z=new Map;D.forEach(z=>{const ee=String(z.partnerId||z.customerId||z.originalRow?.supplier_code||"").trim(),be=`${z.orderId||z.id}_${ee}`;if(!Z.has(be))Z.set(be,z);else{const ve=Z.get(be),G=ve.totalAmount===0&&ve.partnerStatus==="pending",fe=z.totalAmount>0||z.partnerStatus==="approved";G&&fe&&Z.set(be,z)}});const L=Array.from(Z.values());Ce(L)}catch(n){console.error("Error fetching partner orders from Supabase:",n),J(n)}finally{ne(!1)}},[l,w,Fe]);u.useEffect(()=>{if(!l)return;Be();let t=null;const n=()=>{clearTimeout(t),t=setTimeout(()=>Be(),800)},i=M.channel("rt_partner_orders").on("postgres_changes",{event:"*",schema:"public",table:"partner_orders",filter:`company_id=eq.${l}`},n).subscribe();return()=>{clearTimeout(t),M.removeChannel(i)}},[l,Be]),u.useEffect(()=>{if(!l)return;(async()=>{try{const{data:n,error:i}=await M.from("customer_prices").select("id, prices").eq("company_id",l);if(i)throw i;const m={};(n||[]).forEach(c=>{m[c.id]=c.prices||{}}),S(m)}catch(n){console.error("ë¨ê°ì¥ ì¡°í ì¤í¨:",n)}})()},[l]),u.useEffect(()=>{if(!l)return;const t=async()=>{const c=[];let r=null;for(;;){let _=M.from("product_mappings").select("id, partner_id, partner_product_code, master_code, master_product_name, partner_product_name").eq("company_id",l).order("id",{ascending:!0}).limit(1e3);r!==null&&(_=_.gt("id",r));const{data:N,error:I}=await _;if(I){console.error("Mappings fetch error:",I);break}const U=N||[];for(const Z of U)c.push(Z);if(U.length<1e3)break;const D=U[U.length-1]?.id;if(D==null||D===r)break;r=D}if(c.length>0){const _=c.map(N=>({partnerId:N.partner_id,partnerProductCode:N.partner_product_code,masterCode:N.master_code,masterProductName:N.master_product_name,partnerProductName:N.partner_product_name}));A(_)}};t();let n=null;const i=()=>{clearTimeout(n),n=setTimeout(()=>t(),800)},m=M.channel("rt_product_mappings").on("postgres_changes",{event:"*",schema:"public",table:"product_mappings",filter:`company_id=eq.${l}`},i).subscribe();return()=>{clearTimeout(n),M.removeChannel(m)}},[l]),u.useEffect(()=>{if(!l)return;let t=!0;(async()=>{const{data:m,error:c}=await M.from("settings").select("value").eq("company_id",l).eq("key","delivery_schedules").maybeSingle();t&&!c&&F(m?.value||{})})();const i=M.channel(`rt_delivery_schedules_approval_${l}`).on("postgres_changes",{event:"*",schema:"public",table:"settings",filter:`company_id=eq.${l}`},m=>{m.new?.key==="delivery_schedules"&&t&&F(m.new.value||{})}).subscribe();return()=>{t=!1,M.removeChannel(i)}},[l]);const He=u.useCallback((t,n,i)=>{if(!t||t.length===0){re([]);return}lt();let m=t.filter(c=>{if(n.viewMode==="pending"){if(c.status!=="pending"&&c.status!=="modified_after_approval"&&c.status!=="modified"&&c.status!=="re_order")return!1}else if(n.viewMode==="approved"&&c.status!=="approved"&&c.status!=="c
12ancelled")return!1;if(n.startDate&&ct(c.orderDate)<n.startDate||n.endDate&&ct(c.orderDate)>n.endDate)return!1;if(n.searchTerm){const p=n.searchTerm.trim().toLowerCase(),r=Oe.get(c.partnerId)||Oe.get(c.customerId),_=r?r.name_kr||r.name_jp||r.name||"":c.partnerName||"",N=(c.orderId||"").toLowerCase().includes(p),I=_.toLowerCase().includes(p),U=(c.partnerId||"").toLowerCase().includes(p),D=(c.products||[]).some(Z=>(Z.name||"").toLowerCase().includes(p)||(Z.code||"").toLowerCase().includes(p));if(!N&&!I&&!U&&!D)return!1}return!0});i.key&&m.sort((c,p)=>{let r=c[i.key],_=p[i.key];return i.key==="orderDate"?(r=c.orderDate?c.orderDate.toDate?c.orderDate.toDate().getTime():new Date(c.orderDate).getTime():0,_=p.orderDate?p.orderDate.toDate?p.orderDate.toDate().getTime():new Date(p.orderDate).getTime():0):i.key==="desiredDeliveryDate"?(r=c.desiredDeliveryDate||"",_=p.desiredDeliveryDate||""):i.key==="totalAmount"?(r=Number(c.totalAmount||0),_=Number(p.totalAmount||0)):i.key==="itemCount"&&(r=c.products?.length||0,_=p.products?.length||0),r<_?i.direction==="ascending"?-1:1:r>_?i.direction==="ascending"?1:-1:0}),re(m)},[Oe]);u.useEffect(()=>{He(se,ge,Pe)},[se,ge,Pe,He]);const vt=Math.ceil(ce.length/Ue),Ie=u.useMemo(()=>{const t=(Re-1)*Ue,n=t+Ue;return ce.slice(t,n)},[ce,Re]),Ye=u.useMemo(()=>{const t=new Date;return t.setDate(t.getDate()-10),t.setHours(0,0,0,0),se.reduce((n,i)=>{if(i.status==="cancelled")return n;if(i.status==="pending"||i.status==="modified_after_approval")n.pendingCount++;else if(i.status==="approved"){const m=new Date(i.orderDate?.toDate?i.orderDate.toDate():i.orderDate);m.setHours(0,0,0,0),m>=t&&n.approvedCount++}return n},{pendingCount:0,approvedCount:0})},[se]),Ze=u.useMemo(()=>{const t=lt();return se.filter(n=>{if(n.status!=="approved"||(n.desiredDeliveryDate||ct(n.orderDate))!==t)return!1;const m=n.memo||n.modificationReason||"";return!(!m||m.replace(/\[Note\]\n?/g,"").trim().length===0)})},[se]),Ve=u.useMemo(()=>{const t=lt();return se.filter(n=>n.status!=="approved"?!1:(n.desiredDeliveryDate||ct(n.orderDate))===t)},[se]),Xe=u.useMemo(()=>{const t={};return!W||!R||W.forEach(n=>{(n.customerCode===R.partnerId||n.customerId===R.partnerId)&&(n.items||[]).forEach(i=>{const m=(i.masterCode||i.productCode)?.toUpperCase();m&&(t[m]=(t[m]||0)+1)})}),t},[W,R]),Ct=()=>{De({searchTerm:"",startDate:"",endDate:"",viewMode:"pending"}),Ne(1)},Dt=()=>{const t=new Date;t.setDate(t.getDate()-10);const i={searchTerm:"",startDate:ct(t),endDate:lt(),viewMode:"approved"};De(i),Ne(1)},ie=()=>{Ne(1)},_e=()=>{const t={searchTerm:"",startDate:"",endDate:"",viewMode:"pending"},n={key:"orderDate",direction:"descending"};De(t),Ae(n),Ne(1)},Le=t=>{let n="ascending";Pe.key===t&&Pe.direction==="ascending"&&(n="descending"),Ae({key:t,direction:n}),Ne(1)},ze=u.useMemo(()=>(Ie||[]).map(t=>t.id),[Ie]),Te=ze.length>0&&ze.every(t=>T.includes(t)),Rt=t=>{b(n=>n.includes(t)?n.filter(i=>i!==t):[...n,t])},zt=()=>{b(Te?t=>t.filter(n=>!ze.includes(n)):t=>[...new Set([...t,...ze])])},Wt=u.useMemo(()=>R?ce.findIndex(t=>t.id===R.id)>0:!1,[R,ce]),Qt=u.useMemo(()=>R?ce.findIndex(t=>t.id===R.id)!==-1&&ce.findIndex(t=>t.id===R.id)<ce.length-1:!1,[R,ce]),Ut=u.useCallback(t=>{if(!R||ce.length===0)return;const n=ce.findIndex(m=>m.id===R.id);if(n===-1)return;let i=t==="prev"?n-1:n+1;i>=0&&i<ce.length&&Ft(ce[i])},[R,ce]),Ft=u.useCallback(async t=>{const n=f.find(p=>p.code===t.partnerId);if(t.read===!1)try{await M.from("partner_orders").update({read:!0}).eq("id",t.id)}catch(p){console.error("Failed to mark order as read:",p)}let i="íë ¥ì¬ë°°ì¡";if($&&n){const p=$.find(r=>r.linkedCustomerIds?.includes(n.id));p&&(i=p.name)}const m=(t.products||[]).map(p=>{const r=String(p.code).trim(),_=String(t.partnerId).trim(),I=ye.get(`${_}-${r}`)||p.masterCode||r,U=I?Qe.get(I):null;let D=0;if(I){const Z=n?.id||t.customerId;D=de(I,Z,t.partnerId)}else D=p.deliveryPrice!==void 0?p.deliveryPrice:p.unitPrice||0;return{...p,masterCode:I,current_stock_units:U?.current_stock_units||0,deliveryPrice:Number(D)}}),c={...t,products:m,partnerInfo:n||null,deliveryMethod:i};ue(c),P(!0)},[f,$,ye,Qe,de]),Kt=async(t,n)=>{if(!l||!R)return!1;const i=String(R.partnerId).trim(),m=String(t.code).trim(),p={id:`${l}_${i}_${m}`,company_id:l,partner_id:i,partner_product_code:m,partner_product_name:t.name,master_code:n.code,master_product_name:a(n.name_kr,n.name_jp),updated_at:new Date().toISOString()};try{const{error:r}=await M.from("product_mappings").upsert(p,{onConflict:"id"});if(r)throw r;let _=0;const N=R.partnerInfo?.id||R.customerId;N&&X[N]&&X[N][n.code]!==void 0&&(_=Number(X[N][n.code]));const I=R.products.map(U=>U.code===t.code?{...U,masterCode:n.code,deliveryPrice:_}:U);return ue(U=>({...U,products:I})),alert(a("매íì´ ìë ì ì¥/ê°±ì ëìì¼ë©°, ë¨ê°ê° ì¬ê³ì°ëììµëë¤!","ãããã³ã°ãèªåä¿å/æ´æ°ãããå価ãåè¨ç®ããã¾ããï¼")),!0}catch(r){return console.error("매í ì ì¥ ì¤ë¥:",r),alert(a("매í ì ì¥ ì¤ ì¤ë¥ê° ë°ìíìµëë¤.","ãããã³ã°ä¿åä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")),!1}},Jt=async(t,n="")=>{if(!x||!l)return;if(t.status!=="pending"){alert(a("ì´ë¯¸ ì²ë¦¬ë ë°ì£¼ì ëë¤.","æ¢ã«å¦çãããçºæ³¨ã§ãã"));return}const i=n.trim();if(!i){alert(a("ìì ìì² ì¬ì 를 ì ë ¥í´ì£¼ì¸ì.","ä¿®æ£è¦è«çç±ãå ¥åãã¦ãã ããã"));return}try{const{error:m}=await M.from("partner_orders").update({status:"modified",partner_status:"modified",memo:i,expected_date:t.desiredDeliveryDate||null}).eq("id",t.id);if(m)throw m;try{await M.from("partner_notifications").insert({id:crypto.randomUUID(),company_id:l,target_company_id:t.partnerId,message:`${t.orderId} ${a("ë°ì£¼ìì ëí´ ìì ìì²ì´ ëì°©íìµëë¤. (ì¬ì : ","çºæ³¨æ¸ã«å¯¾ãã¦ä¿®æ£è¦è«ãå±ãã¾ããã(äºç±: ")} ${i})`,type:"order_request_edit",target_page:"Order",read:!1,created_at:new Date().toISOString()})}catch{}alert(a("ë°ì£¼ ìì ìì²ì´ ë°ì£¼ììê² ì ì¡ëììµëë¤.","çºæ³¨ä¿®æ£è¦è«ãçºæ³¨è ã«éä¿¡ããã¾ããã")),C&&Je(),Be()}catch(m){console.error("ë°ì£¼ ìì ìì² ì²ë¦¬ ì¤ë¥:",m),alert(a("ë°ì£¼ ìì ìì² ì¤ ì¤ë¥ê° ë°ìíìµëë¤.","çºæ³¨ä¿®æ£è¦è«ä¸ã«ã¨ã©ã¼ãçºçãã¾ããã"))}},Ht=async(t,n="")=>{if(!l||!t||t.length===0)return!1;const i=se.filter(r=>t.includes(r.id)&&["pending","modified","modified_after_approval","re_order"].includes(r.status));if(i.length===0)return alert(a("ì·¨ìí ì ìë(ì¹ì¸ ì ) ë°ì£¼ê° ììµëë¤.","ãã£ã³ã»ã«å¯è½ãª(æ¿èªå)çºæ³¨ãããã¾ããã")),!1;const m=t.length-i.length;if(!window.confirm(a(`${i.length}ê±´ì ë°ì£¼ë¥¼ ì·¨ìí©ëë¤. ë°ì£¼ììê² ì·¨ì ìë¦¼ì´ ì ì¡ëë©° ëë릴 ì ììµëë¤. ì§íí ê¹ì?${m>0?` 13(ì¹ì¸ìë£ ë± ${m}ê±´ì ëììì ì ì¸ë©ëë¤)`:""}`,`${i.length}ä»¶ã®çºæ³¨ããã£ã³ã»ã«ãã¾ããçºæ³¨è ã¸éç¥ãéä¿¡ãããå ã«æ»ãã¾ãããç¶è¡ãã¾ããï¼${m>0?` 14(æ¿èªæ¸ã¿ãªã©${m}ä»¶ã¯å¯¾è±¡å¤ã§ã)`:""}`)))return!1;const c=String(n||"").trim(),p=c?`[çºæ³¨åæ¶] ${c}`:"[çºæ³¨åæ¶]";try{for(const r of i){const _=r.memo?`${r.memo} 15${p}`:p,{error:N}=await M.from("partner_orders").update({status:"cancelled",partner_status:"cancelled",memo:_}).eq("id",r.id);if(N)throw N}try{await M.from("partner_notifications").insert(i.map(r=>({id:crypto.randomUUID(),company_id:l,target_company_id:r.partnerId,message:`${r.orderId} ${a("ë°ì£¼ìê° ì·¨ì ì²ë¦¬ëììµëë¤.","çºæ³¨æ¸ããã£ã³ã»ã«å¦çããã¾ããã")}${c?` (${a("ì¬ì ","äºç±")}: ${c})`:""}`,type:"order_cancelled",target_page:"Order",read:!1,created_at:new Date().toISOString()})))}catch{}return alert(a(`${i.length}ê±´ì ë°ì£¼ê° ì·¨ìëììµëë¤. (ì¹ì¸ìë£ ëª©ë¡ìì íì¸ ê°ë¥)`,`${i.length}ä»¶ã®çºæ³¨ããã£ã³ã»ã«ãã¾ããã(æ¿èªå®äºãªã¹ãã§ç¢ºèªå¯è½)`)),b([]),C&&Je(),Be(),!0}catch(r){return console.error("ë°ì£¼ ì·¨ì ì²ë¦¬ ì¤ë¥:",r),alert(a("ë°ì£¼ ì·¨ì ì¤ ì¤ë¥ê° ë°ìíìµëë¤.","çºæ³¨ãã£ã³ã»ã«ä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")),!1}},es=async(t,n,i)=>{const m=String(t.partnerId).trim(),c=m.replace(/^0+/,""),p=[...new Set([m,c].filter(
15Boolean))];let r=null;{const{data:g,error:k}=await M.from("customers").select("*").eq("company_id",l).in("code",p).limit(1).maybeSingle();if(k)throw console.error("Supabase ê±°ëì² ì¡°í ì¤ë¥:",k.message),new Error(a("ê±°ëì² ì ë³´ ì¡°í ì¤ ì¤ë¥ ë°ì","åå¼å
æ
å ±ç
§ä¼ä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")+`: ${k.message}`);r=g}if(!r){const{data:g,error:k}=await M.from("customers").select("*").eq("company_id",l).eq("id",m).maybeSingle();if(k)throw console.error("Supabase ê±°ëì²(id) ì¡°í ì¤ë¥:",k.message),new Error(a("ê±°ëì² ì ë³´ ì¡°í ì¤ ì¤ë¥ ë°ì","åå¼å
æ
å ±ç
§ä¼ä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")+`: ${k.message}`);r=g}if(!r)throw new Error(a("ê±°ëì² ì 보를 ì°¾ì ì ììµëë¤.","åå¼å
æ
å ±ãè¦ã¤ããã¾ããã")+`: ${t.partnerId}`);const _=r.id;let N="íë ¥ì¬ë°°ì¡";if(r){if($&&$.length>0){const g=$.find(k=>k.linkedCustomerIds?.includes(r.id));g&&(N=g.name)}if(N==="íë ¥ì¬ë°°ì¡"&&(r.deliveryMethod||r.delivery_methods)){const g=r.deliveryMethod||r.delivery_methods,k=($||[]).find(te=>String(te.code)===String(g)||String(te.name)===String(g));k?N=k.name:N=g}}const I=lt();let U=ct(t.desiredDeliveryDate||t.expected_date||t.orderDate||new Date);(!U||U<I)&&(U=I);const D=new Date(`${U}T00:00:00+09:00`),Z=U;try{const g=K&&K[Z]||{},k=($||[]).find(Ge=>Ge.name===N||Ge.code===N),te=String(k?k.code:N),ke=String(k?k.name:N),Me=g.customerOverrides?.[_]||r?.code&&g.customerOverrides?.[r.code]||t.partnerId&&g.customerOverrides?.[t.partnerId]||m&&g.customerOverrides?.[m],rt=te&&g.sourceToTarget?.[te]||ke&&g.sourceToTarget?.[ke],We=Me||rt;if(We){const Ge=($||[]).find(at=>String(at.code)===String(We)||String(at.name)===String(We));Ge?N=Ge.name:N=We}}catch(g){console.warn("ë°°ì¡ë°©ë² í¹ì ì¼ ìì¸ ì ì© ì¤í¨:",g)}const L=[];let z=!1;const ee=t.products.map(g=>{let k=g.masterCode;if(!k){const te=String(g.code).trim(),ke=String(t.partnerId).trim();k=ye.get(`${ke}-${te}`)||te}return{p:g,myProduct:Qe.get(k)}}),be=ee.find(g=>!g.myProduct);if(be)throw z=!0,new Error(a("매í ì¤ë¥","ãããã³ã°ã¨ã©ã¼")+`: ${be.p.name}`);const ve=[...new Set(ee.map(g=>g.myProduct.id).filter(Boolean))],G=new Map;if(ve.length>0){const{data:g,error:k}=await M.from("inventory").select("product_id, quantity, location").eq("company_id",l).eq("warehouse_id",n).in("product_id",ve);if(k)throw console.error("ì¬ê³ ì ë³´ ì¡°í ì¤ë¥:",k.message),new Error(a("ì¬ê³ ì ë³´ ì¡°í ì¤ ì¤ë¥ ë°ì","å¨åº«æ
å ±ç
§ä¼ä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")+`: ${k.message}`);(g||[]).forEach(te=>G.set(String(te.product_id),te))}const fe=new Map;for(const{p:g,myProduct:k}of ee){const te=G.get(String(k.id))||null,ke=te?te.quantity:0,Me=te?te.location:null,rt=g.deliveryPrice!==void 0?Number(g.deliveryPrice):Number(g.unitPrice||0),We=t.desiredDeliveryDate||ct(t.orderDate)||lt(),Ge=`${k.code}__${We}`;let at=fe.get(Ge);at===void 0&&(at=Number(os(k,q||[],We))||0,fe.set(Ge,at));const _t=!!g.isReserveFulfillment||!!g.isSupportFulfillment?0:Math.round(Number(at));let ht=.1;const xt=k?k.tax_rate:void 0;if(xt!=null&&xt!==""){const gt=parseFloat(xt);isNaN(gt)||(Math.abs(gt-.08)<.001?ht=.08:Math.abs(gt)<.001?ht=0:ht=.1)}const wt=parseInt(k.box_qty,10)||1,jt=Number(g.qty||0);
15L.push({product_id:k.id,productCode:k.code,productNameKr:k.name_kr,productNameJp:k.name_jp,name:k.name,boxQty:jt%wt===0&&jt!==0?jt/wt:"",unitQty:jt,unitCost:_t,unitPrice:rt,taxRate:ht,boxCapacity:wt,profitRate:rt>0&&_t>0?(rt-_t)/rt*100:0,is_direct_delivery:!!k.is_direct_delivery,isContainer:!!g.isContainer,isReserveFulfillment:!!g.isReserveFulfillment,isSupportFulfillment:!!g.isSupportFulfillment,isRebateApplied:!!g.isRebateApplied,rebateId:g.rebateId||null,supportDocId:g.supportDocId||null,isPromoFreebie:!!g.isPromoFreebie,note:g.note||"",currentStock:ke,stockLocation:Me})}if(z)throw new Error(a("매íëì§ ìì ìíì´ í¬í¨ëì´ ììµëë¤.","ãããã³ã°ããã¦ããªãååãå«ã¾ãã¦ãã¾ãã"));const $e=[],Se=[],we=[],Ke=[];if(L.forEach(g=>{g.is_direct_delivery?Ke.push(g):!g.isContainer&&g.currentStock<g.unitQty?we.push(g):Se.push(g)}),Se.length>0&&$e.push({items:Se,suffix:"",notePrefix:"",isDirect:!1}),we.length>0&&we.forEach((g,k)=>{$e.push({items:[g],suffix:`-M${k+1}`,notePrefix:"[æ¬ ååå] ",isDirect:!1})}),Ke.length>0&&$e.push({items:Ke,suffix:"-D",notePrefix:"[éä¸ä»å
¥] ",isDirect:!0}),$e.length===0)throw new Error("ì²ë¦¬í ìíì´ ììµëë¤.");const ut=t.status==="pending"||t.status==="approving";let et=[];if(!ut){const{data:g}=await M.from("sales_slips").select("*, sales_slip_items(*)").eq("company_id",l).eq("customer_id",_).eq("remarks2",t.orderId);et=g||[];for(const k of et)for(const te of k.sales_slip_items||[]){const ke=Number(te.unit_qty||0);if(ke!==0){if(te.is_support_fulfillment){const{data:Me}=await M.from("customer_supports").select("id, remaining_qty").eq("customer_id",_).eq("product_code",te.product_code).maybeSingle();Me&&await M.from("customer_supports").update({remaining_qty:Number(Me.remaining_qty)+ke}).eq("id",Me.id)}if(te.is_rebate_applied&&te.rebate_id){const{data:Me}=await M.from("rebate_promotions").select("remaining_qty").eq("id",te.rebate_id).maybeSingle();Me&&await M.from("rebate_promotions").update({remaining_qty:Number(Me.remaining_qty)+ke}).eq("id",Me.id)}}}}const kt=[];for(const g of et){if(g.is_deleted)continue;const{error:k}=await M.from("sales_slips").update({is_deleted:!0,deleted_by:O?.displayName||O?.name||"ReApproval",deleted_at:new Date().toISOString(),delete_reason:"çºæ³¨åæ¿èªã«ããä¼ç¥¨å使",updated_at:new Date().toISOString()}).eq("id",g.id);k||kt.push(g.id)}const ot=[];let it=0;const st={};let Pt=!1;const mt=D.toISOString();try{for(const g of $e){let k=0,te=0,ke=0,Me=0;const rt=crypto.randomUUID(),We=et.find(H=>g.suffix==="-D"?H.slip_no?.endsWith("-D"):g.suffix.startsWith("-M")?H.slip_no?.endsWith(g.suffix):!H.slip_no?.endsWith("-D")&&!H.slip_no?.includes("-M")),Ge=We&&We.slip_no?We.slip_no:await Yt(o,l),at=We&&We.delivery_note_print_count||0,Mt=is(g.items,mt);k=Mt.subTotal,te=Mt.tax8,ke=Mt.tax10,Me=Mt.profit;const _t=g.items.map(H=>{const nt=Math.round(H.unitQty*H.unitPrice);return H.unitPrice>0&&H.productCode&&!H.isReserveFulfillment&&(st[H.productCode]=Number(H.unitPrice),Pt=!0),{id:crypto.randomUUID(),sales_slip_id:rt,company_id:l,product_id:H.product_id,product_code:H.productC
15ode,product_name:H.name,product_name_kr:H.productNameKr||H.name,product_name_jp:H.productNameJp||H.name,unit_qty:H.unitQty,box_qty:Number(H.boxQty||0),unit_price:H.unitPrice,unit_cost:H.unitCost,amount:nt,tax:Math.round(nt*Number(H.taxRate||0)),tax_rate:H.taxRate,remark:H.note||"",note:H.note||"",box_capacity:H.boxCapacity||1,total:Math.round(nt*(1+Number(H.taxRate||0))),is_reserve_fulfillment:!!H.isReserveFulfillment,is_support_fulfillment:!!H.isSupportFulfillment,is_rebate_applied:!!H.isRebateApplied,rebate_id:H.rebateId||null}}),ht=Math.round(k),xt=Math.round(te),wt=Math.round(ke),jt=Math.round(Me),gt=ht+xt+wt;it+=gt;const fs=(r?.billingConfig?.slipType||r?.slipType||"credit")==="cash"?a("íê¸","ç¾é"):a("ì¸ì","æå£²ã"),hs={id:rt,company_id:l,slip_no:Ge,date:mt,delivery_date:mt,slip_type:fs,customer_id:_,customer_code:t.partnerId,customer_name:r.name_kr||r.name||t.partnerName,warehouse_id:n,delivery_method:N,sub_total:ht,tax_8:xt,tax_10:wt,final_total:gt,total_amount:gt,profit:jt,remarks:g.notePrefix,remarks2:t.orderId,writer_name:O?.displayName||O?.name||a("ì¹ì¸ì","æ¿èªè "),pic:O?.displayName||O?.name||a("ì¹ì¸ì","æ¿èªè "),delivery_note_print_count:at,created_at:new Date().toISOString(),updated_at:new Date().toISOString()},{error:Nt}=await M.from("sales_slips").insert(hs);if(Nt)throw console.error("Supabase sales_slips ì½ì ì¤ë¥:",Nt.message,Nt.details,Nt.hint,Nt.code),new Error(a("ë§¤ì¶ ì í ìì± ì¤ ì¤ë¥ ë°ì","売ä¸ä¼ç¥¨ä½æä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")+`: ${Nt.message}`);const{error:St}=await M.from("sales_slip_items").insert(_t);if(St)throw console.error("Supabase sales_slip_items ì½ì ì¤ë¥:",St.message,St.details,St.hint,St.code),new Error(a("ë§¤ì¶ í목 ìì± ì¤ ì¤ë¥ ë°ì","売ä¸é ç®ä½æä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")+`: ${St.message}`);for(const H of g.items){if(H.isSupportFulfillment&&H.supportDocId){const{data:nt}=await M.from("customer_supports").select("id, remaining_qty").eq("id",H.supportDocId).maybeSingle();nt&&await M.from("customer_supports").update({remaining_qty:Math.max(0,Number(nt.remaining_qty)-H.unitQty)}).eq("id",H.supportDocId)}if(H.isRebateApplied&&H.rebateId){const{data:nt}=await M.from("rebate_promotions").select("id, remaining_qty").eq("id",H.rebateId).maybeSingle();nt&&await M.from("rebate_promotions").update({remaining_qty:Math.max(0,Number(nt.remaining_qty)-H.unitQty)}).eq("id",H.rebateId)}}ot.push({slip_no:Ge,items:_t.map(H=>({...H,productCode:H.product_code,unitQty:H.unit_qty,unitPrice:H.unit_price}))})}}catch(g){for(const k of kt)try{await M.from("sales_slips").update({is_deleted:!1,updated_at:new Date().toISOString()}).eq("id",k)}catch{}throw g}for(const g of et)await M.from("sales_slip_items").delete().eq("sales_slip_id",g.id),await M.from("sales_slips").delete().eq("id",g.id);if(Pt){const{data:g}=await M.from("customer_prices").select("prices").eq("id",_).maybeSingle(),k={...g?.prices||{}};for(const[te,ke]of Object.entries(st))k[te]=ke;await M.from("customer_prices").upsert({id:_,company_id:l,prices:k,updated_at:new Date().toISOString()},{onConflict:"id"})}const{error:It}=await M.from("partner_orders").update({status:"approved",partner_status:"approved",sub_total:it,final_total:it,items:t.products,expected_date:t.desiredDeliveryDate||null,writer_name:O?.displayName||O?.name||a("ì¹ì¸ì","æ¿èªè "),received_date:mt}).eq("id",t.id);It&&console.error("Supabase partner_orders ì¹ì¸ ì ë°ì´í¸ ì¤í¨:",It);let $t=!1,pt="";const ft=t.memo||t.modificationReason||"";if(ft&&ft.trim()!==""&&(pt=ft.replace(/\[Note\]\n?/g,"").trim(),pt!=="")){$t=!0;try{await M.from("customer_memos").insert({id:crypto.randomUUID(),company_id:l,customer_id:_,content:`[모ë°ì¼ ë°ì£¼ ìì²ì¬í - ${t.orderId}] 16${pt}`,created_by:x||"System",creator_name:"모ë°ì¼ ë°ì£¼ ìì¤í ",created_at:new Date().toISOString()})}catch{}}try{await M.from("partner_notifications").insert({id:crypto.randomUUID(),company_id:l,target_company_id:t.partnerId,message:`${t.orderId} ${a("ë°ì£¼ìê° ìµì¢ ì¹ì¸ëììµëë¤.","çºæ³¨æ¸ê° ìµì¢ ì¹ì¸ëììµëë¤.")}`,type:"order_approved",target_page:"Order",read:!1,created_at:new Date().toISOString()})}catch{}const he={updated_at:new Date().toISOString()};if($t){const{data:g}=await M.from("customers").select("memo").eq("id",_).maybeSingle();let k=[];if(g&&Array.isArray(g.memo))k=g.memo;
16else if(g&&typeof g.memo=="string"&&g.memo.trim().startsWith("["))try{k=JSON.parse(g.memo)}catch{k=[]}const te={id:crypto.randomUUID(),content:`[모ë°ì¼ ë°ì£¼ ìì²ì¬í - ${t.orderId}] 17${pt}`,createdAt:new Date().toISOString(),createdBy:x||"System",creatorName:"모ë°ì¼ ë°ì£¼ ìì¤í "};he.memo=[te,...k],he.last_memo_at=new Date().toISOString()}return await M.from("customers").update(he).eq("id",_),{newSalesDataList:ot,partnerInfo:r}},Vt=async(t,n)=>{if(!t||!t.id)return!1;if(le.has(t.id))return alert(a("íì¬ í´ë¹ ë°ì£¼ì ì¹ì¸ì´ ì§í ì¤ì ëë¤. ì ìë§ ê¸°ë¤ë ¤ì£¼ì¸ì.","ç¾å¨è©²å½çºæ³¨ã®æ¿èªãé²è¡ä¸ã§ãããã°ãããå¾ ã¡ãã ããã")),!1;y(i=>new Set(i).add(t.id));try{const i=t.status==="modified_after_approval";if(["pending","modified","re_order","modified_after_approval"].includes(t.status)){const{data:_,error:N}=await M.from("partner_orders").update({status:"approving"}).eq("id",t.id).in("status",["pending","modified","re_order","modified_after_approval"]).select("id, status");if(N||!_||_.length===0)return alert(a("ì´ë¯¸ ì²ë¦¬ ì¤ì´ê±°ë ì¹ì¸ ìë£ë ë°ì£¼ì ëë¤.","æ¢ã«å¦çä¸ã¾ãã¯æ¿èªå®äºããçºæ³¨ã§ãã")),!1;if(!i){const{data:I}=await M.from("sales_slips").select("id, slip_no").eq("company_id",l).in("remarks2",[t.orderId,t.id].filter(Boolean)).limit(1).maybeSingle();if(I)return await M.from("partner_orders").update({status:"approved"}).eq("id",t.id),alert(a("ì´ë¯¸ í´ë¹ ë°ì£¼ë¡ ìì±ë ë§¤ì¶ ì íê° ì¡´ì¬í©ëë¤.","æ¢ã«è©²å½çºæ³¨ã§ä½æããã売ä¸ä¼ç¥¨ãåå¨ãã¾ãã")),!1}}const c=await Yt(o,l),{newSalesDataList:p,partnerInfo:r}=await es(t,n,c);if(t.status==="modified_after_approval"&&p&&p.length>0){const _=p.map(N=>({slip:N,customer:r}));Ee(_),oe(!0)}return Be(),!0}catch(i){console.error("ë°ì£¼ ì¹ì¸ ì²ë¦¬ ì¤ë¥:",i);try{await M.from("partner_orders").update({status:t.status||"pending"}).eq("id",t.id)}catch{}return alert(a("ë°ì£¼ ì¹ì¸ ì¤ ì¤ë¥ê° ë°ìíìµëë¤.","çºæ³¨æ¿èªä¸ã«ã¨ã©ã¼ãçºçãã¾ããã")+` 18${i.message}`),!1}finally{y(i=>{const m=new Set(i);return m.delete(t.id),m})}};return{orders:se,displayedOrders:ce,paginatedOrders:Ie,loading:Y,error:v,selectedOrder:R,isModalOpen:C,selectedOrderIds:T,isBatchModalOpen:E,isBatchExportModalOpen:je,isPickingListModalOpen:tt,pendingBatchPdfData:pe,pendingPickingListData:ae,filters:ge,sortConfig:Pe,paginationCurrentPage:Re,totalPages:vt,summaryData:Ye,customerOrderCounts:Xe,todaysMemoOrders:Ze,todaysApprovedOrders:Ve,productMap:Qe,mappingMap:ye,allCustomerPrices:X,customerLookup:Oe,setFilters:De,setSortConfig:Ae,setPaginationCurrentPage:Ne,setSelectedOrder:ue,setIsModalOpen:P,setSelectedOrderIds:b,setIsBatchModalOpen:me,setIsBatchExportModalOpen:oe,setIsPickingListModalOpen:qe,setPendingBatchPdfData:Ee,setPendingPickingListData:xe,handleOpenModal:Ft,handleCloseModal:Je,handleShowAllPending:Ct,handleShowApproved:Dt,handleSearch:ie,handleReset:_e,requestSort:Le,handleMapProduct:Kt,handleModify:Jt,handleCancelOrders:Ht,handleApprove:Vt,handleBatchApprove:async t=>{if(!t){alert(a("ì¶í ì°½ê³ ë¥¼ ì íí´ì¼ í©ëë¤.","åºåº«å庫ã鏿ãã¦ãã ããã"));return}const n=T.map(r=>se.find(_=>_.id===r)).filter(r=>r&&(r.status==="pending"||r.status==="modified_after_approval"||r.status==="modified"));if(n.length===0){alert(a("æ¿èªããæ³¨æãããã¾ããã","æ¿èªããæ³¨æãããã¾ããã"));return}me(!1),ne(!0);const i=[],m=[],c=[];let p=0;try{const r=[...new Set(n.map(D=>{const Z=f.find(L=>L.code===D.partnerId);return Z?Z.id:null}).filter(Boolean))],_={},N={},I=[],U=[];if(r.length>0){const{data:D}=await M.from("promo_rules").select("*").eq("company_id",l).eq("is_active",!0);(D||[]).forEach(ee=>I.push({id:ee.id,...ee,productCode:ee.product_code,buyQty:ee.buy_qty,freeQty:ee.free_qty,customerId:ee.customer_id}));const{data:Z}=await M.from("rebate_promotions").select("*").eq("company_id",l).eq("is_archived",!1).gt("remaining_qty",0);(Z||[]).forEach(ee=>U.push({id:ee.id,...ee,productCode:ee.product_code,rebateCost:ee.rebate_cost,remainingQty:ee.remaining_qty,targetCustomers:ee.target_customers}));const z=((ee,be)=>{const ve=[];for(let G=0;G<ee.length;G+=be)ve.push(ee.slice(G,G+be));return ve})(r,50);for(const ee of z){const{data:be}=await M.from("customer_reserves").select("*").eq("company_id",l).in("customer_id",ee).gt("remaining_qty",0);
18(be||[]).forEach(G=>{_[`${G.customer_id}_${G.product_code}`]={id:G.id,...G,customerId:G.customer_id,productCode:G.product_code,remainingQty:G.remaining_qty}});const{data:ve}=await M.from("customer_supports").select("*").eq("company_id",l).in("customer_id",ee).gt("remaining_qty",0);(ve||[]).forEach(G=>{N[`${G.customer_id}_${G.product_code}`]={id:G.id,...G,customerId:G.customer_id,productCode:G.product_code,remainingQty:G.remaining_qty}})}}for(const D of n){const Z=await Yt(o,l),L=Oe.get(D.partnerId)?.id||D.customerId,z=[],ee=[],be=[];for(const G of D.products||[]){const fe=String(G.code).trim(),$e=String(D.partnerId).trim(),Se=ye.get(`${$e}-${fe}`)||G.masterCode||fe,we=Qe.get(Se);if(!we){z.push(G);continue}let Ke=Number(G.qty||0),ut=Ke,et=G.unitPrice||0,kt=!1;const ot=`${L}_${Se}`,it=`${L}_${Se}`;if(et===0&&(et=de(Se,L,D.partnerId)),L&&N[ot]&&N[ot].remainingQty>0){const he=N[ot].remainingQty,g=Math.min(Ke,he),k=he-g,te=we?.box_qty||1,ke=Math.floor(k/te),Me=k%te;z.push({...G,masterCode:Se,qty:g,unitQty:g,deliveryPrice:0,unitPrice:0,isSupportFulfillment:!0,supportDocId:N[ot].id,isRebateApplied:!1,note:`[ç¡åæ¯æ´æ®]: ${ke}Box / ${Me} (è¨ ${k})`}),N[ot].remainingQty-=g,ut-=g}else if(L&&_[it]&&_[it].remainingQty>0){const he=_[it].remainingQty,g=Math.min(Ke,he);kt=!0;const k=he-g,te=we?.box_qty||1,ke=Math.floor(k/te),Me=k%te;z.push({...G,masterCode:Se,qty:g,unitQty:g,deliveryPrice:0,unitPrice:0,isReserveFulfillment:!0,isRebateApplied:!1,note:`[ç´å徿®]: ${ke}Box / ${Me} (è¨ ${k})`}),_[it].remainingQty-=g,ut-=g}const st=U.find(he=>he.productCode!==Se?!1:(!he.targetCustomers||he.targetCustomers.length===0||L&&he.targetCustomers.some(k=>k.id===L))&&he.remainingQty>0);let Pt=!1,mt=null,It=null,$t=null,pt=0;st&&(Pt=!0,mt=st.id,pt=st.remainingQty,It=Number(st.rebateCost||0),$t=st.promotion_code||st.id),ut>0&&z.push({...G,masterCode:Se,qty:ut,unitQty:ut,deliveryPrice:et,unitPrice:et,isSupportFulfillment:!1,isReserveFulfillment:!1,note:G.note||"",isRebateApplied:Pt,rebateId:mt,rebateRemaining:pt,rebate_cost:It,promotion_id:$t});const ft=I.find(he=>he.productCode===Se&&(he.customerId==="ALL"||he.customerId===L));if(ft){const he=Number(ft.buyQty||1),g=Number(ft.freeQty||1),te=Math.floor(Ke/he)*g;te>0&&be.push({code:G.code,masterCode:Se,name:a(we?.name_kr||G.name,we?.name_jp||G.name),qty:te,unitQty:te,unitPrice:0,deliveryPrice:0,taxRate:we?.tax_rate?parseFloat(we.tax_rate):.1,is_direct_delivery:we?.is_direct_delivery||!1,isReserveFulfillment:!1,isSupportFulfillment:!1,isRebateApplied:!1,isPromoFreebie:!0,note:`[${he}+${g} ããã¢ã¼ã·ã§ã³è´å]`})}if(we.linked_container_id&&!kt){const he=d.find(g=>g.id===we.linked_container_id);if(he){let g=de(he.code,L,D.partnerId);g===0&&(g=he.sales_price||0),ee.push({code:he.code,name:a(he.name_kr,he.name_jp),masterCode:he.code,qty:G.qty,unitPrice:-Math.abs(g),deliveryPrice:-Math.abs(g),isReserveFulfillment:!1})}}}const ve={...D,products:[...z,...be,...ee]};try{await Vt(ve,t)?p++:c.push(`${D.orderId}`)}catch(G){console.error(`[${D.orderId}] Error:`,G),c.push(`${D.orderId} (${G.message})`)}}alert(a(`ì¼ê´ ì¹ì¸ ìë£: ${p}ê±´ ì±ê³µ, ${c.length}ê±´ ì¤í¨.`,`䏿¬æ¿èªå®äº: ${p}ä»¶ æå, ${c.length}ä»¶ 失æã`)+(c.length>0?` 19 20${a("ì¤í¨ ì¬ì :","失æäºç±:")} 21${c.join(` 22`)}`:"")),i.length>0&&(Ee(i),xe(m),oe(!0)),b([]),Be()}catch(r){console.error("Batch error:",r),alert(a("ì¼ê´ ì¹ì¸ ì²ë¦¬ ì¤ ìì¤í ì¤ë¥ê° ë°ìíìµëë¤.","䏿¬æ¿èªå¦çä¸ã«ã·ã¹ãã ã¨ã©ã¼ãçºçãã¾ããã")+` 23${r.message}`)}finally{ne(!1)}},handleNavigateOrder:Ut,handleSelectOne:Rt,handleSelectAll:zt,canGoPrev:Wt,canGoNext:Qt,formatDate:ct,formatCurrency:zs,findLastSaleCost:Ks,findLastPurchaseCost:Ls,getStatusClasses:Js,getStatusName:Hs,formatMessage:Ws}},Gs=u.memo(({order:s,isSelected:o,onSelectOne:x,onOpenModal:f,todayStrJST:a,mappingMap:l,purchases:w,productMap:d,salesData:j,allCustomerPrices:Q,customers:W,T:q,formatDate:$,formatCurrency:O,formatMessage:V,findLastSaleCost:X,findLastPurchaseCost:S,getStatusClasses:B,getStatusName:A,getCustomerName:le})=>{const y=s.desiredDeliveryDate&&s.desiredDeliveryDate<a&&s.status==="pending",K=s.status==="cancelled",F=s.products?.some(re=>{const Y=String(re.code).trim();let ne=re.masterCode||l?.get(`${String(s.partnerId).trim()}-${Y}`)||Y;if(!ne)return!1;const v=S(w,ne),J=d.get(ne)?.cost_price||0,R=v!==null?v:J,ue=X(j,s.partnerId,ne);return!(ue===null||ue===R)}),de=s.desiredDeliveryDate?s.desiredDeliveryDate:$(s.orderDate);let se=s.totalAmount||0;if(!se||se===0){const Y=W?.find(v=>v.code===s.partnerId)?.id||s.customerId,ne=Y&&Q?Q[Y]:null;se=(s.products||[]).reduce((v,J)=>{let R=0;const ue=Number(J.qty||0),C=String(J.code).trim();let P=J.masterCode||l?.get(`${String(s.partnerId).trim()}-${C}`)||C;ne&&P&&ne[P]!==void 0&&ne[P]>0?R=Number(ne[P]):P&&d.has(P)?R=Number(d.get(P).sales_price||0):J.unitPrice>
230&&(R=Number(J.unitPrice));let T=.1;return J.taxRate?T=Number(J.taxRate):P&&d.has(P)&&(T=Number(d.get(P).tax_rate||.1)),v+Math.round(R*ue*(1+T))},0)}const Ce=s.products?.length||0,ce=V(s.memo||s.modificationReason);return e.jsxs("tr",{className:` 24 transition-all duration-200 border-b border-gray-100 25 ${K?"opacity-40 bg-gray-50/50":"hover:bg-gray-50/80"} 26 ${s.status==="modified_after_approval"?"bg-red-50/30":F?"bg-orange-50/20":""} 27 `,children:[e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-center",children:e.jsx("input",{type:"checkbox",disabled:K,className:"h-4 w-4 rounded text-indigo-600 border-gray-300 focus:ring-indigo-500 cursor-pointer",checked:o,onChange:()=>x(s.id),onClick:re=>re.stopPropagation()})}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-[13px] text-gray-500 font-mono",children:$(s.orderDate)}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-[13px] cursor-pointer",onClick:()=>f(s),children:e.jsxs("div",{className:`flex items-center gap-1 ${y?"text-red-600 font-black animate-pulse":"text-gray-900 font-medium"}`,children:[e.jsx(js,{size:14,className:y?"text-red-500":"text-gray-400"}),de,y&&e.jsx("span",{className:"ml-1 text-[10px] bg-red-100 px-1 py-0.5 rounded border border-red-200",children:q("ì´ê³¼!","è¶ é!")})]})}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-[13px] text-gray-900 font-bold font-mono cursor-pointer",onClick:()=>f(s),children:s.orderId}),e.jsx("td",{className:`px-4 py-4 whitespace-nowrap text-[13px] font-semibold cursor-pointer ${K?"text-gray-400 line-through":"text-gray-800"}`,onClick:()=>f(s),children:le(s)}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-[13px] text-center text-gray-600 font-medium",children:e.jsx("span",{className:"bg-gray-100 px-2 py-0.5 rounded-full",children:Ce})}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-[13px] text-right font-bold text-gray-900",children:e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[F&&!K&&e.jsx(Ns,{size:14,className:"text-orange-500",title:q("ìê° ë³ë ê°ì§ë¨","å価å¤åæç¥")}),e.jsx("span",{className:K?"text-gray-400 line-through":F?"text-orange-600":"text-gray-900",children:O(se)})]})}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-[13px] text-gray-500",title:s.modificationReason||"",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[s.modificationReason&&e.jsx(Xt,{size:14,className:"text-indigo-400"}),ce]})}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx("span",{className:`px-3 py-1 inline-flex text-[11px] font-bold rounded-lg border ${B(s.status)}`,children:A(s.status,q)}),s.status==="pending"&&s.read===!1&&!K&&e.jsx("span",{className:"px-1.5 py-0.5 bg-red-500 text-white text-[10px] font-bold rounded animate-pulse",children:"NEW"})]})}),e.jsx("td",{className:"px-4 py-4 whitespace-nowrap text-center",children:e.jsx("button",{onClick:()=>f(s),title:q("ìì¸ë³´ê¸°","詳細表示"),className:"p-1.5 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all active:scale-90",children:e.jsx(Ss,{className:"w-4 h-4"})})})]})},(s,o)=>s.isSelected===o.isSelected&&s.order===o.order),Ys=dt.memo(({orders:s,onOpenModal:o,T:x,sortConfig:f,requestSort:a,onSelectOne:l,onSelectAll:w,selectedOrderIds:d,salesData:j,productMap:Q,mappingMap:W,purchases:q,allCustomerPrices:$,customers:O,currentUser:V,formatDate:X,formatCurrency:S,formatMessage:B,findLastSaleCost:A,findLastPurchaseCost:le,getStatusClasses:y,getStatusName:K})=>{const F=({label:re,sortKey:Y,align:ne="left",width:v=""})=>e.jsx("th",{className:`px-4 py-3 text-${ne} text-[11px] font-bold text-gray-400 uppercase tracking-wider ${v} ${Y?"cursor-pointer hover:text-indigo-600 transition-colors":""}`,onClick:()=>Y&&a(Y),children:e.jsxs("div",{className:`flex items-center gap-1 ${ne==="right"?"justify-end":ne==="center"?"justify-center":"justify-start"}`,children:[re,Y&&(f?.key===Y?f.direction==="ascending"?"â²":"â¼":e.jsx("span",{className:"opacity-30",children:"â"}))]})}),de=u.useMemo(()=>s.map(re=>re.id),[s]),se=de.length>0&&de.every(re=>d.includes(re));if(!s||s.length===0)return e.jsx("div",{className:"bg-white p-10 rounded-lg border border-gray-200 text-center text-gray-500 shadow-sm",children:x("íìí ë°ì£¼ ë°ì´í°ê° ììµëë¤.","表示ããçºæ³¨ãã¼ã¿ãããã¾ããã")});const Ce=re=>{const Y=O.find(ne=>ne.code===re.partnerId);
27return Y?x(Y.name_kr||Y.name,Y.name_jp||Y.name):re.partnerName},ce=(()=>{const re=new Date,Y=re.getTime()+re.getTimezoneOffset()*6e4;return new Date(Y+540*60*1e3).toISOString().split("T")[0]})();return e.jsx("div",{className:"bg-white rounded-2xl overflow-hidden border border-gray-100 shadow-none",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-gray-100",children:[e.jsx("thead",{className:"bg-white",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-center w-10",children:e.jsx("input",{type:"checkbox",className:"h-4 w-4 rounded text-indigo-600 border-gray-300 focus:ring-indigo-500 cursor-pointer",checked:se,onChange:w})}),e.jsx(F,{label:x("ë°ì£¼ì¼","çºæ³¨æ¥"),sortKey:"orderDate"}),e.jsx(F,{label:x("ë©íì¼","ç´åæ¥")}),e.jsx(F,{label:x("ë°ì£¼ë²í¸","çºæ³¨çªå·"),sortKey:"orderId"}),e.jsx(F,{label:x("ê±°ëì²ëª
","åå¼å
å"),sortKey:"partnerName"}),e.jsx(F,{label:x("í목ì","åç®æ°"),sortKey:"itemCount",align:"center"}),e.jsx(F,{label:x("ì´ê¸ì¡","ç·é¡"),sortKey:"totalAmount",align:"right"}),e.jsx(F,{label:x("ë©ìì§","ã¡ãã»ã¼ã¸"),sortKey:"modificationReason"}),e.jsx(F,{label:x("ìí","ã¹ãã¼ã¿ã¹"),sortKey:"status",align:"center"}),e.jsx("th",{className:"px-4 py-3 text-center text-[11px] font-bold text-gray-400 uppercase tracking-wider",children:x("ìì
","æä½")})]})}),e.jsx("tbody",{className:"bg-white divide-y divide-gray-100",children:s.map(re=>e.jsx(Gs,{order:re,isSelected:d.includes(re.id),onSelectOne:l,onOpenModal:o,todayStrJST:ce,mappingMap:W,purchases:q,productMap:Q,salesData:j,allCustomerPrices:$,customers:O,T:x,formatDate:X,formatCurrency:S,formatMessage:B,findLastSaleCost:A,findLastPurchaseCost:le,getStatusClasses:y,getStatusName:K,getCustomerName:Ce},re.id))})]})})})}),Bt=dt.memo(({children:s,onClose:o,maxWidth:x="max-w-lg"})=>e.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 p-4 transition-all duration-300",onClick:o,children:e.jsxs("div",{className:`bg-white rounded-2xl shadow-xl w-full ${x} max-h-[90vh] overflow-y-auto relative transform scale-100 transition-transform duration-300 ease-out`,onClick:f=>f.stopPropagation(),children:[s,e.jsx("button",{onClick:o,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-900 bg-transparent hover:bg-gray-100 rounded-full p-1.5 transition-colors",children:e.jsx(bt,{size:18,strokeWidth:2.5})})]})})),yt=dt.memo(({children:s,onClick:o,icon:x,variant:f="primary",type:a="button",disabled:l=!1,size:w="md",className:d=""})=>{let j="flex items-center justify-center font-medium rounded-xl transition-all duration-200 ease-out border border-transparent active:scale-[0.98] outline-none ";switch(w==="md"&&(j+="px-5 py-2.5 text-[13px] "),w==="sm"&&(j+="px-3 py-1.5 text-xs "),f){case"primary":j+="bg-indigo-600 text-white hover:bg-indigo-700 shadow-sm ";break;case"search":j+="bg-gray-900 text-white hover:bg-black shadow-sm ";break;case"secondary":j+="bg-white text-gray-700 border-gray-200 hover:bg-gray-50 ";break;case"warning":j+="bg-amber-500 text-white hover:bg-amber-600 shadow-sm ";break;default:j+="bg-indigo-600 text-white hover:bg-indigo-700 shadow-sm "}return l&&(j+=" opacity-50 cursor-not-allowed active:scale-100 grayscale-[50%] "),e.jsxs("button",{type:a,onClick:o,className:`${j} ${d}`,disabled:l,children:[x&&e.jsx(x,{className:`mr-1.5 ${w==="md"?"w-4 h-4":"w-3.5 h-3.5"}`,strokeWidth:2.5}),s]})}),Zs=dt.memo(({isOpen:s,onClose:o,onBatchApprove:x,selectedIds:f,T:a,warehouses:l,mainWarehouseId:w})=>{const[d,j]=u.useState(w||l&&l[0]?.id||""),[Q,W]=u.useState(!1);u.useEffect(()=>{s&&j(w||l&&l[0]?.id||"")},[s,w,l]);const q=async()=>{if(!d){alert(a("ì¶í ì°½ê³ ë¥¼ ì íí´ì¼ í©ëë¤.","åºåº«å庫ã鏿ãã¦ãã ããã"));return}W(!0),await x(d),W(!1),o()};return s?e.jsx(Bt,{onClose:o,maxWidth:"max-w-md",children:e.jsxs("div",{className:"p-7",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-teal-50 flex items-center justify-center text-teal-600",children:e.jsx(Ot,{size:20,strokeWidth:2.5})}),e.jsx("h3",{className:"text-xl font-bold text-gray-900 tracking-tight",children:a("ë°ì£¼ ì¼ê´ ì¹ì¸","çºæ³¨ä¸æ¬æ¿èª")})]}),e.jsx("p",{className:"text-[13px] text-gray-500 mb-6 ml-13",children:a(`ì íë ${f.length}ê±´ì 'ì¹ì¸ë기' ë°ì£¼ë¥¼ ì¶í ì²ë¦¬í©ëë¤.`,`鏿ããã ${f.length}ä»¶ã®ãæ¿èªå¾
ã¡ãçºæ³¨ãåºåº«å¦çãã¾ãã`)}),e.jsxs("div",{className:"mb-8 p-5 bg-gray-50/80 rounded-xl border border-gray-100",children:[e.jsxs("label",{className:"block text-[12px] font-bold text-gray-600 mb-2 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(ds,{size:14}),a("ì¶í ì°½ê³ ì í","åºåº«ååº«é¸æ")]}),e.jsxs("select",{value:d,onChange:$=>j($.target.value),className:"w-full px-4 py-2.5 bg-white border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 text-[13px] font-medium text-gray-800 outline-none transition-all cursor-pointer appearance-none",disabled:Q,children:[e.jsx("option",{value:"",disabled:!0,children:a("ì°½ê³ ë¥¼ ì ííì¸ì","å庫ã鏿ãã¦ãã ãã")}),(l||[]).map($=>e.jsxs("option",{value:$.id,children:[$.name," ",$.is_main?a("(ë©ì¸)","(ã¡ã¤ã³)"):""]},$.id))]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-gray-100",children:[e.jsx(yt,{type:"button",onClick:o,variant:"secondary",disabled:Q,children:a("ì·¨ì","ãã£ã³ã»ã«")}),e.jsx(yt,{type:"button",onClick:q,variant:"primary",icon:Q?Tt:null,disabled:Q||!d||f.length===0,className:Q?"animate-spin":"bg-teal-600 hover:bg-teal-700 text-white",children:Q?a("ì²ë¦¬ ì¤...","å¦çä¸..."):a("ì¹ì¸ ìë£","æ¿èªå®äº")})]})]})}):null}),ps=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Tokyo"}),Xs="W001",Lt="ALL",Ts=(s,o,x)=>{const f=new Map;
27(o||[]).forEach(j=>{j&&j.id!==void 0&&j.id!==null&&f.set(String(j.id),String(j.code??""))});const a=new Map,l=new Map;let w=0,d=0;return(s||[]).forEach(j=>{if(!j)return;w+=1;const Q=j.warehouseId??j.warehouse_id;if(x!==Lt&&String(Q??"")!==String(x??""))return;d+=1;const W=Number(j.quantity??j.qty??0)||0,q=j.productId??j.product_id,$=j.product_code??j.productCode,O=$!=null&&String($)!==""?String($):q!=null&&f.get(String(q))||"";if(O&&a.set(O,(a.get(O)||0)+W),q!=null){const V=String(q);l.set(V,(l.get(V)||0)+W)}}),{byCode:a,byId:l,total:w,here:d}},er=(s,o,x)=>{if(!s)return null;const f=x!=null?String(x):"";if(f&&s.byCode.has(f))return s.byCode.get(f);if(o&&o.id!==void 0&&o.id!==null){const a=String(o.id);if(s.byId.has(a))return s.byId.get(a)}return s.here>0?0:null},tr=(s,o)=>{const x=new Map;return(s||[]).forEach(f=>{const a=f?.id??f?.warehouse_id??f?.code;a&&x.set(String(a),f?.name||f?.name_kr||f?.name_jp||String(a))}),(o||[]).forEach(f=>{const a=f?.warehouseId??f?.warehouse_id;a&&!x.has(String(a))&&x.set(String(a),String(a))}),[...x.entries()].map(([f,a])=>({id:f,name:a})).sort((f,a)=>f.id.localeCompare(a.id,"ja"))},sr=(s,o,x)=>{const f=new Map;(o||[]).forEach(j=>{j&&j.id!==void 0&&j.id!==null&&f.set(String(j.id),String(j.code??""))});const a=new Map,l=new Map;let w=0,d=0;return(s||[]).forEach(j=>{!j||j.is_deleted===!0||j.stock_posted!==!1&&(w+=1,(j.sales_slip_items||[]).forEach(Q=>{if(!Q||Q.is_reserve_fulfillment===!0)return;const W=Q.warehouse_id||j.warehouse_id;if(!W||x!==Lt&&String(W)!==String(x??""))return;const q=Number(Q.unit_qty??0)||0;if(q===0)return;const $=Q.product_id,O=Q.product_code,V=O!=null&&String(O)!==""?String(O):$!=null&&f.get(String($))||"";if(!(!V&&$==null)&&(d+=1,V&&a.set(V,(a.get(V)||0)+q),$!=null)){const X=String($);l.set(X,(l.get(X)||0)+q)}}))}),{byCode:a,byId:l,slipCount:w,lineCount:d}},rr=(s,o,x)=>{if(!s)return 0;const f=x!=null?String(x):"";if(f&&s.byCode.has(f))return s.byCode.get(f);if(o&&o.id!==void 0&&o.id!==null){const a=String(o.id);if(s.byId.has(a))return s.byId.get(a)}return 0},Et=(s,o)=>{const x=Number(s)||0,f=Math.max(0,Number(o)||0);return Math.max(0,x-f)},ns=(s=0)=>ps.format(new Date(Date.now()+s*864e5)),ar=s=>{if(!s)return"";const o=s?.toDate?s.toDate():new Date(s);return isNaN(o.getTime())?"":ps.format(o)},nr=({isOpen:s,onClose:o,watchedCodes:x,setWatchedCodes:f,products:a,T:l})=>{const[w,d]=u.useState(""),[j,Q]=u.useState([]),[W,q]=u.useState(-1),$=u.useRef(null);u.useEffect(()=>{if(!w.trim()){Q([]),q(-1);return}const S=bs(a,w).slice(0,20);Q(S),q(-1)},[w,a]),u.useEffect(()=>{s&&setTimeout(()=>$.current?.focus(),100)},[s]);const O=S=>{x.includes(S)||f([...x,S]),d(""),Q([]),q(-1),$.current?.focus()},V=S=>{f(x.filter(B=>B!==S))},X=S=>{j.length!==0&&(S.key==="ArrowDown"?(S.preventDefault(),q(B=>Math.min(B+1,j.length-1))):S.key==="ArrowUp"?(S.preventDefault(),q(B=>Math.max(B-1,0))):S.key==="Enter"&&(S.preventDefault(),W>=0&&W<j.length?O(j[W].code):j.length>0&&W===-1&&O(j[0].code)))};return u.useEffect(()=>{W>=0&&document.getElementById(`watched-search-result-${W}`)?.scrollIntoView({block:"nearest",behavior:"smooth"})},[W]),s?e.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/60 p-4",onClick:o,children:e.jsxs("div",{className:"bg-white rounded-xl shadow-2xl w-full max-w-lg flex flex-col overflow-hidden",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"p-4 border-b bg-amber-50 flex justify-between items-center",children:[e.jsxs("h3",{className:"font-bold text-lg text-amber-900 flex items-center gap-2",children:[e.jsx(ms,{size:20,className:"text-amber-600"}),l("ì§ì¤ ê´ë¦¬ ìí ì¤ì ","éä¸ç®¡çåå è¨å®")]}),e.jsx("button",{onClick:o,children:e.jsx(bt,{size:24,className:"text-gray-400 hover:text-gray-600"})})]}),e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:l("ìí ê²ì ë° ì¶ê°","ååæ¤ç´¢åã³è¿½å ")}),e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-3 text-gray-400 w-5 h-5"}),e.jsx("input",{ref:$,type:"text",value:w,onChange:S=>d(S.target.value),onKeyDown:X,placeholder:l("ìíëª
, ì½ë, ì´ì± ê²ì...","åååãã³ã¼ãæ¤ç´¢..."),className:"w-full pl-10 pr-4 py-2.5 border-2 border-amber-200 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 outline-none transition-all font-medium text-gray-800"})]}),j.length>0&&e.jsx("div",{className:"absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl max-h-60 overflow-y-auto",children:j.map((S,B)=>e.jsxs("div",{id:`watched-search-result-${B}`,onClick:()=>O(S.code),onMouseEnter:()=>q(B),className:`p-3 cursor-pointer border-b last:border-b-0 flex justify-between items-center group transition-colors ${B===W?"bg-amber-100 border-l-4 border-l-amber-500":"hover:bg-amber-50"}`,children:[e.jsxs("div",{children:[e.jsx("div",{className:`text-sm font-bold ${B===W?"text-amber-900":"text-gray-800"}`,children:l(S.name_kr,S.name_jp)}),e.jsx("div",{className:"text-xs font-mono text-gray-500",children:S.code})]}),e.jsx(us,{size:16,className:`transition-opacity ${B===W?"text-amber-600 opacity-100":"text-amber-400 opacity-0 group-hover:opacity-100"}`})]},S.id))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 border-b pb-2",children:[l("íì¬ ë±ë¡ë ìí","ç¾å¨ç»é²ããã¦ããåå")," ",e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",x.length,")"]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 max-h-40 overflow-y-auto pt-2",children:x.length===0?e.jsx("p",{className:"text-sm text-gray-400 italic",children:l("ë±ë¡ë ìíì´ ììµëë¤.","ç»é²ãããååãããã¾ããã")}):x.map(S=>{const B=a.find(le=>le.code===S),A=B?l(B.name_kr,B.name_jp):S;return e.jsxs("span",{className:"bg-amber-100 text-amber-900 px-3 py-1.5 rounded-full text-xs font-bold flex items-center shadow-sm border border-amber-200",children:[A," ",e.jsxs("span",{className:"text-[10px] text-amber-600 ml-1",children:["(",S,")"]}),e.jsx("button",{onClick:()=>V(S),className:"ml-2 hover:bg-amber-200 rounded-full p-0.5 transition-colors",children:e.jsx(bt,{size:14,className:"text-red-500"})})]},S)})})]})]}),e.jsx("div",{className:"p-4 border-t bg-gray-50 flex justify-end",children:e.jsx("button",{onClick:o,className:"bg-amber-600 text-white px-6 py-2 rounded-lg font-bold shadow-md hover:bg-amber-700 transition-colors",children:l("ì¤ì ìë£","è¨å®å®äº")})})]})}):null};function or({isOpen:s,onClose:o,orders:x,customers:f,products:a=[],inventory:l=[],warehouses:w=[],T:d,db:j,companyId:Q}){const W=u.useRef(null),[q,$]=u.useState([]),[O,V]=u.useState(!1),X=u.useRef(void 0),S=u.useRef(!1);u.useEffect(()=>{if(!Q){V(!0);return}let C=!0;(async()=>{const{data:b,error:E}=await M.from("settings").select("value").eq("company_id",Q).eq("key","watched_codes").maybeSingle();if(!C)return;if(E){console.error("[WatchedCodes] Supabase ì¡°í ì¤í¨:",E.message),S.current=!1,V(!0);return}const me=Array.isArray(b?.value?.codes)?b.value.codes:[];X.current=JSON.stringify(me),S.current=!0,$(me),V(!0)})();const T=M.channel(`rt_watched_codes_${Q}`).on("postgres_changes",{event:"*",schema:"public",table:"settings",filter:`company_id=eq.${Q}`},b=>{if(b.new?.key!=="watched_codes")return;const E=Array.isArray(b.new?.value?.codes)?b.new.value.codes:[];X.current=JSON.stringify(E),S.current=!0,$(E)}).subscribe();return()=>{C=!1,M.removeChannel(T)}},[Q]),u.useEffect(()=>{if(!Q||!O||!S.current)return;const C=JSON.stringify(q);if(X.current===C)return;const P=X.current;X.current=C,(async()=>{const{error:T}=await M.from("settings").upsert({company_id:Q,key:"watched_codes",value:{codes:q},updated_at:new Date().toISOString()},{onConflict:"company_id,key"});T&&(console.error("[WatchedCodes] Supabase ì ì¥ ì¤í¨:",T.message),X.current=P)})()},[q,O,Q]);const[B,A]=u.useState(!1),[le,y]=u.useState(Xs),K=u.useMemo(()=>tr(w,l),[w,l]),F=u.useMemo(()=>Ts(l,a,le),[l,a,le]),[de,se]=u.useState({status:"idle",rows:[],error:""}),Ce=u.useMemo(()=>[...new Set((x||[]).map(C=>
27C?.orderId).filter(Boolean).map(String))].sort().join("�"),[x]);u.useEffect(()=>{if(!s||!Q)return;const C=Ce?Ce.split("�"):[];if(C.length===0){se({status:"ok",rows:[],error:""});return}let P=!1;return se(T=>({...T,status:"loading",error:""})),(async()=>{try{const T=[];for(let b=0;b<C.length;b+=100){const E=C.slice(b,b+100);for(let me=0;;me+=1e3){const{data:je,error:oe}=await M.from("sales_slips").select("id, remarks2, warehouse_id, stock_posted, is_deleted, sales_slip_items(product_id, product_code, unit_qty, warehouse_id, is_reserve_fulfillment)").eq("company_id",Q).eq("is_deleted",!1).in("remarks2",E).order("id",{ascending:!0}).range(me,me+999);if(oe)throw oe;if(T.push(...je||[]),!je||je.length<1e3)break}}P||se({status:"ok",rows:T,error:""})}catch(T){console.error("[åºè·ã¬ãã¼ã] æ¿èªæ¸ã¿ä¼ç¥¨ã®èªã¿è¾¼ã¿å¤±æ:",T?.message||T),P||se({status:"error",rows:[],error:T?.message||String(T)})}})(),()=>{P=!0}},[s,Q,Ce]);const ce=u.useMemo(()=>sr(de.status==="ok"?de.rows:[],a,le),[de,a,le]),re=de.status==="ok",Y=u.useMemo(()=>({keys:F.byCode.size+F.byId.size,total:F.total,here:F.here}),[F]),ne=u.useMemo(()=>{if(le===Lt)return d("ì ì°½ê³ í©ê³","å ¨å庫 åè¨");const C=K.find(P=>P.id===le);return C?`${C.name} (${C.id})`:le},[le,K,d]),v=u.useMemo(()=>{const C={},P=ns(-7),T={};return(x||[]).forEach(b=>{let E=b.desiredDeliveryDate||"";!E&&b.orderDate?E=ar(b.orderDate)||"ë ì§ ë¯¸ì":E||(E="ë ì§ ë¯¸ì"),C[E]||(C[E]={memos:[],shortages:[],watched:[],costChanges:[],firstDelivery:[]}),T[E]||(T[E]={});const me=(f||[]).find(ae=>ae.code===b.partnerId||ae.id===b.partnerId||ae.id===b.customerId),je=b.partnerName||b.customerName||"Unknown",oe=me?d(me.name_kr||me.name||je,me.name_jp||me.name||je):je,tt=me?.code||b.partnerId||b.customerCode||b.customerId||"",qe=b.slipNo||b.orderId;b.warehouseId;const pe=b.memo||b.modificationReason||"",Ee=pe?pe.replace(/\[Note\]\n?/g,"").trim():"";Ee&&C[E].memos.push({id:b.id,customerName:oe,slipNo:qe,memo:Ee}),(b.products||b.items||[]).forEach(ae=>{const xe=ae.masterCode||ae.code||ae.productCode,ge=a.find(Oe=>Oe.code===xe),De=d(ge?.name_kr||ae.name,ge?.name_jp||ae.name),Pe=Number(ae.qty||ae.unitQty||0),Ae=er(F,ge,xe),Re=Ae!==null?Ae:Number(ae.current_stock_units??ae.currentStockUnits??ge?.current_stock_units??ge?.currentStockUnits??0),Ne=Ae!==null?Re+rr(ce,ge,xe):Re;T[E][xe]||(T[E][xe]={masterCode:xe,productName:De,currentStock:Re,preStock:Ne,totalQty:0,orders:[]}),T[E][xe].totalQty+=Pe,T[E][xe].orders.push({orderId:b.id,customerName:oe,slipNo:qe,qty:Pe}),Et(Pe,Ne)>0&&C[E].shortages.push({id:`${b.id}-${xe}`,customerName:oe,slipNo:qe,productCode:xe,productName:De,qty:Pe,currentStock:Re,preStock:Ne,shortage:Et(Pe,Ne),isBatch:!1}),q.includes(xe)&&C[E].watched.push({id:`${b.id}-${xe}`,customerCode:tt,customerName:oe,slipNo:qe,productCode:xe,productName:De,qty:Pe,currentStock:Re});const Ue=Number(ae.deliveryPrice||ae.unitPrice||ae.unit_price||0),Je=ae.isReserveFulfillment||ae.is_reserve_fulfillment||ae.isSupportFulfillment||ae.is_support_fulfillment||ae.isPromoFreebie||ae.is_promo_freebie;if(Ue===0&&!Je&&C[E].firstDelivery.push({id:`${b.id}-${xe}`,customerName:oe,slipNo:qe,productCode:xe,productName:De,qty:Pe}),ge?.cost_history&&Array.isArray(ge.cost_history)&&ge.cost_history.filter(ye=>ye.date>=P&&ye.type!=="migration").length>0){const ye=Number(ge.unit_cost??ge.cost_price??ge.unitCost??ge.costPrice??0),Qe=Number(ae.deliveryPrice||ae.unitPrice||ae.unit_price||0),Fe=Qe>0?(Qe-ye)/Qe*100:0;C[E].costChanges.push({id:`${b.id}-${xe}`,customerName:oe,slipNo:qe,productCode:xe,productName:De,deliveryPrice:Qe,currentCost:ye,margin:Fe})}})}),Object.keys(T).forEach(b=>{Object.values(T[b]).forEach(E=>{if(Et(E.totalQty,E.preStock)>0&&E.orders.length>1&&!C[b].shortages.some(je=>je.productCode===E.masterCode)){const je=E.orders.map(oe=>`${oe.customerName}(${oe.qty})`).join(", ");C[b].shortages.push({id:`batch-${b}-${E.masterCode}`,customerName:`[ëì í©ê³] ${je}`,slipNo:`${E.orders.length}ê° ì í í©ì°`,productCode:E.masterCode,productName:E.productName,qty:E.totalQty,currentStock:E.currentStock,preStock:E.preStock,shortage:Et(E.totalQty,E.preStock),isBatch:!0})}})}),C},[x,f,a,F,ce,q,d]),J=Object.keys(v).sort(),R=ns(0);if(!s)return null;const ue=()=>{const C=document.createElement("iframe");C.style.position="fixed",C.style.width="0px",C.style.height="0px",C.style.border="none",document.body.appendChild(C);const P=C.contentWindow.document;P.open(),P.write(` 28 <!DOCTYPE html> 29 <html> 30 <head> 31 <title>Dispatch_Control_Report_${R}</title> 32 <style> 33 @page { size: A4; margin: 10mm; } 34 body { font-family: 'Inter', 'Noto Sans JP', sans-serif; -webkit-print-color-adjust: exact; color: #111; margin: 0; padding: 0; } 35 .date-header { border-bottom: 2px solid #333; padding-bottom: 4px; margin-bottom: 16px; margin-top: 24px; font-size: 16px; font-weight: bold; background: #f3f4f6; padding: 8px; } 36 .section-title { font-size: 14px; font-weight: bold; margin-bottom: 8px; padding-bottom: 4px; border-bottom: 2px solid; display: flex; align-items: center; gap: 6px; } 37 .table { width: 100%; border-collapse: collapse; font-size: 12px; margin-bottom: 20px; } 38 .table th { border: 1px solid #ccc; padding: 6px; background-color: #f9f9f9; text-align: left; font-weight: bold; } 39 .table td { border: 1px solid #ccc; padding: 6px; vertical-align: middle; } 40 .text-right { text-align: right; } 41 .text-red { color: #dc2626; font-weight: bold; } 42 .bg-red-light { background-color: #fef2f2; } 43 </style> 44 </head> 45 <body> 46 ${W.current.innerHTML} 47 </body> 48 </html> 49 `),P.close(),C.contentWindow.focus(),C.contentWindow.print(),setTimeout(()=>{document.body.removeChild(C)},1e3)};return e.jsxs(e.Fragment,{children:[e.jsxs(Bt,{onClose:o,maxWidth:"max-w-5xl",children:[e.jsxs("div",{className:"flex justify-between items-center p-4 border-b bg-indigo-50 rounded-t-xl print:hidden",children:[e.jsxs("h2",{className:"text-lg font-bold text-indigo-900 flex items-center gap-2",children:[e.jsx(ss,{size:20}),d("ì¶í íµí© ê´ì 리í¬í¸","åºè· çµ±å管å¶ã¬ãã¼ã")]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs font-bold text-indigo-900",children:[d("ì¬ê³ 기ì¤","å¨åº«åºæº"),e.jsxs("select",{value:le,onChange:C=>y(C.target.value),className:"h-9 px-2 rounded-lg border border-indigo-300 bg-white text-sm font-bold text-gray-800",title:d("ê²°í íì ê³¼ íì¬ê³ íìì 기ì¤ì´ ëë ì°½ê³ ì ëë¤.","æ¬ åå¤å®ã¨ç¾å¨åº«è¡¨ç¤ºã®åºæºã¨ãªãå庫ã§ãã"),children:[K.map(C=>
49e.jsxs("option",{value:C.id,children:[C.name," (",C.id,")"]},C.id)),e.jsx("option",{value:Lt,children:d("ì ì°½ê³ í©ê³","å
¨å庫 åè¨")})]})]}),e.jsx("span",{className:`text-[11px] font-bold tabular-nums ${Y.total===0||Y.here===0||Y.keys===0?"text-rose-600":"text-gray-400"}`,title:d("ì¬ê³ íìì ì½ì í ìì
ëë¤. ãì´ ì°½ê³ ãê° 0 ì´ë©´ ê·¸ ì°½ê³ ì½ëë¡ ë ì¬ê³ íì´ ìë¤ë ë»ì
ëë¤.","å¨åº«è¡¨ããèªã¿åã£ãè¡æ°ã§ããããã®å庫ãã 0 ãªãããã®å庫ã³ã¼ãã®å¨åº«è¡ãããã¾ããã"),children:Y.total===0?d("ð´ ì¬ê³ í 0í â ì íì ì ì¥ë ê°ì ìëë¤","ð´ å¨åº«è¡¨ 0è¡ â ä¼ç¥¨ã®ä¿åå¤ã使ç¨"):Y.here===0?d(`ð´ ì´ ì°½ê³ 0í (ì¬ê³ í ${Y.total.toLocaleString()}í)`,`ð´ ãã®å庫 0è¡ (å¨åº«è¡¨ ${Y.total.toLocaleString()}è¡)`):d(`ì¬ê³ í ${Y.total.toLocaleString()}í · ì´ ì°½ê³ ${Y.here.toLocaleString()}í · ìì¸ ${Y.keys.toLocaleString()}í¤`,`å¨åº«è¡¨ ${Y.total.toLocaleString()}è¡ Â· ãã®å庫 ${Y.here.toLocaleString()}è¡ Â· ç´¢å¼ ${Y.keys.toLocaleString()}ãã¼`)}),!re&&e.jsx("span",{className:"text-[11px] font-bold text-rose-600",title:de.error||"",children:de.status==="error"?d("ð´ ì¹ì¸ ì í를 못 ì½ì â ë¶ì¡±ì´ ë§ê² ëìµëë¤","ð´ æ¿èªæ¸ã¿ä¼ç¥¨ãèªãã¾ãã â ä¸è¶³ãå¤ãã«åºã¾ã"):d("ì¹ì¸ ì í ì½ë ì¤â¦","æ¿èªæ¸ã¿ä¼ç¥¨ãèªã¿è¾¼ã¿ä¸â¦")}),e.jsxs("button",{onClick:()=>A(!0),className:"flex items-center gap-2 px-4 py-2 bg-amber-100 text-amber-800 hover:bg-amber-200 border border-amber-300 rounded-lg transition-colors font-bold text-sm",children:[e.jsx(ms,{size:16})," ",d("ì§ì¤ ê´ë¦¬ ìí ì¤ì ","éä¸ç®¡çååè¨å®"),q.length>0&&e.jsx("span",{className:"bg-amber-500 text-white px-1.5 py-0.5 rounded-full text-[10px] ml-1",children:q.length})]}),e.jsx(yt,{onClick:ue,variant:"primary",icon:ss,children:d("A4 ë¤ì´ë¡ë / ì¸ì","A4 ãã¦ã³ãã¼ã / å°å·")})]})]}),e.jsx("div",{className:"p-6 bg-gray-100 overflow-y-auto max-h-[70vh] print:p-0 print:m-0 print:max-h-none print:bg-white print:overflow-visible",children:e.jsxs("div",{ref:W,className:"bg-white mx-auto shadow-md print:shadow-none",style:{width:"210mm",minHeight:"297mm",padding:"15mm",boxSizing:"border-box"},children:[e.jsxs("div",{style:{borderBottom:"3px solid #111",paddingBottom:"10px",marginBottom:"20px",display:"flex",justifyContent:"space-between",alignItems:"flex-end"},children:[e.jsx("h1",{style:{fontSize:"26px",fontWeight:"900",margin:0,color:"#111"},children:d("ì¶í íµí© ê´ì 리í¬í¸","åºè· çµ±å管å¶ã¬ãã¼ã")}),e.jsxs("div",{style:{fontSize:"13px",color:"#666",fontWeight:"bold",textAlign:"right"},children:[e.jsxs("div",{children:[d("ì¸ìì¼ì:","å°å·æ¥:")," ",R]}),e.jsxs("div",{style:{marginTop:"3px",color:"#111"},children:[d("ì¬ê³ 기ì¤:","å¨åº«åºæº:")," ",ne]}),!re&&e.jsx("div",{style:{marginTop:"3px",color:"#dc2626"},children:d("â» ì¹ì¸ ì í를 못 ì½ì´ ê²°íì´ ë§ê² ëì¬ ì ììµëë¤","â» æ¿èªæ¸ã¿ä¼ç¥¨ãèªãããæ¬ åãå¤ãã«åºã¦ããå¯è½æ§ãããã¾ã")})]})]}),J.length===0?e.jsx("div",{style:{textAlign:"center",padding:"50px 0",color:"#888"},children:d("ì¶í ì í ë°ì´í°ê° ììµëë¤.","åºè·ä¼ç¥¨ãã¼ã¿ãããã¾ããã")}):J.map(C=>{const P=v[C];return P.memos.length>0||P.shortages.length>0||P.watched.length>0||P.costChanges.length>0||P.firstDelivery.length>0?e.jsxs("div",{style:{marginBottom:"40px"},children:[e.jsxs("div",{className:"date-header",children:["ð
",d("ë©íí¬ë§ì¼","ç´å叿æ¥"),": ",C]}),P.memos.length>0&&e.jsxs("div",{style:{marginBottom:"20px"},children:[e.jsxs("div",{className:"section-title",style:{borderColor:"#0ea5e9",color:"#0c4a6e"},children:["ð¬ ",d("ê±°ëì² í¹ë³ ìì²ì¬í (ë©ëª¨)","åå¼å
ç¹å¥è¦æäºé
(ã¡ã¢)")]}),e.jsxs("table",{className:"table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"25%"},children:d("ê±°ëì²ëª
","åå¼å
å")}),e.jsx("th",{style:{width:"20%"},children:d("ì íë²í¸","ä¼ç¥¨çªå·")}),e.jsx("th",{style:{width:"55%"},children:d("ìì²ì¬í","è¦æäºé
")})]})}),e.jsx("tbody",{children:P.memos.map(b=>e.jsxs("tr",{children:[e.jsx("td",{style:{fontWeight:"bold"},children:b.customerName}),e.jsx("td",{style:{color:"#555",fontFamily:"monospace"},children:b.slipNo}),e.jsx("td",{style:{whiteSpace:"pre-wrap"},children:b.memo})]},b.id))})]})]}),P.shortages.length>0&&e.jsxs("div",{style:{marginBottom:"20px"},children:[e.jsxs("div",{className:"section-title",style:{borderColor:"#ef4444",color:"#7f1d1d"},children:["ð¨ ",d("ê²°í/ì¬ê³ ë¶ì¡± ìí (í¼í¹ ì íë
)","æ¬ å/å¨åº«ä¸è¶³ åå (ãããã³ã°å å¿
èª)")]}),e.jsx("div",{style:{fontSize:"11px",color:"#666",margin:"-4px 0 6px"},children:d("ì¶íì ì¬ê³ = íì¬ê³ + ì´ ë¦¬í¬í¸ì ì¹ì¸ ì íê° ì´ë¯¸ ëº ìë","åºè·åå¨åº« = ç¾å¨åº« + ãã®ã¬ãã¼ãã®æ¿èªæ¸ã¿ä¼ç¥¨ã§æ¢ã«å·®ãå¼ããæ°")}),e.jsxs("table",{className:"table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"20%"},children:d("ê±°ëì²ëª
","åå¼å
å")}),e.jsx("th",{style:{width:"15%"},children:d("ìíì½ë","ã³ã¼ã")}),e.jsx("th",{style:{width:"35%"},children:d("ìíëª
","ååå")}),e.jsx("th",{className:"text-right",style:{width:"10%"},children:d("ë°ì£¼ë","çºæ³¨é")}),e.jsxs("th",{className:"text-right",style:{width:"10%"},children:[d("ì¶íì ì¬ê³ ","åºè·åå¨åº«"),e.jsx("br",{}),e.jsx("span",{style:{fontWeight:"normal",fontSize:"10px",color:"#666"},children:ne})]}),e.jsx("th",{className:"text-right",style:{width:"10%"},children:d("ë¶ì¡±ë¶","ä¸è¶³å")})]})}),e.jsx("tbody",{children:P.shortages.map(b=>e.jsxs("tr",{className:"bg-red-light",children:[e.jsx("td",{style:{fontWeight:"bold"},children:b.customerName}),e.jsx("td",{style:{fontFamily:"monospace"}
49,children:b.productCode}),e.jsx("td",{children:b.productName}),e.jsx("td",{className:"text-right font-bold",children:b.qty.toLocaleString()}),e.jsx("td",{className:"text-right",children:b.preStock.toLocaleString()}),e.jsxs("td",{className:"text-right text-red",children:["-",b.shortage.toLocaleString()]})]},b.id))})]})]}),P.firstDelivery.length>0&&e.jsxs("div",{style:{marginBottom:"20px"},children:[e.jsxs("div",{className:"section-title",style:{borderColor:"#16a34a",color:"#14532d"},children:["ð ",d("첫 ë©í / ë¨ê° 미ë±ë¡ ìí (ë¨ê° íì¸ íì)","ååç´å / å価æªç»é² åå (å価確èªè¦)")]}),e.jsxs("table",{className:"table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"25%"},children:d("ê±°ëì²ëª
","åå¼å
å")}),e.jsx("th",{style:{width:"15%"},children:d("ìíì½ë","ã³ã¼ã")}),e.jsx("th",{style:{width:"35%"},children:d("ìíëª
","ååå")}),e.jsx("th",{className:"text-right",style:{width:"12%"},children:d("주문ë","注æé")}),e.jsx("th",{className:"text-right",style:{width:"13%"},children:d("ë©íë¨ê°","ç´åå価")})]})}),e.jsx("tbody",{children:P.firstDelivery.map(b=>e.jsxs("tr",{style:{backgroundColor:"#f0fdf4"},children:[e.jsx("td",{style:{fontWeight:"bold"},children:b.customerName}),e.jsx("td",{style:{fontFamily:"monospace"},children:b.productCode}),e.jsx("td",{style:{fontWeight:"bold",color:"#15803d"},children:b.productName}),e.jsx("td",{className:"text-right font-bold",children:b.qty.toLocaleString()}),e.jsx("td",{className:"text-right text-red",style:{fontWeight:"bold"},children:"Â¥0"})]},b.id))})]})]}),P.watched.length>0&&e.jsxs("div",{style:{marginBottom:"20px"},children:[e.jsxs("div",{className:"section-title",style:{borderColor:"#f59e0b",color:"#78350f"},children:["ð¯ ",d("ì§ì¤ ê´ë¦¬ ìí (í¹ì ìí ì림)","éä¸ç®¡çåå (ç¹è¨äºé
)")]}),e.jsxs("table",{className:"table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"13%"},children:d("ê±°ëì²ì½ë","åå¼å
ã³ã¼ã")}),e.jsx("th",{style:{width:"22%"},children:d("ê±°ëì²ëª
","åå¼å
å")}),e.jsx("th",{style:{width:"13%"},children:d("ìíì½ë","ã³ã¼ã")}),e.jsx("th",{style:{width:"27%"},children:d("ìíëª
","ååå")}),e.jsx("th",{className:"text-right",style:{width:"12%"},children:d("ë°ì£¼ìë","çºæ³¨æ°é")}),e.jsxs("th",{className:"text-right",style:{width:"13%"},children:[d("íì¬ê³ ","ç¾å¨åº«"),e.jsx("br",{}),e.jsx("span",{style:{fontWeight:"normal",fontSize:"10px",color:"#666"},children:ne})]})]})}),e.jsx("tbody",{children:P.watched.map(b=>e.jsxs("tr",{children:[e.jsx("td",{style:{fontFamily:"monospace",fontWeight:"bold"},children:b.customerCode||"-"}),e.jsx("td",{style:{fontWeight:"bold"},children:b.customerName}),e.jsx("td",{style:{fontFamily:"monospace"},children:b.productCode}),e.jsx("td",{style:{fontWeight:"bold",color:"#d97706"},children:b.productName}),e.jsx("td",{className:"text-right font-bold",children:b.qty.toLocaleString()}),e.jsx("td",{className:"text-right",children:b.currentStock.toLocaleString()})]},b.id))})]})]}),P.costChanges.length>0&&e.jsxs("div",{style:{marginBottom:"20px"},children:[e.jsxs("div",{className:"section-title",style:{borderColor:"#8b5cf6",color:"#4c1d95"},children:["ð ",d("ìµê·¼ ìê° ë³ë ìí (ììµì± ì¬ê²í ìë§)","ç´è¿ å価å¤ååå (åçæ§åæ¤è¨ è¦æ)")]}),e.jsxs("table",{className:"table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"20%"},children:d("ê±°ëì²ëª
","åå¼å
å")}),e.jsx("th",{style:{width:"15%"},children:d("ìíì½ë","ã³ã¼ã")}),e.jsx("th",{style:{width:"25%"},children:d("ìíëª
","ååå")}),e.jsx("th",{className:"text-right",style:{width:"10%"},children:d("ë©íê°","ç´å価")}),e.jsx("th",{className:"text-right",style:{width:"15%"},children:d("íì¬ìê°","ç¾å¨å価")}),e.jsx("th",{className:"text-right",style:{width:"15%"},children:d("íì¬ ë§ì§ì¨","ç¾å¨ãã¼ã¸ã³")})]})}),e.jsx("tbody",{children:P.costChanges.map(b=>e.jsxs("tr",{children:[e.jsx("td",{style:{fontWeight:"bold"},children:b.customerName}),e.jsx("td",{style:{fontFamily:"monospace"}
49,children:b.productCode}),e.jsx("td",{children:b.productName}),e.jsx("td",{className:"text-right",children:b.deliveryPrice.toLocaleString()}),e.jsx("td",{className:"text-right",style:{color:"#6d28d9",fontWeight:"bold"},children:b.currentCost.toLocaleString()}),e.jsx("td",{className:"text-right",style:{color:b.margin<0?"#ef4444":"#111",fontWeight:"bold"},children:b.margin<0?`ð¨ ${d("[ìë§ì§]","[éãã¼ã¸ã³]")} ${b.margin.toFixed(1)}%`:`${b.margin.toFixed(1)}%`})]},b.id))})]})]})]},C):null}),e.jsxs("div",{style:{marginTop:"40px",borderTop:"1px solid #ddd",paddingTop:"10px",fontSize:"11px",color:"#888",textAlign:"center"},children:["SESE ERP System - æ¬æ¥åºè·ã¡ã¢ä¸è¦§ ⢠",d("ì´","è¨")," ",x?.length||0," ",d("ê±´ì ì í ë¶ìë¨","ä»¶ã®ä¼ç¥¨ç¢ºèªæ¸ã¿")]})]})})]}),e.jsx(nr,{isOpen:B,onClose:()=>A(!1),watchedCodes:q,setWatchedCodes:$,products:a,T:d})]})}function _r(s){const{T:o,setCurrentPage:x,warehouses:f,mainWarehouseId:a,db:l,companyId:w,products:d,salesData:j,purchases:Q,customers:W=[],currentUser:q}=s,{displayedOrders:$,paginatedOrders:O,loading:V,error:X,selectedOrder:S,isModalOpen:B,selectedOrderIds:A,isBatchModalOpen:le,isBatchExportModalOpen:y,isPickingListModalOpen:K,pendingBatchPdfData:F,pendingPickingListData:de,filters:se,sortConfig:Ce,paginationCurrentPage:ce,totalPages:re,summaryData:Y,customerOrderCounts:ne,todaysMemoOrders:v,todaysApprovedOrders:J,productMap:R,mappingMap:ue,allCustomerPrices:C,setFilters:P,setPaginationCurrentPage:T,setIsBatchModalOpen:b,setIsBatchExportModalOpen:E,setIsPickingListModalOpen:me,setPendingBatchPdfData:je,setPendingPickingListData:oe,handleOpenModal:tt,handleCloseModal:qe,handleShowAllPending:pe,handleShowApproved:Ee,handleSearch:ae,handleReset:xe,requestSort:ge,handleMapProduct:De,handleModify:Pe,handleCancelOrders:Ae,handleApprove:Re,handleBatchApprove:Ne,handleNavigateOrder:Ue,handleSelectOne:Je,handleSelectAll:Oe,canGoPrev:ye,canGoNext:Qe,formatCurrency:Fe,findLastSaleCost:Be,findLastPurchaseCost:He,getStatusClasses:vt,getStatusName:Ie,formatMessage:Ye}=Vs(s),[Ze,Ve]=dt.useState(!1),Xe=dt.useCallback(ie=>{if(!ie)return"-";try{const _e=ie.toDate?ie.toDate():new Date(ie);if(isNaN(_e.getTime()))return"-";const Le=_e.getTime()+_e.getTimezoneOffset()*6e4,ze=540*60*1e3;return new Date(Le+ze).toISOString().split("T")[0]}catch{return"-"}},[]),Ct=u.useMemo(()=>O?O.map(ie=>{const _e=W.find(Te=>Te.code===ie.partnerId||Te.id===ie.partnerId),Le=_e?.name_kr||_e?.name||ie.partnerName,ze=_e?.name_jp||_e?.name||ie.partnerName;return{...ie,displayPartnerName:o(Le,ze)}}):[],[O,W,o]),Dt=async()=>{if(A.length===0)return;const ie=window.prompt(o("ë°ì£¼ ì·¨ì ì¬ì 를 ì
ë ¥íì¸ì. (ìëµ ê°ë¥ â ë°ì£¼ì ì림ì í¬í¨ë©ëë¤)","ãã£ã³ã»ã«çç±ãå
¥åãã¦ãã ããã(çç¥å¯ â çºæ³¨è
ã¸ã®éç¥ã«å«ã¾ãã¾ã)"),"");ie!==null&&await Ae(A,ie)};return X?e.jsx("div",{className:"p-8 text-center text-red-400 bg-white min-h-screen",children:X}):V?e.jsxs("div",{className:"flex items-center justify-center min-h-screen bg-gray-50 text-gray-700",children:[e.jsx(Tt,{className:"w-8 h-8 animate-spin mr-3 text-teal-600"}),o("ë°ì´í° ë¡ë© ì¤...","ãã¼ã¿èªã¿è¾¼ã¿ä¸...")]}):e.jsxs("div",{className:"bg-gray-50 text-gray-900 min-h-screen",children:[e.jsxs("div",{className:"p-6 md:p-8",children:[e.jsx("header",{className:"mb-6 flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-gray-800 flex items-center gap-2",children:[e.jsx(Cs,{className:"text-teal-600"})," ",o("ê±°ëì² ë°ì£¼ì¹ì¸","åå¼å
çºæ³¨æ¿èª")]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:o("íë ¥ì¬ë¡ë¶í° ë¤ì´ì¨ 모ë°ì¼ ë°ì£¼ì를 íì¸íê³ ì¹ì¸í©ëë¤.","ååä¼ç¤¾ããã®ã¢ãã¤ã«çºæ³¨æ¸ã確èªããæ¿èªãã¾ãã")})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{onClick:pe,className:"bg-white p-5 rounded-xl border border-blue-200 shadow-sm flex items-center justify-between cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-all group",title:o("í´ë¦ ì ì ì²´ ì¹ì¸ë기 ëª©ë¡ ë³´ê¸°","ã¯ãªãã¯ã§å
¨æ¿èªå¾
ã¡ãªã¹ã表示"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-blue-600 mb-1 group-hover:text-blue-700",children:o("ì¹ì¸ ë기 ê±´ì","æ¿èªå¾
ã¡ä»¶æ°")}),e.jsxs("p",{className:"text-3xl font-black text-gray-800",children:[Y?.pendingCount||0,e.jsx("span",{className:"text-sm font-normal text-gray-500 ml-1",children:o("ê±´","ä»¶")})]})]}),e.jsx("div",{className:"p-3 bg-blue-100 rounded-full text-blue-600 group-hover:scale-110 transition-transform",children:e.jsx(Ds,{size:24})})]}),e.jsxs("div",{onClick:Ee,className:"bg-white p-5 rounded-xl border border-green-200 shadow-sm flex items-center justify-between cursor-pointer hover:bg-green-50 hover:border-green-300 transition-all group",title:o("í´ë¦ ì ìµê·¼ 10ì¼ ì¹ì¸ìë£Â·ì·¨ì ëª©ë¡ ë³´ê¸°","ã¯ãªãã¯ã§éå»10æ¥ã®æ¿èªå®äºã»ãã£ã³ã»ã«ãªã¹ã表示"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-green-600 mb-1 group-hover:text-green-700",children:o("ì¹ì¸ ìë£ (ìµê·¼ 10ì¼)","æ¿èªå®äº (éå»10æ¥)")}),e.jsxs("p",{className:"text-3xl font-black text-gray-800",children:[Y?.approvedCount||0,e.jsx("span",{className:"text-sm font-normal text-gray-500 ml-1",children:o("ê±´","ä»¶")})]})]}),e.jsx("div",{className:"p-3 bg-green-100 rounded-full text-green-600 group-hover:scale-110 transition-transform",children:e.jsx(Ot,{size:24})})]}),e.jsxs("div",{onClick:()=>Ve(!0),className:"bg-white p-5 rounded-xl border border-amber-200 shadow-sm flex items-center justify-between cursor-pointer hover:bg-amber-50 hover:border-amber-300 transition-all group",title:o("í´ë¦ ì ì¤ë ì¶íë ê±°ëì²ì ìì²ì¬í(ë©ëª¨)ë§ ëª¨ìì ì¸ìí©ëë¤.","ã¯ãªãã¯ã§æ¬æ¥åºè·ãããåå¼å
ã®è¦æäºé
(ã¡ã¢)ãå°å·ãã¾ãã"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-amber-600 mb-1 group-hover:text-amber-700",children:o("ì¤ë ì¶í ë©ëª¨ 모ì보기","æ¬æ¥åºè·ã¡ã¢ä¸è¦§")}),e.jsxs("p",{className:"text-3xl font-black text-gray-800",children:[v.length,e.jsx("span",{className:"text-sm font-normal text-gray-500 ml-1",children:o("ê±´","ä»¶")})]})]}),e.jsx("div",{className:"p-3 bg-amber-100 rounded-full text-amber-600 group-hover:scale-110 transition-transform",children:e.jsx(Xt,{size:24})})]})]}),e.jsxs("div",{className:"bg-white p-6 rounded-xl shadow-lg border-t-4 border-teal-500",children:[e.jsxs("div",{className:"mb-6 pb-6 border-b border-gray-100 flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"flex-1 min-w-[250px]",children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-1",children:o("ê±°ëì² ê²ì","åå¼å
æ¤ç´¢")}),e.jsxs("div",{className:"relative",children:[e.jsx(Zt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4"}),e.jsx("input",{type:"text",value:se.searchTerm,onChange:ie=>P(_e=>({..._e,searchTerm:ie.target.value})),onKeyDown:ie=>ie.key==="Enter"&&ae(),placeholder:o("ì´ë¦(í/ì¼), ì íë²í¸, ì½ë ê²ì...","åå(é/æ¥)ãé»è©±çªå·ãã³ã¼ãæ¤ç´¢..."),className:"w-full bg-gray-50 border border-gray-200 rounded-lg pl-9 pr-3 py-2 text-sm focus:bg-white focus:ring-2 focus:ring-teal-500 outline-none transition-colors"})]})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-1",children:o("ììì¼","éå§æ¥")}),e.jsx("input",{type:"date",value:se.startDate,onChange:ie=>P(_e=>({..._e,startDate:ie.target.value})),className:"bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 text-sm focus:bg-white focus:ring-2 focus:ring-teal-500 outline-none"})]}),e.jsx("span",{className:"text-gray-400 mt-4",children:"~"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-1",children:o("ì¢
ë£ì¼","çµäºæ¥")}),e.jsx("input",{type:"date",value:se.endDate,onChange:ie=>P(_e=>
49({..._e,endDate:ie.target.value})),className:"bg-gray-50 border border-gray-200 rounded-lg px-3 py-2 text-sm focus:bg-white focus:ring-2 focus:ring-teal-500 outline-none"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(yt,{onClick:ae,variant:"search",icon:Zt,children:o("ê²ì","æ¤ç´¢")}),e.jsx(yt,{onClick:xe,variant:"secondary",icon:ks})]})]}),e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(yt,{onClick:()=>b(!0),disabled:A.length===0||V,variant:"primary",icon:Ot,children:o(`ì í ${A.length}ê±´ ì¹ì¸`,`鏿 ${A.length}ä»¶ æ¿èª`)}),e.jsx(yt,{onClick:Dt,disabled:A.length===0||V,variant:"warning",icon:Ps,children:o(`ì í ${A.length}ê±´ ë°ì£¼ì·¨ì`,`鏿 ${A.length}ä»¶ çºæ³¨åæ¶`)})]}),e.jsx("span",{className:"text-sm font-medium text-gray-500",children:o(`ê²ì ê²°ê³¼: ${$.length}ê±´`,`æ¤ç´¢çµæ: ${$.length}ä»¶`)})]}),e.jsx(Ys,{orders:Ct,onOpenModal:tt,T:o,sortConfig:Ce,requestSort:ge,selectedOrderIds:A,onSelectOne:Je,onSelectAll:Oe,salesData:j,purchases:Q,productMap:R,mappingMap:ue,allCustomerPrices:C,customers:W,currentUser:q,formatDate:Xe,formatCurrency:Fe,formatMessage:Ye,findLastSaleCost:Be,findLastPurchaseCost:He,getStatusClasses:vt,getStatusName:Ie}),re>1&&e.jsxs("div",{className:"flex justify-center items-center mt-6 text-gray-600 space-x-4",children:[e.jsx("button",{onClick:()=>T(ie=>Math.max(1,ie-1)),disabled:ce===1,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 disabled:opacity-30 transition-colors",children:e.jsx(ls,{className:"w-5 h-5"})}),e.jsxs("span",{className:"text-sm font-bold bg-gray-100 px-4 py-1 rounded-full",children:[ce," / ",re]}),e.jsx("button",{onClick:()=>T(ie=>Math.min(re,ie+1)),disabled:ce===re,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 disabled:opacity-30 transition-colors",children:e.jsx(cs,{className:"w-5 h-5"})})]})]})]}),B&&e.jsx(Os,{db:l,companyId:w,order:S,isOpen:B,onClose:qe,onApprove:Re,onModify:Pe,T:o,productMap:R,products:d,onMapProduct:De,warehouses:f,mainWarehouseId:a,salesData:j,purchases:Q,formatCurrency:Fe,findLastSaleCost:Be,findLastPurchaseCost:He,inventory:s.inventory,onPrev:()=>Ue("prev"),onNext:()=>Ue("next"),hasPrev:ye,hasNext:Qe,customerOrderCounts:ne}),e.jsx(Zs,{isOpen:le,onClose:()=>b(!1),onBatchApprove:Ne,selectedIds:A,T:o,warehouses:f,mainWarehouseId:a}),y&&F&&e.jsx(Bt,{onClose:()=>{E(!1),je(null),de&&me(!0)},maxWidth:"max-w-4xl",children:e.jsx(xs,{...s,salesList:F})}),K&&de&&e.jsx(Bt,{onClose:()=>{me(!1),oe(null)},maxWidth:"max-w-4xl",children:e.jsx(gs,{...s,selectedSlips:de,setCurrentPage:(ie,_e)=>{me(!1),oe(null),x({page:ie,params:_e})}})}),e.jsx(or,{isOpen:Ze,onClose:()=>Ve(!1),orders:J,customers:s.customers,products:s.products,inventory:s.inventory,warehouses:f,T:s.T,db:s.db,companyId:s.companyId})]})}export{_r as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.