PageSourceSearch

https://tsofit.org.il/assets/BillingModule-cAmjIA8f.js

js tsofit.org.il collected 2026-09-25 02:14:03 UTC 619,822 bytes, 63 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/exceljs.min-CcgsY5Wm.js","assets/index-BuF13C9R.js","assets/index-B811haHf.css","assets/reportPdf-BRmDXPVe.js"])))=>i.map(i=>d[i]);
2import{R as he,bS as ir,r as i,j as e,d as D,as as Pt,a9 as Oe,X as $e,y as qt,F as bs,U as so,aA as ye,T as Re,P as We,C as la,b as Ie,z as W,aE as Jt,dx as Ke,a7 as nt,ar as At,x as De,ad as fs,aT as es,H as or,l as ra,aH as ao,M as no,u as ia,w as xt,aM as Xe,bs as Ns,aU as oa,Y as vs,aQ as In,ak as lo,a8 as gn,bK as ro,aD as Rc,a3 as Gs,aF as ws,N as zn,G as ca,_ as Kn,aG as ks,bX as io,dw as qc,aP as Ic,$ as gs,a as Aa,bE as yn,t as zc,ao as Kc,aJ as cr,aa as Wc,aO as Uc,d8 as Hc,ap as kr}from"./index-BuF13C9R.js";import{K as Yc}from"./KibbutzModuleGuard-ervrt65z.js";import{u as Vc}from"./useActionVisibility-DLgqAw2q.js";import{N as Me}from"./softDelete-X2GBluex.js";import{f as ve,b as oo}from"./money-CmD9E_V-.js";import{S as Gc}from"./SumitEmbeddedCheckout-X1I3bJQZ.js";import{g as Xc}from"./dashboardUtils-BNRxAObU.js";import{y as _e,W as dr,z as Zc,A as Qc,B as Jc,E as ed,G as ka,o as td,l as _n,r as Sr,v as Wn,h as Lt,q as as,S as sd,H as $r,J as ad,K as nd,M as ld,N as rd,O as Xs,Q as Cr,R as Es,U as ur,V as id,C as co,X as uo,Y as mo,Z as od,_ as cd,$ as dd,s as ud,u as md,m as xd,t as Ll,F as pd,i as hd,j as xo,w as po,k as bd}from"./kolboFile-9wwPFBSx.js";import{I as Un}from"./info-BIFqAg3-.js";import{H as Tl}from"./history-DRsCxblu.js";import{P as It}from"./pencil-CoE4mwuD.js";import{P as ho}from"./power-Cjs5sAhy.js";import{U as ys}from"./user-round-4Z7t4la9.js";import{B as fd}from"./baby-BUG_dxit.js";import{I as gd}from"./id-card-CMzMo_8f.js";import{S as da}from"./shopping-basket-Z4y6WHkT.js";import{B as yd}from"./BudgetItemSelect-D9zLjNZr.js";import{P as mr}from"./percent-C2DmKTeC.js";import{C as Be}from"./calendar-clock-Dg6I_-A7.js";import{E as _d}from"./eye-off-lYYIvXNt.js";import{R as Mt}from"./repeat-CJHHLdIV.js";import{S as jd}from"./StepCards-CDtME9a2.js";import{C as Ma,G as Nd,R as vd,F as wd,P as kd,a as xr,S as Sd,c as $d,b as bo,H as Cd}from"./sheet-D9xmjyjc.js";import{S as Ad}from"./settings-2-O6_6aFLq.js";import{C as lt}from"./chevron-left-D2IUBEPa.js";import{R as fo}from"./receipt-C8ikpKpP.js";import{S as Hn}from"./sliders-horizontal-D0cjPgOh.js";import{C as Md}from"./columns-3-DJizGI6o.js";import{F as pr}from"./file-spreadsheet-B8pSCGeX.js";import{F as go}from"./file-down-CrVKunWa.js";import{P as yo}from"./printer-BwQiYGcP.js";import{F as hr}from"./filter-Bnc7eQ-s.js";import{A as _o}from"./arrow-down-CqE1RxaS.js";import{A as jo}from"./arrow-up-down-H69UbrCK.js";import{C as No}from"./ConfirmDialog-B9VWyx7W.js";import{U as La}from"./upload-DeFZlL4S.js";import{C as Pd}from"./circle-pause-ARb36XiP.js";import{P as vo}from"./play-BbfkX4y6.js";import{P as Ed}from"./pause-Li2qDNkT.js";import{R as br}from"./refresh-cw-DvPS6Mu1.js";import{A as Ar}from"./arrow-left-right-CHYYMQPF.js";import{B as Fd}from"./banknote-BAXkyBwn.js";import{F as Dd}from"./file-check-D2O-2b5u.js";import{P as jn}from"./paperclip-BMrctHny.js";import{B as Od}from"./ban-BrNeMJoo.js";import{C as rt}from"./coins-Ke0c7IVk.js";import{C as Ld}from"./calendar-range-Drzgm4HZ.js";import{S as Mr}from"./sticky-note-Cb-DcYYp.js";import{P as fr,k as kt,a as gr,b as Js,e as Wa,f as Ua,g as Pr,B as Er,n as Fr,i as wo,v as Dr,s as Or,j as Td,c as ko,l as Bd,d as Rd,p as qd,h as Id,t as zd}from"./paymentCatalogs-CvImawYM.js";import{S as Lr}from"./shopping-cart-CMl29wkm.js";import{L as Zt}from"./link-2-BTwRH0ED.js";import{f as Bt,e as wt,$ as Ha,i as Ws,I as un,M as So,N as Nt,J as Ht,a0 as Kd,O as Bl,Z as Wd,P as Ta,Q as $o,b as Nn,G as Co,K as Zs,_ as vn,H as Ud,S as Tr,a1 as Hd,h as Yd,U as Ao,Y as Vd,a2 as Gd,C as _s,p as Xd,B as pt,q as Zd,R as Rt,T as ht,L as Qd,a3 as Mo}from"./generateCategoricalChart-D9kEchEU.js";import{X as Qt,Y as Ct,B as Ba}from"./BarChart-BV6G5gJY.js";import{C as js}from"./CartesianGrid-D3McakTz.js";import{P as Yn,a as Vn}from"./PieChart-knnFYOG7.js";import{S as Jd}from"./scale-Ccy3cfrP.js";import{L as yr}from"./Line-rdVrUAZx.js";import{S as wn}from"./sparkles-Bk9eJtR5.js";import{W as eu}from"./wand-sparkles-vdWz8Wpd.js";import{B as Po}from"./bookmark-BA373k3D.js";import{H as tu}from"./hash-DXwUI4fi.js";import{m as Br}from"./digitalPageOrder-C4niF6hl.js";import{o as Rr}from"./reorder-BJ1u2xSy.js";import{G as su}from"./grip-vertical-D-WILyUY.js";import{b as au,c as nu,k as lu}from"./messageComposition-CWPHxpB-.js";import{C as Eo}
2from"./copy-BClGV4nG.js";import{S as ru}from"./share-2-BamByTGH.js";import{L as iu}from"./list-ordered-tSTk2Phj.js";import{R as ou}from"./rotate-ccw-BudqP26q.js";import{F as cu}from"./file-pen-line-D5MCQ02J.js";import"./votingUtils-3kN6dDVT.js";import"./headphones-Bk55olo7.js";import"./formStyles-CzLsWpb8.js";import"./alert-dialog-BrDEU3Wj.js";import"./isEqual-Bszk2vQ5.js";import"./tiny-invariant-BaFNuDhB.js";var du=["layout","type","stroke","connectNulls","isRange","ref"],uu=["key"],Fo;function ea(t){"@babel/helpers - typeof";return ea=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},ea(t)}function Do(t,s){if(t==null)return{};var n=mu(t,s),a,l;if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(l=0;l<r.length;l++)a=r[l],!(s.indexOf(a)>=0)&&Object.prototype.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function mu(t,s){if(t==null)return{};var n={};for(var a in t)if(Object.prototype.hasOwnProperty.call(t,a)){if(s.indexOf(a)>=0)continue;n[a]=t[a]}return n}function ms(){return ms=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},ms.apply(this,arguments)}function qr(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);s&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),n.push.apply(n,a)}return n}function Ut(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?qr(Object(n),!0).forEach(function(a){St(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):qr(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function xu(t,s){if(!(t instanceof s))throw new TypeError("Cannot call a class as a function")}function Ir(t,s){for(var n=0;n<s.length;n++){var a=s[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(t,Lo(a.key),a)}}function pu(t,s,n){return s&&Ir(t.prototype,s),n&&Ir(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function hu(t,s,n){return s=kn(s),bu(t,Oo()?Reflect.construct(s,n||[],kn(t).constructor):s.apply(t,n))}function bu(t,s){if(s&&(ea(s)==="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return fu(t)}function fu(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function Oo(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Oo=function(){return!!t})()}function kn(t){return kn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},kn(t)}function gu(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(s&&s.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),s&&Rl(t,s)}function Rl(t,s){return Rl=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,l){return a.__proto__=l,a},Rl(t,s)}function St(t,s,n){return s=Lo(s),s in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function Lo(t){var s=yu(t,"string");return ea(s)=="symbol"?s:s+""}function yu(t,s){if(ea(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,s);if(ea(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var Ss=(function(t){function s(){var n;xu(this,s);for(var a=arguments.length,l=new Array(a),r=0;r<a;r++)l[r]=arguments[r];return n=hu(this,s,[].concat(l)),St(n,"state",{isAnimationFinished:!0}),St(n,"id",$o("recharts-area-")),St(n,"handleAnimationEnd",function(){var o=n.props.onAnimationEnd;n.setState({isAnimationFinished:!0}),Nn(o)&&o()}),St(n,"handleAnimationStart",function(){var o=n.props.onAnimationStart;n.setState({isAnimationFinished:!1}),Nn(o)&&o()}),n}return gu(s,t),pu(s,[{key:"renderDots",value:function(a,l,r){var o=this.props.isAnimationActive,p=this.state.isAnimationFinished;if(o&&!p)return null;var u=this.props,d=u.dot,c=u.points,m=u.dataKey,h=Bt(this.props,!1),b=Bt(d,!0),f=c.map(function(g,y){var $=Ut(Ut(Ut({key:"dot-".concat(y),r:3},h),b),{},{index:y,cx:g.x,cy:g.y,dataKey:m,value:g.value,payload:g.payload,points:c});return s.renderDotItem(d,$)}
2),x={clipPath:a?"url(#clipPath-".concat(l?"":"dots-").concat(r,")"):null};return he.createElement(wt,ms({className:"recharts-area-dots"},x),f)}},{key:"renderHorizontalRect",value:function(a){var l=this.props,r=l.baseLine,o=l.points,p=l.strokeWidth,u=o[0].x,d=o[o.length-1].x,c=a*Math.abs(u-d),m=Ha(o.map(function(h){return h.y||0}));return Ws(r)&&typeof r=="number"?m=Math.max(r,m):r&&Array.isArray(r)&&r.length&&(m=Math.max(Ha(r.map(function(h){return h.y||0})),m)),Ws(m)?he.createElement("rect",{x:u<d?u:u-c,y:0,width:c,height:Math.floor(m+(p?parseInt("".concat(p),10):1))}):null}},{key:"renderVerticalRect",value:function(a){var l=this.props,r=l.baseLine,o=l.points,p=l.strokeWidth,u=o[0].y,d=o[o.length-1].y,c=a*Math.abs(u-d),m=Ha(o.map(function(h){return h.x||0}));return Ws(r)&&typeof r=="number"?m=Math.max(r,m):r&&Array.isArray(r)&&r.length&&(m=Math.max(Ha(r.map(function(h){return h.x||0})),m)),Ws(m)?he.createElement("rect",{x:0,y:u<d?u:u-c,width:m+(p?parseInt("".concat(p),10):1),height:Math.floor(c)}):null}},{key:"renderClipRect",value:function(a){var l=this.props.layout;return l==="vertical"?this.renderVerticalRect(a):this.renderHorizontalRect(a)}},{key:"renderAreaStatically",value:function(a,l,r,o){var p=this.props,u=p.layout,d=p.type,c=p.stroke,m=p.connectNulls,h=p.isRange;p.ref;var b=Do(p,du);return he.createElement(wt,{clipPath:r?"url(#clipPath-".concat(o,")"):null},he.createElement(un,ms({},Bt(b,!0),{points:a,connectNulls:m,type:d,baseLine:l,layout:u,stroke:"none",className:"recharts-area-area"})),c!=="none"&&he.createElement(un,ms({},Bt(this.props,!1),{className:"recharts-area-curve",layout:u,type:d,connectNulls:m,fill:"none",points:a})),c!=="none"&&h&&he.createElement(un,ms({},Bt(this.props,!1),{className:"recharts-area-curve",layout:u,type:d,connectNulls:m,fill:"none",points:l})))}},{key:"renderAreaWithAnimation",value:function(a,l){var r=this,o=this.props,p=o.points,u=o.baseLine,d=o.isAnimationActive,c=o.animationBegin,m=o.animationDuration,h=o.animationEasing,b=o.animationId,f=this.state,x=f.prevPoints,g=f.prevBaseLine;return he.createElement(So,{begin:c,duration:m,isActive:d,easing:h,from:{t:0},to:{t:1},key:"area-".concat(b),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(y){var $=y.t;if(x){var O=x.length/p.length,A=p.map(function(k,C){var w=Math.floor(C*O);if(x[w]){var _=x[w],T=Nt(_.x,k.x),M=Nt(_.y,k.y);return Ut(Ut({},k),{},{x:T($),y:M($)})}return k}),S;if(Ws(u)&&typeof u=="number"){var P=Nt(g,u);S=P($)}else if(Ht(u)||Kd(u)){var E=Nt(g,0);S=E($)}else S=u.map(function(k,C){var w=Math.floor(C*O);if(g[w]){var _=g[w],T=Nt(_.x,k.x),M=Nt(_.y,k.y);return Ut(Ut({},k),{},{x:T($),y:M($)})}return k});return r.renderAreaStatically(A,S,a,l)}return he.createElement(wt,null,he.createElement("defs",null,he.createElement("clipPath",{id:"animationClipPath-".concat(l)},r.renderClipRect($))),he.createElement(wt,{clipPath:"url(#animationClipPath-".concat(l,")")},r.renderAreaStatically(p,u,a,l)))})}},{key:"renderArea",value:function(a,l){var r=this.props,o=r.points,p=r.baseLine,u=r.isAnimationActive,d=this.state,c=d.prevPoints,m=d.prevBaseLine,h=d.totalLength;return u&&o&&o.length&&(!c&&h>0||!Bl(c,o)||!Bl(m,p))?this.renderAreaWithAnimation(a,l):this.renderAreaStatically(o,p,a,l)}},{key:"render",value:function(){var a,l=this.props,r=l.hide,o=l.dot,p=l.points,u=l.className,d=l.top,c=l.left,m=l.xAxis,h=l.yAxis,b=l.width,f=l.height,x=l.isAnimationActive,g=l.id;if(r||!p||!p.length)return null;var y=this.state.isAnimationFinished,$=p.length===1,O=ir("recharts-area",u),A=m&&m.allowDataOverflow,S=h&&h.allowDataOverflow,P=A||S,E=Ht(g)?this.id:g,k=(a=Bt(o,!1))!==null&&a!==void 0?a:{r:3,strokeWidth:2},C=k.r,w=C===void 0?3:C,_=k.strokeWidth,T=_===void 0?2:_,M=Wd(o)?o:{},B=M.clipDot,R=B===void 0?!0:B,j=w*2+T;return he.createElement(wt,{className:O},A||S?he.createElement("defs",null,he.createElement("clipPath",{id:"clipPath-".concat(E)},he.createElement("rect",{x:A?c:c-b/2,y:S?d:d-f/2,width:A?b:b*2,height:S?f:f*2})),!R&&he.createElement("clipPath",{id:"clipPath-dots-".concat(E)},he.createElement("rect",{x:c-j/2,y:d-j/2,width:b+j,height:f+j}))):null,$?null:this.renderArea(P,E),(o||$)&&this.renderDots(P,R,E),(!x||y)&&Ta.renderCallByParent(this.props,p))}}],[{key:"getDerivedStateFromProps",value:function(a,l){return a.animationId!==l.prevAnimationId?{prevAnimationId:a.animationId,curPoints:a.points,curBaseLine:a.baseLine,prevPoints:l.curPoints,prevBaseLine:l.curBaseLine}:a.points!==l.curPoints||a.baseLine!==l.curBaseLine?{curPoints:a.points,curBaseLine:a.baseLine}:null}}])})(i.PureComponent);Fo=Ss;
2St(Ss,"displayName","Area");St(Ss,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!Co.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});St(Ss,"getBaseValue",function(t,s,n,a){var l=t.layout,r=t.baseValue,o=s.props.baseValue,p=o??r;if(Ws(p)&&typeof p=="number")return p;var u=l==="horizontal"?a:n,d=u.scale.domain();if(u.type==="number"){var c=Math.max(d[0],d[1]),m=Math.min(d[0],d[1]);return p==="dataMin"?m:p==="dataMax"||c<0?c:Math.max(Math.min(d[0],d[1]),0)}return p==="dataMin"?d[0]:p==="dataMax"?d[1]:d[0]});St(Ss,"getComposedData",function(t){var s=t.props,n=t.item,a=t.xAxis,l=t.yAxis,r=t.xAxisTicks,o=t.yAxisTicks,p=t.bandSize,u=t.dataKey,d=t.stackedData,c=t.dataStartIndex,m=t.displayedData,h=t.offset,b=s.layout,f=d&&d.length,x=Fo.getBaseValue(s,n,a,l),g=b==="horizontal",y=!1,$=m.map(function(A,S){var P;f?P=d[c+S]:(P=Zs(A,u),Array.isArray(P)?y=!0:P=[x,P]);var E=P[1]==null||f&&Zs(A,u)==null;return g?{x:vn({axis:a,ticks:r,bandSize:p,entry:A,index:S}),y:E?null:l.scale(P[1]),value:P,payload:A}:{x:E?null:a.scale(P[1]),y:vn({axis:l,ticks:o,bandSize:p,entry:A,index:S}),value:P,payload:A}}),O;return f||y?O=$.map(function(A){var S=Array.isArray(A.value)?A.value[0]:null;return g?{x:A.x,y:S!=null&&A.y!=null?l.scale(S):null}:{x:S!=null?a.scale(S):null,y:A.y}}):O=g?l.scale(x):a.scale(x),Ut({points:$,baseLine:O,layout:b,isRange:y},h)});St(Ss,"renderDotItem",function(t,s){var n;if(he.isValidElement(t))n=he.cloneElement(t,s);else if(Nn(t))n=t(s);else{var a=ir("recharts-area-dot",typeof t!="boolean"?t.className:""),l=s.key,r=Do(s,uu);n=he.createElement(Ud,ms({},r,{key:l,className:a}))}return n});function ta(t){"@babel/helpers - typeof";return ta=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},ta(t)}function _u(t,s){if(!(t instanceof s))throw new TypeError("Cannot call a class as a function")}function ju(t,s){for(var n=0;n<s.length;n++){var a=s[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(t,Ro(a.key),a)}}function Nu(t,s,n){return s&&ju(t.prototype,s),Object.defineProperty(t,"prototype",{writable:!1}),t}function vu(t,s,n){return s=Sn(s),wu(t,To()?Reflect.construct(s,n||[],Sn(t).constructor):s.apply(t,n))}function wu(t,s){if(s&&(ta(s)==="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ku(t)}function ku(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function To(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(To=function(){return!!t})()}function Sn(t){return Sn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},Sn(t)}function Su(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(s&&s.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),s&&ql(t,s)}function ql(t,s){return ql=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,l){return a.__proto__=l,a},ql(t,s)}function Bo(t,s,n){return s=Ro(s),s in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function Ro(t){var s=$u(t,"string");return ta(s)=="symbol"?s:s+""}function $u(t,s){if(ta(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,s);if(ta(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var Gn=(function(t){function s(){return _u(this,s),vu(this,s,arguments)}return Su(s,t),Nu(s,[{key:"render",value:function(){return null}}])})(i.Component);Bo(Gn,"displayName","ZAxis");Bo(Gn,"defaultProps",{zAxisId:0,range:[64,64],scale:"auto",type:"number"});var Cu=["option","isActive"];function Sa(){return Sa=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},Sa.apply(this,arguments)}function Au(t,s){if(t==null)return{};var n=Mu(t,s),a,l;if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);for(l=0;l<r.length;l++)a=r[l],!(s.indexOf(a)>=0)&&Object.prototype.propertyIsEnumerable.call(t,a)&&(n[a]=t[a])}return n}function Mu(t,s){if(t==null)return{};var n={};for(var a in t)if(Object.prototype.hasOwnProperty.call(t,a)){if(s.indexOf(a)>=0)continue;n[a]=t[a]}return n}function Pu(t){var s=t.option,n=t.isActive,a=Au(t,Cu);return typeof s=="string"?i.createElement(Tr,Sa({option:i.createElement(Hd,Sa({type:s},a)),isActive:n,shapeType:"symbols"},a)):i.createElement(Tr,Sa({option:s,isActive:n,shapeType:"symbols"},a))}function sa(t){"@babel/helpers - typeof";return sa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},sa(t)}function $a(){return $a=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},$a.apply(this,arguments)}function zr(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);
2s&&(a=a.filter(function(l){return Object.getOwnPropertyDescriptor(t,l).enumerable})),n.push.apply(n,a)}return n}function tt(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?zr(Object(n),!0).forEach(function(a){Yt(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):zr(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function Eu(t,s){if(!(t instanceof s))throw new TypeError("Cannot call a class as a function")}function Kr(t,s){for(var n=0;n<s.length;n++){var a=s[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(t,Io(a.key),a)}}function Fu(t,s,n){return s&&Kr(t.prototype,s),n&&Kr(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function Du(t,s,n){return s=$n(s),Ou(t,qo()?Reflect.construct(s,n||[],$n(t).constructor):s.apply(t,n))}function Ou(t,s){if(s&&(sa(s)==="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Lu(t)}function Lu(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function qo(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(qo=function(){return!!t})()}function $n(t){return $n=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},$n(t)}function Tu(t,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(s&&s.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),s&&Il(t,s)}function Il(t,s){return Il=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(a,l){return a.__proto__=l,a},Il(t,s)}function Yt(t,s,n){return s=Io(s),s in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function Io(t){var s=Bu(t,"string");return sa(s)=="symbol"?s:s+""}function Bu(t,s){if(sa(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,s);if(sa(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}var Xn=(function(t){function s(){var n;Eu(this,s);for(var a=arguments.length,l=new Array(a),r=0;r<a;r++)l[r]=arguments[r];return n=Du(this,s,[].concat(l)),Yt(n,"state",{isAnimationFinished:!1}),Yt(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0})}),Yt(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1})}),Yt(n,"id",$o("recharts-scatter-")),n}return Tu(s,t),Fu(s,[{key:"renderSymbolsStatically",value:function(a){var l=this,r=this.props,o=r.shape,p=r.activeShape,u=r.activeIndex,d=Bt(this.props,!1);return a.map(function(c,m){var h=u===m,b=h?p:o,f=tt(tt({}
2,d),c);return he.createElement(wt,$a({className:"recharts-scatter-symbol",key:"symbol-".concat(c==null?void 0:c.cx,"-").concat(c==null?void 0:c.cy,"-").concat(c==null?void 0:c.size,"-").concat(m)},Yd(l.props,c,m),{role:"img"}),he.createElement(Pu,$a({option:b,isActive:h,key:"symbol-".concat(m)},f)))})}},{key:"renderSymbolsWithAnimation",value:function(){var a=this,l=this.props,r=l.points,o=l.isAnimationActive,p=l.animationBegin,u=l.animationDuration,d=l.animationEasing,c=l.animationId,m=this.state.prevPoints;return he.createElement(So,{begin:p,duration:u,isActive:o,easing:d,from:{t:0},to:{t:1},key:"pie-".concat(c),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(h){var b=h.t,f=r.map(function(x,g){var y=m&&m[g];if(y){var $=Nt(y.cx,x.cx),O=Nt(y.cy,x.cy),A=Nt(y.size,x.size);return tt(tt({},x),{},{cx:$(b),cy:O(b),size:A(b)})}var S=Nt(0,x.size);return tt(tt({},x),{},{size:S(b)})});return he.createElement(wt,null,a.renderSymbolsStatically(f))})}},{key:"renderSymbols",value:function(){var a=this.props,l=a.points,r=a.isA
2nimationActive,o=this.state.prevPoints;return r&&l&&l.length&&(!o||!Bl(o,l))?this.renderSymbolsWithAnimation():this.renderSymbolsStatically(l)}},{key:"renderErrorBar",value:function(){var a=this.props.isAnimationActive;if(a&&!this.state.isAnimationFinished)return null;var l=this.props,r=l.points,o=l.xAxis,p=l.yAxis,u=l.children,d=Ao(u,Vd);return d?d.map(function(c,m){var h=c.props,b=h.direction,f=h.dataKey;return he.cloneElement(c,{key:"".concat(b,"-").concat(f,"-").concat(r[m]),data:r,xAxis:o,yAxis:p,layout:b==="x"?"vertical":"horizontal",dataPointFormatter:function(g,y){return{x:g.cx,y:g.cy,value:b==="x"?+g.node.x:+g.node.y,errorVal:Zs(g,y)}}})}):null}},{key:"renderLine",value:function(){var a=this.props,l=a.points,r=a.line,o=a.lineType,p=a.lineJointType,u=Bt(this.props,!1),d=Bt(r,!1),c,m;if(o==="joint")c=l.map(function(O){return{x:O.cx,y:O.cy}});else if(o==="fitting"){var h=Gd(l),b=h.xmin,f=h.xmax,x=h.a,g=h.b,y=function(A){return x*A+g};c=[{x:b,y:y(b)},{x:f,y:y(f)}]}var $=tt(tt(tt({},u),{},{fill:"none",stroke:u&&u.fill},d),{},{points:c});return he.isValidElement(r)?m=he.cloneElement(r,$):Nn(r)?m=r($):m=he.createElement(un,$a({},$,{type:p})),he.createElement(wt,{className:"recharts-scatter-line",key:"recharts-scatter-line"},m)}},{key:"render",value:function(){var a=this.props,l=a.hide,r=a.points,o=a.line,p=a.className,u=a.xAxis,d=a.yAxis,c=a.left,m=a.top,h=a.width,b=a.height,f=a.id,x=a.isAnimationActive;if(l||!r||!r.length)return null;var g=this.state.isAnimationFinished,y=ir("recharts-scatter",p),$=u&&u.allowDataOverflow,O=d&&d.allowDataOverflow,A=$||O,S=Ht(f)?this.id:f;return he.createElement(wt,{className:y,clipPath:A?"url(#clipPath-".concat(S,")"):null},$||O?he.createElement("defs",null,he.createElement("clipPath",{id:"clipPath-".concat(S)},he.createElement("rect",{x:$?c:c-h/2,y:O?m:m-b/2,width:$?h:h*2,height:O?b:b*2}))):null,o&&this.renderLine(),this.renderErrorBar(),he.createElement(wt,{key:"recharts-scatter-symbols"},this.renderSymbols()),(!x||g)&&Ta.renderCallByParent(this.props,r))}}],[{key:"getDerivedStateFromProps",value:function(a,l){return a.animationId!==l.prevAnimationId?{prevAnimationId:a.animationId,curPoints:a.points,prevPoints:l.curPoints}:a.points!==l.curPoints?{curPoints:a.points}:null}}])})(i.PureComponent);Yt(Xn,"displayName","Scatter");Yt(Xn,"defaultProps",{xAxisId:0,yAxisId:0,zAxisId:0,legendType:"circle",lineType:"joint",lineJointType:"linear",data:[],shape:"circle",hide:!1,isAnimationActive:!Co.isSsr,animationBegin:0,animationDuration:400,animationEasing:"linear"});Yt(Xn,"getComposedData",function(t){var s=t.xAxis,n=t.yAxis,a=t.zAxis,l=t.item,r=t.displayedData,o=t.xAxisTicks,p=t.yAxisTicks,u=t.offset,d=l.props.tooltipType,c=Ao(l.props.children,_s),m=Ht(s.dataKey)?l.props.dataKey:s.dataKey,h=Ht(n.dataKey)?l.props.dataKey:n.dataKey,b=a&&a.dataKey,f=a?a.range:Gn.defaultProps.range,x=f&&f[0],g=s.scale.bandwidth?s.scale.bandwidth():0,y=n.scale.bandwidth?n.scale.bandwidth():0,$=r.map(function(O,A){var S=Zs(O,m),P=Zs(O,h),E=!Ht(b)&&Zs(O,b)||"-",k=[{name:Ht(s.dataKey)?l.props.name:s.name||s.dataKey,unit:s.unit||"",value:S,payload:O,dataKey:m,type:d},{name:Ht(n.dataKey)?l.props.name:n.name||n.dataKey,unit:n.unit||"",value:P,payload:O,dataKey:h,type:d}];E!=="-"&&k.push({name:a.name||a.dataKey,unit:a.unit||"",value:E,payload:O,dataKey:b,type:d});var C=vn({axis:s,ticks:o,bandSize:g,entry:O,index:A,dataKey:m}),w=vn({axis:n,ticks:p,bandSize:y,entry:O,index:A,dataKey:h}),_=E!=="-"?a.scale(E):x,T=Math.sqrt(Math.max(_,0)/Math.PI);return tt(tt({},O),{},{cx:C,cy:w,x:C-T,y:w-T,xAxis:s,yAxis:n,zAxis:a,width:2*T,height:2*T,size:_,node:{x:S,y:P,z:E},tooltipPayload:k,tooltipPosition:{x:C,y:w},payload:O},c&&c[A]&&c[A].props)});return tt({points:$},u)});
2var zo=Xd({chartName:"ComposedChart",GraphicalChild:[yr,Ss,pt,Xn],axisComponents:[{axisType:"xAxis",AxisComp:Qt},{axisType:"yAxis",AxisComp:Ct},{axisType:"zAxis",AxisComp:Gn}],formatAxisMap:Zd});const rl=t=>Number(t)||0,Wr=t=>Math.round((t+Number.EPSILON)*100)/100,Ur=new Set(["approved","issued"]);function Ru(t){const s=rl(t==null?void 0:t.amount),n=rl(t==null?void 0:t.discount_amount),a=rl(t==null?void 0:t.credit_amount),l=Wr(n+a),r=(t==null?void 0:t.status)==="cancelled",o=r?0:Math.max(0,Wr(s-l)),p=!r&&l>0&&o<=.005;return{gross:s,discount:n,credit:a,relief:l,net:o,cancelled:r,nothingLeft:p}}function qu(t,{paid:s=!1,today:n="",labels:a={}}={}){const l=Ru(t),r=!l.cancelled&&s,o=Ur.has(t==null?void 0:t.status)&&!r&&!l.cancelled&&!l.nothingLeft,p=!!(o&&(t!=null&&t.due_date)&&String(t.due_date).slice(0,10)<n),u=l.cancelled?"בוטל":(t==null?void 0:t.status)==="credited"||l.nothingLeft?"זוכה":r?"שולם":p?"באיחור":Ur.has(t==null?void 0:t.status)?"לתשלום":a[t==null?void 0:t.status]||(t==null?void 0:t.status)||"";return{...l,paid:r,open:o,overdue:p,status:u}}function zt(t=[],s=[],{ready:n=!0}={}){if(!n||!(s!=null&&s.length))return t||[];const a=new Set(s.map(l=>l==null?void 0:l.id));return(t||[]).filter(l=>a.has(l==null?void 0:l.charge_type_id))}const Ko=i.createContext(null);function Iu({children:t}){const[s,n]=i.useState(null),a=i.useMemo(()=>({node:s,setNode:n}),[s]);return e.jsx(Ko.Provider,{value:a,children:typeof t=="function"?t(s):t})}function zu(t,s=[]){const n=i.useContext(Ko),a=n==null?void 0:n.setNode;i.useEffect(()=>{if(a)return a(()=>t),()=>a(null)},[a,...s])}const Hr={indigo:"bg-indigo-50 text-indigo-600",blue:"bg-blue-50 text-blue-600",sky:"bg-sky-50 text-sky-600",violet:"bg-violet-50 text-violet-600",purple:"bg-purple-50 text-purple-600",amber:"bg-amber-50 text-amber-600",emerald:"bg-emerald-50 text-emerald-600",rose:"bg-rose-50 text-rose-600",slate:"bg-slate-100 text-slate-600"},Ku={3:"grid-cols-2 sm:grid-cols-3",4:"grid-cols-2 sm:grid-cols-3 md:grid-cols-4",5:"grid-cols-2 sm:grid-cols-3 md:grid-cols-5"};function Wu({items:t=[],className:s="",columns:n,compact:a=!1}){const l=Vc(t);if(l.length===0)return null;const r=Ku[n]||"grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7";return e.jsx("div",{className:`grid gap-3 ${a?"":"sm:gap-4"} ${r} ${s}`,children:l.map((o,p)=>{const u=o.icon,d=Hr[o.tone]||Hr.indigo;return e.jsxs("button",{type:"button",onClick:o.onClick,disabled:o.disabled,className:`group relative flex flex-col items-center justify-start text-center
3              rounded-2xl bg-white border border-slate-200/80 shadow-sm
4              hover:shadow-md hover:border-slate-300 hover:-translate-y-0.5
5              focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400
6              disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0
7              transition-all ${a?"gap-2 px-3 py-4":"gap-4 px-4 py-8"}`,children:[o.badge?e.jsx("span",{className:"absolute top-3 left-3 min-w-[22px] h-[22px] px-1.5 rounded-full bg-red-500 text-white text-[11px] font-black grid place-items-center",children:o.badge}):null,e.jsx("span",{className:`rounded-2xl grid place-items-center flex-none ${d} ${a?"w-12 h-12":"w-20 h-20"}`,children:u?e.jsx(u,{className:a?"w-6 h-6":"w-9 h-9",strokeWidth:1.7}):null}),e.jsxs("span",{className:`min-w-0 flex flex-col items-center justify-start ${a?"min-h-[2.5rem]":"min-h-[3rem]"}`,children:[e.jsx("span",{className:`block font-black text-slate-900 leading-snug ${a?"text-[15px]":"text-[17px]"}`,children:o.label}),o.hint&&e.jsx("span",{className:`block text-slate-400 ${a?"text-[11px] mt-0.5":"text-[12px] mt-1"}`,children:o.hint})]})]},o.key||o.label||p)})})}const Yr=t=>String(t??"").replace(/\D/g,""),Cn=t=>String(t??"").trim().replace(/[״"׳']/g,"").replace(/\s+/g," ").toLowerCase();function Wo(t,{family:s,residents:n=[],properties:a=[]}={}){const l=[],r=(u,d,c)=>{const m=String(c??"").trim();m&&l.push({kind:u,label:d,value:m})};r("name","שם החשבון",t==null?void 0:t.name),r("name","שם משפחה",s==null?void 0:s.name),r("account","מספר חשבון",t==null?void 0:t.account_number),r("budget","מספר תקציב",(t==null?void 0:t.budget_number)??(t==null?void 0:t.budget)),r("id","מספר זהות",t==null?void 0:t.id_number);const o=[s==null?void 0:s.street,s==null?void 0:s.house_number].filter(
7Boolean).join(" ");r("address","כתובת",o),a.forEach(u=>r("address","כתובת נכס",u==null?void 0:u.address)),n.forEach(u=>{r("name","שם ברשומה",u==null?void 0:u.full_name),r("phone","טלפון",u==null?void 0:u.phone),r("budget","מספר תקציב",u==null?void 0:u.budget)});const p=new Set;return l.filter(u=>{const d=`${u.kind}|${Cn(u.value)}`;return p.has(d)?!1:(p.add(d),!0)})}function Uo(t,s){const n=Cn(s);if(!n)return 0;if(/^[\d\s-]+$/.test(String(s??"").trim())&&(t.kind==="phone"||t.kind==="budget"||t.kind==="account"||t.kind==="id")){const r=Yr(s),o=Yr(t.value);if(r&&o)return o===r?3:o.startsWith(r)?2:r.length>=4&&o.includes(r)?1:0}const l=Cn(t.value);return l?l===n?3:l.startsWith(n)||l.split(" ").some(r=>r.startsWith(n))?2:l.includes(n)?1:0:0}function Ho(t=[],s,{limit:n=12}={}){if(Cn(s).length<2)return[];const l=[];for(const r of t){const o=Wo(r.account,r);let p=0,u=null;for(const d of o){const c=Uo(d,s);if(c>p&&(p=c,u=d),p===3)break}p>0&&l.push({...r,score:p,why:u})}return l.sort((r,o)=>{var p,u;return o.score-r.score||String(((p=r.account)==null?void 0:p.name)||"").localeCompare(String(((u=o.account)==null?void 0:u.name)||""),"he")}).slice(0,n)}const Vr={name:["name"],account:["account"],budget:["budget"],phone:["phone"],address:["address"]};function Uu(t=[],s={},{limit:n=25}={}){const a=Object.entries(s).map(([r,o])=>[r,String(o??"").trim()]).filter(([r,o])=>o&&Vr[r]);if(!a.length)return[];const l=[];for(const r of t){const o=Wo(r.account,r);let p=0,u=null,d=!0;for(const[c,m]of a){const h=new Set(Vr[c]);let b=0,f=null;for(const x of o){if(!h.has(x.kind))continue;const g=Uo(x,m);g>b&&(b=g,f=x)}if(!b){d=!1;break}p+=b,u||(u=f)}d&&l.push({...r,score:p,why:u})}return l.sort((r,o)=>{var p,u;return o.score-r.score||String(((p=r.account)==null?void 0:p.name)||"").localeCompare(String(((u=o.account)==null?void 0:u.name)||""),"he")}).slice(0,n)}const il=t=>ve(t,"₪",{decimals:2}),zl="h-11 rounded-xl border border-slate-200 px-3 text-sm focus:outline-none focus:border-teal-400",pa=`${zl} w-full`;function Hu({kibbutzId:t,onClose:s,onDone:n}){const[a,l]=i.useState("who"),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState(null),[b,f]=i.useState(""),[x,g]=i.useState(null),[y,$]=i.useState(!1),[O,A]=i.useState({first:"",last:"",phone:"",email:""}),[S,P]=i.useState([{title:"",price:""}]),[E,k]=i.useState(!1),[C,w]=i.useState(null),[_,T]=i.useState(null);i.useEffect(()=>{let H=!0;return(async()=>{const[z,te,ie,V]=await Promise.all([D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me}).catch(()=>[]),D.functions.invoke("cardTerminal",{action:"status",community_id:t}).then(Y=>(Y==null?void 0:Y.data)||null).catch(()=>null)]);H&&(o(z||[]),u(te||[]),c(ie||[]),h((V==null?void 0:V.ready)??!1))})(),()=>{H=!1}},[t]),i.useEffect(()=>{const H=z=>{z.key==="Escape"&&a!=="card"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[s,a]);const M=i.useMemo(()=>{const H=new Map((d||[]).map(te=>[te.id,te])),z=new Map;return(p||[]).forEach(te=>{te.family_id&&(z.has(te.family_id)||z.set(te.family_id,[]),z.get(te.family_id).push(te))}),(r||[]).map(te=>({id:te.id,account:te,family:H.get(te.family_id)||null,residents:z.get(te.family_id)||[],properties:[]}))},[r,p,d]),B=i.useMemo(()=>{const H=b.trim();return H.length<2?[]:Ho(M,H,{limit:8}).map(z=>z.account)},[b,M]),R=i.useMemo(()=>S.reduce((H,z)=>H+(Number(z.price)||0),0),[S]),j=S.filter(H=>H.title.trim()&&Number(H.price)>0),q=(H,z,te)=>P(ie=>ie.map((V,Y)=>Y===H?{...V,[z]:te}:V)),L=()=>P(H=>[...H,{title:"",price:""}]),N=H=>P(z=>z.length===1?[{title:"",price:""}]:z.filter((te,ie)=>ie!==H)),v=()=>{const H=[O.first.trim(),O.last.trim()].filter(Boolean).join(" ");if(!H){W.error("יש להזין שם");return}g({id:null,name:H,phone:O.phone.trim(),email:O.email.trim(),_new:!0}),$(!1),l("what")},F=async()=>{if(!j.length){W.error("יש להזין לפחות שורת חיוב אחת");return}k(!0);try{const H=await D.functions.invoke("cardTerminal",{action:"start",community_id:t,payer_account_id:(x==null?void 0:x.id)||null,customer_name:(x==null?void 0:x.name)||null,customer_phone:(x==null?void 0:x.phone)||null,customer_email:(x==null?void 0:x.email)||null,lines:j.map(te=>({title:te.title.trim(),price:Number(te.price)}))}),z=(H==null?void 0:H.data)||H;if(!(z!=null&&z.checkout))throw new Error((z==null?void 0:z.error)||"פתיחת החיוב נכשלה");w(z),l("card")}catch(H){W.error((H==null?void 0:H.message)||"פתיחת החיוב נכשלה")}finally{k(!1)}},K=i.useCallback(H=>{T(H||{success:!0}),l("done"),n==null||n()},[n]),Z={who:"סליקת אשראי",what:"פרטי החיוב",card:"תשלום בכרטיס",done:"החיוב בוצע"}[a];return Pt.createPortal(e.jsxs("div",{dir:"rtl",className:"fixed inset-0 z-[80] grid place-items-center p-4",role:"dialog","aria-modal":"true","aria-label":"סליקת אשראי",children:[e.jsx("button",{type:"button","aria-label":"סגירה",onClick:()=>a!=="card"&&s(),className:"absolute inset-0 bg-slate-900/50 backdrop-blur-[2px] curs
7or-default"}),e.jsxs("div",{className:"relative w-full max-w-2xl h-[640px] max-h-[92vh] bg-white rounded-2xl border border-slate-200 shadow-2xl flex flex-col overflow-hidden",children:[e.jsxs("header",{className:"flex items-center gap-3 px-5 py-4 border-b border-slate-100 flex-none",children:[e.jsx("span",{className:"w-10 h-10 rounded-xl bg-rose-50 text-rose-600 grid place-items-center flex-none",children:e.jsx(Oe,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[17px] font-black text-slate-900",children:Z}),x&&a!=="who"&&e.jsxs("p",{className:"text-[12.5px] text-slate-500 truncate",children:[x.name,x.account_number?` · חשבון ${x.account_number}`:x._new?" · משלם חדש":""]})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"סגירה",disabled:a==="card"&&E,className:"mr-auto w-8 h-8 rounded-lg grid place-items-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 flex-none disabled:opacity-40",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="who"&&e.jsxs("div",{className:"space-y-3",children:[m===!1&&e.jsx("p",{className:"text-[12.5px] font-bold text-amber-700 bg-amber-50 border border-amber-200 rounded-xl px-3 py-2",children:"סליקת אשראי אינה מוגדרת לקהילה. יש להגדיר ספק תשלומים במסך «הגדרות מערכת»."}),e.jsxs("label",{className:"block relative",children:[e.jsx(qt,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"}),e.jsx("input",{value:b,onChange:H=>f(H.target.value),autoFocus:!0,placeholder:"חיפוש לפי שם, מספר חשבון או מספר תקציב",className:`${pa} pr-9`})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 overflow-hidden",children:[B.length===0&&e.jsx("p",{className:"text-[13px] text-slate-400 text-center py-8",children:b.trim()?"אין תוצאות":"חפשו חשבון משלם, או הוסיפו משלם חדש"}),B.map(H=>e.jsxs("button",{type:"button",onClick:()=>{g(H),l("what")},className:"w-full flex items-center gap-3 px-3 py-2.5 text-right hover:bg-slate-50 border-b border-slate-50 last:border-0",children:[e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-bold text-slate-800 truncate",children:H.name||`חשבון #${H.account_number}`}),e.jsx("span",{className:"block text-[12px] text-slate-400",children:[H.account_number&&`חשבון ${H.account_number}`,(H.budget_number||H.budget)&&`תקציב ${H.budget_number||H.budget}`].filter(Boolean).join(" · ")})]}),e.jsx(bs,{className:"w-4 h-4 text-slate-300 flex-none"})]},H.id))]}),y?e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50/70 p-4 space-y-3",children:[e.jsx("h4",{className:"text-[13px] font-black text-slate-800",children:"משלם חדש"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx("input",{className:pa,placeholder:"שם מלא",value:O.first,onChange:H=>A(z=>({...z,first:H.target.value}))}),e.jsx("input",{className:pa,placeholder:"שם משפחה",value:O.last,onChange:H=>A(z=>({...z,last:H.target.value}))}),e.jsx("input",{className:pa,placeholder:"טלפון",inputMode:"tel",value:O.phone,onChange:H=>A(z=>({...z,phone:H.target.value}))}),e.jsx("input",{className:pa,placeholder:"דוא״ל",inputMode:"email",value:O.email,onChange:H=>A(z=>({...z,email:H.target.value}))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:v,className:"h-10 px-4 rounded-xl bg-teal-600 text-white text-[13px] font-bold inline-flex items-center gap-1.5 hover:bg-teal-700",children:[e.jsx(ye,{className:"w-4 h-4"})," הוספה"]}),e.jsx("button",{type:"button",onClick:()=>$(!1),className:"h-10 px-4 rounded-xl border border-slate-200 text-[13px] font-bold text-slate-600",children:"ביטול"})]})]}):e.jsxs("button",{type:"button",onClick:()=>$(!0),className:`h-10 px-4 rounded-xl border border-slate-200 bg-white text-[13px] font-bold text-slate-700
8                    inline-flex items-center gap-2 hover:border-teal-300 hover:text-teal-700 transition-colors`,children:[e.jsx(so,{className:"w-4 h-4"})," משלם חדש"]})]}),a==="what"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50/70 p-4",children:[e.jsx("h4",{className:"text-[13px] font-black text-slate-800 mb-1",children:"פרטים"}),e.jsx("p",{className:"text-[14px] font-bold text-slate-900",children:x==null?void 0:x.name}),e.jsx("p",{className:"text-[12.5px] text-slate-500",children:[(x==null?void 0:x.account_number)&&`חשבון ${x.account_number}
8`,x==null?void 0:x.phone,x==null?void 0:x.email].filter(Boolean).join(" · ")||"ללא חשבון בספרים"}),e.jsx("button",{type:"button",onClick:()=>l("who"),className:"text-[12px] font-bold text-teal-700 hover:underline mt-1.5",children:"החלפת משלם"})]}),e.jsx("h4",{className:"text-[13px] font-black text-slate-800 pt-1",children:"שורות החיוב"}),S.map((H,z)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("input",{className:`${zl} flex-1 min-w-0`,placeholder:"כותרת החיוב",value:H.title,onChange:te=>q(z,"title",te.target.value)}),e.jsx("input",{className:`${zl} w-32 flex-none tabular-nums`,placeholder:"מחיר",inputMode:"decimal",type:"number",step:"0.01",min:"0",value:H.price,onChange:te=>q(z,"price",te.target.value)}),e.jsx("button",{type:"button",onClick:()=>N(z),"aria-label":"הסרת שורה",className:"w-11 h-11 rounded-xl border border-slate-200 grid place-items-center text-slate-400 hover:text-red-600 hover:border-red-200 flex-none",children:e.jsx(Re,{className:"w-4 h-4"})})]},z)),e.jsxs("button",{type:"button",onClick:L,className:`h-10 px-4 rounded-xl border border-slate-200 bg-white text-[13px] font-bold text-slate-700
9                  inline-flex items-center gap-2 hover:border-teal-300 hover:text-teal-700 transition-colors`,children:[e.jsx(We,{className:"w-4 h-4"})," שורה נוספת"]})]}),a==="card"&&C&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50/70 p-4",children:[e.jsx("p",{className:"text-[13px] text-slate-600",children:x==null?void 0:x.name}),e.jsx("ul",{className:"mt-2 space-y-1",children:j.map((H,z)=>e.jsxs("li",{className:"flex items-center justify-between text-[13px] text-slate-700",children:[e.jsx("span",{className:"truncate",children:H.title}),e.jsx("span",{className:"tabular-nums font-bold",dir:"ltr",children:il(Number(H.price))})]},z))})]}),e.jsx(Gc,{checkout:C.checkout,paymentReference:C.paymentReference,chargeFunction:"cardTerminal",onSuccess:K,onError:()=>{}})]}),a==="done"&&e.jsx("div",{className:"h-full grid place-items-center text-center",children:e.jsxs("div",{children:[e.jsx(la,{className:"w-16 h-16 text-emerald-500 mx-auto mb-3"}),e.jsx("h4",{className:"text-[19px] font-black text-slate-900",children:"החיוב בוצע"}),e.jsx("p",{className:"text-[26px] font-black text-emerald-700 tabular-nums mt-1",dir:"ltr",children:il(R)}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1",children:x==null?void 0:x.name}),(_==null?void 0:_.reference)&&e.jsxs("p",{className:"text-[12px] text-slate-400 mt-1",dir:"ltr",children:["אסמכתא ",_.reference]}),(_==null?void 0:_.needsReview)&&e.jsx("p",{className:"text-[12.5px] font-bold text-amber-700 bg-amber-50 border border-amber-200 rounded-xl px-3 py-2 mt-3",children:"החיוב נגבה, אך רישומו בספרים נכשל. יש לרשום אותו ידנית."})]})})]}),e.jsx("footer",{className:"flex-none border-t border-slate-100 bg-slate-50 px-5 py-3.5 flex items-center gap-3",children:a==="done"?e.jsx("button",{type:"button",onClick:s,className:"h-11 px-6 rounded-xl bg-teal-600 text-white text-[14px] font-bold mr-auto hover:bg-teal-700",children:"סגירה"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[13px] text-slate-500",children:"סה״כ לחיוב"}),e.jsx("span",{className:"text-[22px] font-black text-slate-900 tabular-nums",dir:"ltr",children:il(R)}),a==="what"&&e.jsxs("button",{type:"button",onClick:F,disabled:E||!j.length||m===!1,className:`h-11 px-6 rounded-xl bg-teal-600 text-white text-[14px] font-bold mr-auto
10                    inline-flex items-center gap-2 hover:bg-teal-700 disabled:opacity-50`,children:[E?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(bs,{className:"w-4 h-4"})," המשך"]}),a==="card"&&e.jsx("button",{type:"button",onClick:()=>{w(null),l("what")},className:"h-11 px-5 rounded-xl border border-slate-200 bg-white text-[13px] font-bold text-slate-600 mr-auto",children:"חזרה לפרטי החיוב"})]})})]})]}),document.body)}const Se="w-full h-12 rounded-xl border border-slate-300 bg-white px-4 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-colors",ua="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-50 transition-colors",ts="inline-flex items-center justify-center gap-2 h-12 px-7 rounded-xl bg-orange-500 hover:bg-orange-600 text-white text-sm font-bold transition-colors disabled:opacity-50",$s="inline-flex items-center justify-center gap-2 h-12 px-7 rounded-xl border border-slate-300 bg-white text-slate-600 text-sm font-semibold hover:bg-slate-50 transition-colors";function Q({label:t,required:s,info:n,hint:a,children:l,className:r=""}){return e.jsxs("div",{className:r,children:[t!=null&&t!==""&&e.jsxs("label",{className:"block mb-1.5 text-sm font-semibold text-slate-700 text-right",children:[e.jsx("span",{children:t}),s&&e.jsx("span",{className:"text-red-500",children:" *"}),n&&e.jsx(Un,{className:"inline-block w-4 h-4 text-blue-500 align-[-3px] mr-1",title:typeof n=="string"?n:void 0})]}),l,a&&e.jsx("p",{className:"text-[11px] text-slate-400 mt-1",children:a})]})}function Ra({title:t,icon:s,summary:n,action:a,children:l,open:r,onToggle:o,tone:p="indigo"}){const u={indigo:"bg-indigo-50 text-indigo-600",emerald:"bg-emerald-50 text-emerald-600",amber:"bg-amber-50 text-amber-600",
10sky:"bg-sky-50 text-sky-600"}[p];return e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3",children:[e.jsxs("button",{type:"button",onClick:o,"aria-expanded":r,className:"flex items-center gap-2.5 flex-1 min-w-0 text-right",children:[e.jsx("span",{className:`w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 ${u}`,children:e.jsx(s,{className:"w-5 h-5"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-base font-bold text-slate-900 truncate",children:t}),n&&e.jsx("span",{className:"block text-xs text-slate-400 truncate",children:n})]}),e.jsx(Jt,{className:`w-4 h-4 text-slate-400 flex-shrink-0 transition-transform ${r?"rotate-180":""}`})]}),a]}),r&&e.jsx("div",{className:"px-4 pb-4 pt-0 border-t border-slate-100",children:l})]})}const ns=Object.freeze({water_low_rate:8.508,water_high_rate:15.623,water_quota_per_soul:3.5,water_min_souls:2,water_eligible_addition:3.5,includes_vat:!0,vat_rate:18}),Yo=(t,s)=>{const n=Number(t);if(!Number.isFinite(n))return NaN;const a=String(n);return a.includes("e")||a.includes("E")?Math.round(n*10**s)/10**s:+`${Math.round(+`${a}e${s}`)}e${-s}`},ha=t=>Yo(t,2),Fs=t=>Yo(t,3),gt=t=>{if(t==null||t==="")return null;const s=Number(t);return Number.isFinite(s)?s:null},Tt=Object.freeze({ok:"ok",opening:"opening",no_meter:"no_meter",no_previous:"no_previous",regression:"regression",duplicate:"duplicate",invalid:"invalid"}),Pa=Object.freeze({ok:"הותאם בהצלחה",opening:"קריאת פתיחה",no_meter:"לא נמצא מונה",no_previous:"חסרה קריאה קודמת",regression:"קריאה נוכחית נמוכה מקודמת",duplicate:"רשומה כפולה בקובץ",invalid:"שגיאה בנתונים"});function Yu({consumption:t,souls:s,eligible:n,months:a,tariff:l}={}){const r=l||{},o=gt(r.water_low_rate),p=gt(r.water_high_rate),u=gt(r.water_quota_per_soul),d=gt(r.water_min_souls)??0,c=gt(r.water_eligible_addition)??0,m=r.includes_vat!==!1,h=gt(r.vat_rate)??0,b=gt(t);if(b===null||b<0)throw new Error("צריכה לא תקינה");if(o===null||p===null||u===null)throw new Error("סוג החיוב חסר תעריפי מים");const f=gt(a)??1,x=Math.max(gt(s)??0,d),g=Math.max(0,Math.round(gt(n)??0)),y=Fs(x*u*f),$=Fs(g*c*f),O=Fs(y+$),A=Fs(Math.min(b,O)),S=Fs(Math.max(b-O,0)),P=A*o,E=S*p,k=P+E,C=m?0:k*(h/100),w=ha(k+C);return{consumption:Fs(b),souls_used:x,eligible_used:g,months_used:f,quota_base:y,quota_eligible:$,quota_total:O,low_consumption:A,high_consumption:S,low_rate:o,high_rate:p,low_amount:ha(P),high_amount:ha(E),subtotal:ha(k),includes_vat:m,vat_rate:h,vat_amount:ha(C),amount:w}}function Vu(t,s){const n="".slice(0,10);return(t||[]).filter(a=>a.calculation_method!=="water_meter"||a.is_active===!1?!1:n?!(a.valid_from&&String(a.valid_from).slice(0,10)>n||a.valid_until&&String(a.valid_until).slice(0,10)<n):!0)}function Gu(t,s){if(!t||!s)return null;const n=new Date(`${String(t).slice(0,10)}T00:00:00Z`),a=new Date(`${String(s).slice(0,10)}T00:00:00Z`);if(Number.isNaN(n.getTime())||Number.isNaN(a.getTime())||a<=n)return null;const l=(a-n)/864e5;return Math.max(.5,Math.round(l/30.44*2)/2)}const yt=Se,Vo=t=>{if(!t)return"—";const[s,n,a]=String(t).slice(0,10).split("-");return a?`${a}/${n}/${s}`:t},mn=t=>t==null||t===""?"—":Number(t).toFixed(3).replace(/\.?0+$/,""),ol=t=>({meter_number:"",consumer_id:"",property_id:"",property_address:"",consumer_name:"",previous_reading:"",previous_reading_date:"",souls:t??"",eligible_count:"0",status:"active",notes:""});function Xu({kibbutzId:t,account:s,properties:n=[],familySouls:a,familyName:l,open:r,onToggle:o}){const[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState(!0),[b,f]=i.useState(!1),[x,g]=i.useState(null),[y,$]=i.useState(()=>ol(a)),[O,A]=i.useState(!1),[S,P]=i.useState(null),E=(j,q)=>$(L=>({...L,[j]:q})),k=i.useCallback(async()=>{h(!0);try{const[j,q]=await Promise.all([D.entities.WaterMeter.filter({kibbutz_id:t,payer_account_id:s.id},"-created_date",50).catch(()=>[]),D.entities.Charge.filter({kibbutz_id:t,payer_account_id:s.id},"-created_date",300).catch(()=>[])]);u(j||[]),c((q||[]).filter(L=>L.water_meter_id))}finally{h(!1)}},[t,s.id]);i.useEffect(()=>{k()},[k]);const C=i.useCallback(j=>d.filter(q=>
10q.water_meter_id===j),[d]),w=()=>{var j,q;g(null),$({...ol(a),consumer_name:l||"",property_id:((j=n[0])==null?void 0:j.id)||"",property_address:((q=n[0])==null?void 0:q.address)||""}),f(!0)},_=j=>{g(j),$({...ol(a),...j,previous_reading:j.previous_reading??"",previous_reading_date:j.previous_reading_date||"",souls:j.souls??"",eligible_count:j.eligible_count??0,property_id:j.property_id||""}),f(!0)},T=async()=>{if(!String(y.meter_number).trim()){W.error("יש להזין מספר מונה");return}A(!0);const j={kibbutz_id:t,payer_account_id:s.id,meter_number:String(y.meter_number).trim(),consumer_id:String(y.consumer_id||"").trim()||null,property_id:y.property_id||null,property_address:y.property_address||null,consumer_name:y.consumer_name||null,previous_reading:y.previous_reading===""?null:Number(y.previous_reading),previous_reading_date:y.previous_reading_date||null,souls:y.souls===""?null:Number(y.souls),eligible_count:y.eligible_count===""?0:Number(y.eligible_count),status:y.status,notes:y.notes||null};try{x?await D.entities.WaterMeter.update(x.id,j):await D.entities.WaterMeter.create(j),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:x?"water_meter_updated":"water_meter_created",entity_type:"water_meter",entity_id:(x==null?void 0:x.id)||null,payer_account_id:s.id,new_value:j.meter_number}).catch(()=>{}),W.success("המונה נשמר"),f(!1),k()}catch(q){W.error(String((q==null?void 0:q.message)||"").includes("unique")?"מספר המונה כבר קיים בקהילה":"שגיאה בשמירת המונה")}finally{A(!1)}},M=async j=>{const q=j.status==="active"?"inactive":"active";try{await D.entities.WaterMeter.update(j.id,{status:q}),W.success(q==="active"?"המונה הופעל":"המונה הושבת"),k()}catch{W.error("שגיאה")}},B=async j=>{if(C(j.id).length){W.error("למונה זה הופקו חשבונות — ניתן להשבית אותו בלבד");return}if(confirm(`למחוק את מונה ${j.meter_number}?`))try{await D.entities.WaterMeter.delete(j.id),W.success("המונה נמחק"),k()}catch{W.error("שגיאה")}},R=i.useMemo(()=>{if(m)return"טוען…";if(!p.length)return"לא הוגדרו מוני מים לחשבון זה";const j=p.filter(q=>q.status!=="inactive").length;return[p.map(q=>q.meter_number).filter(Boolean).join(" · "),j===p.length?"":_e(j,"אחד פעיל","פעילים")].filter(Boolean).join(" · ")},[p,m]);return e.jsx(Ra,{tone:"sky",icon:Ke,title:`מוני מים (${p.length})`,summary:R,open:r,onToggle:o,action:!b&&e.jsxs("button",{onClick:()=>{w(),r||o()},className:"h-8 px-3 rounded-full bg-sky-600 text-white text-xs inline-flex items-center gap-1 flex-shrink-0",children:[e.jsx(We,{className:"w-3.5 h-3.5"})," הוסף מונה"]}),children:e.jsx("div",{className:"billing-form pt-4",children:b?e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 mb-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(Q,{label:"מספר מונה",required:!0,children:e.jsx("input",{className:yt,placeholder:"הזן מספר מונה",value:y.meter_number,onChange:j=>E("meter_number",j.target.value)})}),e.jsx(Q,{label:"מס׳ זיהוי בתאגיד המים",info:"המספר שבו התאגיד מזהה את הצרכן — משמש להתאמה כשמספר המונה אינו תואם",children:e.jsx("input",{className:yt,placeholder:"הזן מס׳ זיהוי",value:y.consumer_id,onChange:j=>E("consumer_id",j.target.value)})}),e.jsx(Q,{label:"נכס משויך",children:e.jsxs("select",{className:yt,value:y.property_id,onChange:j=>{const q=n.find(L=>L.id===j.target.value);$(L=>({...L,property_id:j.target.value,property_address:(q==null?void 0:q.address)||L.property_address}))},children:[e.jsx("option",{value:"",children:"— ללא —"}),n.map(j=>e.jsx("option",{value:j.id,children:j.property_number||j.address},j.id))]})}),e.jsx(Q,{label:"כתובת הנכס",children:e.jsx("input",{className:yt,placeholder:"הזן כתובת",value:y.property_address||"",onChange:j=>E("property_address",j.target.value)})}),e.jsx(Q,{label:"שם צרכן",info:"כפי שהוא מופיע בקובץ התאגיד — לתצוגה בלבד, ההתאמה לעולם אינה לפי שם",children:e.jsx("input",{className:yt,placeholder:"הזן שם צרכן",value:y.consumer_name||"",onChange:j=>
10E("consumer_name",j.target.value)})}),e.jsx(Q,{label:"סטטוס",required:!0,children:e.jsxs("select",{className:yt,value:y.status,onChange:j=>E("status",j.target.value),children:[e.jsx("option",{value:"active",children:"פעיל"}),e.jsx("option",{value:"inactive",children:"לא פעיל"})]})}),e.jsx(Q,{label:"קריאה קודמת (מ״ק)",info:"הקריאה שממנה תחושב הצריכה בטעינה הבאה",children:e.jsx("input",{type:"number",step:"0.001",className:yt,placeholder:"הזן קריאה קודמת",value:y.previous_reading,onChange:j=>E("previous_reading",j.target.value)})}),e.jsx(Q,{label:"תאריך קריאה קודמת",children:e.jsx("input",{type:"date",className:yt,value:y.previous_reading_date||"",onChange:j=>E("previous_reading_date",j.target.value)})}),e.jsx(Q,{label:"נפשות לחישוב",info:"ברירת המחדל היא מספר הנפשות במשפחה, וניתן לשנות אותה — מכסת המים היא עניין של התאגיד ואינה תמיד זהה",children:e.jsx("input",{type:"number",step:"0.5",className:yt,placeholder:"הזן מספר נפשות",value:y.souls,onChange:j=>E("souls",j.target.value)})}),e.jsx(Q,{label:"מספר זכאים",info:"נפשות הזכאיות לתוספת מכסה חודשית",children:e.jsx("input",{type:"number",className:yt,placeholder:"0",value:y.eligible_count,onChange:j=>E("eligible_count",j.target.value)})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Q,{label:"הערות",children:e.jsx("textarea",{className:ua,rows:2,placeholder:"הערות (לא חובה)",value:y.notes||"",onChange:j=>E("notes",j.target.value)})})})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsxs("button",{onClick:T,disabled:O,className:ts,children:[e.jsx(ye,{className:"w-4 h-4"})," ",O?"שומר…":"שמור מונה"]}),e.jsx("button",{onClick:()=>f(!1),className:$s,children:"ביטול"})]})]}):p.length===0?e.jsx("p",{className:"text-sm text-slate-400 text-center py-4",children:"לא הוגדרו מוני מים לחשבון זה"}):e.jsx("div",{className:"space-y-2",children:p.map(j=>{const q=C(j.id),L=(S==null?void 0:S.meterId)===j.id;return e.jsxs("div",{className:"rounded-xl border border-slate-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-sm font-bold text-slate-800",children:["מונה ",j.meter_number]}),j.consumer_id&&e.jsxs("span",{className:"text-[11px] px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:["זיהוי ",j.consumer_id]}),j.status==="inactive"&&e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-full bg-red-50 text-red-600",children:"לא פעיל"})]}),e.jsx("div",{className:"text-xs text-slate-400 mt-0.5",children:[j.property_address,j.previous_reading!=null?`קריאה אחרונה ${mn(j.previous_reading)} (${Vo(j.previous_reading_date)})`:"אין קריאה קודמת",j.souls!=null?_e(Number(j.souls),"נפש אחת","נפשות"):"",j.eligible_count?_e(Number(j.eligible_count),"זכאי אחד","זכאים"):""].filter(Boolean).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{onClick:()=>P(L&&S.tab==="readings"?null:{meterId:j.id,tab:"readings"}),title:"היסטוריית קריאות",className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(Tl,{className:"w-4 h-4"})}),e.jsxs("button",{onClick:()=>P(L&&S.tab==="charges"?null:{meterId:j.id,tab:"charges"}),title:"חשבונות שהופקו",className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 relative",children:[e.jsx(nt,{className:"w-4 h-4"}),q.length>0&&e.jsx("span",{className:"absolute -top-0.5 -left-0.5 text-[9px] bg-sky-600 text-white rounded-full px-1",children:q.length})]}),e.jsx("button",{onClick:()=>_(j),title:"עריכה",className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>M(j),title:j.status==="active"?"השבת מונה":"הפעל מונה",className:`w-8 h-8 rounded-lg flex items-center justify-center hover:bg-slate-100 ${j.status==="active"?"text-amber-600":"text-emerald-600"}`,children:e.jsx(ho,{className:"w-4 h-4"})}),q.length===0&&e.jsx("button",{onClick:()=>B(j),title:"מחיקה",className:"w-8 h-8 rounded-lg flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})]})]}),L&&(S.tab==="readings"?e.jsx(Zu,{kibbutzId:t,meter:j}):e.jsx(Qu,{bills:q}))]},j.id)})})})})}function Zu({kibbutzId:t,meter:s}){const[n,a]=i.useState(null);return i.useEffect(()=>{let l=!0;return D.entities.WaterReading.filter({kibbutz_id:t,water_meter_id:s.id},"-created_date",60).then(r=>{l&&a(r||[])}).catch(()=>{l&&a([])}),()=>{l=!1}},[t,s.id]),n===null?e.jsx("p",{className:"text-xs text-slate-400 px-3 pb-3",children:"טוען קריאות…"}):n.length?e.jsx("div",{className:"border-t border-slate-100 px-3 py-2 overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"text-slate-400",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right font-medium py-1",children:"תאריך"}),e.jsx("th",{className:"text-right font-medium",children:"קודמת"}),e.jsx("th",{className:"text-right font-medium",children:"נוכחית"}),e.jsx("th",{className:"text-right font-medium",children:"צריכה"}),e.jsx("th",{className:"text-right font-medium",children:"סכום"}),e.jsx("th",{className:"text-right font-medium",children:"סטטוס"})]})}),e.jsx("tbody",{children:n.map(l=>e.jsxs("tr",{className:"border-t border-slate-50",children:[e.jsx("td",{className:"py-1.5 text-slate-500",children:l.read_at||Vo(l.created_date)}),e.jsx("td",{className:"tabular-nums",dir:"ltr",children:mn(l.previous_reading)}),e.jsx("td",{className:"tabular-nums",dir:"ltr",children:mn(l.current_reading)}),e.jsx("td",{className:"tabular-nums font-semibold",dir:"ltr",children:mn(l.consumption)}),e.jsx("td",{className:"tabular-nums",dir:"ltr",children:l.amount==null?"—":ve(l.amount)}),e.jsx("td",{className:"text-slate-500",children:Pa[l.status]||l.status})]},l.id))})]})}):e.jsx("p",{className:"text-xs text-slate-400 px-3 pb-3",children:"אין עדיין קריאות למונה זה"})}function Qu({bills:t}){const[s,n]=i.useState(null);return t.length?e.jsx("div",{className:"border-t border-slate-100 px-3 py-2 space-y-1.5",children:t.map(a=>{var l;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>n(s===a.id?null:a.id),className:"w-full flex items-center justify-between gap-2 text-xs py-1 text-right",children:[e.jsx("span",{className:"text-slate-600 truncate",children:a.description||a.billing_period}),e.jsx("span",{className:"font-bold tabular-nums flex-shrink-0",dir:"ltr",children:ve(a.amount)})]}),s===a.id&&((l=a.details)==null?void 0:l.breakdown)&&e.jsx(dr,{b:a.details.breakdown,compact:!0})]},a.id)})}):e.jsx("p",{className:"text-xs text-slate-400 px-3 pb-3",children:"לא הופקו חשבונות למונה זה"})}const Gr=()=>`apm-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;function Ju({kibbutzId:t,account:s}){const[n,a]=i.useState([]),[l,r]=i.useState([]),[o,p]=i.useState({}),[u,d]=i.useState([]),[c,m]=i.useState(!0),[h,b]=i.useState(null),[f,x]=i.useState(!1),g=i.useCallback(async()=>{m(!0);try{const[S,P,E]=await Promise.all([D.entities.ChargeType.filter({kibbutz_id:t,is_active:!0},"order",300).catch(()=>[]),D.entities.AccountPaymentMethod.filter({kibbutz_id:t,payer_account_id:s.id},"-created_date",50).catch(()=>[]),D.entities.ChargeTypePaymentMethod.filter({kibbutz_id:t,payer_account_id:s.id},"-created_date",200).catch(()=>[])]);a(S||[]),r((P||[]).filter(C=>C.is_active!==!1)),d(E||[]);const k={};
10for(const C of E||[])k[C.charge_type_id]=C.payment_method_id;p(k)}finally{m(!1)}},[t,s.id]);i.useEffect(()=>{g()},[g]);const y=i.useMemo(()=>new Map(l.map(S=>[S.id,S])),[l]),$=n.filter(S=>!o[S.id]).length,O=i.useMemo(()=>l.map(S=>({...S,in_use_for:n.filter(P=>o[P.id]===S.id).map(P=>P.name)})),[l,n,o]),A=async(S,P)=>{x(!0);try{let E=P.payment_method_id;E||(E=(await D.entities.AccountPaymentMethod.create({id:Gr(),kibbutz_id:t,payer_account_id:s.id,kind:P.kind,label:ed(P.label),last4:Jc(P.last4),is_active:!0,created_source:"manager"})).id);const k=u.find(C=>C.charge_type_id===S);k?await D.entities.ChargeTypePaymentMethod.update(k.id,{payment_method_id:E,updated_source:"manager"}):await D.entities.ChargeTypePaymentMethod.create({id:Gr().replace("apm-","ctm-"),kibbutz_id:t,payer_account_id:s.id,charge_type_id:S,payment_method_id:E,updated_source:"manager"}),W.success("אמצעי התשלום נשמר"),b(null),await g()}catch{W.error("שגיאה בשמירת אמצעי התשלום")}finally{x(!1)}};return c?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-400 py-4",children:[e.jsx(Ie,{className:"w-4 h-4 animate-spin"})," טוען אמצעי תשלום…"]}):n.length?e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50/60 p-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2 flex-wrap mb-3",children:[e.jsxs("h4",{className:"text-sm font-extrabold text-slate-800 inline-flex items-center gap-1.5",children:[e.jsx(Oe,{className:"w-4 h-4 text-slate-400"})," אמצעי תשלום לפי סוג חיוב"]}),$>0?e.jsx("span",{className:"text-[12px] font-bold text-red-600",children:$===1?"סוג חיוב אחד ללא אמצעי תשלום":`${$} סוגי חיוב ללא אמצעי תשלום`}):e.jsx("span",{className:"text-[12px] font-bold text-emerald-600",children:"לכל סוגי החיוב הוגדר אמצעי תשלום"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:n.map(S=>{const P=y.get(o[S.id]);return e.jsxs("button",{type:"button",onClick:()=>b(S),className:`flex items-center gap-2.5 p-3 rounded-xl border bg-white text-right transition-colors ${P?"border-slate-200 hover:border-slate-300":"border-red-200 hover:border-red-300"}`,children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800 truncate",children:S.name}),e.jsx("span",{className:`block text-[12px] mt-0.5 truncate ${P?"text-slate-500":"text-red-600 font-bold"}`,children:P?Zc(P):"אמצעי תשלום לא הוגדר"})]}),e.jsx(It,{className:"w-3.5 h-3.5 text-slate-400 flex-none"})]},S.id)})}),e.jsxs("p",{className:"text-[11.5px] text-slate-400 mt-3 flex items-start gap-1.5",children:[e.jsx(Un,{className:"w-3.5 h-3.5 flex-none mt-0.5"}),"מה שמוגדר כאן מוצג לתושב במרחב האישי תחת «התשלומים שלי», והוא יכול לשנות אותו בעצמו. לא נשמרים מספרי כרטיס או חשבון בנק."]}),h&&e.jsx(Qc,{title:`הגדרת אמצעי תשלום — ${h.name}`,subtitle:`${s.name||`חשבון #${s.account_number}`} · ניתן לבחור אמצעי תשלום שכבר הוגדר בחשבון או להוסיף חדש`,methods:O,value:o[h.id],busy:f,onClose:()=>b(null),onSave:S=>A(h.id,S)})]}):null}const Go=[{v:"personal_area",l:"אזור אישי"},{v:"email",l:'דוא"ל'},{v:"whatsapp",l:"WhatsApp"},{v:"push",l:"Push"},{v:"print",l:"הדפסה/מסירה"}],Ea=t=>String(t||"").split(",").map(s=>s.trim()).filter(Boolean),em=t=>Ea(t).map(s=>{var n;return((n=Go.find(a=>a.v===s))==null?void 0:n.l)||s}),Xr=[{v:"",l:"— לא הוגדר —"},{v:"standing_order",l:"הוראת קבע"},{v:"credit",l:"כרטיס אשראי"},{v:"bank_transfer",l:"העברה בנקאית"},{v:"cash",l:"מזומן"},{v:"check",l:"המחאה"}],Zr={active:"פעיל",inactive:"לא פעיל",frozen:"מוקפא"},Qr=["בית מגורים","יחידת דיור","עסק","מחסן","מבנה חקלאי","נכס נוסף"],Fa=t=>(t==null?void 0:t.full_name)||[t==null?void 0:t.first_name,t==null?void 0:t.last_name].filter(
10Boolean).join(" ")||"תושב",Pe=Se,Vt=t=>{if(t==null||t==="")return"";const s=Number(t);return Number.isFinite(s)?String(s):String(t).trim()};function tm({kibbutzId:t}){const[s,n]=i.useState(!0),[a,l]=i.useState([]),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState(""),[b,f]=i.useState("all"),[x,g]=i.useState(null),[y,$]=i.useState([]),[O,A]=i.useState({}),S=N=>A(v=>({...v,[N]:!v[N]})),P=i.useCallback(async()=>{n(!0);try{const[N,v,F,K,Z]=await Promise.all([D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name"),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me},"-created_date"),D.entities.PayerAccount.filterAll({kibbutz_id:t}),D.entities.Property.filterAll({kibbutz_id:t}),D.entities.KolboImportBatch.filter({kibbutz_id:t,status:"approved"}).catch(()=>[])]);l(N||[]),o(v||[]),u(F||[]),c(K||[]),$(Z||[])}catch{W.error("שגיאה בטעינת נתונים")}finally{n(!1)}},[t]);i.useEffect(()=>{P()},[P]);const E=i.useMemo(()=>Object.fromEntries(p.map(N=>[N.family_id,N])),[p]),k=i.useCallback(N=>{const v=r.filter(te=>te.family_id===N.id&&te.status!=="inactive"),F=v.find(te=>te.id===N.head_of_family_id)||v.find(te=>te.family_role==="head"),K=v.find(te=>te.family_role==="spouse"),Z=v.filter(te=>te.family_role==="child").map(te=>({...te,age:Xc(te.birth_date)})).sort((te,ie)=>(ie.age??-1)-(te.age??-1)),H=[N.street,N.house_number].filter(Boolean).join(" ")||[F==null?void 0:F.street,F==null?void 0:F.house_number].filter(Boolean).join(" "),z=Vt(F==null?void 0:F.budget)||v.map(te=>Vt(te.budget)).find(Boolean)||"";return{members:v,head:F,spouse:K,children:Z,address:H,budget:z}},[r]),C=i.useMemo(()=>{const N={};r.forEach(F=>{var K;F.family_id&&F.status!=="inactive"&&(N[K=F.family_id]||(N[K]=[])).push(F)});const v={};return a.forEach(F=>{const K=N[F.id]||[],Z=K.find(z=>z.id===F.head_of_family_id)||K.find(z=>z.family_role==="head"),H=Vt(Z==null?void 0:Z.budget)||K.map(z=>Vt(z.budget)).find(Boolean)||"";H&&(v[F.id]=H)}),v},[a,r]),w=i.useMemo(()=>{const N=new Map;return Object.values(C).forEach(v=>N.set(v,(N.get(v)||0)+1)),new Set([...N.entries()].filter(([,v])=>v>1).map(([v])=>v))},[C]),_=i.useMemo(()=>y.map(N=>N.id),[y]),T=i.useMemo(()=>{const N=new Set(r.filter(v=>v.status!=="inactive").map(v=>v.family_id));return a.filter(v=>N.has(v.id)||E[v.id]||C[v.id])},[a,r,E,C]),M=i.useMemo(()=>{let N=[...T];b==="account"?N=N.filter(F=>E[F.id]):b==="budget"?N=N.filter(F=>C[F.id]):b==="none"&&(N=N.filter(F=>!E[F.id]&&!C[F.id]));const v=m.trim().toLowerCase();return v&&(N=N.filter(F=>{var K;return(F.name||"").toLowerCase().includes(v)||[F.street,F.house_number].filter(Boolean).join(" ").toLowerCase().includes(v)||String(((K=E[F.id])==null?void 0:K.account_number)||"").includes(v)||(C[F.id]||"").includes(v)})),N.sort((F,K)=>String(F.name||"").localeCompare(String(K.name||""),"he"))},[T,b,m,E,C]),B=()=>{const N=p.map(v=>parseInt(String(v.account_number||"").replace(/\D/g,""),10)).filter(v=>!Number.isNaN(v));return String((N.length?Math.max(...N):1e3)+1)};async function R(N){var F;const v=k(N);try{const K=await D.entities.PayerAccount.create({kibbutz_id:t,family_id:N.id,primary_resident_id:((F=v.head)==null?void 0:F.id)||null,account_number:B(),name:N.name||Fa(v.head),status:"active",opening_balance:0,preferred_delivery_channel:"personal_area"});D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"account_created",entity_type:"payer_account",entity_id:K.id,payer_account_id:K.id,new_value:K.account_number}).catch(()=>{}),W.success("חשבון המשלם נפתח"),await P(),g(N.id)}catch{W.error("שגיאה בפתיחת חשבון")}}if(s)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})});const j=x?a.find(N=>N.id===x):null,q=j?E[j.id]:null,L=j?k(j):null;return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 items-start",children:[e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-4",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(qt,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx("input",{value:m,onChange:N=>h(N.target.value),placeholder:"חיפוש משפחה / חשבון / תקציב…",className:"w-full h-10 rounded-lg border border-slate-200 pr-9 pl-3 text-sm"})]}),e.jsx("div",{className:"grid grid-cols-4 gap-1 mb-2",children:[{k:"all",l:"הכל",n:T.length},{k:"account",l:"חשבון",n:T.filter(N=>E[N.id]).length},{k:"budget",l:"תקציב",n:T.filter(N=>C[N.id]).length},{k:"none",l:"ללא",n:T.filter(N=>!E[N.id]&&!C[N.id]).length}].map(N=>{const v=b===N.k;return e.jsxs("button",{onClick:()=>f(N.k),title:N.k==="none"?"ללא חשבון וללא מספר תקציב":void 0,className:`h-11 rounded-xl text-xs font-bold border transition-all flex flex-col items-center justify-center leading-none gap-0.5
11                  ${v?"bg-indigo-600 text-white border-transparent shadow-sm":"bg-white border-slate-200 text-slate-600 hover:border-slate-300"}`,children:[e.jsx("span",{children:N.l}),e.jsx("span",{className:`text-[10px] font-semibold ${v?"text-white/70":"text-slate-400"}`,children:N.n})]},N.k)})}),e.jsxs("div",{className:"space-y-1.5 max-h-[70vh] overflow-y-auto",children:[M.map(N=>{const v=E[N.id],F=x===N.id;return e.jsxs("button",{onClick:()=>g(N.id),className:`w-full text-right rounded-xl border px-3 py-2.5 transition-all ${F?"border-indigo-300 ring-2 ring-indigo-100":"border-slate-200 hover:bg-slate-50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-bold text-slate-800 truncate",children:N.name||"—"}),e.jsxs("span",{className:"flex items-center gap-1 flex-shrink-0",children:[C[N.id]&&e.jsxs("span",{className:`text-[11px] px-2 py-0.5 rounded-full inline-flex items-center gap-1
12                          ${w.has(C[N.id])?"bg-rose-50 text-rose-700 ring-1 ring-rose-200":"bg-amber-50 text-amber-700"}`,title:w.has(C[N.id])?"מספר התקציב הזה רשום גם במשפחה אחרת — קניות הכולבו שלו לא יוצגו לאיש":"מספר תקציב",children:[w.has(C[N.id])&&e.jsx(At,{className:"w-3 h-3"}),"תקציב ",C[N.id]]}),v?e.jsxs("span",{className:"text-[11px] px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700",children:["#",v.account_number]}):e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-full bg-slate-100 text-slate-500",children:"אין חשבון"})]})]}),e.jsx("span",{className:"text-xs text-slate-400 truncate block",children:[N.street,N.house_number].filter(
12Boolean).join(" ")})]},N.id)}),M.length===0&&e.jsx("p",{className:"text-sm text-slate-400 text-center py-6",children:"אין תוצאות"})]})]}),e.jsx("div",{className:"lg:col-span-2 space-y-4",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Ra,{tone:"indigo",icon:De,title:j.name,summary:[_e(L.members.length,"נפש אחת","נפשות"),L.head&&Fa(L.head),L.address].filter(Boolean).join(" · "),open:!!O.family,onToggle:()=>S("family"),action:e.jsxs("button",{onClick:()=>S("family"),className:"h-8 px-3 rounded-full bg-indigo-600 text-white text-xs inline-flex items-center gap-1 hover:bg-indigo-700 transition-colors flex-shrink-0",children:[e.jsx(fs,{className:"w-3.5 h-3.5"})," ",O.family?"הסתר פרטים":"הצג פרטים"]}),children:e.jsx(sm,{info:L})}),q?e.jsx(am,{kibbutzId:t,account:q,residents:L.members,budget:L.budget,onSaved:P,open:!!O.account,onToggle:()=>S("account")}):e.jsxs("div",{className:"bg-white rounded-2xl border border-dashed border-indigo-300 p-6 text-center",children:[e.jsx(es,{className:"w-9 h-9 text-indigo-400 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-slate-600 mb-3",children:"למשפחה זו אין עדיין חשבון משלם."}),e.jsxs("button",{onClick:()=>R(j),className:"inline-flex items-center gap-1.5 h-10 px-5 rounded-full bg-indigo-600 text-white text-sm font-bold",children:[e.jsx(We,{className:"w-4 h-4"})," פתח חשבון משלם"]})]}),q&&e.jsx(nm,{kibbutzId:t,account:q,properties:d.filter(N=>N.payer_account_id===q.id),onChanged:P,open:!!O.properties,onToggle:()=>S("properties")}),q&&e.jsx(Xu,{kibbutzId:t,account:q,properties:d.filter(N=>N.payer_account_id===q.id),familySouls:L.members.length,familyName:j.name,open:!!O.water,onToggle:()=>S("water")}),_.length>0&&L.budget&&e.jsx(lm,{kibbutzId:t,family:j,budget:L.budget,approvedBatchIds:_,open:!!O.kolbo,onToggle:()=>S("kolbo")})]}):e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-12 text-center text-sm text-slate-400",children:[e.jsx(De,{className:"w-10 h-10 text-slate-300 mx-auto mb-2"})," בחרו משפחה כדי לצפות בחשבון המשלם ולנהל נכסים"]})})]})}function Jr({label:t,person:s,icon:n}){return e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50/60 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(n,{className:"w-3.5 h-3.5 text-slate-400"}),e.jsx("span",{className:"text-[11px] font-bold text-slate-500",children:t})]}),s?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm font-bold text-slate-900 truncate mb-1.5",children:Fa(s)}),e.jsxs("p",{className:"flex items-center gap-1.5 text-[13px] text-slate-700 mb-0.5",children:[e.jsx(ao,{className:"w-3.5 h-3.5 text-slate-400 flex-shrink-0"}),s.phone?e.jsx("a",{href:`tel:${s.phone}`,className:"hover:underline",dir:"ltr",children:s.phone}):e.jsx("span",{className:"text-slate-400",children:"—"})]}),e.jsxs("p",{className:"flex items-center gap-1.5 text-[13px] text-slate-700 min-w-0",children:[e.jsx(no,{className:"w-3.5 h-3.5 text-slate-400 flex-shrink-0"}),s.email?e.jsx("a",{href:`mailto:${s.email}`,className:"hover:underline truncate",dir:"ltr",title:s.email,children:s.email}):e.jsx("span",{className:"text-slate-400",children:"—"})]}),Vt(s.budget)&&e.jsxs("p",{className:"mt-2 inline-flex items-center gap-1 text-[11px] font-bold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:[e.jsx(es,{className:"w-3 h-3"})," תקציב ",Vt(s.budget)]})]}):e.jsx("p",{className:"text-sm text-slate-400",children:"—"})]})}function sm({info:t}){return e.jsxs("div",{className:"pt-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 mb-3",children:[e.jsx(Jr,{label:"ראש משפחה",person:t.head,icon:ys}),e.jsx(Jr,{label:"בן/בת זוג",person:t.spouse,icon:ys})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm rounded-xl border border-slate-200 px-3 py-2.5 mb-3",children:[e.jsx(or,{className:"w-4 h-4 text-slate-400 flex-shrink-0"}),e.jsx("span",{className:"text-slate-500",children:"כתובת המשפחה"}),e.jsx("span",{className:"font-medium text-slate-900",children:t.address||"—"})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(fd,{className:"w-4 h-4 text-slate-400"}),e.jsxs("span",{className:"text-[11px] font-bold text-slate-500",children:["ילדים (",t.children.length,")"]})]}),e.jsxs("span",{className:"text-[11px] font-bold text-slate-500 bg-slate-100 rounded-full px-2.5 py-0.5 whitespace-nowrap",children:["סה״כ ",t.members.length," נפשות במשפחה"]})]}),t.children.length===0?e.jsx("p",{className:"text-sm text-slate-400",children:"אין ילדים רשומים במשפחה"}):e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.children.map(s=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-1",children:[e.jsx("span",{className:"font-medium text-slate-800",children:Fa(s)}),e.jsx("span",{className:"text-slate-400",children:s.age==null?"—":`גיל ${s.age}`})]},s.id))})]})]})}function am({kibbutzId:t,account:s,residents:n,budget:a="",onSaved:l,open:r,onToggle:o}){var x;const[p,u]=i.useState(!1),[d,c]=i.useState({...s}),[m,h]=i.useState(!1);i.useEffect(()=>{c({...s})},[s]);const b=(g,y)=>c($=>({...$,[g]:y})),f=async()=>{h(!0);try{await D.entities.PayerAccount.update(s.id,{account_number:d.account_number,name:d.name,id_number:d.id_number,status:d.status,opening_balance:Number(d.opening_balance)||0,preferred_delivery_channel:d.preferred_delivery_channel,payment_method:d.payment_method,primary_resident_id:d.primary_resident_id,notes:d.notes}),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"account_updated",entity_type:"payer_account",entity_id:s.id,payer_account_id:s.id}).catch(()=>{}),W.success("החשבון עודכן"),u(!1),l()}catch{W.error("שגיאה בשמירה")}finally{h(!1)}};return e.jsx(Ra,{tone:"emerald",icon:gd,title:`חשבון משלם #${s.account_number}`,summary:[a&&`תקציב ${a}
12`,Zr[s.status]||s.status,s.name].filter(Boolean).join(" · "),open:r,onToggle:o,action:p?e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsxs("button",{onClick:f,disabled:m,className:"h-8 px-3 rounded-full bg-emerald-600 text-white text-xs inline-flex items-center gap-1",children:[e.jsx(ye,{className:"w-3.5 h-3.5"})," שמור"]}),e.jsx("button",{onClick:()=>{u(!1),c({...s})},className:"h-8 w-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-3.5 h-3.5"})})]}):e.jsxs("button",{onClick:()=>{u(!0),r||o()},className:"h-8 px-3 rounded-full bg-emerald-600 text-white text-xs inline-flex items-center gap-1 hover:bg-emerald-700 transition-colors flex-shrink-0",children:[e.jsx(It,{className:"w-3.5 h-3.5"})," עריכה"]}),children:e.jsx("div",{className:"billing-form pt-4",children:p?e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(Q,{label:"מספר חשבון",required:!0,children:e.jsx("input",{className:Pe,placeholder:"הזן מספר חשבון",value:d.account_number||"",onChange:g=>b("account_number",g.target.value)})}),e.jsx(Q,{label:"שם המשלם הראשי",required:!0,children:e.jsx("input",{className:Pe,placeholder:"הזן שם משלם",value:d.name||"",onChange:g=>b("name",g.target.value)})}),e.jsx(Q,{label:'ת"ז / מזהה פנימי',children:e.jsx("input",{className:Pe,placeholder:'הזן ת"ז / מזהה',value:d.id_number||"",onChange:g=>b("id_number",g.target.value)})}),e.jsx(Q,{label:"משלם ראשי",children:e.jsxs("select",{className:Pe,value:d.primary_resident_id||"",onChange:g=>b("primary_resident_id",g.target.value),children:[e.jsx("option",{value:"",children:"—"}),n.map(g=>e.jsx("option",{value:g.id,children:Fa(g)},g.id))]})}),e.jsx(Q,{label:"סטטוס",required:!0,children:e.jsx("select",{className:Pe,value:d.status||"active",onChange:g=>b("status",g.target.value),children:Object.entries(Zr).map(([g,y])=>e.jsx("option",{value:g,children:y},g))})}),e.jsx(Q,{label:"יתרת פתיחה (₪)",children:e.jsx("input",{type:"number",className:Pe,placeholder:"0",value:d.opening_balance??0,onChange:g=>b("opening_balance",g.target.value)})}),e.jsx(Q,{label:"אמצעי קבלת חשבון",info:"הערוצים שבהם החשבון החודשי יישלח לתושב — אפשר לסמן כמה",children:e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Go.map(g=>{const y=Ea(d.preferred_delivery_channel).includes(g.v);return e.jsxs("button",{type:"button",onClick:()=>{const $=Ea(d.preferred_delivery_channel),O=y?$.filter(A=>A!==g.v):[...$,g.v];b("preferred_delivery_channel",O.join(","))},className:`h-9 px-3 rounded-lg border text-[13px] font-bold inline-flex items-center gap-1.5 transition-colors ${y?"bg-indigo-50 border-indigo-300 text-indigo-700":"bg-white border-slate-200 text-slate-500 hover:border-slate-300"}`,children:[e.jsx("span",{className:`w-3.5 h-3.5 rounded-[4px] border flex items-center justify-center ${y?"bg-indigo-600 border-indigo-600 text-white":"border-slate-300"}`,children:y&&e.jsx(ye,{className:"w-2.5 h-2.5"})}),g.l]},g.v)})})}),e.jsx(Q,{label:"אמצעי תשלום כברירת מחדל",hint:"משמש כשלא הוגדר אמצעי תשלום לסוג החיוב",children:e.jsx("select",{className:Pe,value:d.payment_method||"",onChange:g=>b("payment_method",g.target.value),children:Xr.map(g=>e.jsx("option",{value:g.v,children:g.l},g.v))})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Q,{label:"הערות",children:e.jsx("textarea",{className:ua,rows:2,placeholder:"הערות (לא חובה)",value:d.notes||"",onChange:g=>b("notes",g.target.value)})})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Ju,{kibbutzId:t,account:s})})]}):e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"שם המשלם"}),e.jsx("p",{className:"font-medium",children:s.name||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:'ת"ז / מזהה'}),e.jsx("p",{className:"font-medium",children:s.id_number||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"יתרת פתיחה"}),e.jsx("p",{className:"font-medium",children:ve(s.opening_balance)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"אמצעי קבלת חשבון"}),e.jsx("p",{className:"font-medium",children:em(s.preferred_delivery_channel).join(" · ")||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400",children:"אמצעי תשלום"}),e.jsx("p",{className:"font-medium",children:((x=Xr.find(g=>g.v===s.payment_method))==null?void 0:x.l)||"—"})]}),s.notes&&e.jsxs("div",{className:"col-span-full",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"הערות"}),e.jsx("p",{className:"font-medium",children:s.notes})]})]})})})}function nm({kibbutzId:t,account:s,properties:n,onChanged:a,open:l,onToggle:r}){const[o,p]=i.useState(!1),[u,d]=i.useState(null),c={property_number:"",property_type:Qr[0],address:"",gush_helka:"",size_sqm:"",built_sqm:"",extra_sqm:"",occupancy_count:"",active_from:"",active_until:"",status:"active",notes:""},[m,h]=i.useState(c),[b,f]=i.useState(!1),x=(A,S)=>h(P=>({...P,[A]:S})),g=()=>{d(null),h(c),p(!0)},y=A=>{d(A),h({...c,...A}),p(!0)},$=async()=>
12{if(!m.property_number&&!m.address){W.error("יש להזין מספר/כתובת נכס");return}f(!0);const A={kibbutz_id:t,payer_account_id:s.id,property_number:m.property_number,property_type:m.property_type,address:m.address,gush_helka:m.gush_helka,size_sqm:m.size_sqm===""?null:Number(m.size_sqm),built_sqm:m.built_sqm===""?null:Number(m.built_sqm),extra_sqm:m.extra_sqm===""?null:Number(m.extra_sqm),occupancy_count:m.occupancy_count===""?null:Number(m.occupancy_count),active_from:m.active_from||null,active_until:m.active_until||null,status:m.status,notes:m.notes};try{u?await D.entities.Property.update(u.id,A):await D.entities.Property.create(A),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:u?"property_updated":"property_created",entity_type:"property",entity_id:(u==null?void 0:u.id)||null,payer_account_id:s.id}).catch(()=>{}),W.success("הנכס נשמר"),p(!1),a()}catch{W.error("שגיאה בשמירת הנכס")}finally{f(!1)}},O=async A=>{if(confirm(`למחוק את הנכס "${A.property_number||A.address}"?`))try{await D.entities.Property.delete(A.id),W.success("הנכס נמחק"),a()}catch{W.error("שגיאה")}};return e.jsx(Ra,{tone:"amber",icon:ra,title:`נכסים (${n.length})`,summary:n.length?n.map(A=>A.property_number||A.address).filter(Boolean).join(" · "):"לא שויכו נכסים לחשבון זה",open:l,onToggle:r,action:!o&&e.jsxs("button",{onClick:()=>{g(),l||r()},className:"h-8 px-3 rounded-full bg-amber-600 text-white text-xs inline-flex items-center gap-1 flex-shrink-0",children:[e.jsx(We,{className:"w-3.5 h-3.5"})," הוסף נכס"]}),children:e.jsx("div",{className:"billing-form pt-4",children:o?e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 mb-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(Q,{label:"מספר/שם נכס",required:!0,children:e.jsx("input",{className:Pe,placeholder:"הזן מספר או שם נכס",value:m.property_number,onChange:A=>x("property_number",A.target.value)})}),e.jsx(Q,{label:"סוג נכס",required:!0,children:e.jsx("select",{className:Pe,value:m.property_type,onChange:A=>x("property_type",A.target.value),children:Qr.map(A=>e.jsx("option",{value:A,children:A},A))})}),e.jsx(Q,{label:"כתובת",required:!0,children:e.jsx("input",{className:Pe,placeholder:"הזן כתובת",value:m.address,onChange:A=>x("address",A.target.value)})}),e.jsx(Q,{label:"גוש/חלקה",required:!0,children:e.jsx("input",{className:Pe,placeholder:"הזן גוש/חלקה",value:m.gush_helka,onChange:A=>x("gush_helka",A.target.value)})}),e.jsx(Q,{label:"גודל (מ״ר)",required:!0,children:e.jsx("input",{type:"number",className:Pe,placeholder:'הזן גודל במ"ר',value:m.size_sqm,onChange:A=>x("size_sqm",A.target.value)})}),e.jsx(Q,{label:"שטח בנוי (מ״ר)",children:e.jsx("input",{type:"number",className:Pe,placeholder:'הזן שטח בנוי במ"ר',value:m.built_sqm,onChange:A=>x("built_sqm",A.target.value)})}),e.jsx(Q,{label:"שטח נוסף לחיוב",info:"שטח נוסף שמצטרף לחישוב החיוב לפי מ״ר",children:e.jsx("input",{type:"number",className:Pe,placeholder:"הזן שטח נוסף לחיוב",value:m.extra_sqm,onChange:A=>x("extra_sqm",A.target.value)})}),e.jsx(Q,{label:"נפשות משויכות",info:"מספר הנפשות המשמש בחיוב לפי נפש",children:e.jsx("input",{type:"number",className:Pe,placeholder:"הזן מספר נפשות",value:m.occupancy_count,onChange:A=>x("occupancy_count",A.target.value)})}),e.jsx(Q,{label:"סטטוס",required:!0,children:e.jsxs("select",{className:Pe,value:m.status,onChange:A=>x("status",A.target.value),children:[e.jsx("option",{value:"active",children:"פעיל"}),e.jsx("option",{value:"inactive",children:"לא פעיל"})]})}),e.jsx(Q,{label:"תאריך תחילת שיוך",children:e.jsx("input",{type:"date",className:Pe,value:m.active_from||"",onChange:A=>x("active_from",A.target.value)})}),e.jsx(Q,{label:"סיום שיוך",children:e.jsx("input",{type:"date",className:Pe,value:m.active_until||"",onChange:A=>x("active_until",A.target.value)})})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsxs("button",{onClick:$,disabled:b,className:ts,children:[e.jsx(ye,{className:"w-4 h-4"})," ",b?"שומר…":"שמור נכס"]}),e.jsx("button",{onClick:()=>p(!1),className:$s,children:"ביטול"})]})]}):n.length===0?e.jsx("p",{className:"text-sm text-slate-400 text-center py-4",children:"לא שויכו נכסים לחשבון זה"}):e.jsx("div",{className:"space-y-2",children:n.map(A=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-200 px-3 py-2.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-bold text-slate-800",children:A.property_number||A.address||"נכס"}),e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:A.property_type}),A.status==="inactive"&&e.jsx("span",{className:"text-[11px] text-red-500",children:"לא פעיל"})]}),e.jsx("div",{className:"text-xs text-slate-400 mt-0.5",children:[A.address,A.size_sqm!=null?`${A.size_sqm} מ״ר`:"",A.occupancy_count!=null?`${A.occupancy_count}
12 נפשות`:""].filter(Boolean).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{onClick:()=>y(A),className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>O(A),className:"w-8 h-8 rounded-lg flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})]})]},A.id))})})})}function lm({kibbutzId:t,family:s,budget:n,approvedBatchIds:a,open:l,onToggle:r}){const[o,p]=i.useState(null);i.useEffect(()=>{if(!l||o!==null||!(s!=null&&s.id)||!a.length)return;let m=!0;return D.entities.KolboPurchase.filterAll({kibbutz_id:t,family_id:s.id}).then(h=>{m&&p((h||[]).filter(b=>a.includes(b.batch_id)))}).catch(()=>{m&&p([])}),()=>{m=!1}},[l,o,t,s==null?void 0:s.id,a]);const u=i.useMemo(()=>{const m=new Map;return(o||[]).forEach(h=>{const b=String(h.txn_date||"").slice(0,7);if(!b)return;const f=m.get(b)||{month:b,total:0,receipts:new Set,lines:0};f.total+=Number(h.total)||0,f.receipts.add(`${h.txn_date}|${h.receipt}`),f.lines+=1,m.set(b,f)}),[...m.values()].map(h=>({...h,total:ka(h.total),visits:h.receipts.size})).sort((h,b)=>b.month.localeCompare(h.month))},[o]),d=td((o||[]).map(m=>({total:Number(m.total)||0}))),c=_n(o||[]).length;return e.jsx(Ra,{tone:"indigo",icon:da,title:"רכישות בכולבו",summary:o===null?`תקציב ${n} · לחצו לצפייה בדוח`:o.length?[_e(u.length,"חודש אחד","חודשים"),_e(c,"ביקור אחד","ביקורים"),ve(d)].join(" · "):"אין רכישות רשומות למשפחה זו",open:l,onToggle:r,children:e.jsx("div",{className:"pt-4",children:o===null?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx("div",{className:"w-6 h-6 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})}):o.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1.5",children:u.map(m=>e.jsx(rm,{month:m,rows:o||[]},m.month))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 mt-2 rounded-xl bg-slate-50 border border-slate-200",children:[e.jsxs("span",{className:"text-sm font-extrabold text-slate-700",children:["סה״כ רכישות · תקציב ",n]}),e.jsx("span",{className:"text-sm font-extrabold tabular-nums",dir:"ltr",children:ve(d)})]})]}):e.jsx("p",{className:"text-sm text-slate-400 text-center py-4",children:"אין רכישות רשומות למשפחה זו."})})})}function rm({month:t,rows:s}){const[n,a]=i.useState(!1),l=i.useMemo(()=>{if(!n)return[];const r=s.filter(o=>String(o.txn_date||"").slice(0,7)===t.month);return _n(r).map(o=>({...o,total:ka(o.total)})).sort((o,p)=>String(p.date).localeCompare(String(o.date))||String(p.receipt).localeCompare(String(o.receipt)))},[n,s,t.month]);return e.jsxs("div",{className:"rounded-xl border border-slate-200 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>a(r=>!r),className:"w-full flex items-center justify-between gap-3 px-3 py-2.5 text-right hover:bg-slate-50",children:[e.jsx("span",{className:"text-sm font-bold text-slate-800",children:om(t.month)}),e.jsxs("span",{className:"text-xs text-slate-400 flex-1",children:[_e(t.visits,"ביקור אחד","ביקורים")," · ",_e(t.lines,"שורה אחת","שורות")]}),e.jsx("span",{className:"text-sm font-extrabold text-slate-900 tabular-nums",dir:"ltr",children:ve(t.total)}),e.jsx(Jt,{className:`w-4 h-4 text-slate-400 flex-shrink-0 transition-transform ${n?"rotate-180":""}`})]}),n&&e.jsxs("div",{className:"border-t border-slate-100 divide-y divide-slate-50",children:[l.map(r=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2",children:[e.jsxs("span",{className:"text-[11px] font-extrabold px-2 py-1 rounded-lg bg-indigo-50 text-indigo-700 tabular-nums whitespace-nowrap",dir:"ltr",children:["אסמכתא ",r.receipt]}),e.jsxs("span",{className:"text-xs text-slate-500 flex-1 whitespace-nowrap",children:[im(r.date),Sr(r.receipt)?` · ${Sr(r.receipt)}`:""," · ",_e(r.lines.length,"פריט אחד","פריטים")]}),e.jsx("span",{className:"text-sm font-bold text-slate-800 tabular-nums",dir:"ltr",children:ve(r.total)})]},`${r.date}|${r.receipt}`)),l.length===0&&e.jsx("p",{className:"text-xs text-slate-400 px-3 py-2",children:"אין חשבוניות בחודש זה"})]})]})}const im=t=>{const[s,n,a]=String(t||"").slice(0,10).split("-");return a?`${a}/${n}/${String(s).slice(2)}`:t||""};function om(t){const s=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],[n,a]=String(t).split("-");return`${s[Number(a)-1]||a} ${n}`}const cm={א:"A",ב:"B",ג:"G",ד:"D",ה:"H",ו:"V",ז:"Z",ח:"H",ט:"T",י:"Y",כ:"K",ך:"K",ל:"L",מ:"M",ם:"M",נ:"N",ן:"N",ס:"S",ע:"A",פ:"P",ף:"P",צ:"TZ",ץ:"TZ",ק:"K",ר:"R",ש:"SH",ת:"T"},dm=(t,s,n)=>t==="ו"?s===0?"V":"O":t==="י"?s===0?"Y":"I":t==="ה"?s===n?"A":"H":cm[t],Xo=16;function um(t){return String(t||"").trim().split(/[\s\-_/]+/).filter(
12Boolean).map(a=>{const l=[...a];return l.map((r,o)=>{const p=dm(r,o,l.length-1);return p||(/[A-Za-z0-9]/.test(r)?r.toUpperCase():"")}).join("")}).filter(Boolean).join("_").slice(0,Xo).replace(/_+$/,"")}function mm(t,s=[],n=null){const a=um(t);if(!a)return"";const l=new Set((s||[]).filter(r=>!n||r.id!==n).map(r=>String((r==null?void 0:r.code)||"").trim().toUpperCase()).filter(Boolean));if(!l.has(a))return a;for(let r=2;r<100;r+=1){const o=`${a.slice(0,Xo-String(r).length)}${r}`;if(!l.has(o))return o}return a}const Da=[{v:"fixed",l:"סכום קבוע",hint:"סכום זהה לכל משלם"},{v:"per_sqm",l:"לפי מ״ר",hint:"תעריף × שטח הנכס"},{v:"per_person",l:"לפי נפש",hint:"תעריף × מספר נפשות"},{v:"per_property",l:"לפי נכס",hint:"תעריף × מספר נכסים"},{v:"tiered",l:"מדורג",hint:"מדרגות תעריף לפי כמות"},{v:"custom",l:"ידני",hint:"סכום נקבע ידנית לכל משלם"},{v:"water_meter",l:"צריכת מים לפי קריאת מונה",hint:"מכסה לנפש בתעריף נמוך, והשאר בתעריף גבוה"}],Je=t=>t==="water_meter",Oa=t=>{var s;return((s=Da.find(n=>n.v===t))==null?void 0:s.l)||t||"—"},Zo=[{v:"monthly",l:"חודשי"},{v:"bimonthly",l:"דו-חודשי"},{v:"quarterly",l:"רבעוני"},{v:"yearly",l:"שנתי"},{v:"one_time",l:"חד-פעמי"},{v:"per_file",l:"לפי טעינת קובץ"}],ei=t=>{var s;return((s=Zo.find(n=>n.v===t))==null?void 0:s.l)||"חודשי"},it=Se,Ya=()=>({name:"",code:"",description:"",calculation_method:"fixed",rate:"",includes_vat:!0,sumit_budget_item_id:null,billing_cycle:"monthly",due_day:"",issue_days_before:"",valid_from:"",valid_until:"",is_active:!0,show_in_personal_area:!0,online_payable:!1,requires_approval:!1,water_low_rate:"",water_high_rate:"",water_quota_per_soul:"",water_min_souls:"",water_eligible_addition:"",vat_rate:""}),ti=()=>({water_low_rate:String(ns.water_low_rate),water_high_rate:String(ns.water_high_rate),water_quota_per_soul:String(ns.water_quota_per_soul),water_min_souls:String(ns.water_min_souls),water_eligible_addition:String(ns.water_eligible_addition),vat_rate:String(ns.vat_rate),includes_vat:ns.includes_vat,billing_cycle:"per_file"}),et=t=>t===""||t===null||t===void 0?null:Number(t),Ys=t=>t==null||t===""?"—":`${Number(t).toFixed(3).replace(/\.?0+$/,"")} ₪`;function xm({kibbutzId:t,onManage:s}){var R;const[,n]=ia(),a=()=>s?s():n({tab:"monthly"},{replace:!0}),[l,r]=i.useState(!0),[o,p]=i.useState([]),[u,d]=i.useState(null),[c,m]=i.useState(!1),[h,b]=i.useState(null),[f,x]=i.useState(Ya()),[g,y]=i.useState(!1),$=(j,q)=>x(L=>({...L,[j]:q})),O=i.useCallback(async()=>{var j;r(!0);try{const[q,L]=await Promise.all([D.entities.ChargeType.filter({kibbutz_id:t},"order",300),D.entities.BillingSettings.filter({kibbutz_id:t},"-created_date",1).catch(()=>[])]);p(q||[]);const N=Number((j=L==null?void 0:L[0])==null?void 0:j.default_due_day);d(Number.isFinite(N)&&N>0?N:null)}catch{W.error("שגיאה בטעינת סוגי חיובים")}finally{r(!1)}},[t]);i.useEffect(()=>{O()},[O]);const A=()=>{b(null),x(Ya()),m(!0)},S=j=>x(q=>({...q,name:j,code:q.code_touched?q.code:mm(j,o,(h==null?void 0:h.id)||null)})),P=()=>{b(null),x({...Ya(),name:"מים",code:"WATER",code_touched:!0,calculation_method:"water_meter",...ti()}),m(!0)},E=j=>{const q=L=>L==null?"":String(L);b(j),x({...Ya(),...j,code_touched:!0,rate:j.rate??"",due_day:j.due_day??"",issue_days_before:j.issue_days_before??"",valid_from:j.valid_from||"",valid_until:j.valid_until||"",water_low_rate:q(j.water_low_rate),water_high_rate:q(j.water_high_rate),water_quota_per_soul:q(j.water_quota_per_soul),water_min_souls:q(j.water_min_souls),water_eligible_addition:q(j.water_eligible_addition),vat_rate:q(j.vat_rate)}),m(!0)},k=j=>x(q=>({...q,calculation_method:j,...Je(j)&&q.water_low_rate===""?ti():{}})),C=async()=>{if(!f.name.trim()){W.error("יש להזין שם סוג חיוב");return}if(Je(f.calculation_method)&&["water_low_rate","water_high_rate","water_quota_per_soul"].filter(L=>f[L]===""||f[L]===null).length){W.error("יש להזין מחיר נמוך, מחיר גבוה ומכסה לנפש");return}y(!0);const j={kibbutz_id:t,name:f.name.trim(),code:f.code.trim()||null,description:f.description||null,sumit_budget_item_id:f.sumit_budget_item_id||null,calculation_method:f.calculation_method,rate:f.rate===""?0:Number(f.rate),includes_vat:!!f.includes_vat,water_low_rate:Je(f.calculation_method)?et(f.water_low_rate):null,water_high_rate:Je(f.calculation_method)?et(f.water_high_rate):null,water_quota_per_soul:Je(f.calculation_method)?et(f.water_quota_per_soul):null,water_min_souls:Je(f.calculation_method)?et(f.water_min_souls):null,water_eligible_addition:Je(f.calculation_method)?et(f.water_eligible_addition):null,vat_rate:Je(f.calculation_method)?et(f.vat_rate):null,billing_cycle:f.billing_cycle,due_day:f.due_day===""||f.due_day===null?null:Math.min(31,Math.max(1,Number(f.due_day))),issue_days_before:f.issue_days_before===""||f.issue_days_before===null?null:Math.min(60,Math.max(0,Number(f.issue_days_before))),valid_from:f.valid_from||null,valid_until:f.valid_until||null,is_active:!!f.is_active,show_in_personal_area:!!f.show_in_personal_area,online_payable:!!f.online_payable,requires_approval:!!f.requires_approval,order:h?h.order:o.length};try{h?await D.entities.ChargeType.update(h.id,j):await D.entities.ChargeType.create(j),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:h?"charge_type_updated":"charge_type_created",entity_type:"charge_type",entity_id:(h==null?void 0:h.id)||null,new_value:f.name}).catch(()=>{}),W.success("סוג החיוב נשמר"),m(!1),O()}catch{W.error("שגיאה בשמירה")}finally{y(!1)}},w=async j=>{if(confirm(`למחוק את סוג החיוב "${j.name}"? חיובים קיימים לא יימחקו.`))try{await D.entities.ChargeType.delete(j.id),W.success("נמחק"),O()}catch{W.error("שגיאה")}},_=async j=>{try{await D.entities.ChargeType.update(j.id,{is_active:!j.is_active}),O()}catch{W.error("שגיאה")}},T=Je(f.calculation_method),M=i.useMemo(()=>
12{if(!T)return null;try{return Yu({consumption:40,souls:4,eligible:1,months:2,tariff:{water_low_rate:et(f.water_low_rate),water_high_rate:et(f.water_high_rate),water_quota_per_soul:et(f.water_quota_per_soul),water_min_souls:et(f.water_min_souls),water_eligible_addition:et(f.water_eligible_addition),includes_vat:!!f.includes_vat,vat_rate:et(f.vat_rate)}})}catch{return null}},[T,f.water_low_rate,f.water_high_rate,f.water_quota_per_soul,f.water_min_souls,f.water_eligible_addition,f.includes_vat,f.vat_rate]);if(l)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})});const B=({label:j,k:q,icon:L})=>e.jsxs("button",{type:"button",onClick:()=>$(q,!f[q]),className:`flex items-center gap-2 h-10 px-3 rounded-lg border text-sm transition-all ${f[q]?"border-indigo-300 bg-indigo-50 text-indigo-700":"border-slate-200 text-slate-500"}`,children:[L&&e.jsx(L,{className:"w-4 h-4"})," ",e.jsx("span",{className:"flex-1 text-right",children:j}),e.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center ${f[q]?"bg-indigo-600":"bg-slate-200"}`,children:f[q]&&e.jsx(ye,{className:"w-3 h-3 text-white"})})]});return e.jsxs("div",{children:[!c&&e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 mb-4 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("p",{className:"text-[14.5px] font-black text-slate-800",children:["להפעלת חיובים אוטומטית או ידנית גש"," ",e.jsx("button",{type:"button",onClick:a,className:"text-emerald-700 underline decoration-2 decoration-emerald-300 underline-offset-4 hover:text-emerald-800 hover:decoration-emerald-500 transition-colors",children:"לניהול חיובים"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!o.some(j=>Je(j.calculation_method))&&e.jsxs("button",{onClick:P,className:"h-9 px-4 rounded-full bg-sky-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(Ke,{className:"w-4 h-4"})," סוג חיוב מים"]}),e.jsxs("button",{onClick:A,className:"h-9 px-4 rounded-full bg-indigo-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(We,{className:"w-4 h-4"})," סוג חיוב חדש"]})]})]}),c&&e.jsxs("div",{className:"bg-white rounded-2xl border border-indigo-200 shadow-sm p-5 mb-5 billing-form",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-base font-bold",children:h?"עריכת סוג חיוב":"סוג חיוב חדש"}),e.jsx("button",{onClick:()=>m(!1),className:"w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-slate-50/60 p-4",children:[e.jsx("h4",{className:"text-[13px] font-black text-slate-800 mb-3",children:"פרטי סוג החיוב"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsx(Q,{label:"שם סוג החיוב",required:!0,children:e.jsx("input",{className:it,value:f.name,onChange:j=>S(j.target.value),placeholder:"ארנונה / ועד / שמירה…"})}),e.jsx(Q,{label:"קוד / מזהה",hint:f.code_touched?void 0:"נכתב מהשם; אפשר לשנות",children:e.jsx("input",{className:it,value:f.code,placeholder:"נכתב מהשם",onChange:j=>x(q=>({...q,code:j.target.value.toUpperCase(),code_touched:!0}))})}),e.jsx(Q,{label:"מחזור חיוב",required:!0,children:e.jsx("select",{className:it,value:f.billing_cycle,onChange:j=>$("billing_cycle",j.target.value),children:Zo.map(j=>e.jsx("option",{value:j.v,children:j.l},j.v))})}),e.jsx(yd,{communityId:t,value:f.sumit_budget_item_id,onChange:j=>$("sumit_budget_item_id",j),hint:"הסעיף שאליו ייזקפו החיובים מסוג זה"}),e.jsx("div",{className:"sm:col-span-2 lg:col-span-3",children:e.jsx(Q,{label:"תיאור",children:e.jsx("textarea",{className:ua,rows:2,placeholder:"תיאור סוג החיוב (לא חובה)",value:f.description,onChange:j=>$("description",j.target.value)})})})]})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4 mt-3",children:[e.jsx("h4",{className:"text-[13px] font-black text-slate-800 mb-3",children:"הגדרות חישוב"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsx(Q,{label:"שיטת חישוב",required:!0,info:"קובעת כיצד מחושב הסכום לכל משלם",children:e.jsx("select",{className:it,value:f.calculation_method,onChange:j=>k(j.target.value),children:Da.map(j=>e.jsx("option",{value:j.v,children:j.l},j.v))})}),T?e.jsxs("div",{className:"sm:col-span-2 lg:col-span-3 rounded-xl border border-sky-200 bg-sky-50/50 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ke,{className:"w-4 h-4 text-sky-600"}),e.jsx("h4",{className:"text-sm font-extrabold text-slate-800",children:"תעריפי המים והנוסחה"})]}),e.jsxs("p",{className:"text-[12px] text-slate-600 leading-relaxed mb-3",children:["מכסה מוכרת = (נפשות × מכסה לנפש + זכאים × תוספת לזכאי) × מספר חודשי החיוב.",e.jsx("br",{}),"חיוב = MIN(צריכה, מכסה) × מחיר נמוך + MAX(צריכה − מכסה, 0) × מחיר גבוה",f.includes_vat?" (המחירים כוללים מע״מ).":", ובתוספת מע״מ."]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsx(Q,{label:"מחיר למ״ק — תעריף נמוך (₪)",required:!0,info:"המחיר בתוך המכסה המוכרת",children:e.jsx("input",{type:"number",step:"0.001",className:it,value:f.water_low_rate,onChange:j=>$("water_low_rate",j.target.value),placeholder:"8.508"})}),e.jsx(Q,{label:"מחיר למ״ק — תעריף גבוה (₪)",required:!0,info:"המחיר לכל מ״ק מעבר למכסה",children:e.jsx("input",{type:"number",step:"0.001",className:it,value:f.water_high_rate,onChange:j=>$("water_high_rate",j.target.value),placeholder:"15.623"})}),e.jsx(Q,{label:"מכסה חודשית לנפש (מ״ק)",required:!0,children:e.jsx("input",{type:"number",step:"0.001",className:it,value:f.water_quota_per_soul,onChange:j=>$("water_quota_per_soul",j.target.value),placeholder:"3.5"})}),e.jsx(Q,{label:"מינימום נפשות לחישוב",info:"משק בית קטן יותר יחושב לפי מספר זה",children:e.jsx("input",{type:"number",step:"0.5",className:it,value:f.water_min_souls,onChange:j=>$("water_min_souls",j.target.value),placeholder:"2"})}),e.jsx(Q,{label:"תוספת חודשית לנפש זכאית (מ״ק)",children:e.jsx("input",{type:"number",step:"0.001",className:it,value:f.water_eligible_addition,onChange:j=>$("water_eligible_addition",j.target.value),placeholder:"3.5"})}),e.jsx(Q,{label:"אחוז מע״מ",info:"נוסף לחשבון רק כאשר המחירים אינם כוללים מע״מ",children:e.jsx("input",{type:"number",step:"0.1",className:`${it} disabled:bg-slate-50 disabled:text-slate-400`,value:f.vat_rate,onChange:j=>$("vat_rate",j.target.value),placeholder:"18",disabled:!!f.includes_vat})})]}),M&&e.jsxs("div",{className:"mt-3 rounded-lg bg-white border border-sky-200 px-3 py-2 text-[12px] text-slate-600 leading-relaxed",children:[e.jsx("span",{className:"font-bold text-slate-800",children:"בדיקה מהירה:"})," משפחה בת 4 נפשות, זכאי אחד, חודשיים, ",M.consumption," מ״ק →"," ","מכסה ",M.quota_total," מ״ק · ",M.low_consumption," × ",M.low_rate," = ",M.low_amount.toFixed(2)," ₪",M.high_consumption>0&&e.jsxs(e.Fragment,{children:[" · ",M.high_consumption," × ",M.high_rate," = ",M.high_amount.toFixed(2)," ₪"]}
12)," ","· ",e.jsxs("span",{className:"font-extrabold text-slate-900",children:["סה״כ ",M.amount.toFixed(2)," ₪"]})]})]}):e.jsx(e.Fragment,{children:e.jsx(Q,{label:f.calculation_method==="per_sqm"?"תעריף למ״ר (₪)":f.calculation_method==="per_person"?"תעריף לנפש (₪)":f.calculation_method==="per_property"?"תעריף לנכס (₪)":"תעריף / סכום (₪)",required:f.calculation_method!=="custom",hint:(R=Da.find(j=>j.v===f.calculation_method))==null?void 0:R.hint,children:e.jsx("input",{type:"number",className:it,value:f.rate,onChange:j=>$("rate",j.target.value),disabled:f.calculation_method==="custom",placeholder:f.calculation_method==="custom"?"נקבע ידנית":"0"})})})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-2 mt-4",children:[e.jsx(B,{label:"פעיל",k:"is_active",icon:ye}),e.jsx(B,{label:"כולל מע״מ",k:"includes_vat",icon:mr}),e.jsx(B,{label:"מוצג באזור אישי",k:"show_in_personal_area",icon:fs}),e.jsx(B,{label:"דורש אישור",k:"requires_approval",icon:xt})]})]}),e.jsxs("p",{className:"text-[11.5px] text-slate-400 mt-3 flex items-start gap-1.5",children:[e.jsx(Be,{className:"w-3.5 h-3.5 flex-none mt-0.5"}),"מועד ההפקה ומועד החיוב נקבעים בהפעלת סוג החיוב, במסך «ניהול חיובים»."]}),e.jsxs("div",{className:"flex items-center gap-3 mt-5",children:[e.jsxs("button",{onClick:C,disabled:g,className:ts,children:[e.jsx(ye,{className:"w-4 h-4"})," ",g?"שומר…":"שמור סוג חיוב"]}),e.jsx("button",{onClick:()=>m(!1),className:$s,children:"ביטול"})]})]}),c?null:o.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-10 text-center",children:[e.jsx(Xe,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsx("h3",{className:"text-base font-semibold mb-1",children:"אין עדיין סוגי חיובים"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"הגדירו סוג חיוב ראשון (ארנונה, ועד, שמירה, מים…) כדי להתחיל להפיק חיובים."}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsxs("button",{onClick:P,className:"h-9 px-4 rounded-full bg-sky-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(Ke,{className:"w-4 h-4"})," סוג חיוב מים"]}),e.jsxs("button",{onClick:A,className:"h-9 px-4 rounded-full bg-indigo-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(We,{className:"w-4 h-4"})," סוג חיוב חדש"]})]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:o.map(j=>e.jsxs("div",{className:`bg-white rounded-2xl border shadow-sm p-4 ${j.is_active?"border-border":"border-slate-200 opacity-70"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"w-9 h-9 rounded-lg bg-indigo-50 flex items-center justify-center flex-shrink-0",children:e.jsx(Xe,{className:"w-5 h-5 text-indigo-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-sm font-bold truncate",children:j.name}),e.jsx("p",{className:"text-xs text-slate-400",children:j.code||ei(j.billing_cycle)})]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx("button",{onClick:()=>_(j),title:j.is_active?"השבת":"הפעל",className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-400 hover:bg-slate-100",children:j.is_active?e.jsx(fs,{className:"w-4 h-4"}):e.jsx(_d,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>E(j),className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>w(j),className:"w-8 h-8 rounded-lg flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-[11px]",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:Oa(j.calculation_method)}),Je(j.calculation_method)?e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-sky-50 text-sky-700 font-semibold",dir:"ltr",children:[Ys(j.water_low_rate)," / ",Ys(j.water_high_rate)," למ״ק"]}):j.calculation_method!=="custom"&&e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-blue-50 text-blue-700 font-semibold",children:ve(j.rate)}),Je(j.calculation_method)&&j.water_quota_per_soul!=null&&e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:[j.water_quota_per_soul," מ״ק לנפש לחודש"]}),e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:ei(j.billing_cycle)}),j.auto_billing_enabled&&e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-emerald-600 text-white font-bold inline-flex items-center gap-1",children:[e.jsx(Mt,{className:"w-3 h-3"})," הפקה אוטומטית"]}),j.due_day?e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-indigo-50 text-indigo-700 font-bold inline-flex items-center gap-1",children:[e.jsx(Be,{className:"w-3 h-3"})," לתשלום ב-",j.due_day," בחודש"]}):u&&j.billing_cycle!=="per_file"?e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 inline-flex items-center gap-1",title:"ברירת המחדל של הקהילה",children:[e.jsx(Be,{className:"w-3 h-3"})," לתשלום ב-",u," בחודש"]}):null,j.includes_vat&&e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-amber-50 text-amber-700",children:"כולל מע״מ"}),j.requires_approval&&e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-purple-50 text-purple-700",children:"דורש אישור"}),j.online_payable&&e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 inline-flex items-center gap-0.5",children:[e.jsx(Oe,{className:"w-3 h-3"})," תשלום מקוון"]})]}),j.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-2 line-clamp-2",children:j.description})]},j.id))})]})}function pm(t,s){const n=Number(s);if(!t||!Number.isFinite(n)||n<1)return"";const[a,l]=String(t).split("-").map(Number);if(!a||!l||l<1||l>12)return"";const r=new Date(a,l,0).getDate();return`${a}-${String(l).padStart(2,"0")}-${String(Math.min(n,r)).padStart(2,"0")}`}const ot=Se,Ds=t=>ve(t),si=()=>new Date().toISOString().slice(0,7);function hm({kibbutzId:t,mode:s,onClose:n,onDone:a}){var wr;const l=s==="recurring",[r,o]=i.useState(!0),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState([]),[x,g]=i.useState([]),[y,$]=i.useState([]),[O,A]=i.useState([]),[S,P]=i.useState(0),[E,k]=i.useState(""),[C,w]=i.useState("all"),[_,T]=i.useState(""),[M,B]=i.useState(""),[R,j]=i.useState(new Set),[q,L]=i.useState(""),[N,v]=i.useState("fixed"),[F,K]=i.useState(""),[Z,H]=i.useState(si()),[z,te]=i.useState(""),[ie,V]=i.useState(!1),[Y,J]=i.useState(null),[I,X]=i.useState(""),[se,G]=i.useState(!1),[ne,ge]=i.useState(""),[ke,be]=i.useState("monthly"),[je,Ce]=i.useState(si()+"-01"),[ee,oe]=i.useState(""),[le,xe]=i.useState({}),[de,ae]=i.useState(new Set),[Ne,we]=i.useState(!1),Ue=i.useCallback(async()=>{var U;o(!0);try{const[me,fe,pe,ft,al,Ka,Tc,nl]=await Promise.all([D.entities.ChargeType.filter({kibbutz_id:t,is_active:!0},"order",300).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me}).catch(()=>[]),D.entities.Property.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ResidentGroup.filter({kibbutz_id:t},"order",300).catch(()=>[]),D.entities.ResidentGroupMember.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.BillingSettings.filter({kibbutz_id:t},"-created_date",1).catch(()=>[])]);
12u(me||[]),c((fe||[]).filter(Bc=>Bc.status!=="inactive")),h(pe||[]),f(ft||[]),g(al||[]),$(Ka||[]),A(Tc||[]);const ll=Number((U=nl==null?void 0:nl[0])==null?void 0:U.default_due_day);J(Number.isFinite(ll)&&ll>0?ll:null)}catch{W.error("שגיאה בטעינת נתונים")}finally{o(!1)}},[t]);i.useEffect(()=>{Ue()},[Ue]);const re=p.find(U=>U.id===E)||null;i.useEffect(()=>{re&&(v(re.calculation_method||"fixed"),K(re.rate??""),G(!!re.requires_approval),X(U=>U||re.name),ge(U=>U||re.name),re.billing_cycle&&re.billing_cycle!=="one_time"&&be(re.billing_cycle))},[E,re]);const Qe=((re==null?void 0:re.due_day)??null)||Y;i.useEffect(()=>{ie||te(pm(l?je.slice(0,7):Z,Qe))},[Qe,Z,je,l,ie]);const Et=i.useCallback(U=>{const me=d.find(fe=>fe.id===U);return me?m.find(fe=>fe.id===me.family_id):null},[d,m]),bt=i.useCallback(U=>{const me=d.find(pe=>pe.id===U);if(!me)return 0;const fe=b.filter(pe=>pe.family_id===me.family_id&&pe.status!=="inactive").length;return fe||x.filter(pe=>pe.payer_account_id===U).reduce((pe,ft)=>pe+(Number(ft.occupancy_count)||0),0)},[d,b,x]),ue=i.useCallback(U=>x.filter(me=>me.payer_account_id===U&&me.status!=="inactive"),[x]),Ee=i.useMemo(()=>{let U=d;if(C==="group"&&_){const me=new Set(O.filter(pe=>pe.group_id===_&&pe.is_active!==!1).map(pe=>pe.resident_id)),fe=new Set(b.filter(pe=>me.has(pe.id)).map(pe=>pe.family_id));U=d.filter(pe=>fe.has(pe.family_id))}else if(C==="property_type"&&M){const me=new Set(x.filter(fe=>fe.property_type===M).map(fe=>fe.payer_account_id));U=d.filter(fe=>me.has(fe.id))}else C==="select"&&(U=d.filter(me=>R.has(me.id)));return U},[d,C,_,M,R,O,b,x]),za=i.useCallback(U=>{const me=Number(F)||0;switch(N){case"fixed":return me;case"per_sqm":return me*ue(U).reduce((fe,pe)=>fe+(Number(pe.size_sqm)||Number(pe.built_sqm)||0),0);case"per_person":return me*bt(U);case"per_property":return me*ue(U).length;case"tiered":return me*ue(U).reduce((fe,pe)=>fe+(Number(pe.size_sqm)||0),0);case"custom":return 0;default:return me}},[N,F,ue,bt]),Ps=i.useMemo(()=>Ee.map(U=>{const me=za(U.id),fe=le[U.id]!=null?Number(le[U.id]):me;return{account:U,family:Et(U.id),computed:me,amount:fe,included:!de.has(U.id)}}),[Ee,za,le,de,Et]),He=Ps.filter(U=>U.included),sl=He.reduce((U,me)=>U+(Number(me.amount)||0),0),Dc=i.useMemo(()=>[...new Set(x.map(U=>U.property_type).filter(Boolean))],[x]),Nr=[{key:"type",label:"סוג חיוב",icon:Xe},{key:"audience",label:"קהל יעד",icon:De},{key:"calc",label:"חישוב ותעריף",icon:Ma},{key:"preview",label:"תצוגה מקדימה",icon:fs},{key:"options",label:"אפשרויות",icon:Ad},{key:"confirm",label:"סיכום ואישור",icon:la}],Oc=U=>U===S?"current":U===0?E?"done":"todo":U===1?Ee.length>0?"done":U<S?"error":"todo":U<S?"done":"todo",vr=()=>S===0?!!E:S===1?Ee.length>0:S===2?N==="custom"||F!=="":S===3?He.length>0:!0,Lc=async()=>{if(He.length===0){W.error("אין משלמים לחיוב");return}we(!0);try{let U=null;l&&(U=(await D.entities.BillingPlan.create({kibbutz_id:t,charge_type_id:E,name:ne||(re==null?void 0:re.name),audience_type:C,audience_ref:{group_id:_||null,property_type:M||null,account_ids:C==="select"?[...R]:null},calculation_method:N,rate:Number(F)||0,billing_cycle:ke,start_date:je||null,end_date:ee||null,due_day:z?Number(z.slice(8,10)):null,status:"active"})).id);const me=se?"pending":"approved";for(const fe of He){const pe=ue(fe.account.id)[0],ft=N==="per_sqm"||N==="tiered"?ue(fe.account.id).reduce((al,Ka)=>al+(Number(Ka.size_sqm)||Number(Ka.built_sqm)||0),0):N==="per_person"?bt(fe.account.id):N==="per_property"?ue(fe.account.id).length:1;await D.entities.Charge.create({kibbutz_id:t,payer_account_id:fe.account.id,property_id:(pe==null?void 0:pe.id)||null,charge_type_id:E,billing_plan_id:U,billing_period:Z,description:I||(re==null?void 0:re.name),quantity:ft,rate:Number(F)||0,amount:Number(fe.amount)||0,status:me,due_date:z||null})}D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:l?"recurring_charges_created":"onetime_charges_created",entity_type:"charge",new_value:`${He.length} חיובים · ${Ds(sl)}`}).catch(()=>{}),W.success(`נוצרו ${He.length} חיובים`),a==null||a()}catch{W.error("שגיאה ביצירת החיובים"),we(!1)}};return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})}):e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-5 billing-form",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-9 h-9 rounded-lg flex items-center justify-center ${l?"bg-blue-50":"bg-amber-50"}`,children:l?e.jsx(Mt,{className:"w-5 h-5 text-blue-600"}):e.jsx(Ns,{className:"w-5 h-5 text-amber-600"})}),e.jsx("h3",{className:"text-base font-bold",children:l?"חיוב חודשי חדש (חוזר)":"חיוב חד־פעמי חדש"})]}),e.jsx("button",{onClick:n,className:"w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"mb-5",children:e.jsx(jd,{steps:Nr.map((U,me)=>({...U,state:Oc(me)})),onStep:P,primaryColor:"#4f46e5",containerClassName:"grid grid-cols-3 sm:grid-cols-6 gap-2"})}),S===0&&(p.length===0?e.jsx("p",{className:"text-sm text-slate-500 text-center py-10",children:'אין סוגי חיובים פעילים. הגדירו סוג חיוב בלשונית „סוגי חיובים" תחילה.'}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2.5",children:p.map(U=>e.jsxs("button",{onClick:()=>k(U.id),className:`text-right rounded-xl border p-3.5 transition-all ${E===U.id?"border-indigo-400 ring-2 ring-indigo-100 bg-indigo-50/40":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Xe,{className:"w-4 h-4 text-indigo-500"}),e.jsx("span",{className:"text-sm font-bold",children:U.name})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 text-[11px]",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:Oa(U.calculation_method)}),U.calculation_method!=="custom"&&e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-blue-50 text-blue-700",children:Ds(U.rate)})]})]},U.id))})),S===1&&e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 mb-4",children:[{v:"all",l:"כל החשבונות"},{v:"group",l:"לפי קבוצה"},{v:"property_type",l:"לפי סוג נכס"},{v:"select",l:"בחירה ידנית"}].map(U=>e.jsx("button",{onClick:()=>w(U.v),className:`h-10 rounded-lg border text-sm font-medium ${C===U.v?"border-indigo-400 bg-indigo-50 text-indigo-700":"border-slate-200 text-slate-600"}`,children:U.l},U.v))}),C==="group"&&e.jsxs("select",{className:ot+" mb-3",value:_,onCh
12ange:U=>T(U.target.value),children:[e.jsx("option",{value:"",children:"בחרו קבוצה…"}),y.map(U=>e.jsx("option",{value:U.id,children:U.title},U.id))]}),C==="property_type"&&e.jsxs("select",{className:ot+" mb-3",value:M,onChange:U=>B(U.target.value),children:[e.jsx("option",{value:"",children:"בחרו סוג נכס…"}),Dc.map(U=>e.jsx("option",{value:U,children:U},U))]}),C==="select"&&e.jsxs("div",{className:"border border-slate-200 rounded-xl p-3 mb-3",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(qt,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx("input",{value:q,onChange:U=>L(U.target.value),placeholder:"חיפוש חשבון…",className:"w-full h-9 rounded-lg border border-slate-200 pr-9 pl-3 text-sm"})]}),e.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.filter(U=>!q||(U.name||"").includes(q)||(U.account_number||"").includes(q)).map(U=>{var fe;const me=R.has(U.id);return e.jsxs("button",{onClick:()=>j(pe=>{const ft=new Set(pe);return ft.has(U.id)?ft.delete(U.id):ft.add(U.id),ft}),className:`w-full flex items-center justify-between gap-2 rounded-lg border px-3 py-2 text-right ${me?"border-indigo-300 bg-indigo-50":"border-slate-200"}`,children:[e.jsxs("span",{className:"text-sm font-medium",children:[U.name||((fe=Et(U.id))==null?void 0:fe.name)||"—"," ",e.jsxs("span",{className:"text-xs text-slate-400",children:["#",U.account_number]})]}),e.jsx("span",{className:`w-5 h-5 rounded-md flex items-center justify-center ${me?"bg-indigo-600":"bg-slate-100"}`,children:me&&e.jsx(ye,{className:"w-3.5 h-3.5 text-white"})})]},U.id)})})]}),e.jsxs("div",{className:"text-sm bg-slate-50 rounded-lg px-4 py-3 flex items-center gap-2",children:[e.jsx(De,{className:"w-4 h-4 text-indigo-500"})," נבחרו ",e.jsx("b",{children:Ee.length})," חשבונות משלמים לחיוב."]})]}),S===2&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:[e.jsx(Q,{label:"שיטת חישוב",required:!0,info:"קובעת כיצד מחושב הסכום לכל משלם",children:e.jsx("select",{className:ot,value:N,onChange:U=>v(U.target.value),children:Da.map(U=>e.jsx("option",{value:U.v,children:U.l},U.v))})}),e.jsx(Q,{label:N==="custom"?"תעריף (ידני לכל שורה)":"תעריף / סכום (₪)",required:N!=="custom",children:e.jsx("input",{type:"number",className:ot,placeholder:"0",value:F,onChange:U=>K(U.target.value),disabled:N==="custom"})}),e.jsx(Q,{label:"תקופת חיוב",required:!0,children:e.jsx("input",{type:"month",className:ot,value:Z,onChange:U=>H(U.target.value)})}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Q,{label:"שם התוכנית",children:e.jsx("input",{className:ot,value:ne,onChange:U=>ge(U.target.value)})}),e.jsx(Q,{label:"מחזור",children:e.jsxs("select",{className:ot,value:ke,onChange:U=>be(U.target.value),children:[e.jsx("option",{value:"monthly",children:"חודשי"}),e.jsx("option",{value:"bimonthly",children:"דו-חודשי"}),e.jsx("option",{value:"quarterly",children:"רבעוני"}),e.jsx("option",{value:"yearly",children:"שנתי"})]})}),e.jsx(Q,{label:"תחילת התוכנית",children:e.jsx("input",{type:"date",className:ot,value:je,onChange:U=>Ce(U.target.value)})})]}),e.jsxs("div",{className:"sm:col-span-2 lg:col-span-3 text-sm bg-indigo-50/60 rounded-lg px-4 py-3 text-slate-600",children:[(wr=Da.find(U=>U.v===N))==null?void 0:wr.hint,". הסכומים יחושבו אוטומטית לכל משלם וניתן לערוך כל שורה בשלב הבא."]})]}),S===3&&e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center justify-between mb-2 text-sm",children:e.jsxs("span",{className:"text-slate-500",children:[He.length," מתוך ",Ps.length," חשבונות · סה״כ ",e.jsx("b",{className:"text-slate-800",children:Ds(sl)})]})}),e.jsx("div",{className:"border border-slate-200 rounded-xl overflow-hidden max-h-[50vh] overflow-y-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"חיוב"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"חשבון"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"מחושב"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium",children:"סכום לחיוב (₪)"})]})}),e.jsx("tbody",{children:Ps.map(U=>{var me;return e.jsxs("tr",{className:`border-t border-slate-100 ${U.included?"":"opacity-40"}`,children:[e.jsx("td",{className:"px-3 py-1.5",children:e.jsx("button",{onClick:()=>ae(fe=>{const pe=new Set(fe);return pe.has(U.account.id)?pe.delete(U.account.id):pe.add(U.account.id),pe}),className:`w-5 h-5 rounded-md flex items-center justify-center ${U.included?"bg-indigo-600":"bg-slate-200"}`,children:U.included&&e.jsx(ye,{className:"w-3.5 h-3.5 text-white"})})}),e.jsxs("td",{className:"px-3 py-1.5",children:[e.jsx("span",{className:"font-medium",children:U.account.name||((me=U.family)==null?void 0:me.name)||"—"})," ",e.jsxs("span",{className:"text-xs text-slate-400",children:["#",U.account.account_number]})]}),e.jsx("td",{className:"px-3 py-1.5 text-slate-400",children:Ds(U.computed)}),e.jsx("td",{className:"px-3 py-1.5",children:e.jsx("input",{type:"number",value:U.amount,onChange:fe=>xe(pe=>({...pe,[U.account.id]:fe.target.value})),className:"w-28 h-8 rounded-lg border border-slate-200 px-2 text-sm"})})]},U.account.id)})})]})})]}),S===4&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Q,{label:"תיאור החיוב (מופיע בחשבון)",children:e.jsx("input",{className:ot,value:I,onChange:U=>X(U.target.value)})})}),e.jsx(Q,{label:"תאריך לתשלום",hint:ie||!Qe?void 0:`לפי ${re!=null&&re.due_day?`יום החיוב של ${re.
12name}`:"ברירת המחדל של הקהילה"} — ה-${Qe} בחודש`,children:e.jsx("input",{type:"date",className:ot,value:z,onChange:U=>{V(!0),te(U.target.value)}})}),l&&e.jsx(Q,{label:"סיום התוכנית (לא חובה)",children:e.jsx("input",{type:"date",className:ot,value:ee,onChange:U=>oe(U.target.value)})}),e.jsxs("button",{type:"button",onClick:()=>G(U=>!U),className:`flex items-center gap-2 h-10 px-3 rounded-lg border text-sm ${se?"border-purple-300 bg-purple-50 text-purple-700":"border-slate-200 text-slate-500"}`,children:[e.jsx("span",{className:"flex-1 text-right",children:"החיובים ידרשו אישור לפני הפקה"}),e.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center ${se?"bg-purple-600":"bg-slate-200"}`,children:se&&e.jsx(ye,{className:"w-3 h-3 text-white"})})]})]}),S===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:[{l:"סוג חיוב",v:(re==null?void 0:re.name)||"—",icon:Xe},{l:"משלמים",v:He.length,icon:De},{l:"סה״כ לחיוב",v:Ds(sl),icon:Ma},{l:"תקופה",v:Z,icon:ra}].map(U=>{const me=U.icon;return e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-400 mb-1",children:[e.jsx(me,{className:"w-3.5 h-3.5"}),U.l]}),e.jsx("p",{className:"text-sm font-bold text-slate-800",children:U.v})]},U.l)})}),e.jsxs("div",{className:"text-sm bg-white border border-slate-200 rounded-xl p-4 space-y-1 text-slate-600",children:[e.jsxs("p",{children:["• שיטת חישוב: ",e.jsx("b",{children:Oa(N)}),N!=="custom"&&e.jsxs(e.Fragment,{children:[" · תעריף ",Ds(F)]})]}),e.jsxs("p",{children:["• תיאור: ",e.jsx("b",{children:I||(re==null?void 0:re.name)}),z&&e.jsxs(e.Fragment,{children:[" · לתשלום עד ",z]})]}),l&&e.jsxs("p",{children:["• תוכנית חוזרת: ",e.jsx("b",{children:ne})," · מחזור ",ke==="monthly"?"חודשי":ke," · תיווצר גם רשומת תוכנית."]}),e.jsxs("p",{children:["• סטטוס בעת יצירה: ",e.jsx("b",{children:se?"ממתין לאישור":"מאושר להפקה"}),"."]})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-5 pt-4 border-t border-slate-100",children:[e.jsxs("button",{onClick:()=>S===0?n():P(S-1),className:"h-10 px-4 rounded-full border border-slate-200 text-sm inline-flex items-center gap-1",children:[e.jsx(oa,{className:"w-4 h-4"})," ",S===0?"ביטול":"הקודם"]}),S<Nr.length-1?e.jsxs("button",{onClick:()=>vr()?P(S+1):W.error("יש להשלים שלב זה"),disabled:!vr(),className:"h-10 px-6 rounded-full bg-indigo-600 text-white text-sm font-bold inline-flex items-center gap-1 disabled:opacity-40",children:["הבא ",e.jsx(lt,{className:"w-4 h-4"})]}):e.jsxs("button",{onClick:Lc,disabled:Ne||He.length===0,className:"h-10 px-6 rounded-full bg-emerald-600 text-white text-sm font-bold inline-flex items-center gap-1.5 disabled:opacity-40",children:[e.jsx(ye,{className:"w-4 h-4"})," ",Ne?"יוצר…":`צור ${He.length} חיובים`]})]})]})}function _r({title:t,icon:s,steps:n,step:a,onStep:l,onClose:r,onSubmit:o,submitLabel:p="אישור ושמירה",submitting:u,children:d,width:c="max-w-2xl"}){const m=a===n.length-1;return e.jsx("div",{className:"fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:r,dir:"rtl",children:e.jsxs("div",{className:`billing-form bg-white rounded-2xl shadow-2xl w-full ${c} flex flex-col h-[min(42rem,92vh)]`,onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 pt-5 pb-3 flex-none",children:[e.jsxs("h3",{className:"text-[22px] font-black text-slate-900 flex items-center gap-2",children:[s?e.jsx(s,{className:"w-6 h-6 text-teal-600"}):null,t]}),e.jsx("button",{onClick:r,"aria-label":"סגירה",className:"w-9 h-9 rounded-full border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50 flex-none",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("ol",{className:"flex items-center gap-1.5 px-6 pb-3 flex-none","aria-label":"שלבים",children:n.map((h,b)=>{const f=b<a,x=b===a;return e.jsxs("li",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsxs("button",{type:"button",disabled:b>a,onClick:()=>l(b),"aria-current":x?"step":void 0,className:`h-8 px-3 rounded-full text-[12.5px] font-bold inline-flex items-center gap-1.5 transition-colors whitespace-nowrap ${x?"bg-teal-600 text-white":f?"bg-teal-50 text-teal-700 hover:bg-teal-100":"bg-slate-100 text-slate-400 cursor-default"}`,children:[e.jsx("span",{className:`w-4 h-4 rounded-full grid place-items-center text-[10px] flex-none ${x?"bg-white/25":f?"bg-teal-600 text-white":"bg-white text-slate-400"}`,children:f?e.jsx(ye,{className:"w-2.5 h-2.5"}):b+1}),h]}),b<n.length-1&&e.jsx("span",{className:"w-4 h-px bg-slate-200 flex-none"})]},h)})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 pb-2",children:d}),e.jsxs("div",{className:"flex items-center gap-2 px-6 py-4 border-t border-slate-100 flex-none",children:[a>0&&e.jsxs("button",{type:"button",onClick:()=>
12l(a-1),className:"h-11 px-4 rounded-xl border border-slate-200 text-slate-600 text-sm font-bold inline-flex items-center gap-1.5 hover:bg-slate-50",children:[e.jsx(oa,{className:"w-4 h-4"})," חזור"]}),e.jsxs("button",{type:"button",onClick:()=>m?o():l(a+1),disabled:u,className:"h-11 px-6 rounded-xl bg-teal-600 hover:bg-teal-700 text-white text-sm font-bold inline-flex items-center gap-1.5 transition-colors disabled:opacity-60 mr-auto",children:[u?"שומר…":m?p:"המשך",!m&&!u&&e.jsx(lt,{className:"w-4 h-4"})]}),e.jsx("button",{type:"button",onClick:r,className:"h-11 px-4 rounded-xl text-slate-500 text-sm font-bold hover:bg-slate-50",children:"ביטול"})]})]})})}function Qo({value:t,onChange:s,options:n,disabled:a,note:l}){return e.jsxs("div",{className:"space-y-2",children:[n.map(r=>{const o=!!t[r.v];return e.jsxs("button",{type:"button",disabled:a,onClick:()=>s(r.v,!o),className:`w-full rounded-xl border p-3 text-right transition-colors flex items-center gap-3 ${a?"opacity-50 cursor-not-allowed border-slate-200":o?"border-teal-400 bg-teal-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsx("span",{className:`w-10 h-5 rounded-full relative transition-colors flex-none ${o?"bg-teal-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-all ${o?"right-0.5":"right-5.5"}`})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800",children:r.l}),e.jsx("span",{className:"block text-[11.5px] text-slate-400",children:r.hint})]})]},r.v)}),l&&e.jsx("p",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2",children:l})]})}const bm=[{v:"all",l:"כל החשבונות",hint:"כל חשבון משלם פעיל בקהילה"},{v:"with_budget",l:"רק חשבונות עם מספר תקציב",hint:"משפחות שיש להן מספר תקציב בכולבו"},{v:"with_account",l:"רק חשבונות עם מספר חשבון",hint:"חשבונות שקיבלו מספר חשבון במערכת"},{v:"selected",l:"רק חשבונות מסומנים",hint:"רשימה שנבחרת ידנית"}],va=t=>Math.round((Number(t)+Number.EPSILON)*100)/100;function fm(t,s,{residents:n=[],properties:a=[]}={}){var u,d,c,m;const l=Number(t==null?void 0:t.rate)||0,r=(a||[]).filter(h=>h.payer_account_id===s.id&&h.status!=="inactive"),o=r.reduce((h,b)=>h+(Number(b.size_sqm)||Number(b.built_sqm)||0),0),p=(n||[]).filter(b=>b.family_id===s.family_id&&b.status!=="inactive").length||r.reduce((b,f)=>b+(Number(f.occupancy_count)||0),0);switch(t==null?void 0:t.calculation_method){case"per_sqm":case"tiered":return{amount:va(l*o),quantity:o,property_id:((u=r[0])==null?void 0:u.id)||null};case"per_person":return{amount:va(l*p),quantity:p,property_id:((d=r[0])==null?void 0:d.id)||null};case"per_property":return{amount:va(l*r.length),quantity:r.length,property_id:((c=r[0])==null?void 0:c.id)||null};case"fixed":default:return{amount:va(l),quantity:1,property_id:((m=r[0])==null?void 0:m.id)||null}}}const Xt=t=>(t==null?void 0:t.calculation_method)==="water_meter"||(t==null?void 0:t.billing_cycle)==="per_file",Kl=[{v:"manual",l:"הפעלה יזומה",hint:"המשרד מפעיל את ההפקה בכל פעם מחדש. אין שעון."},{v:"auto",l:"הפעלה אוטומטית",hint:"המערכת מפיקה לפי ההגדרות, בכל מחזור, עד שיושהה."}],Wl=[{v:"demand",l:"דרישת תשלום",hint:"מסמך שהמשפחה מתבקשת לשלם לפיו"},{v:"charge",l:"מסמך חיוב ותשלום",hint:"החיוב נגבה, ומופקת חשבונית וקבלה"}],Ul=[{v:"now",l:"מידי",hint:"ההפקה נעשית עם השמירה"},{v:"scheduled",l:"תזמן",hint:"ההפקה לפי המועדים שייקבעו"}],cl=[{v:"auto",l:"חיובים אוטומטים",hint:"רצים לפי ההגדרות עד שיושהו"},{v:"manual",l:"חיובים יזומים",hint:"מופעלים ביד, שוב ושוב"},{v:"file",l:"חיובים מקובץ",hint:"נוצרים מטעינת קובץ"},{v:"paused",l:"חיובים מושהים",hint:"הוגדרו וטרם הופעלו"}],dl=(t,s)=>{var n;return((n=t.find(a=>a.v===s))==null?void 0:n.l)||""};function gm(t){return Xt(t)?"file":ze(t)||"paused"}const ze=t=>(t==null?void 0:t.activation_mode)==="auto"||(t==null?void 0:t.activation_mode)==="manual"?t.activation_mode:t!=null&&t.auto_billing_enabled?"auto":null;function ym(t,s=null){return Xt(t)?ze(t)?!!t.activated_batch_id&&
12(!s||t.activated_batch_id===s):!1:!0}function _m(t,{done:s=!1}={}){const n=ze(t);return Xt(t)?n?s?"הסתיים":"פעיל":"מושהה":n?n==="manual"?(t==null?void 0:t.issue_timing)==="scheduled"?"מתוזמן":"יזום":"אוטומטי":"מושהה"}const jm={אוטומטי:"bg-emerald-50 text-emerald-700 border-emerald-200",יזום:"bg-indigo-50 text-indigo-700 border-indigo-200",מתוזמן:"bg-indigo-50 text-indigo-700 border-indigo-200",פעיל:"bg-sky-50 text-sky-700 border-sky-200","דרישת תשלום":"bg-sky-50 text-sky-700 border-sky-200","חיוב ומסמך תשלום":"bg-teal-50 text-teal-700 border-teal-200","מתחדש אוטומטי":"bg-emerald-50 text-emerald-700 border-emerald-200","מתחדש ידני":"bg-indigo-50 text-indigo-700 border-indigo-200",הסתיים:"bg-slate-100 text-slate-500 border-slate-200",מושהה:"bg-amber-50 text-amber-700 border-amber-200"},Nm=[{v:"active",l:"פעיל"},{v:"demand",l:"דרישת תשלום"},{v:"charge",l:"חיוב ומסמך תשלום"},{v:"done",l:"הסתיים"}],vm={file:"הסתיים",auto:"מתחדש אוטומטי",manual:"מתחדש ידני"},wm=(t=new Date)=>typeof t=="string"?t.slice(0,10):`${t.getFullYear()}-${Mn(t.getMonth()+1)}-${Mn(t.getDate())}`;function ai({activated:t=!1,billed:s=!1,demandDate:n=null,chargeDate:a=null,lastDueDate:l=null,kind:r="file",approvals:o=null,needsApproval:p=!1,now:u=new Date}={}){const d=wm(u),c=ut(a)||ut(l),m=[!!t,!!t&&!!s,!1,!1];m[2]=m[1]&&!!c&&c<=d,m[3]=r==="file"?m[2]&&!!ut(l)&&ut(l)<d:m[2];const h=[null,ut(n),ut(a),r==="file"?ut(l):null],b=m.lastIndexOf(!0),f=o||{},x=[null,f.demand||null,f.charge||null,null];return Nm.map((g,y)=>({...g,l:y===3&&vm[r]||g.l,done:m[y],at:y===b,date:h[y],approved:x[y],awaiting:!!x[y]&&!m[y],blocked:!!p&&!m[y]&&!x[y]&&(y===1||y===2)}))}const km=(t=[])=>{var s;return((s=t.find(n=>n.at))==null?void 0:s.l)||"מושהה"};function Sm(t){return t?Xt(t)?"חיוב יזום משתנה":t.billing_cycle==="one_time"?"חיוב חד־פעמי":ze(t)==="auto"?"חיוב מתחדש אוטומטי":ze(t)==="manual"?"חיוב יזום":"טרם הופעל":""}const Hl=t=>{const s=Number(t);return Number.isFinite(s)&&s>=1&&s<=31?Math.round(s):null},ut=t=>/^\d{4}-\d{2}-\d{2}$/.test(String(t||"").slice(0,10))?String(t).slice(0,10):null,An=t=>ut(t)?Number(String(t).slice(8,10)):null,Mn=t=>String(t).padStart(2,"0"),ni=t=>`${t.getFullYear()}-${Mn(t.getMonth()+1)}-${Mn(t.getDate())}`;function li(t,s=new Date){const n=Hl(t);if(!n)return"";const a=s.getFullYear(),l=s.getMonth(),r=new Date(a,l+1,0).getDate(),o=Math.min(n,r);if(o>=s.getDate())return ni(new Date(a,l,o));const p=new Date(a,l+2,0).getDate();return ni(new Date(a,l+1,Math.min(n,p)))}const xn=t=>{const[s,n,a]=String(t||"").slice(0,10).split("-");return a?`${a}/${n}/${s}`:""};function Pn(t={},{file:s=!1}={}){const n=Kl.some(u=>u.v===t.mode)?t.mode:"manual",a=Ul.some(u=>u.v===t.timing)?t.timing:"now",l=a==="scheduled",r=Wl.some(u=>u.v===t.document_kind)?t.document_kind:"demand",o=r==="demand"?ut(t.demand_issue_date):null,p=ut(t.charge_issue_date);return{activation_mode:n,document_kind:r,issue_timing:a,demand_issue_date:o,charge_issue_date:p,last_due_date:s?ut(t.last_due_date):null,demand_issue_day:s?null:An(o)??Hl(t.demand_issue_day),charge_issue_day:s?null:An(p)??Hl(t.charge_issue_day),requires_manager_approval:n==="manual"&&l?!!t.requires_manager_approval:!1}}function ri(t={},{file:s=!1}={}){const n=Pn(t,{file:s});if(n.document_kind==="demand"&&!n.demand_issue_date)return"יש לבחור תאריך להפקת דרישת התשלום";if(!n.charge_issue_date)return"יש לבחור מועד לחיוב ולהפקת מסמך התשלום";if(n.demand_issue_date&&n.demand_issue_date>n.charge_issue_date)return"דרישת התשלום אינה יכולה לצאת אחרי מועד החיוב";if(s){if(!n.last_due_date)return"יש לבחור תאריך אחרון לתשלום";if(n.charge_issue_date>n.last_due_date)return"התאריך האחרון לתשלום אינו יכול להקדים את מועד החיוב"}return t.audience==="selected"&&!(t.account_ids||[]).length?"יש לבחור לפחות חשבון אחד":null}function Jo(t={}){const s=t.demand_issue_day??An(t.demand_issue_date),n=t.charge_issue_day??An(t.charge_issue_date);return n?t.document_kind==="demand"&&s?`דרישה ב-${s} בחודש, חיוב ב-${n} בחודש`:`חיוב ב-${n} בחודש`:""}function ec(t={},{file:s=!1,typeName:n="",accounts:a=null,total:l=null,now:r=new Date,pending:o=!1}={}){const p=Pn(t,{file:s}),u=n?` עבור חיובי ${n}`:"",d=[],c=p.demand_issue_date||li(p.demand_issue_day,r),m=p.charge_issue_date||li(p.charge_issue_day,r),h=o&&p.issue_timing==="now"?", עם השמירה":"";p.document_kind==="demand"&&d.push(c?`דרישת התשלום תופק בתאריך ${xn(c)}${h}${u}.`:`דרישת התשלום תופק במועד שייבחר${u}.`),d.push(m?`החיוב והפקת מסמך התשלום יתבצעו בתאריך ${xn(m)}.`:"החיוב והפקת מסמך התשלום יתבצעו במועד שייבחר."),s&&p.last_due_date&&d.push(`תאריך אחרון לתשלום: ${xn(p.last_due_date)}.`);const b=s?"":Jo(p);if(d.push(p.activation_mode==="auto"?`הפעלה אוטומטית — ${b?`ובכל מחזור: ${b}`:"בכל מחזור"}, עד שההפקה תושהה.`:`הפעלה יזומה — מופעלת ביד, שוב ושוב.${p.requires_manager_approval?" ההפקה תמתין לאישור מנהל.":""}
12`),a!==null){const f=l===null?"":` · ${Number(l).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2})} ₪`;d.push(`עבור ${_e(a,"חשבון משלם אחד","חשבונות משלמים")}${f}.`)}return d}const ii=t=>ve(t),ul=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),$m={manual:Ns,auto:Mt},Cm={demand:nt,charge:fo};function Va({options:t,value:s,onChange:n,icons:a={},columns:l=2}){return e.jsx("div",{className:`grid gap-2 ${l===2?"sm:grid-cols-2":""}`,children:t.map(r=>{const o=s===r.v,p=a[r.v];return e.jsxs("button",{type:"button",onClick:()=>n(r.v),"aria-pressed":o,className:`text-right rounded-2xl border-2 p-3.5 transition-colors flex items-start gap-3 ${o?"border-teal-500 bg-teal-50/60":"border-slate-200 bg-white hover:border-slate-300"}`,children:[p&&e.jsx("span",{className:`w-10 h-10 rounded-xl grid place-items-center flex-none ${o?"bg-teal-600 text-white":"bg-slate-50 text-slate-400 border border-slate-200"}`,children:e.jsx(p,{className:"w-5 h-5"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[14px] font-black text-slate-900",children:r.l}),r.hint&&e.jsx("span",{className:"block text-[11.5px] text-slate-500 leading-snug mt-0.5",children:r.hint})]}),e.jsx("span",{className:`w-[18px] h-[18px] rounded-full border-2 grid place-items-center flex-none mt-0.5 ${o?"border-teal-600 bg-teal-600":"border-slate-300"}`,children:o&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white"})})]},r.v)})})}function ml({label:t,value:s,onChange:n,hint:a}){return e.jsxs("label",{className:"block min-w-0",children:[e.jsx("span",{className:"block text-[11.5px] font-bold text-slate-500 mb-1",children:t}),e.jsx("input",{type:"date",value:s||"",onChange:l=>n(l.target.value||null),className:"w-full h-11 rounded-xl border border-slate-200 px-3 text-sm font-bold focus:outline-none focus:border-teal-400"}),a&&e.jsx("span",{className:"block text-[11px] text-slate-400 mt-1",children:a})]})}const Am=()=>{const t=new Date,s=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${s(t.getMonth()+1)}-${s(t.getDate())}`};function Mm({type:t,accounts:s=[],residents:n=[],properties:a=[],busy:l=!1,onSave:r,onClose:o}){const p=Xt(t),[u,d]=i.useState(0),[c,m]=i.useState(()=>({mode:ze(t)||"manual",document_kind:t.document_kind||"demand",timing:t.issue_timing||(ze(t)==="auto"?"scheduled":"now"),demand_issue_date:t.demand_issue_date||t.next_issue||null,charge_issue_date:t.charge_issue_date||t.next_due||null,last_due_date:t.last_due_date||t._batchDue||null,requires_manager_approval:!!t.requires_manager_approval,audience:t.audience||t.auto_audience||"all",account_ids:t.account_ids||t.auto_account_ids||[]})),h=(j,q)=>m(L=>({...L,[j]:q})),b=i.useRef({});i.useEffect(()=>{const j=Am(),q=["demand_issue_date","charge_issue_date",...p?["last_due_date"]:[]];m(L=>{const N={...L};return q.forEach(v=>{c.timing==="now"?L[v]||(N[v]=j,b.current[v]=j):L[v]&&L[v]===b.current[v]&&(N[v]=null,b.current[v]=null)}),N})},[c.timing,p]);const[f,x]=i.useState(""),g=i.useMemo(()=>new Set(c.account_ids||[]),[c.account_ids]),y=j=>j!=null&&String(j).trim()!=="",$=i.useMemo(()=>s.filter(j=>j.status!=="inactive"),[s]),O=i.useMemo(()=>{switch(c.audience){case"with_budget":return $.filter(j=>y(j.budget_number)||y(j.budget));case"with_account":return $.filter(j=>y(j.account_number));case"selected":return $.filter(j=>g.has(j.id));default:return $}},[c.audience,$,g]),A=i.useMemo(()=>{const j=O.map(q=>fm(t,q,{residents:n,properties:a}).amount).filter(q=>q>0);return{accounts:j.length,total:va(j.reduce((q,L)=>q+L,0))}},[O,t,n,a]),S=i.useMemo(()=>{const j=f.trim();return j?$.filter(q=>[q.name,q.account_number,q.budget_number,q.budget].filter(Boolean).join(" ").includes(j)):$},[$,f]),P=j=>m(q=>{const L=new Set(q.account_ids||[]);return L.has(j)?L.delete(j):L.add(j),{...q,account_ids:[...L]}}),E=t._batch||null,k={accounts:Number((E==null?void 0:E.bill_count)||(E==null?void 0:E.row_count))||0,total:Number(E==null?void 0:E.total_amount)||0},C=c.timing==="scheduled",w=ri(c,{file:p}),_=ri({...c,audience:"all"},{file:p}),T=Jo(Pn(c,{file:p})),M=!!ze(t),B=ec(c,{file:p,pending:!0,typeName:t.name,accounts:p?k.accounts:u>=2?A.accounts:null,total:p?k.total:u>=2?A.total:null}),R=()=>{w||l||r({...Pn(c,{file:p}),audience:c.audience,account_ids:c.audience==="selected"?[...g]:null})};return Pt.createPortal(e.jsxs(_r,{title:`ניהול חיובים — ${t.name}`,icon:Be,steps:[u>0?dl(Kl,c.mode):"אופן ההפעלה",u>1?`${dl(Wl,c.document_kind)} · ${dl(Ul,c.timing)}`:"המסמך והמועד",...p?[]:["חשבונות לחיוב"]],step:u,onStep:d,onClose:o,onSubmit:R,submitLabel:l?"שומר…":M?"שמירת השינויים":"שמירה והפעלה",submitting:l,width:"max-w-2xl",children:[u===0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Va,{options:Kl,value:c.mode,onCh
12ange:j=>h("mode",j),icons:$m,columns:1}),e.jsx("p",{className:"text-[12px] text-slate-500 leading-relaxed bg-slate-50 border border-slate-200 rounded-xl px-3 py-2",children:c.mode==="manual"?"חיוב יזום נשאר בידיים של המשרד: הוא מופק בכל פעם שמפעילים אותו, ואפשר להפעיל אותו שוב ושוב.":"חיוב אוטומטי רץ בעצמו לפי ההגדרות, בכל מחזור, עד שמישהו משהה אותו."})]}),u===1&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{children:[e.jsx("h4",{className:"text-[13px] font-black text-slate-800 mb-2",children:"המסמך שיופק"}),e.jsx(Va,{options:Wl,value:c.document_kind,onChange:j=>h("document_kind",j),icons:Cm})]}),e.jsxs("section",{children:[e.jsx("h4",{className:"text-[13px] font-black text-slate-800 mb-2",children:"מועד ההפקה"}),e.jsx(Va,{options:Ul,value:c.timing,onChange:j=>h("timing",j)})]}),e.jsxs("section",{className:"rounded-2xl border border-slate-200 bg-slate-50/60 p-3.5",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[c.document_kind==="demand"&&e.jsx(ml,{label:"הפקת דרישת תשלום",value:c.demand_issue_date,onChange:j=>h("demand_issue_date",j),hint:C?"לפני מועד החיוב":"המסמך יופק עם השמירה"}),e.jsx(ml,{label:"מועד החיוב והפקת מסמך התשלום",value:c.charge_issue_date,onChange:j=>h("charge_issue_date",j),hint:"היום שבו החיוב נגבה"}),p&&e.jsx(ml,{label:"תאריך אחרון לתשלום",value:c.last_due_date,onChange:j=>h("last_due_date",j),hint:"התאריך שמודפס למשפחה"})]}),c.mode==="auto"&&T&&e.jsxs("p",{className:"text-[12px] text-slate-500 mt-2.5 flex items-start gap-1.5",children:[e.jsx(Mt,{className:"w-3.5 h-3.5 flex-none mt-0.5 text-slate-400"}),"אלה מועדי המחזור הראשון. בכל מחזור שאחריו: ",T,"."]})]}),C&&c.mode==="manual"&&e.jsxs("section",{className:"rounded-2xl border border-slate-200 bg-slate-50/60 p-3.5",children:[e.jsxs("h4",{className:"text-[13px] font-black text-slate-800 mb-2 flex items-center gap-1.5",children:[e.jsx(xt,{className:"w-4 h-4 text-slate-400"})," דורש אישור מנהל"]}),e.jsx(Va,{options:[{v:"yes",l:"כן",hint:"ללא אישור מנהל המסמך לא יופק במועד שנקבע"},{v:"no",l:"לא",hint:"ההפקה תיעשה במועד ללא אישור נוסף"}],value:c.requires_manager_approval?"yes":"no",onChange:j=>h("requires_manager_approval",j==="yes")})]}),p&&e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ga,{label:"חשבונות לחיוב",value:ul(k.accounts)}),e.jsx(Ga,{label:"סכום החיוב",value:ii(k.total),strong:!0})]}),e.jsx(oi,{lines:B}),_&&e.jsx("p",{className:"text-[12.5px] font-bold text-rose-600",children:_})]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-2",children:bm.map(j=>{const q=c.audience===j.v,L=j.v==="all"?$.length:j.v==="with_budget"?$.filter(N=>y(N.budget_number)||y(N.budget)).length:j.v==="with_account"?$.filter(N=>y(N.account_number)).length:g.size;return e.jsxs("button",{type:"button",onClick:()=>h("audience",j.v),className:`w-full text-right flex items-center gap-3 p-3 rounded-xl border-2 transition-colors ${q?"border-teal-500 bg-teal-50/50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsx("span",{className:`w-5 h-5 rounded-full border-2 grid place-items-center flex-none ${q?"border-teal-600":"border-slate-300"}`,children:q&&e.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-teal-600"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[14px] font-bold text-slate-800",children:j.l}),e.jsx("span",{className:"block text-[12px] text-slate-400 mt-0.5",children:j.hint})]}),e.jsx("span",{className:"text-[13px] font-black text-slate-500 tabular-nums flex-none",children:ul(L)})]},j.v)})}),c.audience==="selected"&&e.jsxs("div",{className:"rounded-xl border border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"relative border-b border-slate-100",children:[e.jsx(qt,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"}),e.jsx("input",{value:f,onChange:j=>x(j.target.value),placeholder:"חיפוש לפי שם, מספר חשבון או תקציב",className:"w-full h-11 pr-9 px-3 text-sm focus:outline-none"})]}),e.jsxs("div",{className:"max-h-44 overflow-y-auto",children:[S.map(j=>{const q=g.has(j.id);return e.jsxs("button",{type:"button",onClick:()=>P(j.id),className:"w-full flex items-center gap-2.5 px-3 py-2 text-right hover:bg-slate-50 border-b border-slate-50 last:border-0",children:[e.jsx("span",{className:`w-[18px] h-[18px] rounded-md border grid place-items-center flex-none ${q?"bg-teal-600 border-teal-600 text-white":"border-slate-300"}`,children:q&&e.jsx(ye,{className:"w-3 h-3"})}),e.jsx("span",{className:"flex-1 min-w-0 text-[13.5px] font-bold text-slate-700 truncate",children:j.name||`חשבון #${j.account_number}`}),e.jsx("span",{className:"text-[12px] text-slate-400 flex-none",children:[j.account_number&&`#${j.account_number}`,(j.budget_number||j.budget)&&`תקציב ${j.budget_number||j.budget}
12`].filter(Boolean).join(" · ")})]},j.id)}),S.length===0&&e.jsx("p",{className:"text-sm text-slate-400 text-center py-6",children:"אין תוצאות"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ga,{label:"חשבונות לחיוב",value:ul(A.accounts)}),e.jsx(Ga,{label:"צפי הכנסות",value:ii(A.total),strong:!0})]}),e.jsx(oi,{lines:B}),w&&e.jsxs("p",{className:"text-[12.5px] font-bold text-rose-600 flex items-center gap-1.5",children:[e.jsx(Ie,{className:"w-3.5 h-3.5 opacity-0"})," ",w]})]})]}),document.body)}function Ga({label:t,value:s,strong:n}){return e.jsxs("div",{className:"rounded-xl border border-slate-200 p-3 text-center",children:[e.jsx("p",{className:`text-[17px] font-black tabular-nums leading-tight ${n?"text-emerald-700":"text-slate-900"}`,children:s}),e.jsx("p",{className:"text-[11.5px] text-slate-400 mt-0.5",children:t})]})}function oi({lines:t=[]}){return e.jsxs("div",{className:"rounded-2xl border border-teal-100 bg-teal-50/60 p-3",children:[e.jsx("p",{className:"text-[11.5px] font-black text-teal-800 mb-1",children:"מה יקרה"}),e.jsx("ul",{className:"space-y-1",children:t.map(s=>e.jsxs("li",{className:"text-[13px] text-slate-700 leading-snug flex items-start gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-teal-500 flex-none mt-1.5"})," ",s]},s))})]})}const ci=t=>ve(t),xl=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),Pm=t=>{const[s,n,a]=String(t||"").slice(0,10).split("-");return a?`${a}/${n}/${s}`:""},Em=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],di=t=>{const[s,n]=String(t||"").split("-").map(Number);return s&&n>=1&&n<=12?`${Em[n-1]} ${s}`:String(t||"")},Xa=({icon:t,label:s,children:n})=>e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[11px] font-bold text-slate-400 whitespace-nowrap",children:s}),e.jsxs("span",{className:"block text-[13.5px] font-black text-slate-800 truncate inline-flex items-center gap-1.5",children:[t&&e.jsx(t,{className:"w-3.5 h-3.5 text-slate-400 flex-none"}),n]})]});function tc({row:t,stage:s,period:n,busy:a,onClose:l,onConfirm:r}){const[o,p]=i.useState(!1),[u,d]=i.useState(""),c=s==="demand",m=c?"הפקת דרישת תשלום":"החיוב והפקת מסמך התשלום",h=Pm(c?(t==null?void 0:t.next_issue)||(t==null?void 0:t.date):(t==null?void 0:t.next_due)||(t==null?void 0:t.date));return i.useEffect(()=>{const b=f=>{f.key==="Escape"&&l()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[l]),Pt.createPortal(e.jsxs("div",{dir:"rtl",className:"fixed inset-0 z-[75] grid place-items-center p-4",role:"dialog","aria-modal":"true","aria-label":`אישור ${m}`,children:[e.jsx("button",{type:"button","aria-label":"סגירה",onClick:l,className:"absolute inset-0 bg-slate-900/50 backdrop-blur-[2px] cursor-default"}),e.jsxs("div",{className:"relative w-full max-w-lg bg-white rounded-2xl border border-slate-200 shadow-2xl",children:[e.jsxs("div",{className:"flex items-start gap-3 p-5 pb-3",children:[e.jsx("span",{className:"w-10 h-10 rounded-xl bg-amber-50 text-amber-600 grid place-items-center flex-none",children:e.jsx(xt,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"text-[17px] font-black text-slate-900",children:["אישור ",m]}),e.jsxs("p",{className:"text-[12.5px] text-slate-500 mt-0.5",children:[t.name," · מחזור ",di(n)]})]}),e.jsx("button",{type:"button",onClick:l,"aria-label":"סגירה",className:"mr-auto w-8 h-8 rounded-lg grid place-items-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 flex-none",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"px-5 pb-4 space-y-3",children:[e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 px-3.5 py-2.5 grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(Xa,{label:"סוג חיוב",children:t.name}),e.jsx(Xa,{label:"מחזור",children:di(n)}),e.jsx(Xa,{label:"חשבונות",children:t.accounts?xl(t.accounts):"—"}),e.jsx(Xa,{label:c?"מועד הדרישה":"מועד החיוב",icon:vs,children:h||"—"})]}),e.jsx("p",{className:"text-[13.5px] text-slate-700 leading-relaxed bg-amber-50/70 border border-amber-200 rounded-xl px-3.5 py-3",children:c?e.jsxs(e.Fragment,{children:["באישור זה ",e.jsx("b",{children:"תופק עכשיו"})," דרישת תשלום עבור ",e.jsx("b",{children:t.name})," ותישלח למשפחות",t.accounts?e.jsxs(e.Fragment,{children:[" — ",xl(t.accounts)," חשבונות משלמים"]}):null,t.forecast?e.jsxs(e.Fragment,{children:[", בסך ",e.jsx("b",{dir:"ltr",children:ci(t.forecast)})]}):null,". פעולה זו אינה ניתנת לביטול לאחר ההפקה."]}):e.jsxs(e.Fragment,{children:["באישור זה ייגבה החיוב עבור ",e.jsx("b",{children:t.name})," ויופק מסמך תשלום",t.accounts?e.jsxs(e.Fragment,{children:[" — ",xl(t.accounts)," חשבונות משלמים"]}):null,t.forecast?e.jsxs(e.Fragment,{children:[", בסך ",e.jsx("b",{dir:"ltr",children:ci(t.forecast)})]}):null,". פעולה זו אינה ניתנת לביטול לאחר הגבייה."]})}),e.jsxs("label",{className:"flex items-start gap-2.5 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:b=>p(b.target.checked),className:"w-5 h-5 mt-0.5 rounded accent-amber-500 flex-none"}),e.jsxs("span",{className:"text-[13.5px] font-bold text-slate-800",children:["קראתי את הפרטים ואני מאשר/ת את ",m,"."]})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"block text-[11.5px] font-bold text-slate-500 mb-1",children:"הערה לאישור (לא חובה)"}),e.jsx("input",{value:u,onChange:b=>d(b.target.value),maxLength:300,className:"w-full h-11 rounded-xl border border-slate-200 px-3 text-sm focus:outline-none focus:border-amber-400"})]}),e.jsx("p",{className:"text-[11.5px] text-slate-400",children:"שם המאשר, התאריך והשעה יירשמו על האישור."})]}),e.jsxs("div",{className:"flex items-center gap-3 px-5 py-3.5 border-t border-slate-100 bg-slate-50 rounded-b-2xl",children:[e.jsxs("button",{type:"button",onClick:()=>r(u),disabled:!o||a,className:`h-11 px-6 rounded-xl bg-amber-500 text-white text-[14px] font-bold
13              inline-flex items-center gap-2 hover:bg-amber-600 disabled:opacity-50`,children:[a?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(ye,{className:"w-4 h-4"}),c?"אישור והפקה":"אישור ושמירה"]}),e.jsx("button",{type:"button",onClick:l,className:"h-11 px-5 rounded-xl border border-slate-200 bg-white text-[13px] font-bold text-slate-600",children:"ביטול"})]})]})]}),document.body)}const ui={monthly:"חודשי",bimonthly:"דו-חודשי",quarterly:"רבעוני",yearly:"שנתי",one_time:"חד-פעמי",per_file:"לפי טעינת קובץ"},Fm={fixed:"סכום קבוע",per_sqm:"לפי מ״ר",per_person:"לפי נפש",per_property:"לפי נכס",tiered:"מדורג",custom:"ידני",water_meter:"צריכת מים לפי קריאת מונה"},Dm=t=>Fm[t]||t||"—",Om={serial:["מסד","מספרסידורי","סידורי","מסדר","#"],consumer_id:["מסזיהוי","מספרזיהוי","זיהויצרכן","מסצרכן","מספרצרכן","קודצרכן"],meter_number:["מסמונה","מספרמונה","מונה","מסמד","מספרמד"],property_address:["כתובתהנכס","כתובתנכס","כתובת"],consumer_name:["שםצרכן","שםהצרכן","צרכן","שם"],read_at:["תאריךוזמן","תאריךושעה","תאריךקריאה","תאריך","תאריךזמן"],current_reading:["קריאה","קריאהנוכחית","קריאתמונה","מונהנוכחי"],file_consumption:["צריכה","צריכהמק","כמותצריכה"],meter_status:["סטטוסמונה","סטטוס","מצבמונה"]},sc=t=>String(t??"").replace(/[׳״"'`״׳]/g,"").replace(/[\s ._\-–—/\\]/g,"").replace(/[()[\]]/g,"").trim().toLowerCase(),Lm=(()=>{const t=new Map;for(const[s,n]of Object.entries(Om))for(const a of n)t.set(sc(a),s);return t})(),mi=t=>{if(t==null)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;const s=String(t).replace(/[‎‏‪-‮]/g,"").replace(/,/g,"").trim();if(!s)return null;const n=s.match(/-?\d+(\.\d+)?/);if(!n)return null;const a=Number(n[0]);return Number.isFinite(a)?a:null},En=t=>{var s;return t==null?"":t instanceof Date?t.toISOString().slice(0,16).replace("T"," "):typeof t=="object"?String(t.text??t.result??((s=t.ric
13hText)==null?void 0:s.map(n=>n.text).join(""))??"").trim():String(t).replace(/[‎‏]/g,"").trim()};function Tm(t){const s=Math.min((t==null?void 0:t.length)||0,15);for(let n=0;n<s;n++){const a={};let l=0;if((t[n]||[]).forEach((r,o)=>{const p=Lm.get(sc(En(r)));p&&a[p]===void 0&&(a[p]=o,l+=1)}),l>=2&&a.meter_number!==void 0)return{headerRow:n,cols:a};if(l>=3)return{headerRow:n,cols:a}}return null}function Bm(t,s){const n=[];let a="",l=!1;for(let r=0;r<t.length;r++){const o=t[r];l?o==='"'?t[r+1]==='"'?(a+='"',r+=1):l=!1:a+=o:o==='"'?l=!0:o===s?(n.push(a),a=""):a+=o}return n.push(a),n.map(r=>r.trim())}function Rm(t){const s=String(t||"").split(/\r\n|\r|\n/).filter(r=>r.trim()!=="");if(!s.length)return[];const n=s.slice(0,20),a=r=>n.reduce((o,p)=>o+(p.split(r).length-1),0),l=[",",";","	"].sort((r,o)=>a(o)-a(r))[0];return s.map(r=>Bm(r,l))}async function qm(t){const s=(await In(async()=>{const{default:r}=await import("./exceljs.min-CcgsY5Wm.js").then(o=>o.e);return{default:r}},__vite__mapDeps([0,1,2]))).default,n=new s.Workbook;await n.xlsx.load(t);const a=n.worksheets[0];if(!a)return[];const l=[];return a.eachRow({includeEmpty:!1},r=>{const o=r.values||[];l.push(o.slice(1).map(En))}),l}const Im=t=>/\.xlsx?$/i.test(String(t||""));async function zm(t){const s=(t==null?void 0:t.name)||"",n=await t.arrayBuffer();let a=[];if(Im(s))try{a=await qm(n)}catch{return{rows:[],errors:["לא ניתן לקרוא את הקובץ. שמרו אותו מחדש בפורמט XLSX או CSV ונסו שוב."],headerRow:-1,columns:{}}}else a=Rm(new TextDecoder("utf-8").decode(n));return Km(a)}function Km(t){const s=[],n=Tm(t);if(!n)return{rows:[],errors:["לא זוהתה שורת כותרות בקובץ. נדרשות לפחות העמודות: מס׳ מונה, קריאה."],headerRow:-1,columns:{}};const{headerRow:a,cols:l}=n;l.meter_number===void 0&&l.consumer_id===void 0&&s.push("בקובץ אין מס׳ מונה ואין מס׳ זיהוי — לא ניתן להתאים את הרשומות למונים."),l.current_reading===void 0&&s.push("בקובץ אין עמודת קריאה.");const r=(u,d)=>l[d]===void 0?"":En(u[l[d]]),o=[],p=new Map;for(let u=a+1;u<t.length;u++){const d=t[u]||[];if(d.every(g=>En(g)===""))continue;const c=r(d,"meter_number"),m=r(d,"consumer_id"),h=mi(r(d,"current_reading")),b=o.length+1,f={row_no:b,source_serial:r(d,"serial"),consumer_id:m,meter_number:c,property_address:r(d,"property_address"),consumer_name:r(d,"consumer_name"),read_at:r(d,"read_at"),current_reading:h,file_consumption:mi(r(d,"file_consumption")),meter_status:r(d,"meter_status"),file_error:""};!c&&!m?f.file_error="בשורה אין מס׳ מונה ואין מס׳ זיהוי":h===null&&(f.file_error="הקריאה בשורה אינה מספר");const x=c||`id:${m}`;x&&p.has(x)?f.duplicate_of=p.get(x):x&&p.set(x,b),o.push(f)}return o.length||s.push("לא נמצאו שורות נתונים מתחת לשורת הכותרות."),{rows:o,errors:s,headerRow:a,columns:l}}function Wm(t){const s=t||[];return{rows:s.length,meters:new Set(s.map(n=>n.meter_number).filter(Boolean)).size,duplicates:s.filter(n=>n.duplicate_of).length,errors:s.filter(n=>n.file_error).length}}const qa=(t,s)=>t.value?t.value(s):s[t.key],pl=new Set(["num","money","cube","dec3"]);function Fn(t,s){const n=qa(t,s);if(n==null||n==="")return t.blank??"—";switch(t.type){case"money":return Number(n).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2});case"cube":case"dec3":return Number(n).toFixed(3).replace(/\.?0+$/,"");case"num":return new Intl.NumberFormat("he-IL").format(Number(n));case"pct":return`${Number(n).toFixed(1)}%`;case"date":{const a=String(n).slice(0,10),[l,r,o]=a.split("-");return o?`${o}/${r}/${l}`:a}default:return String(n)}}function ac(t,s){const n={};for(const a of t)if(a.total){if(a.total==="count"){n[a.key]=s.length;continue}n[a.key]=s.reduce((l,r)=>{const o=Number(qa(a,r));return l+(Number.isFinite(o)?o:0)},0)}return n}async function nc({fileName:t,sheetName:s,title:n,meta:a=[],columns:l,rows:r,totals:o}){const p=(await In(async()=>{const{default:A}=await import("./exceljs.min-CcgsY5Wm.js").then(S=>S.e);return{default:A}},__vite__mapDeps([0,1,2]))).default,u=new p.Workbook;u.creator="Eshuv",u.created=new Date;const d=l.filter(A=>!A.hide),c=u.addWorksheet((s||n||"דוח").slice(0,30),{views:[{rightToLeft:!0,state:"frozen",ySplit:a.length?3:2}]}),m=d.length;d.forEach((A,S)=>{c.getColumn(S+1).width=A.width||16}),c.mergeCells(1,1,1,m);const h=c.getCell(1,1);h.value=n,h.font={bold:!0,size:15,color:{argb:"FFFFFFFF"}},h.alignment={horizontal:"right",vertical:"middle",readingOrder:"rtl"},h.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FF1E293B"}},c.getRow(1).height=26;let b=2;if(a.length){c.mergeCells(2,1,2,m);const A=c.getCell(2,1);
13A.value=a.join("   ·   "),A.font={size:10,color:{argb:"FF475569"}},A.alignment={horizontal:"right",vertical:"middle",readingOrder:"rtl"},b=3}const f=c.getRow(b);d.forEach((A,S)=>{const P=f.getCell(S+1);P.value=A.header,P.font={bold:!0,size:11,color:{argb:"FFFFFFFF"}},P.alignment={horizontal:"center",vertical:"middle",wrapText:!0,readingOrder:"rtl"},P.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FF0F766E"}}}),f.height=20,r.forEach((A,S)=>{const P=c.getRow(b+1+S);d.forEach((E,k)=>{const C=P.getCell(k+1),w=qa(E,A);if(pl.has(E.type)){const _=Number(w);C.value=Number.isFinite(_)?_:null,C.numFmt=E.type==="money"?"#,##0.00":E.type==="num"?"#,##0":"#,##0.000"}else C.value=w==null?"":String(Fn(E,A)==="—"?"":Fn(E,A));C.font={size:10,color:{argb:"FF1E293B"}},C.alignment={horizontal:pl.has(E.type)?"left":E.align==="center"?"center":"right",vertical:"middle",readingOrder:"rtl"},S%2===1&&(C.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FFF8FAFC"}}),C.border={bottom:{style:"hair",color:{argb:"FFE2E8F0"}}}})});const x=o||ac(d,r);if(Object.keys(x).length){const A=c.getRow(b+1+r.length);d.forEach((S,P)=>{const E=A.getCell(P+1);P===0?E.value=`סה״כ ${r.length}`:x[S.key]!==void 0&&(E.value=Number(x[S.key]),E.numFmt=S.type==="money"?"#,##0.00":S.type==="num"?"#,##0":"#,##0.000"),E.font={bold:!0,size:11},E.fill={type:"pattern",pattern:"solid",fgColor:{argb:"FFEFF2F6"}},E.alignment={horizontal:pl.has(S.type)?"left":"right",vertical:"middle",readingOrder:"rtl"}})}const g=await u.xlsx.writeBuffer(),y=new Blob([g],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),$=URL.createObjectURL(y),O=document.createElement("a");O.href=$,O.download=`${t||"דוח"}.xlsx`,document.body.appendChild(O),O.click(),O.remove(),setTimeout(()=>URL.revokeObjectURL($),1e3)}const hl=new Set(["num","money","cube","dec3"]),Um=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),lc=`
14@media print {
15  @page { size: A4 landscape; margin: 10mm; }
16  body * { visibility: hidden !important; }
17  #billing-report, #billing-report * { visibility: visible !important; }
18  #billing-report { position: absolute; inset: 0; width: 100%; padding: 0; }
19  .no-print { display: none !important; }
20  .print-only { display: block !important; }
21  #billing-report table { font-size: 10px; }
22  #billing-report thead { display: table-header-group; }
23  #billing-report tr { break-inside: avoid; }
24  #billing-report .card, #billing-report .rounded-2xl { box-shadow: none !important; }
25}
26.print-only { display: none; }
27/* The table and the filter row steer with buttons, not with a scrollbar that
28   sits under the fold and that nobody on a laptop trackpad finds. */
29.report-scroll { scrollbar-width: none; -ms-overflow-style: none; }
30.report-scroll::-webkit-scrollbar { width: 0; height: 0; }
31`;function ma({anchorRef:t,open:s,onClose:n,children:a,width:l}){const r=i.useRef(null),[o,p]=i.useState(null),u=i.useCallback(()=>{const d=t.current;if(!d)return;const c=d.getBoundingClientRect(),m=Number.isFinite(l)?l:0,h=c.right-8;if(m&&h<m&&window.innerWidth-c.left-8>=m){p({top:c.bottom+4,left:Math.max(8,c.left),maxWidth:window.innerWidth-c.left-8});return}p({top:c.bottom+4,right:Math.max(8,window.innerWidth-c.right),maxWidth:Math.max(h,m)})},[t,l]);return i.useLayoutEffect(()=>{if(!s)return;u();const d=()=>u();return window.addEventListener("scroll",d,!0),window.addEventListener("resize",d),()=>{window.removeEventListener("scroll",d,!0),window.removeEventListener("resize",d)}},[s,u]),i.useEffect(()=>{if(!s)return;const d=m=>{var h,b;(h=r.current)!=null&&h.contains(m.target)||(b=t.current)!=null&&b.contains(m.target)||n()},c=m=>{m.key==="Escape"&&n()};return document.addEventListener("mousedown",d),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",c)}},[s,n,t]),!s||!o?null:Pt.createPortal(e.jsx("div",{ref:r,dir:"rtl",style:{position:"fixed",top:o.top,right:o.right,left:o.left,maxWidth:o.maxWidth,width:l},className:"z-[60] bg-white rounded-2xl border border-slate-200 shadow-xl",children:a}),document.body)}const Yl="text-[12.5px] font-extrabold text-slate-600 whitespace-nowrap";function jr({label:t,wide:s,children:n}){return e.jsxs("label",{className:`block flex-none ${s?"flex-1 min-w-[8rem] max-w-[15rem]":""}`,children:[e.jsx("span",{className:`block mb-1.5 ${Yl}`,children:t}),n]})}const Ia="h-10 rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-700 focus:outline-none focus:border-teal-500 focus:ring-4 focus:ring-teal-50 transition-colors",rc=Symbol("countTotal");function Te(t=[],s={}){const n={};for(const a of Object.keys(s))n[a]=0;
31for(const a of t)for(const[l,r]of Object.entries(s))r(a)&&(n[l]+=1);return Object.defineProperty(n,rc,{value:t.length,enumerable:!1}),n}function ic(t=[],s,n,a){if(!s)return t;const l=Number.isFinite(a)?a:s[rc],r=t.filter(p=>{const u=String(p.v??"");return u===""||u===String(n??"")?!0:(s[u]??0)>0}),o=r.filter(p=>String(p.v??"")!=="");return o.length===0?[]:o.length===1&&Number.isFinite(l)&&(s[String(o[0].v)]??0)===l?[]:r}function Ae({label:t,hint:s,value:n,onChange:a,options:l=[],counts:r,total:o,inline:p}){const u=l.some(m=>String(m.v??"")===""),d=ic(l,r,n,o).filter(m=>!(u&&String(m.v??"")===""));if(d.length===0)return null;const c=d.map(m=>{const h=String(n??"")===String(m.v),b=()=>a(h&&u?"":m.v);return e.jsx("button",{type:"button",onClick:b,"aria-pressed":h,title:h&&u?"לחצו שוב להצגת הכל":m.l,className:`h-9 rounded-xl text-[13px] font-bold border transition-colors whitespace-nowrap ${p?"px-3":"px-3.5"} ${h?"bg-teal-600 border-teal-600 text-white shadow-sm":"bg-white border-slate-200 text-slate-600 hover:border-slate-300"}`,children:m.l},String(m.v))});return p?e.jsxs("div",{className:"flex items-center gap-1.5 flex-none",children:[t&&e.jsx("span",{className:`${Yl} px-0.5`,children:t}),c]}):e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2 mb-1.5",children:[e.jsx("span",{className:Yl,children:t}),s&&e.jsx("span",{className:"text-[11px] text-slate-400 whitespace-nowrap",children:s})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:c})]})}const Vl=[{v:"month",l:"החודש"},{v:"prev",l:"חודש קודם"},{v:"q",l:"3 חודשים"},{v:"year",l:"השנה"}],ds=t=>`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;function Dn(t,s=new Date){const n=s.getFullYear(),a=s.getMonth();return t==="month"?{from:ds(new Date(n,a,1)),to:ds(new Date(n,a+1,0))}:t==="prev"?{from:ds(new Date(n,a-1,1)),to:ds(new Date(n,a,0))}:t==="q"?{from:ds(new Date(n,a-2,1)),to:ds(new Date(n,a+1,0))}:t==="year"?{from:`${n}-01-01`,to:`${n}-12-31`}:{from:"",to:""}}const oc=({label:t,value:s,onChange:n,options:a=[],counts:l,total:r})=>{const o=ic(a,l,s,r);return o.length===0?null:e.jsx(jr,{label:t,children:e.jsx("select",{className:`${Ia} min-w-[8rem]`,value:s,onChange:p=>n(p.target.value),children:o.map(p=>e.jsx("option",{value:p.v,children:p.l},p.v))})})},cc=({label:t,value:s,onChange:n,placeholder:a})=>e.jsx(jr,{label:t,children:e.jsx("input",{type:"number",className:`${Ia} w-24`,value:s,placeholder:a,onChange:l=>n(l.target.value)})}),Zn=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],Hm=["א","ב","ג","ד","ה","ו","ש"],ba=t=>`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,dc=t=>{const s=String(t||"").slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(s))return null;const[n,a,l]=s.split("-").map(Number);return new Date(n,a-1,l)},Ve=t=>{const s=dc(t);return s?`${String(s.getDate()).padStart(2,"0")}.${String(s.getMonth()+1).padStart(2,"0")}.${String(s.getFullYear()).slice(2)}`:""},Ym=(t,s)=>{const a=new Date(t,s,1).getDay(),l=new Date(t,s+1,0).getDate(),r=Array.from({length:a},()=>null);for(let o=1;o<=l;o++)r.push(new Date(t,s,o));for(;r.length%7;)r.push(null);return r};function uc({from:t,to:s,onChange:n,onDone:a}){const[l,r]=i.useState(()=>{const c=dc(t)||new Date;return new Date(c.getFullYear(),c.getMonth(),1)}),o=c=>{const m=ba(c);if(!t||t&&s){n({from:m,to:""});return}if(m<t){n({from:m,to:t}),a();return}n({from:t,to:m}),a()},p=ba(new Date),u=({base:c})=>e.jsxs("div",{className:"w-[15.5rem]",children:[e.jsxs("p",{className:"text-center text-sm font-bold text-teal-700 mb-2",children:[Zn[c.getMonth()]," ",c.getFullYear()]}),e.jsxs("div",{className:"grid grid-cols-7 gap-y-1 text-center",children:[Hm.map(m=>e.jsx("span",{className:"text-[11px] font-bold text-slate-400",children:m},m)),Ym(c.getFullYear(),c.getMonth()).map((m,h)=>{if(!m)return e.jsx("span",{},h);const b=ba(m),f=b===t,x=b===s,g=t&&s&&b>t&&b<s;return e.jsx("button",{type:"button",onClick:()=>o(m),className:`h-8 w-8 mx-auto text-[13px] rounded-full transition-colors
32                ${f||x?"bg-teal-600 text-white font-bold":g?"bg-teal-50 text-teal-800":"text-slate-700 hover:bg-slate-100"}
33                ${b===p&&!f&&!x?"ring-1 ring-teal-400":""}`,children:m.getDate()},b)})]})]}
33),d=new Date(l.getFullYear(),l.getMonth()+1,1);return e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:[{k:"from",l:"מתאריך",v:t},{k:"to",l:"עד תאריך",v:s}].map(c=>e.jsxs("span",{className:"flex items-center gap-2 h-10 px-3 rounded-xl border border-slate-200 text-sm min-w-[8.5rem]",children:[e.jsx("span",{className:c.v?"text-slate-800":"text-slate-400",children:c.v?Ve(c.v):c.l}),c.v&&e.jsx("button",{type:"button",className:"text-slate-400 hover:text-slate-700",onClick:()=>n({from:c.k==="from"?"":t,to:c.k==="to"?"":s}),children:e.jsx($e,{className:"w-3.5 h-3.5"})})]},c.k))}),e.jsxs("div",{className:"flex items-start gap-6",children:[e.jsx("button",{type:"button",onClick:()=>r(new Date(l.getFullYear(),l.getMonth()-1,1)),className:"w-7 h-7 rounded-full flex items-center justify-center text-slate-400 hover:bg-slate-100 mt-1",children:e.jsx(oa,{className:"w-4 h-4"})}),e.jsx(u,{base:l}),e.jsx(u,{base:d}),e.jsx("button",{type:"button",onClick:()=>r(new Date(l.getFullYear(),l.getMonth()+1,1)),className:"w-7 h-7 rounded-full flex items-center justify-center text-slate-400 hover:bg-slate-100 mt-1",children:e.jsx(lt,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 pt-3 border-t border-slate-100",children:[[{l:"החודש",from:new Date(new Date().getFullYear(),new Date().getMonth(),1),to:new Date},{l:"חודשיים אחרונים",from:new Date(new Date().getFullYear(),new Date().getMonth()-1,1),to:new Date},{l:"השנה",from:new Date(new Date().getFullYear(),0,1),to:new Date}].map(c=>e.jsx("button",{type:"button",onClick:()=>{n({from:ba(c.from),to:ba(c.to)}),a()},className:"h-8 px-3 rounded-full border border-slate-200 text-xs text-slate-600 hover:bg-slate-50",children:c.l},c.l)),e.jsx("button",{type:"button",onClick:()=>{n({from:"",to:""}),a()},className:"h-8 px-3 rounded-full text-xs text-slate-400 hover:text-slate-700 mr-auto",children:"ניקוי"})]})]})}function Vm({label:t="טווח תאריכים",from:s,to:n,onChange:a,placeholder:l="כל התאריכים"}){const[r,o]=i.useState(!1),p=i.useRef(null),u=s||n?`${Ve(s)||"…"} – ${Ve(n)||"…"}`:"";return e.jsxs("div",{className:"block flex-none",children:[e.jsx("span",{className:"block text-[11px] font-bold text-slate-500 mb-1 whitespace-nowrap",children:t}),e.jsxs("div",{className:"relative",ref:p,children:[e.jsxs("button",{type:"button",onClick:()=>o(d=>!d),className:`${Ia} w-[13.5rem] flex items-center gap-2 text-right`,children:[e.jsx(vs,{className:"w-4 h-4 text-slate-400 flex-none"}),e.jsx("span",{className:`flex-1 truncate ${u?"text-slate-700":"text-slate-400"}`,children:u||l}),u?e.jsx($e,{className:"w-4 h-4 text-slate-400 flex-none hover:text-slate-700",onClick:d=>{d.stopPropagation(),a({from:"",to:""})}}):e.jsx(Jt,{className:"w-4 h-4 text-slate-400 flex-none"})]}),e.jsx(ma,{anchorRef:p,open:r,onClose:()=>o(!1),children:e.jsx(uc,{from:s,to:n,onChange:a,onDone:()=>o(!1)})})]})]})}function Gm({label:t="תקופה",value:s,from:n,to:a,onChange:l,counts:r,inline:o}){const[p,u]=i.useState(!1),d=i.useRef(null),c=s==="custom",m=c&&(n||a),h=b=>`h-9 rounded-xl text-[13px] font-bold border transition-colors whitespace-nowrap inline-flex items-center gap-1.5 ${o?"px-3":"px-3.5"} ${b?"bg-teal-600 border-teal-600 text-white shadow-sm":"bg-white border-slate-200 text-slate-600 hover:border-slate-300"}`;return e.jsxs("div",{className:o?"flex items-center gap-1.5 flex-none":"min-w-0",children:[o?t&&e.jsx("span",{className:"text-[11px] font-bold text-slate-400 whitespace-nowrap px-0.5",children:t}):e.jsx("div",{className:"flex items-baseline gap-2 mb-1.5",children:e.jsx("span",{className:"text-[11px] font-bold text-slate-500 whitespace-nowrap",children:t})}),e.jsxs("div",{className:o?"flex items-center gap-1.5":"flex flex-wrap items-center gap-1.5",children:[Vl.filter(b=>!r||b.v===s||(r[b.v]??0)>0).map(b=>e.jsx("button",{type:"button",className:h(s===b.v),onClick:()=>{u(!1),l({span:b.v,...Dn(b.v)})},children:b.l},b.v)),e.jsxs("span",{className:"relative inline-block",ref:d,children:[e.jsxs("button",{type:"button",className:h(c),onClick:()=>u(b=>!b),children:[e.jsx(vs,{className:`w-4 h-4 flex-none ${c?"text-white/80":"text-slate-400"}`}),m?`${Ve(n)||"…"} – ${Ve(a)||"…"}`:"בחר",m&&e.jsx($e,{className:"w-3.5 h-3.5 flex-none opacity-70 hover:opacity-100",onClick:b=>{b.stopPropagation(),u(!1),l({span:"month",...Dn("month")})}})]}),e.jsx(ma,{anchorRef:d,open:p,onClose:()=>
33u(!1),children:e.jsx(uc,{from:c?n:"",to:c?a:"",onChange:({from:b,to:f})=>l({span:"custom",from:b,to:f}),onDone:()=>u(!1)})})]})]})]})}const Gl=(t,s)=>`${t}-${String(s+1).padStart(2,"0")}`;function xi(t){const[s,n]=String(t||"").split("-").map(Number);return!s||!n?{from:"",to:""}:{from:`${s}-${String(n).padStart(2,"0")}-01`,to:ds(new Date(s,n,0))}}const xs=t=>{const[s,n]=String(t||"").split("-").map(Number);return s&&n?`${Zn[n-1]} ${s}`:""},Xm=t=>{const[s,n]=String(t||"").split("-").map(Number);return s&&n?`${Zn[n-1]} ${String(s).slice(-2)}`:""};function mc({label:t="תקופת הדוח",value:s,onChange:n,monthsWithData:a,allowAll:l=!1}){const r=i.useRef(null),[o,p]=i.useState(!1),[u]=String(s||"").split("-").map(Number),[d,c]=i.useState(u||new Date().getFullYear());i.useEffect(()=>{o&&c(u||new Date().getFullYear())},[o,u]);const m=b=>!a||a.has(b),h=a&&![...Array(12).keys()].some(b=>m(Gl(d,b)));return e.jsxs(jr,{label:t,children:[e.jsxs("button",{ref:r,type:"button",onClick:()=>p(b=>!b),"aria-haspopup":"dialog","aria-expanded":o,className:`${Ia} h-9 inline-flex items-center gap-2 font-bold text-[13px] ${o?"border-teal-500 ring-4 ring-teal-50":""}`,children:[e.jsx(vs,{className:"w-4 h-4 flex-none text-teal-600"}),e.jsx("span",{className:"whitespace-nowrap",children:Xm(s)||(l?"כל התקופות":"בחירת חודש")}),e.jsx(Jt,{className:`w-3.5 h-3.5 flex-none text-slate-400 transition-transform ${o?"rotate-180":""}`})]}),e.jsx(ma,{anchorRef:r,open:o,onClose:()=>p(!1),width:272,children:e.jsxs("div",{className:"p-3",role:"dialog","aria-label":t,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2.5",children:[e.jsx("button",{type:"button","aria-label":"שנה קודמת",title:"שנה קודמת",onClick:()=>c(b=>b-1),className:"w-8 h-8 rounded-lg grid place-items-center text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(oa,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-[14px] font-black text-slate-800 tabular-nums",children:d}),e.jsx("button",{type:"button","aria-label":"שנה הבאה",title:"שנה הבאה",onClick:()=>c(b=>b+1),className:"w-8 h-8 rounded-lg grid place-items-center text-slate-400 hover:bg-slate-100 hover:text-slate-700",children:e.jsx(lt,{className:"w-4 h-4"})})]}),l&&e.jsx("button",{type:"button",onClick:()=>{n(""),p(!1)},"aria-pressed":!s,className:`w-full h-9 mb-2 rounded-xl text-[12.5px] font-bold border transition-colors ${s?"bg-white border-slate-200 text-slate-700 hover:border-teal-300 hover:text-teal-700":"bg-teal-600 border-teal-600 text-white shadow-sm"}`,children:"כל התקופות"}),h?e.jsxs("p",{className:"text-[12.5px] text-slate-400 text-center py-4",children:["אין נתונים בשנת ",d,"."]}):e.jsx("div",{className:"grid grid-cols-3 gap-1.5",role:"group",children:Zn.map((b,f)=>{const x=Gl(d,f),g=x===s;return!g&&!m(x)?null:e.jsx("button",{type:"button",title:b,"aria-pressed":g,onClick:()=>{n(x),p(!1)},className:`h-9 rounded-xl text-[12.5px] font-bold border transition-colors ${g?"bg-teal-600 border-teal-600 text-white shadow-sm":"bg-white border-slate-200 text-slate-700 hover:border-teal-300 hover:text-teal-700"}`,children:b},b)})})]})})]})}const Zm="h-9 px-3.5 rounded-xl bg-white border border-slate-200 text-slate-600 text-[13px] font-bold inline-flex items-center gap-1.5 hover:border-slate-300 disabled:opacity-40 transition-colors";function Qm({open:t,onClose:s,columns:n,hidden:a,onToggle:l,onAll:r,onReset:o}){const p=n.length-a.size;i.useEffect(()=>{if(!t)return;const d=c=>{c.key==="Escape"&&s()};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t,s]);const u=d=>{s()};return e.jsx(e.Fragment,{children:t&&Pt.createPortal(e.jsx("div",{dir:"rtl",className:"fixed inset-0 z-[70] bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>u(),children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] flex flex-col",onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 p-5 pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-lg font-black text-slate-900",children:"בחירת עמודות"}),e.jsx("p",{className:"text-[12.5px] text-slate-500 mt-0.5",children:`מוצגות ${p} מתוך ${n.length} עמודות. הבחירה נשמרת ותחזור גם אחרי רענון.`})]}),e.jsx("button",{type:"button",onClick:()=>u(),"aria-label":"סגירה",className:"w-9 h-9 rounded-full border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50 flex-none",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-2 grid sm:grid-cols-2 gap-x-2 content-start",children:n.map(d=>{const c=!a.has(d.key);return e.jsxs("button",{type:"button",onClick:()=>l(d.key),className:`flex items-center gap-2.5 px-2.5 py-2 rounded-xl text-sm text-right transition-colors ${c?"hover:bg-teal-50/60":"hover:bg-slate-50"}`,children:[e.jsx("span",{className:`w-[18px] h-[18px] rounded-md border flex items-center justify-center flex-none ${c?"bg-teal-500 border-teal-500 text-white":"border-slate-300"}`,children:c&&e.jsx(ye,{className:"w-3 h-3"})}),e.jsx("span",{className:`flex-1 truncate ${c?"text-slate-700 font-semibold":"text-slate-400"}`,children:d.header})]},d.key)})}),e.jsxs("div",{className:"flex items-center gap-2 p-4 border-t border-slate-100",children:[a.size>0&&e.jsx("button",{type:"button",onClick:r,className:"h-10 px-4 roun
33ded-xl border border-teal-200 bg-teal-50 text-teal-700 text-sm font-bold hover:bg-teal-100 transition-colors",children:"סמן הכל"}),e.jsx("button",{type:"button",onClick:o,className:"h-10 px-4 rounded-xl border border-slate-200 text-slate-500 text-sm font-bold hover:bg-slate-50 transition-colors",children:"איפוס לברירת המחדל"}),e.jsx("button",{type:"button",onClick:()=>u(),className:"h-10 px-5 rounded-xl bg-slate-900 text-white text-sm font-bold hover:bg-slate-800 transition-colors mr-auto",children:"סיום"})]})]})}),document.body)})}function Jm({columns:t,hidden:s,onToggleColumn:n,onAllColumns:a,onResetColumns:l,onExcel:r,onPdf:o,pdfBusy:p,hasRows:u,compact:d}){const c=i.useRef(null),[m,h]=i.useState(!1),[b,f]=i.useState(!1),x=t.length-s.size,g=t.length>4,y=({Icon:$,iconClass:O,title:A,note:S,onClick:P,disabled:E})=>e.jsxs("button",{type:"button",role:"menuitem",disabled:E,onClick:()=>{h(!1),P()},className:"w-full text-right flex items-start gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 disabled:opacity-40 disabled:hover:bg-transparent transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-teal-400",children:[e.jsx("span",{className:"w-8 h-8 rounded-lg bg-slate-50 grid place-items-center flex-none mt-0.5",children:e.jsx($,{className:`w-4 h-4 ${O}`})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800",children:A}),e.jsx("span",{className:"block text-[11.5px] text-slate-500 leading-snug",children:S})]})]});return e.jsxs(e.Fragment,{children:[e.jsxs("button",{ref:c,type:"button",onClick:()=>h($=>!$),"aria-haspopup":"menu","aria-expanded":m,className:`${Zm} no-print ${d?"":"h-10"} ${m?"border-slate-300 bg-slate-50":""}`,children:[e.jsx(Hn,{className:"w-4 h-4 flex-none text-teal-600"}),"פעולות",e.jsx(Jt,{className:`w-3.5 h-3.5 flex-none text-slate-400 transition-transform ${m?"rotate-180":""}`})]}),e.jsx(ma,{anchorRef:c,open:m,onClose:()=>h(!1),width:288,children:e.jsxs("div",{className:"p-2",role:"menu",children:[g&&e.jsx(y,{Icon:Md,iconClass:"text-teal-600",title:"בחירת עמודות",note:`מוצגות ${x} מתוך ${t.length}. הבחירה נשמרת.`,onClick:()=>f(!0)}),e.jsx(y,{Icon:pr,iconClass:"text-emerald-600",title:"ייצוא לאקסל",note:"כל העמודות, גם המוסתרות, לפי הסינון והמיון הנוכחיים.",onClick:r,disabled:!u}),e.jsx(y,{Icon:p?Ie:go,iconClass:`text-rose-600 ${p?"animate-spin":""}`,title:p?"מכין PDF…":"ייצוא ל-PDF",note:"הדוח כקובץ, בדיוק כפי שהוא נראה בהדפסה.",onClick:o,disabled:!u||p}),e.jsx(y,{Icon:yo,iconClass:"text-slate-500",title:"הדפסה",note:"עם לוגו ופרטי היישוב, ובלי תפריטי המערכת.",onClick:()=>window.print(),disabled:!u})]})}),e.jsx(Qm,{open:b,onClose:()=>f(!1),columns:t,hidden:s,onToggle:n,onAll:a,onReset:l})]})}function ex({value:t,placeholder:s,onChange:n,compact:a}){const l=i.useRef(null),r=t||"",o=a?"h-9":"h-10";return e.jsxs("span",{className:`relative block flex-1 min-w-[7rem] max-w-[17rem] ${o}`,children:[e.jsx(qt,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none z-10","aria-hidden":"true"}),e.jsx("input",{ref:l,value:r,placeholder:s||"חיפוש","aria-label":s||"חיפוש בדוח",onChange:p=>n(p.target.value),onKeyDown:p=>{p.key==="Escape"&&r&&(n(""),p.stopPropagation())},className:`${Ia} ${o} w-full pr-9 pl-8 ${a?"text-[13px]":""}`}),r.length>0&&e.jsx("button",{type:"button","aria-label":"ניקוי החיפוש",onMouseDown:p=>p.preventDefault(),onClick:()=>{var p;n(""),(p=l.current)==null||p.focus()},className:"absolute left-2 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full grid place-items-center text-slate-400 hover:text-slate-700 hover:bg-slate-100",children:e.jsx($e,{className:"w-3.5 h-3.5"})})]})}const tx=t=>{let s=String(t||"").replace(/\D/g,"");return s.startsWith("0")?s=`972${s.slice(1)}`:s.length===9&&(s=`972${s}`),s};function sx({phone:t,name:s}){const[n,a]=i.useState(!1),l=i.useRef(null);if(!t)return e.jsx("span",{className:"text-slate-300",children:"—"});const r=tx(t);return e.jsxs("span",{className:"inline-block",ref:l,children:[e.jsx("button",{type:"button",onClick:()=>a(o=>!o),title:`${s||""} ${t}`.trim(),className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-emerald-600 bg-emerald-50 hover:bg-emerald-100 transition-colors",children:e.jsx(gn,{className:"w-4 h-4"})}),e.jsx(ma,{anchorRef:l,open:n,onClose:()=>a(!1),width:"13rem",children:e.jsxs("div",{className:"p-3 text-right",children:[s&&e.jsx("p",{className:"text-xs font-bold text-slate-700 truncate",children:s}),e.jsx("p",{className:"text-sm font-bold text-slate-900 tabular-nums",dir:"ltr",children:t}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-2",children:[e.jsxs("a",{href:`https://wa.me/${r}`,target:"_blank",rel:"noopener noreferrer",className:"flex-1 h-8 rounded-lg bg-emerald-600 text-white text-xs font-bold inline-flex items-center justify-center gap-1",children:[e.jsx(gn,{className:"w-3.5 h-3.5"})," WhatsApp"]}),e.jsx("a",{href:`tel:${t}`,className:"w-8 h-8 rounded-lg border border-slate-200 inline-flex items-center justify-center text-slate-500 hover:bg-slate-50",children:e.jsx(ao,{className:"w-3.5 h-3.5"})})]})]})})]})}function ax(t){if(t.scrollLeft<0)return-1;if(t.scrollLeft>0)return 1;t.scrollLeft=-1;const s=t.scrollLeft<0?-1:1;return t.scrollLeft=0,s}function nx({children:t,className:s=""}){const n=i.useRef(null),[a,l]=i.useState({show:!1,start:!0,end:!1,pct:0}),r=i.useCallback(()=>{const u=n.current;if(!u)return;const d=u.scrollWidth-u.clientWidth,c=Math.abs(u.scrollLeft),m=(()=>{const h=u.getBoundingClientRect();return h.bottom>120&&h.top<window.innerHeight-40})();l({show:d>8&&m,start:c<=2,end:c>=d-2,pct:d>0?Math.min(100,Math.round(c/d*100)):0})},[]);i.useEffect(()=>{const u=n.current;if(!u)return;r();const d=new ResizeObserver(r);return d.observe(u),u.firstElementChild&&d.observe(u.firstElementChild),u.addEventListener("scroll",r,{passive:!0}),window.addEventListener("scroll",r,{passive:!0}),window.addEventListener("resize",r),()=>{d.disconnect(),u.removeEventListener("scroll",r),window.removeEventListener("scroll",r),window.removeEventListener("resize",r)}},[r,t]);const o=u=>{const d=n.current;if(!d)return;const c=ax(d);d.scrollBy({left:u*c*d.clientWidth*.8,behavior:"smooth"})},p="w-10 h-10 rounded-full flex items-center justify-center transition-colors disabled:opacity-30 disabled:cursor-default";return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:n,className:`overflow-x-auto report-scroll ${s}`,children:t}),a.show&&Pt.createPortal(e.jsxs("div",{dir:"rtl",className:"no-print fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-1 bg-white/95 backdrop-blur border border-slate-200 shadow-xl rounded-full p-1.5",children:[e.jsx("button",{type:"button",onClick:()=>o(-1),disabled:a.start,title:"הזזה ימינה",className:`${p} text-teal-700 hover:bg-teal-50`,children:e.jsx(oa,{className:"w-5 h-5"})}),e.jsx("span",{className:"w-16 h-1.5 rounded-full bg-slate-100 overflow-hidden mx-1",children:e.jsx("span",{className:"block h-full bg-teal-500 rounded-full transition-all",style:{width:`${Math.max(12,a.pct)}%`}})}),e.jsx("button",{type:"button",onClick:()=>o(1),disabled:a.end,title:"הזזה שמאלה",className:`${p} text-teal-700 hover:bg-teal-50`,children:e.jsx(lt,{className:"w-5 h-5"})})]}),document.body)]})}const lx=new Set(["num","money","dec3","dec2","pct"]),pi=typeof Intl<"u"?new Intl.Collator("he",{numeric:!0,sensitivity:"base"}):null;function rx(t,s,n){if(!(n!=null&&n.key))return t;const a=s.find(p=>p.key===n.key);if(!a)return t;const l=n.dir==="desc"?-1:1,r=lx.has(a.type),o=p=>{const u=qa(a,p);return u==null||u===""?null:r?Number(u):String(u)};return[...t].sort((p,u)=>{const d=o(p),c=o(u);return d===null&&c===null?0:d===null?1:c===null?-1:r?(d-c)*l:(pi?pi.compare(d,c):String(d).localeCompare(c,"he"))*l})}const ix=t=>t.sortable===!0||t.sortable!==!1&&!t.render;function ox({columns:t,rows:s,totals:n,sort:a,onSort:l,empty:r="אין רשומות התואמות את הסינון"}){const o=t.filter(c=>!c.hide);if(!s.length)return e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-12 text-center",children:[e.jsx(hr,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r})]});const p=n||ac(o,s),u=Object.keys(p).length>0,d=c=>`text-right${hl.has(c.type)?" tabular-nums":""}`;return e.jsx("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:e.jsx(nx,{children:e.jsxs("table",{className:"w-full text-sm border-collapse",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsx("tr",{children:o.map(c=>{const m=(a==null?void 0:a.key)===c.key;if(!l||!ix(c))return e.jsx("th",{className:`px-3 py-2.5 font-semibold whitespace-nowrap ${d(c)}`,children:c.header},c.key);const h=m?a.dir==="desc"?_o:lo:jo;return e.jsx("th",{className:`px-3 py-2.5 font-semibold whitespace-nowrap ${d(c)} no-print-hover`,children:e.jsxs("button",{type:"button",onClick:()=>l(c.key),title:`מיון לפי ${c.header}`,className:`group inline-flex items-center gap-1 ${m?"text-teal-700":"hover:text-slate-700"}`,children:[c.header,e.jsx(h,{className:`w-3 h-3 flex-none transition-opacity ${m?"opacity-100":"opacity-25 group-hover:opacity-70"}`})]})},c.key)})})}),e.jsx("tbody",{children:s.map((c,m)=>e.jsx("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60 even:bg-slate-50/30",children:o.map(h=>
33e.jsx("td",{className:`px-3 py-2 ${d(h)} ${h.strong?"font-bold":""} ${h.muted?"text-slate-500":""} ${h.clamp?"max-w-[12rem] truncate":"whitespace-nowrap"}`,dir:hl.has(h.type)?"ltr":void 0,title:h.clamp?String(qa(h,c)??""):void 0,children:h.render?h.render(c):Fn(h,c)},h.key))},c.id||m))}),u&&e.jsx("tfoot",{children:e.jsx("tr",{className:"border-t-2 border-slate-200 bg-slate-50 font-bold",children:o.map((c,m)=>e.jsx("td",{className:`px-3 py-2.5 ${d(c)}`,dir:hl.has(c.type)?"ltr":void 0,children:m===0?`סה״כ ${Um(s.length)}`:p[c.key]===void 0?"":Fn(c,{[c.key]:p[c.key]})},c.key))})})]})})})}function cx({stats:t}){return t!=null&&t.length?e.jsx("div",{className:`grid grid-cols-2 gap-3 ${t.length>=5?"lg:grid-cols-5":"sm:grid-cols-4"}`,children:t.map(s=>{const n=s.icon;return e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-4 flex items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[13px] text-slate-500 text-right truncate",children:s.label}),e.jsxs("p",{className:"text-[22px] font-black text-slate-900 tabular-nums text-right leading-tight mt-0.5",children:[e.jsx("span",{dir:"ltr",className:"inline-block",children:s.value}),s.currency&&e.jsx("span",{className:"text-[16px] font-extrabold text-slate-500",children:" ₪"})]}),s.sub&&e.jsx("p",{className:"text-[11px] text-slate-400 text-right truncate",children:s.sub})]}),n&&e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-none ${s.tone||"text-teal-600 bg-teal-50"}`,children:e.jsx(n,{className:"w-[22px] h-[22px]"})})]},s.label)})}):null}function ss({title:t,subtitle:s,settings:n,chips:a=[],filters:l,stats:r,columns:o,rows:p=[],totals:u,fileName:d,loading:c,empty:m,children:h,footNote:b,defaultSort:f,search:x,after:g,banner:y,hero:$,inlineFilters:O}){const A=o.map(K=>K.key).join("|"),S=`report-cols:${d||t}:${A.length}:${A.slice(0,80)}`,P=i.useCallback(()=>{try{const K=localStorage.getItem(S);if(K!==null)return new Set(JSON.parse(K))}catch{}return new Set(o.filter(K=>K.off).map(K=>K.key))},[S,o]),[E,k]=i.useState(P);i.useEffect(()=>{k(P())},[P]);const C=K=>{try{localStorage.setItem(S,JSON.stringify([...K]))}catch{}return K},w=i.useMemo(()=>o.map(K=>E.has(K.key)?{...K,hide:!0}:K),[o,E]),[_,T]=i.useState(f||null);i.useEffect(()=>{T(f||null)},[A]);const M=K=>T(Z=>(Z==null?void 0:Z.key)===K?{key:K,dir:Z.dir==="asc"?"desc":"asc"}:{key:K,dir:"asc"}),B=i.useMemo(()=>rx(p,o,_),[p,o,_]),R=K=>k(Z=>{const H=new Set(Z);return H.has(K)?H.delete(K):H.add(K),C(H)}),j=i.useMemo(()=>
33[...a.filter(Boolean),`הופק ${new Date().toLocaleDateString("he-IL")} ${new Date().toLocaleTimeString("he-IL",{hour:"2-digit",minute:"2-digit"})}`,`${p.length} רשומות`],[a,p.length]),q=i.useRef(null),[L,N]=i.useState(!1),v=async()=>{if(!p.length){W.error("אין נתונים לייצוא");return}N(!0);try{const{exportNodePdf:K}=await In(async()=>{const{exportNodePdf:Z}=await import("./reportPdf-BRmDXPVe.js");return{exportNodePdf:Z}},__vite__mapDeps([3,1,2]));await K(q.current,d||t),W.success("קובץ ה-PDF נוצר")}catch{W.error("שגיאה ביצירת ה-PDF")}finally{N(!1)}},F=async()=>{if(!p.length){W.error("אין נתונים לייצוא");return}try{await nc({fileName:d||t.replace(/\s+/g,"_"),sheetName:t,title:t,meta:j,columns:o,rows:B,totals:u})}catch{W.error("שגיאה בייצוא")}};return e.jsxs("div",{id:"billing-report",ref:q,children:[e.jsx("style",{children:lc}),e.jsxs("div",{className:"min-w-0 hidden print:block mb-2",children:[e.jsx("h3",{className:"text-xl font-black text-slate-900",children:t}),s&&e.jsx("p",{className:"text-[13px] text-slate-500 mt-0.5",children:s}),e.jsxs("div",{className:"print-only mt-1 text-[11px] text-slate-500",children:[[n==null?void 0:n.legal_name,(n==null?void 0:n.business_number)&&`ח.פ. ${n.business_number}`,n==null?void 0:n.address].filter(Boolean).join(" · "),e.jsx("div",{children:j.join("  ·  ")})]})]}),$?e.jsx("div",{className:"mb-4",children:$}):null,!c&&((r==null?void 0:r.length)>0||y)&&e.jsxs("div",{className:"space-y-4 mb-4",children:[y,e.jsx(cx,{stats:r})]}),e.jsx("div",{className:`no-print rounded-2xl border border-slate-200 bg-white shadow-sm mb-4 ${$?"p-4":"p-5"}`,children:e.jsxs("div",{className:"flex flex-wrap items-end gap-x-6 gap-y-4 no-print",children:[l,x&&e.jsx(ex,{value:x.value,placeholder:x.placeholder,onChange:x.onChange,compact:!!O}),e.jsx("span",{className:"flex items-center flex-none mr-auto gap-2",children:e.jsx(Jm,{columns:o,hidden:E,onToggleColumn:R,onAllColumns:()=>k(C(new Set)),onResetColumns:()=>{try{localStorage.removeItem(S)}catch{}k(new Set(o.filter(K=>K.off).map(K=>K.key)))},onExcel:F,onPdf:v,pdfBusy:L,hasRows:p.length>0,compact:!!O})})]})}),c?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-teal-500 rounded-full animate-spin"})}):e.jsxs("div",{className:"space-y-4",children:[h,e.jsx(ox,{columns:w,rows:B,totals:u,sort:_,onSort:M,empty:m}),g,b&&e.jsx("p",{className:"text-[11px] text-slate-400",children:b})]})]})}const bl=300,aa=async(t,s)=>{const n=await D.functions.invoke("waterImport",{...s,kibbutz_id:t});return(n==null?void 0:n.data)??n??{}},$t=t=>new Intl.NumberFormat("he-IL").format(t),Xl=t=>oo(t,"",{decimals:2}).trim(),ls=t=>t==null||t===""?"—":Number(t).toFixed(3).replace(/\.?0+$/,""),xc=t=>{if(!t)return"—";const[s,n,a]=String(t).slice(0,10).split("-");return a?`${a}/${n}/${s}`:t},hi=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"];function dx(t,s){if(!t)return"";const n=new Date(`${t}T00:00:00`),a=s?new Date(`${s}T00:00:00`):n;s&&a.getDate()===1&&a.setDate(0);const l=[hi[n.getMonth()]];return(a.getMonth()!==n.getMonth()||a.getFullYear()!==n.getFullYear())&&l.push(hi[a.getMonth()]),`${l.join("–")} ${a.getFullYear()}`}const On={draft:{label:"טיוטה",cls:"bg-slate-100 text-slate-600"},pending:{label:"ממתין לאישור",cls:"bg-amber-50 text-amber-700"},approved:{label:"אושר",cls:"bg-emerald-50 text-emerald-700"},partially_approved:{label:"אושר חלקית",cls:"bg-sky-50 text-sky-700"},cancelled:{label:"בוטל",cls:"bg-red-50 text-red-600"}},ux={ok:"bg-emerald-50 text-emerald-700",opening:"bg-sky-50 text-sky-700",no_meter:"bg-red-50 text-red-600",no_previous:"bg-amber-50 text-amber-800",regression:"bg-amber-50 text-amber-800",duplicate:"bg-purple-50 text-purple-700",invalid:"bg-red-50 text-red-600"};function vt({label:t,value:s,tone:n=""}){return e.jsxs("div",{className:"bg-white/80 border border-black/5 rounded-2xl px-3 py-2.5 text-right",children:[e.jsx("p",{className:"text-[11px] font-bold text-slate-500",children:t}),e.jsx("p",{className:`text-xl font-extrabold tracking-tight mt-0.5 tabular-nums ${n}`,children:e.jsx("span",{dir:"ltr",className:"inline-block",children:s})})]})}function mx({kibbutzId:t}){const[s,n]=i.useState("home"),[a,l]=i.useState([]),[r,o]=i.useState(""),[p,u]=i.useState(null),[d,c]=i.useState(null),m=i.useCallback(async()=>{try{const f=await aa(t,{action:"list"});l((f==null?void 0:f.batches)||[])}catch{l([])}},[t]);i.useEffect(()=>{m()},[m]);const h=f=>{u(f),n("summary")}
33,b=async f=>{o("cancel");try{await aa(t,{action:f.bill_count?"delete":"cancel",batch_id:f.id}),W.success("הטעינה נמחקה"),c(null),p===f.id&&(u(null),n("home")),m()}catch(x){W.error((x==null?void 0:x.message)||"לא ניתן למחוק את הטעינה"),c(null)}finally{o("")}};return s==="summary"&&p?e.jsx(px,{kibbutzId:t,batchId:p,onBack:()=>{u(null),n("home"),m()}}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"טעינת קובץ קריאות מוני מים, התאמה למשלמים, חישוב והפקת דרישות תשלום."}),e.jsxs("button",{onClick:()=>n("wizard"),className:"h-9 px-4 rounded-full bg-sky-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(La,{className:"w-4 h-4"})," טעינת קובץ צריכת מים"]})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-200 bg-slate-50/60",children:e.jsx("span",{className:"text-sm font-extrabold text-slate-800",children:"היסטוריית טעינות"})}),a.length===0?e.jsxs("div",{className:"p-10 text-center",children:[e.jsx(Ke,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsx("h3",{className:"text-base font-semibold mb-1",children:"אין עדיין טעינות קריאות מים"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"טענו קובץ קריאות כדי לחשב חשבונות מים למשלמים."})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"תאריך"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"קובץ"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"תקופה"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"רשומות"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"חשבונות"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סכום"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סטטוס"}),e.jsx("th",{className:"px-4 py-2.5"})]})}),e.jsx("tbody",{children:a.map(f=>{const x=On[f.status]||On.draft;return e.jsxs("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-500 whitespace-nowrap",children:xc(f.created_date)}),e.jsx("td",{className:"px-4 py-2.5 truncate max-w-[14rem]",children:f.file_name||"—"}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:f.period_name||"—"}),e.jsx("td",{className:"px-4 py-2.5 tabular-nums",dir:"ltr",children:$t(f.row_count||0)}),e.jsx("td",{className:"px-4 py-2.5 tabular-nums",dir:"ltr",children:$t(f.bill_count||0)}),e.jsx("td",{className:"px-4 py-2.5 font-bold tabular-nums",dir:"ltr",children:Xl(f.total_amount)}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${x.cls}`,children:x.label})}),e.jsxs("td",{className:"px-4 py-2.5 text-left whitespace-nowrap",children:[e.jsx("button",{onClick:()=>h(f.id),className:"h-8 px-3 rounded-full border border-slate-200 text-xs hover:bg-slate-50",children:f.status==="pending"||f.status==="draft"?"המשך":"צפייה"}),e.jsx("button",{onClick:()=>c(f),title:"מחיקת טעינה",className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-red-500 hover:bg-red-50 mr-1",children:e.jsx(Re,{className:"w-4 h-4"})})]})]},f.id)})})]})})]}),s==="wizard"&&e.jsx(xx,{kibbutzId:t,onCancel:()=>n("home"),onLoaded:f=>{m(),h(f)}}),d&&e.jsx(No,{open:!0,onOpenChange:f=>{f||c(null)},title:d.bill_count?"מחיקת קובץ שהופקו ממנו חיובים":"מחיקת טעינת קריאות",description:d.bill_count?`מחיקת הקובץ «${d.file_name||d.peri
33od_name||""}» תמחק מהמערכת את כל המסמכים והחיובים שהופקו ממנו — ${_e(d.bill_count,"דרישת תשלום אחת","דרישות תשלום")} — מעמוד המשלם ומהמרחב האישי של התושבים. המונים יוחזרו לקריאה שהייתה לפני הטעינה. אין דרך לשחזר.`:`עדיין לא הופקו מסמכים לקובץ «${d.file_name||d.period_name||""}», והמחיקה לא תשפיע על נתונים אחרים במערכת. ${_e(d.row_count||0,"השורה שלו תימחק","השורות שלו יימחקו")}.`,confirmLabel:r==="cancel"?"מוחק…":"מחק טעינה",destructive:!0,onConfirm:()=>b(d)})]})}function xx({kibbutzId:t,onCancel:s,onLoaded:n}){var E,k;const a=i.useRef(null),[,l]=ia(),r=()=>l({tab:"chargeTypes"}),[o,p]=i.useState(null),[u,d]=i.useState(""),[c,m]=i.useState({period_name:"",period_start:"",period_end:"",due_date:"",months:"2"}),[h,b]=i.useState(null),[f,x]=i.useState(""),[g,y]=i.useState(0),$=(C,w)=>m(_=>({..._,[C]:w}));i.useEffect(()=>{D.entities.ChargeType.filter({kibbutz_id:t},"order",300).then(C=>{const w=Vu(C||[]);p(w),w.length===1&&d(w[0].id)}).catch(()=>p([]))},[t]),i.useEffect(()=>{const C=Gu(c.period_start,c.period_end);C&&m(w=>({...w,months:String(C)}))},[c.period_start,c.period_end]);const O=async C=>{var _;const w=(_=C.target.files)==null?void 0:_[0];if(C.target.value="",!!w){x("read");try{const T=await zm(w);T.errors.length&&!T.rows.length?(W.error(T.errors[0]),b(null)):b({name:w.name,...T,summary:Wm(T.rows)})}catch{W.error("לא ניתן לקרוא את הקובץ")}finally{x("")}}},A=async()=>{var C;if((C=h==null?void 0:h.rows)!=null&&C.length){x("upload"),y(0);try{const w=await aa(t,{action:"start",charge_type_id:u,file_name:h.name,months:Number(c.months),period_name:c.period_name,period_start:c.period_start||null,period_end:c.period_end||null,due_date:c.due_date||null}),_=w==null?void 0:w.batch_id;if(!_)throw new Error("שגיאה בפתיחת הטעינה");for(let T=0;T<h.rows.length;T+=bl)await aa(t,{action:"rows",batch_id:_,rows:h.rows.slice(T,T+bl)}),y(Math.min(100,Math.round((T+bl)/h.rows.length*100)));W.success("הקובץ נטען וחושב"),n(_)}catch(w){W.error((w==null?void 0:w.message)||"שגיאה בטעינת הקובץ")}finally{x("")}}},S=!!u&&!!c.period_name.trim()&&Number(c.months)>0&&!!((E=h==null?void 0:h.rows)!=null&&E.length),P=u?c.period_name.trim()?Number(c.months)>0?(k=h==null?void 0:h.rows)!=null&&k.length?"":"יש לבחור קובץ קריאות":"יש להזין מספר חודשי חיוב":"יש להזין שם תקופה":"יש לבחור סוג חיוב מים";return Pt.createPortal(e.jsx("div",{dir:"rtl",className:"fixed inset-0 z-[80] bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:()=>!f&&s(),children:e.jsxs("div",{className:"billing-form bg-white rounded-2xl shadow-2xl w-full max-w-2xl flex flex-col h-[min(42rem,92vh)]",onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 pt-5 pb-3 flex-none",children:[e.jsxs("h3",{className:"text-[20px] font-black text-slate-900 flex items-center gap-2",children:[e.jsx(Ke,{className:"w-5 h-5 text-sky-600"})," טעינת קובץ צריכת מים"]}),e.jsx("button",{onClick:s,"aria-label":"סגירה",className:"w-9 h-9 rounded-full border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50 flex-none",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 pb-2 space-y-4",children:o===null?e.jsx("p",{className:"text-sm text-slate-400",children:"טוען סוגי חיוב…"}):o.length===0?e.jsxs("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900",children:[e.jsx("p",{className:"font-bold",children:"לא הוגדר סוג חיוב פעיל מסוג «צריכת מים לפי קריאת מונה»"}),e.jsx("p",{className:"text-[13px] mt-0.5",children:"סוג החיוב נושא את התעריפים ואת המכסה שלפיהם יחושב החשבון, ולכן הוא נדרש לפני הטעינה."}
33),e.jsxs("button",{onClick:r,className:"mt-3 h-9 px-4 rounded-full bg-sky-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(Ke,{className:"w-4 h-4"})," להגדרת סוג חיוב מים"]})]}):e.jsxs(e.Fragment,{children:[o.length===1?e.jsxs("div",{className:"rounded-xl border border-sky-200 bg-sky-50/60 px-3.5 py-2.5 flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[13px] font-black text-slate-800",children:o[0].name}),e.jsxs("span",{className:"text-[11.5px] text-slate-500",dir:"ltr",children:[Ys(o[0].water_low_rate)," / ",Ys(o[0].water_high_rate)]}),e.jsxs("span",{className:"text-[11.5px] text-slate-500",children:["למ״ק · ",o[0].water_quota_per_soul," מ״ק לנפש לחודש"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2.5",children:o.map(C=>e.jsxs("button",{onClick:()=>d(C.id),className:`text-right rounded-2xl border p-3 transition-colors ${u===C.id?"border-sky-400 bg-sky-50":"border-slate-200 hover:bg-slate-50"}`,children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800",children:C.name}),e.jsxs("span",{className:"block text-[11.5px] text-slate-500 mt-0.5",children:[Ys(C.water_low_rate)," / ",Ys(C.water_high_rate)," למ״ק · ",C.water_quota_per_soul," מ״ק לנפש"]})]},C.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(Q,{label:"שם התקופה",required:!0,hint:"מופיע בדרישת התשלום, למשל «יולי–אוגוסט 2026»",children:e.jsx("input",{className:Se,placeholder:"הזן שם תקופה",value:c.period_name,onChange:C=>m(w=>({...w,period_name:C.target.value,name_touched:!0}))})}),e.jsx(Vm,{label:"תקופת החיוב",from:c.period_start,to:c.period_end,onChange:({from:C,to:w})=>m(_=>({..._,period_start:C,period_end:w,period_name:_.name_touched?_.period_name:dx(C,w)}))}),e.jsx(Q,{label:"מספר חודשי חיוב",required:!0,info:"המכסה המוכרת מוכפלת במספר זה",children:e.jsx("input",{type:"number",step:"0.5",className:Se,value:c.months,onChange:C=>$("months",C.target.value)})})]}),e.jsx("input",{ref:a,type:"file",accept:".csv,.xls,.xlsx,text/csv",className:"hidden",onChange:O}),h?e.jsxs("div",{className:"space-y-2.5",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5",children:[e.jsx(vt,{label:"שורות בקובץ",value:$t(h.summary.rows)}),e.jsx(vt,{label:"מונים",value:$t(h.summary.meters)}),e.jsx(vt,{label:"רשומות כפולות",value:$t(h.summary.duplicates),tone:h.summary.duplicates?"text-purple-700":""}),e.jsx(vt,{label:"שורות עם שגיאה",value:$t(h.summary.errors),tone:h.summary.errors?"text-red-600":""})]}),h.errors.map(C=>e.jsxs("div",{className:"flex gap-2 rounded-2xl border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900",children:[e.jsx(At,{className:"w-5 h-5 flex-none"})," ",C]},C)),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[11.5px] text-slate-500 truncate",children:h.name}),e.jsx("button",{onClick:()=>b(null),className:"text-[11.5px] text-slate-500 underline flex-none",children:"בחירת קובץ אחר"})]})]}):e.jsxs("button",{onClick:()=>{var C;return(C=a.current)==null?void 0:C.click()},disabled:f==="read",className:"w-full rounded-2xl border-2 border-dashed border-sky-300 bg-sky-50/40 p-8 text-center hover:bg-sky-50",children:[f==="read"?e.jsx(Ie,{className:"w-8 h-8 text-sky-500 mx-auto mb-2 animate-spin"}):e.jsx(pr,{className:"w-8 h-8 text-sky-500 mx-auto mb-2"}),e.jsx("span",{className:"block text-sm font-bold text-slate-700",children:"בחרו קובץ קריאות"}),e.jsx("span",{className:"block text-xs text-slate-400 mt-1",children:"XLSX או CSV — העמודות מזוהות לפי שמותיהן"})]}),f==="upload"&&e.jsx("div",{className:"h-2 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full bg-sky-500 transition-all",style:{width:`${g}%`}})})]})}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-4 border-t border-slate-100 flex-none",children:[e.jsx("button",{onClick:A,disabled:!S||!!f,title:P,className:ts,children:f==="upload"?e.jsxs(e.Fragment,{children:[e.jsx(Ie,{className:"w-4 h-4 animate-spin"})," טוען…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ma,{className:"w-4 h-4"})," טעינה ואישור"]})}),e.jsx("button",{onClick:s,className:$s,children:"ביטול"}),P&&!f&&e.jsx("span",{className:"text-[11.5px] text-slate-400 mr-auto",children:P})]})]})}),document.body)}function px({kibbutzId:t,batchId:s,onBack:n}){const[,a]=ia(),l=()=>a({tab:"monthly",bucket:"file"}),[r,o]=i.useState(null),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState(!0),[x]=i.useState(""),[g,y]=i.useState(null),[$,O]=i.useState(null),A=i.useCallback(async()=>{f(!0);try{const[_,T,M,B]=await Promise.all([D.entities.WaterImportBatch.get(s).catch(()=>null),D.entities.WaterReading.filter({kibbutz_id:t,batch_id:s},"row_no",5e3).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.WaterMeter.filterAll({kibbutz_id:t}).catch(()=>[])]);o(_),u(T||[]),c(M||[]),h(B||[])}finally{f(!1)}},[t,s]);i.useEffect(()=>{A()},[A]);const S=i.useCallback(_=>{const T=d.find(M=>M.id===_);return T?T.name||`#${T.account_number}`:"—"},[d]),P=i.useMemo(()=>{const _=p.filter(M=>M.status===Tt.ok),T=p.filter(M=>M.status!==Tt.ok&&M.status!==Tt.opening);return{rows:p.length,ok:_.length,problem:T.length,unmatched:p.filter(M=>M.status===Tt.no_meter).length,cubic:p.reduce((M,B)=>M+(Number(B.consumption)||0),0),total:_.reduce((M,B)=>M+(Number(B.amount)||0),0),billed:p.filter(M=>M.charge_id).length}}
33,[p]),E=()=>{const _=p.filter(L=>L.status!==Tt.ok&&L.status!==Tt.opening),T=["שורה","מס׳ מונה","מס׳ זיהוי","שם צרכן","כתובת","קריאה בקובץ","סטטוס","הערה"],M=L=>`"${String(L??"").replace(/"/g,'""')}"`,B=[T,..._.map(L=>[L.row_no,L.meter_number,L.consumer_id,L.consumer_name,L.property_address,L.current_reading,Pa[L.status]||L.status,L.status_note])].map(L=>L.map(M).join(",")).join(`\r
34`),R=new Blob([`\uFEFF${B}`],{type:"text/csv;charset=utf-8"}),j=URL.createObjectURL(R),q=document.createElement("a");q.href=j,q.download=`שגיאות_${r.period_name||r.id}.csv`,document.body.appendChild(q),q.click(),q.remove(),setTimeout(()=>URL.revokeObjectURL(j),1e3)},k=async _=>{if(confirm(`להסיר את שורה ${_.row_no} מהטעינה?`))try{await aa(t,{action:"row",reading_id:_.id,remove:!0}),W.success("השורה הוסרה"),A()}catch(T){W.error((T==null?void 0:T.message)||"שגיאה")}};if(b)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-sky-500 rounded-full animate-spin"})});if(!r)return e.jsx("div",{className:"p-10 text-center text-sm text-slate-400",children:"הטעינה לא נמצאה"});const C=On[r.status]||On.draft,w=r.status==="approved"||r.status==="partially_approved";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"text-base font-extrabold flex items-center gap-2",children:[e.jsx(Ke,{className:"w-5 h-5 text-sky-600"})," סיכום חשבונות מים",e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${C.cls}`,children:C.label})]}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:[r.period_name,r.file_name,`${r.months} חודשי חיוב`,r.due_date?`לתשלום עד ${xc(r.due_date)}`:""].filter(Boolean).join(" · ")})]}),e.jsxs("button",{onClick:n,className:"h-9 px-4 rounded-full border border-slate-200 text-sm inline-flex items-center gap-1.5 hover:bg-slate-50",children:[e.jsx(bs,{className:"w-4 h-4"})," חזרה"]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5",children:[e.jsx(vt,{label:"רשומות",value:$t(P.rows)}),e.jsx(vt,{label:"תקינות",value:$t(P.ok),tone:"text-emerald-700"}),e.jsx(vt,{label:"דורשות בדיקה",value:$t(P.problem),tone:P.problem?"text-amber-700":""}),e.jsx(vt,{label:"ללא מונה",value:$t(P.unmatched),tone:P.unmatched?"text-red-600":""}),e.jsx(vt,{label:"סה״כ מ״ק",value:ls(P.cubic)}),e.jsx(vt,{label:"סה״כ לחיוב",value:Xl(P.total)})]}),P.problem>0&&!w&&e.jsxs("div",{className:"flex gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-3.5 text-sm text-amber-900",children:[e.jsx(At,{className:"w-5 h-5 flex-none mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold",children:_e(P.problem,"שורה אחת לא תחויב","שורות לא יחויבו")}),e.jsx("p",{className:"text-[13px] mt-0.5",children:"ניתן לאשר את השורות התקינות עכשיו, ולטפל בשאר לאחר מכן — אישור חוזר יפיק רק את מה שטרם חויב."}),e.jsxs("button",{onClick:E,className:"mt-2 h-8 px-3 rounded-full bg-white border border-amber-300 text-xs inline-flex items-center gap-1.5",children:[e.jsx(ro,{className:"w-3.5 h-3.5"})," הורדת דוח השורות שלא חויבו"]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"#"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"חשבון משלם"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"מונה"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"כתובת"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"קודמת"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"נוכחית"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"צריכה"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"נפשות"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"מכסה"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"נמוך/גבוה"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"סכום"}),e.jsx("th",{className:"text-right px-3 py-2.5 font-medium",children:"סטטוס"}),e.jsx("th",{className:"px-3 py-2.5"})]})}),e.jsx("tbody",{children:p.map(_=>e.jsxs(he.Fragment,{children:[e.jsxs("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-3 py-2 text-slate-400 tabular-nums",dir:"ltr",children:_.row_no}),e.jsx("td",{className:"px-3 py-2 font-medium",children:_.payer_account_id?S(_.payer_account_id):e.jsx("span",{className:"text-slate-400",children:_.consumer_name||"—"})}),e.jsx("td",{className:"px-3 py-2 text-slate-600 tabular-nums",dir:"ltr",children:_.meter_number||"—"}),e.jsx("td",{className:"px-3 py-2 text-slate-500 truncate max-w-[10rem]",children:_.property_address||"—"}),e.jsx("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:ls(_.previous_reading)}),e.jsx("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:ls(_.current_reading)}),e.jsx("td",{className:"px-3 py-2 tabular-nums font-semibold",dir:"ltr",children:ls(_.consumption)}),e.jsxs("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:[_.souls_used??"—",_.eligible_used?`+${_.eligible_used}`:""]}),e.jsx("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:ls(_.quota_total)}),e.jsxs("td",{className:"px-3 py-2 tabular-nums text-xs text-slate-500",dir:"ltr",children:[ls(_.low_consumption)," / ",ls(_.high_consumption)]}),e.jsx("td",{className:"px-3 py-2 font-bold tabular-nums",dir:"ltr",children:_.amount==null?"—":Xl(_.amount)}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full whitespace-nowrap ${ux[_.status]||"bg-slate-100 text-slate-600"}`,title:_.status_note||"",children:Pa[_.status]||_.status}),_.charge_id&&e.jsx("span",{className:"block text-[10px] text-emerald-600 mt-0.5",children:"הופקה דרישת תשלום"})]}),e.jsxs("td",{className:"px-3 py-2 text-left whitespace-nowrap",children:[_.breakdown&&e.jsx("button",{onClick:()=>O($===_.id?null:_.id),title:"פירוט חישוב",className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(Ma,{className:"w-4 h-4"})}),!_.charge_id&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>y(_),title:"עריכה / שיוך",className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>k(_),title:"הסרת שורה",className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})]})]})]}),$===_.id&&_.breakdown&&e.jsx("tr",{className:"bg-slate-50/70",children:e.jsx("td",{colSpan:13,className:"px-4 py-3",children:e.jsx("div",{className:"max-w-xl",children:e.jsx(dr,{b:_.breakdown})})})}),_.status_note&&_.status!==Tt.ok&&e.jsx("tr",{className:"bg-amber-50/40",children:e.jsxs("td",{colSpan:13,className:"px-4 py-1.5 text-[12px] text-amber-800",children:["שורה ",_.row_no,": ",_.status_note]})})]},_.id))})]})})}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[P.ok>0?e.jsxs("button",{onClick:l,disabled:!!x,className:ts,children:[e.jsx(Be,{className:"w-4 h-4"})," אישור ומעבר להפקת חיובים"]}):e.jsxs("button",{onClick:n,className:$s,children:[e.jsx(bs,{className:"w-4 h-4"})," חזרה לרשימת הטעינות"]}),P.billed>0&&e.jsxs("span",{className:"text-xs font-bold text-emerald-700 inline-flex items-center gap-1.5 bg-emerald-50 border border-emerald-200 rounded-full px-3 py-1.5",children:[e.jsx(Rc,{className:"w-4 h-4"})," הופקו ",_e(P.billed,"דרישת תשלום אחת","דרישות תשלום")," מטעינה זו"]})]}),g&&e.jsx(pc,{kibbutzId:t,row:g,meters:m,accounts:d,onClose:()=>y(null),onSaved:()=>{y(null),A()}})]})}function pc({kibbutzId:t,row:s,meters:n,accounts:a,onClose:l,onSaved:r}){const[,o]=ia(),p=A=>n.find(S=>S.id===A)||null,u=(A,S)=>A==null||A===""?S??"":String(A),d=p(s.water_meter_id),[c,m]=i.useState({water_meter_id:s.water_meter_id||"",previous_reading:s.previous_reading??(d==null?void 0:d.previous_reading)??"",previous_reading_date:s.previous_reading_date||(d==null?void 0:d.previous_reading_date)||"",current_reading:s.current_reading??"",souls:u(s.souls_used,d==null?void 0:d.souls),eligible_count:u(s.eligible_used,d==null?void 0:d.eligible_count),mark_opening:!1}),[h,b]=i.useState(!1),f=(A,S)=>m(P=>({...P,[A]:S})),x=A=>{const S=a.find(P=>P.id===A);return S?S.name||`#${S.account_number}`:"ללא חשבון"},g=p(c.water_meter_id),y=g?a.find(A=>A.id===g.payer_account_id):a.find(A=>A.id===s.payer_account_id)||null,$=()=>o(y!=null&&y.id?{tab:"accounts",account:y.id}:{tab:"accounts"});i.useEffect(()=>{g&&m(A=>({...A,previous_reading:A.previous_reading===""?u(g.previous_reading):A.previous_reading,previous_reading_date:A.previous_reading_date||g.previous_reading_date||"",souls:A.s
34ouls===""?u(g.souls):A.souls,eligible_count:A.eligible_count===""?u(g.eligible_count):A.eligible_count}))},[c.water_meter_id]);const O=async()=>{b(!0);try{const A=await aa(t,{action:"row",reading_id:s.id,water_meter_id:c.water_meter_id||void 0,previous_reading:c.previous_reading===""?void 0:c.previous_reading,previous_reading_date:c.previous_reading_date||void 0,current_reading:c.current_reading===""?void 0:c.current_reading,mark_opening:c.mark_opening});W.success(Pa[A==null?void 0:A.status]||"השורה עודכנה"),r()}catch(A){W.error((A==null?void 0:A.message)||"שגיאה בעדכון השורה")}finally{b(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4",onClick:l,children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-2xl p-5 billing-form",onClick:A=>A.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-base font-bold",children:["שורה ",s.row_no," · מונה ",s.meter_number||"—"]}),e.jsx("button",{onClick:l,className:"w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-slate-500 mb-3",children:[s.consumer_name,s.property_address,s.status_note].filter(Boolean).join(" · ")}),(y||g)&&e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50/70 px-3 py-2 mb-4 flex items-center gap-x-4 gap-y-1 flex-wrap text-[12px]",children:[y&&e.jsxs("span",{className:"font-bold text-slate-800",children:[y.name||`#${y.account_number}`,y.account_number?e.jsxs("span",{className:"text-slate-400 font-normal",children:[" · חשבון ",y.account_number]}):null]}),g&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-slate-500",children:["נפשות במונה: ",e.jsx("b",{className:"text-slate-800",children:g.souls??"—"})]}),e.jsxs("span",{className:"text-slate-500",children:["זכאים: ",e.jsx("b",{className:"text-slate-800",children:g.eligible_count??0})]}),e.jsxs("span",{className:"text-slate-500",children:["קריאה קודמת: ",e.jsx("b",{className:"text-slate-800",dir:"ltr",children:g.previous_reading??"—"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(Q,{label:"שיוך למונה",info:"השיוך נשמר על המונה, כך שבטעינה הבאה ההתאמה תתבצע אוטומטית",children:e.jsxs("select",{className:Se,value:c.water_meter_id,onChange:A=>f("water_meter_id",A.target.value),children:[e.jsx("option",{value:"",children:"— בחרו מונה —"}),n.map(A=>e.jsxs("option",{value:A.id,children:[A.meter_number," · ",x(A.payer_account_id),A.status==="inactive"?" (לא פעיל)":""]},A.id))]})}),e.jsx(Q,{label:"קריאה נוכחית (מ״ק)",children:e.jsx("input",{type:"number",step:"0.001",className:Se,value:c.current_reading,onChange:A=>f("current_reading",A.target.value)})}),e.jsx(Q,{label:"קריאה קודמת (מ״ק)",info:"למונה שאין לו קריאה קודמת — הזינו אותה כאן, או סמנו את הקריאה הנוכחית כקריאת פתיחה",children:e.jsx("input",{type:"number",step:"0.001",className:Se,value:c.previous_reading,onChange:A=>f("previous_reading",A.target.value),disabled:c.mark_opening})}),e.jsx(Q,{label:"תאריך קריאה קודמת",children:e.jsx("input",{type:"date",className:Se,value:c.previous_reading_date,onChange:A=>f("previous_reading_date",A.target.value),disabled:c.mark_opening})}),e.jsx(Q,{label:"נפשות לחישוב",hint:"מתוך חשבון המשלם",children:e.jsx("p",{className:`${Se} bg-slate-50 flex items-center font-black text-emerald-700 tabular-nums`,children:c.souls===""?"—":c.souls})}),e.jsx(Q,{label:"מספר זכאים",hint:"מתוך חשבון המשלם",children:e.jsx("p",{className:`${Se} bg-slate-50 flex items-center font-black text-amber-600 tabular-nums`,children:c.eligible_count===""?"0":c.eligible_count})})]}),e.jsxs("p",{className:"text-[12px] text-slate-500 mt-3",children:["לשינוי מספר הנפשות והזכאים"," ",e.jsx("button",{type:"button",onClick:$,className:"font-bold text-sky-700 underline decoration-sky-300 underline-offset-4 hover:text-sky-900",children:"עברו לחשבון המשלם"}),y!=null&&y.name?` — ${y.name}`:"",". השינוי חל על כל חשבונות המים של משק הבית, ולא על השורה הזאת בלבד."]}),e.jsxs("button",{type:"button",onClick:()=>f("mark_opening",!c.mark_opening),className:`flex items-center gap-2 h-11 px-3 mt-4 w-full rounded-xl border text-sm ${c.mark_opening?"border-sky-300 bg-sky-50 text-sky-800":"border-slate-200 text-slate-600"}`,children:[e.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center ${c.mark_opening?"bg-sky-600":"bg-slate-200"}`,children:c.mark_opening&&e.jsx(ye,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:"flex-1 text-right",children:"שמור כקריאת פתיחה — ללא דרישת תשלום, תשמש כקריאה קודמת בטעינה הבאה"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-5",children:[e.jsxs("button",{onClick:O,disabled:h,className:ts,children:[e.jsx(ye,{className:"w-4 h-4"})," ",h?"שומר…":"שמור וחשב מחדש"]}),e.jsx("button",{onClick:l,className:$s,children:"ביטול"})]})]})})}const Ln=t=>ve(t),Vs=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),hx=t=>{if(!t)return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const n=a=>String(a).padStart(2,"0");return`${n(s.getDate())}/${n(s.getMonth()+1)}/${s.getFullYear()}, ${n(s.getHours())}:${n(s.getMinutes())}`},fa=t=>{const[s,n,a]=String(t||"").slice(0,10).split("-");return a?`${a}/${n}/${s}`:"—"},hc=t=>{const s=t==null?void 0:t.produced;
34if(!s)return"האישור נרשם";if(s.status==="ok"){const n=Number(s.charges)||0;return n===1?"האישור נרשם · הופקה דרישת תשלום אחת":`האישור נרשם · הופקו ${Vs(n)} דרישות תשלום · ${Ln(s.total)}`}return`האישור נרשם · ${s.reason_label||"ההפקה תתבצע במועד שנקבע"}`},bx={auto:Mt,manual:Ns,file:Ke,paused:Pd},fx={auto:"text-emerald-600 bg-emerald-50 border-emerald-200",manual:"text-indigo-600 bg-indigo-50 border-indigo-200",file:"text-sky-600 bg-sky-50 border-sky-200",paused:"text-amber-600 bg-amber-50 border-amber-200"};function bc({kibbutzId:t}){const[s,n]=i.useState(null),[a,l]=i.useState([]),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState(!0),[x,g]=i.useState(null),[y,$]=i.useState(null),[O,A]=i.useState(""),[S]=ia(),P=S.get("bucket"),[E,k]=i.useState(null),[C,w]=i.useState(()=>cl.some(N=>N.v===P)?P:"auto"),_=i.useCallback(async()=>{f(!0);try{const[N,v,F,K,Z,H]=await Promise.all([D.functions.invoke("recurringBilling",{action:"status",community_id:t}).catch(()=>null),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me}).catch(()=>[]),D.entities.Property.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.WaterImportBatch.filterAll({kibbutz_id:t}).catch(()=>[])]);n((N==null?void 0:N.data)||null),l((v||[]).filter(z=>z.is_active!==!1)),o(F||[]),u(K||[]),c(Z||[]),h(H||[])}catch{W.error("שגיאה בטעינה")}finally{f(!1)}},[t]);i.useEffect(()=>{_()},[_]);const T=async(N,v)=>{A(N.charge_type_id||"run");try{const F=await D.functions.invoke("recurringBilling",{community_id:t,...N});return v&&W.success(typeof v=="function"?v(F==null?void 0:F.data):v),g(null),await _(),F==null?void 0:F.data}catch{return W.error("שגיאה בפעולה"),null}finally{A("")}},M=async N=>{var z;
34const v=x,F=ze(v)?"ההגדרות עודכנו":N.activation_mode==="auto"?"ההפקה האוטומטית הופעלה":"סוג החיוב הופעל כחיוב יזום",K=v._batch||R.get(v.id);if(!await T({action:"activate",charge_type_id:v.id,...N,activated_batch_id:Xt(v)&&(K==null?void 0:K.id)||null},F))return;const H=K;if(!(!Xt(v)||N.issue_timing!=="now"||!H||H.bill_count))try{const te=await D.functions.invoke("waterImport",{action:"approve",community_id:t,batch_id:H.id,due_date:N.last_due_date||null}),ie=Number(((z=te==null?void 0:te.data)==null?void 0:z.created)||0);W.success(ie===1?"הופקה דרישת תשלום אחת":`הופקו ${Vs(ie)} דרישות תשלום`),await _()}catch{W.error("ההגדרות נשמרו, אך הפקת החיובים מהקובץ נכשלה")}},B=i.useMemo(()=>{const N=new Map;return(m||[]).forEach(v=>{!v.charge_type_id||v.status==="cancelled"||(N.has(v.charge_type_id)||N.set(v.charge_type_id,[]),N.get(v.charge_type_id).push(v))}),N.forEach(v=>v.sort((F,K)=>String(K.created_date||"").localeCompare(String(F.created_date||"")))),N},[m]),R=i.useMemo(()=>{const N=new Map;return B.forEach((v,F)=>N.set(F,v[0])),N},[B]),j=i.useMemo(()=>{const N=new Map(((s==null?void 0:s.types)||[]).map(F=>[F.id,F])),v=[];return(a||[]).forEach(F=>{const K=N.get(F.id)||{},Z=Xt(F);(Z?B.get(F.id)||[null]:[null]).forEach(z=>{const te=Z?!!ze(F)&&!!z&&F.activated_batch_id===z.id:ym(F,null),ie=!!(z!=null&&z.bill_count),V=te?F:{...F,activation_mode:null,auto_billing_enabled:!1,issue_timing:null,demand_issue_date:null,charge_issue_date:null,last_due_date:null},Y=ze(V)||(Z&&ie?ze(F):null),J=ai(Z?{activated:te||ie,billed:ie,demandDate:ie?z==null?void 0:z.approved_at:F.demand_issue_date,chargeDate:te?F.charge_issue_date:null,lastDueDate:(te?F.last_due_date:null)||(z==null?void 0:z.due_date)||null,kind:"file"}:{activated:!!Y,billed:!!K.billed_this_period,demandDate:K.next_issue||F.demand_issue_date,chargeDate:K.next_due||F.charge_issue_date,kind:Y==="auto"?"auto":"manual",approvals:K.approvals||null,needsApproval:!!F.requires_manager_approval});v.push({...V,accounts:Z?(z==null?void 0:z.bill_count)||(z==null?void 0:z.row_count)||null:K.accounts??null,forecast:Z?(z==null?void 0:z.total_amount)??null:K.forecast??null,next_issue:K.next_issue||"",next_due:K.next_due||"",billed_this_period:!!K.billed_this_period,due_now:!!K.due_now,due_day:K.due_day??F.due_day??null,_schedulable:!!K.id,_key:z?`${F.id}|${z.id}`:F.id,_mode:Y,_live:te,_approvals:K.approvals||{},_needsApproval:!!F.requires_manager_approval,_canActivate:Z?!te&&!ie:!ze(F),_bucket:gm(V),_status:Y?km(J):_m(V),_steps:Y?J:null,_issued:Z?ie:!!K.billed_this_period,_caption:Z?(z==null?void 0:z.period_name)||"":`חיוב ${ui[F.billing_cycle]||""}`.trim(),_batch:z||null,_batchDue:(z==null?void 0:z.due_date)||null})})}),v},[a,s,B]),q=i.useMemo(()=>{const N={auto:0,manual:0,file:0,paused:0};return j.forEach(v=>{(v._bucket!=="file"||v._batch)&&(N[v._bucket]+=1)}),N},[j]);i.useEffect(()=>{if(b||q[C]||P)return;const N=cl.map(v=>v.v).find(v=>q[v]);N&&w(N)},[b,q,C,P]);const L=j.filter(N=>N._bucket===C&&!(N._bucket==="file"&&!N._batch));return b?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-emerald-500 rounded-full animate-spin"})}):j.length?e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-2.5 mb-4",children:cl.map(N=>{const v=bx[N.v],F=C===N.v;return e.jsxs("button",{type:"button",onClick:()=>w(N.v),"aria-pressed":F,className:`rounded-2xl border bg-white p-3.5 text-right transition-all ${F?"border-slate-800 shadow-md":"border-slate-200 hover:border-slate-300 shadow-sm"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:`text-[26px] font-black tabular-nums leading-none ${q[N.v]?"text-slate-900":"text-slate-300"}`,children:Vs(q[N.v])}),e.jsx("span",{className:`w-10 h-10 rounded-xl grid place-items-center flex-none border ${fx[N.v]}`,children:e.jsx(v,{className:"w-5 h-5"})})]}),e.jsx("p",{className:"text-[13px] font-bold text-slate-700 mt-2",children:N.l}),e.jsx("p",{className:"text-[11px] text-slate-400 leading-snug",children:N.hint})]},N.v)})}),e.jsx("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"סוג חיוב"}),e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"מחזור"}),e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"שיטת חישוב"}),e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"מועדים"}),e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"חשבונות"}),e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"צפי הכנסות"}),e.jsx("th",{className:"text-right px-4 py-3 font-semibold",children:"סטטוס"}),e.jsx("th",{className:"px-4 py-3"})]})}),e.jsxs("tbody",{children:[L.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 py-10 text-center text-[13px] text-slate-400",children:"אין סוגי חיוב במגירה הזאת."})}),L.map(N=>{var v,F,K,Z,H;return e.jsxs(he.Fragment,{children:[e.jsxs("tr",{className:`border-t border-slate-100 align-middle ${N._batch?"cursor-pointer hover:bg-slate-50":"hover:bg-slate-50/60"}`,onClick:N._batch?()=>k(z=>z===N._key?null:N._key):void 0,children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsxs("span",{className:"font-bold text-slate-800 inline-flex items-center gap-1.5",children:[N._batch&&e.jsx(Jt,{className:`w-4 h-4 text-slate-400 transition-transform ${E===N._key?"":"-rotate-90"}`}),N.name]}),N.billed_this_period&&e.jsxs("span",{className:"block text-[11px] text-emerald-700 font-bold",children:["חויב כבר לתקופה ",s==null?void 0:s.period]})]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:ui[N.billing_cycle]||N.billing_cycle}),e.jsx("td",{className:"px-4 py-3 text-slate-500",children:Dm(N.calculation_method)}),e.jsx("td",{className:"px-4 py-3 text-slate-600 text-[12.5px] whitespace-nowrap",children:e.jsx(yx,{row:N})}),e.jsx("td",{className:"px-4 py-3 tabular-nums",children:N.accounts===null?e.jsx("span",{className:"text-slate-300",children:"—"}):Vs(N.accounts)}),e.jsx("td",{className:"px-4 py-3 tabular-nums font-bold",dir:"ltr",children:N.forecast===null?e.jsx("span",{className:"text-slate-300",children:"—"}):Ln(N.forecast)}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:`text-[11.5px] font-bold px-2.5 py-1 rounded-full border ${jm[N._status]||"bg-slate-100 text-slate-500 border-slate-200"}`,children:N._status}),N._mode&&e.jsx("span",{className:`text-[11px] font-bold px-2 py-0.5 rounded-full border ${N._mode==="auto"?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-indigo-50 text-indigo-700 border-indigo-200"}`,children:N._mode==="auto"?"אוטומטי":N.issue_timing==="scheduled"?"מתוזמן":"יזום"})]}),N._mode&&!N._steps&&!N._note&&e.jsx("ul",{className:"mt-1.5 space-y-0.5",children:ec({mode:N._mode,document_kind:N.document_kind,timing:N.issue_timing,demand_issue_day:N.demand_issue_day,charge_issue_day:N.charge_issue_day,demand_issue_date:N.demand_issue_date||N.next_issue||null,charge_issue_date:N.charge_issue_date||N.next_due||null,last_due_date:N.last_due_date,requires_manager_approval:N.requires_manager_approval},{file:N._bucket==="file"}).slice(0,-1).map(z=>e.jsxs("li",{className:"text-[11.5px] text-slate-500 leading-snug flex items-start gap-1",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-slate-300 flex-none mt-1.5"})," ",z]},z))})]}),e.jsx("td",{className:"px-4 py-3 text-left whitespace-nowrap",onClick:z=>z.stopPropagation(),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[N.due_now&&N._mode&&e.jsxs("button",{type:"button",disabled:!!O,onClick:()=>T({action:"run",charge_type_ids:[N.id]},z=>`הופקו ${Vs((z==null?void 0:z.charges)||0)} חיובים · ${Ln((z==null?void 0:z.total)||0)}`),className:"h-8 px-3 rounded-full bg-blue-600 text-white text-[12px] font-bold inline-flex items-center gap-1 hover:bg-blue-700 disabled:opacity-50",children:[O===N.id?e.jsx(Ie,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ns,{className:"w-3.5 h-3.5"})," הפק עכשיו"]}),N._needsApproval&&N._live&&!((v=N._approvals)!=null&&v.demand)&&e.jsxs("button",{type:"button",disabled:!!O,onClick:()=>$({row:N,stage:"demand"}),className:`h-8 px-3 rounded-full bg-amber-500 text-white text-[12px] font-bold
35                          inline-flex items-center gap-1.5 hover:bg-amber-600 disabled:opacity-50`,children:[e.jsx(xt,{className:"w-3.5 h-3.5"})," אישור דרישת תשלום"]}),N._needsApproval&&N._live&&((F=N._approvals)==null?void 0:F.demand)&&!((K=N._approvals)!=null&&K.charge)&&e.jsxs("button",{type:"button",disabled:!!O,onClick:()=>$({row:N,stage:"charge"}),className:`h-8 px-3 rounded-full bg-amber-500 text-white text-[12px] font-bold
36                          inline-flex items-center gap-1.5 hover:bg-amber-600 disabled:opacity-50`,children:[e.jsx(xt,{className:"w-3.5 h-3.5"})," אישור חיוב ומסמך תשלום"]}),N._canActivate?e.jsxs("button",{type:"button",onClick:()=>g(N),disabled:!!O,className:"h-8 px-3 rounded-full text-[12px] font-bold inline-flex items-center gap-1.5 disabled:opacity-50 bg-emerald-600 text-white hover:bg-emerald-700",children:[e.jsx(vo,{className:"w-3.5 h-3.5"})," ניהול חיובים"]}):N._live&&!N._issued?e.jsxs("button",{type:"button",onClick:()=>g(N),disabled:!!O,className:`h-8 px-3 rounded-full border border-slate-200 bg-white text-[12px] font-bold text-slate-600
37                          inline-flex items-center gap-1.5 hover:border-emerald-300 hover:text-emerald-700 disabled:opacity-50`,children:[e.jsx(It,{className:"w-3.5 h-3.5"})," עריכה"]}
37):N._live?null:e.jsx("span",{className:"text-[11.5px] text-slate-400",children:"מחזור קודם"}),N._mode&&N._live&&e.jsx("button",{type:"button",disabled:!!O,onClick:()=>T({action:"disable",charge_type_id:N.id},"סוג החיוב הושהה"),title:"השהיה","aria-label":"השהיה",className:"w-8 h-8 rounded-full border border-slate-200 bg-white grid place-items-center text-slate-400 hover:text-amber-600 hover:border-amber-200 disabled:opacity-50",children:e.jsx(ho,{className:"w-3.5 h-3.5"})})]})})]}),N._steps&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"rounded-2xl border border-slate-200/70 bg-slate-50 px-6 py-5",children:[e.jsx(gx,{steps:N._steps,caption:N._caption}),(((Z=N._approvals)==null?void 0:Z.demand)||((H=N._approvals)==null?void 0:H.charge))&&e.jsx("ul",{className:"mt-4 pt-3 border-t border-slate-200/70 flex flex-wrap items-center justify-center gap-x-6 gap-y-1",children:[["demand","דרישת התשלום"],["charge","החיוב ומסמך התשלום"]].map(([z,te])=>{var ie;return(ie=N._approvals)!=null&&ie[z]?e.jsxs("li",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:[e.jsx(xt,{className:"w-3.5 h-3.5 text-emerald-600 flex-none"}),te," אושרה על ידי ",e.jsx("b",{className:"text-slate-700",children:N._approvals[z].by||"מנהל"}),e.jsx("span",{dir:"ltr",className:"tabular-nums",children:hx(N._approvals[z].at)})]},z):null})})]})})}),E===N._key&&N._batch&&e.jsx("tr",{className:"bg-slate-50/60",children:e.jsx("td",{colSpan:8,className:"px-4 py-3",children:e.jsx(_x,{kibbutzId:t,batch:N._batch,locked:!!N._batch.bill_count,onChanged:_})})})]},N._key)})]})]})}),C==="file"&&e.jsxs("p",{className:"text-[11.5px] text-slate-400 mt-3 flex items-start gap-1.5",children:[e.jsx(Ke,{className:"w-3.5 h-3.5 flex-none mt-0.5"}),"חיוב מקובץ נוצר עם אישור הקובץ, לפי מועד התשלום שנקבע בטעינה. אין לו מחזור קבוע — הקובץ מגיע מהתאגיד ולא לפי לוח שנה — ובתום המחזור הוא נשאר כאן בסטטוס «הסתיים»."]}),y&&e.jsx(tc,{row:y.row,stage:y.stage,period:s==null?void 0:s.period,busy:O===y.row.id,onClose:()=>$(null),onConfirm:N=>T({action:"approve_cycle",charge_type_id:y.row.id,stage:y.stage,period:s==null?void 0:s.period,note:N},hc).then(()=>$(null))}),x&&e.jsx(Mm,{type:x,accounts:r,residents:p,properties:d,busy:O===x.id,onClose:()=>g(null),onSave:M})]}):e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-12 text-center",children:[e.jsx(Xe,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsx("h3",{className:"text-base font-semibold mb-1",children:"אין עדיין סוגי חיוב"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"הגדירו סוג חיוב במסך «סוגי חיובים», והוא יופיע כאן מושהה — מוכן להפעלה יזומה או אוטומטית."})]})}const bi={done:{dot:"bg-emerald-500 border-emerald-500",line:"bg-emerald-500",text:"text-emerald-700"},now:{dot:"bg-indigo-600 border-indigo-600 ring-4 ring-indigo-100",line:"bg-indigo-500",text:"text-slate-900"},waiting:{dot:"bg-amber-500 border-amber-500 ring-4 ring-amber-100",line:"bg-slate-200",text:"text-amber-700"},blocked:{dot:"bg-white border-amber-400",line:"bg-slate-200",text:"text-amber-700"},next:{dot:"bg-white border-slate-300",line:"bg-slate-200",text:"text-slate-400"}},fi=t=>t.done?t.at?"now":"done":t.awaiting?"waiting":t.blocked?"blocked":t.at?"now":"next";function gx({steps:t=[],caption:s=""}){const n=t.length?100/t.length/2:0;return e.jsxs("div",{className:"relative w-full",children:[e.jsx("div",{className:"absolute top-[12px] h-1 flex overflow-hidden rounded-full",style:{insetInlineStart:`${n}%`,insetInlineEnd:`${n}%`},"aria-hidden":"true",children:t.slice(0,-1).map(a=>e.jsx("span",{className:`flex-1 ${bi[fi(a)].line}`},a.v))}),e.jsx("ol",{className:"relative flex items-start w-full","aria-label":"שלבי המחזור",children:t.map(a=>{var o;const l=fi(a),r=bi[l];return e.jsxs("li",{className:"flex-1 min-w-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-7 grid place-items-center",children:e.jsxs("span",{className:`grid place-items-center flex-none rounded-full border-2 ${r.dot} ${l==="next"?"w-4 h-4":"w-7 h-7"}`,children:[(l==="done"||l==="now")&&e.jsx(ye,{className:"w-3.5 h-3.5 text-white",strokeWidth:3}),l==="waiting"&&e.jsx(xt,{className:"w-3.5 h-3.5 text-white",strokeWidth:2.5}),l==="blocked"&&e.jsx(xt,{className:"w-3.5 h-3.5 text-amber-500",strokeWidth:2.5})]})}),e.jsx("p",{className:`text-[15px] leading-tight mt-2.5 text-center px-1 ${a.at?"font-black":"font-bold"} ${r.text}`,children:a.l}),a.date&&e.jsx("p",{className:"text-[14px] font-bold text-slate-500 tabular-nums mt-1.5",dir:"ltr",children:xn(a.date)}),(a.awaiting||a.blocked)&&e.jsx("p",{className:`text-[12px] font-bold mt-1 text-center ${r.text}`,children:a.awaiting?"אושר · ממתין להפקה":"ממתין לאישור מנהל"}),a.v===((o=t[0])==null?void 0:o.v)&&s&&e.jsx("p",{className:"text-[12.5px] text-slate-400 mt-1 text-center",children:s})]},a.v)})})]})}function yx({row:t}){if(t._bucket==="file"){const s=t._batch;return s?e.jsxs("span",{children:[s.period_name||fa(s.created_date),s.due_date?e.jsxs(e.Fragment,{children:[" · תשלום ",e.jsx("b",{className:"text-slate-800",children:fa(s.due_date)})]}):null]}):e.jsx("span",{className:"text-slate-300",children:"טרם נטען קובץ"})}return t._mode?t._bucket==="auto"?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Be,{className:"w-3.5 h-3.5 text-emerald-600 flex-none"}),"הפקה ",e.jsx("b",{className:"text-slate-800",children:t.next_issue?fa(t.next_issue):`ה-${t.demand_issue_day||t.due_day||"—"}`}),e.jsx("span",{className:"text-slate-300",children:"·"}),"חיוב ",e.jsx("b",{className:"text-slate-800",children:t.next_due?fa(t.next_due):`ה-${t.charge_issue_day||t.due_day||"—"}`})]}):t.issue_timing!=="scheduled"?e.jsx("span",{className:"text-slate-500",children:"בהפעלה"}):e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Be,{className:"w-3.5 h-3.5 text-indigo-500 flex-none"}),t.charge_issue_date?e.jsxs(e.Fragment,{children:["חיוב ",e.jsx("b",{className:"text-slate-800",children:fa(t.charge_issue_date)})]}):"מתוזמן",t.requires_manager_approval?" · דורש אישור מנהל":""]}):e.jsx("span",{className:"text-slate-300",children:"—"})}function _x({kibbutzId:t,batch:s,locked:n,onChanged:a}){const[l,r]=i.useState(null),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState(null),[h,b]=i.useState(null),f=i.useCallback(()=>{Promise.all([D.entities.WaterReading.filterAll({kibbutz_id:t,batch_id:s.id}).catch(()=>[]),D.entities.WaterMeter.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[])]).then(([S,P,E])=>{r((S||[]).slice().sort((k,C)=>(k.row_no||0)-(C.row_no||0))),p(P||[]),d(E||[])})},[t,s.id]);if(i.useEffect(()=>{f()},[f]),l===null)return e.jsx("p",{className:"text-[12.5px] text-slate-400 py-2",children:"טוען את שורות הקובץ…"});if(!l.length)return e.jsx("p",{className:"text-[12.5px] text-slate-400 py-2",children:"אין שורות בטעינה הזאת."});const x=new Map(o.map(S=>[S.id,S])),g=new Map(u.map(S=>[S.id,S])),y=S=>{var P;return((P=g.get(S))==null?void 0:P.name)||""},$=S=>{var P;return S.souls_used??((P=x.get(S.water_meter_id))==null?void 0:P.souls)??null},O=S=>{var P;return S.eligible_used??((P=x.get(S.water_meter_id))==null?void 0:P.eligible_count)??null},A=S=>S==null||S===""?"—":S;return e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-2 border-b border-slate-100 flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[12.5px] font-black text-slate-700",children:[s.period_name||"טעינה"," · ",Vs(l.length)," שורות"]}),e.jsx("span",{className:"text-[11.5px] text-slate-400",children:n?"שורות שהופק מהן חיוב נעולות; מה שטרם חויב עדיין ניתן לתיקון.":"ניתן לערוך שורה כל עוד לא הופק ממנה חיוב."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-[12.5px]",children:[e.jsx("thead",{className:"bg-slate-50/70 text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"#"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"חשבון משלם"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"נפשות / זכאים"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"מונה"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"קריאה אחרונה"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"קריאה עדכנית"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"צריכה (מ״ק)"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"סכום (₪)"}),e.jsx("th",{className:"text-right px-3 py-2 font-semibold",children:"סטטוס"}),e.jsx("th",{className:"px-3 py-2"})]})}),e.jsx("tbody",{children:l.map(S=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"px-3 py-2 text-slate-400 tabular-nums",children:S.row_no}),e.jsx("td",{className:"px-3 py-2 font-bold text-slate-700",children:y(S.payer_account_id)||S.consumer_name||e.jsx("span",{className:"text-slate-300",children:"—"})}),e.jsxs("td",{className:"px-3 py-2 tabular-nums",children:[e.jsx("span",{className:"font-black text-emerald-700",children:A($(S))}),e.jsx("span",{className:"text-slate-300 mx-1",children:"/"}),e.jsx("span",{className:"font-black text-amber-600",children:O(S)??
370})]}),e.jsx("td",{className:"px-3 py-2 text-slate-500 tabular-nums",dir:"ltr",children:S.meter_number||"—"}),e.jsx("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:A(S.previous_reading)}),e.jsx("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:A(S.current_reading)}),e.jsx("td",{className:"px-3 py-2 tabular-nums",dir:"ltr",children:A(S.consumption)}),e.jsx("td",{className:"px-3 py-2 tabular-nums font-bold",dir:"ltr",children:S.amount?Ln(S.amount):"—"}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("span",{className:`text-[11px] font-bold px-2 py-0.5 rounded-full ${S.status===Tt.ok?"bg-emerald-50 text-emerald-700":S.status===Tt.opening?"bg-slate-100 text-slate-500":"bg-amber-50 text-amber-700"}`,children:Pa[S.status]||S.status}),S.charge_id&&e.jsx("span",{className:"block text-[10.5px] text-emerald-600 mt-0.5",children:"הופק חיוב"})]}),e.jsx("td",{className:"px-3 py-2 text-left whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[S.breakdown&&e.jsxs("button",{type:"button",onClick:()=>b(S),className:"h-7 px-2.5 rounded-full border border-slate-200 text-[11.5px] font-bold text-slate-600 hover:bg-slate-50 inline-flex items-center gap-1",children:[e.jsx(Ma,{className:"w-3 h-3"})," הצג חישוב"]}),!S.charge_id&&e.jsxs("button",{type:"button",onClick:()=>m(S),className:"h-7 px-2.5 rounded-full border border-slate-200 text-[11.5px] font-bold text-slate-600 hover:bg-slate-50 inline-flex items-center gap-1",children:[e.jsx(It,{className:"w-3 h-3"})," עריכה"]})]})})]},S.id))})]})}),h&&e.jsx(Wn,{onClose:()=>b(null),title:`פירוט החישוב · ${y(h.payer_account_id)||h.consumer_name||""} · מונה ${h.meter_number||""}`.trim(),children:e.jsx("div",{className:"max-w-xl mx-auto",children:e.jsx(dr,{b:h.breakdown})})}),c&&e.jsx(pc,{kibbutzId:t,row:c,meters:o,accounts:u,onClose:()=>m(null),onSaved:()=>{m(null),f(),a==null||a()}})]})}const fl=t=>ve(t),jx={draft:"טיוטה",pending:"ממתין לאישור",approved:"מאושר",issued:"הופק",cancelled:"בוטל",credited:"זוכה"},Nx={monthly:"חודשי",bimonthly:"דו-חודשי",quarterly:"רבעוני",yearly:"שנתי",one_time:"חד-פעמי",per_file:"לפי טעינת קובץ"},vx={draft:"bg-slate-100 text-slate-600",pending:"bg-amber-50 text-amber-700",approved:"bg-blue-50 text-blue-700",issued:"bg-emerald-50 text-emerald-700",cancelled:"bg-red-50 text-red-600",credited:"bg-purple-50 text-purple-700"};function gi({kibbutzId:t,mode:s}){const n=s==="recurring",[a,l]=i.useState(!0),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState(!1),[x,g]=i.useState(""),y=i.useCallback(async()=>{l(!0);try{const[w,_,T,M]=await Promise.all([D.entities.Charge.filter({kibbutz_id:t},"-created_date",5e3).catch(()=>[]),D.entities.BillingPlan.filter({kibbutz_id:t},"-created_date",500).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filter({kibbutz_id:t},"order",300).catch(()=>[])]);o(w||[]),u(_||[]),c(T||[]),h(M||[])}catch{W.error("שגיאה בטעינה")}finally{l(!1)}},[t]);i.useEffect(()=>{y()},[y]);const $=i.useCallback(w=>{const _=d.find(T=>T.id===w);return _?_.name||`#${_.account_number}`:"—"},[d]),O=i.useCallback(w=>{var _;return((_=m.find(T=>T.id===w))==null?void 0:_.name)||"—"},[m]),A=i.useMemo(()=>n?r.filter(w=>w.billing_plan_id):r.filter(w=>!w.billing_plan_id),[r,n]),S=i.useMemo(()=>[...new Set(A.map(w=>w.billing_period).filter(Boolean))].sort().reverse(),[A]),P=i.useMemo(()=>x?A.filter(w=>w.billing_period===x):A,[A,x]),E=async w=>{if(confirm("למחוק חיוב זה?"))try{await D.entities.Charge.delete(w.id),W.success("נמחק"),y()}catch{W.error("שגיאה")}},k=async w=>{try{await D.entities.BillingPlan.update(w.id,{status:w.status==="active"?"paused":"active"}),y()}catch{W.error("שגיאה")}},C=async w=>{if(confirm("למחוק תוכנית חיוב חוזרת? חיובים שכבר נוצרו יישארו."))try{await D.entities.BillingPlan.delete(w.id),W.success("נמחקה"),y()}catch{W.error("שגיאה")}};return n?e.jsx(bc,{kibbutzId:t}):b?e.jsx(hm,{kibbutzId:t,mode:s,onClose:()=>f(!1),onDone:()=>{f(!1),y()}}):a?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})}):e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:n?"חיובים חוזרים ותוכניות חיוב חודשיות.":"חיובים חד־פעמיים ידניים למשלמים נבחרים."}),e.jsxs("button",{onClick:()=>
37f(!0),className:`h-9 px-4 rounded-full text-white text-sm font-bold inline-flex items-center gap-1.5 ${n?"bg-blue-600":"bg-amber-600"}`,children:[e.jsx(We,{className:"w-4 h-4"})," ",n?"חיוב חודשי חדש":"חיוב חד־פעמי חדש"]})]}),n&&p.length>0&&e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 mb-5",children:p.map(w=>e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0",children:e.jsx(Mt,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h4",{className:"text-sm font-bold truncate",children:w.name||O(w.charge_type_id)}),e.jsxs("p",{className:"text-xs text-slate-400",children:[Oa(w.calculation_method)," · ",Nx[w.billing_cycle]||w.billing_cycle]})]})]}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${w.status==="active"?"bg-emerald-50 text-emerald-700":"bg-slate-100 text-slate-500"}`,children:w.status==="active"?"פעילה":w.status==="paused"?"מושהית":w.status})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] mb-2",children:[e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-blue-50 text-blue-700",children:fl(w.rate)}),e.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-slate-100 text-slate-600",children:[r.filter(_=>_.billing_plan_id===w.id).length," חיובים"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>k(w),className:"h-8 px-3 rounded-full border border-slate-200 text-xs inline-flex items-center gap-1 hover:bg-slate-50",children:w.status==="active"?e.jsxs(e.Fragment,{children:[e.jsx(Ed,{className:"w-3.5 h-3.5"})," השהה"]}):e.jsxs(e.Fragment,{children:[e.jsx(vo,{className:"w-3.5 h-3.5"})," הפעל"]})}),e.jsx("button",{onClick:()=>C(w),className:"w-8 h-8 rounded-full flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})]})]},w.id))}),S.length>1&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 overflow-x-auto pb-1",children:[e.jsx(hr,{className:"w-4 h-4 text-slate-400 flex-shrink-0"}),e.jsx("button",{onClick:()=>g(""),className:`h-8 px-3 rounded-full text-xs font-medium border flex-shrink-0 ${x?"bg-white border-slate-200 text-slate-600":"bg-indigo-600 text-white border-transparent"}`,children:"הכל"}),S.map(w=>e.jsx("button",{onClick:()=>g(w),className:`h-8 px-3 rounded-full text-xs font-medium border flex-shrink-0 ${x===w?"bg-indigo-600 text-white border-transparent":"bg-white border-slate-200 text-slate-600"}`,children:w},w))]}),P.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-10 text-center",children:[n?e.jsx(Mt,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}):e.jsx(Ns,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsxs("h3",{className:"text-base font-semibold mb-1",children:["אין ",n?"חיובים חוזרים":"חיובים חד־פעמיים"," עדיין"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"צרו חיוב חדש והנתונים יופיעו כאן. הסכומים מחושבים אוטומטית לכל משלם לפי סוג החיוב."}),e.jsxs("button",{onClick:()=>f(!0),className:`h-9 px-4 rounded-full text-white text-sm font-bold inline-flex items-center gap-1.5 ${n?"bg-blue-600":"bg-amber-600"}`,children:[e.jsx(We,{className:"w-4 h-4"})," חיוב חדש"]})]}):e.jsx("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"משלם"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סוג חיוב"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"תקופה"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סכום"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סטטוס"}),e.jsx("th",{className:"px-4 py-2.5"})]})}),e.jsx("tbody",{children:P.map(w=>e.jsxs("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-2.5 font-medium",children:$(w.payer_account_id)}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3.5 h-3.5 text-slate-400"}),O(w.charge_type_id)]})}),e.jsx("td",{className:"px-4 py-2.5 text-slate-500",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Be,{className:"w-3.5 h-3.5 text-slate-400"}),w.billing_period||"—"]}
37)}),e.jsx("td",{className:"px-4 py-2.5 font-bold",children:fl(w.amount)}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${vx[w.status]||"bg-slate-100 text-slate-600"}`,children:jx[w.status]||w.status})}),e.jsx("td",{className:"px-4 py-2.5 text-left",children:e.jsx("button",{onClick:()=>E(w),className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})})]},w.id))}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"border-t-2 border-slate-200 bg-slate-50",children:[e.jsxs("td",{colSpan:3,className:"px-4 py-2.5 text-xs text-slate-500 inline-flex items-center gap-1",children:[e.jsx(De,{className:"w-3.5 h-3.5"})," ",P.length," חיובים"]}),e.jsx("td",{className:"px-4 py-2.5 font-black",children:fl(P.reduce((w,_)=>w+(Number(_.amount)||0),0))}),e.jsx("td",{colSpan:2})]})})]})})]})}const yi=()=>new Date().toISOString().slice(0,7),wx={draft:"טיוטה",pending_approval:"ממתין לאישור",approved:"מאושר",issued:"הופק",sent:"נשלח",paid:"שולם",partial:"שולם חלקית",overdue:"באיחור",cancelled:"בוטל",credited:"זוכה"},kx={draft:"bg-slate-100 text-slate-600",issued:"bg-blue-50 text-blue-700",sent:"bg-indigo-50 text-indigo-700",paid:"bg-emerald-50 text-emerald-700",partial:"bg-amber-50 text-amber-700",overdue:"bg-red-50 text-red-600",cancelled:"bg-slate-100 text-slate-400",credited:"bg-purple-50 text-purple-700"},_i=[{v:"email",l:'דוא"ל',icon:no},{v:"whatsapp",l:"WhatsApp",icon:gn},{v:"personal_area",l:"אזור אישי",icon:or},{v:"print",l:"הדפסה/מסירה",icon:yo}];function Sx({kibbutzId:t}){var ie,V,Y,J;const[s,n]=i.useState(!0),[a,l]=i.useState(yi()),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState([]),[x,g]=i.useState([]),[y,$]=i.useState([]),[O,A]=i.useState({}),[S,P]=i.useState(!1),[E,k]=i.useState(null),[C,w]=i.useState(null),[_,T]=i.useState([]),[M,B]=i.useState(null),R=i.useCallback(async()=>{n(!0);try{const[I,X,se,G,ne,ge,ke,be,je]=await Promise.all([D.entities.MonthlyStatement.filter({kibbutz_id:t},"-billing_month",5e3).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Charge.filter({kibbutz_id:t},"-created_date",8e3).catch(()=>[]),D.entities.Payment.filter({kibbutz_id:t},"-created_date",5e3).catch(()=>[]),D.entities.ChargeType.filter({kibbutz_id:t},"order",300).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me}).catch(()=>[]),D.entities.BillingSettings.filter({kibbutz_id:t},"-created_date",1).catch(()=>[]),D.entities.Kibbutz.get(t).catch(()=>null)]);o(I||[]),u(X||[]),c(se||[]),h(G||[]),f(ne||[]),g(ge||[]),$(ke||[]);const Ce=(be||[])[0]||{};A({name:Ce.legal_name||(je==null?void 0:je.name)||"חשבון תקופתי",address:Ce.address||"",phone:Ce.phone||"",email:Ce.email||"",business_number:Ce.business_number||"",logo_url:Ce.logo_url||(je==null?void 0:je.logo_url)||"",footer_note:Ce.footer_note||""})}catch{W.error("שגיאה בטעינה")}finally{n(!1)}},[t]);i.useEffect(()=>{R()},[R]);const j=i.useCallback(I=>{var X;return((X=b.find(se=>se.id===I))==null?void 0:X.name)||"חיוב"},[b]),q=i.useCallback(I=>x.find(X=>X.id===(I==null?void 0:I.family_id)),[x]),L=i.useCallback(I=>{const X=y.filter(se=>se.family_id===(I==null?void 0:I.family_id)&&se.status!=="inactive");return{emails:[...new Set(X.map(se=>se.email).filter(Boolean))],phones:[...new Set(X.map(se=>se.phone).filter(Boolean))],head:X.find(se=>se.family_role==="head")||X[0]}},[y]),N=i.useMemo(()=>r.filter(I=>I.billing_month===a),[r,a]),v=i.useMemo(()=>{const I=new Set(r.map(X=>X.billing_month).filter(Boolean));return I.add(yi()),I.add(a),[...I].sort().reverse()},[r,a]),F=i.useMemo(()=>{const I=new Set(N.map(se=>se.payer_account_id));return[...new Set(d.filter(se=>se.billing_period===a&&se.status==="approved"&&se.payer_account_id).map(se=>se.payer_account_id))].filter(se=>!I.has(se)).length},[d,a,N]);async function K(){var I,X;P(!0);try{const se=d.filter(be=>be.billing_period===a&&(be.status==="approved"||be.status==="issued")),G={};for(const be of se)(G[I=be.payer_account_id]||(G[I]=[])).push(be);
37const ne=Object.keys(G).filter(Boolean);if(ne.length===0){W.error("אין חיובים מאושרים בתקופה זו להפקה"),P(!1);return}const ge=new Date().toISOString();let ke=0;for(const be of ne){const je=p.find(ue=>ue.id===be);if(!je)continue;const Ce=q(je),ee=L(je),oe=G[be].map(ue=>({description:ue.description,charge_type:j(ue.charge_type_id),quantity:ue.quantity,rate:ue.rate,amount:ue.amount})),le=G[be].reduce((ue,Ee)=>ue+(Number(Ee.amount)||0),0),xe=G[be].reduce((ue,Ee)=>ue+(Number(Ee.discount_amount)||0),0),de=G[be].reduce((ue,Ee)=>ue+(Number(Ee.credit_amount)||0),0),ae=r.filter(ue=>ue.payer_account_id===be&&ue.billing_month<a).sort((ue,Ee)=>Ee.billing_month.localeCompare(ue.billing_month))[0],Ne=ae?Number(ae.balance_due)||0:Number(je.opening_balance)||0,we=m.filter(ue=>ue.payer_account_id===be&&ue.status==="paid"&&String(ue.payment_date||"").slice(0,7)===a).reduce((ue,Ee)=>ue+(Number(Ee.amount)||0),0),Ue=Ne+le-xe-de-we,re={issuer:O,account:{account_number:je.account_number,name:je.name,id_number:je.id_number,payment_method:je.payment_method},family:{name:Ce==null?void 0:Ce.name,address:[Ce==null?void 0:Ce.street,Ce==null?void 0:Ce.house_number].filter(Boolean).join(" "),head:(X=ee.head)==null?void 0:X.full_name,emails:ee.emails,phones:ee.phones},lines:oe,previous_balance:Ne,charges_total:le,discounts_total:xe,credits_total:de,payments_total:we,balance_due:Ue,month:a,issued_at:ge},Qe={kibbutz_id:t,payer_account_id:be,billing_month:a,previous_balance:Ne,charges_total:le,discounts_total:xe,credits_total:de,payments_total:we,balance_due:Ue,status:"issued",snapshot:re,due_date:je.due_date||null,issued_at:ge},Et=r.find(ue=>ue.payer_account_id===be&&ue.billing_month===a);let bt;Et?(await D.entities.MonthlyStatement.update(Et.id,Qe),bt=Et.id):bt=(await D.entities.MonthlyStatement.create(Qe)).id;for(const ue of G[be])(ue.status!=="issued"||ue.statement_id!==bt)&&await D.entities.Charge.update(ue.id,{statement_id:bt,status:"issued"});ke++}D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"statements_generated",entity_type:"monthly_statement",new_value:`${ke} מסמכי חשבון · ${Lt(a)}`}).catch(()=>{}),W.success(`הופקו ${ke} מסמכי חשבון`),await R()}catch{W.error("שגיאה בהפקת המסמכים")}finally{P(!1)}}async function Z(I,X){var je,Ce,ee,oe,le,xe,de,ae,Ne;const se=p.find(we=>we.id===I.payer_account_id),G=L(se),ne=Number(I.balance_due)||0,ge=`חשבון לתקופה ${Lt(I.billing_month)} — ${O.name}`;let ke="sent",be=null;try{if(X==="email"){const we=G.emails[0];if(!we){W.error('אין כתובת דוא"ל למשלם');return}const Ue=`<div dir="rtl" style="font-family:Arial,sans-serif"><h2>${O.name}</h2><p>שלום ${((Ce=(je=I.snapshot)==null?void 0:je.account)==null?void 0:Ce.name)||((ee=G.head)==null?void 0:ee.full_name)||""},</p><p>מצורף חשבון לתקופה <b>${Lt(I.billing_month)}</b>.</p><p>יתרה לתשלום: <b>${as(ne)}</b>${I.due_date?` · לתשלום עד ${I.due_date}`:""}</p><p>ניתן לצפות בפירוט המלא ולשלם באזור האישי במערכת.</p><p>${O.footer_note||""}</p></div>`,re=await D.functions.invoke("sendNotification",{channel:"email",to:we,subject:ge,body:Ue});!((oe=re==null?void 0:re.data)!=null&&oe.ok)&&((le=re==null?void 0:re.data)==null?void 0:le.ok)!==void 0&&(ke="failed",be="email_failed")}else if(X==="whatsapp"){const we=G.phones[0];if(!we){W.error("אין טלפון למשלם");return}const Ue=`חשבון ${Lt(I.billing_month)} · יתרה לתשלום ${as(ne)}${I.due_date?` · עד ${I.due_date}`:""}. לפירוט מלא — האזור האישי.`,re=await D.functions.invoke("sendNotification",{channel:"whatsapp",to:we,name:((de=(xe=I.snapshot)==null?void 0:xe.account)==null?void 0:de.name)||"",variables:[ge,Ue]});((ae=re==null?void 0:re.data)==null?void 0:ae.ok)===!1&&(ke="failed",be=((Ne=re==null?void 0:re.data)==null?void 0:Ne.error)||"whatsapp_failed")}await D.entities.StatementDelivery.create({kibbutz_id:t,statement_id:I.id,payer_account_id:I.payer_account_id,channel:X,status:ke,sent_at:new Date().toISOString()}),ke==="sent"&&I.status==="issued"&&await D.entities.MonthlyStatement.update(I.id,{status:"sent"}),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"statement_sent",entity_type:"monthly_statement",entity_id:I.id,payer_account_id:I.payer_account_id,new_value:X}).catch(()=>{}
37),ke==="failed"?W.error(`השליחה נכשלה (${be})`):W.success("החשבון נשלח"),w(null),await R()}catch{W.error("שגיאה בשליחה")}}async function H(){const I=N.filter(X=>X.status==="issued");if(I.length===0){W.error("אין מסמכים חדשים לשליחה");return}if(confirm(`לשלוח ${I.length} חשבונות לפי אמצעי הקבלה המועדף של כל משלם?`)){P(!0);for(const X of I){const se=p.find(ne=>ne.id===X.payer_account_id),G=Ea(se==null?void 0:se.preferred_delivery_channel);for(const ne of G.length?G:["personal_area"])await Z(X,ne)}P(!1)}}async function z(I){B(I);try{const X=await D.entities.StatementDelivery.filter({kibbutz_id:t,statement_id:I.id},"-sent_at",100);T(X||[])}catch{T([])}}if(s)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})});const te=N.reduce((I,X)=>({charges:I.charges+(Number(X.charges_total)||0),balance:I.balance+(Number(X.balance_due)||0)}),{charges:0,balance:0});return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-slate-500",children:"תקופה:"}),e.jsx("select",{value:a,onChange:I=>l(I.target.value),className:"h-9 rounded-lg border border-slate-200 px-3 text-sm",children:v.map(I=>e.jsx("option",{value:I,children:Lt(I)},I))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:K,disabled:S,className:"h-9 px-4 rounded-full bg-indigo-600 text-white text-sm font-bold inline-flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(br,{className:`w-4 h-4 ${S?"animate-spin":""}`})," הפק מסמכי חשבון"]}),N.some(I=>I.status==="issued")&&e.jsxs("button",{onClick:H,disabled:S,className:"h-9 px-4 rounded-full bg-emerald-600 text-white text-sm font-bold inline-flex items-center gap-1.5 disabled:opacity-50",children:[e.jsx(Gs,{className:"w-4 h-4"})," שלח הכל"]})]})]}),F>0&&e.jsxs("div",{className:"flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-xl px-4 py-2.5 mb-4 text-sm text-amber-800",children:[e.jsx(At,{className:"w-4 h-4 flex-shrink-0"})," ",F,' חשבונות עם חיובים מאושרים בתקופה זו טרם הופקו. לחצו „הפק מסמכי חשבון".']}),N.length>0&&e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4",children:[{l:"מסמכים בתקופה",v:N.length,icon:nt,tone:"text-indigo-600 bg-indigo-50"},{l:"סה״כ חיובים",v:as(te.charges),icon:nt,tone:"text-blue-600 bg-blue-50"},{l:"יתרה לגבייה",v:as(te.balance),icon:ws,tone:"text-amber-600 bg-amber-50"},{l:"נשלחו",v:N.filter(I=>["sent","paid","partial"].includes(I.status)).length,icon:la,tone:"text-emerald-600 bg-emerald-50"}].map(I=>{const X=I.icon;return e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-4",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center mb-2 ${I.tone}`,children:e.jsx(X,{className:"w-5 h-5"})}),e.jsx("p",{className:"text-lg font-black text-slate-900",children:I.v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I.l})]},I.l)})}),N.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-10 text-center",children:[e.jsx(nt,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsxs("h3",{className:"text-base font-semibold mb-1",children:["אין מסמכי חשבון לתקופה ",Lt(a)]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'לאחר יצירת חיובים מאושרים לתקופה, לחצו „הפק מסמכי חשבון" כדי לאגד אותם למסמך אחד לכל משלם.'})]}):e.jsx("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"משלם"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"חיובים"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"יתרה לתשלום"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סטטוס"}),e.jsx("th",{className:"px-4 py-2.5"})]})}),e.jsx("tbody",{children:N.map(I=>{var X,se,G,ne,ge;return e.jsxs("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60",children:[e.jsxs("td",{className:"px-4 py-2.5 font-medium",children:[((se=(X=I.snapshot)==null?void 0:X.account)==null?void 0:se.name)||((G=p.find(ke=>ke.id===I.payer_account_id))==null?void 0:G.name)||"—"," ",e.jsxs("span",{className:"text-xs text-slate-400",children:["#",((ge=(ne=I.snapshot)==null?void 0:ne.account)==null?void 0:ge.account_number)||""]})]}),e.jsx("td",{className:"px-4 py-2.5",children:as(I.charges_total)}),e.jsx("td",{className:"px-4 py-2.5 font-bold",children:as(I.balance_due)}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${kx[I.status]||"bg-slate-100 text-slate-600"}`,children:wx[I.status]||I.status})}),e.jsx("td",{className:"px-4 py-2.5 text-left",children:e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx("button",{onClick:()=>k(I),title:"צפייה / הדפסה",className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100",children:e.jsx(fs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>w(I),title:"שליחה",className:"w-8 h-8 rounded-lg flex items-center justify-center text-indigo-600 hover:bg-indigo-50",children:e.jsx(Gs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>z(I),title:"יומן שליחות",className:"w-8 h-8 rounded-lg flex items-center justify-center text-slate-400 hover:bg-slate-100",children:e.jsx(Tl,{className:"w-4 h-4"})})]})})]},I.id)})})]})}),E&&e.jsx(Wn,{onClose:()=>k(null),title:`מסמך חשבון — ${((V=(ie=E.snapshot)==null?void 0:ie.account)==null?void 0:V.name)||""}`,children:e.jsx(sd,{statement:E})}),C&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",onClick:()=>w(null),children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-md p-5",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-base font-bold",children:"שליחת חשבון"}),e.jsx("button",{onClick:()=>w(null),className:"w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-slate-500 mb-3",children:[(J=(Y=C.snapshot)==null?void 0:Y.account)==null?void 0:J.name," · ",Lt(C.billing_month)," · יתרה ",as(C.balance_due)]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:_i.map(I=>{const X=I.icon,se=p.find(ne=>ne.id===C.payer_account_id),G=Ea(se==null?void 0:se.preferred_delivery_channel).includes(I.v);return e.jsxs("button",{onClick:()=>Z(C,I.v),className:`flex items-center gap-2 h-11 px-3 rounded-xl border text-sm ${G?"border-indigo-300 bg-indigo-50 text-indigo-700":"border-slate-200 text-slate-600 hover:bg-slate-50"}`,children:[e.jsx(X,{className:"w-4 h-4"})," ",I.l," ",G&&e.jsx("span",{className:"text-[10px] mr-auto",children:"מועדף"})]},I.v)})})]})}),M&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4",onClick:()=>B(null),children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-md p-5",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-base font-bold inline-flex items-center gap-1.5",children:[e.jsx(Tl,{className:"w-4 h-4"})," יומן שליחות"]}),e.jsx("button",{onClick:()=>B(null),className:"w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-4 h-4"})})]}),_.length===0?e.jsx("p",{className:"text-sm text-slate-400 text-center py-6",children:"טרם נשלח חשבון זה"}):e.jsx("div",{className:"space-y-2",children:_.map(I=>{const X=_i.find(G=>G.v===I.channel),se=(X==null?void 0:X.icon)||Gs;return e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-200 px-3 py-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm",children:[e.jsx(se,{className:"w-4 h-4 text-slate-400"})," ",(X==null?void 0:X.l)||I.channel]}),e.jsx("span",{className:"text-xs text-slate-400",children:String(I.sent_at||"").slice(0,16).replace("T"," ")}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${I.status==="failed"?"bg-red-50 text-red-600":"bg-emerald-50 text-emerald-700"}`,children:I.status==="failed"?"נכשל":"נשלח"})]},I.id)})})]})})]})}const Os=t=>ve(t),ji=()=>new Date().toISOString().slice(0,10),Zl=[{v:"standing_order",l:"הוראת קבע",icon:Ar},{v:"credit",l:"כרטיס אשראי",icon:Oe},{v:"bank_transfer",l:"העברה בנקאית",icon:Ar},{v:"cash",l:"מזומן",icon:Fd},{v:"check",l:"המחאה",icon:Dd}],$x=t=>{var s;return((s=Zl.find(n=>n.v===t))==null?void 0:s.l)||t||"—"},rs=Se;function Cx({kibbutzId:t}){const[s,n]=i.useState(!0),[a,l]=i.useState([]),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState(!1),[b,f]=i.useState(!1),[x,g]=i.useState(!1),[y,$]=i.useState(""),[O,A]=i.useState(""),S={payer_account_id:"",statement_id:"",amount:"",payment_method:"standing_order",reference_number:"",payment_date:ji(),receipt_url:"",notes:""},[P,E]=i.useState(S),k=(L,N)=>E(v=>({...v,[L]:N})),C=i.useCallback(async()=>{n(!0);try{const[L,N,v,F]=await Promise.all([D.entities.Payment.filter({kibbutz_id:t},"-payment_date",5e3).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.MonthlyStatement.filter({kibbutz_id:t},"-billing_month",5e3).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[])]);l(L||[]),o(N||[]),u(v||[]),c(F||[])}catch{W.error("שגיאה בטעינה")}finally{n(!1)}},[t]);i.useEffect(()=>{C()},[C]);const w=i.useCallback(L=>{var v;const N=r.find(F=>F.id===L);return N?N.name||((v=d.find(F=>F.id===N.family_id))==null?void 0:v.name)||`#${N.account_number}`:"—"},[r,d]),_=i.useMemo(()=>p.filter(L=>P.payer_account_id?L.payer_account_id===P.payer_account_id:!1),[p,P.payer_account_id]);async function T(L,N){const v=p.find(z=>z.id===L);if(!v)return;const F=N.filter(z=>z.statement_id===L&&z.status==="paid").reduce((z,te)=>z+(Number(te.amount)||0),0),Z=(Number(v.previous_balance)||0)+(Number(v.charges_total)||0)-(Number(v.discounts_total)||0)-(Number(v.credits_total)||0)-F,H=Z<=.001?"paid":F>0?"partial":v.status==="paid"||v.status==="partial"?"sent":v.status;await D.entities.MonthlyStatement.update(L,{payments_total:F,balance_due:Z,status:H})}async function M(L){if(L){g(!0);try{const{file_url:N}=await D.integrations.Core.UploadFile({file:L});k("receipt_url",N),W.success("הקבלה הועלתה")}catch{W.error("שגיאה בהעלאה")}finally{g(!1)}}}async function B(){if(!P.payer_account_id){W.error("בחרו חשבון משלם");return}if(!P.amount||Number(P.amount)<=0){W.error("הזינו סכום");return}f(!0);try{const L=await D.entities.Payment.create({kibbutz_id:t,payer_account_id:P.payer_account_id,statement_id:P.statement_id||null,amount:Number(P.amount),payment_method:P.payment_method,reference_number:P.reference_number||null,payment_date:P.payment_date||ji(),status:"paid",receipt_url:P.receipt_url||null,notes:P.notes||null}),N=[...a,L];P.statement_id&&await T(P.statement_id,N),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"payment_recorded",entity_type:"payment",entity_id:L.id,payer_account_id:P.payer_account_id,new_value:Os(P.amount)}).catch(()=>{}),W.success("התשלום נרשם"),h(!1),E(S),await C()}catch{W.error("שגיאה ברישום")}finally{f(!1)}}async function R(L){if(confirm(`למחוק תשלום על סך ${Os(L.amount)}?`))try{await D.entities.Payment.delete(L.id),L.statement_id&&await T(L.statement_id,a.filter(N=>
37N.id!==L.id)),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"payment_deleted",entity_type:"payment",entity_id:L.id,payer_account_id:L.payer_account_id,old_value:Os(L.amount)}).catch(()=>{}),W.success("התשלום נמחק"),await C()}catch{W.error("שגיאה")}}if(s)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})});const j=O?a.filter(L=>L.payment_method===O):a,q=j.filter(L=>L.status==="paid").reduce((L,N)=>L+(Number(N.amount)||0),0);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"רישום תשלומים ותקבולים ידני מול חשבונות ומסמכי חשבון."}),!m&&e.jsxs("button",{onClick:()=>{E(S),h(!0)},className:"h-9 px-4 rounded-full bg-emerald-600 text-white text-sm font-bold inline-flex items-center gap-1.5",children:[e.jsx(We,{className:"w-4 h-4"})," רישום תשלום"]})]}),e.jsx("div",{className:"bg-blue-50/60 border border-blue-100 rounded-xl px-4 py-2.5 mb-4 text-xs text-slate-500",children:"תשלום מקוון בכרטיס אשראי (סליקה) יתווסף בהמשך לאחר חיבור ספק סליקה. בשלב זה נרשמים תשלומים ידנית."}),m&&e.jsxs("div",{className:"bg-white rounded-2xl border border-emerald-200 shadow-sm p-5 mb-5 billing-form",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-base font-bold",children:"רישום תשלום חדש"}),e.jsx("button",{onClick:()=>h(!1),className:"w-8 h-8 rounded-full border border-slate-200 flex items-center justify-center text-slate-400",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx("div",{className:"sm:col-span-1",children:e.jsxs(Q,{label:"חשבון משלם",required:!0,children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(qt,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx("input",{value:y,onChange:L=>$(L.target.value),placeholder:"חיפוש…",className:"w-full h-10 rounded-xl border border-slate-300 pr-9 pl-3 text-sm"})]}),e.jsxs("select",{className:rs,value:P.payer_account_id,onChange:L=>{k("payer_account_id",L.target.value),k("statement_id","")},children:[e.jsx("option",{value:"",children:"בחרו חשבון…"}),r.filter(L=>{var N;return!y||(L.name||"").includes(y)||(L.account_number||"").includes(y)||(((N=d.find(v=>v.id===L.family_id))==null?void 0:N.name)||"").includes(y)}).map(L=>e.jsxs("option",{value:L.id,children:[w(L.id)," · #",L.account_number]},L.id))]})]})}),e.jsx(Q,{label:"שיוך למסמך חשבון",info:"שיוך התשלום לחשבון חודשי מסוים יעדכן את יתרתו אוטומטית",children:e.jsxs("select",{className:rs,value:P.statement_id,onChange:L=>k("statement_id",L.target.value),disabled:!P.payer_account_id,children:[e.jsx("option",{value:"",children:"— תשלום על החשבון —"}),_.map(L=>e.jsxs("option",{value:L.id,children:[Lt(L.billing_month)," · יתרה ",Os(L.balance_due)]},L.id))]})}),e.jsx(Q,{label:"סכום (₪)",required:!0,children:e.jsx("input",{type:"number",className:rs,placeholder:"הזן סכום",value:P.amount,onChange:L=>k("amount",L.target.value)})}),e.jsx(Q,{label:"אמצעי תשלום",required:!0,children:e.jsx("select",{className:rs,value:P.payment_method,onChange:L=>k("payment_method",L.target.value),children:Zl.map(L=>e.jsx("option",{value:L.v,children:L.l},L.v))})}),e.jsx(Q,{label:"אסמכתא / מס' קבלה",children:e.jsx("input",{className:rs,placeholder:"הזן אסמכתא / מספר קבלה",value:P.reference_number,onChange:L=>k("reference_number",L.target.value)})}),e.jsx(Q,{label:"תאריך תשלום",required:!0,children:e.jsx("input",{type:"date",className:rs,value:P.payment_date,onChange:L=>k("payment_date",L.target.value)})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Q,{label:"הערות",children:e.jsx("input",{className:rs,placeholder:"הערות (לא חובה)",value:P.notes,onChange:L=>k("notes",L.target.value)})})}),e.jsx(Q,{label:"קבלה סרוקה",children:P.receipt_url?e.jsxs("a",{href:P.receipt_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 h-12 px-4 roun
37ded-xl border border-emerald-200 bg-emerald-50 text-emerald-700 text-sm",children:[e.jsx(jn,{className:"w-4 h-4"})," קבלה מצורפת"]}):e.jsxs("label",{className:"inline-flex items-center gap-1.5 h-12 px-4 rounded-xl border border-slate-300 text-sm text-slate-500 cursor-pointer hover:bg-slate-50",children:[e.jsx(La,{className:"w-4 h-4"})," ",x?"מעלה…":"העלאת קבלה",e.jsx("input",{type:"file",className:"hidden",onChange:L=>{var N;return M((N=L.target.files)==null?void 0:N[0])}})]})})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-5",children:[e.jsxs("button",{onClick:B,disabled:b,className:ts,children:[e.jsx(ye,{className:"w-4 h-4"})," ",b?"שומר…":"רשום תשלום"]}),e.jsx("button",{onClick:()=>h(!1),className:$s,children:"ביטול"})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 overflow-x-auto pb-1",children:[e.jsx(hr,{className:"w-4 h-4 text-slate-400 flex-shrink-0"}),e.jsx("button",{onClick:()=>A(""),className:`h-8 px-3 rounded-full text-xs font-medium border flex-shrink-0 ${O?"bg-white border-slate-200 text-slate-600":"bg-indigo-600 text-white border-transparent"}`,children:"הכל"}),Zl.map(L=>e.jsx("button",{onClick:()=>A(L.v),className:`h-8 px-3 rounded-full text-xs font-medium border flex-shrink-0 ${O===L.v?"bg-indigo-600 text-white border-transparent":"bg-white border-slate-200 text-slate-600"}`,children:L.l},L.v))]}),j.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-10 text-center",children:[e.jsx(es,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsx("h3",{className:"text-base font-semibold mb-1",children:"אין תשלומים רשומים"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"רשמו תשלום ראשון. הוא ישויך לחשבון ולמסמך החשבון ויעדכן את היתרה אוטומטית."})]}):e.jsx("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"תאריך"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"משלם"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"אמצעי"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"אסמכתא"}),e.jsx("th",{className:"text-right px-4 py-2.5 font-medium",children:"סכום"}),e.jsx("th",{className:"px-4 py-2.5"})]})}),e.jsx("tbody",{children:j.map(L=>e.jsxs("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-500",children:L.payment_date||"—"}),e.jsxs("td",{className:"px-4 py-2.5 font-medium",children:[w(L.payer_account_id),L.statement_id&&e.jsx("span",{className:"text-[11px] text-slate-400",children:" · משויך למסמך"})]}),e.jsx("td",{className:"px-4 py-2.5 text-slate-600",children:$x(L.payment_method)}),e.jsxs("td",{className:"px-4 py-2.5 text-slate-500",children:[L.reference_number||"—",L.receipt_url&&e.jsx("a",{href:L.receipt_url,target:"_blank",rel:"noreferrer",className:"text-indigo-500 mr-1 inline-flex",children:e.jsx(jn,{className:"w-3.5 h-3.5"})})]}),e.jsx("td",{className:"px-4 py-2.5 font-bold text-emerald-700",children:Os(L.amount)}),e.jsx("td",{className:"px-4 py-2.5 text-left",children:e.jsx("button",{onClick:()=>R(L),className:"w-8 h-8 rounded-lg inline-flex items-center justify-center text-red-500 hover:bg-red-50",children:e.jsx(Re,{className:"w-4 h-4"})})})]},L.id))}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"border-t-2 border-slate-200 bg-slate-50",children:[e.jsxs("td",{colSpan:4,className:"px-4 py-2.5 text-xs text-slate-500",children:[j.length," תשלומים"]}),e.jsx("td",{className:"px-4 py-2.5 font-black text-emerald-700",children:Os(q)}),e.jsx("td",{})]})})]})})]})}const gl=t=>ve(t);function Ax({kibbutzId:t}){const[s,n]=i.useState(!0),[a,l]=i.useState([]),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState([]),[x,g]=i.useState("pending"),[y,$]=i.useState(null),O=i.useCallback(async()=>{n(!0);try{const[w,_,T,M,B,R]=await Promise.all([D.entities.Charge.filter({kibbutz_id:t},"-created_date",8e3).catch(()=>[]),D.entities.Payment.filter({kibbutz_id:t},"-created_date",5e3).catch(()=>[]),D.entities.BillingApproval.filter({kibbutz_id:t},"-created_date",1e3).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filter({kibbutz_id:t},"order",300).catch(()=>[]),D.entities.MonthlyStatement.filter({kibbutz_id:t},"-billing_month",5e3).catch(()=>[])]);l(w||[]),o(_||[]),u(T||[]),c(M||[]),h(B||[]),f(R||[])}catch{W.error("שגיאה בטעינה")}finally{n(!1)}},[t]);i.useEffect(()=>{O()},[O]);const A=i.useCallback(w=>{const _=d.find(T=>T.id===w);return _?_.name||`#${_.account_number}`:"—"},[d]),S=i.useCallback(w=>{var _;return((_=m.find(T=>T.id===w))==null?void 0:_.name)||"חיוב"},[m]);async function P(w){const _=b.find(R=>R.id===w);if(!_)return;const T=r.filter(R=>R.statement_id===w&&R.status==="paid").reduce((R,j)=>R+(Number(j.amount)||0),0),B=(Number(_.previous_balance)||0)+(Number(_.charges_total)||0)-(Number(_.discounts_total)||0)-(Number(_.credits_total)||0)-T;await D.entities.MonthlyStatement.update(w,{payments_total:T,balance_due:B,status:B<=.001?"paid":T>0?"partial":_.status})}const E=i.useMemo(()=>{const w=[];for(const _ of a)_.status==="pending"&&w.push({kind:"charge",id:_.id,row:_,account:_.payer_account_id,title:S(_.charge_type_id),sub:`${_.description||""} · ${Lt(_.billing_period)}`,amount:_.amount,icon:nt,tone:"text-blue-600 bg-blue-50"});for(const _ of r)_.status==="pending_approval"&&w.push({kind:"payment",id:_.id,row:_,account:_.payer_account_id,title:"תשלום",sub:_.reference_number||_.payment_method||"",amount:_.amount,icon:es,tone:"text-emerald-600 bg-emerald-50"});for(const _ of p)_.status==="pending"&&w.push({kind:"approval",id:_.id,row:_,account:_.payer_account_id,title:_.approval_type||"בקשת אישור",sub:_.reason||"",amount:_.amount,icon:Oe,tone:"text-purple-600 bg-purple-50"});return w},[a,r,p,S]),k=i.useMemo(()=>p.filter(w=>w.status!=="pending").map(w=>({kind:"approval",id:w.id,row:w,account:w.payer_account_id,title:w.approval_type||"בקשה",amount:w.amount,status:w.status})),[p]);async function C(w,_){$(w.id);try{w.kind==="charge"?await D.entities.Charge.update(w.id,{status:_?"approved":"cancelled"}):w.kind==="payment"?(await D.entities.Payment.update(w.id,{status:_?"paid":"cancelled"}),w.row.statement_id&&await P(w.row.statement_id)):w.kind==="approval"&&await D.entities.BillingApproval.update(w.id,{status:_?"approved":"rejected",resolved_at:new Date().toISOString()}),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:_?"approval_granted":"approval_rejected",entity_type:w.kind,entity_id:w.id,payer_account_id:w.account,new_value:w.amount!=null?gl(w.amount):null}).catch(()=>{}),W.success(_?"אושר":"נדחה"),await O()}catch{W.error("שגיאה")}finally{$(null)}}return s?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})}):e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-4",children:[e.jsxs("button",{onClick:()=>
37g("pending"),className:`h-9 px-4 rounded-full text-sm font-medium border ${x==="pending"?"bg-indigo-600 text-white border-transparent":"bg-white border-slate-200 text-slate-600"}`,children:["ממתינים לאישור ",E.length>0&&e.jsx("span",{className:"mr-1 px-1.5 py-0.5 rounded-full bg-white/25 text-[11px]",children:E.length})]}),e.jsx("button",{onClick:()=>g("resolved"),className:`h-9 px-4 rounded-full text-sm font-medium border ${x==="resolved"?"bg-indigo-600 text-white border-transparent":"bg-white border-slate-200 text-slate-600"}`,children:"היסטוריית החלטות"})]}),x==="pending"?E.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-10 text-center",children:[e.jsx(la,{className:"w-10 h-10 text-emerald-300 mx-auto mb-3"}),e.jsx("h3",{className:"text-base font-semibold mb-1",children:"אין פריטים הממתינים לאישור"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'חיובים שהוגדרו „דורש אישור", תשלומים לאישור ובקשות חריגה יופיעו כאן.'})]}):e.jsx("div",{className:"space-y-2",children:E.map(w=>{const _=w.icon;return e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-4 flex items-center gap-3",children:[e.jsx("span",{className:`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${w.tone}`,children:e.jsx(_,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-bold",children:w.title}),e.jsx("span",{className:"text-xs text-slate-400",children:A(w.account)})]}),w.sub&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:w.sub})]}),w.amount!=null&&e.jsx("span",{className:"text-base font-black text-slate-800 flex-shrink-0",children:gl(w.amount)}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e.jsxs("button",{onClick:()=>C(w,!0),disabled:y===w.id,className:"h-9 px-3 rounded-full bg-emerald-600 text-white text-sm inline-flex items-center gap-1 disabled:opacity-50",children:[e.jsx(ye,{className:"w-4 h-4"})," אשר"]}),e.jsxs("button",{onClick:()=>C(w,!1),disabled:y===w.id,className:"h-9 px-3 rounded-full border border-red-200 text-red-600 text-sm inline-flex items-center gap-1 disabled:opacity-50",children:[e.jsx($e,{className:"w-4 h-4"})," דחה"]})]})]},w.kind+w.id)})}):k.length===0?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-10 text-center",children:[e.jsx(ws,{className:"w-10 h-10 text-slate-300 mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"אין עדיין היסטוריית החלטות."})]}):e.jsx("div",{className:"space-y-2",children:k.map(w=>e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-4 flex items-center gap-3",children:[e.jsx("span",{className:`w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0 ${w.status==="approved"?"text-emerald-600 bg-emerald-50":"text-red-500 bg-red-50"}`,children:w.status==="approved"?e.jsx(ye,{className:"w-5 h-5"}):e.jsx(Od,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-bold",children:w.title})," ",e.jsx("span",{className:"text-xs text-slate-400",children:A(w.account)})]}),w.amount!=null&&e.jsx("span",{className:"text-sm font-bold text-slate-700",children:gl(w.amount)}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full ${w.status==="approved"?"bg-emerald-50 text-emerald-700":"bg-red-50 text-red-600"}`,children:w.status==="approved"?"אושר":"נדחה"})]},w.kind+w.id))})]})}const Mx={status:"active",link:"",ready:"",q:""},Za=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),yl=t=>t==null||t===""?null:Number(t);function Px({kibbutzId:t,settings:s}){const[n,a]=i.useState(!0),[l,r]=i.useState([]),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState([]),[h,b]=i.useState(Mx),f=(k,C)=>b(w=>({...w,[k]:C})),x=i.useCallback(async()=>{a(!0);try{const[k,C,w,_]=await Promise.all([D.entities.WaterMeter.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.Property.filterAll({kibbutz_id:t}).catch(()=>[])]);r(k||[]),p(C||[]),d(w||[]),m(_||[])}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{x()},[x]);const g=i.useMemo(()=>new Map(o.map(k=>[k.id,k])),[o]),y=i.useMemo(()=>new Map(u.map(k=>[k.id,k])),[u]),$=i.useMemo(()=>new Map(c.map(k=>[k.id,k])),[c]),O=k=>!!k.payer_account_id&&Number(k.souls)>0&&k.previous_reading!=null,A=i.useMemo(()=>({status:Te(l||[],{active:k=>(k.status||"active")==="active",inactive:k=>k.status==="inactive"}),link:Te(l||[],{linked:k=>!!k.payer_account_id,orphan:k=>!k.payer_account_id}),ready:Te(l||[],{ready:O,missing:k=>!O(k)})}),[l]),S=i.useMemo(()=>{const k=h.q.trim();return(l||[]).filter(C=>{const w=C.status||"active";if(h.status&&w!==h.status||h.link==="linked"&&!C.payer_account_id||h.link==="orphan"&&
37C.payer_account_id)return!1;const _=!!C.payer_account_id&&Number(C.souls)>0&&C.previous_reading!=null;if(h.ready==="ready"&&!_||h.ready==="missing"&&_)return!1;if(k){const T=g.get(C.payer_account_id);if(![C.meter_number,C.consumer_id,C.property_address,C.consumer_name,T==null?void 0:T.name,T==null?void 0:T.account_number].join(" ").includes(k))return!1}return!0}).map(C=>{const w=g.get(C.payer_account_id),_=w!=null&&w.family_id?y.get(w.family_id):null,T=$.get(C.property_id),M=[!C.payer_account_id&&"חשבון",!(Number(C.souls)>0)&&"נפשות",C.previous_reading==null&&"קריאה"].filter(Boolean);return{...C,_account:w?w.name||`#${w.account_number}`:"ללא חשבון משלם",_accountNumber:(w==null?void 0:w.account_number)||"",_family:(_==null?void 0:_.name)||"",_property:(T==null?void 0:T.property_number)||"",_address:C.property_address||(T==null?void 0:T.address)||"",_souls:yl(C.souls),_eligible:yl(C.eligible_count),_reading:yl(C.previous_reading),_statusLabel:(C.status||"active")==="active"?"פעיל":"מושבת",_ready:M.length===0,_missing:M.length?`חסר ${M.join(" · ")}`:"מוכן לחיוב"}})},[l,h,g,y,$]),P=[{key:"_account",header:"חשבון משלם",width:24,strong:!0},{key:"_accountNumber",header:"מס׳ חשבון",width:11,muted:!0,off:!0},{key:"_family",header:"משפחה",width:18,muted:!0,off:!0},{key:"meter_number",header:"מספר מונה",width:14,strong:!0},{key:"consumer_id",header:"מס׳ זיהוי",width:12,muted:!0},{key:"_address",header:"כתובת הנכס",width:24,clamp:!0},{key:"_property",header:"נכס",width:10,muted:!0,off:!0},{key:"consumer_name",header:"שם צרכן",width:20,muted:!0,off:!0},{key:"_souls",header:"נפשות",width:9,type:"num",total:!0},{key:"_eligible",header:"זכאים",width:9,type:"num",total:!0},{key:"_reading",header:"קריאה אחרונה",width:13,type:"cube"},{key:"previous_reading_date",header:"תאריך קריאה",width:12,type:"date"},{key:"notes",header:"הערות",width:20,muted:!0,clamp:!0,off:!0},{key:"_statusLabel",header:"סטטוס",width:10,align:"center"},{key:"_missing",header:"מוכנות לחיוב",width:18,align:"center",render:k=>e.jsx("span",{className:`inline-block px-2.5 py-1 rounded-full border text-[11.5px] font-bold ${k._ready?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:k._missing})}],E=i.useMemo(()=>{const k=S.filter(w=>!w.payer_account_id).length,C=S.filter(w=>!w._ready).length;return[{label:"מונים",value:Za(S.length),icon:Nd,tone:"text-sky-600 bg-sky-50"},{label:"סה״כ נפשות",value:Za(S.reduce((w,_)=>w+(Number(_._souls)||0),0)),icon:De,tone:"text-blue-600 bg-blue-50"},{label:"ללא חשבון משלם",value:Za(k),icon:or,tone:k?"text-amber-600 bg-amber-50":"text-slate-400 bg-slate-100"},{label:"חסרים פרטים לחיוב",value:Za(C),icon:At,tone:C?"text-red-600 bg-red-50":"text-slate-400 bg-slate-100"}]},[S]);return e.jsx(ss,{title:"דוח מונים",subtitle:"מוני המים הרשומים בקהילה — החשבון שהם שייכים לו, הנכס, הנפשות שהמכסה מחושבת לפיהן והקריאה האחרונה",settings:s,chips:[h.status?h.status==="active"?"מונים פעילים":"מונים מושבתים":"כל הסטטוסים",h.link==="linked"?"משויכים לחשבון":h.link==="orphan"?"ללא חשבון משלם":"",h.ready==="ready"?"מוכנים לחיוב":h.ready==="missing"?"חסרים פרטים":"",h.q&&`חיפוש: ${h.q}`],search:{value:h.q,onChange:k=>f("q",k),placeholder:"חיפוש לפי משלם, מונה, מס׳ זיהוי או כתובת"},filters:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"סטטוס",value:h.status,onChange:k=>f("status",k),counts:A.status,options:[{v:"active",l:"פעילים"},{v:"inactive",l:"מושבתים"},{v:"",l:"הכל"}]}),e.jsx(Ae,{label:"שיוך",value:h.link,onChange:k=>f("link",k),counts:A.link,options:[{v:"",l:"הכל"},{v:"linked",l:"משויכים לחשבון"},{v:"orphan",l:"ללא חשבון"}]}),e.jsx(Ae,{label:"מוכנות לחיוב",value:h.ready,onChange:k=>f("ready",k),counts:A.ready,options:[{v:"",l:"הכל"},{v:"ready",l:"מוכנים"},{v:"missing",l:"חסרים פרטים"}]})]}),stats:E,columns:P,defaultSort:{key:"_account",dir:"asc"},rows:S,loading:n,fileName:"דוח_מונים",empty:"אין מונים התואמים את הסינון",footNote:"«מוכן לחיוב» = למונה יש חשבון משלם, מספר נפשות וקריאה אחרונה. בלי שלושתם טעינת קובץ קריאות לא תוכל להפיק ממנו חשבון."})}const Ex={type:"",status:"active",link:"",q:"",min:""},Qa=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),Ja=t=>t==null||t===""?null:Number(t);function Fx({kibbutzId:t,settings:s}){const[n,a]=i.useState(!0),[l,r]=i.useState([]),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState([]),[h,b]=i.useState(Ex),f=(k,C)=>b(w=>({...w,[k]:C})),x=i.useCallback(async()=>{a(!0);try{const[k,C,w,_]=await Promise.all([D.entities.Property.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.WaterMeter.filterAll({kibbutz_id:t}).catch(()=>[])]);r(k||[]),p(C||[]),d(w||[]),m(_||[])}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{x()},[x]);const g=i.useMemo(()=>new Map(o.map(k=>[k.id,k])),[o]),y=i.useMemo(()=>new Map(u.map(k=>[k.id,k])),[u]),$=i.useMemo(()=>{const k=new Map;
37return c.forEach(C=>{C.property_id&&k.set(C.property_id,[...k.get(C.property_id)||[],C])}),k},[c]),O=i.useMemo(()=>[...new Set(l.map(k=>k.property_type).filter(Boolean))],[l]),A=i.useMemo(()=>({status:Te(l,{active:k=>(k.status||"active")==="active",inactive:k=>k.status==="inactive"}),link:Te(l,{linked:k=>!!k.payer_account_id,orphan:k=>!k.payer_account_id})}),[l]),S=i.useMemo(()=>{const k=h.q.trim(),C=h.min===""?null:Number(h.min);return(l||[]).filter(w=>{if(h.type&&w.property_type!==h.type||h.status&&(w.status||"active")!==h.status||h.link==="linked"&&!w.payer_account_id||h.link==="orphan"&&w.payer_account_id||C!==null&&!(Number(w.size_sqm)>=C))return!1;if(k){const _=g.get(w.payer_account_id);if(![w.property_number,w.address,w.gush_helka,_==null?void 0:_.name,_==null?void 0:_.account_number].join(" ").includes(k))return!1}return!0}).map(w=>{const _=g.get(w.payer_account_id),T=_!=null&&_.family_id?y.get(_.family_id):null;return{...w,_account:_?_.name||`#${_.account_number}`:"ללא חשבון משלם",_accountNumber:(_==null?void 0:_.account_number)||"",_family:(T==null?void 0:T.name)||"",_meters:($.get(w.id)||[]).map(M=>M.meter_number).join(", "),_status:(w.status||"active")==="active"?"פעיל":"לא פעיל",_size:Ja(w.size_sqm),_built:Ja(w.built_sqm),_extra:Ja(w.extra_sqm),_souls:Ja(w.occupancy_count)}}).sort((w,_)=>String(w._account).localeCompare(String(_._account),"he"))},[l,h,g,y,$]),P=[{key:"property_number",header:"מספר / שם נכס",width:16,strong:!0},{key:"property_type",header:"סוג",width:14,muted:!0},{key:"address",header:"כתובת",width:24,clamp:!0},{key:"gush_helka",header:"גוש/חלקה",width:14,muted:!0},{key:"_size",header:"שטח (מ״ר)",width:11,type:"num",total:!0},{key:"_built",header:"בנוי (מ״ר)",width:11,type:"num",total:!0},{key:"_extra",header:"שטח נוסף",width:11,type:"num",total:!0},{key:"_souls",header:"נפשות",width:9,type:"num",total:!0},{key:"_account",header:"חשבון משלם",width:24,strong:!0},{key:"_accountNumber",header:"מס׳ חשבון",width:11,muted:!0},{key:"_family",header:"משפחה",width:18,muted:!0},{key:"_meters",header:"מוני מים",width:14,muted:!0},{key:"active_from",header:"תחילת שיוך",width:12,type:"date",muted:!0},{key:"_status",header:"סטטוס",width:10,align:"center"}],E=i.useMemo(()=>{const k=S.filter(C=>!C.payer_account_id).length;return[{label:"נכסים",value:Qa(S.length),icon:ra},{label:"סה״כ מ״ר",value:Qa(S.reduce((C,w)=>C+(Number(w._size)||0),0)),icon:vd,tone:"text-indigo-600 bg-indigo-50"},{label:"סה״כ נפשות",value:Qa(S.reduce((C,w)=>C+(Number(w._souls)||0),0)),icon:De,tone:"text-blue-600 bg-blue-50"},{label:"ללא חשבון משלם",value:Qa(k),icon:es,tone:k?"text-amber-600 bg-amber-50":"text-slate-400 bg-slate-100"}]},[S]);return e.jsx(ss,{title:"דוח נכסים",subtitle:"יחידות החיוב של הקהילה, שטחיהן, הנפשות המשויכות והחשבון שמשלם עליהן",settings:s,chips:[h.type&&`סוג: ${h.type}`,h.status?h.status==="active"?"נכסים פעילים":"נכסים לא פעילים":"כל הסטטוסים",h.link==="linked"?"משויכים לחשבון":h.link==="orphan"?"ללא חשבון משלם":"",h.min!==""&&`שטח מעל ${h.min} מ״ר`,h.q&&`חיפוש: ${h.q}`],search:{value:h.q,onChange:k=>f("q",k),placeholder:"חיפוש לפי נכס, כתובת, גוש/חלקה או משלם"},filters:e.jsxs(e.Fragment,{children:[e.jsx(oc,{label:"סוג נכס",value:h.type,onChange:k=>f("type",k),options:[{v:"",l:"הכל"},...O.map(k=>({v:k,l:k}))]}),e.jsx(Ae,{label:"סטטוס",value:h.status,onChange:k=>f("status",k),counts:A.status,options:[{v:"active",l:"פעילים"},{v:"inactive",l:"לא פעילים"},{v:"",l:"הכל"}]}),e.jsx(Ae,{label:"שיוך",value:h.link,onChange:k=>f("link",k),counts:A.link,options:[{v:"",l:"הכל"},{v:"linked",l:"משויכים לחשבון"},{v:"orphan",l:"ללא חשבון"}]}),e.jsx(cc,{label:"שטח מעל (מ״ר)",value:h.min,onChange:k=>f("min",k),placeholder:"0"})]}),stats:E,columns:P,defaultSort:{key:"_account",dir:"asc"},rows:S,loading:n,fileName:"דוח_נכסים",empty:"אין נכסים התואמים את הסינון"})}const _l=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),Dx=t=>
37(Number(t)||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),jl=[{v:"lines",l:"שורות"},{v:"family",l:"לפי משפחה"},{v:"dept",l:"לפי קבוצת מוצר"},{v:"item",l:"לפי פריט"}];function Ox({kibbutzId:t,settings:s}){var O,A;const[n,a]=i.useState(!0),[l,r]=i.useState([]),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState({batch:"",mode:"family",q:""}),h=(S,P)=>m(E=>({...E,[S]:P})),b=i.useCallback(async()=>{a(!0);try{const[S,P]=await Promise.all([D.entities.KolboImportBatch.filterAll({kibbutz_id:t,status:"approved"},"-created_date").catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[])]);r(S||[]),d(P||[]),m(E=>{var k;return{...E,batch:E.batch||((k=S==null?void 0:S[0])==null?void 0:k.id)||""}})}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{if(!c.batch){p([]);return}let S=!0;return a(!0),D.entities.KolboPurchase.filterAll({kibbutz_id:t,batch_id:c.batch}).then(P=>{S&&p(P||[])}).catch(()=>{S&&p([])}).finally(()=>{S&&a(!1)}),()=>{S=!1}},[t,c.batch]);const f=i.useMemo(()=>new Map(u.map(S=>[S.id,S])),[u]),x=i.useMemo(()=>{const S=c.q.trim();return o.filter(P=>{var E;if(S){const k=P.family_id?(E=f.get(P.family_id))==null?void 0:E.name:"";if(![P.item,P.dept,P.payer_name,P.budget,P.sku,k].join(" ").includes(S))return!1}return!0}).map(P=>{var E;return{...P,_family:P.family_id&&((E=f.get(P.family_id))==null?void 0:E.name)||P.payer_name||"",_unit:P.qty!=null&&P.unit?`${P.unit}`:""}})},[o,c,f]),g=i.useMemo(()=>{if(c.mode==="lines")return{rows:[...x].sort((E,k)=>String(k.txn_date).localeCompare(String(E.txn_date))||String(E.receipt).localeCompare(String(k.receipt))),columns:[{key:"txn_date",header:"תאריך",width:12,type:"date"},{key:"receipt",header:"חשבונית",width:12,muted:!0},{key:"budget",header:"תקציב",width:10},{key:"_family",header:"משפחה / משלם",width:22,strong:!0,clamp:!0},{key:"dept",header:"קבוצת מוצר",width:18,muted:!0},{key:"item",header:"פריט",width:28,clamp:!0},{key:"qty",header:"כמות",width:9,type:"num",total:!0},{key:"_unit",header:"יחידה",width:8,muted:!0,align:"center"},{key:"total",header:"סכום (₪)",width:12,type:"money",total:!0,strong:!0}]};if(c.mode==="family"){const E=new Map;return x.forEach(k=>{const C=k.family_id||`b:${k.budget}`,w=E.get(C)||{id:C,_family:k._family||"—",budget:k.budget,lines:0,total:0,rows:[]};w.lines+=1,w.total+=Number(k.total)||0,w.rows.push(k),E.set(C,w)}),{rows:[...E.values()].map(k=>({...k,visits:_n(k.rows).length,total:ka(k.total)})).sort((k,C)=>C.total-k.total),columns:[{key:"_family",header:"משפחה / משלם",width:28,strong:!0},{key:"budget",header:"מספר תקציב",width:12},{key:"visits",header:"ביקורים",width:10,type:"num",total:!0},{key:"lines",header:"שורות",width:10,type:"num",total:!0},{key:"total",header:"סה״כ קניות (₪)",width:14,type:"money",total:!0,strong:!0}]}}const S=new Map;return x.forEach(E=>{const k=c.mode==="dept"?E.dept||"—":`${E.sku||""}|${E.item||"—"}`,C=S.get(k)||{id:k,dept:E.dept||"—",item:E.item||"—",sku:E.sku||"",lines:0,qty:0,total:0,buyers:new Set};C.lines+=1,C.qty+=Number(E.qty)||0,C.total+=Number(E.total)||0,C.buyers.add(E.family_id||E.budget),S.set(k,C)}),{rows:[...S.values()].map(E=>({...E,qty:ka(E.qty),total:ka(E.total),buyers:E.buyers.size})).sort((E,k)=>k.total-E.total),columns:c.mode==="dept"?[{key:"dept",header:"קבוצת מוצר",width:28,strong:!0},{key:"lines",header:"שורות",width:10,type:"num",total:!0},{key:"qty",header:"כמות",width:10,type:"num",total:!0},{key:"buyers",header:"משקי בית",width:11,type:"num"},{key:"total",header:"סה״כ (₪)",width:14,type:"money",total:!0,strong:!0}]:[{key:"item",header:"פריט",width:32,strong:!0,clamp:!0},{key:"sku",header:"מק״ט",width:12,muted:!0},{key:"dept",header:"קבוצת מוצר",width:20,muted:!0},{key:"qty",header:"כמות",width:10,type:"num",total:!0},{key:"buyers",header:"משקי בית",width:11,type:"num"},{key:"total",header:"סה״כ (₪)",width:14,type:"money",total:!0,strong:!0}]}},[c.mode,x]),y=l.find(S=>S.id===c.batch),$=i.useMemo(()=>{const S=x.reduce((k,C)=>k+(Number(C.total)||0),0),P=new Set(x.map(k=>k.family_id||k.budget)).size,E=_n(x).length;return[{label:"שורות",value:_l(x.length),icon:da},{label:"ביקורים",value:_l(E),icon:fo,tone:"text-indigo-600 bg-indigo-50"},{label:"משקי בית",value:_l(P),icon:De,tone:"text-blue-600 bg-blue-50"},{label:"סה״כ קניות",value:Dx(S),currency:!0,icon:rt,tone:"text-emerald-600 bg-emerald-50"}
37]},[x]);return e.jsx(ss,{title:"דוח כולבו",subtitle:y?`קניות המרכול בקובץ «${y.file_name||""}»${y.period_from?` · ${String(y.period_from).slice(0,10)} – ${String(y.period_to||"").slice(0,10)}`:""}`:"קניות המרכול, לפי קובץ שנטען ואושר",settings:s,chips:[y&&`טעינה: ${y.file_name||y.id.slice(0,6)}`,`תצוגה: ${(O=jl.find(S=>S.v===c.mode))==null?void 0:O.l}`,c.q&&`חיפוש: ${c.q}`],search:{value:c.q,onChange:S=>h("q",S),placeholder:"חיפוש לפי פריט, משפחה, מספר תקציב או מק״ט"},filters:e.jsx(Ae,{label:"תצוגה",value:c.mode,onChange:S=>h("mode",S),options:jl}),stats:$,columns:g.columns,defaultSort:{key:"_family",dir:"asc"},rows:g.rows,loading:n,fileName:`דוח_כולבו_${((A=jl.find(S=>S.v===c.mode))==null?void 0:A.l)||""}`,empty:l.length?"אין שורות התואמות את הסינון":"עדיין לא אושרה טעינת קובץ כולבו",footNote:"מספר החשבונית הוא חותמת השעה והקופה, ולכן ביקור מזוהה לפי תאריך + חשבונית + מספר תקציב."})}function Tn(t,s=new Date){const n=String(t||"").slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return null;const[a,l,r]=n.split("-").map(Number),o=Date.UTC(a,l-1,r),p=Date.UTC(s.getFullYear(),s.getMonth(),s.getDate());return Math.round((o-p)/864e5)}function wa(t,{prefix:s=""}={}){if(t==null)return"";const n=s?`${s} `:"";if(t<0){const a=Math.abs(t);return a===1?s?`${s} היה אתמול`:"באיחור יום":a===2?s?`${s} עבר לפני יומיים`:"באיחור יומיים":s?`${s} עבר לפני ${a} ימים`:`באיחור ${a} ימים`}return t===0?s?`${s} היום`:"היום":t===1?s?`${s} מחר`:"מחר":t===2?`${n}עוד יומיים`:`${n}עוד ${t} ימים`}function Ql(t){return t==null?"none":t<0?"late":t<=3?"soon":t<=7?"week":"far"}const Lx={late:"bg-red-50 text-red-700 border-red-200",soon:"bg-emerald-50 text-emerald-700 border-emerald-200",week:"bg-cyan-50 text-cyan-700 border-cyan-200",far:"bg-sky-50 text-sky-700 border-sky-200",none:"bg-slate-50 text-slate-400 border-slate-200"};function Tx(t=[],{today:s=new Date}={}){const n=new Map;for(const o of t){const p=String((o==null?void 0:o.date)||"").slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(p))continue;const u=n.get(p)||{date:p,count:0,sum:0,days:Tn(p,s)};u.count+=Number((o==null?void 0:o.count)??1)||0,u.sum+=Number(o==null?void 0:o.amount)||0,n.set(p,u)}const a=[...n.values()].sort((o,p)=>o.days-p.days),r=a.filter(o=>o.days>=0)[0]||a[0]||null;return{dates:a,next:r,mixed:a.length>1,count:a.reduce((o,p)=>o+p.count,0),sum:Math.round(a.reduce((o,p)=>o+p.sum,0)*100)/100}}function Bx(t,s){if(!s)return t;const n={...t,...s},a=String(s.due||"").slice(0,7);return a&&a!==t.month?{...n,month:a}:n}const Bn=t=>/^\d{4}-\d{2}$/.test(String(t||"").slice(0,7));function Rx(t){const s=String((t==null?void 0:t.billing_period)||"").slice(0,7);if(Bn(s))return s;const n=String((t==null?void 0:t.created_date)||"").slice(0,7);return Bn(n)?n:String((t==null?void 0:t.due_date)||"").slice(0,10).slice(0,7)}const Le=t=>(Number(t)||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),Ls=t=>{const s=String(t||"").slice(0,10),[n,a,l]=s.split("-");return l?`${l}/${a}/${n}`:"—"},qx=()=>new Date().toISOString().slice(0,10),Nl=t=>Bn(t)?Xs(String(t).slice(0,7)):String(t||""),Ts=`w-full h-11 rounded-xl border border-slate-200 bg-white px-3 text-[14px] text-slate-800
38  focus:outline-none focus:border-teal-500 focus:ring-4 focus:ring-teal-50 transition-colors`,Kt=({label:t,hint:s,required:n,children:a})=>e.jsxs("label",{className:"block min-w-0",children:[e.jsxs("span",{className:"block text-[12.5px] font-bold text-slate-600 mb-1.5",children:[t,n&&e.jsx("span",{className:"text-rose-500",children:" *"})]}),a,s&&e.jsx("span",{className:"block text-[11.5px] text-slate-400 mt-1.5",children:s})]});function vl({options:t,value:s,onChange:n,name:a}){return e.jsx("div",{className:`grid gap-3 ${t.length>1?"grid-cols-2":"grid-cols-1"}`,children:t.map(l=>{const r=s===l.v;return e.jsxs("button",{type:"button",role:"radio","aria-checked":r,name:a,onClick:()=>
38n(l.v),className:`h-14 px-4 rounded-2xl border-2 flex items-center gap-2.5 transition-colors ${r?"border-teal-500 bg-teal-50/70":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx("span",{className:`w-5 h-5 rounded-full border-2 grid place-items-center flex-none ${r?"border-teal-600 bg-teal-600":"border-slate-300"}`,children:r&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white"})}),e.jsx("span",{className:`text-[14px] font-bold ${r?"text-teal-800":"text-slate-500"}`,children:l.l})]},l.v)})})}const is=({children:t,note:s})=>e.jsxs("div",{className:"rounded-2xl bg-teal-50/70 border border-teal-100 px-4 py-3 flex items-start gap-3",children:[e.jsx("span",{className:"w-8 h-8 rounded-full bg-teal-600 text-white grid place-items-center flex-none",children:e.jsx(ye,{className:"w-4 h-4",strokeWidth:3})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-teal-900 leading-relaxed",children:t}),s&&e.jsx("span",{className:"block text-[12.5px] text-teal-700/80 mt-0.5",children:s})]})]}),en=({children:t})=>e.jsxs("p",{className:"rounded-2xl bg-sky-50/70 border border-sky-100 px-4 py-3 text-[13px] text-slate-600 flex items-start gap-3",children:[e.jsx(Un,{className:"w-4 h-4 text-sky-500 flex-none mt-0.5"}),e.jsx("span",{children:t})]}),ga=({label:t,children:s,tone:n=""})=>e.jsxs("span",{className:`px-3 py-1.5 rounded-xl text-center min-w-0 ${n||"bg-white/70"}`,children:[e.jsx("span",{className:"block text-[11px] font-bold text-slate-400 whitespace-nowrap",children:t}),e.jsx("span",{className:"block text-[13.5px] font-black text-slate-800 truncate",children:s})]}),Ix=[{v:"due_date",l:"שינוי מועדי חיוב",hint:"עדכון מועדי הפקת המסמך והתשלום",icon:Ld,card:"bg-teal-50/50 border-teal-100/80",icon_:"bg-teal-100 text-teal-600"},{v:"credit",l:"זיכוי חיוב",hint:"זיכוי מלא או חלקי",icon:wd,card:"bg-sky-50/50 border-sky-100/80",icon_:"bg-sky-100 text-sky-600"},{v:"cancel",l:"ביטול החיוב",hint:"ביטול קבוע או למספר מחזורים",icon:Re,card:"bg-rose-50/50 border-rose-100/80",icon_:"bg-rose-100 text-rose-500"},{v:"add",l:"הוספת מוצרים",hint:"הוספת פריטים לחשבון החיוב",icon:kd,card:"bg-teal-50/50 border-teal-100/80",icon_:"bg-teal-100 text-teal-600"},{v:"back",l:"חזרה לפרטי החיוב",hint:"ללא ביצוע שינוי",icon:bs,card:"bg-sky-50/50 border-sky-100/80",icon_:"bg-sky-100 text-sky-600"}];function zx({charge:t,account:s,type:n,existing:a=[],onClose:l,onSave:r,onCancelException:o}){const p=!!n&&!["per_file","one_time"].includes(n.billing_cycle)&&n.calculation_method!=="water_meter"&&n.calculation_method!=="custom",u=Ix,[d,c]=i.useState("menu"),[m,h]=i.useState([{description:"",amount:""}]),[b,f]=i.useState(6),[x,g]=i.useState(()=>$r(t)?"now":"cycles"),[y,$]=i.useState({kind:"partial",amount:""}),[O,A]=i.useState(p?"temporary":"permanent"),[S,P]=i.useState(3),[E,k]=i.useState(String((t==null?void 0:t.due_date)||"").slice(0,10)||qx()),[C,w]=i.useState(""),[_,T]=i.useState(!1),[M,B]=i.useState(null),R=Number(t==null?void 0:t.amount)||0,j=Number((t==null?void 0:t._net)??(t==null?void 0:t.amount))||0,q=ad(n),L=$r(t),N=y.kind==="full"?Math.max(0,j):Number(y.amount)||0,v=nd(m),F=x==="now",K=x==="next",Z=F||K?1:Es(b),H=v.reduce((G,ne)=>G+ne.amount,0),z=H*Z,te=ld(t==null?void 0:t.due_date,S,q),ie=d==="due_date"?/^\d{4}-\d{2}-\d{2}$/.test(E)?E===String((t==null?void 0:t.due_date)||"").slice(0,10)?"המועד לא שונה":null:"יש לבחור מועד חיוב ותשלום":d==="add"?v.length?F&&!L?"החיוב כבר נגבה — לא ניתן להוסיף לו פריטים":null:"יש להזין לפחות מוצר אחד — כותרת ומחיר":d==="credit"?N>0?N>R+.001?"הזיכוי גדול מסכום החיוב":C.trim()?null:"יש לפרט את סיבת הזיכוי":"יש להזין סכום זיכוי":d==="cancel"?C.trim()?null:"יש לפרט את סיבת הביטול":"יש לבחור פעולה";function V(){const G={reason:C.trim(),payer_account_id:t==null?void 0:t.payer_account_id,charge_type_id:t==null?void 0:t.charge_type_id,charge_id:t==null?void 0:t.id};if(d==="due_date")return[{...G,exception_action:"due_date",due_date:E}];if(d==="add")return F?[{...G,exception_action:"add_now",lines:v}]:K?p?[{...G,exception_action:"add",cycles:1,lines:v}]:[{...G,exception_action:"add_next",lines:v}]:[{...G,exception_action:"add",cycles:Z,lines:v}];if(d==="credit")return[{...G,exception_action:"credit",discount_amount:0,credit_amount:N}];if(d==="cancel"){if(O==="temporary")return[{...G,exception_action:"skip",cycles:Es(S)}];const ne=[{...G,exception_action:"cancel"}];return p&&ne.push({...G,exception_action:"stop",cycles:1}),ne}return[]}const Y=()=>d==="due_date"?[`תאריך חיוב החשבון שונה למועד ${Ls(E)}`]:d==="add"?[...v.map(G=>`נוסף «${G.description}» — ${Le(G.amount)} ₪`),F?`לחיוב הזה · סכומו עודכן ל-${Le(R+H)} ₪`:K?"לחיוב הבא שיופק לחשבון":`ל-${Z} מחזורי החיוב הבאים`]:d==="credit"?[`${y.kind==="full"?"זיכוי מלא":"זיכוי חלקי"} — ${Le(N)} ₪`,"קוזז מהחיוב הזה; סכום החיוב עצמו לא השתנה"]:d==="cancel"?O==="temporary"?[`החיוב יושהה ל-${Es(S)} ${Es(S)===1?"מחזור":"מחזורים"}`,te?`ויחל שוב במועד ${Ls(te)}
38`:""].filter(Boolean):["החיוב בוטל וירד מיתרת החשבון",...p?["המחזורים הבאים נפסקו"]:[]]:[];i.useEffect(()=>{const G=document.documentElement,ne=[G.style.overflow,document.body.style.overflow];return G.style.overflow="hidden",document.body.style.overflow="hidden",()=>{G.style.overflow=ne[0],document.body.style.overflow=ne[1]}},[]),i.useEffect(()=>{const G=ne=>{ne.key==="Escape"&&(d==="menu"||M?l():c("menu"))};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[l,d,M]);const J=async()=>{if(!(ie||_)){T(!0);try{const G=Y();await r(V()),B(G)}catch{}finally{T(!1)}}},I=u.find(G=>G.v===d),X=(s==null?void 0:s.name)||(t==null?void 0:t._account)||"",se=(s==null?void 0:s.account_number)||(t==null?void 0:t._accountNumber)||"";return Pt.createPortal(e.jsx("div",{dir:"rtl",className:"fixed inset-0 z-[80] bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-3 sm:p-5",onClick:l,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl w-full max-w-2xl flex flex-col max-h-[94vh] overflow-hidden",onClick:G=>G.stopPropagation(),children:[e.jsxs("header",{className:"flex items-center gap-3 px-6 pt-5 pb-4 flex-none bg-gradient-to-l from-teal-50/80 via-sky-50/40 to-transparent",children:[e.jsx("span",{className:"w-11 h-11 rounded-2xl bg-teal-100/80 text-teal-700 grid place-items-center flex-none",children:d==="menu"&&!M?e.jsx(zn,{className:"w-5 h-5"}):e.jsx(De,{className:"w-5 h-5"})}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-[20px] font-black text-slate-900 truncate",children:M?"השינוי נשמר":(I==null?void 0:I.l)||"ניהול חיוב — בחר פעולה"}),e.jsx("span",{className:"block text-[13px] text-slate-500 truncate",children:[X,se&&`חשבון ${se}`].filter(Boolean).join(" · ")||"חיוב"})]}),e.jsx("button",{type:"button",onClick:d==="menu"||M?l:()=>c("menu"),"aria-label":d==="menu"||M?"סגירה":"חזרה לפעולות",className:"w-10 h-10 rounded-2xl bg-white border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50 flex-none",children:d==="menu"||M?e.jsx($e,{className:"w-4 h-4"}):e.jsx(bs,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"mx-6 rounded-2xl bg-slate-50 border border-slate-100 px-2 py-2 flex items-center justify-between gap-1 flex-none overflow-x-auto",children:[e.jsx(ga,{label:"סוג תשלום",tone:"bg-sky-50",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Ke,{className:"w-3.5 h-3.5 text-sky-500 flex-none"}),(t==null?void 0:t._type)||(n==null?void 0:n.name)||"—"]})}),e.jsx(ga,{label:"סכום חיוב",children:e.jsxs("span",{className:"tabular-nums",dir:"ltr",children:[Le(j)," ₪"]})}),(t==null?void 0:t.billing_period)&&e.jsx(ga,{label:"תקופה",children:Nl(t.billing_period)}),e.jsx(ga,{label:"מועד חיוב",children:e.jsx("span",{className:"tabular-nums",dir:"ltr",children:Ls(t==null?void 0:t.due_date)})}),(t==null?void 0:t._status)&&e.jsx(ga,{label:"סטטוס",tone:"bg-emerald-50",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-emerald-700",children:[e.jsx(xt,{className:"w-3.5 h-3.5 flex-none"}),t._status]})})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-6 py-4 space-y-4",children:M?e.jsx("div",{className:"rounded-2xl border border-teal-100 bg-teal-50/60 p-4",children:e.jsxs("ul",{className:"space-y-1.5",children:[M.map(G=>e.jsxs("li",{className:"text-[14px] font-bold text-teal-900 flex items-start gap-2",children:[e.jsx(ye,{className:"w-4 h-4 text-teal-600 flex-none mt-0.5",strokeWidth:3})," ",G]},G)),C.trim()&&e.jsxs("li",{className:"text-[12.5px] text-teal-700/80 flex items-start gap-2 pt-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-teal-400 flex-none mt-1.5"}),"הסיבה שנרשמה: ",C.trim()]})]})}):d==="menu"?e.jsxs(e.Fragment,{children:[[u.slice(0,3),u.slice(3)].map((G,ne)=>G.length===0?null:e.jsx("div",{className:`grid grid-cols-1 gap-3 ${G.length>=3?"sm:grid-cols-3":G.length===2?"sm:grid-cols-2":""}`,children:G.map(ge=>{const ke=ge.icon;return e.jsxs("button",{type:"button",onClick:()=>ge.v==="back"?l():c(ge.v),className:`rounded-2xl border p-4 text-center flex flex-col items-center gap-2 transition-all
39                        hover:shadow-md hover:-translate-y-0.5 ${ge.card}`,children:[e.jsx("span",{className:`w-12 h-12 rounded-full grid place-items-center flex-none ${ge.icon_}`,children:e.jsx(ke,{className:"w-6 h-6",strokeWidth:1.9})}),e.jsx("span",{className:"block text-[15px] font-black text-slate-800 leading-tight",children:ge.l}),e.jsx("span",{className:"block text-[11.5px] text-slate-400 leading-snug",children:ge.hint})]},ge.v)})},ne)),a.length>0&&e.jsxs("section",{className:"rounded-2xl border border-amber-200 bg-amber-50/60 p-3.5",children:[e.jsx("p",{className:"text-[12.5px] font-black text-amber-800 mb-1.5",children:a.length===1?"הוראה פעילה על החיוב הזה":`${a.length} הוראות פעילות על החיוב הזה`}),e.jsx("ul",{className:"space-y-2",children:a.map(G=>{const ne=rd(G);return e.jsxs("li",{className:"flex items-start gap-2 text-[12.5px] text-slate-700",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-bold text-slate-900",children:ne.text}),e.jsxs("span",{className:"block text-[11.5px] text-slate-500",children:[[ne.by&&`על ידי ${ne.by}
39`,ne.at].filter(Boolean).join(" · "),G.from_period&&` · ${Xs(G.from_period)}${G.through_period?` – ${Xs(G.through_period)}`:" ואילך"}`,G.reason&&` · ${G.reason}`]})]}),o&&e.jsxs("button",{type:"button",onClick:()=>o(G.id),className:"mr-auto flex-none inline-flex items-center gap-1 text-[11.5px] font-bold text-rose-600 hover:text-rose-800",children:[e.jsx(Re,{className:"w-3.5 h-3.5"})," ביטול ההוראה"]})]},G.id)})})]})]}):d==="due_date"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-2xl border border-slate-200 p-4",children:e.jsx(Kt,{label:"מועד חיוב ותשלום",hint:`המועד הנוכחי: ${Ls(t==null?void 0:t.due_date)}`,children:e.jsx("input",{type:"date",value:E,className:`${Ts} tabular-nums`,onChange:G=>k(G.target.value)})})}),E!==String((t==null?void 0:t.due_date)||"").slice(0,10)&&e.jsxs(is,{note:"הסכום והמחזורים הבאים אינם מושפעים.",children:["תאריך חיוב החשבון ישונה למועד ",e.jsx("b",{className:"tabular-nums",dir:"ltr",children:Ls(E)}),t!=null&&t.billing_period?` (${Nl(t.billing_period)})`:"","."]}),e.jsx(en,{children:"מועד הפקת מסמך דרישת התשלום נקבע בסוג החיוב ואינו משתנה כאן."})]}):d==="credit"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4 space-y-4",children:[e.jsx(vl,{name:"credit-kind",options:[{v:"partial",l:"זיכוי חלקי"},{v:"full",l:"זיכוי מלא"}],value:y.kind,onChange:G=>$(ne=>({...ne,kind:G}))}),y.kind==="partial"?e.jsx(Kt,{label:"סכום הזיכוי",hint:`ניתן לתת זיכוי עד גובה סכום החיוב: ${Le(R)} ₪`,children:e.jsxs("span",{className:"flex items-stretch",children:[e.jsx("span",{className:"w-11 rounded-r-xl border border-l-0 border-slate-200 bg-slate-50 grid place-items-center text-[13px] font-bold text-slate-400 flex-none",children:"₪"}),e.jsx("input",{type:"number",min:"0",step:"0.01",max:R,value:y.amount,placeholder:"0.00",dir:"ltr",className:`${Ts} tabular-nums rounded-r-none text-left`,onChange:G=>$(ne=>({...ne,amount:G.target.value}))})]})}):e.jsxs("p",{className:"text-[13.5px] text-slate-600",children:["יזוכה מלוא הסכום לתשלום — ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(j)," ₪"]}),"."]}),e.jsx(Kt,{label:"סיבת הזיכוי",required:!0,children:e.jsx("textarea",{value:C,onChange:G=>w(G.target.value),rows:3,maxLength:500,placeholder:"יש לפרט את סיבת הזיכוי",className:`w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-[14px] text-slate-800 resize-none
40                      focus:outline-none focus:border-teal-500 focus:ring-4 focus:ring-teal-50 transition-colors`})})]}),N>0&&e.jsxs(is,{children:["זיכוי בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(N)," ₪"]})," יקוזז מהחיוב הזה. סכום החיוב עצמו אינו משתנה."]}),e.jsx(en,{children:"במסמך דרישת התשלום ובמסמך החיוב תתווסף שורת זיכוי מתחת לשורת החיוב."})]}):d==="cancel"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[15px] font-black text-slate-900 mb-2.5",children:"סוג הביטול"}),e.jsx(vl,{name:"cancel-kind",options:[...p?[{v:"temporary",l:"ביטול מחזורי"}]:[],{v:"permanent",l:"ביטול קבוע"}],value:O,onChange:A})]}),O==="temporary"&&e.jsx(Kt,{label:"מספר מחזורים",children:e.jsx("input",{type:"number",min:"1",max:Cr,value:S,dir:"ltr",className:`${Ts} tabular-nums text-left`,onChange:G=>P(G.target.value)})})]}),O==="temporary"?e.jsxs(is,{children:["החיוב יושהה ל-",Es(S)," ",Es(S)===1?"מחזור":"מחזורים",te?e.jsxs(e.Fragment,{children:[" ויחל שוב במועד ",e.jsx("b",{className:"tabular-nums",dir:"ltr",children:Ls(te)})]}):"","."]}):e.jsx(is,{note:p?"והמחזורים הבאים ייפסקו.":null,children:"החיוב יבוטל, יירד מיתרת החשבון ויישאר בכרטסת מסומן כמבוטל."}),e.jsx("div",{className:"rounded-2xl border border-slate-200 p-4",children:e.jsx(Kt,{label:"סיבת הביטול",required:!0,children:e.jsx("textarea",{value:C,onChange:G=>w(G.target.value),rows:3,maxLength:500,placeholder:"יש לפרט את סיבת הביטול",className:`w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-[14px] text-slate-800 resize-none
41                      focus:outline-none focus:border-teal-500 focus:ring-4 focus:ring-teal-50 transition-colors`})})}),e.jsx(en,{children:"ביטול קבוע יסיר את החיוב מהחשבון. ביטול מחזורי ישהה אותו זמנית."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4 space-y-3",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[15px] font-black text-slate-900",children:"מוצרים לחיוב"}),e.jsx("button",{type:"button","aria-label":"הוספת מוצר נוסף",title:"הוספת מוצר נוסף",onClick:()=>h(G=>[...G,{description:"",amount:""}]),className:`mr-auto w-9 h-9 rounded-xl bg-teal-50 border border-teal-200 text-teal-700
42                      grid place-items-center flex-none hover:bg-teal-100 transition-colors`,children:e.jsx(We,{className:"w-4 h-4",strokeWidth:2.5})})]}),m.map((G,ne)=>e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-3 flex items-end gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Kt,{label:"כותרת המוצר",children:e.jsx("input",{value:G.description,placeholder:"לדוגמה: דמי תחזוקה",className:Ts,onChange:ge=>h(ke=>ke.map((be,je)=>je===ne?{...be,description:ge.target.value}:be))})})}),e.jsx("div",{className:"w-36 flex-none",children:e.jsx(Kt,{label:"מחיר",children:e.jsxs("span",{className:"flex items-stretch",children:[e.jsx("span",{className:"w-10 rounded-r-xl border border-l-0 border-slate-200 bg-slate-50 grid place-items-center text-[13px] font-bold text-slate-400 flex-none",children:"₪"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:G.amount,placeholder:"0.00",dir:"ltr",className:`${Ts} tabular-nums rounded-r-none text-left`,onChange:ge=>h(ke=>ke.map((be,je)=>je===ne?{...be,amount:ge.target.value}:be))})]})})}),e.jsx("button",{type:"button","aria-label":"הסרת המוצר",disabled:m.length===1,onClick:()=>h(ge=>ge.filter((ke,be)=>be!==ne)),className:`w-11 h-11 rounded-xl bg-rose-50 border border-rose-100 grid place-items-center text-rose-500
43                        hover:bg-rose-100 disabled:opacity-30 flex-none`,children:e.jsx(Re,{className:"w-4 h-4"})})]},ne))]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 p-4 space-y-3",children:[e.jsx("span",{className:"block text-[15px] font-black text-slate-900",children:"בחר להוסיף לחיוב"}),e.jsx(vl,{name:"add-span",options:[...L?[{v:"now",l:"לחיוב הנוכחי"}]:[],{v:"next",l:"לחיוב הבא"},...p?[{v:"cycles",l:"למחזורי חיוב"}]:[]],value:x,onChange:g}),!F&&!K&&p&&e.jsx(Kt,{label:"מספר חיובים",children:e.jsx("input",{type:"number",min:"1",max:Cr,value:b,dir:"ltr",className:`${Ts} tabular-nums text-left`,onChange:G=>f(G.target.value)})})]}),v.length>0&&(F?e.jsxs(is,{note:`סכום החיוב יעודכן מ-${Le(R)} ₪ ל-${Le(R+H)} ₪.`,children:[v.length===1?e.jsxs(e.Fragment,{children:["מוצר אחד בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(H)," ₪"]}
43)," יתווסף"]}):e.jsxs(e.Fragment,{children:[v.length," מוצרים בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(H)," ₪"]})," יתווספו"]})," ","לחיוב הזה",t!=null&&t.billing_period?` (${Nl(t.billing_period)})`:"","."]}):K?e.jsxs(is,{note:p?"החיוב הזה אינו משתנה.":"הפריטים ימתינו עד לטעינת הקובץ הבא, וייכנסו לחיוב שייווצר ממנו.",children:[v.length===1?e.jsxs(e.Fragment,{children:["מוצר אחד בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(H)," ₪"]})," יתווסף"]}):e.jsxs(e.Fragment,{children:[v.length," מוצרים בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(H)," ₪"]})," יתווספו"]})," ","לחיוב הבא שיופק לחשבון, פעם אחת."]}):e.jsxs(is,{note:Z>1?`סה״כ תוספת צפויה: ${Le(z)} ₪`:null,children:[v.length===1?e.jsxs(e.Fragment,{children:["מוצר אחד בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(H)," ₪"]})]}):e.jsxs(e.Fragment,{children:[v.length," מוצרים בסך ",e.jsxs("b",{className:"tabular-nums",dir:"ltr",children:[Le(H)," ₪"]})]})," ",v.length===1?"יתווסף":"יתווספו"," ל-",Z," מחזורי החיוב הבאים."]})),e.jsx(en,{children:L?F?"כל עוד לא הופק מסמך חיוב ואישור תשלום, הפריטים נכנסים לחיוב הנוכחי ומסמך דרישת התשלום יונפק מחדש הכולל אותם.":K?"ההוראה ממתינה עד שיופק החיוב הבא לחשבון, נכנסת אליו פעם אחת ואז מסתיימת. היא מוצגת עד אז ברשימת ההוראות הפעילות, ואפשר לבטל אותה.":"הפריטים יתווספו בכל אחד מהמחזורים שנבחרו. החיוב הזה אינו משתנה.":"החיוב הזה כבר נגבה, ולכן לא ניתן להוסיף לו פריטים — מסמך שכבר נמסר אינו משתנה. תוספת תיכנס לחיוב הבא."})]})}),e.jsxs("footer",{className:"flex items-center gap-3 px-6 py-4 flex-none border-t border-slate-100",children:[M?e.jsx("button",{type:"button",onClick:l,className:"h-12 px-8 rounded-2xl bg-teal-600 text-white text-[15px] font-bold hover:bg-teal-700",children:"סגור"}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:J,disabled:!!ie||_,title:ie||"",className:`h-12 flex-1 rounded-2xl bg-teal-600 text-white text-[15px] font-bold inline-flex items-center justify-center gap-2
44                  hover:bg-teal-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors`,children:[_?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):d==="menu"?null:e.jsx(ye,{className:"w-4 h-4",strokeWidth:3}),"עדכן שינויים"]}),e.jsx("button",{type:"button",onClick:l,className:"h-12 px-8 rounded-2xl border border-slate-200 text-slate-600 text-[15px] font-bold hover:bg-slate-50",children:"ביטול"})]}),!M&&ie&&d!=="menu"&&e.jsx("span",{className:"text-[11.5px] text-slate-400 flex-none max-w-[12rem] truncate",children:ie})]})]})}),document.body)}const ce=t=>Math.round(((Number(t)||0)+Number.EPSILON)*100)/100,Qs=t=>Number.isFinite(Number(t))?Number(t):0,Qn=t=>String(t||"").slice(0,7),na=t=>Math.max(0,ce(Qs(t==null?void 0:t.amount)-Qs(t==null?void 0:t.discount_amount)-Qs(t==null?void 0:t.credit_amount))),Gt=t=>(t==null?void 0:t.status)!=="cancelled",Kx=t=>{const s=String(t||"").match(/(\d{4})(\d{2})$/);return s?`${s[1]}-${s[2]}`:""};function xa({statements:t=[],payments:s=[],charges:n=[]}={}){const a=new Set(t.filter(h=>(h==null?void 0:h.status)==="paid").map(h=>h.id)),l=new Map(t.map(h=>[h.id,String((h==null?void 0:h.billing_month)||"")])),r=new Map;for(const h of s){if(!["paid","partial"].includes(h==null?void 0:h.status))continue;const b=l.get(h.statement_id)||Kx(h.reference_number);if(!b||!h.payer_account_id)continue;const f=`${h.payer_account_id}|${b}`;r.set(f,ce((r.get(f)||0)+Qs(h.amount)))}const o=new Map;for(const h of n){if(!Gt(h))continue;const b=String((h==null?void 0:h.billing_period)||"");if(!b||!h.payer_account_id)continue;const f=`${h.payer_account_id}|${b}`;o.set(f,ce((o.get(f)||0)+na(h)))}const p=h=>`${(h==null?void 0:h.payer_account_id)||""}|${String((h==null?void 0:h.billing_period)||"")}`,u=h=>{const b=p(h),f=r.get(b)||0;return f>0?f+.01>
44=(o.get(b)||0):!1},d=h=>!!h&&Gt(h)&&(!!h.statement_id&&a.has(h.statement_id)||u(h)),c=h=>{if(!h||!Gt(h))return 0;if(d(h))return 1;const b=p(h),f=o.get(b)||0;return f>0?Math.min(1,(r.get(b)||0)/f):0};return{isPaid:d,paidOf:h=>Gt(h)?ce(na(h)*c(h)):0,coverOf:c}}const Wx=[{v:"credit",l:"כרטיס אשראי",color:"#3b82f6"},{v:"standing_order",l:"הוראת קבע",color:"#0d9488"},{v:"bank_transfer",l:"העברה בנקאית",color:"#6ee7b7"},{v:"bit",l:"ביט",color:"#8b5cf6"},{v:"cash",l:"מזומן",color:"#f59e0b"},{v:"check",l:"המחאה",color:"#94a3b8"},{v:"other",l:"אחר",color:"#cbd5e1"}];function Ux({payments:t=[],inRange:s=()=>!0}={}){const n=new Map(Wx.map(a=>[a.v,{key:a.v,label:a.l,color:a.color,count:0,gross:0,fee:0,net:0,byMonth:{}}]));for(const a of t){if(!["paid","partial"].includes(a==null?void 0:a.status))continue;const l=a.payment_date||a.created_date;if(!s(l))continue;const r=n.has(a.payment_method)?a.payment_method:"other",o=n.get(r),p=ce(Qs(a.amount)),u=ce(Qs(a.fee_amount??a.commission));o.count+=1,o.gross=ce(o.gross+p),o.fee=ce(o.fee+u),o.net=ce(o.gross-o.fee);const d=Qn(l);d&&(o.byMonth[d]=ce((o.byMonth[d]||0)+p))}return[...n.values()].filter(a=>a.count>0).sort((a,l)=>l.gross-a.gross)}function Hx(t=[]){var a;const s=ce(t.reduce((l,r)=>l+r.gross,0)),n=ce(t.reduce((l,r)=>l+r.fee,0));return{count:t.reduce((l,r)=>l+r.count,0),gross:s,fee:n,net:ce(s-n),leader:((a=t[0])==null?void 0:a.label)||"—",hasFees:t.some(l=>l.fee>0)}}const ya=(t,s)=>s>0?ce(t.gross/s*100):0;function Yx({charges:t=[],accounts:s=[],types:n=[],isPaid:a=()=>!1,today:l=new Date}={}){var d;const r=typeof l=="string"?l.slice(0,10):l.toISOString().slice(0,10),o=new Map(s.map(c=>[c.id,c])),p=new Map(n.map(c=>[c.id,c])),u=[];for(const c of t){if(!Gt(c))continue;const m=String(c.due_date||"").slice(0,10);if(!m||m>=r||a(c))continue;const h=na(c);if(h<=.005)continue;const b=o.get(c.payer_account_id);u.push({id:c.id,payer:(b==null?void 0:b.name)||"ללא חשבון",account:(b==null?void 0:b.account_number)||"",type:((d=p.get(c.charge_type_id))==null?void 0:d.name)||"—",dueDate:m,days:Math.max(0,Math.round((Date.parse(`${r}T00:00:00Z`)-Date.parse(`${m}T00:00:00Z`))/864e5)),balance:h,month:Qn(m)})}return u.sort((c,m)=>m.days-c.days||m.balance-c.balance)}function Vx(t=[]){const s=ce(t.reduce((n,a)=>n+a.balance,0));return{count:t.length,balance:s,avgDays:s>0?Math.round(t.reduce((n,a)=>n+a.days*a.balance,0)/s):0}}function Gx(t=[],s=[]){const n=new Map(s.map(a=>[a,{month:a,amount:0,count:0}]));for(const a of t){const l=n.get(a.month);l&&(l.amount=ce(l.amount+a.balance),l.count+=1)}return[...n.values()]}function Xx({charges:t=[],types:s=[],paidOf:n=()=>0,inRange:a=()=>!0,names:l={},groupUnassigned:r=!1}={}){const o=new Map(s.map(c=>[c.id,c])),p=new Map,u=c=>{const m=Jl(c);return m?`budget:${m}`:r?"none":c?`type:${c.id}`:"none"},d=c=>{const m=Jl(c);return m?l[m]||(c==null?void 0:c.budget_item_name)||`סעיף ${m}`:r?"ללא סעיף תקציבי":(c==null?void 0:c.name)||"ללא סעיף"};for(const c of s){const m=u(c);p.has(m)||p.set(m,{key:m,name:d(c),count:0,billed:0,collected:0,balance:0,budget:c.budget_amount==null?null:ce(c.budget_amount)})}for(const c of t){if(!Gt(c))continue;const m=c.due_date||c.created_date;if(!a(m))continue;const h=o.get(c.charge_type_id);if(!h)continue;const b=u(h);p.has(b)||p.set(b,{key:b,name:d(h),count:0,billed:0,collected:0,balance:0,budget:null});const f=p.get(b),x=na(c);f.count+=1,f.billed=ce(f.billed+x),f.collected=ce(f.collected+n(c)),f.balance=ce(Math.max(0,f.billed-f.collected))}return[...p.values()].sort((c,m)=>m.billed-c.billed)}function Zx(t=[]){const s=t.filter(n=>n.budget!=null);return{lines:t.filter(n=>n.count>0).length,count:t.reduce((n,a)=>n+a.count,0),billed:ce(t.reduce((n,a)=>n+a.billed,0)),collected:ce(t.reduce((n,a)=>n+a.collected,0)),balance:ce(t.reduce((n,a)=>n+a.balance,0)),budget:s.length?ce(s.reduce((n,a)=>n+a.budget,0)):null}}const Jl=t=>(t==null?void 0:t.sumit_budget_item_id)||(t==null?void 0:t.budget_item_id)||null,wl=t=>t.billed>0?ce(t.collected/t.billed*100):0,fc=95;function Qx({charges:t=[],months:s=[],paidOf:n=()=>0}={}){const a=new Map(s.map(l=>[l,{month:l,billed:0,collected:0,balance:0,rate:0}]));for(const l of t){if(!Gt(l))continue;const r=Qn(l.due_date||l.created_date),o=a.get(r);o&&(o.billed=ce(o.billed+na(l)),o.collected=ce(o.collected+n(l)))}for(const l of a.values())l.balance=ce(Math.max(0,l.billed-l.collected)),l.rate=l.billed>0?ce(l.collected/l.billed*100):0;return[...a.values()]}function Jx(t=[]){const s=ce(t.reduce((a,l)=>a+l.billed,0)),n=ce(t.reduce((a,l)=>a+l.collected,0));return{billed:s,collected:n,balance:ce(Math.max(0,s-n)),rate:s>0?ce(n/s*100):0}}function kl(t,s=fc){return t>0?t>=s?{v:"above",l:"מעל ליעד",tone:"emerald"}:t>=s-2?{v:"near",l:"קרוב ליעד",tone:"emerald"}:{v:"below",l:"מתחת ליעד",tone:"rose"}:{v:"none",l:"—",tone:"slate"}}function ep({charges:t=[],months:s=[],paidOf:n=()=>0,typeOf:a=()=>""}={}){const l=new Map(s.map(o=>[o,{month:o,count:0,billed:0,collected:0,balance:0,rate:0,mainDate:"",dates:0,types:[],_byDate:new Map,_byType:new Map}]));for(const o of t){if(!Gt(o))continue;const p=String(o.due_date||"").slice(0,10),u=l.get(Qn(p));if(!u)continue;const d=na(o);u.count+=1,u.billed=ce(u.billed+d),u.collected=ce(u.collected+n(o)),u._byDate.set(p,ce((u._byDate.get(p)||0)+d));const c=a(o)||"ללא סוג",m=u._byType.get(c)||{name:c,count:0,amount:0};m.count+=1,m.amount=ce(m.amount+d),u._byType.set(c,m)}const r=[];for(const o of l.values()){const{_byDate:p,_byType:u,...d}=o;d.balance=ce(Math.max(0,d.billed-d.collected)),d.rate=d.billed>0?ce(d.collected/d.billed*100):0,d.dates=p.size;let c="",m=-1;for(const[h,b]of[...p.entries()].sort((f,x)=>String(f[0]).localeCompare(String(x[0]))))b>m&&(m=b,c=h);d.mainDate=c,d.types=[...u.values()].sort((h,b)=>b.amount-h.amount||b.count-h.count),r.push(d)}return r}function tp(t=[],s=[]){const n=ce(t.reduce((r,o)=>r+o.billed,0)),a=ce(t.reduce((r,o)=>r+o.collected,0)),l=s.length||t.length||0;return{count:t.reduce((r,o)=>r+o.count,0),months:t.filter(r=>r.count>0).length,billed:n,collected:a,balance:ce(Math.max(0,n-a)),rate:n>0?ce(a/n*100):0,avg:l>0?ce(n/l):0}}const Ge=t=>
44(Number(t)||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),Ni=()=>new Date().toISOString().slice(0,10),sp={draft:"טיוטה",pending:"ממתין לאישור",approved:"מאושר",issued:"הופק",cancelled:"בוטל",credited:"זוכה"},ap={שולם:"bg-emerald-50 text-emerald-700 border-emerald-200",באיחור:"bg-red-50 text-red-700 border-red-200",לתשלום:"bg-amber-50 text-amber-700 border-amber-200","ממתין לאישור":"bg-violet-50 text-violet-700 border-violet-200",טיוטה:"bg-slate-100 text-slate-500 border-slate-200",בוטל:"bg-slate-100 text-slate-400 border-slate-200",זוכה:"bg-purple-50 text-purple-700 border-purple-200"},np=t=>ap[t]||"bg-slate-100 text-slate-500 border-slate-200";function lp({cancelled:t,relief:s,marks:n=[]}){const a=new Set;return t&&a.add("בוטל"),s>0&&a.add(`זוכה ${Ge(s)} ₪`),n.forEach(l=>{var o;const r=(o=uo[l.action])==null?void 0:o.note;!r||r==="זיכוי"||r==="בוטל"||a.add(r)}),[...a]}const er=t=>Bn(t)?xs(String(t).slice(0,7)):t||"—",Sl=[{v:"lines",l:"מפורט",full:"מפורט"},{v:"type",l:"סוג חיוב",full:"לפי סוג חיוב"},{v:"payer",l:"משלם",full:"לפי משלם"},{v:"period",l:"תקופה",full:"לפי תקופה"}];function rp({kibbutzId:t,settings:s,initialFilter:n}){var be,je,Ce;const[a,l]=i.useState(!0),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState([]),[b,f]=i.useState([]),[x,g]=i.useState([]),[y,$]=i.useState([]),[O,A]=i.useState([]),[S,P]=i.useState(null),[E,k]=i.useState(null),[C,w]=i.useState(null),[_,T]=i.useState([]),M=i.useRef(!1),B={mode:"lines",type:"",status:"",month:Ni().slice(0,7),q:"",due:""},[R,j]=i.useState(()=>Bx(B,n)),q=(ee,oe)=>j(le=>({...le,[ee]:oe})),L=i.useCallback(async()=>{l(!0);try{const[ee,oe,le,xe,de,ae,Ne,we,Ue]=await Promise.all([D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.MonthlyStatement.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[]),D.functions.invoke("recurringBilling",{action:"exceptions",community_id:t}).then(re=>{var Qe;return((Qe=re==null?void 0:re.data)==null?void 0:Qe.exceptions)||[]}).catch(()=>[]),D.entities.AccountPaymentMethod.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeTypePaymentMethod.filterAll({kibbutz_id:t}).catch(()=>[])]);o(ee||[]),u(oe||[]),c(le||[]),h(xe||[]),f(de||[]),g(ae||[]),T(Ne||[]),$(we||[]),A(Ue||[])}catch{W.error("שגיאה בטעינת הדוח")}finally{l(!1)}},[t]);i.useEffect(()=>{L()},[L]);const N=i.useMemo(()=>new Map(p.map(ee=>[ee.id,ee])),[p]),v=i.useMemo(()=>ur(y,O),[y,O]),F=i.useMemo(()=>zt(r,p,{ready:!a}),[r,p,a]),K=i.useMemo(()=>new Map(d.map(ee=>[ee.id,ee])),[d]),Z=i.useMemo(()=>new Map(m.map(ee=>[ee.id,ee])),[m]),H=i.useMemo(()=>new Map(b.map(ee=>[ee.id,ee])),[b]),z=i.useMemo(()=>xa({statements:b,payments:x,charges:F}),[b,x,F]),te=i.useMemo(()=>{const ee=new Set(F.map(oe=>oe.charge_type_id).filter(Boolean));return p.filter(oe=>ee.has(oe.id))},[F,p]),ie=i.useMemo(()=>{const ee=Ni();return F.map(oe=>{var He;const le=K.get(oe.payer_account_id),xe=le!=null&&le.family_id?Z.get(le.family_id):null,de=N.get(oe.charge_type_id),ae=z.isPaid(oe),{gross:Ne,discount:we,credit:Ue,relief:re,net:Qe,cancelled:Et,paid:bt,open:ue,overdue:Ee,status:za}=qu(oe,{paid:ae,today:ee,labels:sp}),Ps=id(_,{accountId:oe.payer_account_id,typeId:oe.charge_type_id,chargeId:oe.id});return{...oe,_account:le?le.name||`#${le.account_number}`:"ללא חשבון",_accountNumber:(le==null?void 0:le.account_number)||"",_family:(xe==null?void 0:xe.name)||"",_type:(de==null?void 0:de.name)||"—",_kindNote:Sm(de),_typeId:oe.charge_type_id||"",_method:Oa(de==null?void 0:de.calculation_method),_gross:Ne,_discount:we,_credit:Ue,_net:Qe,_open:ue,_overdue:Ee,_statement:((He=H.get(oe.statement_id))==null?void 0:He.billing_month)||"",_paid:bt,_status:za,_relief:re,_marks:Ps,_changes:lp({cancelled:Et,relief:re,marks:Ps})}})},[F,K,Z,N,H,z,_]),V=i.useMemo(()=>
44{if(!R.month)return 0;const{from:ee,to:oe}=xi(R.month);return ie.filter(le=>le._open&&(String(le.due_date||"")<ee||String(le.due_date||"9999")>oe)).length},[ie,R.month]),Y=i.useMemo(()=>{const ee=R.q.trim(),{from:oe,to:le}=xi(R.month);return ie.filter(xe=>!(R.type&&xe.charge_type_id!==R.type||R.status==="open"&&!xe._open||R.status==="paid"&&!xe._paid||R.status==="overdue"&&!xe._overdue||R.status==="cancelled"&&xe.status!=="cancelled"||oe&&String(xe.due_date||"")<oe||le&&String(xe.due_date||"9999")>le||ee&&![xe._account,xe._accountNumber,xe._family,xe._type,xe.description,xe.billing_period].join(" ").includes(ee)))},[ie,R]),J=i.useMemo(()=>R.due?Y.filter(ee=>ee._open&&String(ee.due_date||"").slice(0,10)===R.due):Y,[Y,R.due]),I=i.useMemo(()=>({status:Te(ie,{open:ee=>ee._open,paid:ee=>ee._paid,overdue:ee=>ee._overdue})}),[ie]),X=i.useMemo(()=>new Set(F.map(ee=>String(ee.due_date||"").slice(0,7)).filter(ee=>ee.length===7)),[F]),se=i.useRef(!1);i.useEffect(()=>{if(!(se.current||a||n!=null&&n.due)){if(!R.month){se.current=!0;return}!X.size||X.has(R.month)||(se.current=!0,j(ee=>({...ee,month:[...X].sort().pop()})))}},[a,X,R.month,n]);const G=i.useMemo(()=>Y.filter(ee=>ee._open&&ee.due_date).map(ee=>({date:ee.due_date,count:1,amount:ee._net})),[Y]),ne=(ee,oe,le={})=>({key:ee,header:oe,width:13,type:"money",total:!0,...le}),ge=i.useMemo(()=>{const ee=J.some(ae=>ae._relief>0);if(R.mode==="lines")return{rows:[...J].sort((ae,Ne)=>String(Ne.due_date||Ne.created_date||"").localeCompare(String(ae.due_date||ae.created_date||""))),columns:[{key:"_account",header:"חשבון משלם",width:24,strong:!0},{key:"_accountNumber",header:"מס׳ חשבון",width:11,muted:!0,off:!0},{key:"_type",header:"סוג חיוב",width:18,render:ae=>e.jsxs("span",{className:"block min-w-0",children:[e.jsx("span",{className:"block font-bold text-slate-800 truncate",children:ae._type}),ae._kindNote&&e.jsx("span",{className:"block text-[11px] text-slate-400 truncate",children:ae._kindNote})]})},{key:"_method",header:"שיטת חישוב",width:16,muted:!0,off:!0},{key:"billing_period",header:"תקופה",width:16,render:ae=>er(ae.billing_period)},{key:"description",header:"תיאור",width:26,muted:!0,clamp:!0,off:!0},{key:"quantity",header:"כמות",width:9,type:"num",off:!0},{key:"rate",header:"תעריף (₪)",width:11,type:"dec3",off:!0},ne("_gross","סכום (₪)"),ne("_discount","הנחה (₪)",{off:!ee}),ne("_credit","זיכוי (₪)",{off:!ee}),ne("_net","לתשלום (₪)",{strong:!0,width:14}),{key:"due_date",header:"מועד תשלום",width:12,type:"date"},{key:"_dueDays",header:"עוד",width:12,align:"center",sortable:!0,render:ae=>{var Ne;return e.jsxs("button",{type:"button",onClick:()=>k(ae),title:"ניהול החיוב",className:"inline-flex items-center gap-1 rounded-full transition-shadow hover:shadow-sm",children:[ae._open?e.jsx(tr,{days:Tn(ae.due_date)}):(Ne=ae._changes)!=null&&Ne.length?null:e.jsx("span",{className:"text-slate-300 px-2",children:"—"}
44),e.jsx(ip,{marks:ae._marks,labels:ae._changes})]})}},{key:"_statement",header:"מסמך חשבון",width:12,muted:!0,off:!0},{key:"_status",header:"סטטוס תשלום",width:16,align:"center",render:ae=>e.jsxs("button",{type:"button",onClick:()=>P(ae),title:"הצגת המסמך",className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full border text-[11.5px] font-bold transition-shadow hover:shadow-sm ${np(ae._status)}`,children:[ae._status||"—",e.jsx(fs,{className:"w-3.5 h-3.5 opacity-60"})]})}]};const oe=ae=>R.mode==="type"?ae._typeId||"—":R.mode==="payer"?ae.payer_account_id||"—":ae.billing_period||"—",le=new Map;J.forEach(ae=>{const Ne=oe(ae),we=le.get(Ne)||{id:Ne,_type:ae._type,_method:ae._method,_account:ae._account,_accountNumber:ae._accountNumber,_family:ae._family,billing_period:ae.billing_period||"—",count:0,payers:new Set,_gross:0,_discount:0,_credit:0,_net:0,_overdue:0,_openSum:0,_dues:new Set,_lines:[]};we.count+=1,we._lines.push(ae),we.payers.add(ae.payer_account_id),we._gross+=ae._gross,we._discount+=ae._discount,we._credit+=ae._credit,we._net+=ae._net,ae._overdue&&(we._overdue+=1,we._openSum+=ae._net),ae._open&&ae.due_date&&we._dues.add(String(ae.due_date).slice(0,10)),le.set(Ne,we)});const xe=[...le.values()].map(ae=>{const Ne=[...ae._dues].sort();return{...ae,payers:ae.payers.size,_dues:Ne,_due:Ne[0]||"",_dueDays:Ne.length?Tn(Ne[0]):null,_dueMixed:Ne.length>1}}).sort((ae,Ne)=>Ne._net-ae._net),de=R.mode==="type"?[{key:"_type",header:"סוג חיוב",width:26,strong:!0},{key:"_method",header:"שיטת חישוב",width:18,muted:!0}]:R.mode==="payer"?[{key:"_account",header:"חשבון משלם",width:26,strong:!0},{key:"_accountNumber",header:"מס׳ חשבון",width:12,muted:!0}]:[{key:"billing_period",header:"תקופה",width:22,strong:!0,render:ae=>er(ae.billing_period)}];return{rows:xe,columns:[...de,{key:"count",header:"חיובים",width:10,type:"num",total:!0},{key:"payers",header:"משלמים",width:10,type:"num"},ne("_gross","סכום (₪)"),ne("_discount","הנחות (₪)",{off:!ee}),ne("_credit","זיכויים (₪)",{off:!ee}),ne("_net","לתשלום (₪)",{strong:!0,width:14}),{key:"_due",header:"מועד חיוב",width:14,align:"center",sortable:!0,render:ae=>e.jsx(tr,{days:ae._dueDays,mixed:ae._dueMixed,onOpen:ae._dueMixed?()=>w(ae):null})},{key:"_overdue",header:"באיחור",width:10,type:"num",total:!0},ne("_openSum","סכום באיחור (₪)",{width:14})]}},[R.mode,J]),ke=i.useMemo(()=>{const ee=J.reduce((de,ae)=>de+ae._net,0),oe=J.filter(de=>de._overdue),le=J.filter(de=>de._paid),xe=J.filter(de=>de._open);return[{label:"סך החיובים",value:Ge(ee),currency:!0,sub:_e(J.length,"חיוב אחד","חיובים"),icon:nt,tone:"text-indigo-600 bg-indigo-50"},{label:"סך לגבייה",value:Ge(xe.reduce((de,ae)=>de+ae._net,0)),currency:!0,sub:"יתרה פתוחה",icon:rt,tone:"text-amber-600 bg-amber-50"},{label:"סך שולם",value:Ge(le.reduce((de,ae)=>de+ae._net,0)),currency:!0,sub:_e(le.length,"חיוב אחד שולם","חיובים שולמו"),icon:mr,tone:"text-emerald-600 bg-emerald-50"},{label:"סך באיחור",value:Ge(oe.reduce((de,ae)=>de+ae._net,0)),currency:!0,sub:_e(oe.length,"חיוב אחד באיחור","חיובים באיחור"),icon:Be,tone:oe.length?"text-red-600 bg-red-50":"text-slate-400 bg-slate-100"}]},[J]);return e.jsxs(ss,{title:"דוח חיובים",subtitle:"כל החיובים שהופקו — לפי סוג חיוב, תקופה, מועד תשלום והחשבון המשלם",settings:s,chips:[R.type?`סוג חיוב: ${((be=N.get(R.type))==null?void 0:be.name)||""}`:"הכל",{open:"חיובים פתוחים",paid:"ששולמו",overdue:"באיחור בלבד",cancelled:"מבוטלים","":"כל הסטטוסים"}[R.status],xs(R.month)||"כל התקופות",R.mode!=="lines"&&`תצוגה: ${(je=Sl.find(ee=>ee.v===R.mode))==null?void 0:je.full}`,R.due&&`מועד ${Ve(R.due)}`,R.q&&`חיפוש: ${R.q}`],search:{value:R.q,onChange:ee=>q("q",ee),placeholder:"חיפוש לפי משלם, חשבון או תיאור חיוב"},filters:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"סוג חיוב",hint:"מוצגים רק סוגי חיוב עם נתונים",value:R.type,onCh
44ange:ee=>q("type",ee),options:[{v:"",l:"הכל"},...te.map(ee=>({v:ee.id,l:ee.name}))]}),e.jsx(Ae,{label:"סטטוס תשלום",value:R.status,onChange:ee=>q("status",ee),counts:I.status,options:[{v:"",l:"הכל"},{v:"open",l:"פתוח"},{v:"paid",l:"שולם"},{v:"overdue",l:"באיחור"}]}),e.jsx(mc,{label:"תקופה",value:R.month,monthsWithData:X,allowAll:!0,onChange:ee=>j(oe=>({...oe,month:ee,due:""}))}),e.jsx(Ae,{label:"תצוגה",value:R.mode,onChange:ee=>q("mode",ee),options:Sl})]}),stats:ke,columns:ge.columns,defaultSort:{key:R.mode==="lines"||R.mode==="payer"?"_account":R.mode==="type"?"_type":"billing_period",dir:"asc"},rows:ge.rows,loading:a,fileName:`דוח_חיובים_${((Ce=Sl.find(ee=>ee.v===R.mode))==null?void 0:Ce.full)||""}`,empty:"אין חיובים התואמים את הסינון",footNote:"«לתשלום» הוא הסכום בניכוי הנחות וזיכויים. «שולם» נקבע לפי מסמך חשבון שנפרע או תשלום שכיסה את התקופה, ו«באיחור» לפי מועד התשלום מול היום — לא לפי סטטוס החיוב.",children:[e.jsx(cp,{items:G,value:R.due,onPick:ee=>q("due",ee===R.due?"":ee)}),V>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-3 rounded-xl border border-amber-200 bg-amber-50/70 px-3 py-2",children:[e.jsx(rt,{className:"w-4 h-4 text-amber-600 flex-none"}),e.jsxs("span",{className:"text-[12.5px] text-slate-700",children:[_e(V,"חיוב פתוח אחד","חיובים פתוחים")," מחוץ ל",xs(R.month),"."]}),e.jsx("button",{type:"button",onClick:()=>j(ee=>({...ee,month:"",due:""})),className:`h-7 px-2.5 rounded-lg bg-white border border-amber-300 text-[12px] font-bold text-amber-700
45              hover:bg-amber-100 transition-colors`,children:"הצגת כל התקופות"})]}),S&&e.jsx(Wn,{onClose:()=>P(null),title:`${S._paid?"אישור תשלום":"דרישת תשלום"} · ${S.description||S._type||""}`.trim(),children:e.jsx(co,{charge:{...S,charge_type_name:S._type,paid:S._paid},account:K.get(S.payer_account_id)||{name:S._account,account_number:S._accountNumber},issuer:s||{},method:v(S.payer_account_id,S.charge_type_id)})}),e.jsx(op,{row:C,mode:R.mode,onClose:()=>w(null)}),E&&e.jsx(zx,{charge:E,account:K.get(E.payer_account_id)||null,type:N.get(E.charge_type_id)||null,existing:E._marks||[],onClose:()=>{k(null),M.current&&(M.current=!1,L())},onSave:async ee=>{var le,xe;const oe=Array.isArray(ee)?ee:[ee];try{for(const de of oe){const ae=await D.functions.invoke("recurringBilling",{action:"exception_create",community_id:t,...de});if(!((le=ae==null?void 0:ae.data)!=null&&le.success))throw new Error("save failed")}M.current=!0}catch(de){throw W.error((xe=de==null?void 0:de.message)!=null&&xe.includes("סיבת")?de.message:"שמירת השינוי נכשלה"),de}},onCancelException:async ee=>{var oe;try{const le=await D.functions.invoke("recurringBilling",{action:"exception_cancel",community_id:t,exception_id:ee});W.success((oe=le==null?void 0:le.data)!=null&&oe.reverted?"ההוראה בוטלה והחיוב הוחזר למצבו הקודם":"ההוראה בוטלה"),M.current=!0,k(null),await L()}catch(le){const xe=String((le==null?void 0:le.message)||"");W.error(xe.includes("החיוב")||xe.includes("ההוראה")?xe:"ביטול ההוראה נכשל")}}})]})}function ip({marks:t=[],labels:s=[]}){if(!s.length&&!t.length)return null;const n=t.map(a=>{const l=uo[a.action],r=(l==null?void 0:l.scope)==="charge"?"":a.through_period?` · ${Xs(a.from_period)} – ${Xs(a.through_period)}`:` · ${Xs(a.from_period)} ואילך`,o=a.details,p=o&&o.before&&o.after&&Number(o.before.amount)!==Number(o.after.amount)?` · ${Ge(o.before.amount)} ₪ ← ${Ge(o.after.amount)} ₪`:"";return`${(l==null?void 0:l.note)||a.action}${r}${p} · ${a.reason}`}).join(`
46`);return s.length?e.jsx("span",{className:"inline-flex items-center gap-1 flex-none",title:n||void 0,"aria-label":n?`הערה: ${n}`:void 0,children:s.slice(0,2).map(a=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 text-[11px] font-bold whitespace-nowrap",children:[e.jsx(Mr,{className:"w-3 h-3 flex-none"})," ",a]},a))}):e.jsx("span",{title:n,"aria-label":`הערה: ${n}`,className:"inline-flex items-center justify-center w-6 h-6 rounded-full bg-amber-100 text-amber-700 flex-none",children:e.jsx(Mr,{className:"w-3.5 h-3.5"})})}function op({row:t,mode:s,onClose:n}){i.useEffect(()=>{if(!t)return;const o=p=>{p.key==="Escape"&&n()};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[t,n]);const a=i.useMemo(()=>
46{if(!t)return[];const o=u=>s==="type"?u._account:u._type,p=new Map;return(t._lines||[]).forEach(u=>{const d=String(u.due_date||"").slice(0,10)||"—",c=p.get(d)||{due:d,count:0,net:0,names:new Set,open:0};c.count+=1,c.net+=u._net,u._open&&(c.open+=1);const m=o(u);m&&c.names.add(m),p.set(d,c)}),[...p.values()].sort((u,d)=>u.due.localeCompare(d.due))},[t,s]);if(!t)return null;const l=s==="type"?t._type:s==="payer"?t._account:er(t.billing_period),r=s==="payer"?De:s==="type"?Xe:Be;return Pt.createPortal(e.jsxs("div",{dir:"rtl",className:"fixed inset-0 z-[70] grid place-items-center p-4",role:"dialog","aria-modal":"true","aria-label":`מועדי החיוב של ${l}`,children:[e.jsx("button",{type:"button","aria-label":"סגירה",onClick:n,className:"absolute inset-0 bg-slate-900/40 backdrop-blur-[3px] cursor-default"}),e.jsxs("div",{className:"relative w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden",children:[e.jsxs("header",{className:"relative bg-gradient-to-l from-teal-50/80 via-sky-50/60 to-white px-6 py-5 flex items-start gap-4",children:[e.jsx("span",{className:"w-12 h-12 rounded-2xl bg-white/90 border border-white shadow-sm grid place-items-center flex-none text-teal-600",children:e.jsx(r,{className:"w-6 h-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[21px] font-black text-slate-900 leading-tight truncate",children:l}),e.jsxs("p",{className:"text-[13px] text-slate-500 mt-0.5",children:["מועדי החיוב · ",_e(t.count,"חיוב אחד","חיובים")]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":"סגירה",className:`mr-auto w-9 h-9 rounded-xl bg-white/80 border border-slate-200 grid place-items-center
47              text-slate-400 hover:text-slate-700 hover:bg-white flex-none`,children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"px-4 pb-4 max-h-[60vh] overflow-y-auto",children:[e.jsxs("div",{className:"grid grid-cols-[minmax(0,1.1fr)_minmax(0,1.3fr)_72px_minmax(0,1fr)] gap-3 px-3 py-2.5 text-[12px] font-bold text-slate-400",children:[e.jsx("span",{children:"מועד חיוב"}),e.jsx("span",{children:s==="type"?"משלמים":"סוג תשלום"}),e.jsx("span",{className:"text-center",children:"חיובים"}),e.jsx("span",{className:"text-left",children:"לתשלום (₪)"})]}),e.jsx("ul",{className:"space-y-2",children:a.map(o=>{const p=o.due==="—"?null:Tn(o.due);return e.jsxs("li",{className:`grid grid-cols-[minmax(0,1.1fr)_minmax(0,1.3fr)_72px_minmax(0,1fr)] gap-3 items-center
48                    rounded-2xl border border-slate-100 bg-white shadow-[0_1px_2px_rgba(15,23,42,0.04)] px-3 py-3`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[15px] font-black text-slate-900 tabular-nums",dir:"ltr",children:o.due==="—"?"—":Ve(o.due)}),p!==null&&o.open>0&&e.jsx("span",{className:"block mt-1",children:e.jsx(tr,{days:p})})]}),e.jsx("span",{className:"min-w-0 text-[13px] font-bold text-slate-600 leading-snug",children:[...o.names].join(" · ")||"—"}),e.jsx("span",{className:"text-[15px] font-bold text-slate-700 tabular-nums text-center",dir:"ltr",children:o.count}),e.jsx("span",{className:"text-[17px] font-black text-slate-900 tabular-nums text-left",dir:"ltr",children:Ge(o.net)})]},o.due)})})]}),e.jsxs("footer",{className:`grid grid-cols-[minmax(0,1.1fr)_minmax(0,1.3fr)_72px_minmax(0,1fr)] gap-3 items-center
49          px-7 py-4 border-t border-slate-100 bg-gradient-to-l from-teal-50/70 to-sky-50/50`,children:[e.jsx("span",{className:"text-[15px] font-black text-slate-900",children:"סה״כ"}),e.jsx("span",{}),e.jsx("span",{className:"text-[15px] font-black text-slate-800 tabular-nums text-center",dir:"ltr",children:t.count}),e.jsx("span",{className:"text-[20px] font-black text-teal-700 tabular-nums text-left",dir:"ltr",children:Ge(t._net)})]})]})]}),document.body)}function tr({days:t,mixed:s,onOpen:n=null}){if(s){const a=e.jsxs(e.Fragment,{children:["מועדים שונים",n&&e.jsx(lt,{className:"w-3.5 h-3.5 opacity-60"})]}),l="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border text-[11.5px] font-bold bg-slate-50 text-slate-500 border-slate-200";return n?e.jsx("button",{type:"button",onClick:n,title:"פירוט המועדים שבקבוצה",className:`${l} hover:bg-slate-100 hover:text-slate-700 hover:border-slate-300 transition-colors`,children:a}):e.jsx("span",{className:l,title:"לשורות שבקבוצה יש יותר ממועד תשלום אחד",children:a})}return t==null?e.jsx("span",{className:"text-slate-300",children:"—"}):e.jsx("span",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full border text-[11.5px] font-bold ${Lx[Ql(t)]}`,children:wa(t)})}function cp({items:t=[],value:s="",onPick:n}){const a=i.useMemo(()=>Tx(t),[t]);if(!a.next)return null;const l=a.dates.find(d=>d.date===s)||null,r=Ql(a.next.days),o={late:"bg-red-50/70 border-red-200",soon:"bg-emerald-50/70 border-emerald-200",week:"bg-cyan-50/60 border-cyan-200",far:"bg-sky-50/60 border-sky-200",none:"bg-slate-50 border-slate-200"}[r],p={late:"bg-red-100 text-red-600",soon:"bg-emerald-100 text-emerald-700",week:"bg-cyan-100 text-cyan-700",far:"bg-sky-100 text-sky-700",none:"bg-white text-slate-400 border border-slate-200"}[r],u={late:"text-red-800",soon:"text-emerald-900",week:"text-cyan-900",far:"text-sky-900",none:"text-slate-800"}[r];return e.jsxs("div",{className:`rounded-2xl border px-4 py-3 flex items-center gap-4 flex-wrap ${o}`,children:[e.jsx("span",{className:`w-10 h-10 rounded-xl grid place-items-center flex-none ${p}`,children:e.jsx(Be,{className:"w-5 h-5"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:`block text-[15px] font-black leading-tight ${u}`,children:l?`${wa(l.days,{prefix:"מועד החיוב"})} · ${Ve(l.date)}
49`:a.mixed?`${a.dates.length} מועדי חיוב · הקרוב ${wa(a.next.days)}`:wa(a.next.days,{prefix:"מועד החיוב"})}),e.jsx("span",{className:"block text-[11.5px] text-slate-500 mt-0.5 whitespace-nowrap",children:l?`${_e(l.count,"חיוב אחד","חיובים")} · ${Ge(l.sum)} ₪ · מוצג בטבלה`:a.mixed?`סה״כ ${_e(a.count,"חיוב אחד","חיובים")} · ${Ge(a.sum)} ₪`:`${Ve(a.next.date)} · ${_e(a.next.count,"חיוב אחד","חיובים")} · ${Ge(a.next.sum)} ₪`})]}),a.mixed&&e.jsx("span",{className:"flex items-stretch gap-2 flex-wrap mr-auto",children:a.dates.map(d=>{const c=d.date===s,m=Ql(d.days),h={late:"border-red-300",soon:"border-emerald-300",week:"border-cyan-300",far:"border-sky-300",none:"border-slate-200"}[m],b={late:"ring-red-400",soon:"ring-emerald-400",week:"ring-cyan-400",far:"ring-sky-400",none:"ring-slate-400"}[m],f={late:"text-red-600",soon:"text-emerald-600",week:"text-cyan-700",far:"text-sky-700",none:"text-slate-400"}[m];return e.jsxs("button",{type:"button",onClick:()=>n(d.date),"aria-pressed":c,title:c?"ביטול הסינון":`הצגת החיובים של ${Ve(d.date)} בלבד`,className:`rounded-xl bg-white border px-3.5 py-2.5 text-right transition-all min-w-[9.5rem] ${h} ${c?`ring-2 ${b} shadow-md`:"shadow-sm hover:shadow-md"}`,children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[14px] font-medium text-slate-800 tabular-nums",children:Ve(d.date)}),e.jsx("span",{className:`text-[12px] font-medium mr-auto whitespace-nowrap ${f}`,children:wa(d.days)})]}),e.jsxs("span",{className:"flex items-baseline gap-2 mt-1.5",children:[e.jsxs("span",{className:"text-[15px] font-medium text-slate-900",children:[e.jsx("span",{dir:"ltr",className:"inline-block tabular-nums",children:Ge(d.sum)}),e.jsx("span",{className:"text-[12px] text-slate-400",children:" ₪"})]}),e.jsx("span",{className:"text-[11.5px] text-slate-400 mr-auto whitespace-nowrap",children:_e(d.count,"חיוב אחד","חיובים")})]})]},d.date)})}),l&&e.jsxs("button",{type:"button",onClick:()=>n(l.date),className:"h-9 px-3 rounded-xl bg-white border border-slate-300 text-[12.5px] font-bold text-slate-600 inline-flex items-center gap-1.5 hover:bg-slate-50 flex-none",children:[e.jsx($e,{className:"w-3.5 h-3.5 flex-none"})," כל המועדים"]})]})}const dp={status:"active",method:"",scope:"",q:"",min:""},up=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),$l=t=>(Number(t)||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),mp={active:"פעיל",inactive:"לא פעיל",frozen:"מוקפא"},tn={standing_order:"הוראת קבע",credit:"כרטיס אשראי",bank_transfer:"העברה בנקאית",cash:"מזומן",check:"המחאה"},xp={personal_area:"אזור אישי",email:"דוא״ל",whatsapp:"WhatsApp",push:"Push",print:"הדפסה/מסירה"},vi=new Set(["approved","issued"]);function pp({kibbutzId:t,settings:s}){const[n,a]=i.useState(!0),[l,r]=i.useState([]),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState([]),[h,b]=i.useState([]),[f,x]=i.useState([]),[g,y]=i.useState([]),[$,O]=i.useState(dp),A=(_,T)=>O(M=>({...M,[_]:T})),S=i.useCallback(async()=>{a(!0);try{const[_,T,M,B,R,j,q,L]=await Promise.all([D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me},"-created_date").catch(()=>[]),D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Property.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.WaterMeter.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[])]);r(_||[]),p(T||[]),d(M||[]),m(zt(B,L)),b(R||[]),x(j||[]),y(q||[])}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{S()},[S]);const P=i.useMemo(()=>{const _=new Map(o.map(L=>[L.id,L])),T=L=>{const N=new Map;return L.forEach(v=>N.set(v.payer_account_id,[...N.get(v.payer_account_id)||[],v])),N}
49,M=T(c),B=T(h),R=T(f),j=T(g),q=new Map;return u.forEach(L=>{!L.family_id||L.status==="inactive"||q.set(L.family_id,[...q.get(L.family_id)||[],L])}),l.map(L=>{const N=L.family_id?_.get(L.family_id):null,v=L.family_id&&q.get(L.family_id)||[],F=v.find(z=>z.id===(N==null?void 0:N.head_of_family_id))||v.find(z=>z.family_role==="head")||v.find(z=>z.id===L.primary_resident_id),K=(M.get(L.id)||[]).filter(z=>vi.has(z.status)).reduce((z,te)=>z+(Number(te.amount)||0)-(Number(te.discount_amount)||0)-(Number(te.credit_amount)||0),0),Z=(B.get(L.id)||[]).filter(z=>z.status==="paid"||z.status==="partial").reduce((z,te)=>z+(Number(te.amount)||0),0),H=Number(L.opening_balance)||0;return{...L,_name:L.name||(N==null?void 0:N.name)||"—",_family:(N==null?void 0:N.name)||"",_head:F?F.full_name||[F.first_name,F.last_name].filter(Boolean).join(" "):"",_phone:(F==null?void 0:F.phone)||(F==null?void 0:F.mobile)||"",_budget:Vt(F==null?void 0:F.budget)||v.map(z=>Vt(z.budget)).find(Boolean)||"",_souls:v.length,_properties:(R.get(L.id)||[]).length,_meters:(j.get(L.id)||[]).length,_charges:(M.get(L.id)||[]).filter(z=>vi.has(z.status)).length,_opening:H,_billed:K,_paid:Z,_balance:H+K-Z,_method:tn[L.payment_method]||"",_delivery:String(L.preferred_delivery_channel||"").split(",").map(z=>xp[z.trim()]||z.trim()).filter(Boolean).join(" · "),_status:mp[L.status]||L.status||"פעיל"}})},[l,o,u,c,h,f,g]),E=i.useMemo(()=>{const _=$.q.trim(),T=$.min===""?null:Number($.min);return P.filter(M=>!($.status&&(M.status||"active")!==$.status||$.method&&M.payment_method!==$.method||$.scope==="debt"&&!(M._balance>0)||$.scope==="credit"&&!(M._balance<0)||$.scope==="clear"&&M._balance!==0||T!==null&&!(M._balance>=T)||_&&![M._name,M.account_number,M._family,M._head,M._budget,M.id_number].join(" ").includes(_))).sort((M,B)=>B._balance-M._balance)},[P,$]),k=[{key:"account_number",header:"מס׳ חשבון",width:12},{key:"_name",header:"שם החשבון",width:26,strong:!0},{key:"_head",header:"ראש משפחה",width:20,muted:!0},{key:"_phone",header:"טלפון",width:14,align:"center",render:_=>e.jsx(sx,{phone:_._phone,name:_._head||_._name})},{key:"_budget",header:"מספר תקציב",width:12},{key:"_souls",header:"נפשות",width:9,type:"num",total:!0},{key:"_properties",header:"נכסים",width:9,type:"num",total:!0},{key:"_meters",header:"מוני מים",width:10,type:"num",total:!0},{key:"_charges",header:"חיובים",width:9,type:"num",total:!0},{key:"_opening",header:"יתרת פתיחה (₪)",width:13,type:"money",total:!0},{key:"_billed",header:"סה״כ חויב (₪)",width:13,type:"money",total:!0},{key:"_paid",header:"סה״כ שולם (₪)",width:13,type:"money",total:!0},{key:"_balance",header:"יתרה (₪)",width:14,type:"money",total:!0,strong:!0},{key:"_method",header:"אמצעי תשלום",width:15,muted:!0},{key:"_delivery",header:"ערוץ מסירה",width:13,muted:!0},{key:"_status",header:"סטטוס",width:10,align:"center"}],C=i.useMemo(()=>({status:Te(P,{active:_=>(_.status||"active")==="active",inactive:_=>_.status==="inactive",frozen:_=>_.status==="frozen"}),scope:Te(P,{debt:_=>_._balance>0,credit:_=>_._balance<0,clear:_=>_._balance===0}),method:Te(P,Object.fromEntries(Object.keys(tn).map(_=>[_,T=>T.payment_method===_])))}),[P]),w=i.useMemo(()=>{const _=E.reduce((B,R)=>B+R._billed,0),T=E.reduce((B,R)=>B+R._paid,0),M=E.filter(B=>B._balance>0);return[{label:"חשבונות",value:up(E.length),icon:De},{label:"סה״כ חויב",value:$l(_),currency:!0,icon:rt,tone:"text-indigo-600 bg-indigo-50"},{label:"סה״כ נגבה",value:$l(T),currency:!0,icon:Oe,tone:"text-emerald-600 bg-emerald-50"},{label:"שיעור גבייה",value:`${_>0?Math.min(100,Math.round(T/_*100)):0}%`,icon:rt,tone:"text-blue-600 bg-blue-50"},{label:"חשבונות ביתרה",value:$l(M.reduce((B,R)=>B+R._balance,0)),currency:!0,sub:_e(M.length,"חשבון אחד","חשבונות"),icon:es,tone:M.length?"text-amber-600 bg-amber-50":"text-slate-400 bg-slate-100"}]},[E]);return e.jsx(ss,{title:"דוח חשבונות",subtitle:"פירוט חשבונות המשלמים — המשפחה שמאחורי כל חשבון, מה חויב, מה שולם ומה נותר",settings:s,chips:[{active:"חשבונות פעילים",inactive:"לא פעילים",frozen:"מוקפאים","":"כל הסטטוסים"}[$.status],$.method&&`אמצעי תשלום: ${tn[$.method]||$.method}`,{debt:"ביתרת חובה",credit:"ביתרת זכות",clear:"ללא יתרה","":""}[$.scope],$.min!==""&&`יתרה מעל ${$.min} ₪`,$.q&&`חיפוש: ${$.q}`],search:{value:$.q,onChange:_=>A("q",_),placeholder:"חיפוש לפי חשבון, משפחה, ראש משפחה או מספר תקציב"},filters:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"סטטוס",value:$.status,onChange:_=>A("status",_),counts:C.status,options:[{v:"active",l:"פעילים"},{v:"inactive",l:"לא פעילים"},{v:"frozen",l:"מוקפאים"},{v:"",l:"הכל"}]}
49),e.jsx(Ae,{label:"יתרה",value:$.scope,onChange:_=>A("scope",_),counts:C.scope,options:[{v:"",l:"הכל"},{v:"debt",l:"יתרת חובה"},{v:"credit",l:"יתרת זכות"},{v:"clear",l:"ללא יתרה"}]}),e.jsx(oc,{label:"אמצעי תשלום",value:$.method,onChange:_=>A("method",_),counts:C.method,options:[{v:"",l:"הכל"},...Object.entries(tn).map(([_,T])=>({v:_,l:T}))]}),e.jsx(cc,{label:"יתרה מעל (₪)",value:$.min,onChange:_=>A("min",_),placeholder:"0"})]}),stats:w,columns:k,defaultSort:{key:"_name",dir:"asc"},rows:E,loading:n,fileName:"דוח_חשבונות_משלמים",empty:"אין חשבונות התואמים את הסינון",footNote:"יתרה = יתרת פתיחה + סה״כ חויב − סה״כ שולם. חיוב מבוטל ותשלום שנכשל אינם נכללים."})}const hp={mode:"pages",kind:"",status:"",visibility:"",sales:"",buyer:"",pay:"",q:""},wi=[{v:"pages",l:"עמודים"},{v:"buyers",l:"רוכשים"}],Rn=[{v:"paid",l:"שולם",tone:"bg-emerald-50 text-emerald-700 border-emerald-200"},{v:"pending",l:"ממתין",tone:"bg-amber-50 text-amber-700 border-amber-200"},{v:"failed",l:"נכשל",tone:"bg-red-50 text-red-700 border-red-200"},{v:"refunded",l:"זוכה",tone:"bg-purple-50 text-purple-700 border-purple-200"}],Cl=t=>Rn.find(s=>s.v===t)||Rn[1],bp={credit_card:"כרטיס אשראי",bit:"ביט",google_pay:"Google Pay",apple_pay:"Apple Pay",bank_transfer:"העברה בנקאית",account_charge:"חיוב לחשבון",cash:"מזומן",check:"שיק"},os=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),ki=t=>Number(t||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),Si={פעיל:"bg-emerald-50 text-emerald-700 border-emerald-200",מושבת:"bg-slate-100 text-slate-500 border-slate-200"};function fp({kibbutzId:t,settings:s}){const[n,a]=i.useState(!0),[l,r]=i.useState([]),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState([]),[h,b]=i.useState(hp),f=(M,B)=>b(R=>({...R,[M]:B})),x=i.useCallback(async()=>{a(!0);try{const[M,B,R,j]=await Promise.all([D.entities.PaymentPage.filterAll({kibbutz_id:t}).catch(()=>
49[]),D.entities.PaymentPagePurchase.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[])]);r(M||[]),p(B||[]),d(R||[]),m(j||[])}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{x()},[x]);const g=i.useMemo(()=>new Map(u.map(M=>[M.id,M])),[u]),y=i.useMemo(()=>new Map(c.map(M=>[M.id,M])),[c]),$=i.useMemo(()=>{const M=new Map;return(o||[]).forEach(B=>{const R=B.payment_page_id;if(!R)return;const j=M.get(R)||{paid:0,pending:0,failed:0,refunded:0,total:0,last:null},q=B.status||"pending";j[q]!==void 0&&(j[q]+=1),q==="paid"&&(j.total+=Number(B.amount)||0),q==="refunded"&&(j.total-=Number(B.amount)||0);const L=B.paid_date||B.created_date;L&&(!j.last||L>j.last)&&(j.last=L),M.set(R,j)}),M},[o]),O=i.useMemo(()=>{const M=new Set(l.map(B=>B.kind||"one_time"));return fr.filter(B=>M.has(B.v))},[l]),A=i.useMemo(()=>{const M=B=>{var R;return(((R=$.get(B.id))==null?void 0:R.paid)||0)>0};return{status:Te(l||[],{active:B=>B.is_active!==!1,inactive:B=>B.is_active===!1}),visibility:Te(l||[],{public:B=>(B.visibility||"public")==="public",residents:B=>B.visibility==="residents"}),sales:Te(l||[],{sold:M,none:B=>!M(B)})}},[l,$]),S=i.useMemo(()=>{const M=h.q.trim();return(l||[]).filter(B=>{var q;const R=B.is_active!==!1;if(h.kind&&(B.kind||"one_time")!==h.kind||h.status==="active"&&!R||h.status==="inactive"&&R||h.visibility&&(B.visibility||"public")!==h.visibility)return!1;const j=(((q=$.get(B.id))==null?void 0:q.paid)||0)>0;return!(h.sales==="sold"&&!j||h.sales==="none"&&j||M&&![B.title,B.description,B.slug].join(" ").includes(M))}).map(B=>{var q;const R=$.get(B.id)||{paid:0,pending:0,refunded:0,total:0,last:null},j=kt(B.kind);return{...B,_kind:Wa(B.kind),_priceLabel:Js(B),_price:j.fields.price&&B.price!==null&&B.price!==void 0?Number(B.price):null,_months:B.months_limit?Number(B.months_limit):null,_visibility:(B.visibility||"public")==="public"?"ציבורי":"לתושבים בלבד",_status:B.is_active===!1?"מושבת":"פעיל",_chargeType:B.charge_type_id&&((q=g.get(B.charge_type_id))==null?void 0:q.name)||"",_sales:R.paid,_pending:R.pending,_refunded:R.refunded,_total:R.total,_last:R.last||"",_link:gr(t,B.slug)}})},[l,h,$,g,t]),P=i.useMemo(()=>{const M=h.q.trim(),B=new Map(l.map(R=>[R.id,R]));return(o||[]).map(R=>{const j=B.get(R.payment_page_id)||null,q=Ua(Pr(R)),L=R.payer_account_id?y.get(R.payer_account_id):null;return{...R,_buyer:R.payer_name||"—",_who:q.v,_whoLabel:q.l,_page:(j==null?void 0:j.title)||"— עמוד שנמחק —",_pageKind:j?Wa(j.kind):"",_kindV:(j==null?void 0:j.kind)||"",_account:L&&L.account_number||"",_method:bp[R.payment_method]||R.payment_method||"",_statusHe:Cl(R.status).l,_amount:Number(R.amount)||0,_when:R.paid_date||R.created_date||""}}).filter(R=>!(h.buyer&&R._who!==h.buyer||h.pay&&R.status!==h.pay||h.kind&&R._kindV!==h.kind||M&&![R._buyer,R.payer_phone,R.payer_email,R._page,R._account,R.note].join(" ").includes(M)))},[o,l,y,h]),E=i.useMemo(()=>{const M=(o||[]).map(B=>({k:Pr(B),s:B.status}));return{buyer:Te(M,Object.fromEntries(Er.map(B=>[B.v,R=>R.k===B.v]))),pay:Te(M,Object.fromEntries(Rn.map(B=>[B.v,R=>R.s===B.v])))}},[o]),k=[{key:"_buyer",header:"רוכש/ת",width:24,strong:!0,render:M=>e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-slate-800",children:M._buyer}),e.jsx("span",{className:`inline-block px-2 py-0.5 rounded-full border text-[11px] font-bold whitespace-nowrap ${Ua(M._who).tone}`,title:Ua(M._who).full,children:M._whoLabel})]})},{key:"_whoLabel",header:"סוג רוכש",width:13,muted:!0,off:!0},{key:"_page",header:"עמוד תשלום",width:26},{key:"_pageKind",header:"סוג העמוד",width:18,muted:!0,off:!0},{key:"_amount",header:"סכום (₪)",width:13,type:"money",total:!0,strong:!0},{key:"_statusHe",header:"סטטוס",width:11,align:"center",render:M=>e.jsx("span",{className:`inline-block px-2.5 py-1 rounded-full border text-[11.5px] font-bold ${Cl(M.status).tone}`,children:M._statusHe})},{key:"_method",header:"אמצעי תשלום",width:14,muted:!0}
49,{key:"_account",header:"מס׳ חשבון",width:11,muted:!0},{key:"payer_phone",header:"טלפון",width:13,muted:!0},{key:"payer_email",header:"אימייל",width:20,muted:!0,off:!0},{key:"months",header:"חודשים",width:9,type:"num",off:!0},{key:"_when",header:"תאריך",width:12,type:"date"},{key:"note",header:"הערה",width:22,muted:!0,clamp:!0,off:!0},{key:"provider_reference",header:"אסמכתה",width:16,muted:!0,off:!0}],C=i.useMemo(()=>{const M=P.filter(q=>q.status==="paid"),B=M.reduce((q,L)=>q+L._amount,0)-P.filter(q=>q.status==="refunded").reduce((q,L)=>q+L._amount,0),R=P.filter(q=>q._who==="guest").length,j=P.filter(q=>q._who!=="guest").length;return[{label:"רכישות",value:os(P.length),icon:Lr,tone:"text-indigo-600 bg-indigo-50"},{label:"סה״כ נגבה",value:ki(B),currency:!0,sub:`${os(M.length)} שולמו`,icon:rt,tone:B?"text-teal-600 bg-teal-50":"text-slate-400 bg-slate-100"},{label:"תושבים",value:os(j),sub:"מזוהים בקהילה",icon:ys,tone:"text-sky-600 bg-sky-50"},{label:"אורחים",value:os(R),sub:"אינם רשומים בקהילה",icon:so,tone:R?"text-amber-600 bg-amber-50":"text-slate-400 bg-slate-100"}]},[P]),w=[{key:"title",header:"שם דף התשלום",width:26,strong:!0},{key:"_kind",header:"סוג",width:20,muted:!0},{key:"_priceLabel",header:"עלות",width:18},{key:"_price",header:"סכום",width:12,type:"money",off:!0},{key:"_months",header:"חודשים",width:9,type:"num",off:!0},{key:"_sales",header:"מספר רכישות",width:12,type:"num",total:!0},{key:"_total",header:"סה״כ",width:14,type:"money",total:!0},{key:"_pending",header:"ממתינים",width:10,type:"num",total:!0,off:!0},{key:"_refunded",header:"זוכו",width:9,type:"num",total:!0,off:!0},{key:"_last",header:"רכישה אחרונה",width:13,type:"date",muted:!0,off:!0},{key:"_visibility",header:"נראות",width:13,align:"center"},{key:"_status",header:"סטטוס",width:10,align:"center",render:M=>e.jsx("span",{className:`inline-block px-2.5 py-1 rounded-full border text-[11.5px] font-bold ${Si[M._status]||Si.מושבת}`,children:M._status})},{key:"_chargeType",header:"סוג חיוב",width:14,muted:!0,off:!0},{key:"description",header:"תיאור",width:28,muted:!0,clamp:!0,off:!0},{key:"_link",header:"קישור",width:30,muted:!0,clamp:!0,off:!0},{key:"created_date",header:"נוצר בתאריך",width:12,type:"date",muted:!0}],_=i.useMemo(()=>{const M=S.filter(j=>j._status==="פעיל").length,B=S.reduce((j,q)=>j+(q._sales||0),0),R=S.reduce((j,q)=>j+(q._total||0),0);return[{label:"עמודי תשלום",value:os(S.length),icon:Zt,tone:"text-purple-600 bg-purple-50"},{label:"פעילים",value:os(M),icon:ca,tone:"text-emerald-600 bg-emerald-50"},{label:"סה״כ רכישות",value:os(B),icon:Lr,tone:B?"text-indigo-600 bg-indigo-50":"text-slate-400 bg-slate-100"},{label:"סה״כ נגבה",value:ki(R),currency:!0,icon:rt,tone:R?"text-teal-600 bg-teal-50":"text-slate-400 bg-slate-100"}]},[S]),T=h.mode==="buyers";return e.jsx(ss,{title:"דוח עמודי תשלום",subtitle:"הקישורים שהקהילה הוציאה — מה כל אחד מבקש, כמה שילמו דרכו וכמה נגבה בפועל",settings:s,chips:T?["תצוגה: רוכשים",h.buyer&&Ua(h.buyer).full,h.pay&&`סטטוס: ${Cl(h.pay).l}`,h.kind&&`סוג דף: ${Wa(h.kind)}`,h.q&&`חיפוש: ${h.q}`]:[h.kind&&`סוג: ${Wa(h.kind)}`,h.status==="active"?"עמודים פעילים":h.status==="inactive"?"עמודים מושבתים":"כל הסטטוסים",h.visibility==="public"?"ציבוריים":h.visibility==="residents"?"לתושבים בלבד":"",h.sales==="sold"?"עם רכישות":h.sales==="none"?"ללא רכישות":"",h.q&&`חיפוש: ${h.q}`],search:{value:h.q,onChange:M=>f("q",M),placeholder:T?"חיפוש לפי שם הרוכש, טלפון, אימייל או עמוד":"חיפוש לפי שם הדף, תיאור או קישור"},filters:T?e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"תצוגה",value:h.mode,onChange:M=>f("mode",M),options:wi}
49),e.jsx(Ae,{label:"רוכש",value:h.buyer,onChange:M=>f("buyer",M),counts:E.buyer,options:[{v:"",l:"הכל"},...Er.map(M=>({v:M.v,l:M.l}))]}),e.jsx(Ae,{label:"סטטוס תשלום",value:h.pay,onChange:M=>f("pay",M),counts:E.pay,options:[{v:"",l:"הכל"},...Rn.map(M=>({v:M.v,l:M.l}))]}),e.jsx(Ae,{label:"סוג דף",hint:"מוצגים רק סוגים שקיימים בקהילה",value:h.kind,onChange:M=>f("kind",M),options:[{v:"",l:"הכל"},...O.map(M=>({v:M.v,l:M.l}))]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"תצוגה",value:h.mode,onChange:M=>f("mode",M),options:wi}),e.jsx(Ae,{label:"סוג דף",hint:"מוצגים רק סוגים שקיימים בקהילה",value:h.kind,onChange:M=>f("kind",M),options:[{v:"",l:"הכל"},...O.map(M=>({v:M.v,l:M.l}))]}),e.jsx(Ae,{label:"סטטוס",value:h.status,onChange:M=>f("status",M),counts:A.status,options:[{v:"",l:"הכל"},{v:"active",l:"פעילים"},{v:"inactive",l:"מושבתים"}]}),e.jsx(Ae,{label:"נראות",value:h.visibility,onChange:M=>f("visibility",M),counts:A.visibility,options:[{v:"",l:"הכל"},{v:"public",l:"ציבורי"},{v:"residents",l:"לתושבים"}]}),e.jsx(Ae,{label:"רכישות",value:h.sales,onChange:M=>f("sales",M),counts:A.sales,options:[{v:"",l:"הכל"},{v:"sold",l:"עם רכישות"},{v:"none",l:"ללא רכישות"}]})]}),stats:T?C:_,columns:T?k:w,defaultSort:T?{key:"_when",dir:"desc"}:{key:"title",dir:"asc"},rows:T?P:S,loading:n,fileName:T?"דוח_רוכשים_בעמודי_תשלום":"דוח_עמודי_תשלום",empty:T?"אין רכישות התואמות את הסינון":"אין עמודי תשלום התואמים את הסינון",footNote:T?"«אורח/ת» הוא מי שאינו רשום כתושב בקהילה — עמוד ציבורי פתוח לכל מי שהקישור הגיע אליו, וכל הידוע עליו הוא מה שהקליד בעמוד. «תושב/ת» שילם/ה בכרטיס אשראי ולכן דבר לא נרשם על חשבון המשלם; «תושב/ת · חשבון» הוא חיוב שנרשם בחשבון. הסכום בתחתית הטבלה הוא סכום השורות המוצגות — כולל ממתינים ונכשלים — ואילו «סה״כ נגבה» שלמעלה סופר תשלומים שהושלמו בלבד, בניכוי זיכויים.":"«מספר רכישות» ו«סה״כ» סופרים תשלומים שהושלמו בלבד — ממתינים אינם נספרים וזיכוי יורד מהסכום. תשלום מקוון טרם חובר לעמודי התשלום, ולכן המספרים יתמלאו מרגע חיבור ספק הסליקה."})}const ps=t=>(Number(t)||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),pn=t=>(Number(t)||0).toLocaleString("he-IL",{maximumFractionDigits:0}),Us=(t,s)=>s>0?Math.round(t/s*1e3)/10:0,gp=()=>new Date().toISOString().slice(0,10),yp=new Set(["approved","issued"]),_p=(t,s)=>{if(s!=null&&s.due_day)return Number(s.due_day);const n=String((t==null?void 0:t.due_date)||"").slice(0,10),a=Number(n.slice(8,10));return Number.isFinite(a)&&a>0?a:null},jp=t=>{const s=String(t||"").match(/(\d{4})(\d{2})$/);return s?`${s[1]}-${s[2]}`:""},$i=[{v:"type",l:"לפי סוג חיוב"},{v:"method",l:"לפי אמצעי תשלום"},{v:"payer",l:"לפי משלם"},{v:"lines",l:"מפורט"}],sr=t=>t>=90?"#059669":t>=75?"#0d9488":t>=50?"#d97706":"#dc2626";function Np({kibbutzId:t,settings:s}){var te,ie;const[n,a]=i.useState(!0),[l,r]=i.useState([]),[o,p]=i.useState([]),[u,d]=i.useState([]),[c,m]=i.useState([]),[h,b]=i.useState([]),[f,x]=i.useState([]),[g,y]=i.useState([]),[$,O]=i.useState(null),A=new Date,S={month:Gl(A.getFullYear(),A.getMonth()),type:"",view:"type",q:""},[P,E]=i.useState(S),k=(V,Y)=>E(J=>({...J,[V]:Y})),C=i.useCallback(async()=>{a(!0);try{const[V,Y,J,I,X,se,G]=await Promise.all([D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.MonthlyStatement.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.AccountPaymentMethod.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeTypePaymentMethod.filterAll({kibbutz_id:t}).catch(()=>[])]);r(V||[]),p(Y||[]),d(J||[]),m(I||[]),b(X||[]),x(se||[]),y(G||[])}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{C()},[C]);const w=i.useMemo(()=>new Map(o.map(V=>[V.id,V])),[o]),_=i.useMemo(()=>zt(l,o,{ready:!n}
49),[l,o,n]),T=i.useMemo(()=>new Map(u.map(V=>[V.id,V])),[u]),M=i.useMemo(()=>{const V=ur(f,g);return(Y,J)=>{var I,X;return((I=V(Y,J))==null?void 0:I.kind)||((X=T.get(Y))==null?void 0:X.payment_method)||""}},[f,g,T]),B=i.useMemo(()=>{const V=new Set(h.filter(se=>se.status==="paid").map(se=>se.id)),Y=new Map(h.map(se=>[se.id,String(se.billing_month||"")])),J=new Map;c.filter(se=>se.status==="paid"||se.status==="partial").forEach(se=>{const G=Y.get(se.statement_id)||jp(se.reference_number);if(!G||!se.payer_account_id)return;const ne=`${se.payer_account_id}|${G}`;J.set(ne,(J.get(ne)||0)+(Number(se.amount)||0))});const I=new Map;_.filter(se=>se.status!=="cancelled").forEach(se=>{const G=String(se.billing_period||"");if(!G||!se.payer_account_id)return;const ne=`${se.payer_account_id}|${G}`;I.set(ne,(I.get(ne)||0)+(Number(se.amount)||0)-(Number(se.discount_amount)||0)-(Number(se.credit_amount)||0))});const X=new Set([...J.entries()].filter(([se,G])=>G+.01>=(I.get(se)||0)).map(([se])=>se));return{stPaid:V,covered:X}},[h,c,_]),R=i.useCallback(V=>Rx(V),[]),j=i.useMemo(()=>new Set(_.filter(V=>V.status!=="cancelled").map(R).filter(Boolean)),[_,R]),q=i.useMemo(()=>{if(!P.month||j.has(P.month))return[];const V=J=>{const[I,X]=J.split("-").map(Number);return I*12+(X-1)},Y=V(P.month);return[...j].sort((J,I)=>Math.abs(V(J)-Y)-Math.abs(V(I)-Y)||I.localeCompare(J)).slice(0,3)},[j,P.month]),L=i.useMemo(()=>{const V=gp();return _.filter(Y=>Y.status!=="cancelled").filter(Y=>R(Y)===P.month).map(Y=>{const J=T.get(Y.payer_account_id),I=w.get(Y.charge_type_id),X=(Number(Y.amount)||0)-(Number(Y.discount_amount)||0)-(Number(Y.credit_amount)||0),se=Y.statement_id&&B.stPaid.has(Y.statement_id)||B.covered.has(`${Y.payer_account_id}|${Y.billing_period||""}`),G=yp.has(Y.status)&&!se,ne=G&&Y.due_date&&String(Y.due_date).slice(0,10)<V,ge=M(Y.payer_account_id,Y.charge_type_id);return{...Y,_typeId:Y.charge_type_id||"",_type:(I==null?void 0:I.name)||"—",_dueDay:_p(Y,I),_account:J?J.name||`#${J.account_number}`:"ללא חשבון",_accountNumber:(J==null?void 0:J.account_number)||"",_kind:ge||"",_method:ge?mo(ge).l:"לא הוגדר",_turnover:X,_paidSum:se?X:0,_lateSum:ne?X:0,_openSum:G?X:0,_paid:se,_overdue:ne}})},[_,P.month,R,T,w,B,M]),N=i.useMemo(()=>{const V=P.q.trim();return L.filter(Y=>!(P.type&&Y._typeId!==P.type||V&&![Y._type,Y._method,Y._account,Y._accountNumber,Y.description].join(" ").includes(V)))},[L,P.type,P.q]),v=i.useMemo(()=>{const V=new Set(L.map(Y=>Y._typeId).filter(Boolean));return o.filter(Y=>V.has(Y.id))},[L,o]),F=i.useMemo(()=>{const V=N.reduce((I,X)=>I+X._turnover,0),Y=N.reduce((I,X)=>I+X._paidSum,0),J=N.reduce((I,X)=>I+X._lateSum,0);return{turnover:V,paid:Y,late:J,lateCount:N.filter(I=>I._overdue).length,rate:Us(Y,V)}},[N]),K=i.useMemo(()=>{const V=new Map;return N.forEach(Y=>{const J=V.get(Y._typeId)||{id:Y._typeId||"—",_type:Y._type,_turnover:0,_paidSum:0,_lateSum:0,count:0};J._turnover+=Y._turnover,J._paidSum+=Y._paidSum,J._lateSum+=Y._lateSum,J.count+=1,V.set(Y._typeId,J)}),[...V.values()].map(Y=>({...Y,_rate:Us(Y._paidSum,Y._turnover)})).sort((Y,J)=>J._turnover-Y._turnover)},[N]),Z=i.useMemo(()=>{const V=new Map;return N.forEach(Y=>{const J=`${Y._typeId}|${Y._dueDay??""}`,I=V.get(J)||{id:J,_typeId:Y._typeId,_type:Y._type,_dueDay:Y._dueDay,_turnover:0,_paidSum:0,_lateSum:0,count:0,kinds:new Map};I._turnover+=Y._turnover,I._paidSum+=Y._paidSum,I._lateSum+=Y._lateSum,I.count+=1;const X=I.kinds.get(Y._kind)||{kind:Y._kind,label:Y._method,count:0,turnover:0,paid:0};X.count+=1,X.turnover+=Y._turnover,X.paid+=Y._paidSum,I.kinds.set(Y._kind,X),V.set(J,I)}),[...V.values()].map(Y=>{const J=[...Y.kinds.values()].sort((I,X)=>X.turnover-I.turnover);return{...Y,_methods:J,_method:J.length===1?J[0].label:`${J.length} סוגי תשלום`,_rate:Us(Y._paidSum,Y._turnover)}}).sort((Y,J)=>J._turnover-Y._turnover||(Y._dueDay??99)-(J._dueDay??99))},[N]),H=i.useMemo(()=>{const V=(J,I,X={})=>({key:J,header:I,width:14,type:"money",total:!0,...X}),Y={key:"_rate",header:"אחוז גבייה",width:12,type:"pct",sortable:!0,render:J=>e.jsxs("span",{className:"inline-flex items-center gap-2 justify-start w-full",children:[e.jsxs("span",{className:"text-[13px] font-black tabular-nums",style:{color:sr(J._rate)},dir:"ltr",children:[J._rate.toFixed(1),"%"]}),e.jsx("span",{className:"w-20 h-2 rounded-full bg-slate-100 overflow-hidden flex-none",children:e.jsx("span",{className:"block h-full rounded-full",style:{width:`${Math.min(100,Math.max(2,J._rate))}%`,backgroundColor:sr(J._rate)}})})]})};if(P.view==="type")return{rows:Z,columns:[{key:"_type",header:"סוג תשלום",width:20,strong:!0},{key:"_method",header:"אמצעי תשלום",width:18,muted:!0,render:J=>J._methods.length>1?e.jsxs("button",{type:"button",onClick:()=>O(J),title:"פירוט ההתפלגות לפי אמצעי תשלום",className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-lg bg-slate-100 border border-slate-200
50                      text-[12.5px] font-bold text-slate-700 hover:bg-slate-200 hover:border-slate-300 transition-colors`,children:[J._method,e.jsx(lt,{className:"w-3.5 h-3.5 text-slate-400"})]}):J._method},V("_turnover","סכום המחזור"),{key:"_dueDay",header:"יום החיוב",width:11,align:"center",sortable:!0,render:J=>J._dueDay?`${J._dueDay} בחודש`:e.jsx("span",{className:"text-slate-300",children:"—"})},V("_paidSum","סכום ששולם",{strong:!0}),V("_lateSum","באיחור"),Y]};if(P.view==="method"){const J=new Map;
50return N.forEach(I=>{const X=J.get(I._kind)||{id:I._kind||"—",_method:I._method,_turnover:0,_paidSum:0,_lateSum:0,count:0,types:new Set};X._turnover+=I._turnover,X._paidSum+=I._paidSum,X._lateSum+=I._lateSum,X.count+=1,X.types.add(I._typeId),J.set(I._kind,X)}),{rows:[...J.values()].map(I=>({...I,types:I.types.size,_rate:Us(I._paidSum,I._turnover)})).sort((I,X)=>X._turnover-I._turnover),columns:[{key:"_method",header:"אמצעי תשלום",width:22,strong:!0},{key:"types",header:"סוגי חיוב",width:10,type:"num"},{key:"count",header:"חיובים",width:10,type:"num",total:!0},V("_turnover","סכום המחזור"),V("_paidSum","סכום ששולם",{strong:!0}),V("_lateSum","באיחור"),Y]}}if(P.view==="payer"){const J=new Map;return N.forEach(I=>{const X=J.get(I.payer_account_id)||{id:I.payer_account_id||"—",_account:I._account,_accountNumber:I._accountNumber,_method:I._method,_turnover:0,_paidSum:0,_lateSum:0,count:0};X._turnover+=I._turnover,X._paidSum+=I._paidSum,X._lateSum+=I._lateSum,X.count+=1,J.set(I.payer_account_id,X)}),{rows:[...J.values()].map(I=>({...I,_rate:Us(I._paidSum,I._turnover)})).sort((I,X)=>X._turnover-X._paidSum-(I._turnover-I._paidSum)),columns:[{key:"_account",header:"חשבון משלם",width:24,strong:!0},{key:"_accountNumber",header:"מס׳ חשבון",width:11,muted:!0},{key:"_method",header:"אמצעי תשלום",width:16,muted:!0,off:!0},{key:"count",header:"חיובים",width:9,type:"num",total:!0},V("_turnover","סכום המחזור"),V("_paidSum","סכום ששולם",{strong:!0}),V("_lateSum","באיחור"),Y]}}return{rows:[...N].sort((J,I)=>String(J._type).localeCompare(String(I._type),"he")),columns:[{key:"_type",header:"סוג תשלום",width:18,strong:!0},{key:"_account",header:"חשבון משלם",width:22},{key:"_accountNumber",header:"מס׳ חשבון",width:11,muted:!0,off:!0},{key:"description",header:"תיאור",width:24,muted:!0,clamp:!0,off:!0},{key:"_method",header:"אמצעי תשלום",width:16,muted:!0},V("_turnover","סכום המחזור"),{key:"due_date",header:"מועד תשלום",width:12,type:"date"},V("_paidSum","סכום ששולם",{strong:!0}),V("_lateSum","באיחור")]}},[P.view,Z,N]),z=[{label:"סכום המחזור",value:ps(F.turnover),currency:!0,sub:xs(P.month),icon:Kn,tone:"text-indigo-600 bg-indigo-50"},{label:"סכום ששולם",value:ps(F.paid),currency:!0,sub:`${F.rate.toFixed(1)}% מהמחזור`,icon:rt,tone:"text-emerald-600 bg-emerald-50"},{label:"סכום באיחור",value:ps(F.late),currency:!0,sub:_e(F.lateCount,"חיוב אחד","חיובים"),icon:ws,tone:F.late>0?"text-amber-600 bg-amber-50":"text-slate-400 bg-slate-100"},{label:"אחוז גבייה",value:`${F.rate.toFixed(1)}%`,sub:F.turnover>0?`מתוך ${pn(F.turnover)} ₪`:"אין מחזור בחודש זה",icon:ks,tone:"text-teal-600 bg-teal-50"}];return e.jsxs(e.Fragment,{children:[e.jsx(ss,{title:"דוח הכנסות",subtitle:"מרכז הכנסות לפי סוג חיוב, אמצעי תשלום ומועד חיוב",settings:s,chips:[xs(P.month),P.type?`סוג חיוב: ${((te=w.get(P.type))==null?void 0:te.name)||""}`:"כל סוגי החיוב",P.view!=="type"&&`תצוגה: ${(ie=$i.find(V=>V.v===P.view))==null?void 0:ie.l}`,P.q&&`חיפוש: ${P.q}`],search:{value:P.q,onChange:V=>k("q",V),placeholder:"חיפוש לפי סוג חיוב, אמצעי תשלום או חשבון"},filters:e.jsxs(e.Fragment,{children:[e.jsx(mc,{value:P.month,onChange:V=>k("month",V),monthsWithData:j}),e.jsx(Ae,{label:"סוג חיוב",value:P.type,onChange:V=>k("type",V),options:[{v:"",l:"הכל"},...v.map(V=>({v:V.id,l:V.name}))]}),e.jsx(Ae,{label:"תצוגה",value:P.view,onChange:V=>k("view",V),options:$i})]}),stats:z,columns:H.columns,rows:H.rows,defaultSort:{key:"_turnover",dir:"desc"},loading:n,fileName:`דוח_הכנסות_${P.month}`,empty:q.length?e.jsxs("span",{className:"inline-flex flex-wrap items-center justify-center gap-x-2 gap-y-1.5",children:[e.jsxs("span",{children:["אין הכנסות ב",xs(P.month),". יש הכנסות ב־"]}),q.map(V=>e.jsx("button",{type:"button",onClick:()=>k("month",V),className:`h-7 px-2.5 rounded-lg bg-teal-50 border border-teal-200 text-[12.5px] font-bold
51                text-teal-700 hover:bg-teal-100 hover:border-teal-300 transition-colors`,children:xs(V)},V))]}):"אין הכנסות בחודש שנבחר",footNote:"«סכום המחזור» הוא הסכום לאחר הנחות וזיכויים. «שולם» נקבע לפי מסמך חשבון שנפרע או תשלום שכיסה את התקופה, ו«באיחור» לפי מועד התשלום מול היום — לא לפי סטטוס החיוב. אמצעי התשלום נקרא מההגדרה של משק הבית לאותו סוג חיוב, ובהיעדרה מאמצעי התשלום של החשבון.",after:H.rows.length>0?e.jsx(wp,{byType:K,totals:F}):null}),e.jsx(vp,{row:$,onClose:()=>O(null)})]})}function vp({row:t,onClose:s}){return i.useEffect(()=>{if(!t)return;const n=r=>{r.key==="Escape"&&s()};document.addEventListener("keydown",n);const a=document.documentElement,l={html:a.style.overflow,body:document.body.style.overflow};return a.style.overflow="hidden",document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",n),a.style.overflow=l.html,document.body.style.overflow=l.body}},[t,s]),t?Pt.createPortal(e.jsxs("div",{dir:"rtl",className:"fixed inset-0 z-[70] grid place-items-center p-4",role:"dialog","aria-modal":"true","aria-label":`התפלגות אמצעי תשלום — ${t._type}`,children:[e.jsx("button",{type:"button","aria-label":"סגירה",onClick:s,className:"absolute inset-0 bg-slate-900/45 backdrop-blur-[2px] curs
51or-default"}),e.jsxs("div",{className:"relative w-full max-w-xl bg-white rounded-2xl border border-slate-200 shadow-2xl",children:[e.jsxs("div",{className:"flex items-start gap-3 p-5 pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-[17px] font-black text-slate-900",children:t._type}),e.jsxs("p",{className:"text-[12.5px] text-slate-500 mt-0.5",children:["התפלגות לפי אמצעי תשלום",t._dueDay?` · חיוב ב-${t._dueDay} בחודש`:"",` · ${_e(t.count,"חיוב אחד","חיובים")}`]})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"סגירה",className:"mr-auto w-8 h-8 rounded-lg grid place-items-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 flex-none",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"px-3 pb-3",children:e.jsxs("table",{className:"w-full text-sm border-collapse",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-xs",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2.5 font-semibold text-right",children:"אמצעי תשלום"}),e.jsx("th",{className:"px-3 py-2.5 font-semibold text-right",children:"משלמים"}),e.jsx("th",{className:"px-3 py-2.5 font-semibold text-right",children:"סכום לתשלום"}),e.jsx("th",{className:"px-3 py-2.5 font-semibold text-right",children:"מהמחזור"})]})}),e.jsx("tbody",{children:t._methods.map(n=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"px-3 py-2.5 font-bold text-slate-800 text-right",children:n.label}),e.jsx("td",{className:"px-3 py-2.5 text-right tabular-nums text-slate-700",dir:"ltr",children:n.count}),e.jsx("td",{className:"px-3 py-2.5 text-right tabular-nums font-bold text-slate-900",dir:"ltr",children:ps(n.turnover)}),e.jsxs("td",{className:"px-3 py-2.5 text-right tabular-nums text-slate-500",dir:"ltr",children:[Us(n.turnover,t._turnover).toFixed(1),"%"]})]},n.kind||"none"))}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"border-t-2 border-slate-200 bg-slate-50 font-bold",children:[e.jsx("td",{className:"px-3 py-2.5 text-right",children:"סה״כ"}),e.jsx("td",{className:"px-3 py-2.5 text-right tabular-nums",dir:"ltr",children:t.count}),e.jsx("td",{className:"px-3 py-2.5 text-right tabular-nums",dir:"ltr",children:ps(t._turnover)}),e.jsx("td",{className:"px-3 py-2.5 text-right tabular-nums",dir:"ltr",children:"100.0%"})]})})]})})]})]}),document.body):null}function wp({byType:t,totals:s}){const n=t.slice(0,8).map(r=>({name:r._type,מחזור:Math.round(r._turnover),שולם:Math.round(r._paidSum)})),a=[{name:"נגבה",value:Math.max(0,s.paid)},{name:"נותר",value:Math.max(0,s.turnover-s.paid)}],l=sr(s.rate);return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsxs("section",{className:"lg:col-span-2 bg-white rounded-2xl border border-slate-200 shadow-sm p-4",children:[e.jsxs("header",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ks,{className:"w-4 h-4 text-teal-600 flex-none"}),e.jsx("h4",{className:"text-[15px] font-bold text-slate-800",children:"גבייה לפי סוג חיוב"})]}),e.jsx("div",{style:{width:"100%",height:260},children:e.jsx(Rt,{children:e.jsxs(Ba,{data:n,margin:{top:4,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#f1f5f9",vertical:!1}),e.jsx(Qt,{dataKey:"name",tick:{fontSize:12,fill:"#64748b"},axisLine:!1,tickLine:!1,reversed:!0}),e.jsx(Ct,{tick:{fontSize:11,fill:"#94a3b8"},axisLine:!1,tickLine:!1,orientation:"right",tickFormatter:pn,width:56}),e.jsx(ht,{formatter:(r,o)=>[`${ps(r)} ₪`,o],contentStyle:{direction:"rtl",fontSize:12,borderRadius:12,border:"1px solid #e2e8f0"}}),e.jsx(Qd,{wrapperStyle:{fontSize:12,direction:"rtl"}}),e.jsx(pt,{dataKey:"מחזור",fill:"#cbd5e1",radius:[6,6,0,0],maxBarSize:44}),e.jsx(pt,{dataKey:"שולם",fill:"#0d9488",radius:[6,6,0,0],maxBarSize:44})]})})})]}),e.jsxs("section",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-4 flex flex-col",children:[e.jsxs("header",{className:"flex items-center gap-2 mb-1",children:[e.jsx(xr,{className:"w-4 h-4 text-teal-600 flex-none"}),e.jsx("h4",{className:"text-[15px] font-bold text-slate-800",children:"אחוז גבייה"})]}),e.jsxs("div",{className:"relative flex-1 min-h-[220px]",children:[e.jsx(Rt,{children:e.jsxs(Yn,{children:[e.jsxs(Vn,{data:a,dataKey:"value",innerRadius:"66%",outerRadius:"88%",startAngle:90,endAngle:-270,stroke:"none",isAnimationActive:!1,children:[e.jsx(_s,{fill:l}),e.jsx(_s,{fill:"#e2e8f0"})]}),e.jsx(ht,{formatter:(r,o)=>[`${ps(r)} ₪`,o],contentStyle:{direction:"rtl",fontSize:12,borderRadius:12,border:"1px solid #e2e8f0"}})]})}),e.jsx("div",{className:"absolute inset-0 grid place-items-center pointer-events-none",children:e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-[26px] font-black tabular-nums leading-none",style:{color:l},dir:"ltr",children:[s.rate.toFixed(1),"%"]}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-1",children:"מתוך המחזור"})]})})]}),e.jsxs("dl",{className:"grid grid-cols-2 gap-2 text-center pt-2 border-t border-slate-100",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] text-slate-400",children:"נגבה"}),e.jsxs("dd",{className:"text-[13px] font-black text-emerald-600 tabular-nums",dir:"ltr",children:[pn(s.paid)," ₪"]}
51)]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] text-slate-400",children:"נותר"}),e.jsxs("dd",{className:"text-[13px] font-black text-slate-600 tabular-nums",dir:"ltr",children:[pn(Math.max(0,s.turnover-s.paid))," ₪"]})]})]})]})]})}const us=t=>{const s=Number(t);return Number.isFinite(s)?Math.round((s+Number.EPSILON)*100)/100:0},kp=t=>us((Number(t==null?void 0:t.amount)||0)-(Number(t==null?void 0:t.discount_amount)||0)-(Number(t==null?void 0:t.credit_amount)||0)),Sp=t=>String((t==null?void 0:t.due_date)||(t==null?void 0:t.created_date)||"").slice(0,10),$p=t=>String((t==null?void 0:t.payment_date)||(t==null?void 0:t.created_date)||"").slice(0,10);function Cp({account:t,charges:s=[],payments:n=[],typeName:a=new Map}={}){const l=us(t==null?void 0:t.opening_balance),r=[...s.filter(c=>c.status!=="cancelled").map(c=>({id:`c:${c.id}`,kind:"charge",date:Sp(c),_type:a.get(c.charge_type_id)||"חיוב",description:c.description||a.get(c.charge_type_id)||"חיוב",reference:c.billing_period||"",note:c.notes||"",debit:kp(c),credit:0,_source:c})),...n.filter(c=>c.status==="paid"||c.status==="partial").map(c=>({id:`p:${c.id}`,kind:"payment",date:$p(c),_type:"תשלום",description:"תשלום שהתקבל",reference:c.reference_number||"",note:c.notes||"",debit:0,credit:us(c.amount),_source:c}))];r.sort((c,m)=>String(c.date||"").localeCompare(String(m.date||""))||(c.kind===m.kind?0:c.kind==="charge"?-1:1));let o=l;const p=r.map(c=>(o=us(o+c.debit-c.credit),{...c,balance:o})),u=us(p.reduce((c,m)=>c+m.debit,0)),d=us(p.reduce((c,m)=>c+m.credit,0));return{rows:p,opening:l,debit:u,credit:d,balance:us(l+u-d)}}const Bs=t=>(Number(t)||0).toLocaleString("he-IL",{minimumFractionDigits:2,maximumFractionDigits:2}),Ap=[{v:"",l:"הכל"},{v:"charge",l:"חיובים"},{v:"payment",l:"תשלומים"}];function Mp({kibbutzId:t,settings:s}){var M;const[n,a]=i.useState(!0),[l,r]=i.useState({accounts:[],families:[],residents:[],properties:[],types:[],charges:[],payments:[],methods:[],methodLinks:[]}),[o,p]=i.useState(null),[u,d]=i.useState(null),c={kind:"",span:"year",...Dn("year"),q:""},[m,h]=i.useState(c),b=(B,R)=>h(j=>({...j,[B]:R})),f=i.useCallback(async()=>{a(!0);try{const[B,R,j,q,L,N,v,F,K]=await Promise.all([D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Family.filterAll({kibbutz_id:t,is_deleted:Me},"name").catch(()=>[]),D.entities.Resident.filterAll({kibbutz_id:t,is_deleted:Me}).catch(()=>[]),D.entities.Property.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.AccountPaymentMethod.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeTypePaymentMethod.filterAll({kibbutz_id:t}).catch(()=>[])]);r({accounts:B||[],families:R||[],residents:j||[],properties:q||[],types:L||[],charges:zt(N,L),payments:v||[],methods:F||[],methodLinks:K||[]})}catch{W.error("שגיאה בטעינת הדוח")}finally{a(!1)}},[t]);i.useEffect(()=>{f()},[f]);const x=i.useMemo(()=>ur(l.methods,l.methodLinks),[l.methods,l.methodLinks]),g=i.useMemo(()=>{const B=new Map(l.families.map(q=>[q.id,q])),R=new Map;l.residents.forEach(q=>{q.family_id&&(R.has(q.family_id)||R.set(q.family_id,[]),R.get(q.family_id).push(q))});const j=new Map;return l.properties.forEach(q=>{q.payer_account_id&&(j.has(q.payer_account_id)||j.set(q.payer_account_id,[]),j.get(q.payer_account_id).push(q))}),l.accounts.map(q=>({account:q,family:q.family_id&&B.get(q.family_id)||null,residents:q.family_id?R.get(q.family_id)||[]:[],properties:j.get(q.id)||[]}))},[l]),y=i.useMemo(()=>new Map(l.types.map(B=>[B.id,B.name])),[l.types]),$=i.useMemo(()=>g.find(B=>B.account.id===o)||null,[g,o]),O=i.useMemo(()=>$?Cp({account:$.account,charges:l.charges.filter(B=>B.payer_account_id===$.account.id),payments:l.payments.filter(B=>B.payer_account_id===$.account.id),typeName:y}):null,[$,l.charges,l.payments,y]),A=i.useMemo(()=>{const B=(O==null?void 0:O.rows)||[],R=j=>{const{from:q,to:L}=Dn(j);return N=>(!q||N.date>=q)&&(!L||N.date<=L)};return{kind:Te(B,{charge:j=>j.kind==="charge",payment:j=>j.kind==="payment"}),span:Te(B,Object.fromEntries(Vl.map(j=>[j.v,R(j.v)])))}},[O]),S=i.useMemo(()=>
51{if(!O)return[];const B=m.q.trim();return O.rows.filter(R=>!(m.kind&&R.kind!==m.kind||m.from&&R.date&&R.date<m.from||m.to&&R.date&&R.date>m.to||B&&![R.description,R._type,R.reference].join(" ").includes(B)))},[O,m]);if(n)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-teal-500 rounded-full animate-spin"})});const P=B=>{p(B),h(c)},E=e.jsx(Fp,{rows:g,currentId:o,onPick:P});if(!$)return e.jsxs("div",{children:[E,e.jsxs("p",{className:"text-center text-[13px] text-slate-400 py-10",children:[_e(g.length,"חשבון משלם אחד בקהילה","חשבונות משלמים בקהילה")," — חפשו חשבון כדי להציג את הכרטסת שלו."]})]});const{account:k,family:C,residents:w,properties:_}=$,T=w.find(B=>B.family_role==="head")||w[0]||null;return e.jsxs(e.Fragment,{children:[E,e.jsx(ss,{title:"דוח כרטסת",subtitle:`כל התנועות בחשבון — חיובים, תשלומים ויתרה רצה · ${k.name||""}`,settings:s,chips:[k.account_number?`חשבון ${k.account_number}`:null,{charge:"חיובים בלבד",payment:"תשלומים בלבד","":"חיובים ותשלומים"}[m.kind],m.span==="custom"?m.from||m.to?`${Ve(m.from)||"…"} – ${Ve(m.to)||"…"}`:"כל התקופות":((M=Vl.find(B=>B.v===m.span))==null?void 0:M.l)||"כל התקופות",m.q&&`חיפוש: ${m.q}`],search:{value:m.q,onChange:B=>b("q",B),placeholder:"חיפוש בתנועות — תיאור, סוג חיוב או אסמכתא"},inlineFilters:!0,filters:e.jsxs(e.Fragment,{children:[e.jsx(Ae,{inline:!0,value:m.kind,onChange:B=>b("kind",B),options:Ap,counts:A.kind}),e.jsx(Gm,{inline:!0,value:m.span,from:m.from,to:m.to,counts:A.span,onChange:({span:B,from:R,to:j})=>h(q=>({...q,span:B,from:R,to:j}))})]}),hero:e.jsx(Pp,{account:k,family:C,head:T,properties:_}),stats:[{label:"יתרת פתיחה",value:Bs(O.opening),currency:!0,icon:nt,tone:"text-slate-500 bg-slate-100"},{label:"סך חיובים",value:Bs(O.debit),currency:!0,icon:rt,tone:"text-indigo-600 bg-indigo-50"},{label:"סך תשלומים",value:Bs(O.credit),currency:!0,icon:es,tone:"text-emerald-600 bg-emerald-50"},{label:O.balance<-.001?"יתרת זכות":"יתרה לתשלום",value:Bs(Math.abs(O.balance)),currency:!0,icon:Jd,tone:O.balance>.001?"text-amber-600 bg-amber-50":"text-emerald-600 bg-emerald-50"}],columns:[{key:"date",header:"תאריך",width:12,type:"date"},{key:"description",header:"תיאור",width:28,strong:!0,clamp:!0},{key:"_type",header:"סוג תנועה",width:14},{key:"reference",header:"אסמכתא",width:13,muted:!0},{key:"debit",header:"חיוב (₪)",width:13,type:"money",total:!0,sortable:!0,render:B=>B.debit?Bs(B.debit):""},{key:"credit",header:"תשלום (₪)",width:13,type:"money",total:!0,sortable:!0,render:B=>B.credit?Bs(B.credit):""},{key:"balance",header:"יתרה (₪)",width:14,type:"money",strong:!0},{key:"note",header:"הערות",width:20,muted:!0,clamp:!0,sortable:!0,render:B=>B.note||""}],rows:S,defaultSort:{key:"date",dir:"asc"},empty:"אין תנועות בחשבון בתקופה שנבחרה",fileName:`כרטסת_${k.account_number||k.name||""}`,footNote:"היתרה הרצה מחושבת על כל תנועות החשבון לפי סדר כרונולוגי, מיתרת הפתיחה ואילך — סינון לתקופה מסתיר שורות אך אינו מאפס את היתרה. חיוב מבוטל אינו תנועה.",children:u&&e.jsx(Wn,{onClose:()=>d(null),title:`דרישת תשלום · ${u.description||""}`.trim(),children:e.jsx(co,{charge:u,account:k,issuer:s||{},method:x(u.payer_account_id,u.charge_type_id)})})})]})}function Pp({account:t,family:s,head:n,properties:a=[]}){var u;const l=[s==null?void 0:s.street,s==null?void 0:s.house_number].filter(Boolean).join(" ")||((u=a[0])==null?void 0:u.address)||"",r=t.status==="frozen",o=t.status==="inactive",p=[["בעל החשבון",n==null?void 0:n.full_name,!1],["טלפון",n==null?void 0:n.phone,!0],["כתובת",l,!1],["אמצעי תשלום",t.payment_method?mo(t.payment_method).l:"לא הוגדר",!1]];return e.jsx("section",{className:"rounded-2xl border border-slate-200/80 bg-white shadow-sm px-4 sm:px-5 py-3.5",children:e.jsxs("div",{className:"flex items-center gap-x-4 gap-y-2 flex-wrap",children:[e.jsx("h3",{className:"text-[19px] font-black text-slate-900 leading-none flex-none",children:t.name||(s==null?void 0:s.name)||"חשבון משלם"}),e.jsxs("span",{className:`inline-flex items-center gap-1.5 text-[11.5px] font-bold px-2.5 py-1 rounded-full flex-none ${r?"bg-sky-50 text-sky-700":o?"bg-slate-100 text-slate-500":"bg-emerald-50 text-emerald-700"}`,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${r?"bg-sky-500":o?"bg-slate-400":"bg-emerald-500"}`}),r?"חשבון מוקפא":o?"חשבון לא פעיל":"חשבון פעיל"]}),e.jsx("span",{className:"text-[12.5px] text-slate-500 flex-none",children:[t.account_number&&`חשבון משלם מס׳ ${t.account_number}`,(t.budget_number||t.budget)&&`תקציב ${t.budget_number||t.budget}
51`].filter(Boolean).join("  |  ")||"חשבון משלם"}),p.map(([d,c,m])=>e.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0 flex-none border-r border-slate-200 pr-4",children:[e.jsx("span",{className:"text-[11.5px] text-slate-400 flex-none",children:d}),e.jsx("span",{className:`text-[13.5px] font-bold truncate ${d==="אמצעי תשלום"&&!t.payment_method?"text-amber-700":"text-slate-800"}`,dir:m&&c?"ltr":void 0,style:m&&c?{textAlign:"right"}:void 0,children:c||"—"})]},d))]})})}function Ci({h:t,onPick:s}){var n,a,l;return e.jsxs("button",{type:"button",onClick:()=>s(t.account.id),className:"w-full flex items-center gap-3 p-2.5 rounded-xl text-right hover:bg-teal-50/70 transition-colors",children:[e.jsx("span",{className:"w-9 h-9 rounded-lg bg-slate-100 text-slate-400 grid place-items-center flex-none",children:e.jsx(ys,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[14px] font-bold text-slate-800 truncate",children:t.account.name||((n=t.family)==null?void 0:n.name)||"חשבון ללא שם"}),e.jsx("span",{className:"block text-[11.5px] text-slate-400 truncate",children:[t.account.account_number&&`חשבון ${t.account.account_number}`,(t.account.budget_number||t.account.budget)&&`תקציב ${t.account.budget_number||t.account.budget}`,[(a=t.family)==null?void 0:a.street,(l=t.family)==null?void 0:l.house_number].filter(Boolean).join(" ")].filter(Boolean).join(" · ")})]}),t.why&&e.jsxs("span",{className:"text-[11px] text-slate-500 bg-slate-100 rounded-full px-2 py-0.5 flex-none max-w-[11rem] truncate",children:[t.why.label,": ",t.why.value]})]})}const Ep=[{k:"name",l:"שם משפחה / תושב",p:"כהן"},{k:"account",l:"מספר חשבון",p:"1010"},{k:"budget",l:"מספר תקציב",p:"472"},{k:"phone",l:"טלפון",p:"050…"},{k:"address",l:"כתובת",p:"החמנית 8"}],sn={name:"",account:"",budget:"",phone:"",address:""};function Fp({rows:t,currentId:s,onPick:n}){const[a,l]=i.useState(""),[r,o]=i.useState(!1),[p,u]=i.useState(!1),[d,c]=i.useState(sn),m=i.useRef(null),h=i.useRef(null),b=i.useMemo(()=>Ho(t,a).filter(y=>y.account.id!==s),[t,a,s]),f=Object.values(d).some(y=>y.trim()),x=i.useMemo(()=>Uu(t,d).filter(y=>y.account.id!==s),[t,d,s]);i.useEffect(()=>{if(!r)return;const y=$=>{var O;(O=m.current)!=null&&O.contains($.target)||o(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[r]);const g=y=>{n(y),l(""),o(!1),u(!1),c(sn)};return e.jsxs("section",{ref:m,className:"rounded-2xl border border-teal-200/70 bg-teal-50/40 p-3.5 sm:p-4 no-print mb-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2.5 flex-wrap",children:[e.jsx("label",{htmlFor:"ledger-find",className:"text-[14px] font-extrabold text-slate-700 flex-none",children:"חפש והצג כרטסת"}),e.jsxs("div",{className:"relative w-full sm:w-[30rem]",children:[e.jsx("input",{id:"ledger-find",ref:h,value:a,onChange:y=>{l(y.target.value),o(!0)},onFocus:()=>o(!0),onKeyDown:y=>{y.key==="Enter"&&b[0]&&g(b[0].account.id),y.key==="Escape"&&o(!1)},placeholder:"חיפוש לפי שם משפחה, מספר חשבון, מספר תקציב, טלפון או כתובת","aria-label":"מעבר לכרטסת אחרת",autoComplete:"off",className:`w-full h-11 rounded-xl border border-slate-200 bg-white px-4 pl-10 text-[14px] text-slate-800
52              focus:outline-none focus:border-teal-500 focus:ring-4 focus:ring-teal-50 transition-colors`}),a&&e.jsx("button",{type:"button",onClick:()=>{l(""),o(!1)},"aria-label":"ניקוי",className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-7 h-7 rounded-full grid place-items-center text-slate-400 hover:bg-slate-100",children:e.jsx($e,{className:"w-4 h-4"})}),r&&a.trim().length>=2&&e.jsx("ul",{className:"absolute z-30 mt-1.5 w-full bg-white rounded-2xl border border-slate-200 shadow-xl p-1.5 max-h-80 overflow-y-auto",children:b.length===0?e.jsx("li",{className:"px-3 py-3 text-[13px] text-slate-400 text-center",children:s?`לא נמצא חשבון אחר התואם «${a.trim()}».`:`לא נמצא חשבון התואם «${a.trim()}».`}):b.map(y=>e.jsx("li",{children:e.jsx(Ci,{h:y,onPick:g})},y.account.id))})]}),e.jsx("button",{type:"button","aria-label":"חיפוש",onClick:()=>{var y;b[0]?g(b[0].account.id):(y=h.current)==null||y.focus()},className:"w-11 h-11 rounded-xl bg-teal-600 text-white grid place-items-center flex-none hover:bg-teal-700 transition-colors",children:e.jsx(qt,{className:"w-5 h-5"})}),e.jsx("span",{className:"hidden lg:block w-px h-8 bg-teal-200/80 flex-none"}),e.jsxs("button",{type:"button",onClick:()=>u(y=>
52!y),"aria-expanded":p,className:`h-11 px-4 rounded-xl border text-[13px] font-bold inline-flex items-center gap-1.5 flex-none transition-colors ${p?"bg-teal-600 border-teal-600 text-white":"bg-white border-teal-300 text-teal-700 hover:bg-teal-50"}`,children:[e.jsx(Hn,{className:"w-4 h-4"})," חיפוש מתקדם"]})]}),p&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-teal-200/60",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-2",children:Ep.map(y=>e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"block text-[11px] font-bold text-slate-500 mb-1",children:y.l}),e.jsx("input",{value:d[y.k],placeholder:y.p,autoComplete:"off",onChange:$=>c(O=>({...O,[y.k]:$.target.value})),className:`w-full h-9 rounded-xl border border-slate-200 bg-white px-3 text-[13px] text-slate-800
53                    focus:outline-none focus:border-teal-500 focus:ring-4 focus:ring-teal-50 transition-colors`})]},y.k))}),e.jsx("div",{className:"mt-2.5",children:f?x.length===0?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("p",{className:"text-[12.5px] text-slate-500",children:"לא נמצא חשבון שעונה על כל השדות."}),e.jsx("button",{type:"button",onClick:()=>c(sn),className:"text-[12px] font-bold text-teal-700 hover:underline",children:"ניקוי השדות"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline gap-2 mb-1",children:[e.jsx("span",{className:"text-[12px] font-bold text-slate-500",children:_e(x.length,"חשבון אחד","חשבונות")}),e.jsx("button",{type:"button",onClick:()=>c(sn),className:"text-[12px] font-bold text-teal-700 hover:underline",children:"ניקוי השדות"})]}),e.jsx("ul",{className:"bg-white rounded-2xl border border-slate-200 p-1.5 max-h-72 overflow-y-auto",children:x.map(y=>e.jsx("li",{children:e.jsx(Ci,{h:y,onPick:g})},y.account.id))})]}):e.jsx("p",{className:"text-[12px] text-slate-400",children:"מלאו שדה אחד או יותר — יוצגו רק חשבונות שעונים על כולם."})})]})]})}const ar=t=>String(t).padStart(2,"0"),gc=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],nr=gc,Rs=(t,s,n)=>`${t}-${ar(s+1)}-${ar(n)}`,Ai=(t,s)=>new Date(t,s+1,0).getDate(),Al=[{v:"month",l:"חודשי",hint:"חודש אחד"},{v:"quarter",l:"רבעוני",hint:"שלושה חודשים"},{v:"year",l:"שנתי",hint:"שנה שלמה"},{v:"range",l:"טווח תאריכים",hint:"מתאריך עד תאריך"}],hs=[{v:1,l:"רבעון ראשון",months:[0,2]},{v:2,l:"רבעון שני",months:[3,5]},{v:3,l:"רבעון שלישי",months:[6,8]},{v:4,l:"רבעון רביעי",months:[9,11]}],Dp=(t=new Date)=>({mode:"year",year:t.getFullYear(),month:t.getMonth(),quarter:Math.floor(t.getMonth()/3)+1,from:"",to:""});function yc(t){const s=t||{},n=Number(s.year)||new Date().getFullYear();if(s.mode==="month"){const a=Math.min(11,Math.max(0,Number(s.month)||0));return{from:Rs(n,a,1),to:Rs(n,a,Ai(n,a))}}if(s.mode==="quarter"){const a=hs.find(o=>o.v===Number(s.quarter))||hs[0],[l,r]=a.months;return{from:Rs(n,l,1),to:Rs(n,r,Ai(n,r))}}if(s.mode==="range"){const a=String(s.from||"").slice(0,10),l=String(s.to||"").slice(0,10);return{from:a,to:l}}return{from:Rs(n,0,1),to:Rs(n,11,31)}}function Cs(t){const s=t||{},n=Number(s.year)||new Date().getFullYear();if(s.mode==="month")return`${gc[Math.min(11,Math.max(0,Number(s.month)||0))]} ${n}`;if(s.mode==="quarter")return`${(hs.find(a=>a.v===Number(s.quarter))||hs[0]).l} ${n}`;if(s.mode==="range"){const a=o=>{const[p,u,d]=String(o||"").slice(0,10).split("-");return d?`${d}/${u}/${p}`:""},l=a(s.from),r=a(s.to);return l&&r?`${l} – ${r}`:l?`מ-${l}`:r?`עד ${r}`:"כל התאריכים"}return String(n)}function Jn(t,s){const n=String(t||"").slice(0,10);if(!n)return!1;const{from:a,to:l}=yc(s);return!(a&&n<a||l&&n>l)}function el(t){const{from:s,to:n}=yc(t);if(!s||!n)return[];const[a,l]=s.split("-").map(Number),[r,o]=n.split("-").map(Number),p=[];for(let u=a,d=l;(u<r||u===r&&d<=o)&&!(d>
5312&&(d=1,u+=1,u>r)||(p.push(`${u}-${ar(d)}`),p.length>=120));d+=1);return p}const mt=t=>Math.round(((Number(t)||0)+Number.EPSILON)*100)/100,Ft=t=>Number.isFinite(Number(t))?Number(t):0,Op=new Set(["pending_payment","cancelled","rejected"]),Lp=t=>(t==null?void 0:t.paid)===!0||["completed","paid"].includes(t==null?void 0:t.payment_status),Mi=[{v:"charge_type",l:"סוג חיוב",icon:"tag",tone:"teal"},{v:"payment_page",l:"עמודי תשלום",icon:"link",tone:"purple"},{v:"event",l:"יומן אירועים",icon:"calendar",tone:"sky"},{v:"class",l:"חוגים וסדנאות",icon:"users",tone:"emerald"},{v:"venue",l:"יומנים ותורים",icon:"clock",tone:"indigo"},{v:"quick_charge",l:"סליקה מהירה",icon:"zap",tone:"amber"}],Tp=t=>Mi.find(s=>s.v===t)||Mi[0],qs=t=>String(t||"").slice(0,7),Is=(t,s,n,a=!0)=>({key:t,name:s,kind:n,connected:a,count:0,amount:0,paid:0,open:0,byMonth:{}}),zs=(t,{amount:s,paid:n,month:a})=>{t.count+=1,t.amount=mt(t.amount+s),t.paid=mt(t.paid+n),t.open=mt(Math.max(0,t.amount-t.paid)),a&&(t.byMonth[a]=mt((t.byMonth[a]||0)+s))};function Bp({charges:t=[],types:s=[],purchases:n=[],eventRegs:a=[],classRegs:l=[],bookings:r=[],quickCharges:o=[],connected:p={},paidOf:u=()=>0,inRange:d=()=>!0}={}){const c=new Map,m=new Map((s||[]).map(y=>[y.id,y]));for(const y of s||[])c.set(`type:${y.id}`,Is(`type:${y.id}`,y.name||"סוג חיוב","charge_type"));for(const y of t||[]){if((y==null?void 0:y.status)==="cancelled")continue;const $=y.due_date||y.created_date;if(!d($))continue;const O=m.get(y.charge_type_id);if(!O)continue;const A=`type:${O.id}`,S=Math.max(0,Ft(y.amount)-Ft(y.discount_amount)-Ft(y.credit_amount));zs(c.get(A),{amount:S,paid:Math.min(S,Math.max(0,Ft(u(y)))),month:qs($)})}const h=Is("pages","עמודי תשלום","payment_page");for(const y of n||[]){const $=y.paid_date||y.created_date;if(!d($)||!["paid","refunded"].includes(y.status))continue;const O=Ft(y.amount??y.total_amount??y.price);zs(h,{amount:y.status==="refunded"?0:O,paid:y.status==="refunded"?0:O,month:qs($)})}c.set("pages",h);const b=Is("events","יומן אירועים","event");for(const y of a||[]){if(Op.has(y==null?void 0:y.status))continue;const $=y.payment_completed_at||y.created_date;if(!d($))continue;const O=Ft(y.payment_amount);O>0&&zs(b,{amount:O,paid:Lp(y)?O:0,month:qs($)})}c.set("events",b);const f=Is("classes","חוגים וסדנאות","class",!!p.class);for(const y of l||[]){const $=y.paid_at||y.created_date;if(!d($))continue;const O=Ft(y.payment_amount??y.amount);zs(f,{amount:O,paid:y.payment_status==="paid"?O:0,month:qs($)})}c.set("classes",f);const x=Is("venues","יומנים ותורים","venue",!!p.venue);for(const y of r||[]){const $=y.paid_at||y.start_at||y.created_date;if(!d($))continue;const O=Ft(y.total_price??y.payment_amount??y.amount??y.price);zs(x,{amount:O,paid:y.payment_status==="paid"?O:0,month:qs($)})}c.set("venues",x);const g=Is("quick","סליקה מהירה","quick_charge",p.quick_charge!==!1);g.counted="charge_type";for(const y of o||[]){const $=y.paid_at||y.payment_date||y.created_date;if(!d($))continue;const O=Ft(y.amount??y.total_amount);zs(g,{amount:O,paid:y.status==="paid"?O:0,month:qs($)})}return c.set("quick",g),[...c.values()].sort((y,$)=>Number($.connected)-Number(y.connected)||$.amount-y.amount||String(y.name).localeCompare(String($.name),"he"))}function Rp(t=[]){const s=t.filter(n=>n.connected);return{sources:s.filter(n=>n.count>0).length,count:s.reduce((n,a)=>n+a.count,0),amount:mt(s.reduce((n,a)=>n+a.amount,0)),paid:mt(s.reduce((n,a)=>n+a.paid,0)),open:mt(s.reduce((n,a)=>n+a.open,0)),pending:t.filter(n=>!n.connected).length}}const Ml=(t,s)=>s>0?mt(t.amount/s*100):0;function qp(t=[],s=[],n=6){const a=t.filter(u=>u.connected&&u.amount>0),l=a.slice(0,n),r=a.slice(n),o=[...l.map(u=>({key:u.key,name:u.name,kind:u.kind})),...r.length?[{key:"_rest",name:"מקורות נוספים",kind:"charge_type"}]:[]],p=s.map(u=>{const d={month:u};let c=0;for(const m of l){const h=mt(m.byMonth[u]||0);d[m.key]=h,c+=h}if(r.length){const m=mt(r.reduce((h,b)=>h+(b.byMonth[u]||0),0));d._rest=m,c+=m}return d._total=mt(c),d});return{series:o,data:p}}const Ze=t=>{const[s,n]=String(t||"").split("-");return n?`${n}/${s}`:String(t||"")},Pl=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0);function Ip({label:t,value:s,sub:n,tone:a="teal"}){const l={teal:"bg-teal-50/60 border-teal-100",sky:"bg-sky-50/60 border-sky-100",rose:"bg-rose-50/60 border-rose-100",amber:"bg-amber-50/60 border-amber-100",slate:"bg-slate-50 border-slate-100"};return e.jsxs("div",{className:`h-full rounded-2xl border px-4 py-3 min-w-0 text-right ${l[a]||l.teal}`,children:[e.jsx("span",{className:"block text-[11.5px] font-medium text-slate-500 truncate whitespace-nowrap",children:t}),e.jsx("span",{className:"block text-[17px] font-bold text-slate-800 leading-snug tabular-nums truncate mt-0.5",dir:"ltr",children:s}),n&&e.jsx("span",{className:"block text-[11px] text-slate-400 truncate whitespace-nowrap mt-0.5",children:n})]})}const qe=({color:t,children:s})=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[12px] text-slate-600 whitespace-nowrap",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-none",style:{background:t}}),s]});function As({title:t,legend:s,note:n,center:a,children:l,height:r="20rem"}){return e.jsxs("section",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-5 paper-keep",children:[e.jsxs("header",{className:"flex items-center flex-wrap gap-x-4 gap-y-2 mb-4",children:[e.jsx("h4",{className:"text-[15px] font-black text-slate-800 flex-none",children:t}),s&&e.jsx("span",{className:"mr-auto flex items-center flex-wrap gap-x-4 gap-y-1",children:s})]}),e.jsxs("div",{className:"w-full relative",style:{height:r},dir:"ltr",children:[l,a&&e.jsx("span",{className:"absolute inset-0 grid place-items-center pointer-events-none text-center",children:e.jsxs("span",{children:[e.jsx("span",{className:"block text-[11.5px] font-bold text-slate-400",children:a.label}),e.jsx("span",{className:"block text-[19px] font-black text-slate-900 tabular-nums",dir:"ltr",children:a.value})]})})]}),n&&e.jsx("p",{className:"text-[11.5px] text-slate-400 mt-3 text-center",children:n})]})}function zp({page:t,pages:s,from:n,to:a,total:l,unit:r,onPage:o}){return l===0?null:e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-t border-slate-100 no-print",children:[e.jsxs("span",{className:"text-[12px] text-slate-500",children:["מציג ",Pl(n),"–",Pl(a)," מתוך ",Pl(l)," ",r]}),s>1&&e.jsxs("span",{className:"mr-auto flex items-center gap-1",children:[e.jsx("button",{type:"button","aria-label":"הקודם",disabled:t===1,onClick:()=>o(t-1),className:"w-8 h-8 rounded-lg border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50 disabled:opacity-30",children:e.jsx(oa,{className:"w-4 h-4"})}),Array.from({length:s},(p,u)=>u+1).slice(0,9).map(p=>e.jsx("button",{type:"button",onClick:()=>o(p),className:`w-8 h-8 rounded-lg text-[12.5px] font-bold ${p===t?"bg-teal-600 text-white":"border border-slate-200 text-slate-600 hover:bg-slate-50"}`,children:p},p)),e.jsx("button",{type:"button","aria-label":"הבא",disabled:t===s,onClick:()=>o(t+1),className:"w-8 h-8 rounded-lg border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50 disabled:opacity-30",children:e.jsx(lt,{className:"w-4 h-4"})})]})]})}function Ms({title:t,period:s,subtitle:n,icon:a,tone:l="teal",stats:r=[],chart:o,tableTitle:p,columns:u=[],rows:d=[],totals:c,excelTotals:m,unit:h="רשומות",perPage:b=8,loading:f,empty:x="אין נתונים בתקופה שנבחרה",footNote:g,fileName:y}){const[$,O]=i.useState(1),A=i.useRef(null),[S,P]=i.useState(!1),[E,k]=i.useState(!1),[C,w]=i.useState(null),_=i.useMemo(()=>
53{if(!C)return d;const v=u.find(Z=>Z.key===C.key);if(!v)return d;const F=v.sort||(Z=>Z[v.key]),K=C.dir==="asc"?1:-1;return[...d].sort((Z,H)=>{const z=F(Z),te=F(H),ie=z==null||z==="",V=te==null||te==="";return ie||V?ie&&V?0:ie?1:-1:typeof z=="number"&&typeof te=="number"?(z-te)*K:String(z).localeCompare(String(te),"he",{numeric:!0})*K})},[d,C,u]);i.useEffect(()=>{O(1)},[C]);const T=v=>w(F=>(F==null?void 0:F.key)===v?F.dir==="desc"?{key:v,dir:"asc"}:null:{key:v,dir:"desc"}),M=Math.max(1,Math.ceil(_.length/b)),B=Math.min($,M),R=i.useMemo(()=>_.slice((B-1)*b,B*b),[_,B,b]),j=`${t} — ${s}`,q=async()=>{if(!d.length){W.error("אין נתונים לייצוא");return}try{await nc({fileName:(y||t).replace(/\s+/g,"_"),sheetName:t,title:j,meta:[n,s].filter(Boolean),columns:u.map(v=>({key:v.key,header:v.label,type:v.type,width:v.width,value:v.excel||(F=>F[v.key])})),rows:_,totals:m})}catch{W.error("שגיאה בייצוא")}},L=async()=>{if(!d.length){W.error("אין נתונים לייצוא");return}P(!0);try{const{exportNodePdf:v}=await In(async()=>{const{exportNodePdf:F}=await import("./reportPdf-BRmDXPVe.js");return{exportNodePdf:F}},__vite__mapDeps([3,1,2]));await v(A.current,j),W.success("קובץ ה-PDF נוצר")}catch{W.error("שגיאה ביצירת ה-PDF")}finally{P(!1)}},N={teal:"text-teal-700 bg-teal-50 border-teal-100",rose:"text-rose-600 bg-rose-50 border-rose-100",sky:"text-sky-700 bg-sky-50 border-sky-100"};return e.jsxs("div",{ref:A,id:"billing-report",children:[e.jsx("style",{children:lc}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("section",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-4 paper-keep",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1.7fr,1fr,1fr,1fr] gap-3 items-stretch",children:[e.jsxs("div",{className:"h-full rounded-2xl border border-slate-100 bg-slate-50/70 px-4 py-3 flex items-center gap-3 min-w-0",children:[a&&e.jsx("span",{className:`w-11 h-11 rounded-2xl grid place-items-center flex-none border ${N[l]||N.teal}`,children:e.jsx(a,{className:"w-5 h-5"})}),e.jsxs("span",{className:"min-w-0 flex-1 text-right",children:[e.jsxs("h3",{className:"text-[18px] font-black text-slate-900 leading-tight truncate",title:`${t} — ${s}`,children:[t," — ",s]}),n&&e.jsx("p",{className:"text-[12px] text-slate-500 mt-0.5 truncate",title:n,children:n})]})]}),r.map(v=>e.jsx(Ip,{...v},v.label))]})}),e.jsx("div",{className:"min-h-[46rem]",children:f?e.jsx("div",{className:"grid place-items-center py-40",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-teal-500 rounded-full animate-spin"})}):e.jsxs("div",{className:"space-y-4",children:[o,e.jsxs("section",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden paper-keep",children:[e.jsxs("div",{className:"flex items-center gap-3 px-5 pt-5 pb-3",children:[e.jsx("h4",{className:"text-[15px] font-black text-slate-800",children:p}),e.jsxs("span",{className:"relative mr-auto flex-none no-print",children:[e.jsxs("button",{type:"button",onClick:()=>k(v=>!v),"aria-expanded":E,className:`h-10 px-4 rounded-xl border border-slate-200 bg-white text-[13.5px] font-bold text-slate-600
54                    inline-flex items-center gap-2 hover:border-slate-300`,children:[S?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Hn,{className:"w-4 h-4 text-slate-400"}),"פעולות"]}),E&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":"סגירה",onClick:()=>k(!1),className:"fixed inset-0 z-[40] cursor-default"}),e.jsxs("div",{className:"absolute left-0 z-[41] mt-1 w-48 rounded-xl border border-slate-200 bg-white shadow-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>{k(!1),L()},className:"w-full text-right px-3.5 py-2.5 text-[13.5px] font-bold text-slate-700 hover:bg-slate-50 inline-flex items-center gap-2 border-b border-slate-50",children:[e.jsx(go,{className:"w-4 h-4 text-rose-500"})," הפקת PDF"]}),e.jsxs("button",{type:"button",onClick:()=>{k(!1),q()},className:"w-full text-right px-3.5 py-2.5 text-[13.5px] font-bold text-slate-700 hover:bg-slate-50 inline-flex items-center gap-2",children:[e.jsx(Sd,{className:"w-4 h-4 text-emerald-600"})," ייצוא לאקסל"]})]})]})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500 text-[12px]",children:e.jsx("tr",{children:u.map(v=>
54{const F=(C==null?void 0:C.key)===v.key,K=F?C.dir==="desc"?_o:lo:jo;return e.jsx("th",{"aria-sort":F?C.dir==="asc"?"ascending":"descending":"none",className:"px-4 py-3 font-semibold whitespace-nowrap text-right",children:v.sortable===!1?v.label:e.jsxs("button",{type:"button",onClick:()=>T(v.key),title:`מיון לפי ${v.label}`,className:`w-full inline-flex items-center gap-2 text-right ${F?"text-teal-700":"hover:text-slate-700"}`,children:[e.jsx("span",{children:v.label}),e.jsx(K,{className:`w-3.5 h-3.5 mr-auto flex-none ${F?"text-teal-600":"text-slate-300"}`})]})},v.key)})})}),e.jsxs("tbody",{children:[R.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:u.length,className:"px-4 py-12 text-center text-[13px] text-slate-400",children:x})}),R.map((v,F)=>e.jsx("tr",{className:"border-t border-slate-100 hover:bg-slate-50/60",children:u.map(K=>e.jsx("td",{className:"px-4 py-3 text-right whitespace-nowrap",children:K.render?K.render(v):v[K.key]},K.key))},v.key||v.id||F))]}),c&&d.length>0&&e.jsx("tfoot",{children:e.jsx("tr",{className:"bg-teal-50/60 border-t-2 border-teal-100 font-semibold text-slate-900",children:u.map(v=>e.jsx("td",{className:"px-4 py-3 text-right whitespace-nowrap",children:c[v.key]??""},v.key))})})]})}),e.jsx(zp,{page:B,pages:M,unit:h,from:_.length?(B-1)*b+1:0,to:Math.min(B*b,_.length),total:_.length,onPage:O})]}),g&&e.jsx("p",{className:"text-[11.5px] text-slate-400 text-center",children:g})]})})]})]})}const jt=t=>ve(t),_a=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),ct=t=>t.connected&&t.counted!=="charge_type",Kp={tag:Xe,link:Zt,calendar:vs,users:De,clock:ws,zap:Ns},an=["#0f766e","#14b8a6","#6ee7b7","#7dd3fc","#a78bfa","#f9a8d4","#cbd5e1"],Pi={teal:"bg-teal-50 text-teal-700 border-teal-100",purple:"bg-purple-50 text-purple-700 border-purple-100",sky:"bg-sky-50 text-sky-700 border-sky-100",emerald:"bg-emerald-50 text-emerald-700 border-emerald-100",indigo:"bg-indigo-50 text-indigo-700 border-indigo-100",amber:"bg-amber-50 text-amber-700 border-amber-100"};function Wp({row:t}){const s=Tp(t.kind),n=Kp[s.icon]||Xe;return e.jsxs("span",{className:"inline-flex items-center gap-2 min-w-0",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg border text-[12.5px] font-bold ${Pi[s.tone]||Pi.teal}`,children:[e.jsx(n,{className:"w-3.5 h-3.5 flex-none"}),e.jsx("span",{className:"truncate",children:t.name})]}),!t.connected&&e.jsx("span",{className:"text-[10.5px] font-bold text-slate-400 border border-slate-200 rounded-full px-2 py-0.5 whitespace-nowrap",children:"טרם מחובר"}),t.counted==="charge_type"&&e.jsx("span",{className:"text-[10.5px] font-bold text-teal-600 bg-teal-50 border border-teal-100 rounded-full px-2 py-0.5 whitespace-nowrap",children:"נספר תחת סוג החיוב"})]})}function Up({active:t,payload:s,label:n}){if(!t||!(s!=null&&s.length))return null;const a=s.filter(r=>Number(r.value)>0).reverse(),l=a.reduce((r,o)=>r+Number(o.value),0);return e.jsxs("div",{dir:"rtl",className:"rounded-xl border border-slate-200 bg-white shadow-lg px-3 py-2 min-w-[11rem]",children:[e.jsx("p",{className:"text-[12px] font-black text-slate-800 mb-1",children:Ze(n)}),e.jsx("ul",{className:"space-y-0.5",children:a.map(r=>e.jsxs("li",{className:"flex items-center gap-2 text-[11.5px]",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm flex-none",style:{background:r.color}}),e.jsx("span",{className:"text-slate-600 truncate",children:r.name}),e.jsx("span",{className:"mr-auto font-bold tabular-nums text-slate-800",dir:"ltr",children:jt(r.value)})]},r.dataKey))}),e.jsxs("p",{className:"mt-1.5 pt-1.5 border-t border-slate-100 flex items-center gap-2 text-[12px]",children:[e.jsx("span",{className:"font-bold text-slate-500",children:"סה״כ"}),e.jsx("span",{className:"mr-auto font-black tabular-nums text-slate-900",dir:"ltr",children:jt(l)})]})]})}function Hp({kibbutzId:t,scope:s}){const[n,a]=i.useState({loading:!0,charges:[],types:[],purchases:[],eventRegs:[],statements:[],payments:[]});i.useEffect(()=>{let m=!0;return a(h=>({...h,loading:!0})),Promise.all([D.entities.Charge.filterAllFields({kibbutz_id:t},["id","charge_type_id","payer_account_id","billing_period","statement_id","amount","discount_amount","credit_amount","status","due_date","created_date"]).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>
54[]),D.entities.PaymentPagePurchase.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.EventRegistration.filterAllFields({kibbutz_id:t,is_deleted:Me},["id","status","paid","payment_amount","payment_status","payment_completed_at","created_date"]).catch(()=>[]),D.entities.MonthlyStatement.filterAllFields({kibbutz_id:t},["id","status","billing_month","payer_account_id"]).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[])]).then(([h,b,f,x,g,y])=>{m&&a({loading:!1,charges:h||[],types:(b||[]).filter($=>$.is_active!==!1),purchases:f||[],eventRegs:x||[],statements:g||[],payments:y||[]})}).catch(()=>{m&&a(h=>({...h,loading:!1}))}),()=>{m=!1}},[t]);const l=i.useMemo(()=>xa({statements:n.statements,payments:n.payments,charges:n.charges}),[n.statements,n.payments,n.charges]),r=i.useMemo(()=>Bp({charges:n.charges,types:n.types,purchases:n.purchases,eventRegs:n.eventRegs,paidOf:l.paidOf,inRange:m=>Jn(m,s)}),[n,l,s]),o=i.useMemo(()=>Rp(r),[r]),p=i.useMemo(()=>el(s),[s]),u=i.useMemo(()=>qp(r,p),[r,p]),d=Cs(s),c=[{key:"name",label:"מקור חיוב",width:26,render:m=>e.jsx(Wp,{row:m}),excel:m=>m.name},{key:"count",label:"מספר חיובים",type:"num",render:m=>ct(m)?_a(m.count):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:m=>ct(m)?m.count:void 0},{key:"amount",label:"סכום לחיוב",type:"money",render:m=>ct(m)?jt(m.amount):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:m=>ct(m)?m.amount:void 0},{key:"paid",label:"שולם",type:"money",render:m=>ct(m)?jt(m.paid):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:m=>ct(m)?m.paid:void 0},{key:"open",label:"יתרה",type:"money",render:m=>ct(m)?jt(m.open):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:m=>ct(m)?m.open:void 0},{key:"share",label:"אחוז מהסכום",type:"pct",render:m=>ct(m)?e.jsxs("span",{className:"tabular-nums font-medium text-slate-700",children:[Ml(m,o.amount).toFixed(1),"%"]}):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:m=>ct(m)?Ml(m,o.amount):void 0,sort:m=>ct(m)?Ml(m,o.amount):null}];return e.jsx(Ms,{title:"דוח מקורות חיוב",period:d,subtitle:"ריכוז החיובים מכל המודולים במערכת",icon:Kn,loading:n.loading,fileName:`דוח_מקורות_חיוב_${d}`,stats:[{label:"מקורות פעילים",value:_a(o.sources),tone:"teal",sub:o.pending?`${_a(o.pending)} מקורות טרם מחוברים`:null},{label:"סה״כ חיובים",value:_a(o.count),tone:"sky"},{label:"סכום כולל",value:jt(o.amount),tone:"amber",sub:`שולם ${jt(o.paid)}`}],chart:e.jsx(As,{title:"מקורות החיוב לפי חודש",legend:u.series.map((m,h)=>e.jsx(qe,{color:an[h%an.length],children:m.name},m.key)),height:"20rem",note:u.series.length?null:"אין חיובים בתקופה שנבחרה.",children:e.jsx(Rt,{width:"100%",height:"100%",children:e.jsxs(Ba,{data:u.data,margin:{top:24,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(Qt,{dataKey:"month",tickFormatter:Ze,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#e2e8f0"},reversed:!0}),e.jsx(Ct,{tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:!1,orientation:"right",width:70,tickFormatter:m=>new Intl.NumberFormat("he-IL").format(m)}),e.jsx(ht,{content:e.jsx(Up,{}),cursor:{fill:"#f1f5f9"}}),u.series.map((m,h)=>e.jsx(pt,{dataKey:m.key,name:m.name,stackId:"all",fill:an[h%an.length],radius:h===u.series.length-1?[6,6,0,0]:0,children:h===u.series.length-1&&e.jsx(Ta,{dataKey:"_total",position:"top",offset:8,formatter:b=>Number(b)>0?new Intl.NumberFormat("he-IL").format(b):"",style:{fontSize:11,fontWeight:700,fill:"#334155"}})},m.key))]})})}),tableTitle:"פירוט לפי מקור חיוב",columns:c,rows:r,unit:"מקורות",perPage:16,totals:{name:"סה״כ",count:_a(o.count),amount:jt(o.amount),paid:jt(o.paid),open:jt(o.open),share:"100.0%"},excelTotals:{count:o.count,amount:o.amount,paid:o.paid,open:o.open,share:100},footNote:"כל סוג חיוב שמנוהל במודול «סוגי חיובים» מוצג בשורה נפרדת. «שולם» נגזר ממסמכי החשבון ומהתשלומים, כמו בשאר הדוחות. סליקה מהירה נרשמת כחיוב ותשלום רגילים, ולכן היא נספרת תחת סוג החיוב שלה ולא פעמיים. מקור שטרם חובר מוצג בתחתית הטבלה בלי מספרים — «אין נתונים» ו«לא נמדד» אינם אותו דבר."})}const _t=t=>ve(t),hn=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0);function Yp({active:t,payload:s}){var a;if(!t||!(s!=null&&s.length))return null;const n=(a=s[0])==null?void 0:a.payload;return n?e.jsxs("div",{dir:"rtl",className:"rounded-xl border border-slate-200 bg-white shadow-lg px-3 py-2",children:[e.jsxs("p",{className:"text-[12px] font-black text-slate-800 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:n.color}}),n.label]}),e.jsx("p",{className:"text-[12px] text-slate-600 mt-1 tabular-nums",dir:"ltr",children:_t(n.gross)}),e.jsxs("p",{className:"text-[11.5px] text-slate-400",children:[hn(n.count)," תשלומים"]})]}):null}function Vp({kibbutzId:t,scope:s}){const[n,a]=i.useState({loading:!0,payments:[]});i.useEffect(()=>{let u=!0;return a(d=>({...d,loading:!0})),D.entities.Payment.filterAll({kibbutz_id:t}).then(d=>{u&&a({loading:!1,payments:d||[]})}).catch(()=>{u&&a({loading:!1,payments:[]})}),()=>{u=!1}},[t]);const l=i.useMemo(()=>Ux({payments:n.payments,inRange:u=>Jn(u,s)}),[n.payments,s]),r=i.useMemo(()=>Hx(l),[l]),o=Cs(s),p=[{key:"label",label:"אמצעי תשלום",width:22,render:u=>e.jsxs("span",{className:"inline-flex items-center gap-2 font-medium text-slate-700 whitespace-nowrap",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-none",style:{background:u.color}}),u.label]}),excel:u=>u.label},{key:"count",label:"מספר תשלומים",type:"num",render:u=>hn(u.count)},{key:"gross",label:"סכום",type:"money",render:u=>_t(u.gross)},{key:"fee",label:"עמלות",type:"money",render:u=>r.hasFees?_t(u.fee):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:u=>r.hasFees?u.fee:void 0},{key:"net",label:"נטו",type:"money",render:u=>e.jsx("span",{className:"font-medium text-slate-800",children:_t(u.net)})},{key:"share",label:"אחוז מהגבייה",type:"pct",render:u=>{const d=ya(u,r.gross);return e.jsxs("span",{className:"inline-flex items-center gap-2 min-w-[7rem]",children:[e.jsx("span",{className:"flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("span",{className:"block h-full rounded-full",style:{width:`${Math.min(100,d)}%`,background:u.color}})}),e.jsxs("span",{className:"tabular-nums font-medium text-slate-700 text-[12.5px] w-12 text-left",dir:"ltr",children:[d.toFixed(1),"%"]})]})},excel:u=>ya(u,r.gross),sort:u=>ya(u,r.gross)}];return e.jsx(Ms,{title:"דוח אמצעי תשלום",period:o,subtitle:"התפלגות הגבייה לפי אמצעי התשלום שנפרע בו",icon:Oe,tone:"sky",loading:n.loading,fileName:`דוח_אמצעי_תשלום_${o}`,stats:[{label:"סה״כ נגבה",value:_t(r.gross),tone:"teal",sub:r.hasFees?`נטו ${_t(r.net)}`:null},{label:"מספר תשלומים",value:hn(r.count),tone:"sky"},{label:"אמצעי מוביל",value:r.leader,tone:"amber",sub:l[0]?`${ya(l[0],r.gross).toFixed(1)}% מהגבייה`:null}],chart:e.jsx(As,{title:"התפלגות הגבייה",legend:l.map(u=>e.jsxs(qe,{color:u.color,children:[u.label," · ",e.jsxs("b",{className:"tabular-nums",children:[ya(u,r.gross).toFixed(1),"%"]})]},u.key)),height:"20rem",center:l.length?{label:"סה״כ נגבה",value:_t(r.gross)}:null,note:l.length?null:"לא נרשמו תשלומים בתקופה שנבחרה.",children:e.jsx(Rt,{width:"100%",height:"100%",children:e.jsxs(Yn,{children:[e.jsx(Vn,{data:l,dataKey:"gross",nameKey:"label",innerRadius:"58%",outerRadius:"86%",paddingAngle:l.length>1?2:0,stroke:"#fff",strokeWidth:2,children:l.map(u=>e.jsx(_s,{fill:u.color},u.key))}),e.jsx(ht,{content:e.jsx(Yp,{})})]})})}),tableTitle:"פירוט לפי אמצעי תשלום",columns:p,rows:l,unit:"אמצעים",totals:{label:"סה״כ",count:hn(r.count),gross:_t(r.gross),fee:r.hasFees?_t(r.fee):"—",net:_t(r.net),share:l.length?"100.0%":"—"},excelTotals:{count:r.count,gross:r.gross,...r.hasFees?{fee:r.fee}:{},net:r.net,share:l.length?100:void 0},footNote:"נספרים תשלומים שנפרעו בלבד. עמלות סליקה אינן נשמרות היום על התשלום, ולכן העמודה ריקה ולא אפס."})}const bn=t=>ve(t),Hs=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),Gp=t=>{const[s,n,a]=String(t||"").slice(0,10).split("-");return a?`${a}/${n}/${s}`:"—"},El=t=>t>
5490?"#e11d48":t>30?"#f59e0b":"#94a3b8";function Xp({active:t,payload:s,label:n}){var l;if(!t||!(s!=null&&s.length))return null;const a=(l=s[0])==null?void 0:l.payload;return e.jsxs("div",{dir:"rtl",className:"rounded-xl border border-slate-200 bg-white shadow-lg px-3 py-2",children:[e.jsx("p",{className:"text-[12px] font-black text-slate-800",children:Ze(n)}),e.jsx("p",{className:"text-[12px] text-slate-600 mt-1 tabular-nums",dir:"ltr",children:bn(a==null?void 0:a.amount)}),e.jsxs("p",{className:"text-[11.5px] text-slate-400",children:[Hs(a==null?void 0:a.count)," חיובים באיחור"]})]})}function Zp({kibbutzId:t,scope:s}){const[n,a]=i.useState({loading:!0,charges:[],accounts:[],types:[],statements:[],payments:[]});i.useEffect(()=>{let b=!0;return a(f=>({...f,loading:!0})),Promise.all([D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.PayerAccount.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.MonthlyStatement.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[])]).then(([f,x,g,y,$])=>{b&&a({loading:!1,charges:f||[],accounts:x||[],types:g||[],statements:y||[],payments:$||[]})}).catch(()=>{b&&a(f=>({...f,loading:!1}))}),()=>{b=!1}},[t]);const l=i.useMemo(()=>zt(n.charges,n.types,{ready:!n.loading}),[n.charges,n.types,n.loading]),r=i.useMemo(()=>xa({statements:n.statements,payments:n.payments,charges:l}),[n.statements,n.payments,l]),o=i.useMemo(()=>Yx({charges:l.filter(b=>Jn(b.due_date,s)),accounts:n.accounts,types:n.types,isPaid:r.isPaid}),[l,n.accounts,n.types,r,s]),p=i.useMemo(()=>Vx(o),[o]),u=i.useMemo(()=>el(s),[s]),d=i.useMemo(()=>Gx(o,u),[o,u]),c=Cs(s),m=i.useMemo(()=>new Set(o.map(b=>b.payer)).size,[o]),h=[{key:"payer",label:"חשבון משלם",width:24,render:b=>e.jsxs("span",{className:"min-w-0 block",children:[e.jsx("span",{className:"block font-medium text-slate-800 truncate",children:b.payer}),b.account&&e.jsxs("span",{className:"block text-[11.5px] text-slate-400 tabular-nums",dir:"ltr",children:["#",b.account]})]}),excel:b=>b.payer},{key:"type",label:"סוג חיוב",render:b=>e.jsx("span",{className:"text-slate-600",children:b.type})},{key:"dueDate",label:"מועד תשלום",type:"date",render:b=>e.jsx("span",{className:"tabular-nums",dir:"ltr",children:Gp(b.dueDate)})},{key:"days",label:"ימי איחור",type:"num",render:b=>e.jsx("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[12.5px] font-bold tabular-nums",style:{color:El(b.days),background:`${El(b.days)}14`},children:Hs(b.days)})},{key:"balance",label:"יתרה לתשלום",type:"money",render:b=>e.jsx("span",{className:"font-medium text-slate-800",children:bn(b.balance)})}];return e.jsx(Ms,{title:"דוח חשבונות באיחור",period:c,subtitle:"חיובים שמועד התשלום שלהם עבר וטרם נפרעו",icon:ws,tone:"rose",loading:n.loading,fileName:`דוח_חשבונות_באיחור_${c}`,empty:"אין חיובים באיחור בתקופה שנבחרה.",stats:[{label:"יתרה באיחור",value:bn(p.balance),tone:"rose"},{label:"חשבונות באיחור",value:Hs(m),tone:"amber",sub:`${Hs(p.count)} חיובים`},{label:"ממוצע ימי איחור",value:Hs(p.avgDays),tone:"slate",sub:"משוקלל לפי סכום"}],chart:e.jsx(As,{title:"יתרה באיחור לפי חודש החיוב",legend:[e.jsx(qe,{color:"#94a3b8",children:"עד 30 יום"},"a"),e.jsx(qe,{color:"#f59e0b",children:"31–90 יום"},"b"),e.jsx(qe,{color:"#e11d48",children:"מעל 90 יום"},"c")],height:"20rem",note:o.length?"הצבע נקבע לפי ותק האיחור של החיובים באותו חודש.":"אין חיובים באיחור בתקופה שנבחרה.",children:e.jsx(Rt,{width:"100%",height:"100%",children:e.jsxs(Ba,{data:d,margin:{top:24,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(Qt,{dataKey:"month",tickFormatter:Ze,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#e2e8f0"},reversed:!0}),e.jsx(Ct,{tick:{fontSize:11,fill:"#64748b"}
54,tickLine:!1,axisLine:!1,orientation:"right",width:70,tickFormatter:b=>new Intl.NumberFormat("he-IL").format(b)}),e.jsx(ht,{content:e.jsx(Xp,{}),cursor:{fill:"#f1f5f9"}}),e.jsxs(pt,{dataKey:"amount",radius:[6,6,0,0],maxBarSize:54,children:[d.map(b=>{const f=o.filter(g=>g.month===b.month),x=f.length?Math.max(...f.map(g=>g.days)):0;return e.jsx(_s,{fill:El(x)},b.month)}),e.jsx(Ta,{dataKey:"amount",position:"top",offset:8,formatter:b=>Number(b)>0?new Intl.NumberFormat("he-IL").format(b):"",style:{fontSize:11,fontWeight:700,fill:"#334155"}})]})]})})}),tableTitle:"פירוט החיובים באיחור",columns:h,rows:o,unit:"חיובים",totals:{payer:"סה״כ",days:p.avgDays?`${Hs(p.avgDays)} בממוצע`:"",balance:bn(p.balance)},excelTotals:{days:p.avgDays,balance:p.balance},footNote:"חיוב נחשב פרוע כשמסמך החשבון שלו סומן כשולם או שתשלומי התקופה מכסים את חיוביה — אותו כלל בדיוק שדוח החיובים פועל לפיו."})}const Ye=t=>ve(t),nn=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),Ei=["#0f766e","#14b8a6","#6ee7b7","#7dd3fc","#38bdf8","#a78bfa","#f9a8d4","#fbbf24","#cbd5e1"],Qp=t=>Ei[t%Ei.length];function Jp({active:t,payload:s}){var a;if(!t||!(s!=null&&s.length))return null;const n=(a=s[0])==null?void 0:a.payload;return n?e.jsxs("div",{dir:"rtl",className:"rounded-xl border border-slate-200 bg-white shadow-lg px-3 py-2",children:[e.jsxs("p",{className:"text-[12px] font-black text-slate-800 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{background:n.color}}),n.name]}),e.jsx("p",{className:"text-[12px] text-slate-600 mt-1 tabular-nums",dir:"ltr",children:Ye(n.billed)}),e.jsxs("p",{className:"text-[11.5px] text-slate-400",children:["נגבה ",Ye(n.collected)]})]}):null}function eh({kibbutzId:t,scope:s}){const[n,a]=i.useState({loading:!0,charges:[],types:[],statements:[],payments:[]}),[l,r]=i.useState({});i.useEffect(()=>{let x=!0;return a(g=>({...g,loading:!0})),Promise.all([D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.MonthlyStatement.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[])]).then(([g,y,$,O])=>{x&&a({loading:!1,charges:g||[],types:(y||[]).filter(A=>A.is_active!==!1),statements:$||[],payments:O||[]})}).catch(()=>{x&&a(g=>({...g,loading:!1}))}),D.functions.invoke("listSumitBudgetItems",{community_id:t}).then(g=>{var $;if(!x)return;const y=(($=g==null?void 0:g.data)==null?void 0:$.budgetItems)||[];r(Object.fromEntries(y.map(O=>[String(O.id),O.name])))}).catch(()=>{x&&r({})}),()=>{x=!1}},[t]);const o=i.useMemo(()=>zt(n.charges,n.types,{ready:!n.loading}),[n.charges,n.types,n.loading]),p=i.useMemo(()=>xa({statements:n.statements,payments:n.payments,charges:o}),[n.statements,n.payments,o]),u=i.useMemo(()=>Xx({charges:o,types:n.types,paidOf:p.paidOf,inRange:x=>Jn(x,s),names:l}).map((x,g)=>({...x,color:Qp(g)})),[o,n.types,p,s,l]),d=i.useMemo(()=>n.types.some(x=>Jl(x)),[n.types]),c=i.useMemo(()=>Zx(u),[u]),m=Cs(s),h=i.useMemo(()=>u.filter(x=>x.billed>0),[u]),b=[{key:"name",label:"סעיף תקציב",width:24,render:x=>e.jsxs("span",{className:"inline-flex items-center gap-2 font-medium text-slate-800 min-w-0",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full flex-none",style:{background:x.color}}),e.jsx("span",{className:"truncate",children:x.name})]}),excel:x=>x.name},{key:"count",label:"מספר חיובים",type:"num",render:x=>nn(x.count)}
54,{key:"budget",label:"מתוקצב",type:"money",render:x=>x.budget==null?e.jsx("span",{className:"text-slate-300",children:"—"}):Ye(x.budget),excel:x=>x.budget==null?void 0:x.budget},{key:"billed",label:"סכום חיוב",type:"money",render:x=>Ye(x.billed)},{key:"collected",label:"נגבה",type:"money",render:x=>e.jsx("span",{className:"text-emerald-700 font-medium",children:Ye(x.collected)})},{key:"balance",label:"יתרה",type:"money",render:x=>Ye(x.balance)},{key:"done",label:"אחוז ביצוע",type:"pct",render:x=>{const g=wl(x);return e.jsxs("span",{className:"inline-flex items-center gap-2 min-w-[7rem]",children:[e.jsx("span",{className:"flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("span",{className:"block h-full rounded-full",style:{width:`${Math.min(100,g)}%`,background:x.color}})}),e.jsxs("span",{className:"tabular-nums font-medium text-slate-700 text-[12.5px] w-12 text-left",dir:"ltr",children:[g.toFixed(1),"%"]})]})},excel:x=>wl(x),sort:x=>wl(x)}],f=c.billed>0?c.collected/c.billed*100:0;return e.jsx(Ms,{title:"דוח סעיפי תקציב",period:m,subtitle:"החיוב והגבייה בפועל, לפי הסעיף שהכסף נזקף אליו",icon:xr,loading:n.loading,fileName:`דוח_סעיפי_תקציב_${m}`,stats:[{label:"סעיפים פעילים",value:nn(c.lines),tone:"teal",sub:`${nn(c.count)} חיובים`},{label:"סכום חיוב",value:Ye(c.billed),tone:"sky"},{label:"נגבה בפועל",value:Ye(c.collected),tone:"amber",sub:`${f.toFixed(1)}% ביצוע`}],chart:e.jsx(As,{title:"חלוקת החיוב בין הסעיפים",legend:h.map(x=>e.jsxs(qe,{color:x.color,children:[x.name," · ",e.jsxs("b",{className:"tabular-nums",children:[c.billed>0?(x.billed/c.billed*100).toFixed(1):"0.0","%"]})]},x.key)),height:"20rem",center:h.length?{label:"סכום חיוב",value:Ye(c.billed)}:null,note:h.length?null:"לא חויב דבר בתקופה שנבחרה.",children:e.jsx(Rt,{width:"100%",height:"100%",children:e.jsxs(Yn,{children:[e.jsx(Vn,{data:h,dataKey:"billed",nameKey:"name",innerRadius:"58%",outerRadius:"86%",paddingAngle:h.length>1?2:0,stroke:"#fff",strokeWidth:2,children:h.map(x=>e.jsx(_s,{fill:x.color},x.key))}),e.jsx(ht,{content:e.jsx(Jp,{})})]})})}),tableTitle:"פירוט לפי סעיף תקציב",columns:b,rows:u,unit:"סעיפים",totals:{name:"סה״כ",count:nn(c.count),budget:c.budget==null?"—":Ye(c.budget),billed:Ye(c.billed),collected:Ye(c.collected),balance:Ye(c.balance),done:`${f.toFixed(1)}%`},excelTotals:{count:c.count,...c.budget==null?{}:{budget:c.budget},billed:c.billed,collected:c.collected,balance:c.balance,done:Number(f.toFixed(1))},footNote:d?"הסעיפים מוגדרים בממשק סאמיט ונשלפים משם. סוג חיוב שלא שויך לסעיף מוצג בשמו. סכום מתוקצב אינו נשמר היום ולכן מוצג במקף.":"לסוגי החיוב של הקהילה טרם שויכו סעיפי תקציב מסאמיט, ולכן הפילוח כאן הוא לפי סוג החיוב. השיוך נעשה בטופס סוג החיוב."})}const dt=t=>ve(t),th={emerald:"bg-emerald-50 text-emerald-700 border-emerald-200",rose:"bg-rose-50 text-rose-700 border-rose-200",slate:"bg-slate-100 text-slate-400 border-slate-200"};function sh({active:t,payload:s,label:n}){var l;if(!t||!(s!=null&&s.length))return null;const a=(l=s[0])==null?void 0:l.payload;return a?e.jsxs("div",{dir:"rtl",className:"rounded-xl border border-slate-200 bg-white shadow-lg px-3 py-2 min-w-[11rem]",children:[e.jsx("p",{className:"text-[12px] font-black text-slate-800 mb-1",children:Ze(n)}),e.jsxs("p",{className:"flex items-center gap-2 text-[11.5px]",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm",style:{background:"#cbd5e1"}}),e.jsx("span",{className:"text-slate-600",children:"חויב"}),e.jsx("span",{className:"mr-auto font-bold tabular-nums text-slate-800",dir:"ltr",children:dt(a.billed)})]}),e.jsxs("p",{className:"flex items-center gap-2 text-[11.5px]",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm",style:{background:"#0d9488"}}),e.jsx("span",{className:"text-slate-600",children:"נגבה"}),e.jsx("span",{className:"mr-auto font-bold tabular-nums text-slate-800",dir:"ltr",children:dt(a.collected)})]}),e.jsxs("p",{className:"mt-1.5 pt-1.5 border-t border-slate-100 flex items-center gap-2 text-[12px]",children:[e.jsx("span",{className:"font-bold text-slate-500",children:"אחוז גבייה"}),e.jsx("span",{className:"mr-auto font-black tabular-nums text-slate-900",dir:"ltr",children:a.billed>0?`${Number(a.rate||0).toFixed(1)}%`:"—"})]})]}):null}function ah({kibbutzId:t,settings:s,scope:n}){const[a,l]=i.useState({loading:!0,charges:[],types:[],statements:[],payments:[]});i.useEffect(()=>{let g=!0;return l(y=>({...y,loading:!0})),Promise.all([D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.MonthlyStatement.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[])]).then(([y,$,O,A])=>{g&&l({loading:!1,charges:y||[],types:$||[],statements:O||[],payments:A||[]})}).catch(()=>{g&&l(y=>({...y,loading:!1}))}),()=>{g=!1}},[t]);const r=i.useMemo(()=>zt(a.charges,a.types,{ready:!a.loading}),[a.charges,a.types,a.loading]),o=i.useMemo(()=>xa({statements:a.statements,payments:a.payments,charges:r}),[a.statements,a.payments,r]),p=i.useMemo(()=>el(n),[n]),u=i.useMemo(()=>Qx({charges:r,months:p,paidOf:o.paidOf}),[r,p,o]),d=i.useMemo(()=>Jx(u),[u]),c=Cs(n),m=Number(s==null?void 0:s.collection_target)>0?Number(s.collection_target):fc,h=i.useMemo(()=>u.map(g=>({...g,rate:g.billed>0?g.rate:null})),[u]),b=i.useMemo(()=>[...u].reverse().map(g=>({...g,key:g.month})),[u]),f=kl(d.rate,m),x=[{key:"month",label:"חודש",width:14,render:g=>e.jsx("span",{className:"font-medium text-slate-800 tabular-nums",dir:"ltr",children:Ze(g.month)}),excel:g=>Ze(g.month),sort:g=>g.month},{key:"billed",label:"סכום חיוב",type:"money",render:g=>dt(g.billed)},{key:"collected",label:"נגבה",type:"money",render:g=>e.jsx("span",{className:"text-emerald-700 font-medium",children:dt(g.collected)})},{key:"balance",label:"יתרה",type:"money",render:g=>dt(g.balance)},{key:"rate",label:"אחוז גבייה",type:"pct",render:g=>g.billed>0?e.jsxs("span",{className:"inline-flex items-center gap-2 min-w-[7rem]",children:[e.jsx("span",{className:"flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("span",{className:"block h-full rounded-full",style:{width:`${Math.min(100,g.rate)}%`,background:g.rate>=m-2?"#0d9488":"#e11d48"}})}),e.jsxs("span",{className:"tabular-nums font-medium text-slate-700 text-[12.5px] w-12 text-left",dir:"ltr",children:[g.rate.toFixed(1),"%"]})]}):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:g=>g.billed>0?g.rate:void 0},{key:"target",label:`מול היעד (${m}%)`,render:g=>{const y=kl(g.rate,m);return e.jsx("span",{className:`inline-block px-2.5 py-1 rounded-lg border text-[12px] font-bold ${th[y.tone]}`,children:y.l})},excel:g=>kl(g.rate,m).l,sort:g=>g.billed>0?g.rate:null}];return e.jsx(Ms,{title:"דוח אחוזי גבייה",period:c,subtitle:"הגבייה בפועל מול החיוב, חודש בחודש, מול יעד הקהילה",icon:ks,loading:a.loading,fileName:`דוח_אחוזי_גבייה_${c}`,empty:"לא חויב דבר בתקופה שנבחרה.",stats:[{label:"סכום חיוב",value:dt(d.billed),tone:"sky"},{label:"נגבה בפועל",value:dt(d.collected),tone:"teal",sub:`יתרה ${dt(d.balance)}`},{label:"אחוז גבייה",value:`${d.rate.toFixed(1)}
54%`,tone:f.tone==="rose"?"rose":"amber",sub:`${f.l} · יעד ${m}%`}],chart:e.jsx(As,{title:"חיוב מול גבייה",legend:[e.jsx(qe,{color:"#cbd5e1",children:"חויב"},"b"),e.jsx(qe,{color:"#0d9488",children:"נגבה"},"c"),e.jsx(qe,{color:"#f59e0b",children:"אחוז גבייה"},"r")],height:"20rem",note:`הקו המקווקו הוא יעד הגבייה של הקהילה — ${m}%.`,children:e.jsx(Rt,{width:"100%",height:"100%",children:e.jsxs(zo,{data:h,margin:{top:24,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(Qt,{dataKey:"month",tickFormatter:Ze,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#e2e8f0"},reversed:!0}),e.jsx(Ct,{yAxisId:"money",orientation:"right",width:70,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:!1,tickFormatter:g=>new Intl.NumberFormat("he-IL").format(g)}),e.jsx(Ct,{yAxisId:"rate",orientation:"left",width:44,domain:[0,100],tick:{fontSize:11,fill:"#94a3b8"},tickLine:!1,axisLine:!1,tickFormatter:g=>`${g}%`}),e.jsx(ht,{content:e.jsx(sh,{}),cursor:{fill:"#f1f5f9"}}),e.jsx(Mo,{yAxisId:"rate",y:m,stroke:"#f59e0b",strokeDasharray:"5 4",strokeWidth:1.5}),e.jsx(pt,{yAxisId:"money",dataKey:"billed",name:"חויב",fill:"#cbd5e1",radius:[6,6,0,0],maxBarSize:38}),e.jsx(pt,{yAxisId:"money",dataKey:"collected",name:"נגבה",fill:"#0d9488",radius:[6,6,0,0],maxBarSize:38}),e.jsx(yr,{yAxisId:"rate",type:"linear",dataKey:"rate",name:"אחוז גבייה",connectNulls:!1,stroke:"#f59e0b",strokeWidth:2.5,dot:{r:3,fill:"#f59e0b"}})]})})}),tableTitle:"פירוט חודשי",columns:x,rows:b,unit:"חודשים",perPage:12,totals:{month:"סה״כ",billed:dt(d.billed),collected:dt(d.collected),balance:dt(d.balance),rate:`${d.rate.toFixed(1)}%`,target:f.l},excelTotals:{billed:d.billed,collected:d.collected,balance:d.balance,rate:d.rate},footNote:"החודש נקבע לפי מועד החיוב: תשלום שהגיע בספטמבר על חיוב של אוגוסט נזקף לאוגוסט."})}const Dt=t=>ve(t),Ot=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),_c=t=>{const[s,n,a]=String(t||"").slice(0,10).split("-");return a?`${a}/${n}/${s}`:"—"},Fi=t=>{const[s,n]=String(t||"").split("-"),a=nr[Number(n)-1];return a?`${a} ${String(s).slice(2)}`:String(t||"")};function nh({active:t,payload:s,label:n}){var l;if(!t||!(s!=null&&s.length))return null;const a=(l=s[0])==null?void 0:l.payload;return a?e.jsxs("div",{dir:"rtl",className:"rounded-xl border border-slate-200 bg-white shadow-lg px-3 py-2 min-w-[11rem]",children:[e.jsx("p",{className:"text-[12px] font-black text-slate-800 mb-1",children:Ze(n)}),e.jsx("p",{className:"text-[12px] text-slate-600 tabular-nums",dir:"ltr",children:Dt(a.billed)}),e.jsxs("p",{className:"text-[11.5px] text-slate-400",children:[Ot(a.count)," חיובים"]}),a.mainDate&&e.jsxs("p",{className:"text-[11.5px] text-slate-400",children:["מועד מרכזי ",_c(a.mainDate)]})]}):null}function lh({kibbutzId:t,scope:s}){const[n,a]=i.useState({loading:!0,charges:[],types:[],statements:[],payments:[]});i.useEffect(()=>{let b=!0;return a(f=>({...f,loading:!0})),Promise.all([D.entities.Charge.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").catch(()=>[]),D.entities.MonthlyStatement.filterAll({kibbutz_id:t}).catch(()=>[]),D.entities.Payment.filterAll({kibbutz_id:t}).catch(()=>[])]).then(([f,x,g,y])=>{b&&a({loading:!1,charges:f||[],types:x||[],statements:g||[],payments:y||[]})}).catch(()=>{b&&a(f=>({...f,loading:!1}))}),()=>{b=!1}},[t]);const l=i.useMemo(()=>zt(n.charges,n.types,{ready:!n.loading}),[n.charges,n.types,n.loading]),r=i.useMemo(()=>xa({statements:n.statements,payments:n.payments,charges:l}),[n.statements,n.payments,l]),o=i.useMemo(()=>el(s),[s]),p=i.useMemo(()=>{const b=new Map((n.types||[]).map(f=>[f.id,f.name]));return f=>b.get(f.charge_type_id)||""},[n.types]),u=i.useMemo(()=>ep({charges:l,months:o,paidOf:r.paidOf,typeOf:p}),[l,o,r,p]),d=i.useMemo(()=>tp(u,o),[u,o]),c=Cs(s),m=i.useMemo(()=>[...u].filter(b=>b.count>0).reverse().map(b=>({...b,key:b.month})),[u]),h=[{key:"month",label:"חודש",width:14,render:b=>e.jsx("span",{className:"font-medium text-slate-800",children:Fi(b.month)}),excel:b=>Fi(b.month),sort:b=>b.month},{key:"count",label:"מספר חיובים",type:"num",render:b=>Ot(b.count)},{key:"types",label:"סוגי חיובים",width:24,render:b=>b.types.length?e.jsxs("span",{className:"inline-flex items-center gap-1.5 flex-nowrap",children:[b.types.slice(0,2).map(f=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-lg bg-slate-50 border border-slate-100 text-[12px] font-medium text-slate-600 whitespace-nowrap",children:[f.name,e.jsx("span",{className:"text-slate-400 tabular-nums",children:Ot(f.count)})]},f.name)),b.types.length>2&&e.jsxs("span",{className:"text-[11.5px] font-medium text-slate-400 whitespace-nowrap",title:b.types.slice(2).map(f=>f.name).join(", "),children:["+",Ot(b.types.length-2)]})]}):e.jsx("span",{className:"text-slate-300",children:"—"}),excel:b=>b.types.map(f=>`${f.name} (${f.count})`).join(", "),sort:b=>b.types.length},{key:"billed",label:"סכום לחיוב",type:"money",render:b=>Dt(b.billed)},{key:"collected",label:"שולם",type:"money",render:b=>e.jsx("span",{className:"text-emerald-700 font-medium",children:Dt(b.collected)})},{key:"balance",label:"יתרה",type:"money",render:b=>Dt(b.balance)},{key:"rate",label:"אחוז גבייה",type:"pct",render:b=>e.jsxs("span",{className:"inline-flex items-center gap-2 min-w-[7rem]",children:[e.jsx("span",{className:"flex-1 h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("span",{className:"block h-full rounded-full bg-teal-600",
54style:{width:`${Math.min(100,b.rate)}%`}})}),e.jsxs("span",{className:"tabular-nums font-medium text-slate-700 text-[12.5px] w-12 text-left",dir:"ltr",children:[b.rate.toFixed(0),"%"]})]}),excel:b=>b.rate},{key:"mainDate",label:"מועד מרכזי",type:"date",render:b=>e.jsxs("span",{className:"inline-block",children:[e.jsx("span",{className:"block font-medium text-slate-700 tabular-nums",dir:"ltr",children:_c(b.mainDate)}),b.dates>1&&e.jsxs("span",{className:"block text-[11px] text-slate-400",children:[Ot(b.dates)," מועדים בחודש"]})]}),excel:b=>b.mainDate}];return e.jsx(Ms,{title:"דוח מועדי חיוב",period:c,subtitle:"ריכוז חיובים לפי מועד החיוב לאורך השנה",icon:Be,loading:n.loading,fileName:`דוח_מועדי_חיוב_${c}`,empty:"לא נקבעו מועדי חיוב בתקופה שנבחרה.",stats:[{label:"סה״כ חיובים",value:Ot(d.count),tone:"teal",sub:d.months?`ב-${Ot(d.months)} חודשים`:null},{label:"סכום לחיוב",value:Dt(d.billed),tone:"sky"},{label:"ממוצע חודשי",value:Dt(d.avg),tone:"amber",sub:`על פני ${Ot(o.length)} חודשים`}],chart:e.jsx(As,{title:"סכום לחיוב לפי חודש (₪)",legend:[e.jsx(qe,{color:"#2dd4a7",children:"סכום לחיוב"},"b")],height:"20rem",note:d.count?"חודש בלי חיובים נשאר על הציר — היעלמותו מסתירה שלא חויב בו דבר.":"לא נקבעו מועדי חיוב בתקופה שנבחרה.",children:e.jsx(Rt,{width:"100%",height:"100%",children:e.jsxs(Ba,{data:u,margin:{top:26,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(Qt,{dataKey:"month",tickFormatter:Ze,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#e2e8f0"},reversed:!0}),e.jsx(Ct,{tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:!1,orientation:"right",width:70,tickFormatter:b=>new Intl.NumberFormat("he-IL").format(b)}),e.jsx(ht,{content:e.jsx(nh,{}),cursor:{fill:"#f1f5f9"}}),e.jsx(pt,{dataKey:"billed",fill:"#2dd4a7",radius:[6,6,0,0],maxBarSize:54,children:e.jsx(Ta,{dataKey:"billed",position:"top",offset:8,formatter:b=>new Intl.NumberFormat("he-IL").format(Math.round(Number(b)||0)),style:{fontSize:11,fontWeight:700,fill:"#334155"}})})]})})}),tableTitle:"פירוט לפי מועדי חיוב",columns:h,rows:m,unit:"חודשים",perPage:12,totals:{month:"סה״כ",count:Ot(d.count),types:"",billed:Dt(d.billed),collected:Dt(d.collected),balance:Dt(d.balance),rate:`${d.rate.toFixed(0)}%`,mainDate:"—"},excelTotals:{count:d.count,billed:d.billed,collected:d.collected,balance:d.balance,rate:d.rate},footNote:"החודש נקבע לפי מועד החיוב. «מועד מרכזי» הוא היום שרוב הכסף של אותו חודש נופל עליו — לא הראשון ולא הממוצע."})}function ln({label:t,value:s,onClick:n,open:a}){return e.jsxs("button",{type:"button",onClick:n,"aria-expanded":a,className:`w-full h-11 pr-3 pl-2 rounded-xl border bg-white text-right inline-flex items-center gap-1.5 min-w-0 transition-colors ${a?"border-teal-400 ring-4 ring-teal-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[10px] font-bold text-slate-400 leading-none",children:t}),e.jsx("span",{className:"block text-[13px] font-black text-slate-800 truncate leading-tight mt-0.5",children:s})]}),e.jsx(Jt,{className:`w-3.5 h-3.5 text-slate-400 flex-none transition-transform ${a?"rotate-180":""}`})]})}function rn({open:t,onClose:s,children:n,width:a="w-full"}){return t?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":"סגירה",onClick:s,className:"fixed inset-0 z-[40] cursor-default"}),e.jsx("div",{className:`absolute z-[41] mt-1 ${a} min-w-[9rem] rounded-xl border border-slate-200 bg-white shadow-xl overflow-hidden`,children:n})]}):null}function rh(t=12){const[s,n]=i.useState(t);return i.useEffect(()=>{const a=()=>{const o=document.querySelector('header.sticky, header[class*="sticky"]'),p=o?Math.round(o.getBoundingClientRect().height):0;n(p+t)};a(),window.addEventListener("resize",a);const l=typeof ResizeObserver<"u"?new ResizeObserver(a):null,r=document.querySelector('header.sticky, header[class*="sticky"]');return l&&r&&l.observe(r),()=>{window.removeEventListener("resize",a),l==null||l.disconnect()}},[t]),s}const on=({on:t,children:s,onClick:n})=>e.jsxs("button",{type:"button",onClick:n,className:`w-full text-right px-3.5 py-2.5 text-[13.5px] font-bold flex items-center gap-2 border-b border-slate-50 last:border-0 ${t?"bg-teal-50/70 text-teal-800":"text-slate-700 hover:bg-slate-50"}`,children:[t?e.jsx(ye,{className:"w-4 h-4 flex-none",strokeWidth:3}):e.jsx("span",{className:"w-4 flex-none"}),s]}),ja=[{key:"dates",label:"מועדי חיוב",icon:Be,hint:"מתי נגבה, ומה עוד לפנינו",tone:"teal",Comp:lh},{key:"budget",label:"סעיפי תקציב",icon:xr,hint:"לאיזה סעיף נזקף הכסף",tone:"violet",Comp:eh},{key:"collection",label:"אחוזי גבייה",icon:ks,hint:"כמה מהחיוב נפרע בפועל",tone:"emerald",Comp:ah},{key:"late",label:"חשבונות באיחור",icon:ws,hint:"מי חייב, וכמה זמן",tone:"rose",Comp:Zp},{key:"methods",label:"אמצעי תשלום",icon:Oe,hint:"במה משלמים",tone:"sky",Comp:Vp},{key:"sources",label:"מקורות חיוב",icon:Kn,hint:"מאיזה מודול הגיע",tone:"amber",Comp:Hp}],Di={teal:"bg-teal-50 text-teal-600",violet:"bg-violet-50 text-violet-600",emerald:"bg-emerald-50 text-emerald-600",rose:"bg-rose-50 text-rose-500",sky:"bg-sky-50 text-sky-600",amber:"bg-amber-50 text-amber-600"};function ih({kibbutzId:t,settings:s}){const n=rh(),[a,l]=i.useState(()=>{var x;return((x=ja.find(g=>g.Comp))==null?void 0:x.key)||ja[0].key}),[r,o]=i.useState(()=>Dp()),[p,u]=i.useState(""),d=()=>u(""),c=x=>{o(g=>({...g,...x})),d()},m=i.useMemo(()=>{const x=new Date().getFullYear();return[x+1,x,x-1,x-2,x-3,x-4]},[]),h=Al.find(x=>x.v===r.mode)||Al[2],b=ja.find(x=>x.key===a)||ja[0],f=b.Comp;return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1fr,17rem] gap-4 items-start",children:[e.jsx("div",{className:"min-w-0 order-2 lg:order-1",children:f?e.jsx(f,{kibbutzId:t,settings:s,scope:r},b.key):null}),e.jsx("aside",{className:"no-print order-1 lg:order-2 lg:sticky lg:self-start",style:{to
54p:`${n}px`,maxHeight:`calc(100vh - ${n+16}px)`},children:e.jsxs("div",{className:"space-y-3 lg:overflow-y-auto lg:max-h-full lg:pl-0.5",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-gradient-to-b from-teal-50/70 to-white shadow-sm p-4",children:[e.jsx("h3",{className:"text-[19px] font-black text-slate-900 leading-tight",children:"דוחות, הכל בשליטה"}),e.jsx("p",{className:"text-[12px] text-slate-500 mt-1",children:"ריכוזים לפי חתך, על תקופה אחת"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("span",{className:"relative block",children:[e.jsx(ln,{label:"תקופה",value:h.l,open:p==="mode",onClick:()=>u(x=>x==="mode"?"":"mode")}),e.jsx(rn,{open:p==="mode",onClose:d,width:"w-52",children:Al.map(x=>e.jsx(on,{on:x.v===r.mode,onClick:()=>c({mode:x.v}),children:e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block",children:x.l}),e.jsx("span",{className:"block text-[11px] font-normal text-slate-400",children:x.hint})]})},x.v))})]}),e.jsxs("span",{className:"relative block",children:[e.jsx(ln,{label:"שנה",value:String(r.year),open:p==="year",onClick:()=>u(x=>x==="year"?"":"year")}),e.jsx(rn,{open:p==="year",onClose:d,children:e.jsx("div",{className:"max-h-64 overflow-y-auto",children:m.map(x=>e.jsx(on,{on:x===r.year,onClick:()=>c({year:x}),children:x},x))})})]})]}),r.mode==="month"&&e.jsxs("span",{className:"relative block",children:[e.jsx(ln,{label:"חודש",value:nr[r.month]||"",open:p==="month",onClick:()=>u(x=>x==="month"?"":"month")}),e.jsx(rn,{open:p==="month",onClose:d,children:e.jsx("div",{className:"max-h-64 overflow-y-auto",children:nr.map((x,g)=>e.jsx(on,{on:g===r.month,onClick:()=>c({month:g}),children:x},x))})})]}),r.mode==="quarter"&&e.jsxs("span",{className:"relative block",children:[e.jsx(ln,{label:"רבעון",value:(hs.find(x=>x.v===r.quarter)||hs[0]).l,open:p==="quarter",onClick:()=>u(x=>x==="quarter"?"":"quarter")}),e.jsx(rn,{open:p==="quarter",onClose:d,children:hs.map(x=>e.jsx(on,{on:x.v===r.quarter,onClick:()=>c({quarter:x.v}),children:x.l},x.v))})]}),r.mode==="range"&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:[["from","מתאריך"],["to","עד תאריך"]].map(([x,g])=>e.jsxs("label",{className:"h-11 px-3 rounded-xl border border-slate-200 bg-white flex flex-col justify-center min-w-0",children:[e.jsx("span",{className:"text-[10px] font-bold text-slate-400 leading-none",children:g}),e.jsx("input",{type:"date",value:r[x]||"",onChange:y=>o($=>({...$,[x]:y.target.value})),className:"text-[12.5px] font-bold text-slate-800 bg-transparent focus:outline-none tabular-nums min-w-0"})]},x))})]}),e.jsxs("p",{className:"mt-2.5 text-[12px] text-slate-500 flex items-center gap-1.5",children:[e.jsx(vs,{className:"w-3.5 h-3.5 text-slate-400 flex-none"}),"מוצג עבור ",e.jsx("b",{className:"text-slate-700",children:Cs(r)})]})]}),e.jsx("nav",{className:"rounded-2xl border border-slate-200 bg-white shadow-sm p-2 space-y-1","aria-label":"דוחות תנועות",children:ja.map(x=>{const g=x.icon,y=x.key===a,$=!!x.Comp;return e.jsxs("button",{type:"button",disabled:!$,onClick:()=>$&&l(x.key),"aria-current":y?"page":void 0,title:$?x.hint:"בהכנה",className:`w-full text-right rounded-xl px-3 py-2.5 flex items-center gap-2.5 transition-colors ${y?"bg-teal-600 text-white shadow-sm":$?"text-slate-700 hover:bg-slate-50":"text-slate-300 cursor-not-allowed"}`,children:[e.jsx("span",{className:`w-8 h-8 rounded-lg grid place-items-center flex-none ${y?"bg-white/20 text-white":$?Di[x.tone]||Di.teal:"bg-slate-50 text-slate-300"}`,children:$?e.jsx(g,{className:"w-4 h-4"}):e.jsx(io,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[14px] font-bold truncate",children:x.label}),e.jsx("span",{className:`block text-[11px] truncate ${y?"text-white/70":"text-slate-400"}`,children:$?x.hint:"בהכנה"})]})]},x.key)})})]})})]})}const jc=[{v:"billed",l:"סכום חיוב",unit:"money",hint:"כמה חויב"},{v:"collected",l:"סכום ששולם",unit:"money",hint:"כמה נגבה בפועל"},{v:"balance",l:"יתרה פתוחה",unit:"money",hint:"כמה עוד לא שולם"},{v:"overdue",l:"חיובים באיחור",unit:"money",hint:"עבר המועד ולא שולם"},{v:"rate",l:"אחוז גבייה",unit:"percent",hint:"כמה מהחיוב נפרע"},{v:"payments",l:"תשלומים שנקלטו",unit:"money",hint:"כסף שנכנס בפועל"},{v:"credits",l:"זיכויים",unit:"money",hint:"כמה זוכה"},{v:"cancelled",l:"ביטולים",unit:"money",hint:"חיובים שבוטלו"},{v:"failed",l:"עסקאות שנכשלו",unit:"money",hint:"תשלומים שנדחו"}],lr=t=>jc.find(s=>s.v===t)||null,Nc=[{v:"month",l:"חודש"},{v:"method",l:"אמצעי תשלום"},{v:"budget",l:"סעיף תקציב"},{v:"type",l:"סוג חיוב"},{v:"status",l:"סטטוס"},{v:"source",l:"מקור חיוב"},{v:"account",l:"חשבון משלם"}],oh=t=>Nc.find(s=>s.v===t)||null,vc=[{v:"due",l:"מועד החיוב",hint:"התאריך שבו החיוב אמור להיגבות"},{v:"created",l:"מועד יצירת החיוב",hint:"התאריך שבו החיוב הופק"},{v:"paid",l:"מועד התשלום",hint:"התאריך שבו הכסף נכנס"}],ch=["credit","standing_order","bank_transfer","bit","cash","check","other"],dh=["draft","pending","approved","issued","cancelled","credited"],uh=["charge_type","payment_page","event","class","venue","quick_charge"],mh={charge_type:{l:"סוגי חיובים",state:"connected"},quick_charge:{l:"סליקה מהירה",state:"connected",note:"נרשמת כחיוב ותשלום, ונספרת תחת סוג החיוב שלה"},event:{l:"יומן אירועים",state:"connected",note:"הרשמה, סכום, סליקה וסעיף תקציבי"},payment_page:{l:"עמודי תשלום",state:"empty",note:"המודול קיים ונקרא, אך טרם חובר אליו ספק סליקה ואין בו תנועות"},class:{l:"חוגים וסדנאות",state:"unavailable",note:"להרשמה לחוג אין שדה סכום, ואינה יוצרת חיוב או תשלום"},venue:{l:"יומנים ותורים",state:"partial",note:"להזמנה יש מחיר וסימון תשלום ידני, אך היא אינה נסלקת ואינה יוצרת חיוב"}},xh={method:{l:"אמצעי תשלום",values:ch,labels:{credit:"כרטיס אשראי",standing_order:"הוראת קבע",bank_transfer:"העברה בנקאית",bit:"ביט",cash:"מזומן",check:"המחאה",other:"אחר"}},status:{l:"סטטוס החיוב",values:dh,labels:{draft:"טיוטה",pending:"ממתין לאישור",approved:"מאושר",issued:"הופק",cancelled:"בוטל",credited:"זוכה"}},source:{l:"מקור",values:uh,labels:Object.fromEntries(Object.entries(mh).map(([t,s])=>[t,s.l]))},charge_type_id:{l:"סוג חיוב",dynamic:!0}},ph=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"];function wc(t){const{from:s,to:n}=t||{};if(!s||!n)return"";const[a,l,r]=s.split("-"),[o,p,u]=n.split("-"),d=String(new Date(Date.UTC(Number(o),Number(p),0)).getUTCDate()).padStart(2,"0");return a===o&&l===p&&r==="01"&&u===d?`${ph[Number(l)-1]} ${a}`:a===o&&l==="01"&&r==="01"&&p==="12"&&u==="31"?String(a):`${r}/${l}/${a} – ${u}/${p}/${o}`}function hh(t,{withPeriod:s=!0}={}){var p;const n=t||{},a=lr(n.metric),l=[(a==null?void 0:a.l)||"דוח"],r=(p=n.dimensions)!=null&&p[0]?oh(n.dimensions[0]):null;r&&l.push(`לפי ${r.l}`);const o=s?wc(n.dateRange):"";return o&&l.push(`— ${o}`),l.join(" ")}function bh(t,s={}){var r;const n=[],a=t||{},l=s.typeNames||{};for(const[o,p]of Object.entries(a.filters||{})){const u=xh[o];if(!u)continue;const d=c=>{var m;return u.dynamic?l[c]||c:((m=u.labels)==null?void 0:m[c])||c};n.push(`${u.l}: ${p.map(d).join(", ")}`)}return a.dateBasis&&n.push(`נחתך לפי ${(r=vc.find(o=>o.v===a.dateBasis))==null?void 0:r.l}`),a.comparison&&a.comparison!=="none"&&n.push(a.comparison==="previous_year"?"בהשוואה לשנה שעברה":"בהשוואה לתקופה הקודמת"),n}jc.map(t=>t.v),Nc.map(t=>t.v),vc.map(t=>t.v);const Ca=t=>ve(t),kc=t=>new Intl.NumberFormat("he-IL").format(Number(t)||0),cn=["#0f766e","#14b8a6","#6ee7b7","#7dd3fc","#38bdf8","#a78bfa","#f9a8d4","#fbbf24","#cbd5e1"],fh=["הצג חיובים לפי אמצעי תשלום בחודש ספטמבר","הצג חיובים לפי סעיפי תקציב השנה","הצג חשבונות באיחור","הצג אחוזי גבייה השנה לעומת שנה שעברה","הצג עסקאות אשראי שנכשלו"],Sc=(t,s)=>s==="money"?Ca(t):s==="percent"?`${Number(t||0).toFixed(1)}%`:s==="number"?kc(t):String(t??"—"),gh=t=>Sc(t.value,t.unit),yh=t=>{const s=[];return t.sub&&s.push(t.subValue===null||t.subValue===void 0?t.sub:`${t.sub} ${Sc(t.subValue,t.subUnit)}`),t.note&&s.push(t.note),s.join(" · ")||null},_h={money:rt,number:tu,percent:mr,text:Xe},Oi=(t,s)=>{const n=s[t.key];if(t.type==="money")return Ca(n);if(t.type==="num")return kc(n);if(t.type==="pct")return`${Number(n||0).toFixed(1)}%`;if(t.type==="month")return Ze(n);if(t.type==="date"){const[a,l,r]=String(n||"").slice(0,10).split("-");return r?`${r}/${l}/${a}`:"—"}return n??"—"};function jh({from:t,children:s}){const n=t==="user";return e.jsx("div",{className:`flex ${n?"justify-start":"justify-end"}`,children:e.jsx("div",{className:`max-w-[42rem] rounded-2xl px-4 py-3 text-[14px] leading-relaxed ${n?"bg-slate-100 text-slate-700":"bg-teal-600 text-white shadow-sm"}`,children:s})})}function Nh({result:t,intent:s,onBack:n,onSave:a,onFallback:l,saving:r,typeNames:o}){var f,x;const p=i.useMemo(()=>bh(s,{typeNames:o}),[s,o]),u=i.useMemo(()=>(t.columns||[]).map(g=>({key:g.key,label:g.label,type:g.type==="month"||g.type==="date"?"date":g.type,render:y=>e.jsxs("span",{className:g.type==="text"?"font-bold text-slate-800":"tabular-nums",children:[g.dot&&y[g.dot]&&e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full ml-2 align-middle",style:{background:y[g.dot]}}),Oi(g,y),g.sub&&y[g.sub]?e.jsxs("span",{className:"block text-[11.5px] text-slate-400",dir:"ltr",children:["#",y[g.sub]]}):null]}),excel:y=>y[g.key]})),[t.columns]),d=i.useMemo(()=>
54{if(!t.totals)return;const g={};for(const y of t.columns||[]){const $=t.totals[y.key];g[y.key]=$==null?"":Oi(y,t.totals)}return g},[t.totals,t.columns]),c=t.chart,m=c?e.jsx(As,{title:c.kind==="donut"?"התפלגות":"לאורך התקופה",legend:c.kind==="donut"?(c.data||[]).slice(0,8).map((g,y)=>e.jsx(qe,{color:g.color||cn[y%cn.length],children:g[c.nameKey]||g.name},g.key||g.name||y)):c.kind==="collection"?[e.jsx(qe,{color:"#cbd5e1",children:"חויב"},"b"),e.jsx(qe,{color:"#0d9488",children:"נגבה"},"c"),e.jsx(qe,{color:"#f59e0b",children:"אחוז גבייה"},"r")]:[e.jsx(qe,{color:"#e11d48",children:"יתרה באיחור"},"a")],height:"20rem",children:e.jsx(Rt,{width:"100%",height:"100%",children:c.kind==="donut"?e.jsxs(Yn,{children:[e.jsx(Vn,{data:c.data,dataKey:c.valueKey,nameKey:c.nameKey,innerRadius:"58%",outerRadius:"86%",paddingAngle:2,stroke:"#fff",strokeWidth:2,children:(c.data||[]).map((g,y)=>e.jsx(_s,{fill:g.color||cn[y%cn.length]},g.key||y))}),e.jsx(ht,{formatter:g=>Ca(g)})]}):c.kind==="collection"?e.jsxs(zo,{data:c.data,margin:{top:20,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(Qt,{dataKey:"month",tickFormatter:Ze,tick:{fontSize:11,fill:"#64748b"},reversed:!0,tickLine:!1}),e.jsx(Ct,{yAxisId:"m",orientation:"right",width:70,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:!1,tickFormatter:g=>new Intl.NumberFormat("he-IL").format(g)}),e.jsx(Ct,{yAxisId:"r",orientation:"left",width:44,domain:[0,100],tick:{fontSize:11,fill:"#94a3b8"},tickLine:!1,axisLine:!1,tickFormatter:g=>`${g}%`}),e.jsx(ht,{formatter:(g,y)=>y==="rate"?`${Number(g).toFixed(1)}%`:Ca(g)}),e.jsx(Mo,{yAxisId:"r",y:95,stroke:"#f59e0b",strokeDasharray:"5 4"}),e.jsx(pt,{yAxisId:"m",dataKey:"billed",name:"חויב",fill:"#cbd5e1",radius:[6,6,0,0],maxBarSize:38}),e.jsx(pt,{yAxisId:"m",dataKey:"collected",name:"נגבה",fill:"#0d9488",radius:[6,6,0,0],maxBarSize:38}),e.jsx(yr,{yAxisId:"r",type:"linear",dataKey:"rate",name:"rate",stroke:"#f59e0b",strokeWidth:2.5,dot:{r:3}})]}):e.jsxs(Ba,{data:c.data,margin:{top:20,right:8,left:8,bottom:4},children:[e.jsx(js,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(Qt,{dataKey:c.xKey,tickFormatter:Ze,tick:{fontSize:11,fill:"#64748b"},reversed:!0,tickLine:!1}),e.jsx(Ct,{orientation:"right",width:70,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:!1,tickFormatter:g=>new Intl.NumberFormat("he-IL").format(g)}),e.jsx(ht,{formatter:g=>Ca(g)}),e.jsx(pt,{dataKey:c.valueKey,fill:"#e11d48",radius:[6,6,0,0],maxBarSize:54})]})})}):null,h=(t.unavailable||[]).filter(g=>g.state!=="connected"),b=t.included||[];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center flex-wrap gap-2 no-print",children:[e.jsxs("button",{type:"button",onClick:n,className:"h-10 px-4 rounded-xl border border-slate-200 bg-white text-[13.5px] font-bold text-slate-600 inline-flex items-center gap-2 hover:border-slate-300",children:[e.jsx(bs,{className:"w-4 h-4"})," שאלה חדשה"]}),e.jsxs("button",{type:"button",onClick:a,disabled:r,className:"h-10 px-4 rounded-xl bg-teal-600 text-white text-[13.5px] font-bold inline-flex items-center gap-2 hover:bg-teal-700 disabled:opacity-60",children:[r?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Po,{className:"w-4 h-4"})," שמירת הדוח"]}),e.jsx("span",{className:"mr-auto flex items-center flex-wrap gap-1.5",children:p.map(g=>e.jsx("span",{className:"text-[12px] font-bold text-slate-500 bg-slate-100 rounded-lg px-2.5 py-1",children:g},g))})]}),t.budget&&!t.budget.configured&&e.jsxs("section",{className:"rounded-2xl border border-amber-200 bg-amber-50/70 p-4 flex items-start gap-3",children:[e.jsx(At,{className:"w-4 h-4 text-amber-600 flex-none mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[13.5px] font-bold text-amber-900",children:"לא הוגדרו סעיפי תקציב לקהילה זו בממשק סאמיט"}),e.jsx("p",{className:"text-[12.5px] text-amber-800 mt-0.5",children:"החיובים מוצגים תחת «ללא סעיף תקציבי». אפשר להציג את אותה תקופה לפי סוג החיוב."}),e.jsx("button",{type:"button",onClick:l,className:"mt-2 h-9 px-3.5 rounded-xl bg-white border border-amber-300 text-[13px] font-bold text-amber-900 hover:bg-amber-50",children:"הצג במקום זאת לפי סוג חיוב"})]})]}),e.jsx(Ms,{title:((f=lr(s.metric))==null?void 0:f.l)||t.title,period:t.period||wc(s.dateRange),subtitle:t.title||((x=lr(s.metric))==null?void 0:x.hint)||"",icon:wn,stats:(t.cards||[]).map(g=>({label:g.label,value:gh(g),sub:yh(g),icon:_h[g.unit]||wn,tone:g.unit==="percent"?"amber":g.unit==="number"?"sky":"teal"})),chart:m,tableTitle:"פירוט",columns:u,rows:t.rows||[],totals:d,unit:"שורות",perPage:12,empty:"לא נמצאו נתונים לבקשה הזאת בתקופה שנבחרה.",fileName:`דוח_חכם_${t.period||""}`,footNote:(t.notes||[]).join(" ")}),e.jsxs("section",{className:"rounded-2xl border border-slate-200 bg-slate-50/60 p-4",children:[e.jsxs("h4",{className:"text-[13.5px] font-black text-slate-800 flex items-center gap-2",children:[e.jsx($d,{className:"w-4 h-4 text-teal-600"})," הדוח מבוסס על מקורות החיוב המחוברים כעת למערכת"]}),b.length>0&&e.jsxs("p",{className:"mt-2 text-[12.5px] text-slate-600",children:[e.jsx("b",{className:"text-slate-700",children:"נכללו:"})," ",b.map(g=>g.label).join(" · ")]}),h.length>0&&e.jsx("ul",{className:"mt-1.5 space-y-1",children:h.map(g=>e.jsxs("li",{className:"text-[12.5px] text-slate-500",children:[e.jsxs("b",{className:"text-slate-600",children:["לא נכלל — ",g.label,":"]}
54)," ",g.state==="empty"?g.note||"אין נתונים במקור הזה":g.note||"המודול אינו מדווח סכומים"]},g.key))})]})]})}function vh({kibbutzId:t}){const[s,n]=i.useState(""),[a,l]=i.useState([]),[r,o]=i.useState(!1),[p,u]=i.useState(null),[d,c]=i.useState({}),[m,h]=i.useState(""),[b,f]=i.useState(null),[x,g]=i.useState(null),[y,$]=i.useState(!1),[O,A]=i.useState([]),[S,P]=i.useState([]),[E,k]=i.useState(""),C=i.useRef(null),w=i.useMemo(()=>Object.fromEntries(S.map(N=>[N.id,N.name])),[S]),_=i.useCallback(()=>{D.functions.invoke("smartReport",{action:"list"}).then(N=>{var v;return A(((v=N==null?void 0:N.data)==null?void 0:v.reports)||[])}).catch(()=>A([]))},[]);i.useEffect(()=>{_(),D.entities.ChargeType.filterAll({kibbutz_id:t},"order").then(N=>P(N||[])).catch(()=>P([]))},[t,_]);const T=(N,v)=>l(F=>[...F,{from:N,body:v,id:`${Date.now()}-${F.length}`}]),M=async(N,v)=>{o(!0),u(null);try{const F=await D.functions.invoke("smartReport",{action:"parse",text:N,answers:v||{}}),K=F==null?void 0:F.data;if(!(K!=null&&K.success))throw new Error("parse");if(K.status==="unsupported"){T("bot",e.jsxs("span",{children:["לא הצלחתי להפוך את הבקשה לדוח. אפשר לנסח אותה כך:",e.jsx("span",{className:"block mt-2 space-y-1",children:(K.suggestions||[]).map(Z=>e.jsx("button",{type:"button",onClick:()=>{n(Z)},className:"block w-full text-right rounded-lg bg-white/15 hover:bg-white/25 px-3 py-1.5 text-[13px]",children:Z},Z))})]}));return}if(K.status==="need_input"){g(K.intent),u(K.question),T("bot",K.question.text);return}g(K.intent),T("bot",e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(ye,{className:"w-4 h-4",strokeWidth:3})," הדוח שלך מוכן — ",K.title]})),await B(K.intent)}catch(F){T("bot",(F==null?void 0:F.message)==="parse"?"לא הצלחתי לפרש את הבקשה. נסו לנסח אותה מחדש.":"אירעה שגיאה. נסו שוב.")}finally{o(!1)}},B=async(N,v)=>{o(!0);try{const F=await D.functions.invoke("smartReport",{action:"run",intent:N,saved_id:v}),K=F==null?void 0:F.data;if(!(K!=null&&K.success))throw new Error("run");f(K.result),g(K.intent)}catch{W.error("לא הצלחנו להפיק את הדוח"),T("bot","לא הצלחנו להפיק את הדוח. נסו שוב או שנו את הבקשה.")}finally{o(!1)}},R=N=>{const v=(N??s).trim();!v||r||(n(""),c({}),h(v),T("user",v),M(v,{}))},j=N=>{var F;const v={...d,[p.key]:N};c(v),T("user",((F=p.options.find(K=>K.v===N))==null?void 0:F.l)||N),M(m,v)},q=async()=>{var N;if(x){$(!0);try{const v=await D.functions.invoke("smartReport",{action:"save",intent:x,prompt:m,name:hh(x)});if(!((N=v==null?void 0:v.data)!=null&&N.success))throw new Error;W.success("הדוח נשמר"),_()}catch{W.error("לא הצלחנו לשמור את הדוח")}finally{$(!1)}}},L=async N=>{try{await D.functions.invoke("smartReport",{action:"delete",id:N}),_()}catch{W.error("לא הצלחנו למחוק")}};return i.useEffect(()=>{C.current&&(C.current.scrollTop=C.current.scrollHeight)},[a,p]),b&&x?e.jsx(Nh,{result:b,intent:x,typeNames:w,saving:y,onSave:q,onFallback:()=>B({...x,dimensions:["type"]}),onBack:()=>{f(null),l([]),u(null),c({})}}):e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1fr,19rem] gap-4 items-start",children:[e.jsxs("section",{className:"min-w-0 rounded-2xl border border-slate-200 bg-gradient-to-b from-slate-50 to-white shadow-sm overflow-hidden",children:[e.jsxs("header",{className:"px-5 py-4 border-b border-slate-100 bg-white/70",children:[e.jsxs("h3",{className:"text-[20px] font-black text-slate-900 flex items-center gap-2",children:[e.jsx("span",{className:"w-9 h-9 rounded-xl bg-teal-600 text-white grid place-items-center",children:e.jsx(wn,{className:"w-[18px] h-[18px]"})}),"הדוח החכם"]}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1.5",children:"כתבו בשפה חופשית איזה דוח אתם צריכים — «הצג חיובים בכרטיסי אשראי בספטמבר» — ואנחנו נבנה אותו מנתוני הקהילה שלכם. אם חסר פרט, נשאל שאלה אחת."})]}),e.jsxs("div",{ref:C,className:"px-5 py-4 space-y-3 max-h-[26rem] overflow-y-auto",children:[a.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[12.5px] font-bold text-slate-400",children:"אפשר להתחיל מאחת מאלה:"}),fh.map(N=>e.jsxs("button",{type:"button",onClick:()=>R(N),className:`w-full text-right rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-[13.5px] text-slate-700
55                    hover:border-teal-300 hover:bg-teal-50/40 inline-flex items-center gap-2`,children:[e.jsx(eu,{className:"w-4 h-4 text-teal-500 flex-none"}),N]},N))]}),a.map(N=>e.jsx(jh,{from:N.from,children:N.body},N.id)),r&&e.jsx("div",{className:"flex justify-end",children:e.jsxs("span",{className:"rounded-2xl bg-teal-600/90 text-white px-4 py-3 inline-flex items-center gap-2 text-[13.5px]",children:[e.jsx(Ie,{className:"w-4 h-4 animate-spin"})," בונה את הדוח…"]})}),p&&!r&&e.jsxs("div",{className:"rounded-2xl border border-teal-200 bg-teal-50/50 p-3",children:[e.jsx("p",{className:"text-[13.5px] font-bold text-teal-900 mb
55-2",children:p.text}),e.jsx("div",{className:"flex flex-wrap gap-2",children:p.options.map(N=>e.jsxs("button",{type:"button",onClick:()=>j(N.v),className:"rounded-xl border border-teal-200 bg-white px-3.5 py-2 text-[13px] font-bold text-slate-700 hover:border-teal-400 text-right",children:[e.jsx("span",{className:"block",children:N.l}),N.hint&&e.jsx("span",{className:"block text-[11px] font-normal text-slate-400",children:N.hint})]},N.v))}),p.allowOther&&e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx("input",{value:E,onChange:N=>k(N.target.value),onKeyDown:N=>{N.key==="Enter"&&E.trim()&&(j(E.trim()),k(""))},placeholder:"אחר…",className:"h-9 flex-1 rounded-xl border border-slate-200 px-3 text-[13px] focus:outline-none focus:border-teal-400"}),e.jsx("button",{type:"button",disabled:!E.trim(),onClick:()=>{j(E.trim()),k("")},className:"h-9 px-3 rounded-xl bg-teal-600 text-white text-[13px] font-bold disabled:opacity-40",children:"שלח"})]})]})]}),e.jsx("div",{className:"px-5 pb-5",children:e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-white shadow-sm focus-within:border-teal-400 focus-within:ring-4 focus-within:ring-teal-50 transition-all",children:[e.jsx("textarea",{value:s,onChange:N=>n(N.target.value),onKeyDown:N=>{N.key==="Enter"&&(N.metaKey||N.ctrlKey)&&R()},rows:4,placeholder:"לדוגמה: הצג את כל החיובים בכרטיסי אשראי בחודש ספטמבר, לפי סעיפי תקציב",className:"w-full resize-none bg-transparent px-4 py-3 text-[15px] leading-relaxed text-slate-800 placeholder:text-slate-300 focus:outline-none"}),e.jsxs("div",{className:"flex items-center gap-2 px-3 pb-3",children:[e.jsxs("span",{className:"text-[11.5px] text-slate-400 inline-flex items-center gap-1",children:[e.jsx(qc,{className:"w-3.5 h-3.5"})," Ctrl+Enter לשליחה"]}),e.jsxs("button",{type:"button",onClick:()=>R(),disabled:r||!s.trim(),className:`mr-auto h-11 px-5 rounded-xl bg-teal-600 text-white text-[14px] font-bold inline-flex items-center gap-2
56                  hover:bg-teal-700 disabled:opacity-40 disabled:cursor-not-allowed`,children:[r?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Gs,{className:"w-4 h-4"}),"בניית הדוח"]})]})]})})]}),e.jsxs("aside",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-white shadow-sm p-4",children:[e.jsxs("h4",{className:"text-[14px] font-black text-slate-800 flex items-center gap-2",children:[e.jsx(Po,{className:"w-4 h-4 text-teal-600"})," דוחות שמורים"]}),O.length===0?e.jsx("p",{className:"text-[12.5px] text-slate-400 mt-2",children:"דוח ששמרתם יופיע כאן, וייפתח על הנתונים של היום."}):e.jsx("ul",{className:"mt-2 space-y-1.5",children:O.map(N=>e.jsx("li",{className:"group rounded-xl border border-slate-100 hover:border-teal-200 hover:bg-teal-50/30",children:e.jsxs("div",{className:"flex items-center gap-1 px-2.5 py-2",children:[e.jsxs("button",{type:"button",onClick:()=>B(N.intent,N.id),className:"min-w-0 flex-1 text-right",children:[e.jsx("span",{className:"block text-[13px] font-bold text-slate-700 truncate",children:N.name}),e.jsxs("span",{className:"block text-[11px] text-slate-400 truncate",children:[N.last_run_at?"הורץ לאחרונה":"טרם הורץ",N.prompt?` · ${N.prompt}`:""]})]}),e.jsx("button",{type:"button",onClick:()=>B(N.intent,N.id),title:"הרצה מחדש",className:"w-7 h-7 rounded-lg grid place-items-center text-slate-300 hover:text-teal-600",children:e.jsx(br,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",onClick:()=>L(N.id),title:"מחיקה",className:"w-7 h-7 rounded-lg grid place-items-center text-slate-300 hover:text-rose-600",children:e.jsx(Re,{className:"w-3.5 h-3.5"})})]})},N.id))})]}),e.jsxs("div",{className:"rounded-2xl border border-slate-200 bg-white shadow-sm p-4",children:[e.jsxs("h4",{className:"text-[14px] font-black text-slate-800 flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4 text-slate-400"})," מה אפשר לשאול"]}),e.jsxs("ul",{className:"mt-2 space-y-1 text-[12.5px] text-slate-500 list-disc pr-4",children:[e.jsx("li",{children:"חיובים ותשלומים לפי אמצעי תשלום"}),e.jsx("li",{children:"חיובים לפי סעיף תקציב או סוג חיוב"}),e.jsx("li",{children:"חשבונות באיחור, ומי חייב הכי הרבה זמן"}),e.jsx("li",{children:"אחוזי גבייה, כולל השוואה לשנה שעברה"}),e.jsx("li",{children:"עסקאות אשראי שנכשלו"})]}),e.jsxs("p",{className:"mt-3 text-[11.5px] text-slate-400 flex items-start gap-1.5",children:[e.jsx(At,{className:"w-3.5 h-3.5 flex-none mt-0.5"}),"הדוח מוצג על נתוני הקהילה שאתם מחוברים אליה בלבד."]})]})]})]})}const Na=[{key:"smart",label:"הדוח החכם",icon:wn,tone:"teal",Comp:vh},{key:"charges",label:"חיובים",icon:nt,tone:"blue",Comp:rp},{key:"paymentPages",label:"עמודי תשלום",icon:Zt,tone:"purple",Comp:fp},{key:"income",label:"הכנסות",icon:ks,tone:"rose",Comp:Np},{key:"accounts",label:"חשבונות",icon:De,tone:"emerald",Comp:pp},{key:"properties",label:"נכסים",icon:ra,tone:"amber",Comp:Fx}
56,{key:"water",label:"מונים",icon:Ke,tone:"sky",Comp:Px},{key:"kolbo",label:"כולבו",icon:da,tone:"indigo",Comp:Ox},{key:"ledger",label:"כרטסת",icon:Ic,tone:"violet",Comp:Mp},{key:"movements",label:"תנועות",icon:Kn,tone:"cyan",Comp:ih}],wh={purple:"bg-purple-600 border-transparent text-white",sky:"bg-sky-600 border-transparent text-white",amber:"bg-amber-600 border-transparent text-white",indigo:"bg-indigo-600 border-transparent text-white",teal:"bg-teal-600 border-transparent text-white",emerald:"bg-emerald-600 border-transparent text-white",rose:"bg-rose-600 border-transparent text-white",blue:"bg-blue-600 border-transparent text-white",violet:"bg-violet-600 border-transparent text-white",cyan:"bg-cyan-600 border-transparent text-white"},Li={purple:"text-purple-600",sky:"text-sky-600",amber:"text-amber-600",indigo:"text-indigo-600",teal:"text-teal-600",emerald:"text-emerald-600",rose:"text-rose-600",blue:"text-blue-600",violet:"text-violet-600",cyan:"text-cyan-600"};function kh({kibbutzId:t,initial:s,initialFilter:n}){const[a,l]=i.useState(()=>Na.some(d=>d.key===s)?s:Na[0].key),[r,o]=i.useState(null);i.useEffect(()=>{let d=!0;return D.entities.BillingSettings.filter({kibbutz_id:t},"-created_date",1).then(c=>{d&&o((c==null?void 0:c[0])||null)}).catch(()=>{}),()=>{d=!1}},[t]);const p=Na.find(d=>d.key===a)||Na[0],u=p.Comp;return e.jsxs("div",{children:[e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2 mb-4 no-print",children:Na.map(d=>{const c=d.icon,m=d.key===a;return e.jsxs("button",{onClick:()=>l(d.key),className:`h-12 px-3 rounded-xl text-[15px] font-bold border inline-flex items-center justify-center gap-2 transition-colors ${m?wh[d.tone]:"bg-white border-slate-200 text-slate-600 hover:bg-slate-50"}`,children:[e.jsx(c,{className:`w-[18px] h-[18px] flex-none ${m?"":Li[d.tone]||Li.teal}`}),e.jsx("span",{className:"truncate",children:d.label})]},d.key)})}),e.jsx(u,{kibbutzId:t,settings:r,initialFilter:p.key===s?n:null},p.key)]})}const cs=Se;function Sh({kibbutzId:t}){const[s,n]=i.useState(!0),[a,l]=i.useState(null),[r,o]=i.useState({}),[p,u]=i.useState(!1),[d,c]=i.useState(!1),m=(x,g)=>o(y=>({...y,[x]:g})),h=i.useCallback(async()=>{n(!0);try{const g=(await D.entities.BillingSettings.filter({kibbutz_id:t},"-created_date",1)||[])[0]||null;l(g),o(g?{...g}:{currency:"ILS",default_due_day:15,online_payments_enabled:!1})}catch{W.error("שגיאה בטעינת ההגדרות")}finally{n(!1)}},[t]);i.useEffect(()=>{h()},[h]);async function b(x){if(x){c(!0);try{const{file_url:g}=await D.integrations.Core.UploadFile({file:x});m("logo_url",g),W.success("הלוגו הועלה")}catch{W.error("שגיאה בהעלאה")}finally{c(!1)}}}async function f(){u(!0);const x={kibbutz_id:t,legal_name:r.legal_name||null,address:r.address||null,phone:r.phone||null,email:r.email||null,business_number:r.business_number||null,logo_url:r.logo_url||null,footer_note:r.footer_note||null,default_due_day:r.default_due_day===""||r.default_due_day==null?null:Number(r.default_due_day),currency:r.currency||"ILS",online_payments_enabled:!!r.online_payments_enabled};try{a?await D.entities.BillingSettings.update(a.id,x):await D.entities.BillingSettings.create(x),D.entities.BillingActivityLog.create({kibbutz_id:t,action_type:"settings_updated",entity_type:"billing_settings",entity_id:(a==null?void 0:a.id)||null}).catch(()=>{}),W.success("ההגדרות נשמרו"),await h()}catch{W.error("שגיאה בשמירה")}finally{u(!1)}}return s?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})}):e.jsxs("div",{className:"max-w-3xl space-y-5 billing-form",children:[e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"w-9 h-9 rounded-lg bg-indigo-50 flex items-center justify-center",children:e.jsx(ra,{className:"w-5 h-5 text-indigo-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-bold",children:"פרטי המנפיק"}),e.jsx("p",{className:"text-xs text-slate-400",children:"מופיעים בכותרת כל מסמך חשבון"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(Q,{label:"שם משפטי / שם המנפיק",required:!0,children:e.jsx("input",{className:cs,placeholder:"הזן שם מנפיק",value:r.legal_name||"",onChange:x=>m("legal_name",x.target.value)})}),e.jsx(Q,{label:"ח.פ / ×¢.מ",children:e.jsx("input",{className:cs,placeholder:"הזן ח.פ / ×¢.מ",value:r.business_number||"",onChange:x=>m("business_number",x.target.value)})}),e.jsx(Q,{label:"כתובת",children:e.jsx("input",{className:cs,placeholder:"הזן כתובת",value:r.address||"",onChange:x=>m("address",x.target.value)})}),e.jsx(Q,{label:"טלפון",children:e.jsx("input",{className:cs,placeholder:"הזן טלפון",value:r.phone||"",onChange:x=>m("phone",x.target.value)})}),e.jsx(Q,{label:'דוא"ל',children:e.jsx("input",{className:cs,placeholder:'הז×
56Ÿ דוא"ל',value:r.email||"",onChange:x=>m("email",x.target.value)})}),e.jsx(Q,{label:"לוגו",children:e.jsxs("div",{className:"flex items-center gap-2",children:[r.logo_url&&e.jsx("img",{src:r.logo_url,alt:"",className:"h-12 w-auto max-w-[80px] object-contain rounded border border-slate-200"}),e.jsxs("label",{className:"inline-flex items-center gap-1.5 h-12 px-4 rounded-xl border border-slate-300 text-sm text-slate-500 cursor-pointer hover:bg-slate-50",children:[e.jsx(La,{className:"w-4 h-4"})," ",d?"מעלה…":r.logo_url?"החלפת לוגו":"העלאת לוגו",e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x=>{var g;return b((g=x.target.files)==null?void 0:g[0])}})]})]})}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(Q,{label:"הערת תחתית למסמך",hint:"לדוגמה: פרטי חשבון בנק לתשלום, או הודעה קבועה",children:e.jsx("textarea",{className:ua,rows:2,placeholder:"הערת תחתית שתופיע בתחתית כל מסמך חשבון",value:r.footer_note||"",onChange:x=>m("footer_note",x.target.value)})})})]})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("span",{className:"w-9 h-9 rounded-lg bg-slate-100 flex items-center justify-center",children:e.jsx(zn,{className:"w-5 h-5 text-slate-600"})}),e.jsx("h3",{className:"text-base font-bold",children:"ברירות מחדל"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(Q,{label:"יום לתשלום כברירת מחדל (בחודש)",children:e.jsx("input",{type:"number",min:"1",max:"31",className:cs,value:r.default_due_day??"",onChange:x=>m("default_due_day",x.target.value)})}),e.jsx(Q,{label:"מטבע",children:e.jsx("input",{className:cs,value:r.currency||"ILS",onChange:x=>m("currency",x.target.value)})})]})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"w-9 h-9 rounded-lg bg-emerald-50 flex items-center justify-center",children:e.jsx(Oe,{className:"w-5 h-5 text-emerald-600"})}),e.jsx("h3",{className:"text-base font-bold",children:"תשלום מקוון"})]}),e.jsxs("div",{className:"flex items-start gap-2 bg-amber-50 border border-amber-200 rounded-xl px-4 py-2.5 mb-3 text-xs text-amber-800",children:[e.jsx(Un,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),' טרם חובר ספק סליקה לקהילה זו. הפעלת המתג תציג לתושבים כפתור „תשלום מקוון" רק לאחר חיבור ספק. עד אז מומלץ להשאירו כבוי.']}),e.jsxs("button",{type:"button",onClick:()=>m("online_payments_enabled",!r.online_payments_enabled),className:`flex items-center gap-2 h-11 px-4 rounded-xl border text-sm w-full sm:w-auto ${r.online_payments_enabled?"border-emerald-300 bg-emerald-50 text-emerald-700":"border-slate-200 text-slate-500"}`,children:[e.jsx(xt,{className:"w-4 h-4"}),e.jsx("span",{className:"flex-1 text-right",children:"אפשר תשלום מקוון באזור האישי"}),e.jsx("span",{className:`w-9 h-5 rounded-full flex items-center px-0.5 transition-all ${r.online_payments_enabled?"bg-emerald-500 justify-end":"bg-slate-300 justify-start"}`,children:e.jsx("span",{className:"w-4 h-4 rounded-full bg-white"})})]})]}),e.jsxs("button",{onClick:f,disabled:p,className:ts,children:[e.jsx(ye,{className:"w-4 h-4"})," ",p?"שומר…":"שמירת הגדרות"]})]})}const Fl=400,Fe=t=>new Intl.NumberFormat("he-IL").format(t),$h=t=>oo(t,"",{decimals:2}).trim(),Ti={pending:{label:"ממתין לאישור",cls:"bg-amber-50 text-amber-700"},approved:{label:"מוצג לתושבים",cls:"bg-emerald-50 text-emerald-700"}},Ks=t=>{if(!t)return"—";const[s,n,a]=String(t).slice(0,10).split("-");return`${a}/${n}/${s}`};function dn({label:t,value:s}){return e.jsxs("div",{className:"bg-white/80 border border-black/5 rounded-2xl px-3 py-2.5 text-right",children:[e.jsx("p",{className:"text-[11px] font-bold text-slate-500",children:t}),e.jsx("p",{className:"text-xl font-extrabold tracking-tight mt-0.5 tabular-nums",children:e.jsx("span",{dir:"ltr",className:"inline-block",children:s})})]})}function Dl({tone:t,icon:s,title:n,children:a}){const l=t==="ok"?"bg-emerald-50 border-emerald-200 text-emerald-800":t==="warn"?"bg-amber-50 border-amber-200 text-amber-900":"bg-rose-50 border-rose-200 text-rose-800";return e.jsxs("div",{className:`flex gap-3 rounded-2xl border p-3.5 ${l}`,children:[e.jsx(s,{className:"w-5 h-5 flex-none mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-bold text-sm",children:n}),a&&e.jsx("div",{className:"text-[13px] mt-0.5 leading-relaxed",children:a})]})]})}function Bi({title:t,hint:s,rows:n,extra:a}){return n!=null&&n.length?e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 border-b border-slate-200 bg-slate-50/60",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"block text-sm font-extrabold text-slate-800",children:[t," (",n.length,")"]}),s&&e.jsx("span",{className:"block text-[11px] text-slate-400",children:s})]}),e.jsx("span",{className:"text-sm font-extrabold tabular-nums whitespace-nowrap",dir:"ltr",children:ve(n.reduce((l,r)=>l+(r.total||0),0))})]}),e.jsx("div",{className:"max-h-72 overflow-y-auto",children:e.jsx("table",{className:"w-full border-collapse",children:e.jsx("tbody",{children:n.map(l=>e.jsxs("tr",{className:"border-b border-slate-100 last:border-0",children:[e.jsxs("td",{className:"px-4 py-2 text-sm",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:l.payer_name||"—"}),e.jsx("span",{className:"block text-[11px] text-slate-400",children:[`מגזר ${l.sector||"—"}
56`,a==null?void 0:a(l)].filter(Boolean).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-2 text-xs text-slate-500 text-left whitespace-nowrap",children:["תקציב ",l.budget]}),e.jsxs("td",{className:"px-4 py-2 text-xs text-slate-500 text-left whitespace-nowrap",children:[Fe(l.lines)," שורות"]}),e.jsx("td",{className:"px-4 py-2 text-sm font-bold text-left tabular-nums",dir:"ltr",children:$h(l.total)})]},l.budget))})})})]}):null}function Ch({kibbutzId:t}){var S,P;const s=i.useRef(null),[n,a]=i.useState(""),[l,r]=i.useState(0),[o,p]=i.useState(null),[u,d]=i.useState(null),[c,m]=i.useState([]),[h,b]=i.useState(null),f=i.useCallback(async()=>{var E;try{const k=await D.functions.invoke("kolboImport",{action:"list",community_id:t});m(((E=k==null?void 0:k.data)==null?void 0:E.batches)||(k==null?void 0:k.batches)||[])}catch{}},[t]);i.useEffect(()=>{f()},[f]);const x=()=>{p(null),d(null),r(0),s.current&&(s.current.value="")};async function g(E){var C;const k=(C=E.target.files)==null?void 0:C[0];if(k){a("parse");try{const w=od(await k.arrayBuffer()),{rows:_,errors:T}=cd(w);if(!_.length){W.error("לא נמצאו שורות קריאות בקובץ"),x();return}const M=dd(_);p({name:k.name,summary:M,rows:_,errors:T});const B=await D.functions.invoke("kolboImport",{action:"start",community_id:t,file_name:k.name,period_from:M.period_from,period_to:M.period_to,error_count:T.length,budgets:M.budgets.map(j=>({budget:j.budget,payer_name:j.payer_name,sector:j.sector,lines:j.lines,total:j.total}))}),R=(B==null?void 0:B.data)||B;if(!(R!=null&&R.batch_id))throw new Error("no batch");d(R),a("upload");for(let j=0;j<_.length;j+=Fl)await D.functions.invoke("kolboImport",{action:"rows",community_id:t,batch_id:R.batch_id,rows:_.slice(j,j+Fl)}),r(Math.min(_.length,j+Fl));await f()}catch(w){W.error((w==null?void 0:w.message)||"שגיאה בטעינת הקובץ"),x()}finally{a("")}}}async function y(E,k){a(E);try{const C=await D.functions.invoke("kolboImport",{action:E,community_id:t,batch_id:k}),w=(C==null?void 0:C.data)||C;E==="approve"?W.success(w!=null&&w.replaced?`אושר — ${Fe(w.replaced)} שורות מטעינה קודמת הוחלפו`:"אושר ומוצג לתושבים"):E==="delete"?W.success(`הטעינה נמחקה — ${Fe((w==null?void 0:w.removed)||0)} שורות הוסרו`):W.success("הטעינה בוטלה"),x(),await f()}catch(C){W.error((C==null?void 0:C.message)||"הפעולה נכשלה")}finally{a("")}}const $=o==null?void 0:o.summary,O=i.useMemo(()=>{if(!u||!$)return 0;const E=new Set([...u.unmatched||[],...u.ambiguous||[]].map(k=>k.budget));return $.budgets.filter(k=>!E.has(k.budget)).reduce((k,C)=>k+C.total,0)},[u,$]),A=((u==null?void 0:u.unmatched)||[]).reduce((E,k)=>E+k.total,0);return e.jsxs("div",{className:"space-y-4",dir:"rtl",children:[o?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-2xl border border-black/5 shadow-sm p-5",style:{background:"linear-gradient(155deg,rgba(99,102,241,.12) 0%,#fff 48%,rgba(99,102,241,.08) 100%)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-bold px-2.5 py-1 rounded-full bg-indigo-100 text-indigo-700",children:[e.jsx(pr,{className:"w-3 h-3"})," קובץ כולבו"]}),e.jsx("h3",{className:"text-xl font-extrabold mt-2 truncate",children:o.name}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[Fe($.rows)," שורות · ",Ks($.period_from)," – ",Ks($.period_to),o.errors.length>0&&e.jsxs("span",{className:"text-rose-600 font-bold",children:[" · ",Fe(o.errors.length)," שורות לא נקראו"]})]})]}),e.jsx("p",{className:"text-2xl font-extrabold tabular-nums whitespace-nowrap",dir:"ltr",children:ve($.total)})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mt-4",children:[e.jsx(dn,{label:"שורות",value:Fe($.rows)}),e.jsx(dn,{label:"חשבוניות",value:Fe($.receipts)}),e.jsx(dn,{label:"מספרי תקציב",value:Fe($.budgets.length)}),e.jsx(dn,{label:"נטענו",value:Fe(l)})]}),n==="upload"&&e.jsx("div",{className:"h-1.5 rounded-full bg-white/70 mt-3 overflow-hidden",children:e.jsx("div",{className:"h-full bg-indigo-500 rounded-full transition-all",style:{width:`${l/$.rows*100}%`}})})]}),u&&e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{tone:"ok",icon:la,title:`${Fe(u.matched)} מתוך ${Fe($.budgets.length)} מספרי תקציב נמצאו תושב תואם.`,children:[ve(O)," ישויכו לתושבים ויוצגו להם במרחב האישי לאחר האישור."]}),((S=u.unmatched)==null?void 0:S.length)>0&&e.jsx(Dl,{tone:"warn",icon:At,title:`${Fe(u.unmatched.length)} מספרי תקציב בקובץ ללא תושב תואם — ${ve(A)}.`,children:"הרשומות נשמרו ולא יוצגו לאיש. הזינו את מספר התקציב בפרטי התושב וטענו את הקובץ שוב."}),((P=u.ambiguous)==null?void 0:P.length)>0&&e.jsx(Dl,{tone:"bad",icon:De,title:`${Fe(u.ambiguous.length)} מספרי תקציב משויכים לשתי משפחות שונות.`,children:"כל עוד המספר רשום בשתי משפחות אי אפשר לדעת למי שייכות הקניות, ולכן הן לא יוצגו לאיש."}),e.jsx(Bi,{title:"ללא תושב תואם",hint:"לא יוצגו לאיש עד שמספר התקציב יוזן בפרטי התושב",rows:u.unmatched}),e.jsx(Bi,{title:"משויך לשתי משפחות",hint:"יש להשאיר את מספר התקציב אצל משפחה אחת בלבד",rows:u.ambiguous,extra:E=>(E.residents||[]).map(k=>k.name).join(" · ")}),e.jsxs("div",{className:"flex flex-wrap gap-2.5 pt-1",children:[e.jsxs("button",{type:"button",disabled:!!n,onClick:()=>y("approve",u.batch_id),className:"inline-flex items-center gap-2 h-11 px-6 rounded-full bg-emerald-600 text-white text-sm font-bold disabled:opacity-60",children:[n==="approve"?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(ye,{className:"w-4 h-4"}),"אשרו והציגו לתושבים"]}),e.jsxs("button",{type:"button",disabled:!!n,onClick:()=>y("cancel",u.batch_id),className:"inline-flex items-center gap-2 h-11 px-5 rounded-full bg-white border border-slate-200 text-slate-600 text-sm font-bold disabled:opacity-60",children:[e.jsx($e,{className:"w-4 h-4"})," ביטול הטעינה"]})]}),e.jsx("p",{className:"text-xs text-slate-400 leading-relaxed",children:"הקובץ כבר נשמר; «אישור» הוא מה שהופך אותו לגלוי במרחב האישי. עד אז אף תושב אינו רואה דבר, והחודש שכבר מוצג נשאר מוצג — כך אפשר לתקן מספרי תקציב ולטעון שוב בלי שמישהו יראה נתונים חלקיים."})]})]}):e.jsxs("div",{className:"bg-white rounded-2xl border border-dashed border-indigo-300 p-8 text-center",children:[e.jsx("span",{className:"w-12 h-12 rounded-2xl bg-indigo-50 grid place-items-center mx-auto mb-3",children:e.jsx(da,{className:"w-6 h-6 text-indigo-600"})}),e.jsx("h3",{className:"text-base font-bold text-slate-800",children:"טעינת קובץ כולבו"}),e.jsx("p",{className:"text-sm text-slate-500 mt-1 max-w-md mx-auto leading-relaxed",children:"הקובץ שהמרכול מפיק, כפי שהוא. כל שורה משויכת לתושב לפי מספר התקציב, ואחרי אישורכם כל משפחה רואה במרחב האישי את הקניות שלה בלבד."}),e.jsxs("label",{className:"inline-flex items-center gap-2 h-11 px-6 rounded-full bg-indigo-600 text-white text-sm font-bold mt-4 cursor-pointer hover:brightness-110 transition-all",children:[n==="parse"?e.jsx(Ie,{className:"w-4 h-4 animate-spin"}):e.jsx(La,{className:"w-4 h-4"}
56),"בחרו קובץ",e.jsx("input",{ref:s,type:"file",accept:".csv,.txt",className:"hidden",onChange:g,disabled:!!n})]})]}),c.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-200 bg-slate-50/60",children:e.jsx("h3",{className:"text-sm font-extrabold text-slate-800",children:"טעינות קודמות"})}),e.jsx("div",{className:"max-h-96 overflow-y-auto",children:c.map(E=>{const k=Ti[E.status]||Ti.pending;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-slate-100 last:border-0",children:[e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-bold text-slate-800 truncate",children:E.file_name||"קובץ כולבו"}),e.jsxs("span",{className:"block text-[11px] text-slate-400",children:[Ks(E.period_from)," – ",Ks(E.period_to)," · ",Fe(E.row_count||0)," שורות ·"," ",Fe(E.matched_count||0),"/",Fe(E.budget_count||0)," תקציבים שויכו"]})]}),e.jsx("span",{className:`text-[11px] font-bold px-2.5 py-1 rounded-full whitespace-nowrap ${k.cls}`,children:k.label}),e.jsx("span",{className:"text-sm font-extrabold tabular-nums whitespace-nowrap",dir:"ltr",children:ve(E.total)}),e.jsxs("span",{className:"flex items-center gap-1 flex-none",children:[E.status==="pending"&&e.jsx("button",{type:"button",title:"אשרו והציגו",disabled:!!n,onClick:()=>y("approve",E.id),className:"w-8 h-8 rounded-full bg-emerald-50 text-emerald-600 grid place-items-center hover:bg-emerald-100 disabled:opacity-50",children:e.jsx(ye,{className:"w-4 h-4"})}),e.jsx("button",{type:"button",title:E.status==="pending"?"ביטול הטעינה":"מחיקת הטעינה וכל נתוניה",disabled:!!n,onClick:()=>b(E),className:"w-8 h-8 rounded-full bg-slate-50 text-slate-400 grid place-items-center hover:bg-rose-50 hover:text-rose-600 disabled:opacity-50",children:e.jsx(Re,{className:"w-4 h-4"})})]})]},E.id)})})]}),e.jsx(No,{open:!!h,onOpenChange:E=>{E||b(null)},destructive:!0,title:(h==null?void 0:h.status)==="pending"?"לבטל את הטעינה?":"למחוק את הטעינה וכל נתוניה?",confirmLabel:(h==null?void 0:h.status)==="pending"?"בטלו את הטעינה":"מחקו את הטעינה",description:h&&(h.status==="pending"?`הקובץ «${h.file_name||"כולבו"}» טרם אושר ואף תושב לא ראה אותו. הוא יוסר לגמרי, ואפשר לטעון אותו שוב בכל עת.`:`«${h.file_name||"כולבו"}» מוצג כעת לתושבים. מחיקה תסיר את ${Fe(h.row_count||0)} השורות שלו — ממשק הניהול וגם מהמרחב האישי של כל תושב — ולא נשמר דבר לשחזור ממנו. התקופה ${Ks(h.period_from)} – ${Ks(h.period_to)} תחזור רק אם תטענו את הקובץ שוב.`),onConfirm:()=>{const E=h;b(null),y(E.status==="pending"?"cancel":"delete",E.id)}})]})}function Ah({catalog:t,pages:s,items:n,onClose:a,onSave:l}){const[r,o]=i.useState(0),[p,u]=i.useState(()=>{const _=Array.isArray(t==null?void 0:t.categories)?t.categories:[],T=[...n||[]].sort((M,B)=>(M.sort_order||0)-(B.sort_order||0));return{id:t==null?void 0:t.id,title:(t==null?void 0:t.title)||"",description:(t==null?void 0:t.description)||"",image_url:(t==null?void 0:t.image_url)||"",visibility:(t==null?void 0:t.visibility)||"public",show_in_menu:!!(t!=null&&t.show_in_menu),show_on_home:!!(t!=null&&t.show_on_home),show_in_personal:!!(t!=null&&t.show_in_personal),sectioned:_.length>0,categories:_,pageIds:T.map(M=>M.payment_page_id),categoryOf:Object.fromEntries(T.map(M=>[M.payment_page_id,M.category_id||""]))}}),d=(_,T)=>u(M=>({...M,[_]:T})),[c,m]=i.useState(!1),[h,b]=i.useState(!1),[f,x]=i.useState(""),g=i.useMemo(()=>new Set(p.pageIds),[p.pageIds]),y=i.useMemo(()=>{const _=f.trim();return(s||[]).filter(T=>!_||[T.title,T.description].join(" ").includes(_))},[s,f]),$=async _=>{if(_){m(!0);try{const{file_url:T}=await D.integrations.Core.UploadFile({file:_});d("image_url",T),W.success("התמונה הועלתה")}catch{W.error("שגיאה בהעלאת התמונה")}finally{m(!1)}}},O=_=>u(T=>T.pageIds.includes(_)?{...T,pageIds:T.pageIds.filter(M=>M!==_)}:{...T,pageIds:[...T.pageIds,_]}),A=()=>u(_=>({..._,categories:[..._.categories,{id:Fr(),title:""}]})),S=(_,T)=>u(M=>({...M,categories:M.categories.map(B=>B.id===_?{...B,title:T}:B)})),P=_=>u(T=>({...T,categories:T.categories.filter(M=>M.id!==_),categoryOf:Object.fromEntries(Object.entries(T.categoryOf).map(([M,B])=>[M,B===_?"":B]))})),E=()=>({...p,categories:p.sectioned?p.categories:[]}),k=_=>{if(_>r){if(r===0){if(!String(p.title||"").trim()){W.error("יש להזין שם לקטלוג");return}if(p.sectioned&&p.categories.some(T=>!String(T.title||"").trim())){W.error("לכל קטגוריה יש להזין כותרת");return}}if(r===1){const T=Dr(E());if(T&&!T.includes("שם לקטלוג")){W.error(T);return}}}o(_)},C=async()=>{const _=E(),T=Dr(_);if(T){o(T.includes("שם לקטלוג")?0:1),W.error(T);return}b(!0),await l(_),b(!1)},w=p.visibility==="public"&&(s||[]).some(_=>g.has(_.id)&&_.visibility==="residents");return e.jsxs(_r,{title:p.id?"עריכת קטלוג תשלום":"קטלוג תשלום חדש",icon:gs,steps:["פרטי הקטלוג","עמודי תשלום","נראות ומיקום"],step:r,onStep:k,onClose:a,onSubmit:C,submitting:h,children:[r===0&&e.jsxs("div",{className:"space-y-4 pb-2",children:[e.jsx(Q,{label:"כותרת הקטלוג",required:!0,children:e.jsx("input",{className:Se,value:p.title,onChange:_=>d("title",_.target.value),placeholder:"למשל: חוגי תשפ״ז",autoFocus:!0})}),e.jsx(Q,{label:"תיאור קצר",hint:"יוצג מתחת לכותרת בעמוד הקטלוג",children:e.jsx("textarea",{className:ua,rows:2,value:p.description,onChange:_=>d("description",_.target.value),placeholder:"מה יש כאן, עד מתי נרשמים, למי לפנות…"})}),e.jsxs(Q,{label:"תמונה ראשית",children:[e.jsxs("label",{className:`${Se} flex items-center gap-2 cursor-pointer ${c?"opacity-60":""}`,children:[e.jsx(jn,{className:"w-4 h-4 text-slate-400 flex-none"}),e.jsx("span",{className:`truncate ${p.image_url?"text-slate-700":"text-slate-400"}`,children:c?"מעלה…":p.image_url?"תמונה נבחרה":"בחירת קובץ"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:_=>{var T;return $((T=_.target.files)==null?void 0:T[0])}})]}),p.image_url&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("img",{src:p.image_url,alt:"",className:"w-16 h-16 rounded-lg object-cover border border-slate-200"}),e.jsx("button",{type:"button",onClick:()=>d("image_url",""),className:"text-[12px] text-red-600 font-bold",children:"הסרה"})]})]}),e.jsxs(Q,{label:"חלוקה לקטגוריות",children:[e.jsx("div",{className:"flex gap-2",children:[{v:!1,l:"ללא קטגוריות",hint:"כל העמודים על מדף אחד"},{v:!0,l:"עם קטגוריות",hint:"כל עמוד משויך לכותרת"}].map(_=>{const T=p.sectioned===_.v;return e.jsxs("button",{type:"button",onClick:()=>u(M=>({...M,sectioned:_.v,categories:_.v&&!M.categories.length?[{id:Fr(),title:""}]:M.categories})),className:`flex-1 rounded-xl border p-3 text-right transition-colors ${T?"border-teal-400 bg-teal-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[13px] font-bold text-slate-800",children:[_.l,T&&e.jsx(ye,{className:"w-3.5 h-3.5 text-teal-600 mr-auto"})]}),e.jsx("span",{className:"block text-[11px] text-slate-400 mt-0.5",children:_.hint})]},String(_.v))})}),p.sectioned&&e.jsxs("div",{className:"mt-3 space-y-2",children:[p.categories.map((_,T)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"w-6 text-[12px] font-black text-slate-400 tabular-nums",children:[T+1,"."]}),e.jsx("input",{className:Se,value:_.title,onChange:M=>S(_.id,M.target.value),placeholder:"כותרת הקטגוריה"}),e.jsx("button",{type:"button",onClick:()=>P(_.id),"aria-label":"הסרת קטגוריה",className:"w-10 h-10 rounded-xl border border-slate-200 grid place-items-center text-slate-400 hover:text-red-600 hover:bg-red-50 flex-none",children:e.jsx(Re,{className:"w-4 h-4"})})]},_.id)),e.jsxs("button",{type:"button",onClick:A,className:"h-9 px-3 rounded-lg border border-dashed border-slate-300 text-[12.5px] font-bold text-slate-500 inline-flex items-center gap-1.5 hover:border-teal-400 hover:text-teal-700",children:[e.jsx(We,{className:"w-4 h-4"})," הוספת קטגוריה"]})]})]})]}),r===1&&e.jsxs("div",{className:"flex flex-col h-full pb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-none pb-2",children:[e.jsx("p",{className:"text-[13px] font-bold text-slate-700",children:p.sectioned?"לכל עמוד שנבחר יש לבחור קטגוריה"
56:"העמודים יוצגו לפי סדר הבחירה"}),e.jsxs("span",{className:"text-[12px] text-slate-400 mr-auto",children:["נבחרו ",p.pageIds.length]})]}),(s||[]).length>6&&e.jsxs("div",{className:"relative mb-2 flex-none",children:[e.jsx(qt,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2"}),e.jsx("input",{className:`${Se} pr-9`,value:f,onChange:_=>x(_.target.value),placeholder:"חיפוש עמוד"})]}),e.jsxs("div",{className:"border border-slate-200 rounded-xl divide-y divide-slate-100 flex-1 min-h-0 overflow-y-auto",children:[y.length===0&&e.jsx("p",{className:"text-[12.5px] text-slate-400 p-4 text-center",children:"אין עמודי תשלום להצגה."}),y.map(_=>{const T=g.has(_.id);return e.jsx("div",{className:`p-2.5 ${T?"bg-teal-50/40":""}`,children:e.jsxs("label",{className:"flex items-center gap-2.5 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:T,onChange:()=>O(_.id),className:"w-4 h-4 rounded border-slate-300 text-teal-600 focus:ring-teal-500 flex-none"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block text-[13px] font-bold text-slate-800 truncate",children:[_.title,_.visibility==="residents"&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10.5px] font-bold text-slate-500 bg-slate-100 rounded-full px-1.5 py-0.5 mr-1.5",children:[e.jsx(Aa,{className:"w-2.5 h-2.5"})," תושבים"]})]}),e.jsxs("span",{className:"block text-[11.5px] text-slate-400",children:[kt(_.kind).l," · ",Js(_)]})]}),T&&p.sectioned&&e.jsxs("select",{className:"h-9 rounded-lg border border-slate-200 text-[12.5px] px-2 text-slate-700 flex-none max-w-[11rem]",value:p.categoryOf[_.id]||"",onClick:M=>M.preventDefault(),onChange:M=>u(B=>({...B,categoryOf:{...B.categoryOf,[_.id]:M.target.value}})),children:[e.jsx("option",{value:"",children:"— קטגוריה —"}),p.categories.map(M=>e.jsx("option",{value:M.id,children:M.title||"ללא שם"},M.id))]})]})},_.id)})]})]}),r===2&&e.jsxs("div",{className:"space-y-4 pb-2",children:[e.jsxs(Q,{label:"מי יכול לפתוח את הקטלוג",children:[e.jsx("div",{className:"flex gap-2",children:[{v:"public",l:"ציבורי",icon:ca,hint:"כל מי שיקבל את הקישור"},{v:"residents",l:"תושבים בלבד",icon:Aa,hint:"נדרשת התחברות לאזור האישי"}].map(_=>{const T=_.icon,M=p.visibility===_.v;return e.jsxs("button",{type:"button",onClick:()=>d("visibility",_.v),className:`flex-1 rounded-xl border p-3 text-right transition-colors ${M?"border-teal-400 bg-teal-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[13px] font-bold text-slate-800",children:[e.jsx(T,{className:`w-4 h-4 ${M?"text-teal-600":"text-slate-400"}`})," ",_.l,M&&e.jsx(ye,{className:"w-3.5 h-3.5 text-teal-600 mr-auto"})]}),e.jsx("span",{className:"block text-[11px] text-slate-400 mt-0.5",children:_.hint})]},_.v)})}),w&&e.jsx("p",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mt-2",children:"בקטלוג נבחרו עמודים שסומנו «תושבים בלבד». הם יוצגו בו לכל מי שפותח את הקישור — שם, מחיר ותיאור — והתשלום עצמו יבקש מהם להתחבר."})]}),e.jsx(Q,{label:"מיקום באתר הקהילה",children:e.jsx(Qo,{options:wo,value:p,disabled:p.visibility==="residents",onChange:(_,T)=>d(_,T),note:p.visibility==="residents"?"מיקום באתר זמין לקטלוג ציבורי בלבד.":""})})]})]})}const Ri={one_time:Oe,recurring:Mt,recurring_debt:nt,open_amount:rt};function Mh({pages:t,catalogs:s,items:n,onChanged:a}){const[l,r]=i.useState([]),[o,p]=i.useState(null),[u,d]=i.useState([]),c=i.useMemo(()=>(s||[]).filter(f=>f.show_in_menu||f.show_on_home||f.show_in_personal),[s]),m=f=>Number(f.placement_order)||0||Number.MAX_SAFE_INTEGER;i.useEffect(()=>{const f=[...(t||[]).filter(x=>x.show_in_menu||x.show_on_home||x.show_in_personal).map(x=>({...x,_kind:"page"})),...(s||[]).filter(x=>x.show_in_menu||x.show_on_home||x.show_in_personal).map(x=>({...x,_kind:"catalog"}))].sort((x,g)=>m(x)-m(g)||String(x.title).localeCompare(String(g.title),"he"));r(f)},[t,s]),i.useEffect(()=>{if(!o){d([]);return}const f=new Map((t||[]).map(x=>[x.id,x]));d((n||[]).filter(x=>x.catalog_id===o.id).sort((x,g)=>(x.sort_order||0)-(g.sort_order||0)).map(x=>({...x,page:f.get(x.payment_page_id)})).filter(x=>x.page))},[o,n,t]);const h=async f=>{r(f);const x=Rr(f,{orderKey:"placement_order"});if(x.length)try{await Promise.all(x.map(g=>{const y=f.find(O=>O.id===g.id),$=(y==null?void 0:y._kind)==="catalog"?"PaymentCatalog":"PaymentPage";return D.entities[$].update(g.id,{placement_order:g.placement_order})})),a==null||a()}catch{W.error("סדר התצוגה לא נשמר")}},b=async f=>{d(f);const x=Rr(f,{orderKey:"sort_order"});if(x.length)try{await Promise.all(x.map(g=>D.entities.PaymentCatalogItem.update(g.id,{sort_order:g.sort_order}))),a==null||a()}catch{W.error("הסדר בקטלוג לא נשמר")}};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 items-start",children:[e.jsx(qi,{title:"סדר התצוגה ברצועה",hint:"לחצו על שורה כדי לסמן אותה, וגררו אותה למעלה או למטה.",children:e.jsx(zi,{items:l,onReorder:h,empty:"אין עדיין עמוד או קטלוג שסומן להצגה באתר.",renderRow:f=>e.jsx(Ki,{icon:f._kind==="catalog"?gs:Ri[f.kind]||Oe,title:f.title,sub:f._kind==="catalog"?"קטלוג תשלום":`${kt(f.kind).l} · ${Js(f)}`,badges:e.jsxs(e.Fragment,{children:[(f.show_in_menu||f.show_on_home)&&e.jsx(Ii,{icon:ca,label:"באתר"}),f.show_in_personal&&e.jsx(Ii,{icon:ys,label:"מרחב אישי"})]})})})}),e.jsx(qi,{title:"סדר הפריטים בקטלוג",hint:"בחרו קטלוג, ואז סמנו עמוד וגררו אותו למקומו.",children:c.length===0?e.jsx("p",{className:"text-[12.5px] text-slate-400 py-6 text-center",children:"אין קטלוג שמוצג באתר."}):e.jsx("div",{className:"space-y-2",children:c.map(f=>{const x=(o==null?void 0:o.id)===f.id,g=(n||[]).filter(y=>y.catalog_id===f.id).length;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>p(x?null:f),className:`w-full flex items-center gap-2.5 p-3 rounded-xl border text-right transition-colors ${x?"border-teal-400 bg-teal-50":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx("span",{className:"w-9 h-9 rounded-lg grid place-items-center flex-none bg-teal-50 text-teal-600 border border-teal-200",children:e.jsx(gs,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800 truncate",children:f.title}),e.jsxs("span",{className:"block text-[11.5px] text-slate-400",children:[g," פריטים"]})]}),e.jsx(lt,{className:`w-4 h-4 text-slate-400 transition-transform ${x?"-rotate-90":""}`})]}),x&&e.jsx("div",{className:"mt-2 mr-4 border-r-2 border-teal-100 pr-3",children:e.jsx(zi,{items:u,onReorder:b,empty:"אין עמודים בקטלוג הזה.",renderRow:y=>e.jsx(Ki,{icon:Ri[y.page.kind]||Oe,title:y.page.title,sub:`${kt(y.page.kind).l} · ${Js(y.page)}`})})})]},f.id)})})})]})}
56function qi({title:t,hint:s,children:n}){return e.jsxs("section",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-4",children:[e.jsx("h4",{className:"text-[14px] font-black text-slate-900",children:t}),e.jsx("p",{className:"text-[12px] text-slate-400 mt-0.5 mb-3",children:s}),n]})}function Ii({icon:t,label:s}){return e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10.5px] font-bold px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 whitespace-nowrap",children:[e.jsx(t,{className:"w-2.5 h-2.5"})," ",s]})}const Ph=8;function zi({items:t,onReorder:s,renderRow:n,empty:a}){const l=i.useRef(null),r=i.useRef(null),[o,p]=i.useState(null),[u,d]=i.useState(null),c=(x,g)=>y=>{var O,A,S;if(y.button!=null&&y.button!==0)return;p(g),(A=(O=y.currentTarget).focus)==null||A.call(O);const $=Array.from(((S=l.current)==null?void 0:S.children)||[]).map(P=>{const E=P.getBoundingClientRect();return{height:E.height,center:E.top+E.height/2}});r.current={rows:$,y0:y.clientY,from:x};try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}d({from:x,to:x,dy:0})},m=x=>{var P;const g=r.current;if(!g)return;const y=x.clientY-g.y0,{rows:$,from:O}=g,A=(((P=$[O])==null?void 0:P.center)||0)+y;let S=O;if(y>0)for(let E=O+1;E<$.length;E+=1)A>$[E].center&&(S=E);else for(let E=O-1;E>=0;E-=1)A<$[E].center&&(S=E);d({from:O,to:S,dy:y})},h=()=>{const x=u;r.current=null,d(null),x&&x.to!==x.from&&s(Br(t,x.from,x.to))},b=x=>{var y;if(!u||!r.current||x===u.from)return 0;const g=(((y=r.current.rows[u.from])==null?void 0:y.height)||0)+Ph;return u.to>u.from&&x>u.from&&x<=u.to?-g:u.to<u.from&&x>=u.to&&x<u.from?g:0},f=x=>g=>{if(g.key!=="ArrowUp"&&g.key!=="ArrowDown"&&g.key!=="Escape")return;if(g.preventDefault(),g.key==="Escape"){p(null);return}const y=x+(g.key==="ArrowDown"?1:-1);y>=0&&y<t.length&&s(Br(t,x,y))};return t.length?e.jsx("div",{ref:l,className:"space-y-2 select-none",children:t.map((x,g)=>{const y=(u==null?void 0:u.from)===g,$=o===x.id;return e.jsxs("div",{role:"button",tabIndex:0,"aria-label":`שינוי מיקום, ${g+1} מתוך ${t.length}`,onPointerDown:c(g,x.id),onPointerMove:y?m:void 0,onPointerUp:y?h:void 0,onPointerCancel:y?h:void 0,onKeyDown:f(g),style:{transform:`translateY(${y?u.dy:b(g)}px)`,transition:y?"none":"transform 160ms ease",touchAction:$?"none":"pan-y",zIndex:y?10:void 0,position:"relative"},className:`flex items-center gap-2.5 p-2.5 rounded-xl border outline-none ${y?"border-emerald-500 bg-emerald-50 shadow-lg cursor-grabbing":$?"border-emerald-400 bg-emerald-50 ring-1 ring-emerald-200 cursor-grab":"border-slate-200 bg-white hover:border-slate-300 cursor-grab"}`,children:[e.jsx(su,{className:`w-4 h-4 flex-none ${$?"text-emerald-500":"text-slate-300"}`}),n(x)]},x.id)})}):e.jsx("p",{className:"text-[12.5px] text-slate-400 py-6 text-center",children:a})}function Ki({icon:t,title:s,sub:n,badges:a}){return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-9 h-9 rounded-lg grid place-items-center flex-none bg-slate-50 text-slate-500 border border-slate-200",children:e.jsx(t,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-[13.5px] font-bold text-slate-800 truncate",children:s}),a]}),e.jsx("span",{className:"block text-[11.5px] text-slate-400 truncate",children:n})]})]})}const $c={one_time:Oe,recurring:Mt,recurring_debt:nt,open_amount:rt},Wi={indigo:"bg-indigo-50 text-indigo-600 border-indigo-200",emerald:"bg-emerald-50 text-emerald-600 border-emerald-200",amber:"bg-amber-50 text-amber-600 border-amber-200",violet:"bg-violet-50 text-violet-600 border-violet-200"},Ui={indigo:"text-indigo-600 bg-indigo-50",emerald:"text-emerald-600 bg-emerald-50",amber:"text-amber-600 bg-amber-50",violet:"text-violet-600 bg-violet-50"},Hi=()=>`pp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;function Eh({kibbutzId:t}){const[s,n]=i.useState(!0),[a,l]=i.useState([]),[r,o]=i.useState([]),[p,u]=i.useState([]),[d,c]=i.useState([]),[m,h]=i.useState(""),[b,f]=i.useState(null),[x,g]=i.useState(null),[y,$]=i.useState(null),[O,A]=i.useState("pages"),[S,P]=i.useState(0),E=i.useCallback(()=>P(v=>v+1),[]);i.useEffect(()=>{if(!t)return;let v=!0;return n(!0),D.entities.PaymentPage.filterAll({kibbutz_id:t}).then(F=>{v&&l(F||[])}).catch(()=>{v&&W.error("שגיאה בטעינת עמודי התשלום")}).finally(()=>{v&&n(!1)}),()=>{v=!1}},[t,S]),i.useEffect(()=>{if(!t)return;let v=!0;return D.entities.PaymentCatalog.filterAll({kibbutz_id:t}).then(F=>{v&&o(F||[])}).catch(()=>{}),D.entities.PaymentCatalogItem.filterAll({kibbutz_id:t}).then(F=>{v&&u(F||[])}).catch(()=>{}),()=>{v=!1}},[t,S]),i.useEffect(()=>{if(!t)return;let v=!0;return D.entities.ChargeType.filterAll({kibbutz_id:t},"order").then(F=>{v&&c(F||[])}).catch(()=>{}),D.entities.Kibbutz.get(t).then(F=>{v&&h((F==null?void 0:F.name)||"")}).catch(()=>{}),()=>{v=!1}},[t]);const k=i.useMemo(()=>{const v=new Map;
56return(p||[]).forEach(F=>{v.has(F.catalog_id)||v.set(F.catalog_id,[]),v.get(F.catalog_id).push(F)}),v},[p]),C=i.useMemo(()=>O==="pages"?a:a.filter(v=>(v.kind||"one_time")===O),[a,O]),w=async v=>{var Z;const F=!v.id,K={kibbutz_id:t,kind:v.kind,title:v.title.trim(),description:((Z=v.description)==null?void 0:Z.trim())||null,price:kt(v.kind).fields.price&&v.price!==""?Number(v.price):null,months_limit:kt(v.kind).fields.months&&v.months_limit!==""?Number(v.months_limit):null,image_url:kt(v.kind).fields.image&&v.image_url||null,charge_type_id:v.kind==="recurring_debt"&&v.charge_type_id||null,max_purchases:v.max_purchases===""?null:Number(v.max_purchases),closes_at:v.closes_at?new Date(v.closes_at).toISOString():null,visibility:v.visibility||"public",show_in_menu:v.visibility!=="residents"&&!!v.show_in_menu,show_on_home:v.visibility!=="residents"&&!!v.show_on_home,show_in_personal:!!v.show_in_personal,is_active:!0};try{F?(await D.entities.PaymentPage.create({...K,id:Hi(),slug:Or(v.title,a.map(H=>H.slug))}),W.success("דף התשלום נוצר")):(await D.entities.PaymentPage.update(v.id,K),W.success("דף התשלום עודכן")),f(null),E()}catch{W.error("שגיאה בשמירה")}},_=async(v,F)=>{try{await D.entities.PaymentPage.update(v.id,{visibility:F}),l(K=>K.map(Z=>Z.id===v.id?{...Z,visibility:F}:Z)),W.success(F==="public"?"הדף ציבורי":"הדף פתוח לתושבים מחוברים בלבד")}catch{W.error("שגיאה בעדכון")}},T=async(v,F,K)=>{const Z=v==="catalog"?"PaymentCatalog":"PaymentPage",H=v==="catalog"?o:l;try{await D.entities[Z].update(F.id,K);const z=await D.entities[Z].get(F.id).catch(()=>null),te=z||{...F,...K};H(V=>V.map(Y=>Y.id===F.id?{...Y,...te}:Y)),z&&Object.entries(K).some(([V,Y])=>!!z[V]!=!!Y)&&W.error("העדכון לא נשמר — יש לרענן ולנסות שוב")}catch{W.error("שגיאה בעדכון")}},M=async v=>{const F=(p||[]).filter(Z=>Z.payment_page_id===v.id).length,K=F?`
57העמוד מוצג ב-${F} קטלוגים, ויוסר גם מהם.`:"";if(window.confirm(`למחוק את «${v.title}»? הקישור שנשלח יפסיק לעבוד.${K}`))try{await D.entities.PaymentPage.delete(v.id),l(Z=>Z.filter(H=>H.id!==v.id)),u(Z=>Z.filter(H=>H.payment_page_id!==v.id)),W.success("דף התשלום נמחק")}catch{W.error("שגיאה במחיקה")}},B=async v=>{var Z;const F=!v.id,K={kibbutz_id:t,title:v.title.trim(),description:((Z=v.description)==null?void 0:Z.trim())||null,image_url:v.image_url||null,categories:v.categories||[],visibility:v.visibility||"public",show_in_menu:v.visibility!=="residents"&&!!v.show_in_menu,show_on_home:v.visibility!=="residents"&&!!v.show_on_home,show_in_personal:!!v.show_in_personal,is_active:!0};try{const H=v.id||Hi().replace(/^pp-/,"pc-");F?await D.entities.PaymentCatalog.create({...K,id:H,slug:Or(v.title,r.map(V=>V.slug))}):await D.entities.PaymentCatalog.update(H,K);const z=(p||[]).filter(V=>V.catalog_id===H),te=new Map(z.map(V=>[V.payment_page_id,V])),ie=new Set(v.pageIds);await Promise.all(z.filter(V=>!ie.has(V.payment_page_id)).map(V=>D.entities.PaymentCatalogItem.delete(V.id).catch(()=>{}))),await Promise.all(v.pageIds.map((V,Y)=>{var X;const J=te.get(V),I={category_id:((X=v.categoryOf)==null?void 0:X[V])||null,sort_order:Y};return J?D.entities.PaymentCatalogItem.update(J.id,I).catch(()=>{}):D.entities.PaymentCatalogItem.create({id:`pci-${H.slice(-6)}-${Y}-${Math.random().toString(36).slice(2,6)}`,kibbutz_id:t,catalog_id:H,payment_page_id:V,...I}).catch(()=>{})})),W.success(F?"הקטלוג נוצר":"הקטלוג עודכן"),g(null),A("catalogs"),E()}catch{W.error("שגיאה בשמירת הקטלוג")}},R=async(v,F)=>{try{await D.entities.PaymentCatalog.update(v.id,{visibility:F}),o(K=>K.map(Z=>Z.id===v.id?{...Z,visibility:F}:Z)),W.success(F==="public"?"הקטלוג ציבורי":"הקטלוג פתוח לתושבים מחוברים בלבד")}catch{W.error("שגיאה בעדכון")}},j=async v=>{if(window.confirm(`למחוק את הקטלוג «${v.title}»? הקישור שנשלח יפסיק לעבוד. עמודי התשלום עצמם יישארו.`))try{await D.entities.PaymentCatalog.delete(v.id),o(F=>F.filter(K=>K.id!==v.id)),u(F=>F.filter(K=>K.catalog_id!==v.id)),W.success("הקטלוג נמחק")}catch{W.error("שגיאה במחיקה")}},q=v=>{const F=`${window.location.origin}${yn(gr(t,v.slug))}`;$({title:v.title,subtitle:`${kt(v.kind).l} · ${Js(v)}`,url:F,message:Td({page:v,url:F,communityName:m}),imageUrl:v.image_url||"",note:v.visibility==="residents"?"הדף פתוח לתושבים מחוברים בלבד — מי שאינו מזוהה יתבקש להתחבר.":""})},L=v=>{const F=`${window.location.origin}${yn(ko(t,v.slug))}`,K=(k.get(v.id)||[]).length;$({title:v.title,subtitle:`קטלוג תשלום · ${K} פריטים`,url:F,message:Bd({catalog:v,url:F,communityName:m,count:K}),imageUrl:v.image_url||"",note:v.visibility==="residents"?"הקטלוג פתוח לתושבים מחוברים בלבד — מי שאינו מזוהה יתבקש להתחבר.":""})};zu(e.jsx(Fh,{onPage:()=>f({}),onCatalog:()=>g({}),onArrange:()=>A("arrange")}),[]);const N=[{v:"pages",l:"עמודי תשלום",n:a.length,icon:Zt,tone:"text-emerald-600 bg-emerald-50"},{v:"catalogs",l:"קטלוג תשלום",n:r.length,icon:gs,tone:"text-teal-600 bg-teal-50"},...fr.map(v=>({v:v.v,l:v.l,n:a.filter(F=>
57(F.kind||"one_time")===v.v).length,icon:$c[v.v]||Oe,tone:Ui[v.tone]||Ui.indigo}))];return e.jsxs("div",{dir:"rtl",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-2.5 mb-5",children:N.map(v=>{const F=v.icon,K=O===v.v;return e.jsxs("button",{type:"button",onClick:()=>A(v.v),"aria-pressed":K,className:`rounded-2xl border bg-white p-3 text-right transition-all ${K?"border-teal-500 ring-2 ring-teal-100 shadow-sm":"border-slate-200 hover:border-slate-300 hover:shadow-sm"}`,children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[19px] font-black text-slate-900 tabular-nums",children:v.n}),e.jsx("span",{className:`w-8 h-8 rounded-xl grid place-items-center flex-none mr-auto ${v.tone}`,children:e.jsx(F,{className:"w-4 h-4"})})]}),e.jsx("span",{className:"block text-[12.5px] font-bold text-slate-600 mt-1.5 leading-tight",children:v.l})]},v.v)})}),s?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-emerald-500 rounded-full animate-spin"})}):O==="arrange"?e.jsx(Mh,{pages:a,catalogs:r,items:p,onChanged:E}):O==="catalogs"?e.jsx(Oh,{catalogs:r,itemsByCatalog:k,pages:a,kibbutzId:t,onNew:()=>g({}),onEdit:g,onShare:L,onVisibility:R,onDelete:j,onPlacement:(v,F)=>T("catalog",v,F)}):e.jsx(Dh,{rows:C,kibbutzId:t,everything:a.length===0,onNew:()=>f({}),onEdit:f,onShare:q,onVisibility:_,onDelete:M,onPlacement:(v,F)=>T("page",v,F)}),b&&e.jsx(Lh,{page:b,types:d,onClose:()=>f(null),onSave:w}),x&&e.jsx(Ah,{catalog:x,pages:a,items:k.get(x.id)||[],onClose:()=>g(null),onSave:B}),y&&e.jsx(Th,{share:y,kibbutzId:t,onClose:()=>$(null)})]})}function Fh({onPage:t,onCatalog:s,onArrange:n}){const[a,l]=i.useState(!1),r=i.useRef(null),o="w-full flex items-start gap-2.5 px-3.5 py-3 text-right hover:bg-slate-50";return e.jsxs("div",{className:"relative flex-none",ref:r,children:[e.jsxs("button",{type:"button",onClick:()=>l(p=>!p),"aria-haspopup":"menu","aria-expanded":a,className:"h-11 px-5 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-bold inline-flex items-center gap-2 transition-colors",children:[e.jsx(Hn,{className:"w-4 h-4"})," פעולות נוספות",e.jsx(Jt,{className:`w-4 h-4 transition-transform ${a?"rotate-180":""}`})]}),e.jsx(ma,{anchorRef:r,open:a,onClose:()=>l(!1),width:"17rem",children:e.jsxs("div",{className:"overflow-hidden rounded-2xl",role:"menu",children:[e.jsxs("button",{className:o,onClick:()=>{l(!1),t()},children:[e.jsx(We,{className:"w-4 h-4 text-emerald-600 mt-0.5 flex-none"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800",children:"עמוד תשלום חדש"}),e.jsx("span",{className:"block text-[11.5px] text-slate-400",children:"קישור אחד לדבר אחד"})]})]}),e.jsxs("button",{className:`${o} border-t border-slate-100`,onClick:()=>{l(!1),s()},children:[e.jsx(gs,{className:"w-4 h-4 text-teal-600 mt-0.5 flex-none"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800",children:"קטלוג תשלום חדש"}),e.jsx("span",{className:"block text-[11.5px] text-slate-400",children:"קישור אחד שמציג כמה עמודי תשלום"})]})]}),e.jsxs("button",{className:`${o} border-t border-slate-100`,onClick:()=>{l(!1),n()},children:[e.jsx(iu,{className:"w-4 h-4 text-slate-500 mt-0.5 flex-none"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-[13.5px] font-bold text-slate-800",children:"ניהול סדר ותצוגות"}),e.jsx("span",{className:"block text-[11.5px] text-slate-400",children:"באיזה סדר הם רצים באתר, ומה הסדר בתוך קטלוג"})]})]})]})})]})}const st="text-right text-[12px] font-black text-slate-500 px-3 py-2.5 whitespace-nowrap",at="px-3 py-3 text-[13px] text-slate-700 align-middle";function rr({icon:t,title:s,text:n,action:a,onAction:l}){return e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm p-12 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-emerald-50 flex items-center justify-center mx-auto mb-3",children:e.jsx(t,{className:"w-7 h-7 text-emerald-500"})}),e.jsx("h4",{className:"text-base font-bold mb-1",children:s}),e.jsx("p",{className:"text-sm text-slate-500 max-w-md mx-auto",children:n}
57),a&&e.jsxs("button",{onClick:l,className:"mt-4 h-10 px-4 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-bold inline-flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4"})," ",a]})]})}function Cc({href:t,onShare:s,onEdit:n,onDelete:a,children:l}){return e.jsxs("span",{className:"flex items-center gap-1.5",children:[l,e.jsxs("a",{href:t,target:"_blank",rel:"noreferrer",title:"צפייה","aria-label":"צפייה",className:"h-8 px-2.5 rounded-lg border border-slate-200 text-[12.5px] font-bold text-slate-600 inline-flex items-center gap-1.5 hover:bg-slate-50",children:[e.jsx(fs,{className:"w-4 h-4"})," צפייה"]}),e.jsxs("button",{onClick:s,title:"שיתוף","aria-label":"שיתוף",className:"h-8 px-2.5 rounded-lg bg-emerald-50 text-emerald-700 text-[12.5px] font-bold inline-flex items-center gap-1.5 hover:bg-emerald-100",children:[e.jsx(ru,{className:"w-4 h-4"})," שתף"]}),e.jsx("button",{onClick:n,title:"עריכה","aria-label":"עריכה",className:"w-8 h-8 rounded-lg border border-slate-200 grid place-items-center text-slate-500 hover:bg-slate-50 hover:text-slate-700",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:a,title:"מחיקה","aria-label":"מחיקה",className:"w-8 h-8 rounded-lg border border-slate-200 grid place-items-center text-slate-400 hover:bg-red-50 hover:text-red-600 hover:border-red-200",children:e.jsx(Re,{className:"w-4 h-4"})})]})}function Ac({row:t,onChange:s}){const n=!!(t.show_in_menu||t.show_on_home),a=l=>`w-8 h-8 rounded-lg border grid place-items-center transition-colors ${l?"border-emerald-300 bg-emerald-50 text-emerald-600 hover:bg-emerald-100":"border-slate-200 text-slate-300 hover:bg-slate-50 hover:text-slate-500"}`;return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:a(n),"aria-pressed":n,title:n?"מוצג באתר הקהילה — לחצו כדי להסיר":"אינו מוצג באתר — לחצו כדי להציג בעמוד הבית",onClick:()=>s(t,n?{show_in_menu:!1,show_on_home:!1}:{show_on_home:!0}),children:e.jsx(ca,{className:"w-4 h-4"})}),e.jsx("button",{type:"button",className:a(!!t.show_in_personal),"aria-pressed":!!t.show_in_personal,title:t.show_in_personal?"מוצג במרחב האישי — לחצו כדי להסיר":"אינו מוצג במרחב האישי — לחצו כדי להציג",onClick:()=>s(t,{show_in_personal:!t.show_in_personal}),children:e.jsx(ys,{className:"w-4 h-4"})})]})}function Mc({href:t}){const[s,n]=i.useState(!1),a=async()=>{try{await navigator.clipboard.writeText(`${window.location.origin}${t}`),n(!0),setTimeout(()=>n(!1),1600),W.success("הקישור הועתק")}catch{W.error("לא ניתן להעתיק")}};return e.jsx("button",{type:"button",onClick:a,"aria-label":"העתקת הקישור",title:t,className:`w-8 h-8 rounded-lg border grid place-items-center transition-colors ${s?"border-emerald-300 bg-emerald-50 text-emerald-600":"border-slate-200 text-slate-400 hover:bg-slate-50 hover:text-slate-700"}`,children:s?e.jsx(ye,{className:"w-4 h-4"}):e.jsx(Eo,{className:"w-4 h-4"})})}function Pc({value:t,onChange:s}){const n=t!=="residents";return e.jsxs("button",{type:"button",role:"switch","aria-checked":n,onClick:()=>s(n?"residents":"public"),title:n?"ציבורי — לחצו כדי להגביל לתושבים":"לתושבים בלבד — לחצו כדי לפתוח לכולם",className:`inline-flex items-center gap-1.5 h-8 px-2 rounded-full border text-[11.5px] font-bold transition-colors ${n?"bg-sky-50 border-sky-200 text-sky-700":"bg-slate-100 border-slate-200 text-slate-500"}`,children:[e.jsx("span",{className:`w-8 h-4 rounded-full relative transition-colors flex-none ${n?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute top-0.5 w-3 h-3 rounded-full bg-white transition-all ${n?"right-0.5":"right-4.5"}`})}),n?e.jsx(ca,{className:"w-3 h-3"}):e.jsx(Aa,{className:"w-3 h-3"}),n?"ציבורי":"תושבים"]})}function Dh({rows:t,kibbutzId:s,everything:n,onNew:a,onEdit:l,onShare:r,onVisibility:o,onDelete:p,onPlacement:u}){return t.length?e.jsx("div",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:st,children:"שם הדף"}),e.jsx("th",{className:st,children:"סוג"}),e.jsx("th",{className:st,children:"עלות"}),e.jsx("th",{className:st,children:"נראות"}),e.jsx("th",{className:st,children:"קישור"}),e.jsx("th",{className:st,children:"פעולות"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:t.map(d=>{const c=kt(d.kind),m=$c[c.v]||Oe,h=yn(gr(s,d.slug)),b=qd(d);return e.jsxs("tr",{className:"hover:bg-slate-50/60",children:[e.jsx("td",{className:at,children:e.jsxs("span",{className:"flex items-center gap-2.5 min-w-0",children:[d.image_url?e.jsx("img",{src:d.image_url,alt:"",className:"w-9 h-9 rounded-lg object-cover flex-none border border-slate-200"}):e.jsx("span",{className:`w-9 h-9 rounded-lg grid place-items-center flex-none border ${Wi[c.tone]||Wi.indigo}`,children:e.jsx(m,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"font-bold text-slate-900 truncate",children:d.title}),!b.open&&e.jsx("span",{className:"flex-none text-[10.5px] font-bold px-1.5 py-0.5 rounded-full bg-red-50 text-red-600 border border-red-200 whitespace-nowrap",title:b.label,children:b.reason==="sold_out"?"אזל":"נסגר"})]}),d.description&&e.jsx("span",{className:"block text-[11.5px] text-slate-400 truncate max-w-[22rem]",children:d.description})]})]})}),e.jsx("td",{className:`${at}
57 text-slate-500 whitespace-nowrap`,children:c.l}),e.jsxs("td",{className:`${at} font-bold whitespace-nowrap`,children:[Js(d),b.open&&b.remaining!==null&&e.jsxs("span",{className:"block text-[11px] font-bold text-amber-600",children:["נותרו ",b.remaining]}),d.closes_at&&b.open&&e.jsxs("span",{className:"block text-[11px] text-slate-400",children:["עד ",Id(d.closes_at)]})]}),e.jsx("td",{className:at,children:e.jsx(Pc,{value:d.visibility,onChange:f=>o(d,f)})}),e.jsx("td",{className:at,children:e.jsx(Mc,{href:h})}),e.jsx("td",{className:at,children:e.jsx(Cc,{href:h,onShare:()=>r(d),onEdit:()=>l(d),onDelete:()=>p(d),children:e.jsx(Ac,{row:d,onChange:u})})})]},d.id)})})]})})}):n?e.jsx(rr,{icon:Zt,title:"עדיין אין עמודי תשלום",text:"עמוד תשלום הוא קישור עצמאי: הוא אינו תלוי בחשבון משלם, ואפשר לשלוח אותו בוואטסאפ למי שאינו תושב.",action:"עמוד תשלום חדש",onAction:a}):e.jsx(rr,{icon:Zt,title:"אין עמודים מסוג זה",text:"בחרו כרטיסייה אחרת, או צרו עמוד חדש מהסוג הזה.",action:"עמוד תשלום חדש",onAction:a})}function Oh({catalogs:t,itemsByCatalog:s,pages:n,kibbutzId:a,onNew:l,onEdit:r,onShare:o,onVisibility:p,onDelete:u,onPlacement:d}){return t.length?e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:st,children:"שם הקטלוג"}),e.jsx("th",{className:st,children:"פריטים"}),e.jsx("th",{className:st,children:"קטגוריות"}),e.jsx("th",{className:st,children:"נראות"}),e.jsx("th",{className:st,children:"קישור"}),e.jsx("th",{className:st,children:"פעולות"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:t.map(c=>{const m=s.get(c.id)||[],h=Array.isArray(c.categories)?c.categories:[],b=yn(ko(a,c.slug)),f=Rd({categories:h,items:m,pages:n}).reduce((x,g)=>x+g.pages.length,0);return e.jsxs("tr",{className:"hover:bg-slate-50/60",children:[e.jsx("td",{className:at,children:e.jsxs("span",{className:"flex items-center gap-2.5 min-w-0",children:[c.image_url?e.jsx("img",{src:c.image_url,alt:"",className:"w-9 h-9 rounded-lg object-cover flex-none border border-slate-200"}):e.jsx("span",{className:"w-9 h-9 rounded-lg grid place-items-center flex-none border bg-teal-50 text-teal-600 border-teal-200",children:e.jsx(gs,{className:"w-4 h-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-bold text-slate-900 truncate",children:c.title}),c.description&&e.jsx("span",{className:"block text-[11.5px] text-slate-400 truncate max-w-[22rem]",children:c.description})]})]})}),e.jsxs("td",{className:`${at} font-bold tabular-nums`,children:[f,f!==m.length&&e.jsxs("span",{className:"text-[11px] text-slate-400",children:[" / ",m.length]})]}),e.jsx("td",{className:`${at} text-slate-500`,children:h.length?h.map(x=>x.title).filter(Boolean).join(" · "):e.jsx("span",{className:"text-slate-300",children:"ללא קטגוריות"})}),e.jsx("td",{className:at,children:e.jsx(Pc,{value:c.visibility,onChange:x=>p(c,x)})}),e.jsx("td",{className:at,children:e.jsx(Mc,{href:b})}),e.jsx("td",{className:at,children:e.jsx(Cc,{href:b,onShare:()=>o(c),onEdit:()=>r(c),onDelete:()=>u(c),children:e.jsx(Ac,{row:c,onChange:d})})})]},c.id)})})]})}),e.jsx("p",{className:"px-4 py-2.5 text-[11.5px] text-slate-400 border-t border-slate-100",children:"קטלוג ציבורי מציג גם עמוד שסומן «תושבים בלבד» — הפריט נראה לכל מי שפותח את הקישור, והתשלום עצמו דורש התחברות."})]}):e.jsx(rr,{icon:gs,title:"עדיין אין קטלוגים",text:"קטלוג הוא קישור אחד שמציג כמה עמודי תשלום יחד — עונת החוגים, מכירת סוף שנה, רשימת המנויים — בעיצוב אתר הקהילה, ואם רוצים גם מחולק לקטגוריות.",action:"קטלוג תשלום חדש",onAction:l})}function Lh({page:t,types:s,onClose:n,onSave:a}){const[l,r]=i.useState(0),[o,p]=i.useState(()=>({id:t.id,kind:t.kind||"one_time",title:t.title||"",description:t.description||"",price:t.price??"",months_limit:t.months_limit??"",max_purchases:t.max_purchases??"",closes_at:zd(t.closes_at),image_url:t.image_url||"",charge_type_id:t.charge_type_id||"",visibility:t.visibility||"public",show_in_menu:!!t.show_in_menu,show_on_home:!!t.show_on_home,show_in_personal:!!t.show_in_personal})),u=($,O)=>p(A=>({...A,[$]:O})),[d,c]=i.useState(!1),[m,h]=i.useState(!1),b=kt(o.kind),f=o.visibility!=="residents",x=async $=>{if($){c(!0);try{const{file_url:O}=await D.integrations.Core.UploadFile({file:$});u("image_url",O),W.success("התמונה הועלתה")}catch{W.error("שגיאה בהעלאת התמונה")}finally{c(!1)}}},g=$=>{if($>l&&!o.title.trim()){W.error("יש להזין שם למוצר/השירות");return}r($)}
57,y=async()=>{if(!o.title.trim()){r(0),W.error("יש להזין שם למוצר/השירות");return}h(!0),await a(o),h(!1)};return e.jsx(_r,{title:o.id?"עריכת דף תשלום":"יצירת דף תשלום",icon:Oe,steps:["מה נמכר","תצוגה ונראות"],step:l,onStep:g,onClose:n,onSubmit:y,submitting:m,children:l===0?e.jsxs("div",{className:"space-y-4 pb-2",children:[e.jsxs(Q,{label:"סוג קישור",children:[e.jsx("select",{className:Se,value:o.kind,onChange:$=>u("kind",$.target.value),disabled:!!o.id,children:fr.map($=>e.jsx("option",{value:$.v,children:$.l},$.v))}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-1",children:o.id?"סוג הקישור נקבע ביצירה ואינו משתנה.":b.hint})]}),e.jsx(Q,{label:"שם המוצר/השירות",required:!0,children:e.jsx("input",{className:Se,value:o.title,onChange:$=>u("title",$.target.value),placeholder:"הזן שם",autoFocus:!0})}),e.jsx(Q,{label:"תיאור",hint:"יוצג בעמוד התשלום עצמו",children:e.jsx("textarea",{className:ua,rows:2,value:o.description,onChange:$=>u("description",$.target.value),placeholder:"הערות, מה כולל התשלום, מועדים…"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[b.fields.price&&e.jsx(Q,{label:"מחיר ללקוח/ה",children:e.jsx("input",{type:"number",min:"0",step:"0.01",className:Se,value:o.price,onChange:$=>u("price",$.target.value),placeholder:"0.00"})}),b.fields.months&&e.jsx(Q,{label:"כמות חודשי חיוב",hint:"ריק = ללא הגבלה",children:e.jsx("input",{type:"number",min:"1",step:"1",className:Se,value:o.months_limit,onChange:$=>u("months_limit",$.target.value),placeholder:"ללא הגבלה"})}),e.jsx(Q,{label:"הגבלת כמות רכישות",hint:"ריק = ללא הגבלה. בהגיע למספר — העמוד נסגר",children:e.jsx("input",{type:"number",min:"1",step:"1",className:Se,value:o.max_purchases,onChange:$=>u("max_purchases",$.target.value),placeholder:"ללא הגבלה"})}),e.jsx(Q,{label:"מועד סגירה",hint:"ריק = ללא מועד. אחריו העמוד לא יגבה",children:e.jsx("input",{type:"datetime-local",className:Se,value:o.closes_at,onChange:$=>u("closes_at",$.target.value)})})]}),o.kind==="recurring_debt"&&e.jsx(Q,{label:"סוג חיוב",info:"החיוב שייווצר יירשם תחת סוג זה ויופיע בדוחות לצידו",children:e.jsxs("select",{className:Se,value:o.charge_type_id,onChange:$=>u("charge_type_id",$.target.value),children:[e.jsx("option",{value:"",children:"— ללא —"}),s.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]})})]}):e.jsxs("div",{className:"space-y-4 pb-2",children:[b.fields.image&&e.jsxs(Q,{label:"תמונה ראשית",children:[e.jsxs("label",{className:`${Se} flex items-center gap-2 cursor-pointer ${d?"opacity-60":""}`,children:[e.jsx(jn,{className:"w-4 h-4 text-slate-400 flex-none"}),e.jsx("span",{className:`truncate ${o.image_url?"text-slate-700":"text-slate-400"}`,children:d?"מעלה…":o.image_url?"תמונה נבחרה":"בחירת קובץ"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:$=>{var O;return x((O=$.target.files)==null?void 0:O[0])}})]}),o.image_url&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("img",{src:o.image_url,alt:"",className:"w-16 h-16 rounded-lg object-cover border border-slate-200"}),e.jsx("button",{type:"button",onClick:()=>u("image_url",""),className:"text-[12px] text-red-600 font-bold",children:"הסרה"})]})]}),e.jsx(Q,{label:"מי יכול לפתוח את הקישור",children:e.jsx("div",{className:"flex gap-2",children:[{v:"public",l:"ציבורי",icon:ca,hint:"כל מי שיקבל את הקישור"},{v:"residents",l:"תושבים בלבד",icon:Aa,hint:"נדרשת התחברות לאזור האישי"}].map($=>{const O=$.icon,A=o.visibility===$.v;return e.jsxs("button",{type:"button",onClick:()=>u("visibility",$.v),className:`flex-1 rounded-xl border p-3 text-right transition-colors ${A?"border-teal-400 bg-teal-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[13px] font-bold text-slate-800",children:[e.jsx(O,{className:`w-4 h-4 ${A?"text-teal-600":"text-slate-400"}`})," ",$.l,A&&e.jsx(ye,{className:"w-3.5 h-3.5 text-teal-600 mr-auto"})]}),e.jsx("span",{className:"block text-[11px] text-slate-400 mt-0.5",children:$.hint})]},$.v)})})}),e.jsx(Q,{label:"מיקום באתר הקהילה",children:e.jsx(Qo,{options:wo,value:o,disabled:!f,onChange:($,O)=>u($,O),note:f?"":"מיקום באתר זמין לעמוד ציבורי בלבד — עמוד לתושבים מוצג באזור האישי דרך הקישור עצמו."})})]})})}function Th({share:t,kibbutzId:s,onClose:n}
57){const a=zc(),{title:l,subtitle:r,url:o,message:p,imageUrl:u,note:d}=t,c=`${l}
58${r||""}
59${o}`,[m,h]=i.useState(!1),b=async()=>{try{await navigator.clipboard.writeText(o),h(!0),setTimeout(()=>h(!1),1800)}catch{W.error("לא ניתן להעתיק")}},f=()=>{a(`/kibbutz/${s}/send-message`,{state:{prefill:{title:l,content:p,imageUrl:u||"",linkUrl:lu(p,o),kind:u?au:nu}}})};return e.jsx("div",{className:"fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:n,dir:"rtl",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-md p-5",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"text-lg font-black text-slate-900",children:"שיתוף הקישור"}),e.jsx("button",{onClick:n,"aria-label":"סגירה",className:"w-9 h-9 rounded-full border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsxs("p",{className:"text-sm text-slate-500 mb-4",children:[l,r?` · ${r}`:""]}),d&&e.jsx("p",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mb-3",children:d}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("a",{href:`https://wa.me/?text=${encodeURIComponent(c)}`,target:"_blank",rel:"noreferrer",className:"flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 hover:bg-slate-50 transition-colors",children:[e.jsx("span",{className:"w-10 h-10 rounded-xl grid place-items-center flex-none bg-emerald-50 text-emerald-700",children:e.jsx(gn,{className:"w-5 h-5"})}),e.jsx("span",{className:"text-[14px] font-bold text-slate-800",children:"שיתוף בוואטסאפ"})]}),e.jsxs("button",{type:"button",onClick:f,className:"w-full flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 hover:bg-slate-50 transition-colors text-right",children:[e.jsx("span",{className:"w-10 h-10 rounded-xl grid place-items-center flex-none bg-blue-50 text-blue-700",children:e.jsx(Gs,{className:"w-5 h-5"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-bold text-slate-800",children:"שליחה בהודעה"}),e.jsx("span",{className:"block text-[11px] text-slate-400",children:"מודול שליחת הודעות — בחירת נמענים, ההודעה כבר כתובה"})]})]}),e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 p-3 rounded-xl border border-slate-200 hover:border-slate-300 hover:bg-slate-50 transition-colors text-right",children:[e.jsx("span",{className:"w-10 h-10 rounded-xl grid place-items-center flex-none bg-slate-100 text-slate-600",children:m?e.jsx(ye,{className:"w-5 h-5 text-emerald-600"}):e.jsx(Eo,{className:"w-5 h-5"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[14px] font-bold text-slate-800",children:m?"הקישור הועתק":"העתקת הקישור"}),e.jsx("span",{className:"block text-[11px] text-slate-400 truncate",dir:"ltr",children:o})]})]})]})]})})}function Bh({kibbutzId:t}){const[s,n]=i.useState([]),[a,l]=i.useState({}),[r,o]=i.useState({}),[p,u]=i.useState(!0),[d,c]=i.useState("all"),[m,h]=i.useState(""),[b,f]=i.useState(null),[x,g]=i.useState(null),y=i.useCallback(async()=>{if(t){u(!0);try{const[k,C,w]=await Promise.all([D.entities.BillingRequest.filter({community_id:t}),D.entities.BillingRequestMessage.filter({community_id:t}),D.entities.PayerAccount.filter({community_id:t}).catch(()=>[])]),_={};for(const M of C||[])(_[M.request_id]=_[M.request_id]||[]).push(M);Object.values(_).forEach(M=>M.sort((B,R)=>String(B.created_date||"").localeCompare(String(R.created_date||""))));const T={};for(const M of w||[])T[M.id]=M;n(k||[]),l(_),o(T)}catch{W.error("שגיאה בטעינת הפניות")}finally{u(!1)}}},[t]);i.useEffect(()=>{y()},[y]),i.useEffect(()=>{D.auth.me().then(g).catch(()=>g(null))},[]);const $=i.useMemo(()=>ud(s),[s]),O=md(s,"manager"),A=i.useMemo(()=>{const k=m.trim().toLowerCase();return $.filter(C=>xd(C,d)).filter(C=>{if(!k)return!0;const w=r[C.payer_account_id];return[C.ticket_no,C.subject,Ll(C.topic),w==null?void 0:w.name,w==null?void 0:w.account_number].filter(
59Boolean).some(_=>String(_).toLowerCase().includes(k))})},[$,d,m,r]),S=async k=>{const C=b===k.id?null:k.id;f(C),C&&k.manager_unread&&(n(w=>w.map(_=>_.id===k.id?{..._,manager_unread:!1}:_)),await D.entities.BillingRequest.update(k.id,{manager_unread:!1}).catch(()=>{}))},P=async(k,C,{close:w=!1}={})=>{const _=new Date().toISOString();await D.entities.BillingRequestMessage.create({community_id:t,request_id:k.id,author_role:"manager",author_id:(x==null?void 0:x.id)||null,author_name:(x==null?void 0:x.full_name)||(x==null?void 0:x.email)||"הנהלת הקהילה",body:C,created_date:_}),await D.entities.BillingRequest.update(k.id,{status:w?"closed":"in_progress",last_message_at:_,last_message_role:"manager",resident_unread:!0,manager_unread:!1,updated_date:_,...w?{closed_at:_,closed_by:(x==null?void 0:x.id)||null,closed_source:"manager"}:{}}),await y()},E=async(k,C)=>{const w=new Date().toISOString();await D.entities.BillingRequest.update(k.id,{status:C,manager_unread:!1,updated_date:w,...C==="closed"?{closed_at:w,closed_by:(x==null?void 0:x.id)||null,closed_source:"manager",resident_unread:!0}:{closed_at:null,closed_by:null,closed_source:null}}),W.success(C==="closed"?"הפנייה נסגרה":`הפנייה סומנה כ${xo(C)}`),await y()};return e.jsxs("div",{dir:"rtl",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap mb-4",children:[e.jsx("h2",{className:"text-xl font-black text-slate-900",children:"פניות בנושא חיובים"}),e.jsxs("span",{className:"relative inline-grid place-items-center w-10 h-10 rounded-full bg-white border border-slate-200",title:O?`${O} פניות ממתינות למענה`:"אין פניות חדשות",children:[e.jsx(Kc,{className:`w-[18px] h-[18px] ${O?"text-slate-700":"text-slate-300"}`}),O>0&&e.jsx("span",{className:"absolute -top-1.5 -right-1.5 min-w-[20px] h-5 px-1 rounded-full bg-rose-500 text-white text-[11px] font-black grid place-items-center",children:O})]}),O>0&&e.jsx("span",{className:"text-[13px] font-bold text-rose-600",children:O===1?"פנייה אחת ממתינה למענה":`${O} פניות ממתינות למענה`})]}),e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-center gap-2.5 flex-wrap mb-4",children:[pd.map(k=>{const C=d===k.v;return e.jsxs("button",{type:"button",onClick:()=>c(k.v),className:`h-9 px-3.5 rounded-full text-[13px] font-bold border inline-flex items-center gap-1.5 transition-colors
60                  ${C?"bg-slate-900 border-slate-900 text-white":"bg-white border-slate-200 text-slate-600 hover:border-slate-300"}`,children:[k.l,e.jsx("span",{className:`text-[11px] font-black px-1.5 min-w-[18px] text-center rounded-full ${C?"bg-white/25":"bg-slate-100 text-slate-500"}`,children:hd(s,k.v)})]},k.v)}),e.jsxs("div",{className:"relative mr-auto",children:[e.jsx(qt,{className:"w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none"}),e.jsx("input",{value:m,onChange:k=>h(k.target.value),placeholder:"חיפוש לפי מספר, משפחה או נושא","aria-label":"חיפוש פניות",className:"h-9 w-64 rounded-full border border-slate-200 pr-9 pl-3 text-[13px]"})]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"})}):A.length===0?e.jsxs("div",{className:"text-center py-14",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-slate-100 grid place-items-center mx-auto mb-3",children:e.jsx(cr,{className:"w-7 h-7 text-slate-300"})}),e.jsx("p",{className:"text-sm text-slate-500",children:s.length===0?"עדיין לא התקבלו פניות בנושא חיובים.":"אין פניות התואמות לסינון."})]}):e.jsx("ul",{className:"space-y-2",children:A.map(k=>e.jsxs("li",{className:`rounded-xl border transition-colors ${b===k.id?"border-slate-300 bg-slate-50/60":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx(Rh,{r:k,account:r[k.payer_account_id],open:b===k.id,onToggle:()=>S(k)}),b===k.id&&e.jsx(qh,{r:k,messages:a[k.id]||[],onReply:P,onStatus:E})]},k.id))})]})]})}function Rh({r:t,account:s,open:n,onToggle:a}){return e.jsxs("button",{type:"button",onClick:a,"aria-expanded":n,className:"w-full flex items-center gap-3 p-3.5 text-right",children:[e.jsx(lt,{className:`w-4 h-4 flex-none text-slate-300 transition-transform ${n?"-rotate-90":""}`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block text-[15px] font-bold text-slate-800 truncate",children:["#",t.ticket_no," · ",t.subject||Ll(t.topic)]}),e.jsxs("span",{className:"block text-[12px] text-slate-400 mt-0.5 truncate",children:[(s==null?void 0:s.name)||"חשבון לא ידוע",s!=null&&s.account_number?` · חשבון ${s.account_number}`:""," · ",Ll(t.topic)," · ",po(t.last_message_at||t.created_date)]})]}),t.manager_unread&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full bg-rose-50 border border-rose-200 text-rose-700 text-[12px] font-bold flex-none",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-rose-500"})," חדשה"]}),e.jsx("span",{className:`h-7 px-2.5 rounded-full border text-[12px] font-bold grid place-items-center flex-none ${bd(t.status)}`,children:xo(t.status)})]})}function qh({r:t,messages:s,onReply:n,onStatus:a}){const[l,r]=i.useState(""),[o,p]=i.useState(!1),u=async d=>{const c=l.trim();if(!c){W.error("יש להזין תוכן לתגובה");return}p(!0);try{await n(t,c,d),r(""),W.success(d!=null&&d.close?"התגובה נשלחה והפנייה נסגרה":"התגובה נשלחה")}catch{W.error("שגיאה בשליחת התגובה")}finally{p(!1)}};return e.jsxs("div",{className:"px-3.5 pb-3.5 pt-3 border-t border-slate-200/80",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-3",children:[t.status!=="in_progress"&&t.status!=="closed"&&e.jsx(Ol,{icon:bo,label:"סימון כבטיפול",onClick:()=>a(t,"in_progress")}),t.status!=="closed"?e.jsx(Ol,{icon:Aa,label:"סגירת הפנייה",onClick:()=>a(t,"closed")}):e.jsx(Ol,{icon:ou,label:"פתיחה מחדש",onClick:()=>a(t,"open")})]}),e.jsx("div",{className:"space-y-2.5",children:s.length===0?e.jsx("p",{className:"text-sm text-slate-400",children:"אין הודעות בפנייה הזו."}):s.map(d=>e.jsx(Ih,{m:d},d.id))}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("input",{value:l,onCh
60ange:d=>r(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),u())},placeholder:"כתיבת תגובה לתושב…","aria-label":"כתיבת תגובה",className:"flex-1 h-11 rounded-xl border border-slate-200 bg-white px-3.5 text-sm"}),e.jsxs("button",{type:"button",onClick:()=>u(),disabled:o||!l.trim(),className:"h-11 px-4 rounded-xl bg-slate-900 text-white font-bold text-sm inline-flex items-center gap-2 disabled:opacity-50 flex-none",children:[e.jsx(Gs,{className:"w-4 h-4 flex-none"})," שליחה"]}),e.jsxs("button",{type:"button",onClick:()=>u({close:!0}),disabled:o||!l.trim(),title:"שליחת התגובה וסגירת הפנייה",className:"h-11 px-4 rounded-xl border border-slate-300 text-slate-700 font-bold text-sm inline-flex items-center gap-2 disabled:opacity-50 flex-none hover:bg-slate-50",children:[e.jsx(la,{className:"w-4 h-4 flex-none"})," מענה וסגירה"]})]})]})}function Ol({icon:t,label:s,onClick:n}){return e.jsxs("button",{type:"button",onClick:n,className:"h-9 px-3.5 rounded-full border border-slate-200 bg-white text-[13px] font-bold text-slate-600 inline-flex items-center gap-1.5 hover:border-slate-300 hover:bg-slate-50",children:[e.jsx(t,{className:"w-3.5 h-3.5 flex-none"})," ",s]})}function Ih({m:t}){const s=t.author_role==="manager";return e.jsxs("div",{className:`flex items-start gap-2.5 ${s?"flex-row-reverse":""}`,children:[e.jsx("span",{className:`w-8 h-8 rounded-full grid place-items-center flex-none ${s?"bg-emerald-50 text-emerald-600":"bg-slate-100 text-slate-400"}`,children:s?e.jsx(ra,{className:"w-4 h-4"}):e.jsx(ys,{className:"w-4 h-4"})}),e.jsxs("div",{className:`min-w-0 max-w-[80%] rounded-2xl px-3.5 py-2.5 ${s?"bg-emerald-50/70":"bg-blue-50/70"}`,children:[e.jsx("p",{className:"text-[14px] text-slate-800 whitespace-pre-wrap break-words",children:t.body}),t.attachment_url&&e.jsxs("a",{href:t.attachment_url,target:"_blank",rel:"noreferrer",className:"mt-1.5 inline-flex items-center gap-1.5 text-[12px] font-bold text-slate-600 hover:text-slate-900 underline",children:[e.jsx(ro,{className:"w-3.5 h-3.5 flex-none"})," ",t.attachment_name||"קובץ מצורף"]}),e.jsxs("p",{className:"text-[11px] text-slate-400 mt-1",children:[t.author_name?`${t.author_name} · `:"",po(t.created_date)]})]})]})}const tl=t=>`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,qn=t=>Math.round(((Number(t)||0)+Number.EPSILON)*100)/100,Ec=t=>(Number(t==null?void 0:t.amount)||0)-(Number(t==null?void 0:t.discount_amount)||0)-(Number(t==null?void 0:t.credit_amount)||0),Fc=t=>(t==null?void 0:t.status)==="approved"||(t==null?void 0:t.status)==="issued",Yi=t=>(t==null?void 0:t.calculation_method)==="water_meter"||(t==null?void 0:t.billing_cycle)==="per_file",zh=["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"];function Kh(t,s=new Date){const n=String(t||"").slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(n))return"";const[a,l,r]=n.split("-").map(Number),o=new Date(a,l-1,r),p=Math.round((Date.UTC(a,l-1,r)-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return p===0?"היום":p===1?"מחר":zh[o.getDay()]}const Wh=["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],fn=t=>{const s=Number(String(t||"").slice(5,7));return s>=1&&s<=12?Wh[s-1]:""},Uh=t=>{const s=String(t||"").slice(0,7);return/^\d{4}-\d{2}$/.test(s)?`${fn(`${s}-01`)} ${s.slice(0,4)}`:""},Hh=(t,s)=>tl(new Date(t.getFullYear(),t.getMonth()+s+1,0));function Yh({charges:t=[],types:s=[],plan:n=null,today:a=new Date,months:l=2}={}){const r=tl(a),o=Hh(a,Math.max(1,l)-1),p=new Map(s.map(c=>[c.id,c])),u=new Map;for(const c of t){if(!Fc(c))continue;const m=String(c.due_date||"").slice(0,10);if(!m||m<r||m>o)continue;const h=`${m}|${c.charge_type_id||""}`,b=p.get(c.charge_type_id),f=u.get(h)||{date:m,month:m.slice(0,7),typeId:c.charge_type_id||"",name:(b==null?void 0:b.name)||"חיוב",calc:(b==null?void 0:b.calculation_method)||"",auto:ze(b)==="auto",byConsumption:Yi(b),count:0,amount:0,planned:!1,awaitingApproval:!1};f.count+=1,f.amount=qn(f.amount+Ec(c)),u.set(h,f)}const d=new Set([...u.values()].map(c=>`${c.month}|${c.typeId}`));for(const c of(n==null?void 0:n.types)||[]){if(!(c.enabled||c.activation_mode))continue;const m=String(c.next_due||"").slice(0,10);if(!/^\d{4}-\d{2}-\d{2}$/.test(m)||m<r||m>o)continue;const h=m.slice(0,7);if(d.has(`${h}|${c.id}`))continue;const b=p.get(c.id);u.set(`${m}|${c.id}|plan`,{date:m,month:h,typeId:c.id,name:c.name||(b==null?void 0:b.name)||"חיוב",calc:c.calculation_method||(b==null?void 0:b.calculation_method)||"",auto:c.enabled||c.activation_mode==="auto",byConsumption:Yi(b||c),count:Number(c.accounts)||0,amount:qn(c.forecast),planned:!0,awaitingApproval:!!c.awaiting_approval})}return[...u.values()].sort((c,m)=>c.date.localeCompare(m.date)||String(c.name).localeCompare(String(m.n
60ame),"he"))}function Vh(t=[]){return{amount:qn(t.filter(s=>!s.byConsumption).reduce((s,n)=>s+n.amount,0)),hasConsumption:t.some(s=>s.byConsumption)}}const Gh={overdue:{l:"עבר המועד",tone:"red",action:"השלמת הפקה"},data:{l:"נדרש טיפול",tone:"red",action:"השלמת נתונים"},file:{l:"לא הושלם",tone:"amber",action:"השלמת הטעינה"},approval:{l:"ממתין לאישור",tone:"amber",action:"אישור הפקה"}},Vi={demand:"דרישת תשלום",charge:"חיוב ומסמך תשלום"};function Xh({plan:t=null,today:s=new Date}={}){const n=tl(s),a=[];for(const l of(t==null?void 0:t.types)||[]){if(!l.requires_manager_approval||!(l.enabled||l.activation_mode))continue;const r=l.approvals||{},o=r.demand?r.charge?null:"charge":"demand";if(!o)continue;const p=String((o==="demand"?l.next_issue:l.next_due)||"").slice(0,10);a.push({kind:"approval",typeId:l.id,name:l.name||"חיוב",stage:o,period:(t==null?void 0:t.period)||"",date:/^\d{4}-\d{2}-\d{2}$/.test(p)?p:n,count:Number(l.accounts)||0,amount:Number(l.forecast)||0,next_issue:String(l.next_issue||"").slice(0,10),next_due:String(l.next_due||"").slice(0,10),note:`הפקת ${Vi[o]}`,title:`אישור ${Vi[o]} · ${l.name||""}${t!=null&&t.period?` · מחזור ${Uh(t.period)}`:""}`})}return a}const Zh=new Set(["draft","pending","partially_approved"]);function Qh({charges:t=[],types:s=[],batches:n=[],meters:a=[],plan:l=null,today:r=new Date}={}){const o=tl(r),p=new Map(s.map(m=>[m.id,m])),u=Xh({plan:l,today:r}),d=new Map;for(const m of t){if(!Fc(m))continue;const h=String(m.due_date||"").slice(0,10);if(!h||h>=o)continue;const b=m.charge_type_id||"",f=p.get(b),x=d.get(b)||{kind:"overdue",typeId:b,name:(f==null?void 0:f.name)||"חיוב",date:h,count:0,amount:0};h<x.date&&(x.date=h),x.count+=1,x.amount=qn(x.amount+Ec(m)),d.set(b,x)}for(const m of d.values())u.push({...m,note:m.count===1?"חשבון אחד שמועד התשלום שלו עבר":`${m.count} חשבונות שמועד התשלום שלהם עבר`});const c=a.filter(m=>(m.status||"active")!=="inactive"&&!(m.payer_account_id&&Number(m.souls)>0&&m.previous_reading!=null));if(c.length){const m=s.find(h=>h.calculation_method==="water_meter");u.push({kind:"data",typeId:(m==null?void 0:m.id)||"",name:(m==null?void 0:m.name)||"מים",date:o,count:c.length,amount:0,note:c.length===1?"חסרים נתונים עבור מונה אחד":`חסרים נתונים עבור ${c.length} מונים`})}for(const m of n){if(!Zh.has(m==null?void 0:m.status))continue;const h=p.get(m.charge_type_id),b=Number(m.row_count)||0;u.push({kind:"file",typeId:m.charge_type_id||"",batchId:m.id,name:(h==null?void 0:h.name)||m.period_name||"חיוב מקובץ",date:String(m.due_date||m.created_date||o).slice(0,10),count:b,amount:0,note:m.status==="partially_approved"?"הקובץ אושר חלקית — נותרו שורות לטיפול":`קובץ שנטען וטרם אושר${b===1?" · שורה אחת":b?` · ${b} שורות`:""}`})}return u.sort((m,h)=>String(m.date).localeCompare(String(h.date)))}const Jh={red:"bg-rose-600 text-white shadow-sm",emerald:"bg-emerald-600 text-white shadow-sm"},e0={red:"bg-rose-100 text-rose-700",emerald:"bg-emerald-100 text-emerald-700"},Gi={red:"bg-rose-50 text-rose-700 border-rose-200",amber:"bg-amber-50 text-amber-800 border-amber-200"};function Xi({tone:t,label:s,n,on:a,onClick:l}){return e.jsxs("button",{type:"button",onClick:l,"aria-pressed":a,className:`h-8 pr-3 pl-2 rounded-full text-[12.5px] font-bold inline-flex items-center gap-1.5 transition-colors
61        ${a?Jh[t]:"text-slate-500 hover:text-slate-800"}`,children:[s,e.jsx("span",{className:`min-w-[1.25rem] h-5 px-1 rounded-full text-[11px] font-black grid place-items-center tabular-nums
62        ${a?"bg-white/25 text-white":e0[t]}`,children:n})]})}function t0({date:t,today:s}){return e.jsxs("span",{className:"text-center",children:[e.jsx("span",{className:"block text-[19px] font-black text-slate-900 leading-none tabular-nums",children:Number(t.slice(8))}),e.jsx("span",{className:"block text-[10.5px] font-bold text-slate-400 mt-0.5 whitespace-nowrap",children:Kh(t,s)})]})}const Wt="text-[11px] font-bold text-slate-400",Zi="grid grid-cols-[3.4rem,1fr,5.5rem,7.5rem] gap-2 items-center",Qi="grid grid-cols-[3.4rem,1fr,5rem,8.5rem] gap-2 items-center";function s0({charges:t=[],types:s=[],batches:n=[],meters:a=[],plan:l=null,loading:r,onOpen:o,className:p=""}){const u=i.useMemo(()=>new Date,[]),d=i.useMemo(()=>Qh({charges:t,types:s,batches:n,meters:a,plan:l,today:u}),[t,s,n,a,l,u]),c=i.useMemo(()=>Yh({charges:t,types:s,plan:l,today:u}),[t,s,l,u]),m=i.useMemo(()=>Vh(c),[c]),[h,b]=i.useState("attention");i.useEffect(()=>{r||b(d.length?"attention":"upcoming")},[r,d.length]);const f=i.useMemo(()=>{const x=new Date(u.getFullYear(),u.getMonth()+2,0);return`${fn(`${x.getFullYear()}
62-${String(x.getMonth()+1).padStart(2,"0")}-01`)} ${x.getFullYear()}`},[u]);return e.jsxs("section",{className:`bg-white rounded-2xl border border-slate-200/80 shadow-sm flex flex-col overflow-hidden ${p}`,children:[e.jsxs("header",{className:"flex items-center gap-2 px-4 pt-4 pb-3",children:[e.jsx(vs,{className:"w-[18px] h-[18px] text-indigo-500 flex-none"}),e.jsx("h3",{className:"text-[15px] font-bold text-slate-800 flex-none",children:"יומן חיובים"}),e.jsxs("span",{className:"mr-auto flex items-center gap-0.5 p-0.5 rounded-full bg-slate-100/80",children:[e.jsx(Xi,{tone:"red",label:"נדרש לטיפול",n:d.length,on:h==="attention",onClick:()=>b("attention")}),e.jsx(Xi,{tone:"emerald",label:"חיובים קרובים",n:c.length,on:h==="upcoming",onClick:()=>b("upcoming")})]})]}),r?e.jsx("div",{className:"grid place-items-center py-16",children:e.jsx("div",{className:"w-7 h-7 border-4 border-slate-200 border-t-indigo-500 rounded-full animate-spin"})}):h==="attention"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mx-4 mb-2 rounded-lg bg-rose-50 border border-rose-100 px-3 py-1.5 text-[12px] font-bold text-rose-700 inline-flex items-center gap-1.5",children:[e.jsx(At,{className:"w-3.5 h-3.5 flex-none"}),"מה שמועדו עבר ולא הושלם, ומה שממתין לאישור מנהל"]}),e.jsx("div",{className:"px-4",children:e.jsxs("div",{className:`${Zi} pb-1.5 border-b border-slate-100`,children:[e.jsx("span",{className:`${Wt} text-center`,children:"תאריך"}),e.jsx("span",{className:Wt,children:"סוג החיוב וההתראה"}),e.jsx("span",{className:`${Wt} text-center`,children:"סטטוס"}),e.jsx("span",{className:`${Wt} text-center`,children:"פעולה"})]})}),d.length===0?e.jsx(Ji,{children:"אין כרגע התראות. כל מה שמועדו עבר — טופל."}):e.jsx("ul",{className:"px-4 divide-y divide-slate-100 max-h-[21rem] overflow-y-auto",children:d.map((x,g)=>{const y=Gh[x.kind]||{};return e.jsxs("li",{className:`${Zi} py-2`,children:[e.jsxs("span",{className:"text-center",children:[e.jsx("span",{className:"block text-[15px] font-black text-slate-900 leading-none tabular-nums",children:Number(x.date.slice(8))}),e.jsx("span",{className:"block text-[10.5px] font-bold text-slate-400 mt-0.5 whitespace-nowrap",children:fn(x.date)})]}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-bold text-slate-800 truncate",children:x.name}),e.jsxs("span",{className:`block text-[11.5px] text-slate-500 ${x.kind==="approval"?"leading-snug":"truncate"}`,title:x.title||x.note,children:[x.note,x.kind==="approval"&&x.count>0&&e.jsxs(e.Fragment,{children:[" · ",_e(x.count,"חשבון אחד","חשבונות"),x.amount>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"font-bold tabular-nums",dir:"ltr",children:ve(x.amount)})]})]})]})]}),e.jsxs("span",{className:`text-[11px] font-bold px-2 py-0.5 rounded-full border whitespace-nowrap text-center inline-flex items-center justify-center gap-1 ${Gi[y.tone]||Gi.amber}`,children:[x.kind==="approval"&&e.jsx(bo,{className:"w-3 h-3 flex-none"}),y.l]}),x.kind==="approval"?e.jsxs("button",{type:"button",onClick:()=>o==null?void 0:o(x.kind,x),className:`h-8 px-3 rounded-lg bg-amber-500 text-white text-[12px] font-bold whitespace-nowrap
63                          inline-flex items-center justify-center gap-1 hover:bg-amber-600 transition-colors`,children:[e.jsx(xt,{className:"w-3.5 h-3.5"}),y.action]}):e.jsxs("button",{type:"button",onClick:()=>o==null?void 0:o(x.kind,x),className:"text-[12px] font-bold text-slate-600 hover:text-indigo-700 whitespace-nowrap inline-flex items-center gap-0.5",children:[y.action,e.jsx(lt,{className:"w-3.5 h-3.5"})]})]},`${x.kind}${x.typeId}${x.batchId||""}${g}`)})}),e.jsxs("footer",{className:"mt-auto px-4 pt-3 pb-4",children:[d.length>0&&e.jsxs("p",{className:"rounded-xl bg-rose-600 text-white px-3.5 py-2.5 flex items-center gap-2",children:[e.jsx(At,{className:"w-4 h-4 flex-none"}),e.jsx("span",{className:"text-[13px] font-black",children:_e(d.length,"חיוב אחד דורש טיפול","חיובים דורשים טיפול")}),e.jsx("span",{className:"mr-auto text-[11.5px] font-bold opacity-90",children:"לתיקון לפני ההפקה הבאה"})]}),e.jsx("p",{className:"text-[11px] text-slate-400 mt-2 text-center",children:"לאחר השלמת הטיפול ההתראה תוסר אוטומטית"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mx-4 mb-2 text-[12px] font-bold text-slate-500",children:["חיובים קרובים עד סוף ",f]}),e.jsx("div",{className:"px-4",children:e.jsxs("div",{className:`${Qi} pb-1.5 border-b border-slate-100`,children:[e.jsx("span",{className:`${Wt} text-center`,children:"תאריך"}),e.jsx("span",{className:Wt,children:"סוג החיוב"}),e.jsx("span",{className:`${Wt} text-center`,children:"הפקה"}),e.jsx("span",{className:`${Wt} text-center`,children:"פעולה"})]})}
63),c.length===0?e.jsxs(Ji,{children:["אין חיובים לגבייה עד סוף ",f,"."]}):e.jsx("ul",{className:"px-4 divide-y divide-slate-100 max-h-[21rem] overflow-y-auto",children:c.map((x,g)=>e.jsxs(he.Fragment,{children:[(g===0||c[g-1].month!==x.month)&&e.jsx("li",{className:"pt-2.5 pb-1 first:pt-0",children:e.jsxs("span",{className:"text-[11px] font-black text-slate-400 tracking-wide",children:[fn(x.date)," ",x.date.slice(0,4)]})}),e.jsxs("li",{className:`${Qi} py-2`,children:[e.jsx(t0,{date:x.date,today:u}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"block text-[13px] font-bold text-slate-800 truncate",children:[x.name,x.planned&&e.jsx("span",{className:"mr-1.5 align-middle text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-slate-100 text-slate-500 border border-slate-200",children:"צפי"}),x.awaitingApproval&&e.jsx("span",{className:"mr-1 align-middle text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200",children:"ממתין לאישור"})]}),e.jsxs("span",{className:"block text-[11.5px] text-slate-500 truncate",children:[_e(x.count,"חשבון אחד","חשבונות")," · ",x.byConsumption?e.jsx("span",{className:"font-bold text-teal-700",children:"לפי צריכה"}):e.jsx("span",{className:"font-bold tabular-nums",dir:"ltr",children:ve(x.amount)})]})]}),x.auto?e.jsxs("span",{className:"text-[11px] font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 whitespace-nowrap inline-flex items-center gap-1",children:[e.jsx(Mt,{className:"w-3 h-3"})," אוטומטי"]}):e.jsxs("span",{className:"text-[11px] font-bold px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 border border-slate-200 whitespace-nowrap inline-flex items-center gap-1",children:[e.jsx(Cd,{className:"w-3 h-3"})," ידני"]}),e.jsx("button",{type:"button",onClick:()=>o==null?void 0:o(x.planned?"issue":"charges",x),title:`${x.name} · ${_e(x.count,"חשבון אחד","חשבונות")}`,className:"h-8 px-3 rounded-lg text-[12px] font-bold whitespace-nowrap border border-indigo-200 text-indigo-700 hover:bg-indigo-50 transition-colors",children:x.planned?"הצג הפקה":"הצג חיובים"})]})]},`${x.date}${x.typeId}${x.planned?"p":""}${g}`))}),e.jsxs("footer",{className:"mt-auto px-4 pt-3 pb-4",children:[c.length>0&&e.jsxs("p",{className:"rounded-xl bg-emerald-600 text-white px-3.5 py-2.5 flex items-center gap-2",children:[e.jsxs("span",{className:"text-[11.5px] font-bold opacity-90",children:["סה״כ צפוי עד סוף ",f]}),e.jsx("span",{className:"mr-auto text-[14px] font-black tabular-nums",dir:"ltr",children:ve(m.amount)}),m.hasConsumption&&e.jsx("span",{className:"text-[11px] font-bold opacity-90 whitespace-nowrap",children:"+ חיובי מים"})]}),e.jsxs("p",{className:"text-[11px] text-slate-400 mt-2 flex items-center justify-center gap-2",children:["מוצגים חיובים מהיום ועד סוף ",f,e.jsxs("button",{type:"button",onClick:()=>o==null?void 0:o("all"),className:"font-bold text-indigo-600 hover:text-indigo-800 inline-flex items-center",children:["לכל החיובים",e.jsx(lt,{className:"w-3 h-3"})]})]})]})]})]})}const Ji=({children:t})=>e.jsx("p",{className:"px-4 py-10 text-center text-[12.5px] text-slate-400",children:t}),a0="https://app.sumit.co.il/users/login/",n0="https://app.upay.co.il/",eo=t=>window.open(t,"_blank","noopener,noreferrer"),to=[{key:"dashboard",label:"דשבורד",icon:Uc,tile:!1},{key:"accounts",label:"חשבונות משלמים",icon:De,tone:"indigo"},{key:"kolbo",label:"טעינת קובץ כולבו",icon:da,tone:"purple",tile:!1},{key:"water",label:"טעינת קובץ צריכת מים",icon:Ke,tone:"sky",tile:!1},{key:"paymentPages",label:"עמודי תשלום",icon:Zt,tone:"purple"},{key:"chargeTypes",label:"סוגי חיובים",icon:Xe,tone:"amber"},{key:"reports",label:"מחולל דוחות",icon:ks,tone:"violet"},{key:"documents",label:"ניהול מסמכים",tileLabel:"מחולל מסמכים",icon:cu,tone:"rose",hint:"בקרוב",note:"מחולל המסמכים יפיק מכתבים, אישורים ומסמכים חתומים מתוך נתוני החשבונות — בתבניות של הקהילה ובלי להקליד מחדש. האזור בבנייה."},{key:"requests",label:"פניות תושבים",icon:cr,tone:"slate"},{key:"settings",label:"הגדרות מערכת",icon:zn,tone:"blue"},{key:"monthly",label:"הפקת חיובים",icon:Be,tone:"emerald"},{key:"plans",label:"תוכניות חיוב",icon:Be,tile:!1},{key:"onetime",label:"חיובים חד־פעמיים",icon:Ns,tile:!1},{key:"statements",label:"מסמכי חשבון",icon:nt,tile:!1},{key:"payments",label:"תשלומים ותקבולים",icon:es,tile:!1},{key:"approvals",label:"חריגות ואישורים",icon:Hc,tile:!1}];function Mb(){return e.jsx(Yc,{moduleKey:"settings",children:e.jsx(l0,{})})}function l0(){const{id:t}=Wc(),[s,n]=ia(),a=to.some(w=>w.key===s.get("tab"))?s.get("tab"):"dashboard",l=(w,_=null)=>n(w==="dashboard"?{}:{tab:w,..._||{}},{replace:!0}),[r,o]=i.useState(0),[p,u]=i.useState(!1),[d,c]=i.useState(!1),[m,h]=i.useState(null),[b,f]=i.useState(!1),[x,g]=i.useState(null),[y,$]=i.useState(null),[O,A]=i.useState(0),[S,P]=i.useState({charges:[],types:[],batches:[],meters:[],plan:null,loading:!0});i.useEffect(()=>{if(!t||a!=="dashboard")return;let w=!0;return P(_=>({..._,loading:!0})),Promise.all([D.entities.BillingRequest.filter({community_id:t,manager_unread:!0}).catch(()=>[]),D.entities.Charge.filterAllFields({kibbutz_id:t},["id","charge_type_id","due_date","amount","discount_amount","credit_amount","status"]).catch(()=>[]),D.entities.ChargeType.filterAllFields({kibbutz_id:t},["id","name","due_day","issue_days_before","auto_billing_enabled","calculation_method","billing_cycle","activation_mode","requires_manager_approval"],"order").catch(()=>[]),D.entities.WaterImportBatch.filterAllFields({kibbutz_id:t},["id","charge_type_id","period_name","due_date","status","row_count","bill_count","total_amount","created_date"]).catch(()=>[]),D.entities.WaterMeter.filterAllFields({kibbutz_id:t},["id","status","payer_account_id","souls","previous_reading"]).catch(()=>[]),D.functions.invoke("recurringBilling",{action:"status",community_id:t}).then(_=>
63(_==null?void 0:_.data)||null).catch(()=>null)]).then(([_,T,M,B,R,j])=>{w&&(A((_||[]).length),P({charges:zt(T,M),types:M||[],batches:B||[],meters:R||[],plan:j||null,loading:!1}))}).catch(()=>{w&&P(_=>({..._,loading:!1}))}),()=>{w=!1}},[t,a,r]);const E=()=>{o(w=>w+1),W.success("הנתונים נקראים מחדש")},k=to.find(w=>w.key===a),C=a==="dashboard";return e.jsx(Iu,{children:w=>{var _;return e.jsxs("div",{dir:"rtl",children:[e.jsxs("div",{className:"flex items-center flex-wrap mb-6",children:[e.jsxs("div",{className:`inline-flex items-center gap-3 bg-white border border-slate-200 rounded-full shadow-sm ${C?"px-5 py-2.5":"pr-5 pl-1 py-1"}`,children:[e.jsx("h1",{className:"text-[19px] font-bold text-slate-900 whitespace-nowrap leading-none",children:"חשבונות ותשלומים"}),C?null:e.jsxs("span",{className:"inline-flex items-center gap-2 h-10 pr-4 pl-2 rounded-full bg-teal-700 text-white text-[15px] font-bold whitespace-nowrap",children:[(k==null?void 0:k.label)||"",e.jsx("button",{type:"button",onClick:()=>l("dashboard"),"aria-label":`סגירת ${(k==null?void 0:k.label)||""}`,title:"חזרה לעמוד המודול",className:"w-6 h-6 rounded-full grid place-items-center text-white/80 hover:bg-white/20 hover:text-white transition-colors",children:e.jsx($e,{className:"w-4 h-4"})})]})]}),w&&e.jsx("span",{className:"mr-auto flex-none",children:w})]}),C&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-4 items-start",children:[e.jsx("div",{className:"xl:col-span-3",children:e.jsx(Wu,{columns:4,compact:!0,items:[{key:"accounts",label:"חשבונות משלמים",icon:De,tone:"indigo",onClick:()=>l("accounts")},{key:"monthly",label:"הפקת חיובים",icon:Be,tone:"emerald",onClick:()=>l("monthly")},{key:"reports",label:"מחולל דוחות",icon:ks,tone:"violet",onClick:()=>l("reports")},{key:"requests",label:"פניות תושבים",icon:cr,tone:"slate",badge:O>0?O:void 0,onClick:()=>l("requests")},{key:"paymentPages",label:"עמודי תשלום",icon:Zt,tone:"purple",onClick:()=>l("paymentPages")},{key:"terminal",label:"סליקת אשראי",icon:Oe,tone:"rose",onClick:()=>c(!0)},{key:"chargeTypes",label:"סוגי חיובים",icon:Xe,tone:"amber",onClick:()=>l("chargeTypes")},{key:"files",label:"טעינת קבצים",icon:La,tone:"sky",onClick:()=>u(!0)},{key:"sumit",label:"חשבון סמאיט",icon:kr,tone:"rose",onClick:()=>eo(a0)},{key:"upay",label:"חשבון UPAY",icon:kr,tone:"rose",onClick:()=>eo(n0)},{key:"settings",label:"הגדרות מערכת",icon:zn,tone:"blue",onClick:()=>l("settings")},{key:"refresh",label:"רענון נתונים",icon:br,tone:"emerald",onClick:E}]})}),e.jsx(s0,{className:"xl:col-span-2",charges:S.charges,types:S.types,batches:S.batches,meters:S.meters,plan:S.plan,loading:S.loading,onOpen:(T,M)=>{if(T==="approval"){h(M);return}if(T==="issue"){g(null),$(null),l("monthly");return}if(T==="file"){g(null),$(null),l("water");return}g(T==="data"?"water":"charges"),$(T==="charges"&&(M!=null&&M.date)?{type:M.typeId||"",due:M.date}:null),l("reports")}})]}),p&&e.jsx(i0,{onPick:T=>{u(!1),l(T)},onClose:()=>u(!1)}),d&&e.jsx(Hu,{kibbutzId:t,onClose:()=>c(!1),onDone:E}),m&&e.jsx(tc,{row:{name:m.name,accounts:m.count,forecast:m.amount,next_issue:m.next_issue,next_due:m.next_due,date:m.date},stage:m.stage,period:m.period||((_=S.plan)==null?void 0:_.period),busy:b,onClose:()=>h(null),onConfirm:async T=>{var M;f(!0);try{const B=await D.functions.invoke("recurringBilling",{action:"approve_cycle",community_id:t,charge_type_id:m.typeId,stage:m.stage,period:m.period||((M=S.plan)==null?void 0:M.period),note:T});W.success(hc(B==null?void 0:B.data)),h(null),o(R=>R+1)}catch{W.error("האישור נכשל")}finally{f(!1)}}})]}),C?null:a==="accounts"?e.jsx(tm,{kibbutzId:t},r):a==="paymentPages"?e.jsx(Eh,{kibbutzId:t},r):a==="chargeTypes"?e.jsx(xm,{kibbutzId:t,onManage:()=>l("monthly")},r):a==="monthly"?e.jsx(bc,{kibbutzId:t},r):a==="plans"?e.jsx(gi,{kibbutzId:t,mode:"recurring"},r):a==="onetime"?e.jsx(gi,{kibbutzId:t,mode:"onetime"},r):a==="statements"?e.jsx(Sx,{kibbutzId:t},r):a==="payments"?e.jsx(Cx,{kibbutzId:t},r):a==="approvals"?e.jsx(Ax,{kibbutzId:t},r):a==="reports"?e.jsx(kh,{kibbutzId:t,initial:x,initialFilter:y},`${r}-${x||""}-${(y==null?void 0:y.type)||""}-${(y==null?void 0:y.due)||""}`):a==="settings"?e.jsx(Sh,{kibbutzId:t},r):a==="kolbo"?e.jsx(Ch,{kibbutzId:t},r):a==="water"?e.jsx(mx,{kibbutzId:t},r):a==="requests"?e.jsx(Bh,{kibbutzId:t},r):e.jsx(r0,{section:k})]})}})}function r0({section:t}){const s=(t==null?void 0:t.icon)||io;return e.jsxs("div",{className:"bg-white rounded-2xl border border-border shadow-sm p-12 text-center",children:[e.jsx("div",{className:"w-14 h-14 roun
63ded-2xl bg-indigo-50 flex items-center justify-center mx-auto mb-3",children:e.jsx(s,{className:"w-7 h-7 text-indigo-500"})}),e.jsx("h3",{className:"text-base font-semibold mb-1",children:t==null?void 0:t.label}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:(t==null?void 0:t.note)||"אזור זה בבנייה ויתווסף בשלב הבא של מודול החיובים. תשתית הנתונים כבר מוכנה."}),e.jsxs("button",{disabled:!0,className:"mt-4 inline-flex items-center gap-1.5 h-9 px-4 rounded-full bg-slate-100 text-slate-400 text-sm cursor-not-allowed",children:[e.jsx(We,{className:"w-4 h-4"})," בקרוב"]})]})}function i0({onPick:t,onClose:s}){const n=[{key:"kolbo",label:"טעינת קובץ כולבו",hint:"קובץ הרכישות מהכולבו, לפי מספרי תקציב",icon:da,tone:"bg-purple-50 text-purple-600"},{key:"water",label:"טעינת קובץ צריכת מים",hint:"קריאות המונים מהתאגיד, לפי מספרי מונה",icon:Ke,tone:"bg-sky-50 text-sky-600"}];return e.jsx("div",{className:"fixed inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4",onClick:s,dir:"rtl",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl w-full max-w-lg p-5",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-black text-slate-900",children:"טעינת קבצים"}),e.jsx("button",{onClick:s,"aria-label":"סגירה",className:"w-9 h-9 rounded-full border border-slate-200 grid place-items-center text-slate-400 hover:bg-slate-50",children:e.jsx($e,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"space-y-2.5",children:n.map(a=>{const l=a.icon;return e.jsxs("button",{type:"button",onClick:()=>t(a.key),className:"w-full flex items-center gap-3.5 p-3.5 rounded-xl border border-slate-200 text-right hover:border-slate-300 hover:bg-slate-50 transition-all",children:[e.jsx("span",{className:`w-12 h-12 rounded-xl grid place-items-center flex-none ${a.tone}`,children:e.jsx(l,{className:"w-6 h-6"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[15px] font-bold text-slate-800",children:a.label}),e.jsx("span",{className:"block text-[12px] text-slate-400 mt-0.5",children:a.hint})]})]},a.key)})})]})})}export{Mb 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.