import{r as i,c as z}from"./vendor-react-CWq2BoMo.js";import{u as G,b as tt,c as b,j as m}from"./vendor-query-BSpUEUJE.js";import{a4 as et}from"./Index-CsHtvMhJ.js";import{u as at}from"./usePhpSellerId-C6BnBLkv.js";import{c as st,b as rt,J as d,a as F}from"./index-DVdSf46I.js";import{V as ct,a1 as nt,F as ot,P as ut}from"./currencyConfig-Ch2cK6at.js";/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const it=st("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]);/**
 * @license lucide-react v0.462.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */const dt=st("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]),Z="stocktake-sessions";function bt(){const o=G(),{get:k,post:l}=et(),p=at(),{currentEmployee:c}=rt(),h=t=>({...t,scope_categories:t.scope_categories?typeof t.scope_categories=="string"?JSON.parse(t.scope_categories):t.scope_categories:[],scope_locations:t.scope_locations?typeof t.scope_locations=="string"?JSON.parse(t.scope_locations):t.scope_locations:[],scope_products:t.scope_products?typeof t.scope_products=="string"?JSON.parse(t.scope_products):t.scope_products:[],assigned_to:t.assigned_to?typeof t.assigned_to=="string"?JSON.parse(t.assigned_to):t.assigned_to:[],total_products:Number(t.total_products)||0,counted_products:Number(t.counted_products)||0,products_with_variance:Number(t.products_with_variance)||0,total_system_qty:Number(t.total_system_qty)||0,total_counted_qty:Number(t.total_counted_qty)||0,total_variance_qty:Number(t.total_variance_qty)||0,total_variance_value:Number(t.total_variance_value)||0}),{data:n=[],isLoading:v,error:S,refetch:C}=tt({queryKey:[Z,p],queryFn:async()=>{if(!p)return[];const t=new URLSearchParams;t.append("action","get"),t.append("table","stocktake_sessions"),t.append("filters",JSON.stringify({seller_id:p})),t.append("orderBy","created_at"),t.append("orderDir","DESC");const e=await k(`auto-crud.php?${t.toString()}`);return e.success&&Array.isArray(e.data)?e.data.map(h):[]},enabled:!!p,staleTime:3e4}),g=i.useCallback(()=>{o.invalidateQueries({queryKey:[Z]})},[o]),I=i.useCallback(async()=>{const t=new Date,e=t.toISOString().slice(0,10).replace(/-/g,""),_=n.filter(f=>f.created_at.startsWith(t.toISOString().slice(0,10))).length+1;return`STK-${e}-${_.toString().padStart(3,"0")}`},[n]),E=b({mutationFn:async t=>{if(!p)throw new Error("لم يتم تحديد البائع");const e=await I(),s=t.name||`جرد ${e}`,_={id:crypto.randomUUID(),seller_id:p,session_number:e,name:s,type:t.type,status:"draft",scope_type:t.scope_type||"all",scope_categories:t.scope_categories?JSON.stringify(t.scope_categories):null,scope_products:t.scope_products?JSON.stringify(t.scope_products):null,scheduled_date:t.scheduled_date||null,assigned_to:t.assigned_to?JSON.stringify(t.assigned_to):null,created_by:(c==null?void 0:c.id)||null,notes:t.notes||null,total_products:0,counted_products:0,products_with_variance:0,total_system_qty:0,total_counted_qty:0,total_variance_qty:0,total_variance_value:0},f=await l("auto-crud.php?action=create&table=stocktake_sessions",_);if(!f.success)throw new Error(f.message||"فشل في إنشاء الجلسة");return f.data},onSuccess:()=>{d.success("تم إنشاء جلسة الجرد بنجاح"),g()},onError:t=>{d.error(t.message||"فشل في إنشاء جلسة الجرد")}}),$=b({mutationFn:async t=>{const e=new Date().toISOString().slice(0,19).replace("T"," "),s=await l(`auto-crud.php?action=update&table=stocktake_sessions&id=${t}`,{status:"in_progress",started_at:e});if(!s.success)throw new Error("فشل في بدء الجلسة");return s.data},onSuccess:()=>{d.success("تم بدء جلسة الجرد"),g()},onError:t=>{d.error(t.message||"فشل في بدء الجلسة")}}),j=b({mutationFn:async t=>{const e=new Date().toISOString().slice(0,19).replace("T"," "),s=await l(`auto-crud.php?action=update&table=stocktake_sessions&id=${t}`,{status:"pending_review",completed_at:e});if(!s.success)throw new Error("فشل في إكمال الجلسة");return s.data},onSuccess:()=>{d.success("تم إكمال العد وإرسال للمراجعة"),g()},onError:t=>{d.error(t.message||"فشل في إكمال الجلسة")}}),A=b({mutationFn:async({sessionId:t,notes:e})=>{const s=new Date().toISOString().slice(0,19).replace("T"," "),_=await l(`auto-crud.php?action=update&table=stocktake_sessions&id=${t}`,{status:"approved",approved_at:s,approved_by:c==null?void 0:c.id,approval_notes:e||null});if(!_.success)throw new Error("فشل في الموافقة");return _.data},onSuccess:()=>{d.success("تم الموافقة على الجرد"),g()},onError:t=>{d.error(t.message||"فشل في الموافقة")}}),M=b({mutationFn:async({sessionId:t,notes:e})=>{const s=new Date().toISOString().slice(0,19).replace("T"," "),_=new URLSearchParams;_.append("action","get"),_.append("table","stocktake_counts"),_.append("filters",JSON.stringify({session_id:t}));const f=await k(`auto-crud.php?${_.toString()}`),y=(f.success?f.data:[]).filter(w=>Number(w.variance_qty)!==0);for(const w of y){const N=Number(w.variance_qty),L=Number(w.counted_qty),Y=Number(w.system_qty),B=Number(w.unit_cost)||0;await l(`auto-crud.php?action=update&table=products&id=${w.product_id}`,{stock_quantity:L}),await l("auto-crud.php?action=create&table=inventory_movements",{id:crypto.randomUUID(),seller_id:p,product_id:w.product_id,type:"stocktake_adjustment",quantity_before:Y,quantity_after:L,quantity_change:N,unit_cost:B,total_cost:Math.abs(N)*B,reference_type:"stocktake",reference_id:t,notes:`تسوية جرد: ${N>0?"زيادة":"نقص"} ${Math.abs(N)} وحدة`,created_by:c==null?void 0:c.id,created_at:s}),await l("auto-crud.php?action=create&table=stocktake_settlements",{id:crypto.randomUUID(),seller_id:p,session_id:t,count_id:w.id,product_id:w.product_id,old_qty:Y,new_qty:L,adjustment_qty:N,adjustment_value:Math.abs(N)*B,variance_reason_id:w.variance_reason_id||null,settled_by:c==null?void 0:c.id,settled_at:s})}if(!(await l(`auto-crud.php?action=update&table=stocktake_sessions&id=${t}`,{status:"settled",settled_at:s,settled_by:c==null?void 0:c.id,settlement_notes:e||null})).success)throw new Error("فشل في التسوية");return{varianceCount:y.length}},onSuccess:t=>{d.success(`تم تسوية الجرد وتحديث ${t.varianceCount} منتج في المخزون`),g(),o.invalidateQueries({queryKey:["products"]})},onError:t=>{d.error(t.message||"فشل في التسوية")}}),O=b({mutationFn:async({sessionId:t,reason:e})=>{const s=await l(`auto-crud.php?action=update&table=stocktake_sessions&id=${t}`,{status:"cancelled",notes:e||"تم الإلغاء"});if(!s.success)throw new Error("فشل في إلغاء الجلسة");return s.data},onSuccess:()=>{d.success("تم إلغاء جلسة الجرد"),g()},onError:t=>{d.error(t.message||"فشل في إلغاء الجلسة")}}),x=b({mutationFn:async t=>{const e=n.find(_=>_.id===t);if(e&&e.status!=="draft")throw new Error("لا يمكن حذف جلسة غير مسودة");const s=await k(`auto-crud.php?action=delete&table=stocktake_sessions&id=${t}`);if(!s.success)throw new Error("فشل في الحذف");return s.data},onSuccess:()=>{d.success("تم حذف الجلسة"),g()},onError:t=>{d.error(t.message||"فشل في الحذف")}}),R=b({mutationFn:async({sessionId:t,stats:e})=>{const s=await l(`auto-crud.php?action=update&table=stocktake_sessions&id=${t}`,e);if(!s.success)throw new Error("فشل في تحديث الإحصائيات");return s.data},onSuccess:()=>{g()}}),U=i.useCallback(async t=>{try{return await E.mutateAsync(t)}catch{return null}},[E]),J=i.useCallback(async t=>{try{return await $.mutateAsync(t),!0}catch{return!1}},[$]),Q=i.useCallback(async t=>{try{return await j.mutateAsync(t),!0}catch{return!1}},[j]),V=i.useCallback(async(t,e)=>{try{return await A.mutateAsync({sessionId:t,notes:e}),!0}catch{return!1}},[A]),P=i.useCallback(async(t,e)=>{try{return await M.mutateAsync({sessionId:t,notes:e}),!0}catch{return!1}},[M]),T=i.useCallback(async(t,e)=>{try{return await O.mutateAsync({sessionId:t,reason:e}),!0}catch{return!1}},[O]),K=i.useCallback(async t=>{try{return await x.mutateAsync(t),!0}catch{return!1}},[x]),a=i.useCallback(async(t,e)=>{try{return await R.mutateAsync({sessionId:t,stats:e}),!0}catch{return!1}},[R]),r=i.useCallback(t=>n.find(e=>e.id===t),[n]),u=i.useCallback(async t=>{await C()},[C]);return{sessions:n,isLoading:v,error:S?S.message:null,fetchSessions:u,createSession:U,startSession:J,completeSession:Q,approveSession:V,settleSession:P,cancelSession:T,deleteSession:K,updateSessionStats:a,getSessionById:r,refetch:C,invalidateSessions:g}}const H="stocktake-counts";function W(o,k,l){const p=Number((k-o).toFixed(4)),c=Number((p*l).toFixed(4));return{variance_qty:p,variance_value:c}}function lt(o){return{...o,system_qty:Number(o.system_qty)||0,counted_qty:o.counted_qty!==null?Number(o.counted_qty):null,variance_qty:Number(o.variance_qty)||0,unit_cost:Number(o.unit_cost)||0,variance_value:Number(o.variance_value)||0,is_counted:o.is_counted===1||o.is_counted==="1"||o.is_counted===!0,recount_required:o.recount_required===1||o.recount_required==="1"||o.recount_required===!0}}function wt(o){const k=G(),{get:l,post:p}=et(),c=at(),{currentEmployee:h}=rt(),{data:n=[],isLoading:v,error:S,refetch:C}=tt({queryKey:[H,o,c],queryFn:async()=>{if(!o||!c)return[];const a=new URLSearchParams;a.append("action","get"),a.append("table","stocktake_counts"),a.append("filters",JSON.stringify({session_id:o,seller_id:c})),a.append("orderBy","product_name"),a.append("orderDir","ASC");const r=await l(`auto-crud.php?${a.toString()}`);return r.success&&Array.isArray(r.data)?(console.log("[Stocktake] Fetched items:",r.data.length),r.data.map(lt)):[]},enabled:!!o&&!!c,staleTime:30*1e3}),g=i.useCallback(()=>{k.invalidateQueries({queryKey:[H]}),k.invalidateQueries({queryKey:["stocktake-sessions"]})},[k]),I=i.useCallback(async a=>{if(!o)return;const r=a.filter(e=>e.is_counted),u=r.filter(e=>e.variance_qty!==0),t={counted_products:r.length,products_with_variance:u.length,total_counted_qty:r.reduce((e,s)=>e+(s.counted_qty||0),0),total_variance_qty:r.reduce((e,s)=>e+s.variance_qty,0),total_variance_value:r.reduce((e,s)=>e+s.variance_value,0)};try{await p(`auto-crud.php?action=update&table=stocktake_sessions&id=${o}`,t)}catch(e){console.error("Error updating session stats:",e)}},[o,p]),E=b({mutationFn:async a=>{var f,q;if(!c)throw new Error("لا يوجد معرف البائع");const r=new URLSearchParams;r.append("action","get"),r.append("table","stocktake_counts"),r.append("filters",JSON.stringify({session_id:a.id,seller_id:c})),r.append("limit","5");const u=await l(`auto-crud.php?${r.toString()}`);if(u.success&&Array.isArray(u.data)&&u.data.length>0)return console.log("Count items already exist"),u.data.length;const t=new URLSearchParams;t.append("action","get"),t.append("table","products"),t.append("filters",JSON.stringify({seller_id:c})),t.append("limit","1000");const e=await l(`auto-crud.php?${t.toString()}`);if(!e.success||!Array.isArray(e.data))throw new Error("فشل في جلب المنتجات");let s=e.data;a.scope_type==="category"&&((f=a.scope_categories)!=null&&f.length)?s=s.filter(y=>a.scope_categories.includes(y.category_id)):a.scope_type==="custom"&&((q=a.scope_products)!=null&&q.length)&&(s=s.filter(y=>a.scope_products.includes(y.id)));let _=0;for(const y of s){const D={id:crypto.randomUUID(),session_id:a.id,product_id:y.id,seller_id:c,system_qty:Number(y.stock_quantity)||0,counted_qty:null,variance_qty:0,unit_cost:Number(y.cost_price)||Number(y.unit_price)||0,variance_value:0,is_counted:0,count_method:"manual",product_name:y.product_name||y.name,product_sku:y.sku||null,product_barcode:y.barcode||null,category_name:y.category_name||null};(await p("auto-crud.php?action=create&table=stocktake_counts",D)).success&&_++}return await p(`auto-crud.php?action=update&table=stocktake_sessions&id=${a.id}`,{total_products:_,total_system_qty:s.reduce((y,D)=>y+(Number(D.stock_quantity)||0),0)}),_},onSuccess:a=>{d.success(`تم تحميل ${a} منتج للجرد`),g()},onError:a=>{d.error(a.message||"فشل في تهيئة عناصر العد")}}),$=b({mutationFn:async a=>{const r=n.find(q=>q.id===a.count_id);if(!r)throw new Error("العنصر غير موجود");const{variance_qty:u,variance_value:t}=W(r.system_qty,a.counted_qty,r.unit_cost),e=new Date().toISOString().slice(0,19).replace("T"," "),s={counted_qty:a.counted_qty,variance_qty:u,variance_value:t,is_counted:1,count_method:a.count_method||"manual",counted_by:h==null?void 0:h.id,counted_at:e,variance_notes:a.notes||null};if(!(await p(`auto-crud.php?action=update&table=stocktake_counts&id=${a.count_id}`,s)).success)throw new Error("فشل في تسجيل العدة");const f=n.map(q=>q.id===a.count_id?{...q,...s,is_counted:!0,counted_qty:a.counted_qty,variance_qty:u,variance_value:t}:q);return await I(f),{item:r,updateData:s}},onSuccess:()=>{g()},onError:a=>{d.error(a.message||"فشل في تسجيل العدة")}}),j=b({mutationFn:async({countId:a,reason:r})=>{if(!(await p(`auto-crud.php?action=update&table=stocktake_counts&id=${a}`,{recount_required:1,variance_notes:r||"يحتاج إعادة عد"})).success)throw new Error("فشل في طلب إعادة العد");return a},onSuccess:()=>{d.info("تم وضع علامة إعادة العد"),g()},onError:()=>{d.error("فشل في طلب إعادة العد")}}),A=b({mutationFn:async({countId:a,recountQty:r})=>{const u=n.find(f=>f.id===a);if(!u)throw new Error("العنصر غير موجود");const{variance_qty:t,variance_value:e}=W(u.system_qty,r,u.unit_cost),s=new Date().toISOString().slice(0,19).replace("T"," ");if(!(await p(`auto-crud.php?action=update&table=stocktake_counts&id=${a}`,{counted_qty:r,variance_qty:t,variance_value:e,recount_qty:r,recount_required:0,recounted_by:h==null?void 0:h.id,recounted_at:s})).success)throw new Error("فشل في تسجيل إعادة العد");return a},onSuccess:()=>{d.success("تم تسجيل إعادة العد"),g()},onError:()=>{d.error("فشل في تسجيل إعادة العد")}}),M=b({mutationFn:async({countId:a,reasonId:r,notes:u})=>{if(!(await p(`auto-crud.php?action=update&table=stocktake_counts&id=${a}`,{variance_reason_id:r,variance_notes:u||null})).success)throw new Error("فشل في تحديث سبب الفرق");return a},onSuccess:()=>{g()},onError:()=>{d.error("فشل في تحديث سبب الفرق")}}),O=i.useCallback(async a=>{try{return await E.mutateAsync(a)}catch{return 0}},[E]),x=i.useCallback(async a=>{try{return await $.mutateAsync(a),!0}catch{return!1}},[$]),R=i.useCallback(async a=>{let r=0;for(const u of a){const t=n.find(e=>e.product_id===u.product_id);t&&await x({count_id:t.id,counted_qty:u.counted_qty,count_method:"bulk"})&&r++}return r>0&&d.success(`تم تسجيل ${r} عدة`),r},[n,x]),U=i.useCallback(async(a,r)=>{try{return await j.mutateAsync({countId:a,reason:r}),!0}catch{return!1}},[j]),J=i.useCallback(async(a,r)=>{try{return await A.mutateAsync({countId:a,recountQty:r}),!0}catch{return!1}},[A]),Q=i.useCallback(async(a,r,u)=>{try{return await M.mutateAsync({countId:a,reasonId:r,notes:u}),!0}catch{return!1}},[M]),V=i.useCallback(a=>{const r=a.trim();return n.find(u=>u.product_barcode===r||u.product_sku===r)},[n]),P=i.useCallback(()=>{const a=n.filter(e=>e.is_counted),r=a.filter(e=>e.variance_qty!==0),u=r.filter(e=>e.variance_qty<0),t=r.filter(e=>e.variance_qty>0);return{total:n.length,counted:a.length,remaining:n.length-a.length,progress:n.length>0?Math.round(a.length/n.length*100):0,withVariance:r.length,shortageCount:u.length,surplusCount:t.length,totalSystemQty:n.reduce((e,s)=>e+s.system_qty,0),totalCountedQty:a.reduce((e,s)=>e+(s.counted_qty||0),0),totalVarianceQty:a.reduce((e,s)=>e+s.variance_qty,0),totalVarianceValue:a.reduce((e,s)=>e+s.variance_value,0),shortageValue:u.reduce((e,s)=>e+Math.abs(s.variance_value),0),surplusValue:t.reduce((e,s)=>e+s.variance_value,0)}},[n]),T=i.useCallback(()=>n.find(a=>!a.is_counted),[n]),K=i.useCallback(async a=>{await C()},[C]);return{countItems:n,isLoading:v,error:S?String(S):null,hasLoadedOnce:n.length>0||!v,fetchCountItems:K,initializeCountItems:O,submitCount:x,bulkCount:R,requestRecount:U,submitRecount:J,updateVarianceReason:Q,searchByBarcode:V,getStatistics:P,getNextUncountedItem:T,refetch:C,invalidateCounts:g}}const X=[{key:"draft",label:"إنشاء",icon:ot},{key:"in_progress",label:"العد",icon:ut},{key:"pending_review",label:"مراجعة",icon:it},{key:"approved",label:"موافقة",icon:nt},{key:"settled",label:"تسوية",icon:dt}],pt={draft:0,in_progress:1,pending_review:2,approved:3,settled:4,cancelled:-1},kt=({currentStatus:o,compact:k=!1})=>{const l=pt[o];return o==="cancelled"?m.jsxs("div",{className:"flex items-center justify-center gap-2 p-3 bg-destructive/10 rounded-lg border border-destructive/20",children:[m.jsx(ct,{className:"h-5 w-5 text-destructive"}),m.jsx("span",{className:"font-medium text-destructive",children:"جلسة ملغاة"})]}):k?m.jsx("div",{className:"flex items-center gap-1 overflow-x-auto pb-1",children:X.map((c,h)=>{const n=h<l,v=h===l,S=c.icon;return m.jsxs(z.Fragment,{children:[h>0&&m.jsx("div",{className:F("w-4 h-0.5 flex-shrink-0",n?"bg-primary":"bg-border")}),m.jsxs("div",{className:F("flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium transition-colors flex-shrink-0",n&&"bg-primary/10 text-primary",v&&"bg-primary text-primary-foreground",!n&&!v&&"bg-muted text-muted-foreground"),children:[m.jsx(S,{className:"h-3 w-3"}),m.jsx("span",{className:"hidden sm:inline",children:c.label})]})]},c.key)})}):m.jsx("div",{className:"flex items-center justify-between p-3 bg-muted/50 rounded-lg",children:X.map((c,h)=>{const n=h<l,v=h===l,S=c.icon;return m.jsxs(z.Fragment,{children:[h>0&&m.jsx("div",{className:F("flex-1 h-0.5 mx-1",n?"bg-primary":"bg-border")}),m.jsxs("div",{className:"flex flex-col items-center gap-1",children:[m.jsx("div",{className:F("w-8 h-8 rounded-full flex items-center justify-center transition-colors",n&&"bg-primary text-primary-foreground",v&&"bg-primary text-primary-foreground ring-4 ring-primary/20",!n&&!v&&"bg-muted text-muted-foreground border border-border"),children:n?m.jsx(nt,{className:"h-4 w-4"}):m.jsx(S,{className:"h-4 w-4"})}),m.jsx("span",{className:F("text-xs font-medium",n||v?"text-primary":"text-muted-foreground"),children:c.label})]})]},c.key)})})};export{it as C,kt as S,wt as a,bt as u};
