import{j as e}from"./vendor-query-BSpUEUJE.js";import{r as o}from"./vendor-react-CWq2BoMo.js";import{C as m,a as N,b as _,d as h,f as te}from"./card-Dd3vXi0j.js";import{B as I,a as g,D as re,j as le,J as ne}from"./index-DVdSf46I.js";import{F as G,m as ce,n as de,o as ie,p as oe,q as j,B as F,a1 as xe,a0 as me,v as he,w as ue,x as H,y as w,z as pe,A as C}from"./currencyConfig-Ch2cK6at.js";import{l as je,p as ve,q as ge,Z as fe,r as be,_ as ye,$ as Ne,a0 as _e,a1 as we,a2 as Ce,a3 as $e,C as qe}from"./Index-CsHtvMhJ.js";import{u as ke,a as Fe,S as Me}from"./StocktakeStepIndicator-D7EjZMX_.js";import{u as Te}from"./useVarianceReasons-C1qsjLC9.js";import{F as De}from"./filter-CrT8avJX.js";import{F as Re}from"./file-down-CoG2-WQC.js";import{R as K,a as Ie,b as Be,C as Y,T as J,B as Ee,d as Ve,X as Pe,Y as Le,f as Oe}from"./vendor-charts-bmwX1u6y.js";import{f as M,c as T}from"./vendor-date-BDZqQjIb.js";import"./vendor-pdf-OPq5ZiHo.js";import"./vendor-ui-extra-CW6ezZiQ.js";import"./vendor-ui-core-BWFXPlYg.js";import"./alert-cV8dsncc.js";import"./vendor-barcode-DhT-N8Id.js";import"./usePhpSellerId-C6BnBLkv.js";const f={draft:{label:"مسودة",color:"bg-gray-100 text-gray-800"},in_progress:{label:"جاري",color:"bg-blue-100 text-blue-800"},pending_review:{label:"مراجعة",color:"bg-yellow-100 text-yellow-800"},approved:{label:"معتمد",color:"bg-purple-100 text-purple-800"},settled:{label:"مُسوى",color:"bg-green-100 text-green-800"},cancelled:{label:"ملغى",color:"bg-red-100 text-red-800"}},na=({selectedSession:i,onSelectSession:ze})=>{var O,z,U,A;const{sessions:x,isLoading:X}=ke(),{reasons:b}=Te(),W=je(),[$,Z]=o.useState("all"),[B,E]=o.useState(!1),[v,V]=o.useState((i==null?void 0:i.id)||"");o.useEffect(()=>{i!=null&&i.id&&i.id!==v&&V(i.id)},[i==null?void 0:i.id]);const r=o.useMemo(()=>x.find(a=>a.id===v)||null,[x,v]),{countItems:d,getStatistics:P}=Fe(v||void 0),Q=o.useMemo(()=>$==="all"?x:x.filter(a=>a.status===$),[x,$]),y=o.useMemo(()=>!r||d.length===0?null:P(),[r,d,P]),L=o.useMemo(()=>{const a={};return d.filter(s=>s.variance_qty!==0&&s.variance_reason_id).forEach(s=>{const t=s.variance_reason_id,n=b.find(u=>u.id===t),p=(n==null?void 0:n.name)||"غير محدد";a[t]||(a[t]={name:p,count:0,value:0}),a[t].count++,a[t].value+=Math.abs(s.variance_value)}),Object.values(a).sort((s,t)=>t.count-s.count)},[d,b]),q=o.useMemo(()=>{const a=d.filter(t=>t.variance_qty<0),s=d.filter(t=>t.variance_qty>0);return[{name:"نقص",value:a.length,total:a.reduce((t,n)=>t+Math.abs(n.variance_value),0)},{name:"زيادة",value:s.length,total:s.reduce((t,n)=>t+n.variance_value,0)}]},[d]),D=o.useMemo(()=>[...d].filter(a=>a.variance_qty!==0).sort((a,s)=>Math.abs(s.variance_value)-Math.abs(a.variance_value)).slice(0,10),[d]),k=o.useMemo(()=>({total:x.length,completed:x.filter(a=>a.status==="settled").length,pending:x.filter(a=>["draft","in_progress","pending_review"].includes(a.status)).length,totalVarianceValue:x.filter(a=>a.status==="settled").reduce((a,s)=>a+Math.abs(s.total_variance_value),0)}),[x]),ee=()=>{if(!r||d.length===0)return;const a=["المنتج","الباركود","كمية النظام","الكمية المعدودة","الفرق","قيمة الفرق","السبب"],s=d.filter(c=>c.variance_qty!==0).map(c=>{var l;return[c.product_name,c.product_barcode||"-",c.system_qty,c.counted_qty,c.variance_qty,c.variance_value.toFixed(2),((l=b.find(R=>R.id===c.variance_reason_id))==null?void 0:l.name)||"-"]}),t="\uFEFF"+[a,...s].map(c=>c.join(",")).join(`
`),n=new Blob([t],{type:"text/csv;charset=utf-8;"}),p=URL.createObjectURL(n),u=document.createElement("a");u.href=p,u.download=`stocktake-report-${r.session_number}.csv`,u.click(),URL.revokeObjectURL(p)},ae=()=>{var n,p,u,c;if(!r||d.length===0)return;const a=d.filter(l=>l.variance_qty!==0),s=`
      <!DOCTYPE html>
      <html dir="rtl" lang="ar">
      <head>
        <meta charset="UTF-8">
        <title>تقرير الجرد - ${r.session_number}</title>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap');
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font-family: 'Tajawal', sans-serif; padding: 20px; direction: rtl; }
          .header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #333; padding-bottom: 20px; }
          .header h1 { font-size: 24px; margin-bottom: 10px; }
          .header p { color: #666; }
          .summary { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 30px; }
          .summary-card { background: #f5f5f5; padding: 15px; border-radius: 8px; text-align: center; }
          .summary-card .value { font-size: 24px; font-weight: bold; }
          .summary-card .label { font-size: 12px; color: #666; margin-top: 5px; }
          .shortage { color: #dc2626; }
          .surplus { color: #16a34a; }
          table { width: 100%; border-collapse: collapse; margin-top: 20px; }
          th, td { border: 1px solid #ddd; padding: 10px; text-align: center; }
          th { background: #333; color: white; }
          tr:nth-child(even) { background: #f9f9f9; }
          .footer { margin-top: 30px; text-align: center; color: #999; font-size: 12px; }
          @media print {
            body { padding: 0; }
            .no-print { display: none; }
          }
        </style>
      </head>
      <body>
        <div class="header">
          <h1>تقرير جرد المخزون</h1>
          <p>رقم الجلسة: ${r.session_number}</p>
          <p>${r.name}</p>
          <p>التاريخ: ${r.settled_at?M(new Date(r.settled_at),"dd/MM/yyyy",{locale:T}):M(new Date,"dd/MM/yyyy",{locale:T})}</p>
        </div>
        
        <div class="summary">
          <div class="summary-card">
            <div class="value">${(y==null?void 0:y.total)||0}</div>
            <div class="label">إجمالي المنتجات</div>
          </div>
          <div class="summary-card">
            <div class="value">${a.length}</div>
            <div class="label">منتجات بها فروقات</div>
          </div>
          <div class="summary-card">
            <div class="value shortage">-${((p=(n=q[0])==null?void 0:n.total)==null?void 0:p.toFixed(2))||"0.00"}</div>
            <div class="label">قيمة النقص</div>
          </div>
          <div class="summary-card">
            <div class="value surplus">+${((c=(u=q[1])==null?void 0:u.total)==null?void 0:c.toFixed(2))||"0.00"}</div>
            <div class="label">قيمة الزيادة</div>
          </div>
        </div>
        
        <h3>تفاصيل الفروقات</h3>
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>المنتج</th>
              <th>الباركود</th>
              <th>كمية النظام</th>
              <th>المعدود</th>
              <th>الفرق</th>
              <th>قيمة الفرق</th>
              <th>السبب</th>
            </tr>
          </thead>
          <tbody>
            ${a.map((l,R)=>{var S;return`
              <tr>
                <td>${R+1}</td>
                <td>${l.product_name}</td>
                <td>${l.product_barcode||"-"}</td>
                <td>${l.system_qty}</td>
                <td>${l.counted_qty}</td>
                <td class="${l.variance_qty<0?"shortage":"surplus"}">${l.variance_qty>0?"+":""}${l.variance_qty}</td>
                <td class="${l.variance_qty<0?"shortage":"surplus"}">${l.variance_qty<0?"-":"+"}${Math.abs(l.variance_value).toFixed(2)}</td>
                <td>${((S=b.find(se=>se.id===l.variance_reason_id))==null?void 0:S.name)||"-"}</td>
              </tr>
            `}).join("")}
          </tbody>
        </table>
        
        <div class="footer">
          <p>تم إنشاء التقرير بواسطة نظام إدارة المخزون</p>
        </div>
        
        <script>window.onload = function() { window.print(); }<\/script>
      </body>
      </html>
    `,t=window.open("","_blank");t&&(t.document.write(s),t.document.close(),ne.success("جاري إنشاء ملف PDF..."))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(m,{children:e.jsx(N,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs(_,{className:"flex items-center gap-2",children:[e.jsx(G,{className:"h-5 w-5"}),"تقارير الجرد"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(ce,{value:$,onValueChange:Z,children:[e.jsxs(de,{className:"w-[140px]",children:[e.jsx(De,{className:"h-4 w-4 ml-2"}),e.jsx(ie,{placeholder:"الحالة"})]}),e.jsxs(oe,{children:[e.jsx(j,{value:"all",children:"جميع الحالات"}),e.jsx(j,{value:"draft",children:"مسودة"}),e.jsx(j,{value:"in_progress",children:"جاري"}),e.jsx(j,{value:"pending_review",children:"مراجعة"}),e.jsx(j,{value:"approved",children:"معتمد"}),e.jsx(j,{value:"settled",children:"مُسوى"}),e.jsx(j,{value:"cancelled",children:"ملغى"})]})]}),e.jsxs(ve,{open:B,onOpenChange:E,children:[e.jsx(ge,{asChild:!0,children:e.jsxs(I,{variant:"outline",role:"combobox","aria-expanded":B,className:"w-[280px] justify-between",children:[v&&r?e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[e.jsx(F,{className:g("text-xs px-1 shrink-0",(O=f[r.status])==null?void 0:O.color),children:(z=f[r.status])==null?void 0:z.label}),e.jsx("span",{className:"truncate",children:r.name||r.session_number})]}):e.jsx("span",{className:"text-muted-foreground",children:"اختر جلسة الجرد..."}),e.jsx(fe,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(be,{className:"w-[280px] p-0",align:"start",children:e.jsxs(ye,{children:[e.jsx(Ne,{placeholder:"ابحث بالاسم أو الرقم..."}),e.jsxs(_e,{children:[e.jsx(we,{children:"لا توجد نتائج"}),e.jsx(Ce,{children:Q.map(a=>{var s,t;return e.jsxs($e,{value:`${a.name||""} ${a.session_number}`,onSelect:()=>{V(a.id),E(!1)},children:[e.jsx(xe,{className:g("ml-2 h-4 w-4",v===a.id?"opacity-100":"opacity-0")}),e.jsx(F,{className:g("text-xs px-1 ml-2",(s=f[a.status])==null?void 0:s.color),children:(t=f[a.status])==null?void 0:t.label}),e.jsxs("div",{className:"flex flex-col items-start",children:[e.jsx("span",{className:"font-medium",children:a.name||"بدون اسم"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a.session_number})]})]},a.id)})})]})]})})]}),r&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{variant:"outline",onClick:ee,className:"gap-2",children:[e.jsx(re,{className:"h-4 w-4"}),"CSV"]}),e.jsxs(I,{variant:"outline",onClick:ae,className:"gap-2",children:[e.jsx(Re,{className:"h-4 w-4"}),"PDF"]})]})]})]}),r&&e.jsx(Me,{currentStatus:r.status,compact:!0})]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(m,{children:e.jsxs(h,{className:"p-4 text-center",children:[e.jsx(qe,{className:"h-6 w-6 mx-auto text-blue-600 mb-2"}),e.jsx("p",{className:"text-2xl font-bold",children:k.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"إجمالي الجلسات"})]})}),e.jsx(m,{children:e.jsxs(h,{className:"p-4 text-center",children:[e.jsx(te,{className:"h-6 w-6 mx-auto text-green-600 mb-2"}),e.jsx("p",{className:"text-2xl font-bold",children:k.completed}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"جلسات مكتملة"})]})}),e.jsx(m,{children:e.jsxs(h,{className:"p-4 text-center",children:[e.jsx(me,{className:"h-6 w-6 mx-auto text-yellow-600 mb-2"}),e.jsx("p",{className:"text-2xl font-bold",children:k.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"قيد التنفيذ"})]})}),e.jsx(m,{children:e.jsxs(h,{className:"p-4 text-center",children:[e.jsx(le,{className:"h-6 w-6 mx-auto text-red-600 mb-2"}),e.jsx("p",{className:"text-2xl font-bold",children:k.totalVarianceValue.toFixed(0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"إجمالي الفروقات"})]})})]}),r&&y&&e.jsxs(e.Fragment,{children:[e.jsxs(m,{children:[e.jsx(N,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(_,{className:"text-lg",children:r.name}),e.jsx(F,{className:(U=f[r.status])==null?void 0:U.color,children:(A=f[r.status])==null?void 0:A.label})]})}),e.jsx(h,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"رقم الجلسة:"}),e.jsx("p",{className:"font-medium",children:r.session_number})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"تاريخ البدء:"}),e.jsx("p",{className:"font-medium",children:r.started_at?M(new Date(r.started_at),"dd/MM/yyyy",{locale:T}):"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"تاريخ الإنهاء:"}),e.jsx("p",{className:"font-medium",children:r.completed_at?M(new Date(r.completed_at),"dd/MM/yyyy",{locale:T}):"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"نسبة الإنجاز:"}),e.jsxs("p",{className:"font-medium",children:[y.progress,"%"]})]})]})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs(m,{children:[e.jsx(N,{className:"pb-2",children:e.jsx(_,{className:"text-base",children:"توزيع الفروقات"})}),e.jsx(h,{children:q.some(a=>a.value>0)?e.jsx(K,{width:"100%",height:200,children:e.jsxs(Ie,{children:[e.jsxs(Be,{data:q,cx:"50%",cy:"50%",innerRadius:40,outerRadius:80,paddingAngle:5,dataKey:"value",label:({name:a,value:s})=>`${a}: ${s}`,children:[e.jsx(Y,{fill:"#ef4444"}),e.jsx(Y,{fill:"#22c55e"})]}),e.jsx(J,{formatter:(a,s,t)=>[`${a} منتج (${t.payload.total.toFixed(2)})`,s]})]})}):e.jsx("div",{className:"h-[200px] flex items-center justify-center text-muted-foreground",children:"لا توجد فروقات"})})]}),e.jsxs(m,{children:[e.jsx(N,{className:"pb-2",children:e.jsx(_,{className:"text-base",children:"الفروقات حسب السبب"})}),e.jsx(h,{children:L.length>0?e.jsx(K,{width:"100%",height:200,children:e.jsxs(Ee,{data:L,layout:"vertical",children:[e.jsx(Ve,{strokeDasharray:"3 3"}),e.jsx(Pe,{type:"number"}),e.jsx(Le,{type:"category",dataKey:"name",width:80,tick:{fontSize:12}}),e.jsx(J,{formatter:a=>[`${a} منتج`,"العدد"]}),e.jsx(Oe,{dataKey:"count",fill:"hsl(var(--primary))",radius:[0,4,4,0]})]})}):e.jsx("div",{className:"h-[200px] flex items-center justify-center text-muted-foreground",children:"لا توجد بيانات"})})]})]}),e.jsxs(m,{children:[e.jsx(N,{className:"pb-3",children:e.jsx(_,{className:"text-base",children:"أكبر الفروقات قيمة"})}),e.jsx(h,{children:D.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"لا توجد فروقات"}):W?e.jsx("div",{className:"space-y-3",children:D.map((a,s)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"text-lg font-bold text-muted-foreground w-6",children:s+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:a.product_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["الفرق: ",a.variance_qty>0?"+":"",a.variance_qty]})]}),e.jsxs("div",{className:g("text-left font-bold",a.variance_qty<0?"text-red-600":"text-green-600"),children:[a.variance_qty<0?"-":"+",Math.abs(a.variance_value).toFixed(2)]})]},a.id))}):e.jsx("div",{className:"rounded-md border",children:e.jsxs(he,{children:[e.jsx(ue,{children:e.jsxs(H,{children:[e.jsx(w,{className:"w-10",children:"#"}),e.jsx(w,{children:"المنتج"}),e.jsx(w,{className:"text-center",children:"الفرق (كمية)"}),e.jsx(w,{className:"text-center",children:"الفرق (قيمة)"}),e.jsx(w,{children:"السبب"})]})}),e.jsx(pe,{children:D.map((a,s)=>{var t;return e.jsxs(H,{children:[e.jsx(C,{className:"font-medium",children:s+1}),e.jsx(C,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:a.product_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a.product_barcode||"-"})]})}),e.jsx(C,{className:"text-center",children:e.jsxs(F,{variant:"outline",className:g(a.variance_qty<0?"bg-red-50 text-red-700":"bg-green-50 text-green-700"),children:[a.variance_qty>0?"+":"",a.variance_qty]})}),e.jsxs(C,{className:g("text-center font-bold",a.variance_qty<0?"text-red-600":"text-green-600"),children:[a.variance_qty<0?"-":"+",Math.abs(a.variance_value).toFixed(2)]}),e.jsx(C,{children:((t=b.find(n=>n.id===a.variance_reason_id))==null?void 0:t.name)||"-"})]},a.id)})})]})})})]})]}),!r&&!X&&e.jsx(m,{children:e.jsxs(h,{className:"py-12 text-center",children:[e.jsx(G,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"اختر جلسة جرد"}),e.jsx("p",{className:"text-muted-foreground",children:"اختر جلسة جرد مكتملة لعرض التقرير التفصيلي"})]})})]})};export{na as StocktakeReport};
