PageSourceSearch

https://company-e82bc.web.app/assets/PartnerOrderApproval-CHH3ksLH.js

js company-e82bc.web.app collected 2026-10-03 12:20:58 UTC 137,571 bytes, 49 lines download raw bytes

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(/[0-9]/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(/[0-9]/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.