vendor: 7,236 bytes, lines 1-17
1var tR=Object.defineProperty;var nR=(t,n,a)=>n in t?tR(t,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[n]=a;var ES=(t,n,a)=>nR(t,typeof n!="symbol"?n+"":n,a);(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const c of i)if(c.type==="childList")for(const l of c.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function a(i){const c={};return i.integrity&&(c.integrity=i.integrity),i.referrerPolicy&&(c.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?c.credentials="include":i.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(i){if(i.ep)return;i.ep=!0;const c=a(i);fetch(i.href,c)}})();var aR=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ub(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function sR(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var n=t.default;if(typeof n=="function"){var a=function s(){return this instanceof s?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};a.prototype=n.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(t).forEach(function(s){var i=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(a,s,i.get?i:{enumerable:!0,get:function(){return t[s]}})}),a}var I0={exports:{}},hf={};/** 2 * @license React 3 * react-jsx-runtime.production.js 4 * 5 * Copyright (c) Meta Platforms, Inc. and affiliates. 6 * 7 * This source code is licensed under the MIT license found in the 8 * LICENSE file in the root directory of this source tree. 9 */var PS;function rR(){if(PS)return hf;PS=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function a(s,i,c){var l=null;if(c!==void 0&&(l=""+c),i.key!==void 0&&(l=""+i.key),"key"in i){c={};for(var m in i)m!=="key"&&(c[m]=i[m])}else c=i;return i=c.ref,{$$typeof:t,type:s,key:l,ref:i!==void 0?i:null,props:c}}return hf.Fragment=n,hf.jsx=a,hf.jsxs=a,hf}var RS;function iR(){return RS||(RS=1,I0.exports=rR()),I0.exports}var e=iR(),_0={exports:{}},ds={};/** 10 * @license React 11 * react.production.js 12 * 13 * Copyright (c) Meta Platforms, Inc. and affiliates. 14 * 15 * This source code is licensed under the MIT license found in the 16 * LICENSE file in the root directory of this source tree. 17 */var TS;function oR(){if(TS)return ds;TS=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),l=Symbol.for("react.context"),m=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),p=Symbol.iterator;function y(V){return V===null||typeof V!="object"?null:(V=p&&V[p]||V["@@iterator"],typeof V=="function"?V:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},N=Object.assign,w={};function C(V,$,F){this.props=V,this.context=$,this.refs=w,this.updater=F||b}C.prototype.isReactComponent={},C.prototype.setState=function(V,$){if(typeof V!="object"&&typeof V!="function"&&V!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,V,$,"setState")},C.prototype.forceUpdate=function(V){this.updater.enqueueForceUpdate(this,V,"forceUpdate")};function R(){}R.prototype=C.prototype;function I(V,$,F){this.props=V,this.context=$,this.refs=w,this.updater=F||b}var _=I.prototype=new R;_.constructor=I,N(_,C.prototype),_.isPureReactComponent=!0;var J=Array.isArray;function T(){}var G={H:null,A:null,T:null,S:null},z=Object.prototype.hasOwnProperty;function H(V,$,F){var P=F.ref;return{$$typeof:t,type:V,key:$,ref:P!==void 0?P:null,props:F}}function K(V,$){return H(V.type,$,V.props)}function L(V){return typeof V=="object"&&V!==null&&V.$$typeof===t}function D(V){var $={"=":"=0",":":"=2"};return"$"+V.replace(/[=:]/g,function(F){return $[F]})}var M=/\/+/g;function Z(V,$){return typeof V=="object"&&V!==null&&V.key!=null?D(""+V.key):$.toString(36)}function fe(V){switch(V.status){case"fulfilled":return V.value;case"rejected":throw V.reason;default:switch(typeof V.status=="string"?V.then(T,T):(V.status="pending",V.then(function($){V.status==="pending"&&(V.status="fulfilled",V.value=$)},function($){V.status==="pending"&&(V.status="rejected",V.reason=$)})),V.status){case"fulfilled":return V.value;case"rejected":throw V.reason}}throw V}function q(V,$,F,P,ue){var me=typeof V;(me==="undefined"||me==="boolean")&&(V=null);var ge=!1;if(V===null)ge=!0;else switch(me){case"bigint":case"string":case"number":ge=!0;break;case"object":switch(V.$$typeof){case t:case n:ge=!0;break;case f:return ge=V._init,q(ge(V._payload),$,F,P,ue)}}if(ge)return ue=ue(V),ge=P===""?"."+Z(V,0):P,J(ue)?(F="",ge!=null&&(F=ge.replace(M,"$&/")+"/"),q(ue,$,F,"",function(Re){return Re})):ue!=null&&(L(ue)&&(ue=K(ue,F+(ue.key==null||V&&V.key===ue.key?"":(""+ue.key).replace(M,"$&/")+"/")+ge)),$.push(ue)),1;ge=0;var de=P===""?".":P+":";if(J(V))for(var Pe=0;Pe<V.length;Pe++)P=V[Pe],me=de+Z(P,Pe),ge+=q(P,$,F,me,ue);else if(Pe=y(V),typeof Pe=="function")for(V=Pe.call(V),Pe=0;!(P=V.next()).done;)P=P.value,me=de+Z(P,Pe++),ge+=q(P,$,F,me,ue);else if(me==="object"){if(typeof V.then=="function")return q(fe(V),$,F,P,ue);throw $=String(V),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(V).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return ge}function ne(V,$,F){if(V==null)return V;var P=[],ue=0;return q(V,P,"","",function(me){return $.call(F,me,ue++)}),P}function ae(V){if(V._status===-1){var $=V._result;$=$(),$.then(function(F){(V._status===0||V._status===-1)&&(V._status=1,V._result=F)},function(F){(V._status===0||V._status===-1)&&(V._status=2,V._result=F)}),V._status===-1&&(V._status=0,V._result=$)}if(V._status===1)return V._result.default;throw V._result}var Y=typeof reportError=="function"?reportError:function(V){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof V=="object"&&V!==null&&typeof V.message=="string"?String(V.message):String(V),error:V});if(!window.dispatchEvent($))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",V);return}console.error(V)},je={map:ne,forEach:function(V,$,F){ne(V,function(){$.apply(this,arguments)},F)},count:function(V){var $=0;return ne(V,function(){$++}),$},toArray:function(V){return ne(V,function($){return $})||[]},only:function(V){if(!L(V))throw Error("React.Children.only expected to receive a single React element child.");return V}};return ds.Activity=g,ds.Children=je,ds.Component=C,ds.Fragment=a,ds.Profiler=i,ds.PureComponent=I,ds.StrictMode=s,ds.Suspense=
vendor: 16,161 bytes, lines 17-43
17d,ds.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=G,ds.__COMPILER_RUNTIME={__proto__:null,c:function(V){return G.H.useMemoCache(V)}},ds.cache=function(V){return function(){return V.apply(null,arguments)}},ds.cacheSignal=function(){return null},ds.cloneElement=function(V,$,F){if(V==null)throw Error("The argument must be a React element, but you passed "+V+".");var P=N({},V.props),ue=V.key;if($!=null)for(me in $.key!==void 0&&(ue=""+$.key),$)!z.call($,me)||me==="key"||me==="__self"||me==="__source"||me==="ref"&&$.ref===void 0||(P[me]=$[me]);var me=arguments.length-2;if(me===1)P.children=F;else if(1<me){for(var ge=Array(me),de=0;de<me;de++)ge[de]=arguments[de+2];P.children=ge}return H(V.type,ue,P)},ds.createContext=function(V){return V={$$typeof:l,_currentValue:V,_currentValue2:V,_threadCount:0,Provider:null,Consumer:null},V.Provider=V,V.Consumer={$$typeof:c,_context:V},V},ds.createElement=function(V,$,F){var P,ue={},me=null;if($!=null)for(P in $.key!==void 0&&(me=""+$.key),$)z.call($,P)&&P!=="key"&&P!=="__self"&&P!=="__source"&&(ue[P]=$[P]);var ge=arguments.length-2;if(ge===1)ue.children=F;else if(1<ge){for(var de=Array(ge),Pe=0;Pe<ge;Pe++)de[Pe]=arguments[Pe+2];ue.children=de}if(V&&V.defaultProps)for(P in ge=V.defaultProps,ge)ue[P]===void 0&&(ue[P]=ge[P]);return H(V,me,ue)},ds.createRef=function(){return{current:null}},ds.forwardRef=function(V){return{$$typeof:m,render:V}},ds.isValidElement=L,ds.lazy=function(V){return{$$typeof:f,_payload:{_status:-1,_result:V},_init:ae}},ds.memo=function(V,$){return{$$typeof:u,type:V,compare:$===void 0?null:$}},ds.startTransition=function(V){var $=G.T,F={};G.T=F;try{var P=V(),ue=G.S;ue!==null&&ue(F,P),typeof P=="object"&&P!==null&&typeof P.then=="function"&&P.then(T,Y)}catch(me){Y(me)}finally{$!==null&&F.types!==null&&($.types=F.types),G.T=$}},ds.unstable_useCacheRefresh=function(){return G.H.useCacheRefresh()},ds.use=function(V){return G.H.use(V)},ds.useActionState=function(V,$,F){return G.H.useActionState(V,$,F)},ds.useCallback=function(V,$){return G.H.useCallback(V,$)},ds.useContext=function(V){return G.H.useContext(V)},ds.useDebugValue=function(){},ds.useDeferredValue=function(V,$){return G.H.useDeferredValue(V,$)},ds.useEffect=function(V,$){return G.H.useEffect(V,$)},ds.useEffectEvent=function(V){return G.H.useEffectEvent(V)},ds.useId=function(){return G.H.useId()},ds.useImperativeHandle=function(V,$,F){return G.H.useImperativeHandle(V,$,F)},ds.useInsertionEffect=function(V,$){return G.H.useInsertionEffect(V,$)},ds.useLayoutEffect=function(V,$){return G.H.useLayoutEffect(V,$)},ds.useMemo=function(V,$){return G.H.useMemo(V,$)},ds.useOptimistic=function(V,$){return G.H.useOptimistic(V,$)},ds.useReducer=function(V,$,F){return G.H.useReducer(V,$,F)},ds.useRef=function(V){return G.H.useRef(V)},ds.useState=function(V){return G.H.useState(V)},ds.useSyncExternalStore=function(V,$,F){return G.H.useSyncExternalStore(V,$,F)},ds.useTransition=function(){return G.H.useTransition()},ds.version="19.2.8",ds}var MS;function zb(){return MS||(MS=1,_0.exports=oR()),_0.exports}var x=zb();const xi=Ub(x);var k0={exports:{}},mf={},D0={exports:{}},E0={};/** 18 * @license React 19 * scheduler.production.js 20 * 21 * Copyright (c) Meta Platforms, Inc. and affiliates. 22 * 23 * This source code is licensed under the MIT license found in the 24 * LICENSE file in the root directory of this source tree. 25 */var $S;function cR(){return $S||($S=1,(function(t){function n(q,ne){var ae=q.length;q.push(ne);e:for(;0<ae;){var Y=ae-1>>>1,je=q[Y];if(0<i(je,ne))q[Y]=ne,q[ae]=je,ae=Y;else break e}}function a(q){return q.length===0?null:q[0]}function s(q){if(q.length===0)return null;var ne=q[0],ae=q.pop();if(ae!==ne){q[0]=ae;e:for(var Y=0,je=q.length,V=je>>>1;Y<V;){var $=2*(Y+1)-1,F=q[$],P=$+1,ue=q[P];if(0>i(F,ae))P<je&&0>i(ue,F)?(q[Y]=ue,q[P]=ae,Y=P):(q[Y]=F,q[$]=ae,Y=$);else if(P<je&&0>i(ue,ae))q[Y]=ue,q[P]=ae,Y=P;else break e}}return ne}function i(q,ne){var ae=q.sortIndex-ne.sortIndex;return ae!==0?ae:q.id-ne.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;t.unstable_now=function(){return c.now()}}else{var l=Date,m=l.now();t.unstable_now=function(){return l.now()-m}}var d=[],u=[],f=1,g=null,p=3,y=!1,b=!1,N=!1,w=!1,C=typeof setTimeout=="function"?setTimeout:null,R=typeof clearTimeout=="function"?clearTimeout:null,I=typeof setImmediate<"u"?setImmediate:null;function _(q){for(var ne=a(u);ne!==null;){if(ne.callback===null)s(u);else if(ne.startTime<=q)s(u),ne.sortIndex=ne.expirationTime,n(d,ne);else break;ne=a(u)}}function J(q){if(N=!1,_(q),!b)if(a(d)!==null)b=!0,T||(T=!0,D());else{var ne=a(u);ne!==null&&fe(J,ne.startTime-q)}}var T=!1,G=-1,z=5,H=-1;function K(){return w?!0:!(t.unstable_now()-H<z)}function L(){if(w=!1,T){var q=t.unstable_now();H=q;var ne=!0;try{e:{b=!1,N&&(N=!1,R(G),G=-1),y=!0;var ae=p;try{t:{for(_(q),g=a(d);g!==null&&!(g.expirationTime>q&&K());){var Y=g.callback;if(typeof Y=="function"){g.callback=null,p=g.priorityLevel;var je=Y(g.expirationTime<=q);if(q=t.unstable_now(),typeof je=="function"){g.callback=je,_(q),ne=!0;break t}g===a(d)&&s(d),_(q)}else s(d);g=a(d)}if(g!==null)ne=!0;else{var V=a(u);V!==null&&fe(J,V.startTime-q),ne=!1}}break e}finally{g=null,p=ae,y=!1}ne=void 0}}finally{ne?D():T=!1}}}var D;if(typeof I=="function")D=function(){I(L)};else if(typeof MessageChannel<"u"){var M=new MessageChannel,Z=M.port2;M.port1.onmessage=L,D=function(){Z.postMessage(null)}}else D=function(){C(L,0)};function fe(q,ne){G=C(function(){q(t.unstable_now())},ne)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(q){q.callback=null},t.unstable_forceFrameRate=function(q){0>q||125<q?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):z=0<q?Math.floor(1e3/q):5},t.unstable_getCurrentPriorityLevel=function(){return p},t.unstable_next=function(q){switch(p){case 1:case 2:case 3:var ne=3;break;default:ne=p}var ae=p;p=ne;try{return q()}finally{p=ae}},t.unstable_requestPaint=function(){w=!0},t.unstable_runWithPriority=function(q,ne){switch(q){case 1:case 2:case 3:case 4:case 5:break;default:q=3}var ae=p;p=q;try{return ne()}finally{p=ae}},t.unstable_scheduleCallback=function(q,ne,ae){var Y=t.unstable_now();switch(typeof ae=="object"&&ae!==null?(ae=ae.delay,ae=typeof ae=="number"&&0<ae?Y+ae:Y):ae=Y,q){case 1:var je=-1;break;case 2:je=250;break;case 5:je=1073741823;break;case 4:je=1e4;break;default:je=5e3}return je=ae+je,q={id:f++,callback:ne,priorityLevel:q,startTime:ae,expirationTime:je,sortIndex:-1},ae>Y?(q.sortIndex=ae,n(u,q),a(d)===null&&q===a(u)&&(N?(R(G),G=-1):N=!0,fe(J,ae-Y))):(q.sortIndex=je,n(d,q),b||y||(b=!0,T||(T=!0,D()))),q},t.unstable_shouldYield=K,t.unstable_wrapCallback=function(q){var ne=p;return function(){var ae=p;p=ne;try{return q.apply(this,arguments)}finally{p=ae}}}})(E0)),E0}var OS;function lR(){return OS||(OS=1,D0.exports=cR()),D0.exports}var P0={exports:{}},io={};/** 26 * @license React 27 * react-dom.production.js 28 * 29 * Copyright (c) Meta Platforms, Inc. and affiliates. 30 * 31 * This source code is licensed under the MIT license found in the 32 * LICENSE file in the root directory of this source tree. 33 */var LS;function dR(){if(LS)return io;LS=1;var t=zb();function n(d){var u="https://react.dev/errors/"+d;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)u+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+d+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(){}var s={d:{f:a,r:function(){throw Error(n(522))},D:a,C:a,L:a,m:a,X:a,S:a,M:a},p:0,findDOMNode:null},i=Symbol.for("react.portal");function c(d,u,f){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:g==null?null:""+g,children:d,containerInfo:u,implementation:f}}var l=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function m(d,u){if(d==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return io.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=s,io.createPortal=function(d,u){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(n(299));return c(d,u,null,f)},io.flushSync=function(d){var u=l.T,f=s.p;try{if(l.T=null,s.p=2,d)return d()}finally{l.T=u,s.p=f,s.d.f()}},io.preconnect=function(d,u){typeof d=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,s.d.C(d,u))},io.prefetchDNS=function(d){typeof d=="string"&&s.d.D(d)},io.preinit=function(d,u){if(typeof d=="string"&&u&&typeof u.as=="string"){var f=u.as,g=m(f,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,y=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;f==="style"?s.d.S(d,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:g,integrity:p,fetchPriority:y}):f==="script"&&s.d.X(d,{crossOrigin:g,integrity:p,fetchPriority:y,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},io.preinitModule=function(d,u){if(typeof d=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var f=m(u.as,u.crossOrigin);s.d.M(d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&s.d.M(d)},io.preload=function(d,u){if(typeof d=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var f=u.as,g=m(f,u.crossOrigin);s.d.L(d,f,{crossOrigin:g,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},io.preloadModule=function(d,u){if(typeof d=="string")if(u){var f=m(u.as,u.crossOrigin);s.d.m(d,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else s.d.m(d)},io.requestFormReset=function(d){s.d.r(d)},io.unstable_batchedUpdates=function(d,u){return d(u)},io.useFormState=function(d,u,f){return l.H.useFormState(d,u,f)},io.useFormStatus=function(){return l.H.useHostTransitionStatus()},io.version="19.2.8",io}var BS;function uR(){if(BS)return P0.exports;BS=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),P0.exports=dR(),P0.exports}/** 34 * @license React 35 * react-dom-client.production.js 36 * 37 * Copyright (c) Meta Platforms, Inc. and affiliates. 38 * 39 * This source code is licensed under the MIT license found in the 40 * LICENSE file in the root directory of this source tree. 41 */var FS;function hR(){if(FS)return mf;FS=1;var t=lR(),n=zb(),a=uR();function s(r){var o="https://react.dev/errors/"+r;if(1<arguments.length){o+="?args[]="+encodeURIComponent(arguments[1]);for(var h=2;h<arguments.length;h++)o+="&args[]="+encodeURIComponent(arguments[h])}return"Minified React error #"+r+"; visit "+o+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(r){return!(!r||r.nodeType!==1&&r.nodeType!==9&&r.nodeType!==11)}function c(r){var o=r,h=r;if(r.alternate)for(;o.return;)o=o.return;else{r=o;do o=r,(o.flags&4098)!==0&&(h=o.return),r=o.return;while(r)}return o.tag===3?h:null}function l(r){if(r.tag===13){var o=r.memoizedState;if(o===null&&(r=r.alternate,r!==null&&(o=r.memoizedState)),o!==null)return o.dehydrated}return null}function m(r){if(r.tag===31){var o=r.memoizedState;if(o===null&&(r=r.alternate,r!==null&&(o=r.memoizedState)),o!==null)return o.dehydrated}return null}function d(r){if(c(r)!==r)throw Error(s(188))}function u(r){var o=r.alternate;if(!o){if(o=c(r),o===null)throw Error(s(188));return o!==r?null:r}for(var h=r,v=o;;){var A=h.return;if(A===null)break;var O=A.alternate;if(O===null){if(v=A.return,v!==null){h=v;continue}break}if(A.child===O.child){for(O=A.child;O;){if(O===h)return d(A),r;if(O===v)return d(A),o;O=O.sibling}throw Error(s(188))}if(h.return!==v.return)h=A,v=O;else{for(var Ne=!1,et=A.child;et;){if(et===h){Ne=!0,h=A,v=O;break}if(et===v){Ne=!0,v=A,h=O;break}et=et.sibling}if(!Ne){for(et=O.child;et;){if(et===h){Ne=!0,h=O,v=A;break}if(et===v){Ne=!0,v=O,h=A;break}et=et.sibling}if(!Ne)throw Error(s(189))}}if(h.alternate!==v)throw Error(s(190))}if(h.tag!==3)throw Error(s(188));return h.stateNode.current===h?r:o}function f(r){var o=r.tag;if(o===5||o===26||o===27||o===6)return r;for(r=r.child;r!==null;){if(o=f(r),o!==null)return o;r=r.sibling}return null}var g=Object.assign,p=Symbol.for("react.element"),y=Symbol.for("react.transitional.element"),b=Symbol.for("react.portal"),N=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),R=Symbol.for("react.consumer"),I=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),J=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),G=Symbol.for("react.memo"),z=Symbol.for("react.lazy"),H=Symbol.for("react.activity"),K=Symbol.for("react.memo_cache_sentinel"),L=Symbol.iterator;function D(r){return r===null||typeof r!="object"?null:(r=L&&r[L]||r["@@iterator"],typeof r=="function"?r:null)}var M=Symbol.for("react.client.reference");function Z(r){if(r==null)return null;if(typeof r=="function")return r.$$typeof===M?null:r.displayName||r.name||null;if(typeof r=="string")return r;switch(r){case N:return"Fragment";case C:return"Profiler";case w:return"StrictMode";case J:return"Suspense";case T:return"SuspenseList";case H:return"Activity"}if(typeof r=="object")switch(r.$$typeof){case b:return"Portal";case I:return r.displayName||"Context";case R:return(r._context.displayName||"Context")+".Consumer";case _:var o=r.render;return r=r.displayName,r||(r=o.displayName||o.name||"",r=r!==""?"ForwardRef("+r+")":"ForwardRef"),r;case G:return o=r.displayName||null,o!==null?o:Z(r.type)||"Memo";case z:o=r._payload,r=r._init;try{return Z(r(o))}catch{}}return null}var fe=Array.isArray,q=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ne=a.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ae={pending:!1,data:null,method:null,action:null},Y=[],je=-1;function V(r){return{current:r}}function $(r){0>je||(r.current=Y[je],Y[je]=null,je--)}function F(r,o){je++,Y[je]=r.current,r.current=o}var P=V(null),ue=V(null),me=V(null),ge=V(null);function de(r,o){switch(F(me,o),F(ue,r),F(P,null),o.nodeType){case 9:case 11:r=(r=o.documentElement)&&(r=r.namespaceURI)?eS(r):0;break;default:if(r=o.tagName,o=o.namespaceURI)o=eS(o),r=tS(o,r);else switch(r){case"svg":r=1;break;case"math":r=2;break;default:r=0}}$(P),F(P,r)}function Pe(){$(P),$(ue),$(me)}function Re(r){r.memoizedState!==null&&F(ge,r);var o=P.current,h=tS(o,r.type);o!==h&&(F(ue,r),F(P,h))}function Ee(r){ue.current===r&&($(P),$(ue)),ge.current===r&&($(ge),cf._currentValue=ae)}var Be,We;function it(r){if(Be===void 0)try{throw Error()}catch(h){var o=h.stack.trim().match(/\n( *(at )?)/);Be=o&&o[1]||"",We=-1<h.stack.indexOf(` 42 at`)?" (<anonymous>)":-1<h.stack.indexOf("@")?"@unknown:0:0":""}return` 43`+Be+r+We}var _e=!1;function ee(r,o){if(!r||_e)return"";_e=!0;var h=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var v={DetermineComponentFrameRoot:function(){try{if(o){var qn=function(){throw Error()};if(Object.defineProperty(qn.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(qn,[])}catch(bn){var fn=bn}Reflect.construct(r,[],qn)}else{try{qn.call()}catch(bn){fn=bn}r.call(qn.prototype)}}else{try{throw Error()}catch(bn){fn=bn}(qn=r())&&typeof qn.catch=="function"&&qn.catch(function(){})}}
vendor: 5,438 bytes, lines 43-48
43catch(bn){if(bn&&fn&&typeof bn.stack=="string")return[bn.stack,fn.stack]}return[null,null]}};v.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var A=Object.getOwnPropertyDescriptor(v.DetermineComponentFrameRoot,"name");A&&A.configurable&&Object.defineProperty(v.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var O=v.DetermineComponentFrameRoot(),Ne=O[0],et=O[1];if(Ne&&et){var _t=Ne.split(` 44`),hn=et.split(` 45`);for(A=v=0;v<_t.length&&!_t[v].includes("DetermineComponentFrameRoot");)v++;for(;A<hn.length&&!hn[A].includes("DetermineComponentFrameRoot");)A++;if(v===_t.length||A===hn.length)for(v=_t.length-1,A=hn.length-1;1<=v&&0<=A&&_t[v]!==hn[A];)A--;for(;1<=v&&0<=A;v--,A--)if(_t[v]!==hn[A]){if(v!==1||A!==1)do if(v--,A--,0>A||_t[v]!==hn[A]){var Dn=` 46`+_t[v].replace(" at new "," at ");return r.displayName&&Dn.includes("<anonymous>")&&(Dn=Dn.replace("<anonymous>",r.displayName)),Dn}while(1<=v&&0<=A);break}}}finally{_e=!1,Error.prepareStackTrace=h}return(h=r?r.displayName||r.name:"")?it(h):""}function qe(r,o){switch(r.tag){case 26:case 27:case 5:return it(r.type);case 16:return it("Lazy");case 13:return r.child!==o&&o!==null?it("Suspense Fallback"):it("Suspense");case 19:return it("SuspenseList");case 0:case 15:return ee(r.type,!1);case 11:return ee(r.type.render,!1);case 1:return ee(r.type,!0);case 31:return it("Activity");default:return""}}function se(r){try{var o="",h=null;do o+=qe(r,h),h=r,r=r.return;while(r);return o}catch(v){return` 47Error generating stack: `+v.message+` 48`+v.stack}}var pe=Object.prototype.hasOwnProperty,Se=t.unstable_scheduleCallback,Me=t.unstable_cancelCallback,ot=t.unstable_shouldYield,wt=t.unstable_requestPaint,ct=t.unstable_now,Ce=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,Te=t.unstable_UserBlockingPriority,ce=t.unstable_NormalPriority,Ye=t.unstable_LowPriority,Je=t.unstable_IdlePriority,le=t.log,nt=t.unstable_setDisableYieldValue,xt=null,te=null;function Ge(r){if(typeof le=="function"&&nt(r),te&&typeof te.setStrictMode=="function")try{te.setStrictMode(xt,r)}catch{}}var pt=Math.clz32?Math.clz32:Nt,$e=Math.log,st=Math.LN2;function Nt(r){return r>>>=0,r===0?32:31-($e(r)/st|0)|0}var be=256,jt=262144,bt=4194304;function tn(r){var o=r&42;if(o!==0)return o;switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return r&261888;case 262144:case 524288:case 1048576:case 2097152:return r&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return r&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return r}}function B(r,o,h){var v=r.pendingLanes;if(v===0)return 0;var A=0,O=r.suspendedLanes,Ne=r.pingedLanes;r=r.warmLanes;var et=v&134217727;return et!==0?(v=et&~O,v!==0?A=tn(v):(Ne&=et,Ne!==0?A=tn(Ne):h||(h=et&~r,h!==0&&(A=tn(h))))):(et=v&~O,et!==0?A=tn(et):Ne!==0?A=tn(Ne):h||(h=v&~r,h!==0&&(A=tn(h)))),A===0?0:o!==0&&o!==A&&(o&O)===0&&(O=A&-A,h=o&-o,O>=h||O===32&&(h&4194048)!==0)?o:A}function xe(r,o){return(r.pendingLanes&~(r.suspendedLanes&~r.pingedLanes)&o)===0}function tt(r,o){switch(r){case 1:case 2:case 4:case 8:case 64:return o+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return o+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ht(){var r=bt;return bt<<=1,(bt&62914560)===0&&(bt=4194304),r}function dt(r){for(var o=[],h=0;31>h;h++)o.push(r);return o}function we(r,o){r.pendingLanes|=o,o!==268435456&&(r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0)}function rt(r,o,h,v,A,O){var Ne=r.pendingLanes;r.pendingLanes=h,r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0,r.expiredLanes&=h,r.entangledLanes&=h,r.errorRecoveryDisabledLanes&=h,r.shellSuspendCounter=0;var et=r.entanglements,_t=r.expirationTimes,hn=r.hiddenUpdates;for(h=Ne&~h;0<h;){var Dn=31-pt(h),qn=1<<Dn;et[Dn]=0,_t[Dn]=-1;var fn=hn[Dn];if(fn!==null)for(hn[Dn]=null,Dn=0;Dn<fn.length;Dn++){var bn=fn[Dn];bn!==null&&(bn.lane&=-536870913)}h&=~qn}v!==0&&St(r,v,0),O!==0&&A===0&&r.tag!==0&&(r.suspendedLanes|=O&~(Ne&~o))}function St(r,o,h){r.pendingLanes|=o,r.suspendedLanes&=~o;var v=31-pt(o);r.entangledLanes|=o,r.entanglements[v]=r.entanglements[v]|1073741824|h&261930}function Qt(r,o){var h=r.entangledLanes|=o;for(r=r.entanglements;h;){var v=31-pt(h),A=1<<v;A&o|r[v]&o&&(r[v]|=o),h&=~A}}function gn(r,o){var h=o&-o;return h=(h&42)!==0?1:An(h),(h&(r.suspendedLanes|o))!==0?0:h}function An(r){switch(r){case 2:r=1;break;case 8:r=4;break;case 32:r=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:r=128;break;case 268435456:r=134217728;break;default:r=0}return r}function Sn(r){return r&=-r,2<r?8<r?(r&134217727)!==0?32:268435456:8:2}function Xt(){var r=ne.p;return r!==0?r:(r=window.event,r===void 0?32:SS(r.type))}function Wt(r,o){var h=ne.p;try{return ne.p=r,o()}finally{ne.p=h}}
vendor: 7,895 bytes, line 48
48var Gt=Math.random().toString(36).slice(2),$t="__reactFiber$"+Gt,Vt="__reactProps$"+Gt,sn="__reactContainer$"+Gt,on="__reactEvents$"+Gt,ke="__reactListeners$"+Gt,Ct="__reactHandles$"+Gt,Et="__reactResources$"+Gt,Rt="__reactMarker$"+Gt;function xn(r){delete r[$t],delete r[Vt],delete r[on],delete r[ke],delete r[Ct]}function dn(r){var o=r[$t];if(o)return o;for(var h=r.parentNode;h;){if(o=h[sn]||h[$t]){if(h=o.alternate,o.child!==null||h!==null&&h.child!==null)for(r=cS(r);r!==null;){if(h=r[$t])return h;r=cS(r)}return o}r=h,h=r.parentNode}return null}function Ln(r){if(r=r[$t]||r[sn]){var o=r.tag;if(o===5||o===6||o===13||o===31||o===26||o===27||o===3)return r}return null}function wa(r){var o=r.tag;if(o===5||o===26||o===27||o===6)return r.stateNode;throw Error(s(33))}function Ca(r){var o=r[Et];return o||(o=r[Et]={hoistableStyles:new Map,hoistableScripts:new Map}),o}function In(r){r[Rt]=!0}var Sa=new Set,aa={};function $a(r,o){jn(r,o),jn(r+"Capture",o)}function jn(r,o){for(aa[r]=o,r=0;r<o.length;r++)Sa.add(o[r])}var vs=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),ka={},Ja={};function _n(r){return pe.call(Ja,r)?!0:pe.call(ka,r)?!1:vs.test(r)?Ja[r]=!0:(ka[r]=!0,!1)}function ha(r,o,h){if(_n(o))if(h===null)r.removeAttribute(o);else{switch(typeof h){case"undefined":case"function":case"symbol":r.removeAttribute(o);return;case"boolean":var v=o.toLowerCase().slice(0,5);if(v!=="data-"&&v!=="aria-"){r.removeAttribute(o);return}}r.setAttribute(o,""+h)}}function ta(r,o,h){if(h===null)r.removeAttribute(o);else{switch(typeof h){case"undefined":case"function":case"symbol":case"boolean":r.removeAttribute(o);return}r.setAttribute(o,""+h)}}function W(r,o,h,v){if(v===null)r.removeAttribute(h);else{switch(typeof v){case"undefined":case"function":case"symbol":case"boolean":r.removeAttribute(h);return}r.setAttributeNS(o,h,""+v)}}function ft(r){switch(typeof r){case"bigint":case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function Zt(r){var o=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(o==="checkbox"||o==="radio")}function vt(r,o,h){var v=Object.getOwnPropertyDescriptor(r.constructor.prototype,o);if(!r.hasOwnProperty(o)&&typeof v<"u"&&typeof v.get=="function"&&typeof v.set=="function"){var A=v.get,O=v.set;return Object.defineProperty(r,o,{configurable:!0,get:function(){return A.call(this)},set:function(Ne){h=""+Ne,O.call(this,Ne)}}),Object.defineProperty(r,o,{enumerable:v.enumerable}),{getValue:function(){return h},setValue:function(Ne){h=""+Ne},stopTracking:function(){r._valueTracker=null,delete r[o]}}}}function Ae(r){if(!r._valueTracker){var o=Zt(r)?"checked":"value";r._valueTracker=vt(r,o,""+r[o])}}function oe(r){if(!r)return!1;var o=r._valueTracker;if(!o)return!0;var h=o.getValue(),v="";return r&&(v=Zt(r)?r.checked?"true":"false":r.value),r=v,r!==h?(o.setValue(r),!0):!1}function Ve(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}var he=/[\n"\\]/g;function Oe(r){return r.replace(he,function(o){return"\\"+o.charCodeAt(0).toString(16)+" "})}function ut(r,o,h,v,A,O,Ne,et){r.name="",Ne!=null&&typeof Ne!="function"&&typeof Ne!="symbol"&&typeof Ne!="boolean"?r.type=Ne:r.removeAttribute("type"),o!=null?Ne==="number"?(o===0&&r.value===""||r.value!=o)&&(r.value=""+ft(o)):r.value!==""+ft(o)&&(r.value=""+ft(o)):Ne!=="submit"&&Ne!=="reset"||r.removeAttribute("value"),o!=null?en(r,Ne,ft(o)):h!=null?en(r,Ne,ft(h)):v!=null&&r.removeAttribute("value"),A==null&&O!=null&&(r.defaultChecked=!!O),A!=null&&(r.checked=A&&typeof A!="function"&&typeof A!="symbol"),et!=null&&typeof et!="function"&&typeof et!="symbol"&&typeof et!="boolean"?r.name=""+ft(et):r.removeAttribute("name")}function At(r,o,h,v,A,O,Ne,et){if(O!=null&&typeof O!="function"&&typeof O!="symbol"&&typeof O!="boolean"&&(r.type=O),o!=null||h!=null){if(!(O!=="submit"&&O!=="reset"||o!=null)){Ae(r);return}h=h!=null?""+ft(h):"",o=o!=null?""+ft(o):h,et||o===r.value||(r.value=o),r.defaultValue=o}v=v??A,v=typeof v!="function"&&typeof v!="symbol"&&!!v,r.checked=et?r.checked:!!v,r.defaultChecked=!!v,Ne!=null&&typeof Ne!="function"&&typeof Ne!="symbol"&&typeof Ne!="boolean"&&(r.name=Ne),Ae(r)}function en(r,o,h){o==="number"&&Ve(r.ownerDocument)===r||r.defaultValue===""+h||(r.defaultValue=""+h)}function It(r,o,h,v){if(r=r.options,o){o={};for(var A=0;A<h.length;A++)o["$"+h[A]]=!0;for(h=0;h<r.length;h++)A=o.hasOwnProperty("$"+r[h].value),r[h].selected!==A&&(r[h].selected=A),A&&v&&(r[h].defaultSelected=!0)}else{for(h=""+ft(h),o=null,A=0;A<r.length;A++){if(r[A].value===h){r[A].selected=!0,v&&(r[A].defaultSelected=!0);return}o!==null||r[A].disabled||(o=r[A])}o!==null&&(o.selected=!0)}}function Pt(r,o,h){if(o!=null&&(o=""+ft(o),o!==r.value&&(r.value=o),h==null)){r.defaultValue!==o&&(r.defaultValue=o);return}r.defaultValue=h!=null?""+ft(h):""}function Jn(r,o,h,v){if(o==null){if(v!=null){if(h!=null)throw Error(s(92));if(fe(v)){if(1<v.length)throw Error(s(93));v=v[0]}h=v}h==null&&(h=""),o=h}h=ft(o),r.defaultValue=h,v=r.textContent,v===h&&v!==""&&v!==null&&(r.value=v),Ae(r)}function na(r,o){if(o){var h=r.firstChild;if(h&&h===r.lastChild&&h.nodeType===3){h.nodeValue=o;return}}r.textContent=o}var Mn=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Ea(r,o,h){var v=o.indexOf("--")===0;h==null||typeof h=="boolean"||h===""?v?r.setProperty(o,""):o==="float"?r.cssFloat="":r[o]="":v?r.setProperty(o,h):typeof h!="number"||h===0||Mn.has(o)?o==="float"?r.cssFloat=h:r[o]=(""+h).trim():r[o]=h+"px"}function ga(r,o,h){if(o!=null&&typeof o!="object")throw Error(s(62));if(r=r.style,h!=null){for(var v in h)!h.hasOwnProperty(v)||o!=null&&o.hasOwnProperty(v)||(v.indexOf("--")===0?r.setProperty(v,""):v==="float"?r.cssFloat="":r[v]="");for(var A in o)v=o[A],o.hasOwnProperty(A)&&h[A]!==v&&Ea(r,A,v)}else for(var O in o)o.hasOwnProperty(O)&&Ea(r,O,o[O])}function zn(r){if(r.indexOf("-")===-1)return!1;switch(r){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Xn=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRen
48dering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Vn=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function ua(r){return Vn.test(""+r)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":r}function Ma(){}var Xe=null;function Jt(r){return r=r.target||r.srcElement||window,r.correspondingUseElement&&(r=r.correspondingUseElement),r.nodeType===3?r.parentNode:r}var Ht=null,xa=null;function ra(r){var o=Ln(r);if(o&&(r=o.stateNode)){var h=r[Vt]||null;e:switch(r=o.stateNode,o.type){case"input":if(ut(r,h.value,h.defaultValue,h.defaultValue,h.checked,h.defaultChecked,h.type,h.name),o=h.name,h.type==="radio"&&o!=null){for(h=r;h.parentNode;)h=h.parentNode;for(h=h.querySelectorAll('input[name="'+Oe(""+o)+'"][type="radio"]'),o=0;o<h.length;o++){var v=h[o];if(v!==r&&v.form===r.form){var A=v[Vt]||null;if(!A)throw Error(s(90));ut(v,A.value,A.defaultValue,A.defaultValue,A.checked,A.defaultChecked,A.type,A.name)}}for(o=0;o<h.length;o++)v=h[o],v.form===r.form&&oe(v)}break e;case"textarea":Pt(r,h.value,h.defaultValue);break e;case"select":o=h.value,o!=null&&It(r,!!h.multiple,o,!1)}}}var Ha=!1;function is(r,o,h){if(Ha)return r(o,h);Ha=!0;try{var v=r(o);return v}finally{if(Ha=!1,(Ht!==null||xa!==null)&&(hy(),Ht&&(o=Ht,r=xa,xa=Ht=null,ra(o),r)))for(o=0;o<r.length;o++)ra(r[o])}}function hs(r,o){var h=r.stateNode;if(h===null)return null;var v=h[Vt]||null;if(v===null)return null;h=v[o];e:switch(o){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(v=!v.disabled)||(r=r.type,v=!(r==="button"||r==="input"||r==="select"||r==="textarea")),r=!v;break e;default:r=!1}if(r)return null;if(h&&typeof h!="function")throw Error(s(231,o,typeof h));return h}var rs=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),oa=!1;if(rs)try{var qa={};Object.defineProperty(qa,"passive",{get:function(){oa=!0}}),window.addEventListener("test",qa,qa),window.removeEventListener("test",qa,qa)}catch{oa=!1}var bs=null,Wa=null,$s=null;function jr(){if($s)return $s;var r,o=Wa,h=o.length,v,A="value"in bs?bs.value:bs.textContent,O=A.length;for(r=0;r<h&&o[r]===A[r];r++);var Ne=h-r;for(v=1;v<=Ne&&o[h-v]===A[O-v];v++);return $s=A.slice(r,1<v?1-v:void 0)}function Kr(r){var o=r.keyCode;return"charCode"in r?(r=r.charCode,r===0&&o===13&&(r=13)):r=o,r===10&&(r=13),32<=r||r===13?r:0}function Xr(){return!0}function Rr(){return!1}function er(r){function o(h,v,A,O,Ne){this._reactName=h,this._targetInst=A,this.type=v,this.nativeEvent=O,this.target=Ne,this.currentTarget=null;for(var et in r)r.hasOwnProperty(et)&&(h=r[et],this[et]=h?h(O):O[et]);return this.isDefaultPrevented=(O.defaultPrevented!=null?O.defaultPrevented:O.returnValue===!1)?Xr:Rr,this.isPropagationStopped=Rr,this}return g(o.prototype,{preventDefault:function(){this.defaultPrevented=!0;var h=this.nativeEvent;h&&(h.preventDefault?h.preventDefault():typeof h.returnValue!="unknown"&&(h.returnValue=!1),this.isDefaultPrevented=Xr)},stopPropagation:function(){var h=this.nativeEvent;h&&(h.stopPropagation?h.stopPropagation():typeof h.cancelBubble!="unknown"&&(h.cancelBubble=!0),this.isPropagationStopped=Xr)},persist:function(){},isPersistent:Xr}),o}var Ir={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(r){return r.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Qo=er(Ir),fo=g({},Ir,{view:0,detail:0}),Jo=er(fo),pr,Or,Js,Ko=g({},fo,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Oi,button:0,buttons:0,relatedTarget:function(r){return r.relatedTarget===void 0?r.fromElement===r.srcElement?r.toElement:r.fromElement:r.relatedTarget},movementX:function(r){return"movementX"in r?r.movementX:(r!==Js&&(Js&&r.type==="mousemove"?(pr=r.screenX-Js.screenX,Or=r.screenY-Js.screenY):Or=pr=0,Js=r),pr)},movementY:function(r){return"movementY"in r?r.movementY:Or}}),to=er(Ko),$i=g({},Ko,{dataTransfer:0}),Bc=er($i),no=g({},fo,{relatedTarget:0}),Fc=er(no),Xo=g({},Ir,{animationName:0,elapsedTime:0,pseudoElement:0}),Yl=er(Xo),Uc=g({},Ir,{clipboardData:function(r){return"clipboardData"in r?r.clipboardData:window.clipboardData}}),Gi=er(Uc),zc=g({},Ir,{data:0}),Zo=er(zc),qc={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ec={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},bc={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function vl(r){var o=this.nativeEvent;return o.getModifierState?o.getModifierState(r):(r=bc[r])?!!o[r]:!1}function Oi(){return vl}var tc=g({},fo,{key:function(r){if(r.key){var o=qc[r.key]||r.key;if(o!=="Unidentified")return o}
vendor: 5,178 bytes, line 48
48return r.type==="keypress"?(r=Kr(r),r===13?"Enter":String.fromCharCode(r)):r.type==="keydown"||r.type==="keyup"?ec[r.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Oi,charCode:function(r){return r.type==="keypress"?Kr(r):0},keyCode:function(r){return r.type==="keydown"||r.type==="keyup"?r.keyCode:0},which:function(r){return r.type==="keypress"?Kr(r):r.type==="keydown"||r.type==="keyup"?r.keyCode:0}}),Vc=er(tc),_o=g({},Ko,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),ko=er(_o),U=g({},fo,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Oi}),Ue=er(U),yt=g({},Ir,{propertyName:0,elapsedTime:0,pseudoElement:0}),kt=er(yt),an=g({},Ko,{deltaX:function(r){return"deltaX"in r?r.deltaX:"wheelDeltaX"in r?-r.wheelDeltaX:0},deltaY:function(r){return"deltaY"in r?r.deltaY:"wheelDeltaY"in r?-r.wheelDeltaY:"wheelDelta"in r?-r.wheelDelta:0},deltaZ:0,deltaMode:0}),Cn=er(an),Qn=g({},Ir,{newState:0,oldState:0}),E=er(Qn),Q=[9,13,27,32],Ie=rs&&"CompositionEvent"in window,Le=null;rs&&"documentMode"in document&&(Le=document.documentMode);var He=rs&&"TextEvent"in window&&!Le,gt=rs&&(!Ie||Le&&8<Le&&11>=Le),Dt=" ",Yt=!1;function vn(r,o){switch(r){case"keyup":return Q.indexOf(o.keyCode)!==-1;case"keydown":return o.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function zt(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Bt=!1;function En(r,o){switch(r){case"compositionend":return zt(o);case"keypress":return o.which!==32?null:(Yt=!0,Dt);case"textInput":return r=o.data,r===Dt&&Yt?null:r;default:return null}}function wn(r,o){if(Bt)return r==="compositionend"||!Ie&&vn(r,o)?(r=jr(),$s=Wa=bs=null,Bt=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(o.ctrlKey||o.altKey||o.metaKey)||o.ctrlKey&&o.altKey){if(o.char&&1<o.char.length)return o.char;if(o.which)return String.fromCharCode(o.which)}return null;case"compositionend":return gt&&o.locale!=="ko"?null:o.data;default:return null}}var ma={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function ca(r){var o=r&&r.nodeName&&r.nodeName.toLowerCase();return o==="input"?!!ma[r.type]:o==="textarea"}function Pa(r,o,h,v){Ht?xa?xa.push(v):xa=[v]:Ht=v,o=by(o,"onChange"),0<o.length&&(h=new Qo("onChange","change",null,h,v),r.push({event:h,listeners:o}))}var kn=null,Kn=null;function Zn(r){YN(r,0)}function da(r){var o=wa(r);if(oe(o))return r}function Ga(r,o){if(r==="change")return o}var Da=!1;if(rs){var Ia;if(rs){var ls="oninput"in document;if(!ls){var Ua=document.createElement("div");Ua.setAttribute("oninput","return;"),ls=typeof Ua.oninput=="function"}Ia=ls}else Ia=!1;Da=Ia&&(!document.documentMode||9<document.documentMode)}function va(){kn&&(kn.detachEvent("onpropertychange",_a),Kn=kn=null)}function _a(r){if(r.propertyName==="value"&&da(Kn)){var o=[];Pa(o,Kn,r,Jt(r)),is(Zn,o)}}function Vs(r,o,h){r==="focusin"?(va(),kn=o,Kn=h,kn.attachEvent("onpropertychange",_a)):r==="focusout"&&va()}function Hn(r){if(r==="selectionchange"||r==="keyup"||r==="keydown")return da(Kn)}function Fa(r,o){if(r==="click")return da(o)}function zs(r,o){if(r==="input"||r==="change")return da(o)}function Bs(r,o){return r===o&&(r!==0||1/r===1/o)||r!==r&&o!==o}var S=typeof Object.is=="function"?Object.is:Bs;function ye(r,o){if(S(r,o))return!0;if(typeof r!="object"||r===null||typeof o!="object"||o===null)return!1;var h=Object.keys(r),v=Object.keys(o);if(h.length!==v.length)return!1;for(v=0;v<h.length;v++){var A=h[v];if(!pe.call(o,A)||!S(r[A],o[A]))return!1}return!0}function Fe(r){for(;r&&r.firstChild;)r=r.firstChild;return r}function lt(r,o){var h=Fe(r);r=0;for(var v;h;){if(h.nodeType===3){if(v=r+h.textContent.length,r<=o&&v>=o)return{node:h,offset:o-r};r=v}e:{for(;h;){if(h.nextSibling){h=h.nextSibling;break e}h=h.parentNode}h=void 0}h=Fe(h)}}function Ot(r,o){return r&&o?r===o?!0:r&&r.nodeType===3?!1:o&&o.nodeType===3?Ot(r,o.parentNode):"contains"in r?r.contains(o):r.compareDocumentPosition?!!(r.compareDocumentPosition(o)&16):!1:!1}function Ft(r){r=r!=null&&r.ownerDocument!=null&&r.ownerDocument.defaultView!=null?r.ownerDocument.defaultView:window;for(var o=Ve(r.document);o instanceof r.HTMLIFrameElement;){try{var h=typeof o.contentWindow.location.href=="string"}catch{h=!1}if(h)r=o.contentWindow;else break;o=Ve(r.document)}return o}function rn(r){var o=r&&r.nodeName&&r.nodeName.toLowerCase();return o&&(o==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||o==="textarea"||r.contentEditable==="true")}var Rn=rs&&"documentMode"in document&&11>=document.documentMode,ea=null,Wn=null,Bn=null,Fn=!1;function Na(r,o,h){var v=h.window===h?h.document:h.nodeType===9?h:h.ownerDocument;Fn||ea==null||ea!==Ve(v)||(v=ea,"selectionStart"in v&&rn(v)?v={start:v.selectionStart,end:v.selectionEnd}:(v=(v.ownerDocument&&v.ownerDocument.defaultView||window).getSelection(),v={anchorNode:v.anchorNode,anchorOffset:v.anchorOffset,focu
vendor: 18,917 bytes, line 48
48sNode:v.focusNode,focusOffset:v.focusOffset}),Bn&&ye(Bn,v)||(Bn=v,v=by(Wn,"onSelect"),0<v.length&&(o=new Qo("onSelect","select",null,o,h),r.push({event:o,listeners:v}),o.target=ea)))}function ya(r,o){var h={};return h[r.toLowerCase()]=o.toLowerCase(),h["Webkit"+r]="webkit"+o,h["Moz"+r]="moz"+o,h}var Ba={animationend:ya("Animation","AnimationEnd"),animationiteration:ya("Animation","AnimationIteration"),animationstart:ya("Animation","AnimationStart"),transitionrun:ya("Transition","TransitionRun"),transitionstart:ya("Transition","TransitionStart"),transitioncancel:ya("Transition","TransitionCancel"),transitionend:ya("Transition","TransitionEnd")},Ya={},Os={};rs&&(Os=document.createElement("div").style,"AnimationEvent"in window||(delete Ba.animationend.animation,delete Ba.animationiteration.animation,delete Ba.animationstart.animation),"TransitionEvent"in window||delete Ba.transitionend.transition);function ys(r){if(Ya[r])return Ya[r];if(!Ba[r])return r;var o=Ba[r],h;for(h in o)if(o.hasOwnProperty(h)&&h in Os)return Ya[r]=o[h];return r}var _r=ys("animationend"),tr=ys("animationiteration"),wr=ys("animationstart"),Ns=ys("transitionrun"),Wr=ys("transitionstart"),nr=ys("transitioncancel"),Fs=ys("transitionend"),Hs=new Map,sr="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");sr.push("scrollEnd");function Ka(r,o){Hs.set(r,o),$a(o,[r])}var Ss=typeof reportError=="function"?reportError:function(r){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var o=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof r=="object"&&r!==null&&typeof r.message=="string"?String(r.message):String(r),error:r});if(!window.dispatchEvent(o))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",r);return}console.error(r)},Es=[],rr=0,ao=0;function xc(){for(var r=rr,o=ao=rr=0;o<r;){var h=Es[o];Es[o++]=null;var v=Es[o];Es[o++]=null;var A=Es[o];Es[o++]=null;var O=Es[o];if(Es[o++]=null,v!==null&&A!==null){var Ne=v.pending;Ne===null?A.next=A:(A.next=Ne.next,Ne.next=A),v.pending=A}O!==0&&Ju(h,A,O)}}function Do(r,o,h,v){Es[rr++]=r,Es[rr++]=o,Es[rr++]=h,Es[rr++]=v,ao|=v,r.lanes|=v,r=r.alternate,r!==null&&(r.lanes|=v)}function go(r,o,h,v){return Do(r,o,h,v),Li(r)}function Hc(r,o){return Do(r,null,null,o),Li(r)}function Ju(r,o,h){r.lanes|=h;var v=r.alternate;v!==null&&(v.lanes|=h);for(var A=!1,O=r.return;O!==null;)O.childLanes|=h,v=O.alternate,v!==null&&(v.childLanes|=h),O.tag===22&&(r=O.stateNode,r===null||r._visibility&1||(A=!0)),r=O,O=O.return;return r.tag===3?(O=r.stateNode,A&&o!==null&&(A=31-pt(h),r=O.hiddenUpdates,v=r[A],v===null?r[A]=[o]:v.push(o),o.lane=h|536870912),O):null}function Li(r){if(50<ef)throw ef=0,Kx=null,Error(s(185));for(var o=r.return;o!==null;)r=o,o=r.return;return r.tag===3?r.stateNode:null}var Ni={};function nm(r,o,h,v){this.tag=r,this.key=h,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=o,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=v,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Bi(r,o,h,v){return new nm(r,o,h,v)}function am(r){return r=r.prototype,!(!r||!r.isReactComponent)}function Eo(r,o){var h=r.alternate;return h===null?(h=Bi(r.tag,o,r.key,r.mode),h.elementType=r.elementType,h.type=r.type,h.stateNode=r.stateNode,h.alternate=r,r.alternate=h):(h.pendingProps=o,h.type=r.type,h.flags=0,h.subtreeFlags=0,h.deletions=null),h.flags=r.flags&65011712,h.childLanes=r.childLanes,h.lanes=r.lanes,h.child=r.child,h.memoizedProps=r.memoizedProps,h.memoizedState=r.memoizedState,h.updateQueue=r.updateQueue,o=r.dependencies,h.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext},h.sibling=r.sibling,h.index=r.index,h.ref=r.ref,h.refCleanup=r.refCleanup,h}function Ku(r,o){r.flags&=65011714;var h=r.alternate;return h===null?(r.childLanes=0,r.lanes=o,r.child=null,r.subtreeFlags=0,r.memoizedProps=null,r.memoizedState=null,r.updateQueue=null,r.dependencies=null,r.stateNode=null):(r.childLanes=h.childLanes,r.lanes=h.lanes,r.child=h.child,r.subtreeFlags=0,r.deletions=null,r.memoizedProps=h.memoizedProps,r.memoizedState=h.memoizedState,r.updateQueue=h.updateQueue,r.type=h.type,o=h.dependencies,r.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext}),r}function Md(r,o,h,v,A,O){var Ne=0;if(v=r,typeof r=="function")am(r)&&(Ne=1);else if(typeof r=="string")Ne=qP(r,h,P.current)?26:r==="html"||r==="head"||r==="body"?27:5;else e:switch(r){case H:return r=Bi(31,h,o,A),r.elementType=H,r.lanes=O,r;case N:return bl(h.children,A,O,o);case w:Ne=8,A|=24;break;case C:return r=Bi(12,h,o,A|2),r.elementType=C,r.lanes=O,r;case J:return r=Bi(13,h,o,A),r.elementType=J,r.lanes=O,r;case T:return r=Bi(19,h,o,A),r.elementType=T,r.lanes=O,r;default:if(typeof r=="object"&&r!==null)switch(r.$$typeof){case I:Ne=10;break e;case R:Ne=9;break e;case _:Ne=11;break e;case G:Ne=14;break e;case z:Ne=16,v=null;break e}Ne=29,h=Error(s(130,r===null?"null":typeof r,"")),v=null}return o=Bi(Ne,h,o,A),o.elementType=r,o.type=v,o.lanes=O,o}function bl(r,o,h,v){return r=Bi(7,r,v,o),r.lanes=h,r}function Xu(r,o,h){return r=Bi(6,r,null,o),r.lanes=h,r}function sm(r){var o=Bi(18,null,null,0);return o.stateNode=r,o}function $d(r,o,h){return o=Bi(4,r.children!==null?r.children:[],r.key,o),o.lanes=h,o.stateNode={containerInfo:r.containerInfo,pendingChildren:null,implementation:r.implementation},o}var rm=new WeakMap;function Po(r,o){if(typeof r=="object"&&r!==null){var h=rm.get(r);return h!==void 0?h:(o={value:r,source:o,stack:se(o)},rm.set(r,o),o)}return{value:r,source:o,stack:se(o)}}var Od=[],Ql=0,im=null,Zu=0,Ro=[],To=0,xl=null,Mo=1,$o="";function yo(r,o){Od[Ql++]=Zu,Od[Ql++]=im,im=r,Zu=o}function Hg(r,o,h){Ro[To++]=Mo,Ro[To++]=$o,Ro[To++]=xl,xl=r;var v=Mo;r=$o;var A=32-pt(v)-1;v&=~(1<<A),h+=1;var O=32-pt(o)+A;if(30<O){var Ne=A-A%5;O=(v&(1<<Ne)-1).toString(32),v>>=Ne,A-=Ne,Mo=1<<32-pt(o)+A|h<<A|v,$o=O+r}else Mo=1<<O|h<<A|v,$o=r}function Rp(r){r.return!==null&&(yo(r,1),Hg(r,1,0))}function om(r){for(;r===im;)im=Od[--Ql],Od[Ql]=null,Zu=Od[--Ql],Od[Ql]=null;for(;r===xl;)xl=Ro[--To],Ro[To]=null,$o=Ro[--To],Ro[To]=null,Mo=Ro[--To],Ro[To]=null}function Wg(r,o){Ro[To++]=Mo,Ro[To++]=$o,Ro[To++]=xl,Mo=o.id,$o=o.overflow,xl=r}var Si=null,Nr=null,Cs=!1,Yi=null,Lr=!1,nc=Error(s(519));function jl(r){var o=Error(s(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Ld(Po(o,r)),nc}function Tp(r){var o=r.stateNode,h=r.type,v=r.memoizedProps;switch(o[$t]=r,o[Vt]=v,h){case"dialog":_s("cancel",o),_s("close",o);break;case"iframe":case"object":case"embed":_s("load",o);break;case"video":case"audio":for(h=0;h<nf.length;h++)_s(nf[h],o);break;case"source":_s("error",o);break;case"img":case"image":case"link":_s("error",o),_s("load",o);break;case"details":_s("toggle",o);break;case"input":_s("invalid",o),At(o,v.value,v.defaultValue,v.checked,v.defaultChecked,v.type,v.name,!0);break;case"select":_s("invalid",o);break;case"textarea":_s("invalid",o),Jn(o,v.value,v.defaultValue,v.children)}h=v.children,typeof h!="string"&&typeof h!="number"&&typeof h!="bigint"||o.textContent===""+h||v.suppressHydrationWarning===!0||XN(o.textContent,h)?(v.popover!=null&&(_s("beforetoggle",o),_s("toggle",o)),v.onScroll!=null&&_s("scroll",o),v.onScrollEnd!=null&&_s("scrollend",o),v.onClick!=null&&(o.onclick=Ma),o=!0):o=!1,o||jl(r,!0)}function Wc(r){for(Si=r.return;Si;)switch(Si.tag){case 5:case 31:case 13:Lr=!1;return;case 27:case 3:Lr=!0;return;default:Si=Si.return}}function Ci(r){if(r!==Si)return!1;if(!Cs)return Wc(r),Cs=!0,!1;var o=r.tag,h;if((h=o!==3&&o!==27)&&((h=o===5)&&(h=r.type,h=!(h!=="form"&&h!=="button")||h0(r.type,r.memoizedProps)),h=!h),h&&Nr&&jl(r),Wc(r),o===13){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(s(317));Nr=oS(r)}else if(o===31){if(r=r.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(s(317));Nr=oS(r)}else o===27?(o=Nr,Xd(r.type)?(r=y0,y0=null,Nr=r):Nr=o):Nr=Si?Ic(r.stateNode.nextSibling):null;return!0}function Jl(){Nr=Si=null,Cs=!1}function Mp(){var r=Yi;return r!==null&&(zo===null?zo=r:zo.push.apply(zo,r),Yi=null),r}function Ld(r){Yi===null?Yi=[r]:Yi.push(r)}var cm=V(null),wl=null,jc=null;function Nl(r,o,h){F(cm,o._currentValue),o._currentValue=h}function Oo(r){r._currentValue=cm.current,$(cm)}function Bd(r,o,h){for(;r!==null;){var v=r.alternate;if((r.childLanes&o)!==o?(r.childLanes|=o,v!==null&&(v.childLanes|=o)):v!==null&&(v.childLanes&o)!==o&&(v.childLanes|=o),r===h)break;r=r.return}}function Kl(r,o,h,v){var A=r.child;for(A!==null&&(A.return=r);A!==null;){var O=A.dependencies;if(O!==null){var Ne=A.child;O=O.firstContext;e:for(;O!==null;){var et=O;O=A;for(var _t=0;_t<o.length;_t++)if(et.context===o[_t]){O.lanes|=h,et=O.alternate,et!==null&&(et.lanes|=h),Bd(O.return,h,r),v||(Ne=null);break e}O=et.next}}else if(A.tag===18){if(Ne=A.return,Ne===null)throw Error(s(341));Ne.lanes|=h,O=Ne.alternate,O!==null&&(O.lanes|=h),Bd(Ne,h,r),Ne=null}else Ne=A.child;if(Ne!==null)Ne.return=A;else for(Ne=A;Ne!==null;){if(Ne===r){Ne=null;break}if(A=Ne.sibling,A!==null){A.return=Ne.return,Ne=A;break}Ne=Ne.return}A=Ne}}function Sl(r,o,h,v){r=null;for(var A=o,O=!1;A!==null;){if(!O){if((A.flags&524288)!==0)O=!0;else if((A.flags&262144)!==0)break}if(A.tag===10){var Ne=A.alternate;if(Ne===null)throw Error(s(387));if(Ne=Ne.memoizedProps,Ne!==null){var et=A.type;S(A.pendingProps.value,Ne.value)||(r!==null?r.push(et):r=[et])}}else if(A===ge.current){if(Ne=A.alternate,Ne===null)throw Error(s(387));Ne.memoizedState.memoizedState!==A.memoizedState.memoizedState&&(r!==null?r.push(cf):r=[cf])}A=A.return}r!==null&&Kl(o,r,h,v),o.flags|=262144}function lm(r){for(r=r.firstContext;r!==null;){if(!S(r.context._currentValue,r.memoizedValue))return!0;r=r.next}return!1}function Cl(r){wl=r,jc=null,r=r.dependencies,r!==null&&(r.firstContext=null)}function Ai(r){return Gg(wl,r)}function dm(r,o){return wl===null&&Cl(r),Gg(r,o)}function Gg(r,o){var h=o._currentValue;if(o={context:o,memoizedValue:h,next:null},jc===null){if(r===null)throw Error(s(308));jc=o,r.dependencies={lanes:0,firstContext:o},r.flags|=524288}else jc=jc.next=o;return h}var gx=typeof AbortController<"u"?AbortController:function(){var r=[],o=this.signal={aborted:!1,addEventListener:function(h,v){r.push(v)}};this.abort=function(){o.aborted=!0,r.forEach(function(h){return h()})}},yx=t.unstable_scheduleCallback,vx=t.unstable_NormalPriority,Gr={$$typeof:I,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Fd(){return{controller:new gx,data:new Map,refCount:0}}function eh(r){r.refCount--,r.refCount===0&&yx(vx,function(){r.controller.abort()})}var th=null,um=0,j=0,k=null;function X(r,o){if(th===null){var h=th=[];um=0,j=a0(),k={status:"pending",value:void 0,then:function(v){h.push(v)}}}return um++,o.then(ve,ve),o}function ve(){if(--um===0&&th!==null){k!==null&&(k.status="fulfilled");var r=th;th=null,j=0,k=null;for(var o=0;o<r.length;o++)(0,r[o])()}}function ze(r,o){var h=[],v={status:"pending",value:null,reason:null,then:function(A){h.push(A)}};return r.then(function(){v.status="fulfilled",v.value=o;for(var A=0;A<h.length;A++)(0,h[A])(o)},function(A){for(v.status="rejected",v.reason=A,A=0;A<h.length;A++)(0,h[A])(void 0)}),v}var Qe=q.S;q.S=function(r,o){wN=ct(),typeof o=="object"&&o!==null&&typeof o.then=="function"&&X(r,o),Qe!==null&&Qe(r,o)};var Ke=V(null);function Ze(){var r=Ke.current;return r!==null?r:Cr.pooledCache}function at(r,o){o===null?F(Ke,Ke.current):F(Ke,o.pool)}function mt(){var r=Ze();return r===null?null:{parent:Gr._currentValue,pool:r}}var Tt=Error(s(460)),ln=Error(s(474)),cn=Error(s(542)),Kt={then:function(){}};function Un(r){return r=r.status,r==="fulfilled"||r==="rejected"}function Nn(r,o,h){switch(h=r[h],h===void 0?r.push(o):h!==o&&(o.then(Ma,Ma),o=h),o.status){case"fulfilled":return o.value;case"rejected":throw r=o.reason,Yn(r),r;default:if(typeof o.status=="string")o.then(Ma,Ma);else{if(r=Cr,r!==null&&100<r.shellSuspendCounter)throw Error(s(482));r=o,r.status="pending",r.then(function(v){if(o.status==="pending"){var A=o;A.status="fulfilled",A.value=v}},function(v){if(o.status==="pending"){var A=o;A.status="rejected",A.reason=v}})}switch(o.status){case"fulfilled":return o.value;case"rejected":throw r=o.reason,Yn(r),r}throw Ut=o,Tt}}function Mt(r){try{var o=r._init;return o(r._payload)}catch(h){throw h!==null&&typeof h=="object"&&typeof h.then=="function"?(Ut=h,Tt):h}}var Ut=null;function $n(){if(Ut===null)throw Error(s(459));var r=Ut;return Ut=null,r}function Yn(r){if(r===Tt||r===cn)throw Error(s(483))}var Tn=null,Aa=0;function fa(r){var o=Aa;return Aa+=1,Tn===null&&(Tn=[]),Nn(Tn,r,o)}function Va(r,o){o=o.props.ref,r.ref=o!==void 0?o:null}function ba(r,o){throw o.$$typeof===p?Error(s(525)):(r=Object.prototype.toString.call(o),Error(s(31,r==="[object Object]"?"object with keys {"+Object.keys(o).join(", ")+"}":r)))}function Us(r){function o(nn,Lt){if(r){var un=nn.deletions;un===null?(nn.deletions=[Lt],nn.flags|=16):un.push(Lt)}}function h(nn,Lt){if(!r)return null;for(;Lt!==null;)o(nn,Lt),Lt=Lt.sibling;return null}function v(nn){for(var Lt=new Map;nn!==null;)nn.key!==null?Lt.set(nn.key,nn):Lt.set(nn.index,nn),nn=nn.sibling;return Lt}function A(nn,Lt){return nn=Eo(nn,Lt),nn.index=0,nn.sibling=null,nn}function O(nn,Lt,un){return nn.index=un,r?(un=nn.alternate,un!==null?(un=un.index,un<Lt?(nn.flags|=67108866,Lt):un):(nn.flags|=67108866,Lt)):(nn.flags|=1048576,Lt)}function Ne(nn){return r&&nn.alternate===null&&(nn.flags|=67108866),nn}function et(nn,Lt,un,On){return Lt===null||Lt.tag!==6?(Lt=Xu(un,nn.mode,On),Lt.return=nn,Lt):(Lt=A(Lt,un),Lt.return=nn,Lt)}function _t(nn,Lt,un,On){var Qa=un.type;return Qa===N?Dn(nn,Lt,un.props.children,On,un.key):Lt!==null&&(Lt.elementType===Qa||typeof Qa=="object"&&Qa!==null&&Qa.$$typeof===z&&Mt(Qa)===Lt.type)?(Lt=A(Lt,un.props),Va(Lt,un),Lt.return=nn,Lt):(Lt=Md(un.type,un.key,un.props,null,nn.mode,On),Va(Lt,un),Lt.return=nn,Lt)}function hn(nn,Lt,un,On){return Lt===null||Lt.tag!==4||Lt.stateNode.containerInfo!==un.containerInfo||Lt.stateNode.implementation!==un.implementation?(Lt=$d(un,nn.mode,On),Lt.return=nn,Lt):(Lt=A(Lt,un.children||[]),Lt.return=nn,Lt)}function Dn(nn,Lt,un,On,Qa){return Lt===null||Lt.tag!==7?(Lt=bl(un,nn.mode,On,Qa),Lt.return=nn,Lt):(Lt=A(Lt,un),Lt.return=nn,Lt)}function qn(nn,Lt,un){if(typeof Lt=="string"&&Lt!==""||typeof Lt=="number"||typeof Lt=="bigint")return Lt=Xu(""+Lt,nn.mode,un),Lt.return=nn,Lt;if(typeof Lt=="object"&&Lt!==null){switch(Lt.$$typeof){case y:return un=Md(Lt.type,Lt.key,Lt.props,null,nn.mode,un),Va(un,Lt),un.return=nn,un;case b:return Lt=$d(Lt,nn.mode,un),Lt.return=nn,Lt;case z:return Lt=Mt(Lt),qn(nn,Lt,un)}if(fe(Lt)||D(Lt))return Lt=bl(Lt,nn.mode,un,null),Lt.return=nn,Lt;if(typeof Lt.then=="function")return qn(nn,fa(Lt),un);if(Lt.$$typeof===I)return qn(nn,dm(nn,Lt),un);ba(nn,Lt)}return null}function fn(nn,Lt,un,On){var Qa=Lt!==null?Lt.key:null;if(typeof un=="string"&&un!==""||typeof un=="number"||typeof un=="bigint")return Qa!==null?null:et(nn,Lt,""+un,On);if(typeof un=="object"&&un!==null){switch(un.$$typeof){case y:return un.key===Qa?_t(nn,Lt,un,On):null;case b:return un.key===Qa?hn(nn,Lt,un,On):null;case z:return un=Mt(un),fn(nn,Lt,un,On)}if(fe(un)||D(un))return Qa!==null?null:Dn(nn,Lt,un,On,null);if(typeof un.then=="function")return fn(nn,Lt,fa(un),On);if(un.$$typeof===I)return fn(nn,Lt,dm(nn,un),On);ba(nn,un)}return null}function bn(nn,Lt,un,On,Qa){if(typeof On=="string"&&On!==""||typeof On=="number"||typeof On=="bigint")return nn=nn.get(un)||null,et(Lt,nn,""+On,Qa);if(typeof On=="object"&&On!==null){switch(On.$$typeof){case y:return nn=nn.get(On.key===null?un:On.key)||null,_t(Lt,nn,On,Qa);case b:return nn=nn.get(On.key===null?un:On.key)||null,hn(Lt,nn,On,Qa);case z:return On=Mt(On),bn(nn,Lt,un,On,Qa)}if(fe(On)||D(On))return nn=nn.get(un)||null,Dn(Lt,nn,On,Qa,null);if(typeof On.then=="function")return bn(nn,Lt,un,fa(On),Qa);if(On.$$typeof===I)return bn(nn,Lt,un,dm(Lt,On),Qa);ba(Lt,On)}return null}function Oa(nn,Lt,un,On){for(var Qa=null,Gs=null,za=Lt,ms=Lt=0,Ts=null;za!==null&&ms<un.length;ms++){za.index>ms?(Ts=za,za=null):Ts=za.sibling;var Ys=fn(nn,za,un[ms],On);if(Ys===null){za===null&&(za=Ts);break}r&&za&&Ys.alternate===null&&o(nn,za),Lt=O(Ys,Lt,ms),Gs===null?Qa=Ys:Gs.sibling=Ys,Gs=Ys,za=Ts}if(ms===un.length)return h(nn,za),Cs&&yo(nn,ms),Qa;if(za===null){for(;ms<un.length;ms++)za=qn(nn,un[ms],On),za!==null&&(Lt=O(za,Lt,ms),Gs===null?Qa=za:Gs.sibling=za,Gs=za);return Cs&&yo(nn,ms),Qa}for(za=v(za);ms<un.length;ms++)Ts=bn(za,nn,ms,un[ms],On),Ts!==null&&(r&&Ts.alternate!==null&&za.delete(Ts.key===null?ms:Ts.key),Lt=O(Ts,Lt,ms),Gs===null?Qa=Ts:Gs.sibling=Ts,Gs=Ts);return r&&za.forEach(function(au){return o(nn,au)}),Cs&&yo(nn,ms),Qa}function es(nn,Lt,un,On){if(un==null)throw Error(s(151));for(var Qa=null,Gs=null,za=Lt,ms=Lt=0,Ts=null,Ys=un.next();za!==null&&!Ys.done;ms++,Ys=un.next()){za.index>ms?(Ts=za,za=null):Ts=za.sibling;var au=fn(nn,za,Ys.value,On);if(au===null){za===null&&(za=Ts);break}r&&za&&au.alternate===null&&o(nn,za),Lt=O(au,Lt,ms),Gs===null?Qa=au:Gs.sibling=au,Gs=au,za=Ts}if(Ys.done)return h(nn,za),Cs&&yo(nn,ms),Qa;if(za===null){for(;!Ys.done;ms++,Ys=un.next())Ys=qn(nn,Ys.value,On),Ys!==null&&(Lt=O(Ys,Lt,ms),Gs===null?Qa=Ys:Gs.sibling=Ys,Gs=Ys);return Cs&&yo(nn,ms),Qa}for(za=v(za);!Ys.done;ms++,Ys=un.next())Ys=bn(za,nn,ms,Ys.value,On),Ys!==null&&(r&&Ys.alternate!==null&&za.delete(Ys.key===null?ms:Ys.key),Lt=O(Ys,Lt,ms),Gs===null?Qa=Ys:Gs.sibling=Ys,Gs=Ys);return r&&za.forEach(function(eR){return o(nn,eR)}),Cs&&yo(nn,ms),Qa}function yr(nn,Lt,un,On){if(typeof un=="object"&&un!==null&&un.type===N&&un.key===null&&(un=un.props.children),typeof un=="object"&&un!==null){switch(un.$$typeof){case y:e:{for(var Qa=un.key;Lt!==null;){if(Lt.key===Qa){if(Qa=un.type,Qa===N){if(Lt.tag===7){h(nn,Lt.sibling),On=A(Lt,un.props.children),On.return=nn,nn=On;break e}}else if(Lt.elementType===Qa||typeof Qa=="object"&&Qa!==null&&Qa.$$typeof===z&&Mt(Qa)===Lt.type){h(nn,Lt.sibling),On=A(Lt,un.props),Va(On,un),On.return=nn,nn=On;break e}h(nn,Lt);break}else o(nn,Lt);Lt=Lt.sibling}un.type===N?(On=bl(un.props.children,nn.mode,On,un.key),On.return=nn,nn=On):(On=Md(un.type,un.key,un.props,null,
vendor: 6,105 bytes, line 48
48nn.mode,On),Va(On,un),On.return=nn,nn=On)}return Ne(nn);case b:e:{for(Qa=un.key;Lt!==null;){if(Lt.key===Qa)if(Lt.tag===4&&Lt.stateNode.containerInfo===un.containerInfo&&Lt.stateNode.implementation===un.implementation){h(nn,Lt.sibling),On=A(Lt,un.children||[]),On.return=nn,nn=On;break e}else{h(nn,Lt);break}else o(nn,Lt);Lt=Lt.sibling}On=$d(un,nn.mode,On),On.return=nn,nn=On}return Ne(nn);case z:return un=Mt(un),yr(nn,Lt,un,On)}if(fe(un))return Oa(nn,Lt,un,On);if(D(un)){if(Qa=D(un),typeof Qa!="function")throw Error(s(150));return un=Qa.call(un),es(nn,Lt,un,On)}if(typeof un.then=="function")return yr(nn,Lt,fa(un),On);if(un.$$typeof===I)return yr(nn,Lt,dm(nn,un),On);ba(nn,un)}return typeof un=="string"&&un!==""||typeof un=="number"||typeof un=="bigint"?(un=""+un,Lt!==null&&Lt.tag===6?(h(nn,Lt.sibling),On=A(Lt,un),On.return=nn,nn=On):(h(nn,Lt),On=Xu(un,nn.mode,On),On.return=nn,nn=On),Ne(nn)):h(nn,Lt)}return function(nn,Lt,un,On){try{Aa=0;var Qa=yr(nn,Lt,un,On);return Tn=null,Qa}catch(za){if(za===Tt||za===cn)throw za;var Gs=Bi(29,za,null,nn.mode);return Gs.lanes=On,Gs.return=nn,Gs}finally{}}}var As=Us(!0),Ps=Us(!1),cs=!1;function Ks(r){r.updateQueue={baseState:r.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ws(r,o){r=r.updateQueue,o.updateQueue===r&&(o.updateQueue={baseState:r.baseState,firstBaseUpdate:r.firstBaseUpdate,lastBaseUpdate:r.lastBaseUpdate,shared:r.shared,callbacks:null})}function Za(r){return{lane:r,tag:0,payload:null,callback:null,next:null}}function ir(r,o,h){var v=r.updateQueue;if(v===null)return null;if(v=v.shared,(Xs&2)!==0){var A=v.pending;return A===null?o.next=o:(o.next=A.next,A.next=o),v.pending=o,o=Li(r),Ju(r,null,h),o}return Do(r,v,o,h),Li(r)}function hi(r,o,h){if(o=o.updateQueue,o!==null&&(o=o.shared,(h&4194048)!==0)){var v=o.lanes;v&=r.pendingLanes,h|=v,o.lanes=h,Qt(r,h)}}function Br(r,o){var h=r.updateQueue,v=r.alternate;if(v!==null&&(v=v.updateQueue,h===v)){var A=null,O=null;if(h=h.firstBaseUpdate,h!==null){do{var Ne={lane:h.lane,tag:h.tag,payload:h.payload,callback:null,next:null};O===null?A=O=Ne:O=O.next=Ne,h=h.next}while(h!==null);O===null?A=O=o:O=O.next=o}else A=O=o;h={baseState:v.baseState,firstBaseUpdate:A,lastBaseUpdate:O,shared:v.shared,callbacks:v.callbacks},r.updateQueue=h;return}r=h.lastBaseUpdate,r===null?h.firstBaseUpdate=o:r.next=o,h.lastBaseUpdate=o}var Fi=!1;function Ls(){if(Fi){var r=k;if(r!==null)throw r}}function Ii(r,o,h,v){Fi=!1;var A=r.updateQueue;cs=!1;var O=A.firstBaseUpdate,Ne=A.lastBaseUpdate,et=A.shared.pending;if(et!==null){A.shared.pending=null;var _t=et,hn=_t.next;_t.next=null,Ne===null?O=hn:Ne.next=hn,Ne=_t;var Dn=r.alternate;Dn!==null&&(Dn=Dn.updateQueue,et=Dn.lastBaseUpdate,et!==Ne&&(et===null?Dn.firstBaseUpdate=hn:et.next=hn,Dn.lastBaseUpdate=_t))}if(O!==null){var qn=A.baseState;Ne=0,Dn=hn=_t=null,et=O;do{var fn=et.lane&-536870913,bn=fn!==et.lane;if(bn?(Rs&fn)===fn:(v&fn)===fn){fn!==0&&fn===j&&(Fi=!0),Dn!==null&&(Dn=Dn.next={lane:0,tag:et.tag,payload:et.payload,callback:null,next:null});e:{var Oa=r,es=et;fn=o;var yr=h;switch(es.tag){case 1:if(Oa=es.payload,typeof Oa=="function"){qn=Oa.call(yr,qn,fn);break e}qn=Oa;break e;case 3:Oa.flags=Oa.flags&-65537|128;case 0:if(Oa=es.payload,fn=typeof Oa=="function"?Oa.call(yr,qn,fn):Oa,fn==null)break e;qn=g({},qn,fn);break e;case 2:cs=!0}}fn=et.callback,fn!==null&&(r.flags|=64,bn&&(r.flags|=8192),bn=A.callbacks,bn===null?A.callbacks=[fn]:bn.push(fn))}else bn={lane:fn,tag:et.tag,payload:et.payload,callback:et.callback,next:null},Dn===null?(hn=Dn=bn,_t=qn):Dn=Dn.next=bn,Ne|=fn;if(et=et.next,et===null){if(et=A.shared.pending,et===null)break;bn=et,et=bn.next,bn.next=null,A.lastBaseUpdate=bn,A.shared.pending=null}}while(!0);Dn===null&&(_t=qn),A.baseState=_t,A.firstBaseUpdate=hn,A.lastBaseUpdate=Dn,O===null&&(A.shared.lanes=0),Gd|=Ne,r.lanes=Ne,r.memoizedState=qn}}function so(r,o){if(typeof r!="function")throw Error(s(191,r));r.call(o)}function ri(r,o){var h=r.callbacks;if(h!==null)for(r.callbacks=null,r=0;r<h.length;r++)so(h[r],o)}var Fr=V(null),mi=V(0);function vo(r,o){r=ld,F(mi,r),F(Fr,o),ld=r|o.baseLanes}function Lo(){F(mi,ld),F(Fr,Fr.current)}function Zr(){ld=mi.current,$(Fr),$(mi)}var Yr=V(null),pi=null;function bo(r){var o=r.alternate;F(Ur,Ur.current&1),F(Yr,r),pi===null&&(o===null||Fr.current!==null||o.memoizedState!==null)&&(pi=r)}function wc(r){F(Ur,Ur.current),F(Yr,r),pi===null&&(pi=r)}function Tr(r){r.tag===22?(F(Ur,Ur.current),F(Yr,r),pi===null&&(pi=r)):Nc()}function Nc(){F(Ur,Ur.current),F(Yr,Yr.current)}function ro(r){$(Yr),pi===r&&(pi=null),$(Ur)}var Ur=V(0);function Xl(r){for(var o=r;o!==null;){if(o.tag===13){var h=o.memoizedState;if(h!==null&&(h=h.dehydrated,h===null||f0(h)||g0(h)))return o}else if(o.tag===19&&(o.memoizedProps.revealOrder==="forwards"||o.memoizedProps.revealOrder==="backwards"||o.memoizedProps.revealOrder==="unstable_legacy-backwards"||o.memoizedProps.revealOrder==="together")){if((o.flags&128)!==0)return o}else if(o.child!==null){o.child.return=o,o=o.child;continue}if(o===r)break;for(;o.sibling===null;){if(o.return===null||o.return===r)return null;o=o.return}o.sibling.return=o.return,o=o.sibling}return null}var xo=0,os=null,ps=null,Sr=null,Gc=!1,Zl=!1,Sc=!1,nh=0,Al=0,Il=null,hm=0;function fr(){throw Error(s(321))}function $p(r,o){if(o===null)return!1;for(var h=0;h<o.length&&h<r.length;h++)if(!S(r[h],o[h]))return!1;return!0}function Op(r,o,h,v,A,O){return xo=O,os=o,o.memoizedState=null,o.updateQueue=null,o.lanes=0,q.H=r===null||r.memoizedState===null?R2:Ax,Sc=!1,O=h(v,A),Sc=!1,Zl&&(O=Yc(o,h,v,A)),mm(r),O}function mm(r){q.H=Hp;var o=ps!==null&&ps.next!==null;if(xo=0,Sr=ps=os=null,Gc=!1,Al=0,Il=null,o)throw Error(s(300));r===null||gi||(r=r.dependencies,r!==null&&lm(r)&&(gi=!0))}function Yc(r,o,h,v){os=r;var A=0;do{if(Zl&&(Il=null),Al=0,Zl=!1,25<=A)throw Error(s(301));if(A+=1,Sr=ps=null,r.updateQueue!=null){var O=r.updateQueue;O.lastEffect=null,O.events=null,O.stores=null,O.memoCache!=null&&(O.memoCache.index=0)}q.H=T2,O=o(h,v)}while(Zl);return O}function bx(){var r=q.H,o=r.useState()[0];
vendor: 16,505 bytes, line 48
48return o=typeof o.then=="function"?_l(o):o,r=r.useState()[0],(ps!==null?ps.memoizedState:null)!==r&&(os.flags|=1024),o}function Lp(){var r=nh!==0;return nh=0,r}function Bp(r,o,h){o.updateQueue=r.updateQueue,o.flags&=-2053,r.lanes&=~h}function pm(r){if(Gc){for(r=r.memoizedState;r!==null;){var o=r.queue;o!==null&&(o.pending=null),r=r.next}Gc=!1}xo=0,Sr=ps=os=null,Zl=!1,Al=nh=0,Il=null}function fi(){var r={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Sr===null?os.memoizedState=Sr=r:Sr=Sr.next=r,Sr}function zr(){if(ps===null){var r=os.alternate;r=r!==null?r.memoizedState:null}else r=ps.next;var o=Sr===null?os.memoizedState:Sr.next;if(o!==null)Sr=o,ps=r;else{if(r===null)throw os.alternate===null?Error(s(467)):Error(s(310));ps=r,r={memoizedState:ps.memoizedState,baseState:ps.baseState,baseQueue:ps.baseQueue,queue:ps.queue,next:null},Sr===null?os.memoizedState=Sr=r:Sr=Sr.next=r}return Sr}function ah(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function _l(r){var o=Al;return Al+=1,Il===null&&(Il=[]),r=Nn(Il,r,o),o=os,(Sr===null?o.memoizedState:Sr.next)===null&&(o=o.alternate,q.H=o===null||o.memoizedState===null?R2:Ax),r}function Ud(r){if(r!==null&&typeof r=="object"){if(typeof r.then=="function")return _l(r);if(r.$$typeof===I)return Ai(r)}throw Error(s(438,String(r)))}function ed(r){var o=null,h=os.updateQueue;if(h!==null&&(o=h.memoCache),o==null){var v=os.alternate;v!==null&&(v=v.updateQueue,v!==null&&(v=v.memoCache,v!=null&&(o={data:v.data.map(function(A){return A.slice()}),index:0})))}if(o==null&&(o={data:[],index:0}),h===null&&(h=ah(),os.updateQueue=h),h.memoCache=o,h=o.data[o.index],h===void 0)for(h=o.data[o.index]=Array(r),v=0;v<r;v++)h[v]=K;return o.index++,h}function Cc(r,o){return typeof o=="function"?o(r):o}function fm(r){var o=zr();return zd(o,ps,r)}function zd(r,o,h){var v=r.queue;if(v===null)throw Error(s(311));v.lastRenderedReducer=h;var A=r.baseQueue,O=v.pending;if(O!==null){if(A!==null){var Ne=A.next;A.next=O.next,O.next=Ne}o.baseQueue=A=O,v.pending=null}if(O=r.baseState,A===null)r.memoizedState=O;else{o=A.next;var et=Ne=null,_t=null,hn=o,Dn=!1;do{var qn=hn.lane&-536870913;if(qn!==hn.lane?(Rs&qn)===qn:(xo&qn)===qn){var fn=hn.revertLane;if(fn===0)_t!==null&&(_t=_t.next={lane:0,revertLane:0,gesture:null,action:hn.action,hasEagerState:hn.hasEagerState,eagerState:hn.eagerState,next:null}),qn===j&&(Dn=!0);else if((xo&fn)===fn){hn=hn.next,fn===j&&(Dn=!0);continue}else qn={lane:0,revertLane:hn.revertLane,gesture:null,action:hn.action,hasEagerState:hn.hasEagerState,eagerState:hn.eagerState,next:null},_t===null?(et=_t=qn,Ne=O):_t=_t.next=qn,os.lanes|=fn,Gd|=fn;qn=hn.action,Sc&&h(O,qn),O=hn.hasEagerState?hn.eagerState:h(O,qn)}else fn={lane:qn,revertLane:hn.revertLane,gesture:hn.gesture,action:hn.action,hasEagerState:hn.hasEagerState,eagerState:hn.eagerState,next:null},_t===null?(et=_t=fn,Ne=O):_t=_t.next=fn,os.lanes|=qn,Gd|=qn;hn=hn.next}while(hn!==null&&hn!==o);if(_t===null?Ne=O:_t.next=et,!S(O,r.memoizedState)&&(gi=!0,Dn&&(h=k,h!==null)))throw h;r.memoizedState=O,r.baseState=Ne,r.baseQueue=_t,v.lastRenderedState=O}return A===null&&(v.lanes=0),[r.memoizedState,v.dispatch]}function gm(r){var o=zr(),h=o.queue;if(h===null)throw Error(s(311));h.lastRenderedReducer=r;var v=h.dispatch,A=h.pending,O=o.memoizedState;if(A!==null){h.pending=null;var Ne=A=A.next;do O=r(O,Ne.action),Ne=Ne.next;while(Ne!==A);S(O,o.memoizedState)||(gi=!0),o.memoizedState=O,o.baseQueue===null&&(o.baseState=O),h.lastRenderedState=O}return[O,v]}function ym(r,o,h){var v=os,A=zr(),O=Cs;if(O){if(h===void 0)throw Error(s(407));h=h()}else h=o();var Ne=!S((ps||A).memoizedState,h);if(Ne&&(A.memoizedState=h,gi=!0),A=A.queue,xx(Up.bind(null,v,A,r),[r]),A.getSnapshot!==o||Ne||Sr!==null&&Sr.memoizedState.tag&1){if(v.flags|=2048,nd(9,{destroy:void 0},Fp.bind(null,v,A,h,o),null),Cr===null)throw Error(s(349));O||(xo&127)!==0||Qc(v,o,h)}return h}function Qc(r,o,h){r.flags|=16384,r={getSnapshot:o,value:h},o=os.updateQueue,o===null?(o=ah(),os.updateQueue=o,o.stores=[r]):(h=o.stores,h===null?o.stores=[r]:h.push(r))}function Fp(r,o,h,v){o.value=h,o.getSnapshot=v,Yg(o)&&zp(r)}function Up(r,o,h){return h(function(){Yg(o)&&zp(r)})}function Yg(r){var o=r.getSnapshot;r=r.value;try{var h=o();return!S(r,h)}catch{return!0}}function zp(r){var o=Hc(r,2);o!==null&&qo(o,r,2)}function kl(r){var o=fi();if(typeof r=="function"){var h=r;if(r=h(),Sc){Ge(!0);try{h()}finally{Ge(!1)}}}return o.memoizedState=o.baseState=r,o.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Cc,lastRenderedState:r},o}function Qg(r,o,h,v){return r.baseState=h,zd(r,ps,typeof v=="function"?v:Cc)}function Jg(r,o,h,v,A){if(ey(r))throw Error(s(485));if(r=o.action,r!==null){var O={payload:A,action:r,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(Ne){O.listeners.push(Ne)}};q.T!==null?h(!0):O.isTransition=!1,v(O),h=o.pending,h===null?(O.next=o.pending=O,Kg(o,O)):(O.next=h.next,o.pending=h.next=O)}}function Kg(r,o){var h=o.action,v=o.payload,A=r.state;if(o.isTransition){var O=q.T,Ne={};q.T=Ne;try{var et=h(A,v),_t=q.S;_t!==null&&_t(Ne,et),qp(r,o,et)}catch(hn){td(r,o,hn)}finally{O!==null&&Ne.types!==null&&(O.types=Ne.types),q.T=O}}else try{O=h(A,v),qp(r,o,O)}catch(hn){td(r,o,hn)}}function qp(r,o,h){h!==null&&typeof h=="object"&&typeof h.then=="function"?h.then(function(v){Xg(r,o,v)},function(v){return td(r,o,v)}):Xg(r,o,h)}function Xg(r,o,h){o.status="fulfilled",o.value=h,vm(o),r.state=h,o=r.pending,o!==null&&(h=o.next,h===o?r.pending=null:(h=h.next,o.next=h,Kg(r,h)))}function td(r,o,h){var v=r.pending;if(r.pending=null,v!==null){v=v.next;do o.status="rejected",o.reason=h,vm(o),o=o.next;while(o!==v)}r.action=null}function vm(r){r=r.listeners;for(var o=0;o<r.length;o++)(0,r[o])()}function sh(r,o){return o}function Ac(r,o){if(Cs){var h=Cr.formState;if(h!==null){e:{var v=os;if(Cs){if(Nr){t:{for(var A=Nr,O=Lr;A.nodeType!==8;){if(!O){A=null;break t}if(A=Ic(A.nextSibling),A===null){A=null;break t}}O=A.data,A=O==="F!"||O==="F"?A:null}if(A){Nr=Ic(A.nextSibling),v=A.data==="F!";break e}}jl(v)}v=!1}v&&(o=h[0])}}return h=fi(),h.memoizedState=h.baseState=o,v={pending:null,lanes:0,dispatch:null,lastRenderedReducer:sh,lastRenderedState:o},h.queue=v,h=D2.bind(null,os,v),v.dispatch=h,v=kl(!1),O=Cx.bind(null,os,!1,v.queue),v=fi(),A={state:o,dispatch:null,action:r,pending:null},v.queue=A,h=Jg.bind(null,os,A,O,h),A.dispatch=h,v.memoizedState=r,[o,h,!1]}function Jc(r){var o=zr();return Kc(o,ps,r)}function Kc(r,o,h){if(o=zd(r,o,sh)[0],r=fm(Cc)[0],typeof o=="object"&&o!==null&&typeof o.then=="function")try{var v=_l(o)}catch(Ne){throw Ne===Tt?cn:Ne}else v=o;o=zr();var A=o.queue,O=A.dispatch;return h!==o.memoizedState&&(os.flags|=2048,nd(9,{destroy:void 0},bm.bind(null,A,h),null)),[v,O,r]}function bm(r,o){r.action=o}function xm(r){var o=zr(),h=ps;if(h!==null)return Kc(o,h,r);zr(),o=o.memoizedState,h=zr();var v=h.queue.dispatch;return h.memoizedState=r,[o,v,!1]}function nd(r,o,h,v){return r={tag:r,create:h,deps:v,inst:o,next:null},o=os.updateQueue,o===null&&(o=ah(),os.updateQueue=o),h=o.lastEffect,h===null?o.lastEffect=r.next=r:(v=h.next,h.next=r,r.next=v,o.lastEffect=r),r}function Zg(){return zr().memoizedState}function qd(r,o,h,v){var A=fi();os.flags|=r,A.memoizedState=nd(1|o,{destroy:void 0},h,v===void 0?null:v)}function Vd(r,o,h,v){var A=zr();v=v===void 0?null:v;var O=A.memoizedState.inst;ps!==null&&v!==null&&$p(v,ps.memoizedState.deps)?A.memoizedState=nd(o,O,h,v):(os.flags|=r,A.memoizedState=nd(1|o,O,h,v))}function g2(r,o){qd(8390656,8,r,o)}function xx(r,o){Vd(2048,8,r,o)}function YE(r){os.flags|=4;var o=os.updateQueue;if(o===null)o=ah(),os.updateQueue=o,o.events=[r];else{var h=o.events;h===null?o.events=[r]:h.push(r)}}function y2(r){var o=zr().memoizedState;return YE({ref:o,nextImpl:r}),function(){if((Xs&2)!==0)throw Error(s(440));return o.impl.apply(void 0,arguments)}}function v2(r,o){return Vd(4,2,r,o)}function b2(r,o){return Vd(4,4,r,o)}function x2(r,o){if(typeof o=="function"){r=r();var h=o(r);return function(){typeof h=="function"?h():o(null)}}if(o!=null)return r=r(),o.current=r,function(){o.current=null}}function j2(r,o,h){h=h!=null?h.concat([r]):null,Vd(4,4,x2.bind(null,o,r),h)}function jx(){}function w2(r,o){var h=zr();o=o===void 0?null:o;var v=h.memoizedState;return o!==null&&$p(o,v[1])?v[0]:(h.memoizedState=[r,o],r)}function N2(r,o){var h=zr();o=o===void 0?null:o;var v=h.memoizedState;if(o!==null&&$p(o,v[1]))return v[0];if(v=r(),Sc){Ge(!0);try{r()}finally{Ge(!1)}}return h.memoizedState=[v,o],v}function wx(r,o,h){return h===void 0||(xo&1073741824)!==0&&(Rs&261930)===0?r.memoizedState=o:(r.memoizedState=h,r=SN(),os.lanes|=r,Gd|=r,h)}function S2(r,o,h,v){return S(h,o)?h:Fr.current!==null?(r=wx(r,h,v),S(r,o)||(gi=!0),r):(xo&42)===0||(xo&1073741824)!==0&&(Rs&261930)===0?(gi=!0,r.memoizedState=h):(r=SN(),os.lanes|=r,Gd|=r,o)}function C2(r,o,h,v,A){var O=ne.p;ne.p=O!==0&&8>O?O:8;var Ne=q.T,et={};q.T=et,Cx(r,!1,o,h);try{var _t=A(),hn=q.S;if(hn!==null&&hn(et,_t),_t!==null&&typeof _t=="object"&&typeof _t.then=="function"){var Dn=ze(_t,v);Vp(r,o,Dn,rc(r))}else Vp(r,o,v,rc(r))}catch(qn){Vp(r,o,{then:function(){},status:"rejected",reason:qn},rc())}finally{ne.p=O,Ne!==null&&et.types!==null&&(Ne.types=et.types),q.T=Ne}}function QE(){}function Nx(r,o,h,v){if(r.tag!==5)throw Error(s(476));var A=A2(r).queue;C2(r,A,o,ae,h===null?QE:function(){return I2(r),h(v)})}function A2(r){var o=r.memoizedState;if(o!==null)return o;o={memoizedState:ae,baseState:ae,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Cc,lastRenderedState:ae},next:null};var h={};return o.next={memoizedState:h,baseState:h,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Cc,lastRenderedState:h},next:null},r.memoizedState=o,r=r.alternate,r!==null&&(r.memoizedState=o),o}function I2(r){var o=A2(r);o.next===null&&(o=r.alternate.memoizedState),Vp(r,o.next.queue,{},rc())}function Sx(){return Ai(cf)}function _2(){return zr().memoizedState}function k2(){return zr().memoizedState}function JE(r){for(var o=r.return;o!==null;){switch(o.tag){case 24:case 3:var h=rc();r=Za(h);var v=ir(o,r,h);v!==null&&(qo(v,o,h),hi(v,o,h)),o={cache:Fd()},r.payload=o;return}o=o.return}}function KE(r,o,h){var v=rc();h={lane:v,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null},ey(r)?E2(o,h):(h=go(r,o,h,v),h!==null&&(qo(h,r,v),P2(h,o,v)))}function D2(r,o,h){var v=rc();Vp(r,o,h,v)}function Vp(r,o,h,v){var A={lane:v,revertLane:0,gesture:null,action:h,hasEagerState:!1,eagerState:null,next:null};if(ey(r))E2(o,A);else{var O=r.alternate;if(r.lanes===0&&(O===null||O.lanes===0)&&(O=o.lastRenderedReducer,O!==null))try{var Ne=o.lastRenderedState,et=O(Ne,h);if(A.hasEagerState=!0,A.eagerState=et,S(et,Ne))return Do(r,o,A,0),Cr===null&&xc(),!1}catch{}finally{}if(h=go(r,o,A,v),h!==null)return qo(h,r,v),P2(h,o,v),!0}return!1}function Cx(r,o,h,v){if(v={lane:2,revertLane:a0(),gesture:null,action:v,hasEagerState:!1,eagerState:null,next:null},ey(r)){if(o)throw Error(s(479))}else o=go(r,h,v,2),o!==null&&qo(o,r,2)}function ey(r){var o=r.alternate;return r===os||o!==null&&o===os}function E2(r,o){Zl=Gc=!0;var h=r.pending;h===null?o.next=o:(o.next=h.next,h.next=o),r.pending=o}function P2(r,o,h){if((h&4194048)!==0){var v=o.lanes;v&=r.pendingLanes,h|=v,o.lanes=h,Qt(r,h)}}var Hp={readContext:Ai,use:Ud,useCallback:fr,useContext:fr,useEffect:fr,useImperativeHandle:fr,useLayoutEffect:fr,useInsertionEffect:fr,useMemo:fr,useReducer:fr,useRef:fr,useState:fr,useDebugValue:fr,useDeferredValue:fr,useTransition:fr,useSyncExternalStore:fr,useId:fr,useHostTransitionStatus:fr,useFormState:fr,useActionState:fr,useOptimistic:fr,useMemoCache:fr,useCacheRefresh:fr};Hp.useEffectEvent=fr;var R2={readContext:Ai,use:Ud,useCallback:function(r,o){return fi().memoizedState=[r,o===void 0?null:o],r},useContext:Ai,useEffect:g2,useImperativeHandle:function(r,o,h){h=h!=null?h.concat([r]):null,qd(4194308,4,x2.bind(null,o,r),h)},useLayoutEffect:function(r,o){return qd(4194308,4,r,o)},useInsertionEffect:function(r,o){qd(4,2,r,o)},useMemo:function(r,o){var h=fi();o=o===void 0?null:o;var v=r();if(Sc){Ge(!0);try{r()}finally{Ge(!1)}}return h.memoizedState=[v,o],v},useReducer:function(r,o,h){var v=fi();if(h!==void 0){var A=h(o);if(Sc){Ge(!0);try{h(o)}finally{Ge(!1)}}}else A=o;return v.memoizedState=v.baseState=A,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:A},v.queue=r,r=r.dispatch=KE.bind(null,os,r),[v.memoizedState,r]},useRef:function(r){var o=fi();return r={current:r},o.memoizedState=r},useState:function(r){r=kl(r);var o=r.queue,h=D2.bind(null,os,o);return o.dispatch=h,[r.memoizedState,h]},useDebugValue:jx,useDeferredValue:function(r,o){var h=fi();return wx(h,r,o)},useTransition:function(){var r=kl(!1);return r=C2.bind(null,os,r.queue,!0,!1),fi().memoizedState=r,[!1,r]},useSyncExternalStore:function(r,o,h){var v=os,A=fi();if(Cs){if(h===void 0)throw Error(s(407));h=h()}else{if(h=o(),Cr===null)throw Error(s(349));(Rs&127)!==0||Qc(v,o,h)}A.memoizedState=h;var O={value:h,getSnapshot:o};return A.queue=O,g2(Up.bind(null,v,O,r),[r]),v.flags|=2048,nd(9,{destroy:void 0},Fp.bind(null,v,O,h,o),null),h},useId:function(){var r=fi(),o=Cr.identifierPrefix;if(Cs){var h=$o,v=Mo;h=(v&~(1<<32-pt(v)-1)).toString(32)+h,o="_"+o+"R_"+h,h=nh++,0<h&&(o+="H"+h.toString(32)),o+="_"}else h=hm++,o="_"+o+"r_"+h.toString(32)+"_";return r.memoizedState=o},useHostTransitionStatus:Sx,useFormState:Ac,useActionState:Ac,useOptimistic:function(r){var o=fi();o.memoizedState=o.baseState=r;var h={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return o.queue=h,o=Cx.bind(null,os,!0,h),h.dispatch=o,[r,o]},useMemoCache:ed,useCacheRefresh:function(){return fi().memoizedState=JE.bind(null,os)},useEffectEvent:function(r){var o=fi(),h={impl:r};return o.memoizedState=h,function(){if((Xs&2)!==0)throw Error(s(440));return h.impl.apply(void 0,arguments)}}},Ax={readContext:Ai,use:Ud,useCallback:w2,useContext:Ai,useEffect:xx,useImperativeHandle:j2,useInsertionEffect:v2,useLayoutEffect:b2,useMemo:N2,useReducer:fm,useRef:Zg,useState:function(){return fm(Cc)},useDebugValue:jx,useDeferredValue:function(r,o){var h=zr();return S2(h,ps.memoizedState,r,o)},useTransition:function(){var r=fm(Cc)[0],o=zr().memoizedState;return[typeof r=="boolean"?r:_l(r),o]},useSyncExternalStore:ym,useId:_2,useHostTransitionStatus:Sx,useFormState:Jc,useActionState:Jc,useOptimistic:function(r,o){var h=zr();return Qg(h,ps,r,o)},useMemoCache:ed,useCacheRefresh:k2};Ax.useEffectEvent=y2;var T2={readContext:Ai,use:Ud,useCallback:w2,useContext:Ai,useEffect:xx,useImperativeHandle:j2,useInsertionEffect:v2,useLayoutEffect:b2,useMemo:N2,useReducer:gm,useRef:Zg,useState:function(){return gm(Cc)},useDebugValue:jx,useDeferredValue:function(r,o){var h=zr();return ps===null?wx(h,r,o):S2(h,ps.memoizedState,r,o)},useTransition:function(){var r=gm(Cc)[0],o=zr().memoizedState;return[typeof r=="boolean"?r:_l(r),o]},useSyncExternalStore:ym,useId:_2,useHostTransitionStatus:Sx,useFormState:xm,useActionState:xm,useOptimistic:function(r,o){var h=zr();return ps!==null?Qg(h,ps,r,o):(h.baseState=r,[r,h.queue.dispatch])},useMemoCache:ed,useCacheRefresh:k2};T2.useEffectEvent=y2;function Ix(r,o,h,v){o=r.memoizedState,h=h(v,o),h=h==null?o:g({},o,h),r.memoizedState=h,r.lanes===0&&(r.updateQueue.baseState=h)}var _x={enqueueSetState:function(r,o,h){r=r._reactInternals;var v=rc(),A=Za(v);A.payload=o,h!=null&&(A.callback=h),o=ir(r,A,v),o!==null&&(qo(o,r,v),hi(o,r,v))},enqueueReplaceState:function(r,o,h){r=r._reactInternals;var v=rc(),A=Za(v);A.tag=1,A.payload=o,h!=null&&(A.callback=h),o=ir(r,A,v),o!==null&&(qo(o,r,v),hi(o,r,v))},enqueueForceUpdate:function(r,o){r=r._reactInternals;var h=rc(),v=Za(h);v.tag=2,o!=null&&(v.callback=o),o=ir(r,v,h),o!==null&&(qo(o,r,h),hi(o,r,h))}};function M2(r,o,h,v,A,O,Ne){return r=r.stateNode,typeof r.shouldComponentUpdate=="function"?r.shouldComponentUpdate(v,O,Ne):o.prototype&&o.prototype.isPureReactComponent?!ye(h,v)||!ye(A,O):!0}function $2(r,o,h,v){r=o.state,typeof o.componentWillReceiveProps=="function"&&o.componentWillReceiveProps(h,v),typeof o.UNSAFE_componentWillReceiveProps=="function"&&o.UNSAFE_componentWillReceiveProps(h,v),o.state!==r&&_x.enqueueReplaceState(o,o.state,null)}function rh(r,o){var h=o;if("ref"in o){h={};for(var v in o)v!=="ref"&&(h[v]=o[v])}if(r=r.defaultProps){h===o&&(h=g({},h));for(var A in r)h[A]===void 0&&(h[A]=r[A])}return h}function O2(r){Ss(r)}
vendor: 5,483 bytes, line 48
48function L2(r){console.error(r)}function B2(r){Ss(r)}function ty(r,o){try{var h=r.onUncaughtError;h(o.value,{componentStack:o.stack})}catch(v){setTimeout(function(){throw v})}}function F2(r,o,h){try{var v=r.onCaughtError;v(h.value,{componentStack:h.stack,errorBoundary:o.tag===1?o.stateNode:null})}catch(A){setTimeout(function(){throw A})}}function kx(r,o,h){return h=Za(h),h.tag=3,h.payload={element:null},h.callback=function(){ty(r,o)},h}function U2(r){return r=Za(r),r.tag=3,r}function z2(r,o,h,v){var A=h.type.getDerivedStateFromError;if(typeof A=="function"){var O=v.value;r.payload=function(){return A(O)},r.callback=function(){F2(o,h,v)}}var Ne=h.stateNode;Ne!==null&&typeof Ne.componentDidCatch=="function"&&(r.callback=function(){F2(o,h,v),typeof A!="function"&&(Yd===null?Yd=new Set([this]):Yd.add(this));var et=v.stack;this.componentDidCatch(v.value,{componentStack:et!==null?et:""})})}function XE(r,o,h,v,A){if(h.flags|=32768,v!==null&&typeof v=="object"&&typeof v.then=="function"){if(o=h.alternate,o!==null&&Sl(o,h,A,!0),h=Yr.current,h!==null){switch(h.tag){case 31:case 13:return pi===null?my():h.alternate===null&&ei===0&&(ei=3),h.flags&=-257,h.flags|=65536,h.lanes=A,v===Kt?h.flags|=16384:(o=h.updateQueue,o===null?h.updateQueue=new Set([v]):o.add(v),e0(r,v,A)),!1;case 22:return h.flags|=65536,v===Kt?h.flags|=16384:(o=h.updateQueue,o===null?(o={transitions:null,markerInstances:null,retryQueue:new Set([v])},h.updateQueue=o):(h=o.retryQueue,h===null?o.retryQueue=new Set([v]):h.add(v)),e0(r,v,A)),!1}throw Error(s(435,h.tag))}return e0(r,v,A),my(),!1}if(Cs)return o=Yr.current,o!==null?((o.flags&65536)===0&&(o.flags|=256),o.flags|=65536,o.lanes=A,v!==nc&&(r=Error(s(422),{cause:v}),Ld(Po(r,h)))):(v!==nc&&(o=Error(s(423),{cause:v}),Ld(Po(o,h))),r=r.current.alternate,r.flags|=65536,A&=-A,r.lanes|=A,v=Po(v,h),A=kx(r.stateNode,v,A),Br(r,A),ei!==4&&(ei=2)),!1;var O=Error(s(520),{cause:v});if(O=Po(O,h),Zp===null?Zp=[O]:Zp.push(O),ei!==4&&(ei=2),o===null)return!0;v=Po(v,h),h=o;do{switch(h.tag){case 3:return h.flags|=65536,r=A&-A,h.lanes|=r,r=kx(h.stateNode,v,r),Br(h,r),!1;case 1:if(o=h.type,O=h.stateNode,(h.flags&128)===0&&(typeof o.getDerivedStateFromError=="function"||O!==null&&typeof O.componentDidCatch=="function"&&(Yd===null||!Yd.has(O))))return h.flags|=65536,A&=-A,h.lanes|=A,A=U2(A),z2(A,r,h,v),Br(h,A),!1}h=h.return}while(h!==null);return!1}var Dx=Error(s(461)),gi=!1;function Qi(r,o,h,v){o.child=r===null?Ps(o,null,h,v):As(o,r.child,h,v)}function q2(r,o,h,v,A){h=h.render;var O=o.ref;if("ref"in v){var Ne={};for(var et in v)et!=="ref"&&(Ne[et]=v[et])}else Ne=v;return Cl(o),v=Op(r,o,h,Ne,O,A),et=Lp(),r!==null&&!gi?(Bp(r,o,A),ad(r,o,A)):(Cs&&et&&Rp(o),o.flags|=1,Qi(r,o,v,A),o.child)}function V2(r,o,h,v,A){if(r===null){var O=h.type;return typeof O=="function"&&!am(O)&&O.defaultProps===void 0&&h.compare===null?(o.tag=15,o.type=O,H2(r,o,O,v,A)):(r=Md(h.type,null,v,o,o.mode,A),r.ref=o.ref,r.return=o,o.child=r)}if(O=r.child,!Lx(r,A)){var Ne=O.memoizedProps;if(h=h.compare,h=h!==null?h:ye,h(Ne,v)&&r.ref===o.ref)return ad(r,o,A)}return o.flags|=1,r=Eo(O,v),r.ref=o.ref,r.return=o,o.child=r}function H2(r,o,h,v,A){if(r!==null){var O=r.memoizedProps;if(ye(O,v)&&r.ref===o.ref)if(gi=!1,o.pendingProps=v=O,Lx(r,A))(r.flags&131072)!==0&&(gi=!0);else return o.lanes=r.lanes,ad(r,o,A)}return Ex(r,o,h,v,A)}function W2(r,o,h,v){var A=v.children,O=r!==null?r.memoizedState:null;if(r===null&&o.stateNode===null&&(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),v.mode==="hidden"){if((o.flags&128)!==0){if(O=O!==null?O.baseLanes|h:h,r!==null){for(v=o.child=r.child,A=0;v!==null;)A=A|v.lanes|v.childLanes,v=v.sibling;v=A&~O}else v=0,o.child=null;return G2(r,o,O,h,v)}if((h&536870912)!==0)o.memoizedState={baseLanes:0,cachePool:null},r!==null&&at(o,O!==null?O.cachePool:null),O!==null?vo(o,O):Lo(),Tr(o);else return v=o.lanes=536870912,G2(r,o,O!==null?O.baseLanes|h:h,h,v)}else O!==null?(at(o,O.cachePool),vo(o,O),Nc(),o.memoizedState=null):(r!==null&&at(o,null),Lo(),Nc());return Qi(r,o,A,h),o.child}function Wp(r,o){return r!==null&&r.tag===22||o.stateNode!==null||(o.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.sibling}function G2(r,o,h,v,A){var O=Ze();return O=O===null?null:{parent:Gr._currentValue,pool:O},o.memoizedState={baseLanes:h,cachePool:O},r!==null&&at(o,null),Lo(),Tr(o),r!==null&&Sl(r,o,v,!0),o.childLanes=A,null}function ny(r,o){return o=sy({mode:o.mode,children:o.children},r.mode),o.ref=r.ref,r.child=o,o.return=r,o}function Y2(r,o,h){return As(o,r.child,null,h),r=ny(o,o.pendingProps),r.flags|=2,ro(o),o.memoizedState=null,r}function ZE(r,o,h){var v=o.pendingProps,A=(o.flags&128)!==0;if(o.flags&=-129,r===null){if(Cs){if(v.mode==="hidden")return r=ny(o,v),o.lanes=536870912,Wp(null,r);if(wc(o),(r=Nr)?(r=iS(r,Lr),r=r!==null&&r.data==="&"?r:null,r!==null&&(o.memoizedState={dehydrated:r,treeContext:xl!==null?{id:Mo,overflow:$o}:null,retryLane:536870912,hydrationErrors:null},h=sm(r),h.return=o,o.child=h,Si=o,Nr=null)):r=null,r===null)throw jl(o);return o.lanes=536870912,null}return ny(o,v)}var O=r.memoizedState;if(O!==null){var Ne=O.dehydrated;if(wc(o),A)if(o.flags&256)o.flags&=-257,o=Y2(r,o,h);else if(o.memoizedState!==null)o.child=r.child,o.flags|=128,o=null;else throw Error(s(558));else if(gi||Sl(r,o,h,!1),A=(h&r.childLanes)!==0,gi||A){if(v=Cr,v!==null&&(Ne=gn(v,h),Ne!==0&&Ne!==O.retryLane))throw O.retryLane=Ne,Hc(r,Ne),qo(v,r,Ne),Dx;my(),o=Y2(r,o,h)}
vendor: 4,531 bytes, line 48
48else r=O.treeContext,Nr=Ic(Ne.nextSibling),Si=o,Cs=!0,Yi=null,Lr=!1,r!==null&&Wg(o,r),o=ny(o,v),o.flags|=4096;return o}return r=Eo(r.child,{mode:v.mode,children:v.children}),r.ref=o.ref,o.child=r,r.return=o,r}function ay(r,o){var h=o.ref;if(h===null)r!==null&&r.ref!==null&&(o.flags|=4194816);else{if(typeof h!="function"&&typeof h!="object")throw Error(s(284));(r===null||r.ref!==h)&&(o.flags|=4194816)}}function Ex(r,o,h,v,A){return Cl(o),h=Op(r,o,h,v,void 0,A),v=Lp(),r!==null&&!gi?(Bp(r,o,A),ad(r,o,A)):(Cs&&v&&Rp(o),o.flags|=1,Qi(r,o,h,A),o.child)}function Q2(r,o,h,v,A,O){return Cl(o),o.updateQueue=null,h=Yc(o,v,h,A),mm(r),v=Lp(),r!==null&&!gi?(Bp(r,o,O),ad(r,o,O)):(Cs&&v&&Rp(o),o.flags|=1,Qi(r,o,h,O),o.child)}function J2(r,o,h,v,A){if(Cl(o),o.stateNode===null){var O=Ni,Ne=h.contextType;typeof Ne=="object"&&Ne!==null&&(O=Ai(Ne)),O=new h(v,O),o.memoizedState=O.state!==null&&O.state!==void 0?O.state:null,O.updater=_x,o.stateNode=O,O._reactInternals=o,O=o.stateNode,O.props=v,O.state=o.memoizedState,O.refs={},Ks(o),Ne=h.contextType,O.context=typeof Ne=="object"&&Ne!==null?Ai(Ne):Ni,O.state=o.memoizedState,Ne=h.getDerivedStateFromProps,typeof Ne=="function"&&(Ix(o,h,Ne,v),O.state=o.memoizedState),typeof h.getDerivedStateFromProps=="function"||typeof O.getSnapshotBeforeUpdate=="function"||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(Ne=O.state,typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount(),Ne!==O.state&&_x.enqueueReplaceState(O,O.state,null),Ii(o,v,O,A),Ls(),O.state=o.memoizedState),typeof O.componentDidMount=="function"&&(o.flags|=4194308),v=!0}else if(r===null){O=o.stateNode;var et=o.memoizedProps,_t=rh(h,et);O.props=_t;var hn=O.context,Dn=h.contextType;Ne=Ni,typeof Dn=="object"&&Dn!==null&&(Ne=Ai(Dn));var qn=h.getDerivedStateFromProps;Dn=typeof qn=="function"||typeof O.getSnapshotBeforeUpdate=="function",et=o.pendingProps!==et,Dn||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(et||hn!==Ne)&&$2(o,O,v,Ne),cs=!1;var fn=o.memoizedState;O.state=fn,Ii(o,v,O,A),Ls(),hn=o.memoizedState,et||fn!==hn||cs?(typeof qn=="function"&&(Ix(o,h,qn,v),hn=o.memoizedState),(_t=cs||M2(o,h,_t,v,fn,hn,Ne))?(Dn||typeof O.UNSAFE_componentWillMount!="function"&&typeof O.componentWillMount!="function"||(typeof O.componentWillMount=="function"&&O.componentWillMount(),typeof O.UNSAFE_componentWillMount=="function"&&O.UNSAFE_componentWillMount()),typeof O.componentDidMount=="function"&&(o.flags|=4194308)):(typeof O.componentDidMount=="function"&&(o.flags|=4194308),o.memoizedProps=v,o.memoizedState=hn),O.props=v,O.state=hn,O.context=Ne,v=_t):(typeof O.componentDidMount=="function"&&(o.flags|=4194308),v=!1)}else{O=o.stateNode,Ws(r,o),Ne=o.memoizedProps,Dn=rh(h,Ne),O.props=Dn,qn=o.pendingProps,fn=O.context,hn=h.contextType,_t=Ni,typeof hn=="object"&&hn!==null&&(_t=Ai(hn)),et=h.getDerivedStateFromProps,(hn=typeof et=="function"||typeof O.getSnapshotBeforeUpdate=="function")||typeof O.UNSAFE_componentWillReceiveProps!="function"&&typeof O.componentWillReceiveProps!="function"||(Ne!==qn||fn!==_t)&&$2(o,O,v,_t),cs=!1,fn=o.memoizedState,O.state=fn,Ii(o,v,O,A),Ls();var bn=o.memoizedState;Ne!==qn||fn!==bn||cs||r!==null&&r.dependencies!==null&&lm(r.dependencies)?(typeof et=="function"&&(Ix(o,h,et,v),bn=o.memoizedState),(Dn=cs||M2(o,h,Dn,v,fn,bn,_t)||r!==null&&r.dependencies!==null&&lm(r.dependencies))?(hn||typeof O.UNSAFE_componentWillUpdate!="function"&&typeof O.componentWillUpdate!="function"||(typeof O.componentWillUpdate=="function"&&O.componentWillUpdate(v,bn,_t),typeof O.UNSAFE_componentWillUpdate=="function"&&O.UNSAFE_componentWillUpdate(v,bn,_t)),typeof O.componentDidUpdate=="function"&&(o.flags|=4),typeof O.getSnapshotBeforeUpdate=="function"&&(o.flags|=1024)):(typeof O.componentDidUpdate!="function"||Ne===r.memoizedProps&&fn===r.memoizedState||(o.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||Ne===r.memoizedProps&&fn===r.memoizedState||(o.flags|=1024),o.memoizedProps=v,o.memoizedState=bn),O.props=v,O.state=bn,O.context=_t,v=Dn):(typeof O.componentDidUpdate!="function"||Ne===r.memoizedProps&&fn===r.memoizedState||(o.flags|=4),typeof O.getSnapshotBeforeUpdate!="function"||Ne===r.memoizedProps&&fn===r.memoizedState||(o.flags|=1024),v=!1)}return O=v,ay(r,o),v=(o.flags&128)!==0,O||v?(O=o.stateNode,h=v&&typeof h.getDerivedStateFromError!="function"?null:O.render(),o.flags|=1,r!==null&&v?(
vendor: 5,858 bytes, line 48
48o.child=As(o,r.child,null,A),o.child=As(o,null,h,A)):Qi(r,o,h,A),o.memoizedState=O.state,r=o.child):r=ad(r,o,A),r}function K2(r,o,h,v){return Jl(),o.flags|=256,Qi(r,o,h,v),o.child}var Px={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Rx(r){return{baseLanes:r,cachePool:mt()}}function Tx(r,o,h){return r=r!==null?r.childLanes&~h:0,o&&(r|=sc),r}function X2(r,o,h){var v=o.pendingProps,A=!1,O=(o.flags&128)!==0,Ne;if((Ne=O)||(Ne=r!==null&&r.memoizedState===null?!1:(Ur.current&2)!==0),Ne&&(A=!0,o.flags&=-129),Ne=(o.flags&32)!==0,o.flags&=-33,r===null){if(Cs){if(A?bo(o):Nc(),(r=Nr)?(r=iS(r,Lr),r=r!==null&&r.data!=="&"?r:null,r!==null&&(o.memoizedState={dehydrated:r,treeContext:xl!==null?{id:Mo,overflow:$o}:null,retryLane:536870912,hydrationErrors:null},h=sm(r),h.return=o,o.child=h,Si=o,Nr=null)):r=null,r===null)throw jl(o);return g0(r)?o.lanes=32:o.lanes=536870912,null}var et=v.children;return v=v.fallback,A?(Nc(),A=o.mode,et=sy({mode:"hidden",children:et},A),v=bl(v,A,h,null),et.return=o,v.return=o,et.sibling=v,o.child=et,v=o.child,v.memoizedState=Rx(h),v.childLanes=Tx(r,Ne,h),o.memoizedState=Px,Wp(null,v)):(bo(o),Mx(o,et))}var _t=r.memoizedState;if(_t!==null&&(et=_t.dehydrated,et!==null)){if(O)o.flags&256?(bo(o),o.flags&=-257,o=$x(r,o,h)):o.memoizedState!==null?(Nc(),o.child=r.child,o.flags|=128,o=null):(Nc(),et=v.fallback,A=o.mode,v=sy({mode:"visible",children:v.children},A),et=bl(et,A,h,null),et.flags|=2,v.return=o,et.return=o,v.sibling=et,o.child=v,As(o,r.child,null,h),v=o.child,v.memoizedState=Rx(h),v.childLanes=Tx(r,Ne,h),o.memoizedState=Px,o=Wp(null,v));else if(bo(o),g0(et)){if(Ne=et.nextSibling&&et.nextSibling.dataset,Ne)var hn=Ne.dgst;Ne=hn,v=Error(s(419)),v.stack="",v.digest=Ne,Ld({value:v,source:null,stack:null}),o=$x(r,o,h)}else if(gi||Sl(r,o,h,!1),Ne=(h&r.childLanes)!==0,gi||Ne){if(Ne=Cr,Ne!==null&&(v=gn(Ne,h),v!==0&&v!==_t.retryLane))throw _t.retryLane=v,Hc(r,v),qo(Ne,r,v),Dx;f0(et)||my(),o=$x(r,o,h)}else f0(et)?(o.flags|=192,o.child=r.child,o=null):(r=_t.treeContext,Nr=Ic(et.nextSibling),Si=o,Cs=!0,Yi=null,Lr=!1,r!==null&&Wg(o,r),o=Mx(o,v.children),o.flags|=4096);return o}return A?(Nc(),et=v.fallback,A=o.mode,_t=r.child,hn=_t.sibling,v=Eo(_t,{mode:"hidden",children:v.children}),v.subtreeFlags=_t.subtreeFlags&65011712,hn!==null?et=Eo(hn,et):(et=bl(et,A,h,null),et.flags|=2),et.return=o,v.return=o,v.sibling=et,o.child=v,Wp(null,v),v=o.child,et=r.child.memoizedState,et===null?et=Rx(h):(A=et.cachePool,A!==null?(_t=Gr._currentValue,A=A.parent!==_t?{parent:_t,pool:_t}:A):A=mt(),et={baseLanes:et.baseLanes|h,cachePool:A}),v.memoizedState=et,v.childLanes=Tx(r,Ne,h),o.memoizedState=Px,Wp(r.child,v)):(bo(o),h=r.child,r=h.sibling,h=Eo(h,{mode:"visible",children:v.children}),h.return=o,h.sibling=null,r!==null&&(Ne=o.deletions,Ne===null?(o.deletions=[r],o.flags|=16):Ne.push(r)),o.child=h,o.memoizedState=null,h)}function Mx(r,o){return o=sy({mode:"visible",children:o},r.mode),o.return=r,r.child=o}function sy(r,o){return r=Bi(22,r,null,o),r.lanes=0,r}function $x(r,o,h){return As(o,r.child,null,h),r=Mx(o,o.pendingProps.children),r.flags|=2,o.memoizedState=null,r}function Z2(r,o,h){r.lanes|=o;var v=r.alternate;v!==null&&(v.lanes|=o),Bd(r.return,o,h)}function Ox(r,o,h,v,A,O){var Ne=r.memoizedState;Ne===null?r.memoizedState={isBackwards:o,rendering:null,renderingStartTime:0,last:v,tail:h,tailMode:A,treeForkCount:O}:(Ne.isBackwards=o,Ne.rendering=null,Ne.renderingStartTime=0,Ne.last=v,Ne.tail=h,Ne.tailMode=A,Ne.treeForkCount=O)}function eN(r,o,h){var v=o.pendingProps,A=v.revealOrder,O=v.tail;v=v.children;var Ne=Ur.current,et=(Ne&2)!==0;if(et?(Ne=Ne&1|2,o.flags|=128):Ne&=1,F(Ur,Ne),Qi(r,o,v,h),v=Cs?Zu:0,!et&&r!==null&&(r.flags&128)!==0)e:for(r=o.child;r!==null;){if(r.tag===13)r.memoizedState!==null&&Z2(r,h,o);else if(r.tag===19)Z2(r,h,o);else if(r.child!==null){r.child.return=r,r=r.child;continue}if(r===o)break e;for(;r.sibling===null;){if(r.return===null||r.return===o)break e;r=r.return}r.sibling.return=r.return,r=r.sibling}switch(A){case"forwards":for(h=o.child,A=null;h!==null;)r=h.alternate,r!==null&&Xl(r)===null&&(A=h),h=h.sibling;h=A,h===null?(A=o.child,o.child=null):(A=h.sibling,h.sibling=null),Ox(o,!1,A,h,O,v);break;case"backwards":case"unstable_legacy-backwards":for(h=null,A=o.child,o.child=null;A!==null;){if(r=A.alternate,r!==null&&Xl(r)===null){o.child=A;break}r=A.sibling,A.sibling=h,h=A,A=r}Ox(o,!0,h,null,O,v);break;case"together":Ox(o,!1,null,null,void 0,v);break;default:o.memoizedState=null}return o.child}function ad(r,o,h){if(r!==null&&(o.dependencies=r.dependencies),Gd|=o.lanes,(h&o.childLanes)===0)if(r!==null){if(Sl(r,o,h,!1),(h&o.childLanes)===0)return null}else return null;if(r!==null&&o.child!==r.child)throw Error(s(153));if(o.child!==null){for(r=o.child,h=Eo(r,r.pendingProps),o.child=h,h.return=o;r.sibling!==null;)r=r.sibling,h=h.sibling=Eo(r,r.pendingProps),h.return=o;h.sibling=null}return o.child}function Lx(r,o){return(r.lanes&o)!==0?!0:(r=r.dependencies,!!(r!==null&&lm(r)))}function eP(r,o,h){switch(o.tag){case 3:de(o,o.stateNode.containerInfo),Nl(o,Gr,r.memoizedState.cache),Jl();break;case 27:case 5:Re(o);break;case 4:de(o,o.stateNode.containerInfo);break;case 10:Nl(o,o.type,o.memoizedProps.value);break;case 31:if(o.memoizedState!==null)return o.flags|=128,wc(o),null;break;case 13:var v=o.memoizedState;if(v!==null)return v.dehydrated!==null?(bo(o),o.flags|=128,null):(h&o.child.childLanes)!==0?X2(r,o,h):(bo(o),r=ad(r,o,h),r!==null?r.sibling:null);bo(o);break;case 19:var A=(r.flags&128)!==0;if(v=(h&o.childLanes)!==0,v||(Sl(r,o,h,!1),v=(h&o.childLanes)!==0),A){if(v)return eN(r,o,h);o.flags|=128}if(A=o.memoizedState,A!==null&&(A.rendering=null,A.tail=null,A.lastEffect=null),F(Ur,Ur.current),v)break;return null;case 22:return o.lanes=0,W2(r,o,h,o.pendingProps);case 24:Nl(o,Gr,r.memoizedState.cache)}return ad(r,o,h)}
vendor: 4,478 bytes, line 48
48function tN(r,o,h){if(r!==null)if(r.memoizedProps!==o.pendingProps)gi=!0;else{if(!Lx(r,h)&&(o.flags&128)===0)return gi=!1,eP(r,o,h);gi=(r.flags&131072)!==0}else gi=!1,Cs&&(o.flags&1048576)!==0&&Hg(o,Zu,o.index);switch(o.lanes=0,o.tag){case 16:e:{var v=o.pendingProps;if(r=Mt(o.elementType),o.type=r,typeof r=="function")am(r)?(v=rh(r,v),o.tag=1,o=J2(null,o,r,v,h)):(o.tag=0,o=Ex(null,o,r,v,h));else{if(r!=null){var A=r.$$typeof;if(A===_){o.tag=11,o=q2(null,o,r,v,h);break e}else if(A===G){o.tag=14,o=V2(null,o,r,v,h);break e}}throw o=Z(r)||r,Error(s(306,o,""))}}return o;case 0:return Ex(r,o,o.type,o.pendingProps,h);case 1:return v=o.type,A=rh(v,o.pendingProps),J2(r,o,v,A,h);case 3:e:{if(de(o,o.stateNode.containerInfo),r===null)throw Error(s(387));v=o.pendingProps;var O=o.memoizedState;A=O.element,Ws(r,o),Ii(o,v,null,h);var Ne=o.memoizedState;if(v=Ne.cache,Nl(o,Gr,v),v!==O.cache&&Kl(o,[Gr],h,!0),Ls(),v=Ne.element,O.isDehydrated)if(O={element:v,isDehydrated:!1,cache:Ne.cache},o.updateQueue.baseState=O,o.memoizedState=O,o.flags&256){o=K2(r,o,v,h);break e}else if(v!==A){A=Po(Error(s(424)),o),Ld(A),o=K2(r,o,v,h);break e}else{switch(r=o.stateNode.containerInfo,r.nodeType){case 9:r=r.body;break;default:r=r.nodeName==="HTML"?r.ownerDocument.body:r}for(Nr=Ic(r.firstChild),Si=o,Cs=!0,Yi=null,Lr=!0,h=Ps(o,null,v,h),o.child=h;h;)h.flags=h.flags&-3|4096,h=h.sibling}else{if(Jl(),v===A){o=ad(r,o,h);break e}Qi(r,o,v,h)}o=o.child}return o;case 26:return ay(r,o),r===null?(h=hS(o.type,null,o.pendingProps,null))?o.memoizedState=h:Cs||(h=o.type,r=o.pendingProps,v=xy(me.current).createElement(h),v[$t]=o,v[Vt]=r,Ji(v,h,r),In(v),o.stateNode=v):o.memoizedState=hS(o.type,r.memoizedProps,o.pendingProps,r.memoizedState),null;case 27:return Re(o),r===null&&Cs&&(v=o.stateNode=lS(o.type,o.pendingProps,me.current),Si=o,Lr=!0,A=Nr,Xd(o.type)?(y0=A,Nr=Ic(v.firstChild)):Nr=A),Qi(r,o,o.pendingProps.children,h),ay(r,o),r===null&&(o.flags|=4194304),o.child;case 5:return r===null&&Cs&&((A=v=Nr)&&(v=DP(v,o.type,o.pendingProps,Lr),v!==null?(o.stateNode=v,Si=o,Nr=Ic(v.firstChild),Lr=!1,A=!0):A=!1),A||jl(o)),Re(o),A=o.type,O=o.pendingProps,Ne=r!==null?r.memoizedProps:null,v=O.children,h0(A,O)?v=null:Ne!==null&&h0(A,Ne)&&(o.flags|=32),o.memoizedState!==null&&(A=Op(r,o,bx,null,null,h),cf._currentValue=A),ay(r,o),Qi(r,o,v,h),o.child;case 6:return r===null&&Cs&&((r=h=Nr)&&(h=EP(h,o.pendingProps,Lr),h!==null?(o.stateNode=h,Si=o,Nr=null,r=!0):r=!1),r||jl(o)),null;case 13:return X2(r,o,h);case 4:return de(o,o.stateNode.containerInfo),v=o.pendingProps,r===null?o.child=As(o,null,v,h):Qi(r,o,v,h),o.child;case 11:return q2(r,o,o.type,o.pendingProps,h);case 7:return Qi(r,o,o.pendingProps,h),o.child;case 8:return Qi(r,o,o.pendingProps.children,h),o.child;case 12:return Qi(r,o,o.pendingProps.children,h),o.child;case 10:return v=o.pendingProps,Nl(o,o.type,v.value),Qi(r,o,v.children,h),o.child;case 9:return A=o.type._context,v=o.pendingProps.children,Cl(o),A=Ai(A),v=v(A),o.flags|=1,Qi(r,o,v,h),o.child;case 14:return V2(r,o,o.type,o.pendingProps,h);case 15:return H2(r,o,o.type,o.pendingProps,h);case 19:return eN(r,o,h);case 31:return ZE(r,o,h);case 22:return W2(r,o,h,o.pendingProps);case 24:return Cl(o),v=Ai(Gr),r===null?(A=Ze(),A===null&&(A=Cr,O=Fd(),A.pooledCache=O,O.refCount++,O!==null&&(A.pooledCacheLanes|=h),A=O),o.memoizedState={parent:v,cache:A},Ks(o),Nl(o,Gr,A)):((r.lanes&h)!==0&&(Ws(r,o),Ii(o,null,null,h),Ls()),A=r.memoizedState,O=o.memoizedState,A.parent!==v?(A={parent:v,cache:v},o.memoizedState=A,o.lanes===0&&(o.memoizedState=o.updateQueue.baseState=A),Nl(o,Gr,v)):(v=O.cache,Nl(o,Gr,v),v!==A.cache&&Kl(o,[Gr],h,!0))),Qi(r,o,o.pendingProps.children,h),o.child;case 29:throw o.pendingProps}throw Error(s(156,o.tag))}function sd(r){r.flags|=4}function Bx(r,o,h,v,A){if((o=(r.mode&32)!==0)&&(o=!1),o){if(r.flags|=16777216,(A&335544128)===A)if(r.stateNode.complete)r.flags|=8192;else if(_N())r.flags|=8192;else throw Ut=Kt,ln}else r.flags&=-16777217}function nN(r,o){if(o.type!=="stylesheet"||(o.state.loading&4)!==0)r.flags&=-16777217;else if(r.flags|=16777216,!yS(o))if(_N())r.flags|=8192;else throw Ut=Kt,ln}function ry(r,o){o!==null&&(r.flags|=4),r.flags&16384&&(o=r.tag!==22?ht():536870912,r.lanes|=o,Sm|=o)}function Gp(r,o){if(!Cs)switch(r.tailMode){case"hidden":o=r.tail;for(var h=null;o!==null;)o.alternate!==null&&(h=o),o=o.sibling;h===null?r.tail=null:h.sibling=null;break;case"collapsed":h=r.tail;for(var v=null;h!==null;)h.alternate!==null&&(v=h),h=h.sibling;
vendor: 8,269 bytes, line 48
48v===null?o||r.tail===null?r.tail=null:r.tail.sibling=null:v.sibling=null}}function Mr(r){var o=r.alternate!==null&&r.alternate.child===r.child,h=0,v=0;if(o)for(var A=r.child;A!==null;)h|=A.lanes|A.childLanes,v|=A.subtreeFlags&65011712,v|=A.flags&65011712,A.return=r,A=A.sibling;else for(A=r.child;A!==null;)h|=A.lanes|A.childLanes,v|=A.subtreeFlags,v|=A.flags,A.return=r,A=A.sibling;return r.subtreeFlags|=v,r.childLanes=h,o}function tP(r,o,h){var v=o.pendingProps;switch(om(o),o.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Mr(o),null;case 1:return Mr(o),null;case 3:return h=o.stateNode,v=null,r!==null&&(v=r.memoizedState.cache),o.memoizedState.cache!==v&&(o.flags|=2048),Oo(Gr),Pe(),h.pendingContext&&(h.context=h.pendingContext,h.pendingContext=null),(r===null||r.child===null)&&(Ci(o)?sd(o):r===null||r.memoizedState.isDehydrated&&(o.flags&256)===0||(o.flags|=1024,Mp())),Mr(o),null;case 26:var A=o.type,O=o.memoizedState;return r===null?(sd(o),O!==null?(Mr(o),nN(o,O)):(Mr(o),Bx(o,A,null,v,h))):O?O!==r.memoizedState?(sd(o),Mr(o),nN(o,O)):(Mr(o),o.flags&=-16777217):(r=r.memoizedProps,r!==v&&sd(o),Mr(o),Bx(o,A,r,v,h)),null;case 27:if(Ee(o),h=me.current,A=o.type,r!==null&&o.stateNode!=null)r.memoizedProps!==v&&sd(o);else{if(!v){if(o.stateNode===null)throw Error(s(166));return Mr(o),null}r=P.current,Ci(o)?Tp(o):(r=lS(A,v,h),o.stateNode=r,sd(o))}return Mr(o),null;case 5:if(Ee(o),A=o.type,r!==null&&o.stateNode!=null)r.memoizedProps!==v&&sd(o);else{if(!v){if(o.stateNode===null)throw Error(s(166));return Mr(o),null}if(O=P.current,Ci(o))Tp(o);else{var Ne=xy(me.current);switch(O){case 1:O=Ne.createElementNS("http://www.w3.org/2000/svg",A);break;case 2:O=Ne.createElementNS("http://www.w3.org/1998/Math/MathML",A);break;default:switch(A){case"svg":O=Ne.createElementNS("http://www.w3.org/2000/svg",A);break;case"math":O=Ne.createElementNS("http://www.w3.org/1998/Math/MathML",A);break;case"script":O=Ne.createElement("div"),O.innerHTML="<script><\/script>",O=O.removeChild(O.firstChild);break;case"select":O=typeof v.is=="string"?Ne.createElement("select",{is:v.is}):Ne.createElement("select"),v.multiple?O.multiple=!0:v.size&&(O.size=v.size);break;default:O=typeof v.is=="string"?Ne.createElement(A,{is:v.is}):Ne.createElement(A)}}O[$t]=o,O[Vt]=v;e:for(Ne=o.child;Ne!==null;){if(Ne.tag===5||Ne.tag===6)O.appendChild(Ne.stateNode);else if(Ne.tag!==4&&Ne.tag!==27&&Ne.child!==null){Ne.child.return=Ne,Ne=Ne.child;continue}if(Ne===o)break e;for(;Ne.sibling===null;){if(Ne.return===null||Ne.return===o)break e;Ne=Ne.return}Ne.sibling.return=Ne.return,Ne=Ne.sibling}o.stateNode=O;e:switch(Ji(O,A,v),A){case"button":case"input":case"select":case"textarea":v=!!v.autoFocus;break e;case"img":v=!0;break e;default:v=!1}v&&sd(o)}}return Mr(o),Bx(o,o.type,r===null?null:r.memoizedProps,o.pendingProps,h),null;case 6:if(r&&o.stateNode!=null)r.memoizedProps!==v&&sd(o);else{if(typeof v!="string"&&o.stateNode===null)throw Error(s(166));if(r=me.current,Ci(o)){if(r=o.stateNode,h=o.memoizedProps,v=null,A=Si,A!==null)switch(A.tag){case 27:case 5:v=A.memoizedProps}r[$t]=o,r=!!(r.nodeValue===h||v!==null&&v.suppressHydrationWarning===!0||XN(r.nodeValue,h)),r||jl(o,!0)}else r=xy(r).createTextNode(v),r[$t]=o,o.stateNode=r}return Mr(o),null;case 31:if(h=o.memoizedState,r===null||r.memoizedState!==null){if(v=Ci(o),h!==null){if(r===null){if(!v)throw Error(s(318));if(r=o.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(s(557));r[$t]=o}else Jl(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;Mr(o),r=!1}else h=Mp(),r!==null&&r.memoizedState!==null&&(r.memoizedState.hydrationErrors=h),r=!0;if(!r)return o.flags&256?(ro(o),o):(ro(o),null);if((o.flags&128)!==0)throw Error(s(558))}return Mr(o),null;case 13:if(v=o.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(A=Ci(o),v!==null&&v.dehydrated!==null){if(r===null){if(!A)throw Error(s(318));if(A=o.memoizedState,A=A!==null?A.dehydrated:null,!A)throw Error(s(317));A[$t]=o}else Jl(),(o.flags&128)===0&&(o.memoizedState=null),o.flags|=4;Mr(o),A=!1}else A=Mp(),r!==null&&r.memoizedState!==null&&(r.memoizedState.hydrationErrors=A),A=!0;if(!A)return o.flags&256?(ro(o),o):(ro(o),null)}return ro(o),(o.flags&128)!==0?(o.lanes=h,o):(h=v!==null,r=r!==null&&r.memoizedState!==null,h&&(v=o.child,A=null,v.alternate!==null&&v.alternate.memoizedState!==null&&v.alternate.memoizedState.cachePool!==null&&(A=v.alternate.memoizedState.cachePool.pool),O=null,v.memoizedState!==null&&v.memoizedState.cachePool!==null&&(O=v.memoizedState.cachePool.pool),O!==A&&(v.flags|=2048)),h!==r&&h&&(o.child.flags|=8192),ry(o,o.updateQueue),Mr(o),null);case 4:return Pe(),r===null&&o0(o.stateNode.containerInfo),Mr(o),null;case 10:return Oo(o.type),Mr(o),null;case 19:if($(Ur),v=o.memoizedState,v===null)return Mr(o),null;if(A=(o.flags&128)!==0,O=v.rendering,O===null)if(A)Gp(v,!1);else{if(ei!==0||r!==null&&(r.flags&128)!==0)for(r=o.child;r!==null;){if(O=Xl(r),O!==null){for(o.flags|=128,Gp(v,!1),r=O.updateQueue,o.updateQueue=r,ry(o,r),o.subtreeFlags=0,r=h,h=o.child;h!==null;)Ku(h,r),h=h.sibling;return F(Ur,Ur.current&1|2),Cs&&yo(o,v.treeForkCount),o.child}r=r.sibling}v.tail!==null&&ct()>dy&&(o.flags|=128,A=!0,Gp(v,!1),o.lanes=4194304)}else{if(!A)if(r=Xl(O),r!==null){if(o.flags|=128,A=!0,r=r.updateQueue,o.updateQueue=r,ry(o,r),Gp(v,!0),v.tail===null&&v.tailMode==="hidden"&&!O.alternate&&!Cs)return Mr(o),null}else 2*ct()-v.renderingStartTime>dy&&h!==536870912&&(o.flags|=128,A=!0,Gp(v,!1),o.lanes=4194304);v.isBackwards?(O.sibling=o.child,o.child=O):(r=v.last,r!==null?r.sibling=O:o.child=O,v.last=O)}return v.tail!==null?(r=v.tail,v.rendering=r,v.tail=r.sibling,v.renderingStartTime=ct(),r.sibling=null,h=Ur.current,F(Ur,A?h&1|2:h&1),Cs&&yo(o,v.treeForkCount),r):(Mr(o),null);case 22:case 23:return ro(o),Zr(),v=o.memoizedState!==null,r!==null?r.memoizedState!==null!==v&&(o.flags|=8192):v&&(o.flags|=8192),v?(h&536870912)!==0&&(o.flags&128)===0&&(Mr(o),o.subtreeFlags&6&&(o.flags|=8192)):Mr(o),h=o.updateQueue,h!==null&&ry(o,h.retryQueue),h=null,r!==null&&r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(h=r.memoizedState.cachePool.pool),v=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(v=o.memoizedState.cachePool.pool),v!==h&&(o.flags|=2048),r!==null&&$(Ke),null;case 24:return h=null,r!==null&&(h=r.memoizedState.cache),o.memoizedState.cache!==h&&(o.flags|=2048),Oo(Gr),Mr(o),null;case 25:return null;case 30:return null}throw Error(s(156,o.tag))}function nP(r,o){switch(om(o),o.tag){case 1:return r=o.flags,r&65536?(o.flags=r&-65537|128,o):null;case 3:return Oo(Gr),Pe(),r=o.flags,(r&65536)!==0&&(r&128)===0?(o.flags=r&-65537|128,o):null;case 26:case 27:case 5:return Ee(o),null;case 31:if(o.memoizedState!==null){if(ro(o),o.alternate===null)throw Error(s(340));Jl()}return r=o.flags,r&65536?(o.flags=r&-65537|128,o):null;case 13:if(ro(o),r=o.memoizedState,r!==null&&r.dehydrated!==null){if(o.alternate===null)throw Error(s(340));Jl()}return r=o.flags,r&65536?(o.flags=r&-65537|128,o):null;case 19:return $(Ur),null;case 4:return Pe(),null;case 10:return Oo(o.type),null;case 22:case 23:return ro(o),Zr(),r!==null&&$(Ke),r=o.flags,r&65536?(o.flags=r&-65537|128,o):null;case 24:return Oo(Gr),null;case 25:return null;default:return null}}function aN(r,o){switch(om(o),o.tag){case 3:Oo(Gr),Pe();break;case 26:case 27:case 5:Ee(o);break;case 4:Pe();break;case 31:o.memoizedState!==null&&ro(o);break;case 13:ro(o);break;case 19:$(Ur);break;case 10:Oo(o.type);break;case 22:case 23:ro(o),Zr(),r!==null&&$(Ke);break;case 24:Oo(Gr)}}function Yp(r,o){try{var h=o.updateQueue,v=h!==null?h.lastEffect:null;if(v!==null){var A=v.next;h=A;do{if((h.tag&r)===r){v=void 0;var O=h.create,Ne=h.inst;v=O(),Ne.destroy=v}h=h.next}while(h!==A)}}catch(et){cr(o,o.return,et)}}function Hd(r,o,h){try{var v=o.updateQueue,A=v!==null?v.lastEffect:null;if(A!==null){var O=A.next;v=O;do{if((v.tag&r)===r){var Ne=v.inst,et=Ne.destroy;if(et!==void 0){Ne.destroy=void 0,A=o;var _t=h,hn=et;try{hn()}catch(Dn){cr(A,_t,Dn)}}}v=v.next}while(v!==O)}}catch(Dn){cr(o,o.return,Dn)}}function sN(r){var o=r.updateQueue;if(o!==null){var h=r.stateNode;try{ri(o,h)}catch(v){cr(r,r.return,v)}}}function rN(r,o,h){h.props=rh(r.type,r.memoizedProps),h.state=r.memoizedState;
vendor: 20,020 bytes, line 48
48try{h.componentWillUnmount()}catch(v){cr(r,o,v)}}function Qp(r,o){try{var h=r.ref;if(h!==null){switch(r.tag){case 26:case 27:case 5:var v=r.stateNode;break;case 30:v=r.stateNode;break;default:v=r.stateNode}typeof h=="function"?r.refCleanup=h(v):h.current=v}}catch(A){cr(r,o,A)}}function Dl(r,o){var h=r.ref,v=r.refCleanup;if(h!==null)if(typeof v=="function")try{v()}catch(A){cr(r,o,A)}finally{r.refCleanup=null,r=r.alternate,r!=null&&(r.refCleanup=null)}else if(typeof h=="function")try{h(null)}catch(A){cr(r,o,A)}else h.current=null}function iN(r){var o=r.type,h=r.memoizedProps,v=r.stateNode;try{e:switch(o){case"button":case"input":case"select":case"textarea":h.autoFocus&&v.focus();break e;case"img":h.src?v.src=h.src:h.srcSet&&(v.srcset=h.srcSet)}}catch(A){cr(r,r.return,A)}}function Fx(r,o,h){try{var v=r.stateNode;SP(v,r.type,h,o),v[Vt]=o}catch(A){cr(r,r.return,A)}}function oN(r){return r.tag===5||r.tag===3||r.tag===26||r.tag===27&&Xd(r.type)||r.tag===4}function Ux(r){e:for(;;){for(;r.sibling===null;){if(r.return===null||oN(r.return))return null;r=r.return}for(r.sibling.return=r.return,r=r.sibling;r.tag!==5&&r.tag!==6&&r.tag!==18;){if(r.tag===27&&Xd(r.type)||r.flags&2||r.child===null||r.tag===4)continue e;r.child.return=r,r=r.child}if(!(r.flags&2))return r.stateNode}}function zx(r,o,h){var v=r.tag;if(v===5||v===6)r=r.stateNode,o?(h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h).insertBefore(r,o):(o=h.nodeType===9?h.body:h.nodeName==="HTML"?h.ownerDocument.body:h,o.appendChild(r),h=h._reactRootContainer,h!=null||o.onclick!==null||(o.onclick=Ma));else if(v!==4&&(v===27&&Xd(r.type)&&(h=r.stateNode,o=null),r=r.child,r!==null))for(zx(r,o,h),r=r.sibling;r!==null;)zx(r,o,h),r=r.sibling}function iy(r,o,h){var v=r.tag;if(v===5||v===6)r=r.stateNode,o?h.insertBefore(r,o):h.appendChild(r);else if(v!==4&&(v===27&&Xd(r.type)&&(h=r.stateNode),r=r.child,r!==null))for(iy(r,o,h),r=r.sibling;r!==null;)iy(r,o,h),r=r.sibling}function cN(r){var o=r.stateNode,h=r.memoizedProps;try{for(var v=r.type,A=o.attributes;A.length;)o.removeAttributeNode(A[0]);Ji(o,v,h),o[$t]=r,o[Vt]=h}catch(O){cr(r,r.return,O)}}var rd=!1,yi=!1,qx=!1,lN=typeof WeakSet=="function"?WeakSet:Set,Ui=null;function aP(r,o){if(r=r.containerInfo,d0=Iy,r=Ft(r),rn(r)){if("selectionStart"in r)var h={start:r.selectionStart,end:r.selectionEnd};else e:{h=(h=r.ownerDocument)&&h.defaultView||window;var v=h.getSelection&&h.getSelection();if(v&&v.rangeCount!==0){h=v.anchorNode;var A=v.anchorOffset,O=v.focusNode;v=v.focusOffset;try{h.nodeType,O.nodeType}catch{h=null;break e}var Ne=0,et=-1,_t=-1,hn=0,Dn=0,qn=r,fn=null;t:for(;;){for(var bn;qn!==h||A!==0&&qn.nodeType!==3||(et=Ne+A),qn!==O||v!==0&&qn.nodeType!==3||(_t=Ne+v),qn.nodeType===3&&(Ne+=qn.nodeValue.length),(bn=qn.firstChild)!==null;)fn=qn,qn=bn;for(;;){if(qn===r)break t;if(fn===h&&++hn===A&&(et=Ne),fn===O&&++Dn===v&&(_t=Ne),(bn=qn.nextSibling)!==null)break;qn=fn,fn=qn.parentNode}qn=bn}h=et===-1||_t===-1?null:{start:et,end:_t}}else h=null}h=h||{start:0,end:0}}else h=null;for(u0={focusedElem:r,selectionRange:h},Iy=!1,Ui=o;Ui!==null;)if(o=Ui,r=o.child,(o.subtreeFlags&1028)!==0&&r!==null)r.return=o,Ui=r;else for(;Ui!==null;){switch(o=Ui,O=o.alternate,r=o.flags,o.tag){case 0:if((r&4)!==0&&(r=o.updateQueue,r=r!==null?r.events:null,r!==null))for(h=0;h<r.length;h++)A=r[h],A.ref.impl=A.nextImpl;break;case 11:case 15:break;case 1:if((r&1024)!==0&&O!==null){r=void 0,h=o,A=O.memoizedProps,O=O.memoizedState,v=h.stateNode;try{var Oa=rh(h.type,A);r=v.getSnapshotBeforeUpdate(Oa,O),v.__reactInternalSnapshotBeforeUpdate=r}catch(es){cr(h,h.return,es)}}break;case 3:if((r&1024)!==0){if(r=o.stateNode.containerInfo,h=r.nodeType,h===9)p0(r);else if(h===1)switch(r.nodeName){case"HEAD":case"HTML":case"BODY":p0(r);break;default:r.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((r&1024)!==0)throw Error(s(163))}if(r=o.sibling,r!==null){r.return=o.return,Ui=r;break}Ui=o.return}}function dN(r,o,h){var v=h.flags;switch(h.tag){case 0:case 11:case 15:od(r,h),v&4&&Yp(5,h);break;case 1:if(od(r,h),v&4)if(r=h.stateNode,o===null)try{r.componentDidMount()}catch(Ne){cr(h,h.return,Ne)}else{var A=rh(h.type,o.memoizedProps);o=o.memoizedState;try{r.componentDidUpdate(A,o,r.__reactInternalSnapshotBeforeUpdate)}catch(Ne){cr(h,h.return,Ne)}}v&64&&sN(h),v&512&&Qp(h,h.return);break;case 3:if(od(r,h),v&64&&(r=h.updateQueue,r!==null)){if(o=null,h.child!==null)switch(h.child.tag){case 27:case 5:o=h.child.stateNode;break;case 1:o=h.child.stateNode}try{ri(r,o)}catch(Ne){cr(h,h.return,Ne)}}break;case 27:o===null&&v&4&&cN(h);case 26:case 5:od(r,h),o===null&&v&4&&iN(h),v&512&&Qp(h,h.return);break;case 12:od(r,h);break;case 31:od(r,h),v&4&&mN(r,h);break;case 13:od(r,h),v&4&&pN(r,h),v&64&&(r=h.memoizedState,r!==null&&(r=r.dehydrated,r!==null&&(h=hP.bind(null,h),PP(r,h))));break;case 22:if(v=h.memoizedState!==null||rd,!v){o=o!==null&&o.memoizedState!==null||yi,A=rd;var O=yi;rd=v,(yi=o)&&!O?cd(r,h,(h.subtreeFlags&8772)!==0):od(r,h),rd=A,yi=O}break;case 30:break;default:od(r,h)}}function uN(r){var o=r.alternate;o!==null&&(r.alternate=null,uN(o)),r.child=null,r.deletions=null,r.sibling=null,r.tag===5&&(o=r.stateNode,o!==null&&xn(o)),r.stateNode=null,r.return=null,r.dependencies=null,r.memoizedProps=null,r.memoizedState=null,r.pendingProps=null,r.stateNode=null,r.updateQueue=null}var qr=null,Bo=!1;function id(r,o,h){for(h=h.child;h!==null;)hN(r,o,h),h=h.sibling}function hN(r,o,h){if(te&&typeof te.onCommitFiberUnmount=="function")try{te.onCommitFiberUnmount(xt,h)}catch{}switch(h.tag){case 26:yi||Dl(h,o),id(r,o,h),h.memoizedState?h.memoizedState.count--:h.stateNode&&(h=h.stateNode,h.parentNode.removeChild(h));break;case 27:yi||Dl(h,o);var v=qr,A=Bo;Xd(h.type)&&(qr=h.stateNode,Bo=!1),id(r,o,h),sf(h.stateNode),qr=v,Bo=A;break;case 5:yi||Dl(h,o);case 6:if(v=qr,A=Bo,qr=null,id(r,o,h),qr=v,Bo=A,qr!==null)if(Bo)try{(qr.nodeType===9?qr.body:qr.nodeName==="HTML"?qr.ownerDocument.body:qr).removeChild(h.stateNode)}catch(O){cr(h,o,O)}else try{qr.removeChild(h.stateNode)}catch(O){cr(h,o,O)}break;case 18:qr!==null&&(Bo?(r=qr,sS(r.nodeType===9?r.body:r.nodeName==="HTML"?r.ownerDocument.body:r,h.stateNode),Pm(r)):sS(qr,h.stateNode));break;case 4:v=qr,A=Bo,qr=h.stateNode.containerInfo,Bo=!0,id(r,o,h),qr=v,Bo=A;break;case 0:case 11:case 14:case 15:Hd(2,h,o),yi||Hd(4,h,o),id(r,o,h);break;case 1:yi||(Dl(h,o),v=h.stateNode,typeof v.componentWillUnmount=="function"&&rN(h,o,v)),id(r,o,h);break;case 21:id(r,o,h);break;case 22:yi=(v=yi)||h.memoizedState!==null,id(r,o,h),yi=v;break;default:id(r,o,h)}}function mN(r,o){if(o.memoizedState===null&&(r=o.alternate,r!==null&&(r=r.memoizedState,r!==null))){r=r.dehydrated;try{Pm(r)}catch(h){cr(o,o.return,h)}}}function pN(r,o){if(o.memoizedState===null&&(r=o.alternate,r!==null&&(r=r.memoizedState,r!==null&&(r=r.dehydrated,r!==null))))try{Pm(r)}catch(h){cr(o,o.return,h)}}function sP(r){switch(r.tag){case 31:case 13:case 19:var o=r.stateNode;return o===null&&(o=r.stateNode=new lN),o;case 22:return r=r.stateNode,o=r._retryCache,o===null&&(o=r._retryCache=new lN),o;default:throw Error(s(435,r.tag))}}function oy(r,o){var h=sP(r);o.forEach(function(v){if(!h.has(v)){h.add(v);var A=mP.bind(null,r,v);v.then(A,A)}})}function Fo(r,o){var h=o.deletions;if(h!==null)for(var v=0;v<h.length;v++){var A=h[v],O=r,Ne=o,et=Ne;e:for(;et!==null;){switch(et.tag){case 27:if(Xd(et.type)){qr=et.stateNode,Bo=!1;break e}break;case 5:qr=et.stateNode,Bo=!1;break e;case 3:case 4:qr=et.stateNode.containerInfo,Bo=!0;break e}et=et.return}if(qr===null)throw Error(s(160));hN(O,Ne,A),qr=null,Bo=!1,O=A.alternate,O!==null&&(O.return=null),A.return=null}if(o.subtreeFlags&13886)for(o=o.child;o!==null;)fN(o,r),o=o.sibling}var Xc=null;function fN(r,o){var h=r.alternate,v=r.flags;switch(r.tag){case 0:case 11:case 14:case 15:Fo(o,r),Uo(r),v&4&&(Hd(3,r,r.return),Yp(3,r),Hd(5,r,r.return));break;case 1:Fo(o,r),Uo(r),v&512&&(yi||h===null||Dl(h,h.return)),v&64&&rd&&(r=r.updateQueue,r!==null&&(v=r.callbacks,v!==null&&(h=r.shared.hiddenCallbacks,r.shared.hiddenCallbacks=h===null?v:h.concat(v))));break;case 26:var A=Xc;if(Fo(o,r),Uo(r),v&512&&(yi||h===null||Dl(h,h.return)),v&4){var O=h!==null?h.memoizedState:null;if(v=r.memoizedState,h===null)if(v===null)if(r.stateNode===null){e:{v=r.type,h=r.memoizedProps,A=A.ownerDocument||A;t:switch(v){case"title":O=A.getElementsByTagName("title")[0],(!O||O[Rt]||O[$t]||O.namespaceURI==="http://www.w3.org/2000/svg"||O.hasAttribute("itemprop"))&&(O=A.createElement(v),A.head.insertBefore(O,A.querySelector("head > title"))),Ji(O,v,h),O[$t]=r,In(O),v=O;break e;case"link":var Ne=fS("link","href",A).get(v+(h.href||""));if(Ne){for(var et=0;et<Ne.length;et++)if(O=Ne[et],O.getAttribute("href")===(h.href==null||h.href===""?null:h.href)&&O.getAttribute("rel")===(h.rel==null?null:h.rel)&&O.getAttribute("title")===(h.title==null?null:h.title)&&O.getAttribute("crossorigin")===(h.crossOrigin==null?null:h.crossOrigin)){Ne.splice(et,1);break t}}O=A.createElement(v),Ji(O,v,h),A.head.appendChild(O);break;case"meta":if(Ne=fS("meta","content",A).get(v+(h.content||""))){for(et=0;et<Ne.length;et++)if(O=Ne[et],O.getAttribute("content")===(h.content==null?null:""+h.content)&&O.getAttribute("name")===(h.name==null?null:h.name)&&O.getAttribute("property")===(h.property==null?null:h.property)&&O.getAttribute("http-equiv")===(h.httpEquiv==null?null:h.httpEquiv)&&O.getAttribute("charset")===(h.charSet==null?null:h.charSet)){Ne.splice(et,1);break t}}O=A.createElement(v),Ji(O,v,h),A.head.appendChild(O);break;default:throw Error(s(468,v))}O[$t]=r,In(O),v=O}r.stateNode=v}else gS(A,r.type,r.stateNode);else r.stateNode=pS(A,v,r.memoizedProps);else O!==v?(O===null?h.stateNode!==null&&(h=h.stateNode,h.parentNode.removeChild(h)):O.count--,v===null?gS(A,r.type,r.stateNode):pS(A,v,r.memoizedProps)):v===null&&r.stateNode!==null&&Fx(r,r.memoizedProps,h.memoizedProps)}break;case 27:Fo(o,r),Uo(r),v&512&&(yi||h===null||Dl(h,h.return)),h!==null&&v&4&&Fx(r,r.memoizedProps,h.memoizedProps);break;case 5:if(Fo(o,r),Uo(r),v&512&&(yi||h===null||Dl(h,h.return)),r.flags&32){A=r.stateNode;try{na(A,"")}catch(Oa){cr(r,r.return,Oa)}}v&4&&r.stateNode!=null&&(A=r.memoizedProps,Fx(r,A,h!==null?h.memoizedProps:A)),v&1024&&(qx=!0);break;case 6:if(Fo(o,r),Uo(r),v&4){if(r.stateNode===null)throw Error(s(162));v=r.memoizedProps,h=r.stateNode;try{h.nodeValue=v}catch(Oa){cr(r,r.return,Oa)}}break;case 3:if(Ny=null,A=Xc,Xc=jy(o.containerInfo),Fo(o,r),Xc=A,Uo(r),v&4&&h!==null&&h.memoizedState.isDehydrated)try{Pm(o.containerInfo)}catch(Oa){cr(r,r.return,Oa)}qx&&(qx=!1,gN(r));break;case 4:v=Xc,Xc=jy(r.stateNode.containerInfo),Fo(o,r),Uo(r),Xc=v;break;case 12:Fo(o,r),Uo(r);break;case 31:Fo(o,r),Uo(r),v&4&&(v=r.updateQueue,v!==null&&(r.updateQueue=null,oy(r,v)));break;case 13:Fo(o,r),Uo(r),r.child.flags&8192&&r.memoizedState!==null!=(h!==null&&h.memoizedState!==null)&&(ly=ct()),v&4&&(v=r.updateQueue,v!==null&&(r.updateQueue=null,oy(r,v)));break;case 22:A=r.memoizedState!==null;var _t=h!==null&&h.memoizedState!==null,hn=rd,Dn=yi;if(rd=hn||A,yi=Dn||_t,Fo(o,r),yi=Dn,rd=hn,Uo(r),v&8192)e:for(o=r.stateNode,o._visibility=A?o._visibility&-2:o._visibility|1,A&&(h===null||_t||rd||yi||ih(r)),h=null,o=r;;){if(o.tag===5||o.tag===26){if(h===null){_t=h=o;try{if(O=_t.stateNode,A)Ne=O.style,typeof Ne.setProperty=="function"?Ne.setProperty("display","none","important"):Ne.display="none";else{et=_t.stateNode;var qn=_t.memoizedProps.style,fn=qn!=null&&qn.hasOwnProperty("display")?qn.display:null;et.style.display=fn==null||typeof fn=="boolean"?"":(""+fn).trim()}}catch(Oa){cr(_t,_t.return,Oa)}}}else if(o.tag===6){if(h===null){_t=o;try{_t.stateNode.nodeValue=A?"":_t.memoizedProps}catch(Oa){cr(_t,_t.return,Oa)}}}else if(o.tag===18){if(h===null){_t=o;try{var bn=_t.stateNode;A?rS(bn,!0):rS(_t.stateNode,!1)}catch(Oa){cr(_t,_t.return,Oa)}}}else if((o.tag!==22&&o.tag!==23||o.memoizedState===null||o===r)&&o.child!==null){o.child.return=o,o=o.child;continue}if(o===r)break e;for(;o.sibling===null;){if(o.return===null||o.return===r)break e;h===o&&(h=null),o=o.return}h===o&&(h=null),o.sibling.return=o.return,o=o.sibling}v&4&&(v=r.updateQueue,v!==null&&(h=v.retryQueue,h!==null&&(v.retryQueue=null,oy(r,h))));break;case 19:Fo(o,r),Uo(r),v&4&&(v=r.updateQueue,v!==null&&(r.updateQueue=null,oy(r,v)));break;case 30:break;case 21:break;default:Fo(o,r),Uo(r)}}function Uo(r){var o=r.flags;if(o&2){try{for(var h,v=r.return;v!==null;){if(oN(v)){h=v;break}v=v.return}if(h==null)throw Error(s(160));switch(h.tag){case 27:var A=h.stateNode,O=Ux(r);iy(r,O,A);break;case 5:var Ne=h.stateNode;h.flags&32&&(na(Ne,""),h.flags&=-33);var et=Ux(r);iy(r,et,Ne);break;case 3:case 4:var _t=h.stateNode.containerInfo,hn=Ux(r);zx(r,hn,_t);break;default:throw Error(s(161))}}catch(Dn){cr(r,r.return,Dn)}r.flags&=-3}o&4096&&(r.flags&=-4097)}function gN(r){if(r.subtreeFlags&1024)for(r=r.child;r!==null;){var o=r;gN(o),o.tag===5&&o.flags&1024&&o.stateNode.reset(),r=r.sibling}}function od(r,o){if(o.subtreeFlags&8772)for(o=o.child;o!==null;)dN(r,o.alternate,o),o=o.sibling}function ih(r){for(r=r.child;r!==null;){var o=r;switch(o.tag){case 0:case 11:case 14:case 15:Hd(4,o,o.return),ih(o);break;case 1:Dl(o,o.return);var h=o.stateNode;typeof h.componentWillUnmount=="function"&&rN(o,o.return,h),ih(o);break;case 27:sf(o.stateNode);case 26:case 5:Dl(o,o.return),ih(o);break;case 22:o.memoizedState===null&&ih(o);break;case 30:ih(o);break;default:ih(o)}r=r.sibling}}function cd(r,o,h){for(h=h&&(o.subtreeFlags&8772)!==0,o=o.child;o!==null;){var v=o.alternate,A=r,O=o,Ne=O.flags;switch(O.tag){case 0:case 11:case 15:cd(A,O,h),Yp(4,O);break;case 1:if(cd(A,O,h),v=O,A=v.stateNode,typeof A.componentDidMount=="function")try{A.componentDidMount()}catch(hn){cr(v,v.return,hn)}if(v=O,A=v.updateQueue,A!==null){var et=v.stateNode;try{var _t=A.shared.hiddenCallbacks;if(_t!==null)for(A.shared.hiddenCallbacks=null,A=0;A<_t.length;A++)so(_t[A],et)}catch(hn){cr(v,v.return,hn)}}h&&Ne&64&&sN(O),Qp(O,O.return);break;case 27:cN(O);case 26:case 5:cd(A,O,h),h&&v===null&&Ne&4&&iN(O),Qp(O,O.return);break;case 12:cd(A,O,h);break;case 31:cd(A,O,h),h&&Ne&4&&mN(A,O);break;case 13:cd(A,O,h),h&&Ne&4&&pN(A,O);break;case 22:O.memoizedState===null&&cd(A,O,h),Qp(O,O.return);break;case 30:break;default:cd(A,O,h)}o=o.sibling}}function Vx(r,o){var h=null;r!==null&&r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(h=r.memoizedState.cachePool.pool),r=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(r=o.memoizedState.cachePool.pool),r!==h&&(r!=null&&r.refCount++,h!=null&&eh(h))}function Hx(r,o){r=null,o.alternate!==null&&(r=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==r&&(o.refCount++,r!=null&&eh(r))}function Zc(r,o,h,v){if(o.subtreeFlags&10256)for(o=o.child;o!==null;)yN(r,o,h,v),o=o.sibling}function yN(r,o,h,v){var A=o.flags;switch(o.tag){case 0:case 11:case 15:Zc(r,o,h,v),A&2048&&Yp(9,o);break;case 1:Zc(r,o,h,v);break;case 3:Zc(r,o,h,v),A&2048&&(r=null,o.alternate!==null&&(r=o.alternate.memoizedState.cache),o=o.memoizedState.cache,o!==r&&(o.refCount++,r!=null&&eh(r)));break;case 12:if(A&2048){Zc(r,o,h,v),r=o.stateNode;try{var O=o.memoizedProps,Ne=O.id,et=O.onPostCommit;typeof et=="function"&&et(Ne,o.alternate===null?"mount":"update",r.passiveEffectDuration,-0)}catch(_t){cr(o,o.return,_t)}}else Zc(r,o,h,v);break;case 31:Zc(r,o,h,v);break;case 13:Zc(r,o,h,v);break;case 23:break;case 22:O=o.stateNode,Ne=o.alternate,o.memoizedState!==null?O._visibility&2?Zc(r,o,h,v):Jp(r,o):O._visibility&2?Zc(r,o,h,v):(O._visibility|=2,jm(r,o,h,v,(o.subtreeFlags&10256)!==0||!1)),A&2048&&Vx(Ne,o);break;case 24:Zc(r,o,h,v),A&2048&&Hx(o.alternate,o);break;default:Zc(r,o,h,v)}}function jm(r,o,h,v,A){for(A=A&&((o.subtreeFlags&10256)!==0||!1),o=o.child;o!==null;){var O=r,Ne=o,et=h,_t=v,hn=Ne.flags;switch(Ne.tag){case 0:case 11:case 15:jm(O,Ne,et,_t,A),Yp(8,Ne);break;case 23:break;case 22:var Dn=Ne.stateNode;Ne.memoizedState!==null?Dn._visibility&2?jm(O,Ne,et,_t,A):Jp(O,Ne):(Dn._visibility|=2,jm(O,Ne,et,_t,A)),A&&hn&2048&&Vx(Ne.alternate,Ne);break;case 24:jm(O,Ne,et,_t,A),A&&hn&2048&&Hx(Ne.alternate,Ne);break;default:jm(O,Ne,et,_t,A)}o=o.sibling}}function Jp(r,o){if(o.subtreeFlags&10256)for(o=o.child;o!==null;){var h=r,v=o,A=v.flags;switch(v.tag){case 22:Jp(h,v),A&2048&&Vx(v.alternate,v);break;case 24:Jp(h,v),A&2048&&Hx(v.alternate,v);break;default:Jp(h,v)}o=o.sibling}}var Kp=8192;function wm(r,o,h){if(r.subtreeFlags&Kp)for(r=r.child;r!==null;)vN(r,o,h),r=r.sibling}function vN(r,o,h){switch(r.tag){case 26:wm(r,o,h),r.flags&Kp&&r.memoizedState!==null&&VP(h,Xc,r.memoizedState,r.memoizedProps);break;case 5:wm(r,o,h);break;case 3:case 4:var v=Xc;Xc=jy(r.stateNode.containerInfo),wm(r,o,h),Xc=v;break;case 22:r.memoizedState===null&&(v=r.alternate,v!==null&&v.memoizedState!==null?(v=Kp,Kp=16777216,wm(r,o,h),Kp=v):wm(r,o,h));break;default:wm(r,o,h)}}function bN(r){var o=r.alternate;if(o!==null&&(r=o.child,r!==null)){o.child=null;do o=r.sibling,r.sibling=null,r=o;while(r!==null)}}function Xp(r){var o=r.deletions;if((r.flags&16)!==0){if(o!==null)for(var h=0;h<o.length;h++){var v=o[h];Ui=v,jN(v,r)}bN(r)}if(r.subtreeFlags&10256)for(r=r.child;r!==null;)xN(r),r=r.sibling}function xN(r){switch(r.tag){case 0:case 11:case 15:Xp(r),r.flags&2048&&Hd(9,r,r.return);break;case 3:Xp(r);break;case 12:Xp(r);break;case 22:var o=r.stateNode;r.memoizedState!==null&&o._visibility&2&&(r.return===null||r.return.tag!==13)?(o._visibility&=-3,cy(r)):Xp(r);break;default:Xp(r)}}function cy(r){var o=r.deletions;if((r.flags&16)!==0){if(o!==null)for(var h=0;h<o.length;h++){var v=o[h];Ui=v,jN(v,r)}bN(r)}for(r=r.child;r!==null;){switch(o=r,o.tag){case 0:case 11:case 15:Hd(8,o,o.return),cy(o);break;case 22:h=o.stateNode,h._visibility&2&&(h._visibility&=-3,cy(o));break;default:cy(o)}r=r.sibling}}function jN(r,o){for(;Ui!==null;){var h=Ui;switch(h.tag){case 0:case 11:case 15:Hd(8,h,o);break;case 23:case 22:if(h.memoizedState!==null&&h.memoizedState.cachePool!==null){var v=h.memoizedState.cachePool.pool;v!=null&&v.refCount++}break;case 24:eh(h.memoizedState.cache)}if(v=h.child,v!==null)v.return=h,Ui=v;else e:for(h=r;Ui!==null;){v=Ui;var A=v.sibling,O=v.return;if(uN(v),v===h){Ui=null;break e}if(A!==null){A.return=O,Ui=A;break e}Ui=O}}}var rP={getCacheForType:function(r){var o=Ai(Gr),h=o.data.get(r);return h===void 0&&(h=r(),o.data.set(r,h)),h},cacheSignal:function(){return Ai(Gr).controller.signal}},iP=typeof WeakMap=="function"?WeakMap:Map,Xs=0,Cr=null,Is=null,Rs=0,or=0,ac=null,Wd=!1,Nm=!1,Wx=!1,ld=0,ei=0,Gd=0,oh=0,Gx=0,sc=0,Sm=0,Zp=null,zo=null,Yx=!1,ly=0,wN=0,dy=1/0,uy=null,Yd=null,_i=0,Qd=null,Cm=null,dd=0,Qx=0,Jx=null,NN=null,ef=0,Kx=null;function rc(){return(Xs&2)!==0&&Rs!==0?Rs&-Rs:q.T!==null?a0():Xt()}function SN(){if(sc===0)if((Rs&536870912)===0||Cs){var r=jt;jt<<=1,(jt&3932160)===0&&(jt=262144),sc=r}else sc=536870912;return r=Yr.current,r!==null&&(r.flags|=32),sc}function qo(r,o,h){(r===Cr&&(or===2||or===9)||r.cancelPendingCommit!==null)&&(Am(r,0),Jd(r,Rs,sc,!1)),we(r,h),((Xs&2)===0||r!==Cr)&&(r===Cr&&((Xs&2)===0&&(oh|=h),ei===4&&Jd(r,Rs,sc,!1)),El(r))}function CN(r,o,h){if((Xs&6)!==0)throw Error(s(327));var v=!h&&(o&127)===0&&(o&r.expiredLanes)===0||xe(r,o),A=v?lP(r,o):Zx(r,o,!0),O=v;do{if(A===0){Nm&&!v&&Jd(r,o,0,!1);break}else{if(h=r.current.alternate,O&&!oP(h)){A=Zx(r,o,!1),O=!1;continue}if(A===2){if(O=o,r.errorRecoveryDisabledLanes&O)var Ne=0;else Ne=r.pendingLanes&-536870913,Ne=Ne!==0?Ne:Ne&536870912?536870912:0;if(Ne!==0){o=Ne;e:{var et=r;A=Zp;var _t=et.current.memoizedState.isDehydrated;if(_t&&(Am(et,Ne).flags|=256),Ne=Zx(et,Ne,!1),Ne!==2){if(Wx&&!_t){et.errorRecoveryDisabledLanes|=O,oh|=O,A=4;break e}O=zo,zo=A,O!==null&&(zo===null?zo=O:zo.push.apply(zo,O))}A=Ne}if(O=!1,A!==2)continue}}if(A===1){Am(r,0),Jd(r,o,0,!0);break}e:{switch(v=r,O=A,O){case 0:case 1:throw Error(s(345));case 4:if((o&4194048)!==o)break;case 6:Jd(v,o,sc,!Wd);break e;case 2:zo=null;break;case 3:case 5:break;default:throw Error(s(329))}if((o&62914560)===o&&(A=ly+300-ct(),10<A)){if(Jd(v,o,sc,!Wd),B(v,0,!0)!==0)break e;
vendor: 20,723 bytes, line 48
48dd=o,v.timeoutHandle=nS(AN.bind(null,v,h,zo,uy,Yx,o,sc,oh,Sm,Wd,O,"Throttled",-0,0),A);break e}AN(v,h,zo,uy,Yx,o,sc,oh,Sm,Wd,O,null,-0,0)}}break}while(!0);El(r)}function AN(r,o,h,v,A,O,Ne,et,_t,hn,Dn,qn,fn,bn){if(r.timeoutHandle=-1,qn=o.subtreeFlags,qn&8192||(qn&16785408)===16785408){qn={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Ma},vN(o,O,qn);var Oa=(O&62914560)===O?ly-ct():(O&4194048)===O?wN-ct():0;if(Oa=HP(qn,Oa),Oa!==null){dd=O,r.cancelPendingCommit=Oa(TN.bind(null,r,o,O,h,v,A,Ne,et,_t,Dn,qn,null,fn,bn)),Jd(r,O,Ne,!hn);return}}TN(r,o,O,h,v,A,Ne,et,_t)}function oP(r){for(var o=r;;){var h=o.tag;if((h===0||h===11||h===15)&&o.flags&16384&&(h=o.updateQueue,h!==null&&(h=h.stores,h!==null)))for(var v=0;v<h.length;v++){var A=h[v],O=A.getSnapshot;A=A.value;try{if(!S(O(),A))return!1}catch{return!1}}if(h=o.child,o.subtreeFlags&16384&&h!==null)h.return=o,o=h;else{if(o===r)break;for(;o.sibling===null;){if(o.return===null||o.return===r)return!0;o=o.return}o.sibling.return=o.return,o=o.sibling}}return!0}function Jd(r,o,h,v){o&=~Gx,o&=~oh,r.suspendedLanes|=o,r.pingedLanes&=~o,v&&(r.warmLanes|=o),v=r.expirationTimes;for(var A=o;0<A;){var O=31-pt(A),Ne=1<<O;v[O]=-1,A&=~Ne}h!==0&&St(r,h,o)}function hy(){return(Xs&6)===0?(tf(0),!1):!0}function Xx(){if(Is!==null){if(or===0)var r=Is.return;else r=Is,jc=wl=null,pm(r),Tn=null,Aa=0,r=Is;for(;r!==null;)aN(r.alternate,r),r=r.return;Is=null}}function Am(r,o){var h=r.timeoutHandle;h!==-1&&(r.timeoutHandle=-1,IP(h)),h=r.cancelPendingCommit,h!==null&&(r.cancelPendingCommit=null,h()),dd=0,Xx(),Cr=r,Is=h=Eo(r.current,null),Rs=o,or=0,ac=null,Wd=!1,Nm=xe(r,o),Wx=!1,Sm=sc=Gx=oh=Gd=ei=0,zo=Zp=null,Yx=!1,(o&8)!==0&&(o|=o&32);var v=r.entangledLanes;if(v!==0)for(r=r.entanglements,v&=o;0<v;){var A=31-pt(v),O=1<<A;o|=r[A],v&=~O}return ld=o,xc(),h}function IN(r,o){os=null,q.H=Hp,o===Tt||o===cn?(o=$n(),or=3):o===ln?(o=$n(),or=4):or=o===Dx?8:o!==null&&typeof o=="object"&&typeof o.then=="function"?6:1,ac=o,Is===null&&(ei=1,ty(r,Po(o,r.current)))}function _N(){var r=Yr.current;return r===null?!0:(Rs&4194048)===Rs?pi===null:(Rs&62914560)===Rs||(Rs&536870912)!==0?r===pi:!1}function kN(){var r=q.H;return q.H=Hp,r===null?Hp:r}function DN(){var r=q.A;return q.A=rP,r}function my(){ei=4,Wd||(Rs&4194048)!==Rs&&Yr.current!==null||(Nm=!0),(Gd&134217727)===0&&(oh&134217727)===0||Cr===null||Jd(Cr,Rs,sc,!1)}function Zx(r,o,h){var v=Xs;Xs|=2;var A=kN(),O=DN();(Cr!==r||Rs!==o)&&(uy=null,Am(r,o)),o=!1;var Ne=ei;e:do try{if(or!==0&&Is!==null){var et=Is,_t=ac;switch(or){case 8:Xx(),Ne=6;break e;case 3:case 2:case 9:case 6:Yr.current===null&&(o=!0);var hn=or;if(or=0,ac=null,Im(r,et,_t,hn),h&&Nm){Ne=0;break e}break;default:hn=or,or=0,ac=null,Im(r,et,_t,hn)}}cP(),Ne=ei;break}catch(Dn){IN(r,Dn)}while(!0);return o&&r.shellSuspendCounter++,jc=wl=null,Xs=v,q.H=A,q.A=O,Is===null&&(Cr=null,Rs=0,xc()),Ne}function cP(){for(;Is!==null;)EN(Is)}function lP(r,o){var h=Xs;Xs|=2;var v=kN(),A=DN();Cr!==r||Rs!==o?(uy=null,dy=ct()+500,Am(r,o)):Nm=xe(r,o);e:do try{if(or!==0&&Is!==null){o=Is;var O=ac;t:switch(or){case 1:or=0,ac=null,Im(r,o,O,1);break;case 2:case 9:if(Un(O)){or=0,ac=null,PN(o);break}o=function(){or!==2&&or!==9||Cr!==r||(or=7),El(r)},O.then(o,o);break e;case 3:or=7;break e;case 4:or=5;break e;case 7:Un(O)?(or=0,ac=null,PN(o)):(or=0,ac=null,Im(r,o,O,7));break;case 5:var Ne=null;switch(Is.tag){case 26:Ne=Is.memoizedState;case 5:case 27:var et=Is;if(Ne?yS(Ne):et.stateNode.complete){or=0,ac=null;var _t=et.sibling;if(_t!==null)Is=_t;else{var hn=et.return;hn!==null?(Is=hn,py(hn)):Is=null}break t}}or=0,ac=null,Im(r,o,O,5);break;case 6:or=0,ac=null,Im(r,o,O,6);break;case 8:Xx(),ei=6;break e;default:throw Error(s(462))}}dP();break}catch(Dn){IN(r,Dn)}while(!0);return jc=wl=null,q.H=v,q.A=A,Xs=h,Is!==null?0:(Cr=null,Rs=0,xc(),ei)}function dP(){for(;Is!==null&&!ot();)EN(Is)}function EN(r){var o=tN(r.alternate,r,ld);r.memoizedProps=r.pendingProps,o===null?py(r):Is=o}function PN(r){var o=r,h=o.alternate;switch(o.tag){case 15:case 0:o=Q2(h,o,o.pendingProps,o.type,void 0,Rs);break;case 11:o=Q2(h,o,o.pendingProps,o.type.render,o.ref,Rs);break;case 5:pm(o);default:aN(h,o),o=Is=Ku(o,ld),o=tN(h,o,ld)}r.memoizedProps=r.pendingProps,o===null?py(r):Is=o}function Im(r,o,h,v){jc=wl=null,pm(o),Tn=null,Aa=0;var A=o.return;try{if(XE(r,A,o,h,Rs)){ei=1,ty(r,Po(h,r.current)),Is=null;return}}catch(O){if(A!==null)throw Is=A,O;ei=1,ty(r,Po(h,r.current)),Is=null;return}o.flags&32768?(Cs||v===1?r=!0:Nm||(Rs&536870912)!==0?r=!1:(Wd=r=!0,(v===2||v===9||v===3||v===6)&&(v=Yr.current,v!==null&&v.tag===13&&(v.flags|=16384))),RN(o,r)):py(o)}function py(r){var o=r;do{if((o.flags&32768)!==0){RN(o,Wd);return}r=o.return;var h=tP(o.alternate,o,ld);if(h!==null){Is=h;return}if(o=o.sibling,o!==null){Is=o;return}Is=o=r}while(o!==null);ei===0&&(ei=5)}function RN(r,o){do{var h=nP(r.alternate,r);if(h!==null){h.flags&=32767,Is=h;return}if(h=r.return,h!==null&&(h.flags|=32768,h.subtreeFlags=0,h.deletions=null),!o&&(r=r.sibling,r!==null)){Is=r;return}Is=r=h}while(r!==null);ei=6,Is=null}function TN(r,o,h,v,A,O,Ne,et,_t){r.cancelPendingCommit=null;do fy();while(_i!==0);if((Xs&6)!==0)throw Error(s(327));if(o!==null){if(o===r.current)throw Error(s(177));if(O=o.lanes|o.childLanes,O|=ao,rt(r,h,O,Ne,et,_t),r===Cr&&(Is=Cr=null,Rs=0),Cm=o,Qd=r,dd=h,Qx=O,Jx=A,NN=v,(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?(r.callbackNode=null,r.callbackPriority=0,pP(ce,function(){return BN(),null})):(r.callbackNode=null,r.callbackPriority=0),v=(o.flags&13878)!==0,(o.subtreeFlags&13878)!==0||v){v=q.T,q.T=null,A=ne.p,ne.p=2,Ne=Xs,Xs|=4;try{aP(r,o,h)}finally{Xs=Ne,ne.p=A,q.T=v}}_i=1,MN(),$N(),ON()}}function MN(){if(_i===1){_i=0;var r=Qd,o=Cm,h=(o.flags&13878)!==0;if((o.subtreeFlags&13878)!==0||h){h=q.T,q.T=null;var v=ne.p;ne.p=2;var A=Xs;Xs|=4;try{fN(o,r);var O=u0,Ne=Ft(r.containerInfo),et=O.focusedElem,_t=O.selectionRange;if(Ne!==et&&et&&et.ownerDocument&&Ot(et.ownerDocument.documentElement,et)){if(_t!==null&&rn(et)){var hn=_t.start,Dn=_t.end;if(Dn===void 0&&(Dn=hn),"selectionStart"in et)et.selectionStart=hn,et.selectionEnd=Math.min(Dn,et.value.length);else{var qn=et.ownerDocument||document,fn=qn&&qn.defaultView||window;if(fn.getSelection){var bn=fn.getSelection(),Oa=et.textContent.length,es=Math.min(_t.start,Oa),yr=_t.end===void 0?es:Math.min(_t.end,Oa);!bn.extend&&es>yr&&(Ne=yr,yr=es,es=Ne);var nn=lt(et,es),Lt=lt(et,yr);if(nn&&Lt&&(bn.rangeCount!==1||bn.anchorNode!==nn.node||bn.anchorOffset!==nn.offset||bn.focusNode!==Lt.node||bn.focusOffset!==Lt.offset)){var un=qn.createRange();un.setStart(nn.node,nn.offset),bn.removeAllRanges(),es>yr?(bn.addRange(un),bn.extend(Lt.node,Lt.offset)):(un.setEnd(Lt.node,Lt.offset),bn.addRange(un))}}}}for(qn=[],bn=et;bn=bn.parentNode;)bn.nodeType===1&&qn.push({element:bn,left:bn.scrollLeft,top:bn.scrollTop});for(typeof et.focus=="function"&&et.focus(),et=0;et<qn.length;et++){var On=qn[et];On.element.scrollLeft=On.left,On.element.scrollTop=On.top}}Iy=!!d0,u0=d0=null}finally{Xs=A,ne.p=v,q.T=h}}r.current=o,_i=2}}function $N(){if(_i===2){_i=0;var r=Qd,o=Cm,h=(o.flags&8772)!==0;if((o.subtreeFlags&8772)!==0||h){h=q.T,q.T=null;var v=ne.p;ne.p=2;var A=Xs;Xs|=4;try{dN(r,o.alternate,o)}finally{Xs=A,ne.p=v,q.T=h}}_i=3}}function ON(){if(_i===4||_i===3){_i=0,wt();var r=Qd,o=Cm,h=dd,v=NN;(o.subtreeFlags&10256)!==0||(o.flags&10256)!==0?_i=5:(_i=0,Cm=Qd=null,LN(r,r.pendingLanes));var A=r.pendingLanes;if(A===0&&(Yd=null),Sn(h),o=o.stateNode,te&&typeof te.onCommitFiberRoot=="function")try{te.onCommitFiberRoot(xt,o,void 0,(o.current.flags&128)===128)}catch{}if(v!==null){o=q.T,A=ne.p,ne.p=2,q.T=null;try{for(var O=r.onRecoverableError,Ne=0;Ne<v.length;Ne++){var et=v[Ne];O(et.value,{componentStack:et.stack})}}finally{q.T=o,ne.p=A}}(dd&3)!==0&&fy(),El(r),A=r.pendingLanes,(h&261930)!==0&&(A&42)!==0?r===Kx?ef++:(ef=0,Kx=r):ef=0,tf(0)}}function LN(r,o){(r.pooledCacheLanes&=o)===0&&(o=r.pooledCache,o!=null&&(r.pooledCache=null,eh(o)))}function fy(){return MN(),$N(),ON(),BN()}function BN(){if(_i!==5)return!1;var r=Qd,o=Qx;Qx=0;var h=Sn(dd),v=q.T,A=ne.p;try{ne.p=32>h?32:h,q.T=null,h=Jx,Jx=null;var O=Qd,Ne=dd;if(_i=0,Cm=Qd=null,dd=0,(Xs&6)!==0)throw Error(s(331));var et=Xs;if(Xs|=4,xN(O.current),yN(O,O.current,Ne,h),Xs=et,tf(0,!1),te&&typeof te.onPostCommitFiberRoot=="function")try{te.onPostCommitFiberRoot(xt,O)}catch{}return!0}finally{ne.p=A,q.T=v,LN(r,o)}}function FN(r,o,h){o=Po(h,o),o=kx(r.stateNode,o,2),r=ir(r,o,2),r!==null&&(we(r,2),El(r))}function cr(r,o,h){if(r.tag===3)FN(r,r,h);else for(;o!==null;){if(o.tag===3){FN(o,r,h);break}else if(o.tag===1){var v=o.stateNode;if(typeof o.type.getDerivedStateFromError=="function"||typeof v.componentDidCatch=="function"&&(Yd===null||!Yd.has(v))){r=Po(h,r),h=U2(2),v=ir(o,h,2),v!==null&&(z2(h,v,o,r),we(v,2),El(v));break}}o=o.return}}function e0(r,o,h){var v=r.pingCache;if(v===null){v=r.pingCache=new iP;var A=new Set;v.set(o,A)}else A=v.get(o),A===void 0&&(A=new Set,v.set(o,A));A.has(h)||(Wx=!0,A.add(h),r=uP.bind(null,r,o,h),o.then(r,r))}function uP(r,o,h){var v=r.pingCache;v!==null&&v.delete(o),r.pingedLanes|=r.suspendedLanes&h,r.warmLanes&=~h,Cr===r&&(Rs&h)===h&&(ei===4||ei===3&&(Rs&62914560)===Rs&&300>ct()-ly?(Xs&2)===0&&Am(r,0):Gx|=h,Sm===Rs&&(Sm=0)),El(r)}function UN(r,o){o===0&&(o=ht()),r=Hc(r,o),r!==null&&(we(r,o),El(r))}function hP(r){var o=r.memoizedState,h=0;o!==null&&(h=o.retryLane),UN(r,h)}function mP(r,o){var h=0;switch(r.tag){case 31:case 13:var v=r.stateNode,A=r.memoizedState;A!==null&&(h=A.retryLane);break;case 19:v=r.stateNode;break;case 22:v=r.stateNode._retryCache;break;default:throw Error(s(314))}v!==null&&v.delete(o),UN(r,h)}function pP(r,o){return Se(r,o)}var gy=null,_m=null,t0=!1,yy=!1,n0=!1,Kd=0;function El(r){r!==_m&&r.next===null&&(_m===null?gy=_m=r:_m=_m.next=r),yy=!0,t0||(t0=!0,gP())}function tf(r,o){if(!n0&&yy){n0=!0;do for(var h=!1,v=gy;v!==null;){if(r!==0){var A=v.pendingLanes;if(A===0)var O=0;else{var Ne=v.suspendedLanes,et=v.pingedLanes;O=(1<<31-pt(42|r)+1)-1,O&=A&~(Ne&~et),O=O&201326741?O&201326741|1:O?O|2:0}O!==0&&(h=!0,HN(v,O))}else O=Rs,O=B(v,v===Cr?O:0,v.cancelPendingCommit!==null||v.timeoutHandle!==-1),(O&3)===0||xe(v,O)||(h=!0,HN(v,O));v=v.next}while(h);n0=!1}}function fP(){zN()}function zN(){yy=t0=!1;var r=0;Kd!==0&&AP()&&(r=Kd);for(var o=ct(),h=null,v=gy;v!==null;){var A=v.next,O=qN(v,o);O===0?(v.next=null,h===null?gy=A:h.next=A,A===null&&(_m=h)):(h=v,(r!==0||(O&3)!==0)&&(yy=!0)),v=A}_i!==0&&_i!==5||tf(r),Kd!==0&&(Kd=0)}function qN(r,o){for(var h=r.suspendedLanes,v=r.pingedLanes,A=r.expirationTimes,O=r.pendingLanes&-62914561;0<O;){var Ne=31-pt(O),et=1<<Ne,_t=A[Ne];_t===-1?((et&h)===0||(et&v)!==0)&&(A[Ne]=tt(et,o)):_t<=o&&(r.expiredLanes|=et),O&=~et}if(o=Cr,h=Rs,h=B(r,r===o?h:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),v=r.callbackNode,h===0||r===o&&(or===2||or===9)||r.cancelPendingCommit!==null)return v!==null&&v!==null&&Me(v),r.callbackNode=null,r.callbackPriority=0;if((h&3)===0||xe(r,h)){if(o=h&-h,o===r.callbackPriority)return o;switch(v!==null&&Me(v),Sn(h)){case 2:case 8:h=Te;break;case 32:h=ce;break;case 268435456:h=Je;break;default:h=ce}return v=VN.bind(null,r),h=Se(h,v),r.callbackPriority=o,r.callbackNode=h,o}return v!==null&&v!==null&&Me(v),r.callbackPriority=2,r.callbackNode=null,2}function VN(r,o){if(_i!==0&&_i!==5)return r.callbackNode=null,r.callbackPriority=0,null;var h=r.callbackNode;if(fy()&&r.callbackNode!==h)return null;var v=Rs;return v=B(r,r===Cr?v:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),v===0?null:(CN(r,v,o),qN(r,ct()),r.callbackNode!=null&&r.callbackNode===h?VN.bind(null,r):null)}function HN(r,o){if(fy())return null;CN(r,o,!0)}function gP(){_P(function(){(Xs&6)!==0?Se(De,fP):zN()})}function a0(){if(Kd===0){var r=j;r===0&&(r=be,be<<=1,(be&261888)===0&&(be=256)),Kd=r}return Kd}function WN(r){return r==null||typeof r=="symbol"||typeof r=="boolean"?null:typeof r=="function"?r:ua(""+r)}function GN(r,o){var h=o.ownerDocument.createElement("input");return h.name=o.name,h.value=o.value,r.id&&h.setAttribute("form",r.id),o.parentNode.insertBefore(h,o),r=new FormData(r),h.parentNode.removeChild(h),r}function yP(r,o,h,v,A){if(o==="submit"&&h&&h.stateNode===A){var O=WN((A[Vt]||null).action),Ne=v.submitter;Ne&&(o=(o=Ne[Vt]||null)?WN(o.formAction):Ne.getAttribute("formAction"),o!==null&&(O=o,Ne=null));var et=new Qo("action","action",null,v,A);r.push({event:et,listeners:[{instance:null,listener:function(){if(v.defaultPrevented){if(Kd!==0){var _t=Ne?GN(A,Ne):new FormData(A);Nx(h,{pending:!0,data:_t,method:A.method,action:O},null,_t)}}else typeof O=="function"&&(et.preventDefault(),_t=Ne?GN(A,Ne):new FormData(A),Nx(h,{pending:!0,data:_t,method:A.method,action:O},O,_t))},currentTarget:A}]})}}for(var s0=0;s0<sr.length;s0++){var r0=sr[s0],vP=r0.toLowerCase(),bP=r0[0].toUpperCase()+r0.slice(1);Ka(vP,"on"+bP)}Ka(_r,"onAnimationEnd"),Ka(tr,"onAnimationIteration"),Ka(wr,"onAnimationStart"),Ka("dblclick","onDoubleClick"),Ka("focusin","onFocus"),Ka("focusout","onBlur"),Ka(Ns,"onTransitionRun"),Ka(Wr,"onTransitionStart"),Ka(nr,"onTransitionCancel"),Ka(Fs,"onTransitionEnd"),jn("onMouseEnter",["mouseout","mouseover"]),jn("onMouseLeave",["mouseout","mouseover"]),jn("onPointerEnter",["pointerout","pointerover"]),jn("onPointerLeave",["pointerout","pointerover"]),$a("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),$a("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),$a("onBeforeInput",["compositionend","keypress","textInput","paste"]),$a("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),$a("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),$a("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var nf="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),xP=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(nf));function YN(r,o){o=(o&4)!==0;for(var h=0;h<r.length;h++){var v=r[h],A=v.event;v=v.listeners;e:{var O=void 0;if(o)for(var Ne=v.length-1;0<=Ne;Ne--){var et=v[Ne],_t=et.instance,hn=et.currentTarget;if(et=et.listener,_t!==O&&A.isPropagationStopped())break e;O=et,A.currentTarget=hn;try{O(A)}catch(Dn){Ss(Dn)}A.currentTarget=null,O=_t}else for(Ne=0;Ne<v.length;Ne++){if(et=v[Ne],_t=et.instance,hn=et.currentTarget,et=et.listener,_t!==O&&A.isPropagationStopped())break e;O=et,A.currentTarget=hn;try{O(A)}catch(Dn){Ss(Dn)}A.currentTarget=null,O=_t}}}}function _s(r,o){var h=o[on];h===void 0&&(h=o[on]=new Set);var v=r+"__bubble";h.has(v)||(QN(o,r,2,!1),h.add(v))}function i0(r,o,h){var v=0;o&&(v|=4),QN(h,r,v,o)}var vy="_reactListening"+Math.random().toString(36).slice(2);function o0(r){if(!r[vy]){r[vy]=!0,Sa.forEach(function(h){h!=="selectionchange"&&(xP.has(h)||i0(h,!1,r),i0(h,!0,r))});var o=r.nodeType===9?r:r.ownerDocument;o===null||o[vy]||(o[vy]=!0,i0("selectionchange",!1,o))}}function QN(r,o,h,v){switch(SS(o)){case 2:var A=YP;break;case 8:A=QP;break;default:A=w0}h=A.bind(null,o,h,r),A=void 0,!oa||o!=="touchstart"&&o!=="touchmove"&&o!=="wheel"||(A=!0),v?A!==void 0?r.addEventListener(o,h,{capture:!0,passive:A}):r.addEventListener(o,h,!0):A!==void 0?r.addEventListener(o,h,{passive:A}):r.addEventListener(o,h,!1)}function c0(r,o,h,v,A){var O=v;if((o&1)===0&&(o&2)===0&&v!==null)e:for(;;){if(v===null)return;var Ne=v.tag;if(Ne===3||Ne===4){var et=v.stateNode.containerInfo;if(et===A)break;if(Ne===4)for(Ne=v.return;Ne!==null;){var _t=Ne.tag;if((_t===3||_t===4)&&Ne.stateNode.containerInfo===A)return;Ne=Ne.return}for(;et!==null;){if(Ne=dn(et),Ne===null)return;if(_t=Ne.tag,_t===5||_t===6||_t===26||_t===27){v=O=Ne;continue e}et=et.parentNode}}v=v.return}is(function(){var hn=O,Dn=Jt(h),qn=[];e:{var fn=Hs.get(r);if(fn!==void 0){var bn=Qo,Oa=r;switch(r){case"keypress":if(Kr(h)===0)break e;case"keydown":case"keyup":bn=Vc;break;case"focusin":Oa="focus",bn=Fc;break;case"focusout":Oa="blur",bn=Fc;break;case"beforeblur":case"afterblur":bn=Fc;break;case"click":if(h.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":bn=to;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":bn=Bc;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":bn=Ue;break;case _r:case tr:case wr:bn=Yl;break;case Fs:bn=kt;break;case"scroll":case"scrollend":bn=Jo;break;case"wheel":bn=Cn;break;case"copy":case"cut":case"paste":bn=Gi;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":bn=ko;break;case"toggle":case"beforetoggle":bn=E}var es=(o&4)!==0,yr=!es&&(r==="scroll"||r==="scrollend"),nn=es?fn!==null?fn+"Capture":null:fn;es=[];for(var Lt=hn,un;Lt!==null;){var On=Lt;if(un=On.stateNode,On=On.tag,On!==5&&On!==26&&On!==27||un===null||nn===null||(On=hs(Lt,nn),On!=null&&es.push(af(Lt,On,un))),yr)break;Lt=Lt.return}0<es.length&&(fn=new bn(fn,Oa,null,h,Dn),qn.push({event:fn,listeners:es}))}}if((o&7)===0){e:{if(fn=r==="mouseover"||r==="pointerover",bn=r==="mouseout"||r==="pointerout",fn&&h!==Xe&&(Oa=h.relatedTarget||h.fromElement)&&(dn(Oa)||Oa[sn]))break e;if((bn||fn)&&(fn=Dn.window===Dn?Dn:(fn=Dn.ownerDocument)?fn.defaultView||fn.parentWindow:window,bn?(Oa=h.relatedTarget||h.toElement,bn=hn,Oa=Oa?dn(Oa):null,Oa!==null&&(yr=c(Oa),es=Oa.tag,Oa!==yr||es!==5&&es!==27&&es!==6)&&(Oa=null)):(bn=null,Oa=hn),bn!==Oa)){if(es=to,On="onMouseLeave",nn="onMouseEnter",Lt="mouse",(r==="pointerout"||r==="pointerover")&&(es=ko,On="onPointerLeave",nn="onPointerEnter",Lt="pointer"),yr=bn==null?fn:wa(bn),un=Oa==null?fn:wa(Oa),fn=new es(On,Lt+"leave",bn,h,Dn),fn.target=yr,fn.relatedTarget=un,On=null,dn(Dn)===hn&&(es=new es(nn,Lt+"enter",Oa,h,Dn),es.target=un,es.relatedTarget=yr,On=es),yr=On,bn&&Oa)t:{for(es=jP,nn=bn,Lt=Oa,un=0,On=nn;On;On=es(On))un++;On=0;for(var Qa=Lt;Qa;Qa=es(Qa))On++;for(;0<un-On;)nn=es(nn),un--;for(;0<On-un;)Lt=es(Lt),On--;for(;un--;){if(nn===Lt||Lt!==null&&nn===Lt.alternate){es=nn;break t}nn=es(nn),Lt=es(Lt)}es=null}else es=null;bn!==null&&JN(qn,fn,bn,es,!1),Oa!==null&&yr!==null&&JN(qn,yr,Oa,es,!0)}}e:{if(fn=hn?wa(hn):window,bn=fn.nodeName&&fn.nodeName.toLowerCase(),bn==="select"||bn==="input"&&fn.type==="file")var Gs=Ga;else if(ca(fn))if(Da)Gs=zs;else{Gs=Hn;var za=Vs}else bn=fn.nodeName,!bn||bn.toLowerCase()!=="input"||fn.type!=="checkbox"&&fn.type!=="radio"?hn&&zn(hn.elementType)&&(Gs=Ga):Gs=Fa;if(Gs&&(Gs=Gs(r,hn))){Pa(qn,Gs,h,Dn);break e}za&&za(r,fn,hn),r==="focusout"&&hn&&fn.type==="number"&&hn.memoizedProps.value!=null&&en(fn,"number",fn.value)}switch(za=hn?wa(hn):window,r){case"focusin":(ca(za)||za.contentEditable==="true")&&(ea=za,Wn=hn,Bn=null);break;case"focusout":Bn=Wn=ea=null;break;case"mousedown":Fn=!0;break;case"contextmenu":case"mouseup":case"dragend":Fn=!1,Na(qn,h,Dn);break;case"selectionchange":if(Rn)break;case"keydown":case"keyup":Na(qn,h,Dn)}var ms;if(Ie)e:{switch(r){case"compositionstart":var Ts="onCompositionStart";break e;case"compositionend":Ts="onCompositionEnd";break e;case"compositionupdate":Ts="onCompositionUpdate";break e}Ts=void 0}else Bt?vn(r,h)&&(Ts="onCompositionEnd"):r==="keydown"&&h.keyCode===229&&(Ts="onCompositionStart");Ts&&(gt&&h.locale!=="ko"&&(Bt||Ts!=="onCompositionStart"?Ts==="onCompositionEnd"&&Bt&&(ms=jr()):(bs=Dn,Wa="value"in bs?bs.value:bs.textContent,Bt=!0)),za=by(hn,Ts),0<za.length&&(Ts=new Zo(Ts,r,null,h,Dn),qn.push({event:Ts,listeners:za}),ms?Ts.data=ms:(ms=zt(h),ms!==null&&(Ts.data=ms)))),(ms=He?En(r,h):wn(r,h))&&(Ts=by(hn,"onBeforeInput"),0<Ts.length&&(za=new Zo("onBeforeInput","beforeinput",null,h,Dn),qn.push({event:za,listeners:Ts}),za.data=ms)),yP(qn,r,hn,h,Dn)}YN(qn,o)})}function af(r,o,h){return{instance:r,listener:o,currentTarget:h}}function by(r,o){for(var h=o+"Capture",v=[];r!==null;){var A=r,O=A.stateNode;if(A=A.tag,A!==5&&A!==26&&A!==27||O===null||(A=hs(r,h),A!=null&&v.unshift(af(r,A,O)),A=hs(r,o),A!=null&&v.push(af(r,A,O))),r.tag===3)return v;r=r.return}return[]}function jP(r){if(r===null)return null;do r=r.return;while(r&&r.tag!==5&&r.tag!==27);return r||null}function JN(r,o,h,v,A){for(var O=o._reactName,Ne=[];h!==null&&h!==v;){var et=h,_t=et.alternate,hn=et.stateNode;if(et=et.tag,_t!==null&&_t===v)break;et!==5&&et!==26&&et!==27||hn===null||(_t=hn,A?(hn=hs(h,O),hn!=null&&Ne.unshift(af(h,hn,_t))):A||(hn=hs(h,O),hn!=null&&Ne.pu
vendor: 7,763 bytes, lines 48-49
48sh(af(h,hn,_t)))),h=h.return}Ne.length!==0&&r.push({event:o,listeners:Ne})}var wP=/\r\n?/g,NP=/\u0000|\uFFFD/g;function KN(r){return(typeof r=="string"?r:""+r).replace(wP,` 49`).replace(NP,"")}function XN(r,o){return o=KN(o),KN(r)===o}function gr(r,o,h,v,A,O){switch(h){case"children":typeof v=="string"?o==="body"||o==="textarea"&&v===""||na(r,v):(typeof v=="number"||typeof v=="bigint")&&o!=="body"&&na(r,""+v);break;case"className":ta(r,"class",v);break;case"tabIndex":ta(r,"tabindex",v);break;case"dir":case"role":case"viewBox":case"width":case"height":ta(r,h,v);break;case"style":ga(r,v,O);break;case"data":if(o!=="object"){ta(r,"data",v);break}case"src":case"href":if(v===""&&(o!=="a"||h!=="href")){r.removeAttribute(h);break}if(v==null||typeof v=="function"||typeof v=="symbol"||typeof v=="boolean"){r.removeAttribute(h);break}v=ua(""+v),r.setAttribute(h,v);break;case"action":case"formAction":if(typeof v=="function"){r.setAttribute(h,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof O=="function"&&(h==="formAction"?(o!=="input"&&gr(r,o,"name",A.name,A,null),gr(r,o,"formEncType",A.formEncType,A,null),gr(r,o,"formMethod",A.formMethod,A,null),gr(r,o,"formTarget",A.formTarget,A,null)):(gr(r,o,"encType",A.encType,A,null),gr(r,o,"method",A.method,A,null),gr(r,o,"target",A.target,A,null)));if(v==null||typeof v=="symbol"||typeof v=="boolean"){r.removeAttribute(h);break}v=ua(""+v),r.setAttribute(h,v);break;case"onClick":v!=null&&(r.onclick=Ma);break;case"onScroll":v!=null&&_s("scroll",r);break;case"onScrollEnd":v!=null&&_s("scrollend",r);break;case"dangerouslySetInnerHTML":if(v!=null){if(typeof v!="object"||!("__html"in v))throw Error(s(61));if(h=v.__html,h!=null){if(A.children!=null)throw Error(s(60));r.innerHTML=h}}break;case"multiple":r.multiple=v&&typeof v!="function"&&typeof v!="symbol";break;case"muted":r.muted=v&&typeof v!="function"&&typeof v!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(v==null||typeof v=="function"||typeof v=="boolean"||typeof v=="symbol"){r.removeAttribute("xlink:href");break}h=ua(""+v),r.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",h);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":v!=null&&typeof v!="function"&&typeof v!="symbol"?r.setAttribute(h,""+v):r.removeAttribute(h);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":v&&typeof v!="function"&&typeof v!="symbol"?r.setAttribute(h,""):r.removeAttribute(h);break;case"capture":case"download":v===!0?r.setAttribute(h,""):v!==!1&&v!=null&&typeof v!="function"&&typeof v!="symbol"?r.setAttribute(h,v):r.removeAttribute(h);break;case"cols":case"rows":case"size":case"span":v!=null&&typeof v!="function"&&typeof v!="symbol"&&!isNaN(v)&&1<=v?r.setAttribute(h,v):r.removeAttribute(h);break;case"rowSpan":case"start":v==null||typeof v=="function"||typeof v=="symbol"||isNaN(v)?r.removeAttribute(h):r.setAttribute(h,v);break;case"popover":_s("beforetoggle",r),_s("toggle",r),ha(r,"popover",v);break;case"xlinkActuate":W(r,"http://www.w3.org/1999/xlink","xlink:actuate",v);break;case"xlinkArcrole":W(r,"http://www.w3.org/1999/xlink","xlink:arcrole",v);break;case"xlinkRole":W(r,"http://www.w3.org/1999/xlink","xlink:role",v);break;case"xlinkShow":W(r,"http://www.w3.org/1999/xlink","xlink:show",v);break;case"xlinkTitle":W(r,"http://www.w3.org/1999/xlink","xlink:title",v);break;case"xlinkType":W(r,"http://www.w3.org/1999/xlink","xlink:type",v);break;case"xmlBase":W(r,"http://www.w3.org/XML/1998/namespace","xml:base",v);break;case"xmlLang":W(r,"http://www.w3.org/XML/1998/namespace","xml:lang",v);break;case"xmlSpace":W(r,"http://www.w3.org/XML/1998/namespace","xml:space",v);break;case"is":ha(r,"is",v);break;case"innerText":case"textContent":break;default:(!(2<h.length)||h[0]!=="o"&&h[0]!=="O"||h[1]!=="n"&&h[1]!=="N")&&(h=Xn.get(h)||h,ha(r,h,v))}}function l0(r,o,h,v,A,O){switch(h){case"style":ga(r,v,O);break;case"dangerouslySetInnerHTML":if(v!=null){if(typeof v!="object"||!("__html"in v))throw Error(s(61));if(h=v.__html,h!=null){if(A.children!=null)throw Error(s(60));r.innerHTML=h}}break;case"children":typeof v=="string"?na(r,v):(typeof v=="number"||typeof v=="bigint")&&na(r,""+v);break;case"onScroll":v!=null&&_s("scroll",r);break;case"onScrollEnd":v!=null&&_s("scrollend",r);break;case"onClick":v!=null&&(r.onclick=Ma);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!aa.hasOwnProperty(h))e:{if(h[0]==="o"&&h[1]==="n"&&(A=h.endsWith("Capture"),o=h.slice(2,A?h.length-7:void 0),O=r[Vt]||null,O=O!=null?O[h]:null,typeof O=="function"&&r.removeEventListener(o,O,A),typeof v=="function")){typeof O!="function"&&O!==null&&(h in r?r[h]=null:r.hasAttribute(h)&&r.removeAttribute(h)),r.addEventListener(o,v,A);break e}h in r?r[h]=v:v===!0?r.setAttribute(h,""):ha(r,h,v)}}}function Ji(r,o,h){switch(o){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":_s("error",r),_s("load",r);var v=!1,A=!1,O;for(O in h)if(h.hasOwnProperty(O)){var Ne=h[O];if(Ne!=null)switch(O){case"src":v=!0;break;case"srcSet":A=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(s(137,o));default:gr(r,o,O,Ne,h,null)}}A&&gr(r,o,"srcSet",h.srcSet,h,null),v&&gr(r,o,"src",h.src,h,null);return;case"input":_s("invalid",r);var et=O=Ne=A=null,_t=null,hn=null;for(v in h)if(h.hasOwnProperty(v)){var Dn=h[v];if(Dn!=null)switch(v){case"name":A=Dn;break;case"type":Ne=Dn;break;case"checked":_t=Dn;break;case"defaultChecked":hn=Dn;break;case"value":O=Dn;break;case"defaultValue":et=Dn;break;case"children":case"dangerouslySetInnerHTML":if(Dn!=null)throw Error(s(137,o));break;default:gr(r,o,v,Dn,h,null)}}At(r,O,et,_t,hn,Ne,A,!1);return;case"select":_s("invalid",r),v=Ne=O=null;for(A in h)if(h.hasOwnProperty(A)&&(et=h[A],et!=null))switch(A){case"value":O=et;break;case"defaultValue":Ne=et;break;case"multiple":v=et;default:gr(r,o,A,et,h,null)}o=O,h=Ne,r.multiple=!!v,o!=null?It(r,!!v,o,!1):h!=null&&It(r,!!v,h,!0);return;case"textarea":_s("invalid",r),O=A=v=null;for(Ne in h)if(h.hasOwnProperty(Ne)&&(et=h[Ne],et!=null))switch(Ne){case"value":v=et;break;case"defaultValue":A=et;break;case"children":O=et;break;case"dangerouslySetInnerHTML":if(et!=null)throw Error(s(91));break;default:gr(r,o,Ne,et,h,null)}Jn(r,v,A,O);return;case"option":for(_t in h)if(h.hasOwnProperty(_t)&&(v=h[_t],v!=null))switch(_t){case"selected":r.selected=v&&typeof v!="function"&&typeof v!="symbol";break;default:gr(r,o,_t,v,h,null)}return;case"dialog":_s("beforetoggle",r),_s("toggle",r),_s("cancel",r),_s("close",r);break;case"iframe":case"object":_s("load",r);break;case"video":case"audio":for(v=0;v<nf.length;v++)_s(nf[v],r);break;case"image":_s("error",r),_s("load",r);break;case"details":_s("toggle",r);break;case"embed":case"source":case"link":_s("error",r),_s("load",r);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(hn
vendor: 7,652 bytes, line 49
49in h)if(h.hasOwnProperty(hn)&&(v=h[hn],v!=null))switch(hn){case"children":case"dangerouslySetInnerHTML":throw Error(s(137,o));default:gr(r,o,hn,v,h,null)}return;default:if(zn(o)){for(Dn in h)h.hasOwnProperty(Dn)&&(v=h[Dn],v!==void 0&&l0(r,o,Dn,v,h,void 0));return}}for(et in h)h.hasOwnProperty(et)&&(v=h[et],v!=null&&gr(r,o,et,v,h,null))}function SP(r,o,h,v){switch(o){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var A=null,O=null,Ne=null,et=null,_t=null,hn=null,Dn=null;for(bn in h){var qn=h[bn];if(h.hasOwnProperty(bn)&&qn!=null)switch(bn){case"checked":break;case"value":break;case"defaultValue":_t=qn;default:v.hasOwnProperty(bn)||gr(r,o,bn,null,v,qn)}}for(var fn in v){var bn=v[fn];if(qn=h[fn],v.hasOwnProperty(fn)&&(bn!=null||qn!=null))switch(fn){case"type":O=bn;break;case"name":A=bn;break;case"checked":hn=bn;break;case"defaultChecked":Dn=bn;break;case"value":Ne=bn;break;case"defaultValue":et=bn;break;case"children":case"dangerouslySetInnerHTML":if(bn!=null)throw Error(s(137,o));break;default:bn!==qn&&gr(r,o,fn,bn,v,qn)}}ut(r,Ne,et,_t,hn,Dn,O,A);return;case"select":bn=Ne=et=fn=null;for(O in h)if(_t=h[O],h.hasOwnProperty(O)&&_t!=null)switch(O){case"value":break;case"multiple":bn=_t;default:v.hasOwnProperty(O)||gr(r,o,O,null,v,_t)}for(A in v)if(O=v[A],_t=h[A],v.hasOwnProperty(A)&&(O!=null||_t!=null))switch(A){case"value":fn=O;break;case"defaultValue":et=O;break;case"multiple":Ne=O;default:O!==_t&&gr(r,o,A,O,v,_t)}o=et,h=Ne,v=bn,fn!=null?It(r,!!h,fn,!1):!!v!=!!h&&(o!=null?It(r,!!h,o,!0):It(r,!!h,h?[]:"",!1));return;case"textarea":bn=fn=null;for(et in h)if(A=h[et],h.hasOwnProperty(et)&&A!=null&&!v.hasOwnProperty(et))switch(et){case"value":break;case"children":break;default:gr(r,o,et,null,v,A)}for(Ne in v)if(A=v[Ne],O=h[Ne],v.hasOwnProperty(Ne)&&(A!=null||O!=null))switch(Ne){case"value":fn=A;break;case"defaultValue":bn=A;break;case"children":break;case"dangerouslySetInnerHTML":if(A!=null)throw Error(s(91));break;default:A!==O&&gr(r,o,Ne,A,v,O)}Pt(r,fn,bn);return;case"option":for(var Oa in h)if(fn=h[Oa],h.hasOwnProperty(Oa)&&fn!=null&&!v.hasOwnProperty(Oa))switch(Oa){case"selected":r.selected=!1;break;default:gr(r,o,Oa,null,v,fn)}for(_t in v)if(fn=v[_t],bn=h[_t],v.hasOwnProperty(_t)&&fn!==bn&&(fn!=null||bn!=null))switch(_t){case"selected":r.selected=fn&&typeof fn!="function"&&typeof fn!="symbol";break;default:gr(r,o,_t,fn,v,bn)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var es in h)fn=h[es],h.hasOwnProperty(es)&&fn!=null&&!v.hasOwnProperty(es)&&gr(r,o,es,null,v,fn);for(hn in v)if(fn=v[hn],bn=h[hn],v.hasOwnProperty(hn)&&fn!==bn&&(fn!=null||bn!=null))switch(hn){case"children":case"dangerouslySetInnerHTML":if(fn!=null)throw Error(s(137,o));break;default:gr(r,o,hn,fn,v,bn)}return;default:if(zn(o)){for(var yr in h)fn=h[yr],h.hasOwnProperty(yr)&&fn!==void 0&&!v.hasOwnProperty(yr)&&l0(r,o,yr,void 0,v,fn);for(Dn in v)fn=v[Dn],bn=h[Dn],!v.hasOwnProperty(Dn)||fn===bn||fn===void 0&&bn===void 0||l0(r,o,Dn,fn,v,bn);return}}for(var nn in h)fn=h[nn],h.hasOwnProperty(nn)&&fn!=null&&!v.hasOwnProperty(nn)&&gr(r,o,nn,null,v,fn);for(qn in v)fn=v[qn],bn=h[qn],!v.hasOwnProperty(qn)||fn===bn||fn==null&&bn==null||gr(r,o,qn,fn,v,bn)}function ZN(r){switch(r){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function CP(){if(typeof performance.getEntriesByType=="function"){for(var r=0,o=0,h=performance.getEntriesByType("resource"),v=0;v<h.length;v++){var A=h[v],O=A.transferSize,Ne=A.initiatorType,et=A.duration;if(O&&et&&ZN(Ne)){for(Ne=0,et=A.responseEnd,v+=1;v<h.length;v++){var _t=h[v],hn=_t.startTime;if(hn>et)break;var Dn=_t.transferSize,qn=_t.initiatorType;Dn&&ZN(qn)&&(_t=_t.responseEnd,Ne+=Dn*(_t<et?1:(et-hn)/(_t-hn)))}if(--v,o+=8*(O+Ne)/(A.duration/1e3),r++,10<r)break}}if(0<r)return o/r/1e6}return navigator.connection&&(r=navigator.connection.downlink,typeof r=="number")?r:5}var d0=null,u0=null;function xy(r){return r.nodeType===9?r:r.ownerDocument}function eS(r){switch(r){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function tS(r,o){if(r===0)switch(o){case"svg":return 1;case"math":return 2;default:return 0}return r===1&&o==="foreignObject"?0:r}function h0(r,o){return r==="textarea"||r==="noscript"||typeof o.children=="string"||typeof o.children=="number"||typeof o.children=="bigint"||typeof o.dangerouslySetInnerHTML=="object"&&o.dangerouslySetInnerHTML!==null&&o.dangerouslySetInnerHTML.__html!=null}var m0=null;function AP(){var r=window.event;return r&&r.type==="popstate"?r===m0?!1:(m0=r,!0):(m0=null,!1)}var nS=typeof setTimeout=="function"?setTimeout:void 0,IP=typeof clearTimeout=="function"?clearTimeout:void 0,aS=typeof Promise=="function"?Promise:void 0,_P=typeof queueMicrotask=="function"?queueMicrotask:typeof aS<"u"?function(r){return aS.resolve(null).then(r).catch(kP)}:nS;function kP(r){setTimeout(function(){throw r})}function Xd(r){return r==="head"}function sS(r,o){var h=o,v=0;do{var A=h.nextSibling;if(r.removeChild(h),A&&A.nodeType===8)if(h=A.data,h==="/$"||h==="/&"){if(v===0){r.removeChild(A),Pm(o);return}v--}else if(h==="$"||h==="$?"||h==="$~"||h==="$!"||h==="&")v++;else if(h==="html")sf(r.ownerDocument.documentElement);else if(h==="head"){h=r.ownerDocument.head,sf(h);for(var O=h.firstChild;O;){var Ne=O.nextSibling,et=O.nodeName;O[Rt]||et==="SCRIPT"||et==="STYLE"||et==="LINK"&&O.rel.toLowerCase()==="stylesheet"||h.removeChild(O),O=Ne}}else h==="body"&&sf(r.ownerDocument.body);h=A}while(h);Pm(o)}function rS(r,o){var h=r;r=0;do{var v=h.nextSibling;if(h.nodeType===1?o?(h._stashedDisplay=h.style.display,h.style.display="none"):(h.style.display=h._stashedDisplay||"",h.getAttribute("style")===""&&h.removeAttribute("style")):h.nodeType===3&&(o?(h._stashedText=h.nodeValue,h.nodeValue=""):h.nodeValue=h._stashedText||""),v&&v.nodeType===8)if(h=v.data,h==="/$"){if(r===0)break;r--}else h!=="$"&&h!=="$?"&&h!=="$~"&&h!=="$!"||r++;h=v}while(h)}function p0(r){var o=r.firstChild;for(o&&o.nodeType===10&&(o=o.nextSibling);o;){var h=o;switch(o=o.nextSibling,h.nodeName){case"HTML":case"HEAD":case"BODY":p0(h),xn(h);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(h.rel.toLowerCase()==="stylesheet")continue}r.removeChild(h)}}function DP(r,o,h,v){for(;r.nodeType===1;){var A=h;if(r.nodeName.toLowerCase()!==o.toLowerCase()){if(!v&&(r.nodeName!=="INPUT"||r.type!=="hidden"))break}else if(v){if(!r[Rt])switch(o){case"meta":if(!r.hasAttribute("itemprop"))break;return r;case"link":if(O=r.getAttribute("rel"),O==="stylesheet"&&r.hasAttribute("data-precedence"))break;if(O!==A.rel||r.getAttribute("href")!==(A.href==null||A.href===""?null:A.href)||r.getAttribute("crossorigin")!==(A.crossOrigin==null?null:A.crossOrigin)||r.getAttribute("title")!==(A.title==null?null:A.title))break;return r;case"style":if(r.hasAttribute("data-precedence"))break;return r;case"script":if(O=r.getAttribute("src"),(O!==(A.src==null?null:A.src)||r.getAttribute("type")!==(A.type==null?null:A.type)||r.getAttribute("crossorigin")!==(A.crossOrigin==null?null:A.crossOrigin))&&O&&r.hasAttribute("async")&&!r.hasAttribute("itemprop"))break;return r;default:return r}}else if(o==="input"&&r.type==="hidden"){var O=A.name==null?null:""+A.name;if(A.type==="hidden"&&r.getAttribute("name")===O)return r}else return r;if(r=Ic(r.nextSibling),r===null)break}return null}function EP(r,o,h){if(o==="")return null;for(;r.nodeType!==3;)if((r.nodeType!==1||r.nodeName!=="INPUT"||r.type!=="hidden")&&!h||(r=
vendor: 9,655 bytes, line 49
49Ic(r.nextSibling),r===null))return null;return r}function iS(r,o){for(;r.nodeType!==8;)if((r.nodeType!==1||r.nodeName!=="INPUT"||r.type!=="hidden")&&!o||(r=Ic(r.nextSibling),r===null))return null;return r}function f0(r){return r.data==="$?"||r.data==="$~"}function g0(r){return r.data==="$!"||r.data==="$?"&&r.ownerDocument.readyState!=="loading"}function PP(r,o){var h=r.ownerDocument;if(r.data==="$~")r._reactRetry=o;else if(r.data!=="$?"||h.readyState!=="loading")o();else{var v=function(){o(),h.removeEventListener("DOMContentLoaded",v)};h.addEventListener("DOMContentLoaded",v),r._reactRetry=v}}function Ic(r){for(;r!=null;r=r.nextSibling){var o=r.nodeType;if(o===1||o===3)break;if(o===8){if(o=r.data,o==="$"||o==="$!"||o==="$?"||o==="$~"||o==="&"||o==="F!"||o==="F")break;if(o==="/$"||o==="/&")return null}}return r}var y0=null;function oS(r){r=r.nextSibling;for(var o=0;r;){if(r.nodeType===8){var h=r.data;if(h==="/$"||h==="/&"){if(o===0)return Ic(r.nextSibling);o--}else h!=="$"&&h!=="$!"&&h!=="$?"&&h!=="$~"&&h!=="&"||o++}r=r.nextSibling}return null}function cS(r){r=r.previousSibling;for(var o=0;r;){if(r.nodeType===8){var h=r.data;if(h==="$"||h==="$!"||h==="$?"||h==="$~"||h==="&"){if(o===0)return r;o--}else h!=="/$"&&h!=="/&"||o++}r=r.previousSibling}return null}function lS(r,o,h){switch(o=xy(h),r){case"html":if(r=o.documentElement,!r)throw Error(s(452));return r;case"head":if(r=o.head,!r)throw Error(s(453));return r;case"body":if(r=o.body,!r)throw Error(s(454));return r;default:throw Error(s(451))}}function sf(r){for(var o=r.attributes;o.length;)r.removeAttributeNode(o[0]);xn(r)}var _c=new Map,dS=new Set;function jy(r){return typeof r.getRootNode=="function"?r.getRootNode():r.nodeType===9?r:r.ownerDocument}var ud=ne.d;ne.d={f:RP,r:TP,D:MP,C:$P,L:OP,m:LP,X:FP,S:BP,M:UP};function RP(){var r=ud.f(),o=hy();return r||o}function TP(r){var o=Ln(r);o!==null&&o.tag===5&&o.type==="form"?I2(o):ud.r(r)}var km=typeof document>"u"?null:document;function uS(r,o,h){var v=km;if(v&&typeof o=="string"&&o){var A=Oe(o);A='link[rel="'+r+'"][href="'+A+'"]',typeof h=="string"&&(A+='[crossorigin="'+h+'"]'),dS.has(A)||(dS.add(A),r={rel:r,crossOrigin:h,href:o},v.querySelector(A)===null&&(o=v.createElement("link"),Ji(o,"link",r),In(o),v.head.appendChild(o)))}}function MP(r){ud.D(r),uS("dns-prefetch",r,null)}function $P(r,o){ud.C(r,o),uS("preconnect",r,o)}function OP(r,o,h){ud.L(r,o,h);var v=km;if(v&&r&&o){var A='link[rel="preload"][as="'+Oe(o)+'"]';o==="image"&&h&&h.imageSrcSet?(A+='[imagesrcset="'+Oe(h.imageSrcSet)+'"]',typeof h.imageSizes=="string"&&(A+='[imagesizes="'+Oe(h.imageSizes)+'"]')):A+='[href="'+Oe(r)+'"]';var O=A;switch(o){case"style":O=Dm(r);break;case"script":O=Em(r)}_c.has(O)||(r=g({rel:"preload",href:o==="image"&&h&&h.imageSrcSet?void 0:r,as:o},h),_c.set(O,r),v.querySelector(A)!==null||o==="style"&&v.querySelector(rf(O))||o==="script"&&v.querySelector(of(O))||(o=v.createElement("link"),Ji(o,"link",r),In(o),v.head.appendChild(o)))}}function LP(r,o){ud.m(r,o);var h=km;if(h&&r){var v=o&&typeof o.as=="string"?o.as:"script",A='link[rel="modulepreload"][as="'+Oe(v)+'"][href="'+Oe(r)+'"]',O=A;switch(v){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":O=Em(r)}if(!_c.has(O)&&(r=g({rel:"modulepreload",href:r},o),_c.set(O,r),h.querySelector(A)===null)){switch(v){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(h.querySelector(of(O)))return}v=h.createElement("link"),Ji(v,"link",r),In(v),h.head.appendChild(v)}}}function BP(r,o,h){ud.S(r,o,h);var v=km;if(v&&r){var A=Ca(v).hoistableStyles,O=Dm(r);o=o||"default";var Ne=A.get(O);if(!Ne){var et={loading:0,preload:null};if(Ne=v.querySelector(rf(O)))et.loading=5;else{r=g({rel:"stylesheet",href:r,"data-precedence":o},h),(h=_c.get(O))&&v0(r,h);var _t=Ne=v.createElement("link");In(_t),Ji(_t,"link",r),_t._p=new Promise(function(hn,Dn){_t.onload=hn,_t.onerror=Dn}),_t.addEventListener("load",function(){et.loading|=1}),_t.addEventListener("error",function(){et.loading|=2}),et.loading|=4,wy(Ne,o,v)}Ne={type:"stylesheet",instance:Ne,count:1,state:et},A.set(O,Ne)}}}function FP(r,o){ud.X(r,o);var h=km;if(h&&r){var v=Ca(h).hoistableScripts,A=Em(r),O=v.get(A);O||(O=h.querySelector(of(A)),O||(r=g({src:r,async:!0},o),(o=_c.get(A))&&b0(r,o),O=h.createElement("script"),In(O),Ji(O,"link",r),h.head.appendChild(O)),O={type:"script",instance:O,count:1,state:null},v.set(A,O))}}function UP(r,o){ud.M(r,o);var h=km;if(h&&r){var v=Ca(h).hoistableScripts,A=Em(r),O=v.get(A);O||(O=h.querySelector(of(A)),O||(r=g({src:r,async:!0,type:"module"},o),(o=_c.get(A))&&b0(r,o),O=h.createElement("script"),In(O),Ji(O,"link",r),h.head.appendChild(O)),O={type:"script",instance:O,count:1,state:null},v.set(A,O))}}function hS(r,o,h,v){var A=(A=me.current)?jy(A):null;if(!A)throw Error(s(446));switch(r){case"meta":case"title":return null;case"style":return typeof h.precedence=="string"&&typeof h.href=="string"?(o=Dm(h.href),h=Ca(A).hoistableStyles,v=h.get(o),v||(v={type:"style",instance:null,count:0,state:null},h.set(o,v)),v):{type:"void",instance:null,count:0,state:null};case"link":if(h.rel==="stylesheet"&&typeof h.href=="string"&&typeof h.precedence=="string"){r=Dm(h.href);var O=Ca(A).hoistableStyles,Ne=O.get(r);if(Ne||(A=A.ownerDocument||A,Ne={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},O.set(r,Ne),(O=A.querySelector(rf(r)))&&!O._p&&(Ne.instance=O,Ne.state.loading=5),_c.has(r)||(h={rel:"preload",as:"style",href:h.href,crossOrigin:h.crossOrigin,integrity:h.integrity,media:h.media,hrefLang:h.hrefLang,referrerPolicy:h.referrerPolicy},_c.set(r,h),O||zP(A,r,h,Ne.state))),o&&v===null)throw Error(s(528,""));return Ne}if(o&&v!==null)throw Error(s(529,""));return null;case"script":return o=h.async,h=h.src,typeof h=="string"&&o&&typeof o!="function"&&typeof o!="symbol"?(o=Em(h),h=Ca(A).hoistableScripts,v=h.get(o),v||(v={type:"script",instance:null,count:0,state:null},h.set(o,v)),v):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,r))}}function Dm(r){return'href="'+Oe(r)+'"'}function rf(r){return'link[rel="stylesheet"]['+r+"]"}function mS(r){return g({},r,{"data-precedence":r.precedence,precedence:null})}function zP(r,o,h,v){r.querySelector('link[rel="preload"][as="style"]['+o+"]")?v.loading=1:(o=r.createElement("link"),v.preload=o,o.addEventListener("load",function(){return v.loading|=1}),o.addEventListener("error",function(){return v.loading|=2}),Ji(o,"link",h),In(o),r.head.appendChild(o))}function Em(r){return'[src="'+Oe(r)+'"]'}function of(r){return"script[async]"+r}function pS(r,o,h){if(o.count++,o.instance===null)switch(o.type){case"style":var v=r.querySelector('style[data-href~="'+Oe(h.href)+'"]');if(v)return o.instance=v,In(v),v;var A=g({},h,{"data-href":h.href,"data-precedence":h.precedence,href:null,precedence:null});return v=(r.ownerDocument||r).createElement("style"),In(v),Ji(v,"style",A),wy(v,h.precedence,r),o.instance=v;case"stylesheet":A=Dm(h.href);var O=r.querySelector(rf(A));if(O)return o.state.loading|=4,o.instance=O,In(O),O;v=mS(h),(A=_c.get(A))&&v0(v,A),O=(r.ownerDocument||r).createElement("link"),In(O);var Ne=O;return Ne._p=new Promise(function(et,_t){Ne.onload=et,Ne.onerror=_t}),Ji(O,"link",v),o.state.loading|=4,wy(O,h.precedence,r),o.instance=O;case"script":return O=Em(h.src),(A=r.querySelector(of(O)))?(o.instance=A,In(A),A):(v=h,(A=_c.get(O))&&(v=g({},h),b0(v,A)),r=r.ownerDocument||r,A=r.createElement("script"),In(A),Ji(A,"link",v),r.head.appendChild(A),o.instance=A);case"void":return null;default:throw Error(s(443,o.type))}else o.type==="stylesheet"&&(o.state.loading&4)===0&&(v=o.instance,o.state.loading|=4,wy(v,h.precedence,r));return o.instance}function wy(r,o,h){for(var v=h.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),A=v.length?v[v.length-1]:null,O=A,Ne=0;Ne<v.length;Ne++){var et=v[Ne];if(et.dataset.precedence===o)O=et;else if(O!==A)break}O?O.parentNode.insertBefore(r,O.nextSibling):(o=h.nodeType===9?h.head:h,o.insertBefore(r,o.firstChild))}function v0(r,o){r.crossOrigin==null&&(r.crossOrigin=o.crossOrigin),r.referrerPolicy==null&&(r.referrerPolicy=o.referrerPolicy),r.title==null&&(r.title=o.title)}function b0(r,o){r.crossOrigin==null&&(r.crossOrigin=o.crossOrigin),r.referrerPolicy==null&&(r.referrerPolicy=o.referrerPolicy),r.integrity==null&&(r.integrity=o.integrity)}var Ny=null;function fS(r,o,h){if(Ny===null){var v=new Map,A=Ny=new Map;A.set(h,v)}else A=Ny,v=A.get(h),v||(v=new Map,A.set(h,v));if(v.has(r))return v;for(v.set(r,null),h=h.getElementsByTagName(r),A=0;A<h.length;A++){var O=h[A];if(!(O[Rt]||O[$t]||r==="link"&&O.getAttribute("rel")==="stylesheet")&&O.namespaceURI!=="http://www.w3.org/2000/svg"){var Ne=O.getAttribute(o)||"";Ne=r+Ne;var et=v.get(Ne);et?et.push(O):v.set(Ne,[O])}}return v}function gS(r,o,h){r=r.ownerDocument||r,r.head.insertBefore(h,o==="title"?r.querySelector("head > title"):null)}function qP(r,o,h){if(h===1||o.itemProp!=null)return!1;switch(r){case"meta":case"title":return!0;case"style":if(typeof o.precedence!="string"||typeof o.href!="string"||o.href==="")break;return!0;case"link":if(typeof o.rel!="string"||typeof o.href!="string"||o.href===""||o.onLoad||o.onError)break;switch(o.rel){case"stylesheet":return r=o.disabled,typeof o.precedence=="string"&&r==null;default:return!0}case"script":if(o.async&&typeof o.async!="function"&&typeof o.async!="symbol"&&!o.onLoad&&!o.onError&&o.src&&typeof o.src=="string")return!0}return!1}function yS(r){return!(r.type==="stylesheet"&&(r.state.loading&3)===0)}function VP(r,o,h,v){if(h.type==="stylesheet"&&(typeof v.media!="str
49ing"||matchMedia(v.media).matches!==!1)&&(h.state.loading&4)===0){if(h.instance===null){var A=Dm(v.href),O=o.querySelector(rf(A));if(O){o=O._p,o!==null&&typeof o=="object"&&typeof o.then=="function"&&(r.count++,r=Sy.bind(r),o.then(r,r)),h.state.loading|=4,h.instance=O,In(O);return}O=o.ownerDocument||o,v=mS(v),(A=_c.get(A))&&v0(v,A),O=O.createElement("link"),In(O);var Ne=O;Ne._p=new Promise(function(et,_t){Ne.onload=et,Ne.onerror=_t}),Ji(O,"link",v),h.instance=O}r.stylesheets===null&&(r.stylesheets=new Map),r.stylesheets.set(h,o),(o=h.state.preload)&&(h.state.loading&3)===0&&(r.count++,h=Sy.bind(r),o.addEventListener("load",h),o.addEventListener("error",h))}}var x0=0;function HP(r,o){return r.stylesheets&&r.count===0&&Ay(r,r.stylesheets),0<r.count||0<r.imgCount?function(h){var v=setTimeout(function(){if(r.stylesheets&&Ay(r,r.stylesheets),r.unsuspend){var O=r.unsuspend;r.unsuspend=null,O()}},6e4+o);0<r.imgBytes&&x0===0&&(x0=62500*CP());var A=setTimeout(function(){if(r.waitingForImages=!1,r.count===0&&(r.stylesheets&&Ay(r,r.stylesheets),r.unsuspend)){var O=r.unsuspend;r.unsuspend=null,O()}},(r.imgBytes>x0?50:800)+o);return r.unsuspend=h,function(){r.unsuspend=null,clearTimeout(v),clearTimeout(A)}}:null}function Sy(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Ay(this,this.stylesheets);else if(this.unsuspend){var r=this.unsuspend;this.unsuspend=null,r()}}}var Cy=null;function Ay(r,o){r.stylesheets=null,r.unsuspend!==null&&(r.count++,Cy=new Map,o.forEach(WP,r),Cy=null,Sy.call(r))}function WP(r,o){if(!(o.state.loading&4)){var h=Cy.get(r);if(h)var v=h.get(null);else{h=new Map,Cy.set(r,h);for(var A=r.querySelectorAll("link[data-precedence],style[data-precedence]"),O=0;O<A.length;O++){var Ne=A[O];(Ne.nodeName==="LINK"||Ne.getAttribute("media")!=="not all")&&(h.set(Ne.dataset.precedence,Ne),v=Ne)}v&&h.set(null,v)}A=o.instance,Ne=A.getAttribute("data-precedence"),O=h.get(Ne)||v,O===v&&h.set(null,A),h.set(Ne,A),this.count++,v=Sy.bind(this),A.addEventListener("load",v),A.addEventListener("error",v),O?O.parentNode.insertBefore(A,O.nextSibling):(r=r.nodeType===9?r.head:r,r.insertBefore(A,r.firstChild)),o.state.loading|=4}}var cf={$$typeof:I,Provider:null,Consumer:null,_currentValue:ae,_currentValue2:ae,_threadCount:0};function GP(r,o,h,v,A,O,Ne,et,_t){this.tag=1,this.containerInfo=r,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=dt(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=dt(0),this.hiddenUpdates=dt(null),this.identifierPrefix=v,this.onUncaughtError=A,this.onCaughtError=O,this.onRecoverableError=Ne,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=_t,this.incompleteTransitions=new Map}function vS(r,o,h,v,A,O,Ne,et,_t,hn,Dn,qn){return r=new GP(r,o,h,Ne,_t,hn,Dn,qn,et),o=1,O===!0&&(o|=24),O=Bi(3,null,null,o),r.current=O,O.stateNode=r,o=Fd(),o.refCount++,r.pooledCache=o,o.refCount++,O.memoizedState={element:v,isDehydrated:h,cache:o},Ks(O),r}function bS(r){return r?(r=Ni,r):Ni}function xS(r,o,h,v,A,O){A=bS(A),v.context===null?v.context=A:v.pendingContext=A,v=Za(o),v.payload={element:h},O=O===void 0?null:O,O!==null&&(v.callback=O),h=ir(r,v,o),h!==null&&(qo(h,r,o),hi(h,r,o))}function jS(r,o){if(r=r.memoizedState,r!==null&&r.dehydrated!==null){var h=r.retryLane;r.retryLane=h!==0&&h<o?h:o}}function j0(r,o){jS(r,o),(r=r.alternate)&&jS(r,o)}function wS(r){if(r.tag===13||r.tag===31){var o=Hc(r,67108864);o!==null&&qo(o,r,67108864),j0(r,67108864)}}function NS(r){if(r.tag===13||r.tag===31){var o=rc();o=An(o);var h=Hc(r,o);h!==null&&qo(h,r,o),j0(r,o)}}var Iy=!0;function YP(r,o,h,v){var A=q.T;q.T=null;var O=ne.p;try{ne.p=2,w0(r,o,h,v)}finally{ne.p=O,q.T=A}}function QP(r,o,h,v){var A=q.T;q.T=null;var O=ne.p;try{ne.p=8,w0(r,o,h,v)}finally{ne.p=O,q.T=A}}function w0(r,o,h,v){if(Iy){var A=N0(v);if(A===null)c0(r,o,v,_y,h),CS(r,v);else if(KP(A,r,o,h,v))v.stopPropagation();else if(CS(r,v),o&4&&-1<JP.indexOf(r)){for(;A!==null;){var O=Ln(A);if(O!==null)switch(O.tag){case 3:if(O=O.stateNode,O.current.memoizedState.isDehydrated){var Ne=tn(O.pendingLanes);if(Ne!==0){var et=O;for(et.pendingLanes|=2,et.entangledLanes|=2;Ne;){var _t=1<<31-pt(Ne);et.entanglements[1]|=_t,Ne&=~_t}El(O),(Xs&6)===0&&(dy=ct()+500,tf(0))}}break;case 31:case 13:et=Hc(O,2),et!==null&&qo(et,O,2),hy(),j0(O,2)}if(O=N0(v),O===null&&c0(r,o,v,_y,h),O===A)break;A=O}A!==null&&v.stopPropagation()}else c0(r,o,v,null,h)}}function N0(r){return r=Jt(r),S0(r)}var _y=null;function S0(r){if(_y=null,r=dn(r),r!==null){var o=c(r);if(o===null)r=null;else{var h=o.tag;if(h===13){if(r=l(o),r!==null)return r;r=null}else if(h===31){if(r=m(o),r!==null)return r;r=null}else if(h===3){if(o.stateNode.current.memoizedState.isDehydrated)return o.tag===3?o.stateNode.containerInfo:null;r=null}else o!==r&&(r=null)}}return _y=r,null}function SS(r){switch(r){case"beforetoggle":case"cancel":case"click":case"close"
vendor: 6,272 bytes, line 49
49:case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Ce()){case De:return 2;case Te:return 8;case ce:case Ye:return 32;case Je:return 268435456;default:return 32}default:return 32}}var C0=!1,Zd=null,eu=null,tu=null,lf=new Map,df=new Map,nu=[],JP="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function CS(r,o){switch(r){case"focusin":case"focusout":Zd=null;break;case"dragenter":case"dragleave":eu=null;break;case"mouseover":case"mouseout":tu=null;break;case"pointerover":case"pointerout":lf.delete(o.pointerId);break;case"gotpointercapture":case"lostpointercapture":df.delete(o.pointerId)}}function uf(r,o,h,v,A,O){return r===null||r.nativeEvent!==O?(r={blockedOn:o,domEventName:h,eventSystemFlags:v,nativeEvent:O,targetContainers:[A]},o!==null&&(o=Ln(o),o!==null&&wS(o)),r):(r.eventSystemFlags|=v,o=r.targetContainers,A!==null&&o.indexOf(A)===-1&&o.push(A),r)}function KP(r,o,h,v,A){switch(o){case"focusin":return Zd=uf(Zd,r,o,h,v,A),!0;case"dragenter":return eu=uf(eu,r,o,h,v,A),!0;case"mouseover":return tu=uf(tu,r,o,h,v,A),!0;case"pointerover":var O=A.pointerId;return lf.set(O,uf(lf.get(O)||null,r,o,h,v,A)),!0;case"gotpointercapture":return O=A.pointerId,df.set(O,uf(df.get(O)||null,r,o,h,v,A)),!0}return!1}function AS(r){var o=dn(r.target);if(o!==null){var h=c(o);if(h!==null){if(o=h.tag,o===13){if(o=l(h),o!==null){r.blockedOn=o,Wt(r.priority,function(){NS(h)});return}}else if(o===31){if(o=m(h),o!==null){r.blockedOn=o,Wt(r.priority,function(){NS(h)});return}}else if(o===3&&h.stateNode.current.memoizedState.isDehydrated){r.blockedOn=h.tag===3?h.stateNode.containerInfo:null;return}}}r.blockedOn=null}function ky(r){if(r.blockedOn!==null)return!1;for(var o=r.targetContainers;0<o.length;){var h=N0(r.nativeEvent);if(h===null){h=r.nativeEvent;var v=new h.constructor(h.type,h);Xe=v,h.target.dispatchEvent(v),Xe=null}else return o=Ln(h),o!==null&&wS(o),r.blockedOn=h,!1;o.shift()}return!0}function IS(r,o,h){ky(r)&&h.delete(o)}function XP(){C0=!1,Zd!==null&&ky(Zd)&&(Zd=null),eu!==null&&ky(eu)&&(eu=null),tu!==null&&ky(tu)&&(tu=null),lf.forEach(IS),df.forEach(IS)}function Dy(r,o){r.blockedOn===o&&(r.blockedOn=null,C0||(C0=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,XP)))}var Ey=null;function _S(r){Ey!==r&&(Ey=r,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Ey===r&&(Ey=null);for(var o=0;o<r.length;o+=3){var h=r[o],v=r[o+1],A=r[o+2];if(typeof v!="function"){if(S0(v||h)===null)continue;break}var O=Ln(h);O!==null&&(r.splice(o,3),o-=3,Nx(O,{pending:!0,data:A,method:h.method,action:v},v,A))}}))}function Pm(r){function o(_t){return Dy(_t,r)}Zd!==null&&Dy(Zd,r),eu!==null&&Dy(eu,r),tu!==null&&Dy(tu,r),lf.forEach(o),df.forEach(o);for(var h=0;h<nu.length;h++){var v=nu[h];v.blockedOn===r&&(v.blockedOn=null)}for(;0<nu.length&&(h=nu[0],h.blockedOn===null);)AS(h),h.blockedOn===null&&nu.shift();if(h=(r.ownerDocument||r).$$reactFormReplay,h!=null)for(v=0;v<h.length;v+=3){var A=h[v],O=h[v+1],Ne=A[Vt]||null;if(typeof O=="function")Ne||_S(h);else if(Ne){var et=null;if(O&&O.hasAttribute("formAction")){if(A=O,Ne=O[Vt]||null)et=Ne.formAction;else if(S0(A)!==null)continue}else et=Ne.action;typeof et=="function"?h[v+1]=et:(h.splice(v,3),v-=3),_S(h)}}}function kS(){function r(O){O.canIntercept&&O.info==="react-transition"&&O.intercept({handler:function(){return new Promise(function(Ne){return A=Ne})},focusReset:"manual",scroll:"manual"})}function o(){A!==null&&(A(),A=null),v||setTimeout(h,20)}function h(){if(!v&&!navigation.transition){var O=navigation.currentEntry;O&&O.url!=null&&navigation.navigate(O.url,{state:O.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var v=!1,A=null;return navigation.addEventListener("navigate",r),navigation.addEventListener("navigatesuccess",o),navigation.addEventListener("navigateerror",o),setTimeout(h,100),function(){v=!0,navigation.removeEventListener("navigate",r),navigation.removeEventListener("navigatesuccess",o),navigation.removeEventListener("navigateerror",o),A!==null&&(A(),A=null)}}}function A0(r){this._internalRoot=r}Py.prototype.render=A0.prototype.render=function(r){var o=this._internalRoot;if(o===null)throw Error(s(409));var h=o.current,v=rc();xS(h,v,r,o,null,null)},Py.prototype.unmount=A0.prototype.unmount=function(){var r=this._internalRoot;if(r!==null){this._internalRoot=null;var o=r.containerInfo;xS(r.current,2,null,r,null,null),hy(),o[sn]=null}};function Py(r){this._internalRoot=r}Py.prototype.unstable_scheduleHydration=function(r){if(r){var o=Xt();r={blockedOn:null,target:r,priority:o};for(var h=0;h<nu.length&&o!==0&&o<nu[h].priority;h++);nu.splice(h,0,r),h===0&&AS(r)}};var DS=n.version;if(DS!=="19.2.8")throw Error(s(527,DS,"19.2.8"));ne.findDOMNode=function(r){var o=r._reactInternals;if(o===void 0)throw typeof r.render=="function"?Error(s(188)):(r=Object.keys(r).join(","),Error(s(268,r)));return r=u(o),r=r!==null?f(r):null,r=r===null?null:r.stateNode,r};var ZP={bundleType:0,version:"19.2.8",rendererPackageName:"react-dom",currentDispatcherRef:q,reconcilerVersion:"19.2.8"};
49if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Ry=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Ry.isDisabled&&Ry.supportsFiber)try{xt=Ry.inject(ZP),te=Ry}catch{}}return mf.createRoot=function(r,o){if(!i(r))throw Error(s(299));var h=!1,v="",A=O2,O=L2,Ne=B2;return o!=null&&(o.unstable_strictMode===!0&&(h=!0),o.identifierPrefix!==void 0&&(v=o.identifierPrefix),o.onUncaughtError!==void 0&&(A=o.onUncaughtError),o.onCaughtError!==void 0&&(O=o.onCaughtError),o.onRecoverableError!==void 0&&(Ne=o.onRecoverableError)),o=vS(r,1,!1,null,null,h,v,null,A,O,Ne,kS),r[sn]=o.current,o0(r),new A0(o)},mf.hydrateRoot=function(r,o,h){if(!i(r))throw Error(s(299));var v=!1,A="",O=O2,Ne=L2,et=B2,_t=null;return h!=null&&(h.unstable_strictMode===!0&&(v=!0),h.identifierPrefix!==void 0&&(A=h.identifierPrefix),h.onUncaughtError!==void 0&&(O=h.onUncaughtError),h.onCaughtError!==void 0&&(Ne=h.onCaughtError),h.onRecoverableError!==void 0&&(et=h.onRecoverableError),h.formState!==void 0&&(_t=h.formState)),o=vS(r,1,!0,o,h??null,v,A,_t,O,Ne,et,kS),o.context=bS(null),h=o.current,v=rc(),v=An(v),A=Za(v),A.callback=null,ir(h,A,v),h=v,o.current.lanes=h,we(o,h),El(o),r[sn]=o.current,o0(r),new Py(o)},mf.version="19.2.8",mf}var US;function mR(){if(US)return k0.exports;US=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),k0.exports=hR(),k0.exports}var pR=mR();const fR=Ub(pR),gR=()=>{};var zS={};/** 50 * @license 51 * Copyright 2017 Google LLC 52 * 53 * Licensed under the Apache License, Version 2.0 (the "License"); 54 * you may not use this file except in compliance with the License. 55 * You may obtain a copy of the License at 56 * 57 * http://www.apache.org/licenses/LICENSE-2.0 58 * 59 * Unless required by applicable law or agreed to in writing, software 60 * distributed under the License is distributed on an "AS IS" BASIS, 61 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 62 * See the License for the specific language governing permissions and 63 * limitations under the License. 64 */const d5={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};/** 65 * @license 66 * Copyright 2017 Google LLC 67 * 68 * Licensed under the Apache License, Version 2.0 (the "License"); 69 * you may not use this file except in compliance with the License. 70 * You may obtain a copy of the License at 71 * 72 * http://www.apache.org/licenses/LICENSE-2.0 73 * 74 * Unless required by applicable law or agreed to in writing, software 75 * distributed under the License is distributed on an "AS IS" BASIS, 76 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 77 * See the License for the specific language governing permissions and 78 * limitations under the License. 79 */const la=function(t,n){if(!t)throw Cp(n)},Cp=function(t){return new Error("Firebase Database ("+d5.SDK_VERSION+") INTERNAL ASSERT FAILED: "+t)};/** 80 * @license 81 * Copyright 2017 Google LLC 82 * 83 * Licensed under the Apache License, Version 2.0 (the "License"); 84 * you may not use this file except in compliance with the License. 85 * You may obtain a copy of the License at 86 * 87 * http://www.apache.org/licenses/LICENSE-2.0 88 * 89 * Unless required by applicable law or agreed to in writing, software 90 * distributed under the License is distributed on an "AS IS" BASIS, 91 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 92 * See the License for the specific language governing permissions and 93 * limitations under the License. 94 */const u5=function(t){const n=[];let a=0;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);i<128?n[a++]=i:i<2048?(n[a++]=i>>6|192,n[a++]=i&63|128):(i&64512)===55296&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(i=65536+((i&1023)<<10)+(t.charCodeAt(++s)&1023),n[a++]=i>>18|240,n[a++]=i>>12&63|128,n[a++]=i>>6&63|128,n[a++]=i&63|128):(n[a++]=i>>12|224,n[a++]=i>>6&63|128,n[a++]=i&63|128)}return n},yR=function(t){const n=[];let a=0,s=0;for(;a<t.length;){const i=t[a++];if(i<128)n[s++]=String.fromCharCode(i);else if(i>191&&i<224){const c=t[a++];n[s++]=String.fromCharCode((i&31)<<6|c&63)}else if(i>239&&i<365){const c=t[a++],l=t[a++],m=t[a++],d=((i&7)<<18|(c&63)<<12|(l&63)<<6|m&63)-65536;n[s++]=String.fromCharCode(55296+(d>>10)),n[s++]=String.fromCharCode(56320+(d&1023))}else{const c=t[a++],l=t[a++];n[s++]=String.fromCharCode((i&15)<<12|(c&63)<<6|l&63)}}return n.join("")},K1={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob=="function",encodeByteArray(t,n){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();const a=n?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let i=0;i<t.length;i+=3){const c=t[i],l=i+1<t.length,m=l?t[i+1]:0,d=i+2<t.length,u=d?t[i+2]:0,f=c>>2,g=(c&3)<<4|m>>4;let p=(m&15)<<2|u>>6,y=u&63;d||(y=64,l||(p=64)),s.push(a[f],a[g],a[p],a[y])}return s.join("")},encodeString(t,n){return this.HAS_NATIVE_SUPPORT&&!n?btoa(t):this.encodeByteArray(u5(t),n)},decodeString(t,n){return this.HAS_NATIVE_SUPPORT&&!n?atob(t):yR(this.decodeStringToByteArray(t,n))},decodeStringToByteArray(t,n){this.init_();const a=n?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let i=0;i<t.length;){const c=a[t.charAt(i++)],m=i<t.length?a[t.charAt(i)]:0;++i;const u=i<t.length?a[t.charAt(i)]:64;++i;const g=i<t.length?a[t.charAt(i)]:64;if(++i,c==null||m==null||u==null||g==null)throw new vR;const p=c<<2|m>>4;if(s.push(p),u!==64){const y=m<<4&240|u>>2;if(s.push(y),g!==64){const b=u<<6&192|g;s.push(b)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let t=0;t<this.ENCODED_VALS.length;t++)this.byteToCharMap_[t]=this.ENCODED_VALS.charAt(t),this.charToByteMap_[this.byteToCharMap_[t]]=t,this.byteToCharMapWebSafe_[t]=this.ENCODED_VALS_WEBSAFE.charAt(t),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[t]]=t,t>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}};
94class vR extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const h5=function(t){const n=u5(t);return K1.encodeByteArray(n,!0)},ib=function(t){return h5(t).replace(/\./g,"")},ob=function(t){try{return K1.decodeString(t,!0)}catch(n){console.error("base64Decode failed: ",n)}return null};/** 95 * @license 96 * Copyright 2017 Google LLC 97 * 98 * Licensed under the Apache License, Version 2.0 (the "License"); 99 * you may not use this file except in compliance with the License. 100 * You may obtain a copy of the License at 101 * 102 * http://www.apache.org/licenses/LICENSE-2.0 103 * 104 * Unless required by applicable law or agreed to in writing, software 105 * distributed under the License is distributed on an "AS IS" BASIS, 106 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 107 * See the License for the specific language governing permissions and 108 * limitations under the License. 109 */function bR(t){return m5(void 0,t)}function m5(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:const a=n;return new Date(a.getTime());case Object:t===void 0&&(t={});break;case Array:t=[];break;default:return n}for(const a in n)!n.hasOwnProperty(a)||!xR(a)||(t[a]=m5(t[a],n[a]));return t}function xR(t){return t!=="__proto__"}/** 110 * @license 111 * Copyright 2022 Google LLC 112 * 113 * Licensed under the Apache License, Version 2.0 (the "License"); 114 * you may not use this file except in compliance with the License. 115 * You may obtain a copy of the License at 116 * 117 * http://www.apache.org/licenses/LICENSE-2.0 118 * 119 * Unless required by applicable law or agreed to in writing, software 120 * distributed under the License is distributed on an "AS IS" BASIS, 121 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 122 * See the License for the specific language governing permissions and 123 * limitations under the License.
124 */function jR(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}/** 125 * @license 126 * Copyright 2022 Google LLC 127 * 128 * Licensed under the Apache License, Version 2.0 (the "License"); 129 * you may not use this file except in compliance with the License. 130 * You may obtain a copy of the License at 131 * 132 * http://www.apache.org/licenses/LICENSE-2.0 133 * 134 * Unless required by applicable law or agreed to in writing, software 135 * distributed under the License is distributed on an "AS IS" BASIS, 136 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 137 * See the License for the specific language governing permissions and 138 * limitations under the License. 139 */const wR=()=>jR().__FIREBASE_DEFAULTS__,NR=()=>{if(typeof process>"u"||typeof zS>"u")return;const t=zS.__FIREBASE_DEFAULTS__;if(t)return JSON.parse(t)},SR=()=>{if(typeof document>"u")return;let t;try{t=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const n=t&&ob(t[1]);return n&&JSON.parse(n)},X1=()=>{try{return gR()||wR()||NR()||SR()}catch(t){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${t}`);return}},p5=t=>{var n,a;return(a=(n=X1())==null?void 0:n.emulatorHosts)==null?void 0:a[t]}
139,CR=t=>{const n=p5(t);if(!n)return;const a=n.lastIndexOf(":");if(a<=0||a+1===n.length)throw new Error(`Invalid host ${n} with no separate hostname and port!`);const s=parseInt(n.substring(a+1),10);return n[0]==="["?[n.substring(1,a-1),s]:[n.substring(0,a),s]},f5=()=>{var t;return(t=X1())==null?void 0:t.config},g5=t=>{var n;return(n=X1())==null?void 0:n[`_${t}`]};/** 140 * @license 141 * Copyright 2017 Google LLC 142 * 143 * Licensed under the Apache License, Version 2.0 (the "License"); 144 * you may not use this file except in compliance with the License. 145 * You may obtain a copy of the License at 146 * 147 * http://www.apache.org/licenses/LICENSE-2.0 148 * 149 * Unless required by applicable law or agreed to in writing, software 150 * distributed under the License is distributed on an "AS IS" BASIS, 151 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 152 * See the License for the specific language governing permissions and 153 * limitations under the License. 154 */class Jh{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((n,a)=>{this.resolve=n,this.reject=a})}wrapCallback(n){return(a,s)=>{a?this.reject(a):this.resolve(s),typeof n=="function"&&(this.promise.catch(()=>{}),n.length===1?n(a):n(a,s))}}}/** 155 * @license 156 * Copyright 2021 Google LLC 157 * 158 * Licensed under the Apache License, Version 2.0 (the "License"); 159 * you may not use this file except in compliance with the License. 160 * You may obtain a copy of the License at 161 * 162 * http://www.apache.org/licenses/LICENSE-2.0 163 * 164 * Unless required by applicable law or agreed to in writing, software 165 * distributed under the License is distributed on an "AS IS" BASIS, 166 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 167 * See the License for the specific language governing permissions and 168 * limitations under the License. 169 */function AR(t,n){if(t.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const a={alg:"none",type:"JWT"},s=n||"demo-project",i=t.iat||0,c=t.sub||t.user_id;if(!c)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const l={iss:`https://securetoken.google.com/${s}`,aud:s,iat:i,exp:i+3600,auth_time:i,sub:c,user_id:c,firebase:{sign_in_provider:"custom",identities:{}},...t};return[ib(JSON.stringify(a)),ib(JSON.stringify(l)),""].join(".")}/** 170 * @license 171 * Copyright 2017 Google LLC 172 * 173 * Licensed under the Apache License, Version 2.0 (the "License"); 174 * you may not use this file except in compliance with the License. 175 * You may obtain a copy of the License at 176 * 177 * http://www.apache.org/licenses/LICENSE-2.0 178 * 179 * Unless required by applicable law or agreed to in writing, software 180 * distributed under the License is distributed on an "AS IS" BASIS, 181 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 182 * See the License for the specific language governing permissions and 183 * limitations under the License. 184 */function Io(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function Z1(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(Io())}function IR(){return typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"}function _R(){const t=typeof chrome=="object"?chrome.runtime:typeof browser=="object"?browser.runtime:void 0;return typeof t=="object"&&t.id!==void 0}function y5(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function kR(){const t=Io();return t.indexOf("MSIE ")>=0||t.indexOf("Trident/")>=0}function DR(){return d5.NODE_ADMIN===!0}function ER(){try{return typeof indexedDB=="object"}catch{return!1}}function PR(){return new Promise((t,n)=>{try{let a=!0;const s="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(s);i.onsuccess=()=>{i.result.close(),a||self.indexedDB.deleteDatabase(s),t(!0)},i.onupgradeneeded=()=>{a=!1},i.onerror=()=>{var c;n(((c=i.error)==null?void 0:c.message)||"")}}catch(a){n(a)}})}/** 185 * @license 186 * Copyright 2017 Google LLC 187 * 188 * Licensed under the Apache License, Version 2.0 (the "License");
189 * you may not use this file except in compliance with the License. 190 * You may obtain a copy of the License at 191 * 192 * http://www.apache.org/licenses/LICENSE-2.0 193 * 194 * Unless required by applicable law or agreed to in writing, software 195 * distributed under the License is distributed on an "AS IS" BASIS, 196 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 197 * See the License for the specific language governing permissions and 198 * limitations under the License. 199 */const RR="FirebaseError";class Yu extends Error{constructor(n,a,s){super(a),this.code=n,this.customData=s,this.name=RR,Object.setPrototypeOf(this,Yu.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Sg.prototype.create)}}class Sg{constructor(n,a,s){this.service=n,this.serviceName=a,this.errors=s}create(n,...a){const s=a[0]||{},i=`${this.service}/${n}`,c=this.errors[n],l=c?TR(c,s):"Error",m=`${this.serviceName}: ${l} (${i}).`;return new Yu(i,m,s)}}function TR(t,n){try{let a=0,s="";for(;a<t.length;){const i=t.indexOf("{$",a);if(i===-1){s+=t.substring(a);break}const c=t.indexOf("}",i+2);if(c===-1){s+=t.substring(a);break}const l=t.substring(i+2,c),m=n[l];s+=t.substring(a,i)+(m!=null?String(m):`<${l}?>`),a=c+1}return s}catch{return t}}/** 200 * @license 201 * Copyright 2017 Google LLC 202 * 203 * Licensed under the Apache License, Version 2.0 (the "License"); 204 * you may not use this file except in compliance with the License. 205 * You may obtain a copy of the License at 206 * 207 * http://www.apache.org/licenses/LICENSE-2.0 208 * 209 * Unless required by applicable law or agreed to in writing, software 210 * distributed under the License is distributed on an "AS IS" BASIS, 211 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 212 * See the License for the specific language governing permissions and 213 * limitations under the License. 214 */function ag(t){return JSON.parse(t)}function Ri(t){return JSON.stringify(t)}/** 215 * @license 216 * Copyright 2017 Google LLC 217 * 218 * Licensed under the Apache License, Version 2.0 (the "License"); 219 * you may not use this file except in compliance with the License. 220 * You may obtain a copy of the License at 221 * 222 * http://www.apache.org/licenses/LICENSE-2.0 223 * 224 * Unless required by applicable law or agreed to in writing, software 225 * distributed under the License is distributed on an "AS IS" BASIS, 226 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 227 * See the License for the specific language governing permissions and 228 * limitations under the License. 229 */const v5=function(t){let n={},a={},s={},i="";try{const c=t.split(".");n=ag(ob(c[0])||""),a=ag(ob(c[1])||""),i=c[2],s=a.d||{},delete a.d}catch{}return{header:n,claims:a,data:s,signature:i}},MR=function(t){const n=v5(t),a=n.claims;return!!a&&typeof a=="object"&&a.hasOwnProperty("iat")},$R=function(t){const n=v5(t).claims;return typeof n=="object"&&n.admin===!0};/** 230 * @license 231 * Copyright 2017 Google LLC 232 * 233 * Licensed under the Apache License, Version 2.0 (the "License"); 234 * you may not use this file except in compliance with the License. 235 * You may obtain a copy of the License at 236 * 237 * http://www.apache.org/licenses/LICENSE-2.0 238 * 239 * Unless required by applicable law or agreed to in writing, software 240 * distributed under the License is distributed on an "AS IS" BASIS, 241 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 242 * See the License for the specific language governing permissions and 243 * limitations under the License. 244 */function pl(t,n){return Object.prototype.hasOwnProperty.call(t,n)}function Lh(t,n){if(Object.prototype.hasOwnProperty.call(t,n))return t[n]}function Yj(t){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n))return!1;return!0}function cb(t,n,a){const s={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(s[i]=n.call(a,t[i],i,t));return s}function Bh(t,n){if(t===n)return!0;const a=Object.keys(t),s=Object.keys(n);for(const i of a){if(!s.includes(i))return!1;const c=t[i],l=n[i];if(qS(c)&&qS(l)){if(!Bh(c,l))return!1}else if(c!==l)return!1}for(const i of s)if(!a.includes(i))return!1;return!0}function qS(t){return t!==null&&typeof t=="object"}/** 245 * @license 246 * Copyright 2017 Google LLC 247 * 248 * Licensed under the Apache License, Version 2.0 (the "License");
249 * you may not use this file except in compliance with the License. 250 * You may obtain a copy of the License at 251 * 252 * http://www.apache.org/licenses/LICENSE-2.0 253 * 254 * Unless required by applicable law or agreed to in writing, software 255 * distributed under the License is distributed on an "AS IS" BASIS, 256 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 257 * See the License for the specific language governing permissions and 258 * limitations under the License. 259 */function Ap(t){const n=[];for(const[a,s]of Object.entries(t))Array.isArray(s)?s.forEach(i=>{n.push(encodeURIComponent(a)+"="+encodeURIComponent(i))}):n.push(encodeURIComponent(a)+"="+encodeURIComponent(s));return n.length?"&"+n.join("&"):""}function Bf(t){const n={};return t.replace(/^\?/,"").split("&").forEach(s=>{if(s){const[i,c]=s.split("=");n[decodeURIComponent(i)]=decodeURIComponent(c)}}),n}function Ff(t){const n=t.indexOf("?");if(!n)return"";const a=t.indexOf("#",n);return t.substring(n,a>0?a:void 0)}/** 260 * @license 261 * Copyright 2017 Google LLC 262 * 263 * Licensed under the Apache License, Version 2.0 (the "License"); 264 * you may not use this file except in compliance with the License. 265 * You may obtain a copy of the License at 266 * 267 * http://www.apache.org/licenses/LICENSE-2.0 268 * 269 * Unless required by applicable law or agreed to in writing, software 270 * distributed under the License is distributed on an "AS IS" BASIS, 271 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 272 * See the License for the specific language governing permissions and 273 * limitations under the License. 274 */class OR{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,this.pad_[0]=128;for(let n=1;n<this.blockSize;++n)this.pad_[n]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,a){a||(a=0);const s=this.W_;if(typeof n=="string")for(let g=0;g<16;g++)s[g]=n.charCodeAt(a)<<24|n.charCodeAt(a+1)<<16|n.charCodeAt(a+2)<<8|n.charCodeAt(a+3),a+=4;else for(let g=0;g<16;g++)s[g]=n[a]<<24|n[a+1]<<16|n[a+2]<<8|n[a+3],a+=4;for(let g=16;g<80;g++){const p=s[g-3]^s[g-8]^s[g-14]^s[g-16];s[g]=(p<<1|p>>>31)&4294967295}let i=this.chain_[0],c=this.chain_[1],l=this.chain_[2],m=this.chain_[3],d=this.chain_[4],u,f;for(let g=0;g<80;g++){g<40?g<20?(u=m^c&(l^m),f=1518500249):(u=c^l^m,f=1859775393):g<60?(u=c&l|m&(c|l),f=2400959708):(u=c^l^m,f=3395469782);const p=(i<<5|i>>>27)+u+d+f+s[g]&4294967295;d=m,m=l,l=(c<<30|c>>>2)&4294967295,c=i,i=p}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+c&4294967295,this.chain_[2]=this.chain_[2]+l&4294967295,this.chain_[3]=this.chain_[3]+m&4294967295,this.chain_[4]=this.chain_[4]+d&4294967295}update(n,a){if(n==null)return;a===void 0&&(a=n.length);const s=a-this.blockSize;let i=0;const c=this.buf_;let l=this.inbuf_;for(;i<a;){if(l===0)for(;i<=s;)this.compress_(n,i),i+=this.blockSize;if(typeof n=="string"){for(;i<a;)if(c[l]=n.charCodeAt(i),++l,++i,l===this.blockSize){this.compress_(c),l=0;break}}else for(;i<a;)if(c[l]=n[i],++l,++i,l===this.blockSize){this.compress_(c),l=0;break}}this.inbuf_=l,this.total_+=a}digest(){const n=[];let a=this.total_*8;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let i=this.blockSize-1;i>=56;i--)this.buf_[i]=a&255,a/=256;this.compress_(this.buf_);let s=0;for(let i=0;i<5;i++)for(let c=24;c>=0;c-=8)n[s]=this.chain_[i]>>c&255,++s;return n}}function LR(t,n){const a=new BR(t,n);return a.subscribe.bind(a)}class BR{constructor(n,a){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=a,this.task.then(()=>{n(this)}).catch(s=>{this.error(s)})}next(n){this.forEachObserver(a=>{a.next(n)})}error(n){this.forEachObserver(a=>{a.error(n)}),this.close(n)}complete(){this.forEachObserver(n=>{n.complete()}),this.close()}subscribe(n,a,s){let i;if(n===void 0&&a===void 0&&s===void 0)throw new Error("Missing Observer.");FR(n,["next","error","complete"])?i=n:i={next:n,error:a,complete:s},i.next===void 0&&(i.next=R0),i.error===void 0&&(i.error=R0),i.complete===void 0&&(i.complete=R0);const c=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch{}}),this.observers.push(i),c}unsubscribeOne(n){this.observers===void 0||this.observers[n]===void 0||(delete this.observers[n],this.observerCount-=1,this.observerCount===0&&this.onNoObservers!==void 0&&this.onNoObservers(this))}forEachObserver(n){if(!this.finalized)for(let a=0;a<this.observers.length;a++)this.sendOne(a,n)}sendOne(n,a){this.task.then(()=>
274{if(this.observers!==void 0&&this.observers[n]!==void 0)try{a(this.observers[n])}catch(s){typeof console<"u"&&console.error&&console.error(s)}})}close(n){this.finalized||(this.finalized=!0,n!==void 0&&(this.finalError=n),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function FR(t,n){if(typeof t!="object"||t===null)return!1;for(const a of n)if(a in t&&typeof t[a]=="function")return!0;return!1}function R0(){}function qb(t,n){return`${t} failed: ${n} argument `}/** 275 * @license 276 * Copyright 2017 Google LLC 277 * 278 * Licensed under the Apache License, Version 2.0 (the "License"); 279 * you may not use this file except in compliance with the License. 280 * You may obtain a copy of the License at 281 * 282 * http://www.apache.org/licenses/LICENSE-2.0 283 * 284 * Unless required by applicable law or agreed to in writing, software 285 * distributed under the License is distributed on an "AS IS" BASIS, 286 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 287 * See the License for the specific language governing permissions and 288 * limitations under the License. 289 */const UR=function(t){const n=[];let a=0;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s);if(i>=55296&&i<=56319){const c=i-55296;s++,la(s<t.length,"Surrogate pair missing trail surrogate.");const l=t.charCodeAt(s)-56320;i=65536+(c<<10)+l}i<128?n[a++]=i:i<2048?(n[a++]=i>>6|192,n[a++]=i&63|128):i<65536?(n[a++]=i>>12|224,n[a++]=i>>6&63|128,n[a++]=i&63|128):(n[a++]=i>>18|240,n[a++]=i>>12&63|128,n[a++]=i>>6&63|128,n[a++]=i&63|128)}return n},Vb=function(t){let n=0;for(let a=0;a<t.length;a++){const s=t.charCodeAt(a);s<128?n++:s<2048?n+=2:s>=55296&&s<=56319?(n+=4,a++):n+=3}return n};/** 290 * @license 291 * Copyright 2021 Google LLC 292 * 293 * Licensed under the Apache License, Version 2.0 (the "License"); 294 * you may not use this file except in compliance with the License. 295 * You may obtain a copy of the License at 296 * 297 * http://www.apache.org/licenses/LICENSE-2.0 298 * 299 * Unless required by applicable law or agreed to in writing, software 300 * distributed under the License is distributed on an "AS IS" BASIS, 301 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 302 * See the License for the specific language governing permissions and 303 * limitations under the License. 304 */function Jr(t){return t&&t._delegate?t._delegate:t}/** 305 * @license 306 * Copyright 2025 Google LLC 307 * 308 * Licensed under the Apache License, Version 2.0 (the "License"); 309 * you may not use this file except in compliance with the License. 310 * You may obtain a copy of the License at 311 * 312 * http://www.apache.org/licenses/LICENSE-2.0 313 * 314 * Unless required by applicable law or agreed to in writing, software 315 * distributed under the License is distributed on an "AS IS" BASIS, 316 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 317 * See the License for the specific language governing permissions and 318 * limitations under the License. 319 */function Cg(t){try{return(t.startsWith("http://")||t.startsWith("https://")?new URL(t).hostname:t).endsWith(".cloudworkstations.dev")}catch{return!1}}async function b5(t){return(await fetch(t,{credentials:"include"})).ok}class Fh{constructor(n,a,s){this.name=n,this.instanceFactory=a,this.type=s,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(n){return this.instantiationMode=n,this}setMultipleInstances(n){return this.multipleInstances=n,this}setServiceProps(n){return this.serviceProps=n,this}setInstanceCreatedCallback(n){return this.onInstanceCreated=n,this}}/** 320 * @license 321 * Copyright 2019 Google LLC 322 * 323 * Licensed under the Apache License, Version 2.0 (the "License"); 324 * you may not use this file except in compliance with the License. 325 * You may obtain a copy of the License at 326 * 327 * http://www.apache.org/licenses/LICENSE-2.0 328 * 329 * Unless required by applicable law or agreed to in writing, software 330 * distributed under the License is distributed on an "AS IS" BASIS, 331 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 332 * See the License for the specific language governing permissions and 333 * limitations under the License. 334 */const bh="[DEFAULT]";/** 335 * @license 336 * Copyright 2019 Google LLC 337 * 338 * Licensed under the Apache License, Version 2.0 (the "License");
339 * you may not use this file except in compliance with the License. 340 * You may obtain a copy of the License at 341 * 342 * http://www.apache.org/licenses/LICENSE-2.0 343 * 344 * Unless required by applicable law or agreed to in writing, software 345 * distributed under the License is distributed on an "AS IS" BASIS, 346 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 347 * See the License for the specific language governing permissions and 348 * limitations under the License. 349 */class zR{constructor(n,a){this.name=n,this.container=a,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(n){const a=this.normalizeInstanceIdentifier(n);if(!this.instancesDeferred.has(a)){const s=new Jh;if(this.instancesDeferred.set(a,s),this.isInitialized(a)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:a});i&&s.resolve(i)}catch{}}return this.instancesDeferred.get(a).promise}getImmediate(n){const a=this.normalizeInstanceIdentifier(n==null?void 0:n.identifier),s=(n==null?void 0:n.optional)??!1;if(this.isInitialized(a)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:a})}catch(i){if(s)return null;throw i}else{if(s)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(n){if(n.name!==this.name)throw Error(`Mismatching Component ${n.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=n,!!this.shouldAutoInitialize()){if(VR(n))try{this.getOrInitializeService({instanceIdentifier:bh})}catch{}for(const[a,s]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(a);try{const c=this.getOrInitializeService({instanceIdentifier:i});s.resolve(c)}catch{}}}}clearInstance(n=bh){this.instancesDeferred.delete(n),this.instancesOptions.delete(n),this.instances.delete(n)}async delete(){const n=Array.from(this.instances.values());await Promise.all([...n.filter(a=>"INTERNAL"in a).map(a=>a.INTERNAL.delete()),...n.filter(a=>"_delete"in a).map(a=>a._delete())])}isComponentSet(){return this.component!=null}isInitialized(n=bh){return this.instances.has(n)}getOptions(n=bh){return this.instancesOptions.get(n)||{}}initialize(n={}){const{options:a={}}=n,s=this.normalizeInstanceIdentifier(n.instanceIdentifier);if(this.isInitialized(s))throw Error(`${this.name}(${s}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:s,options:a});for(const[c,l]of this.instancesDeferred.entries()){const m=this.normalizeInstanceIdentifier(c);s===m&&l.resolve(i)}return i}onInit(n,a){const s=this.normalizeInstanceIdentifier(a),i=this.onInitCallbacks.get(s)??new Set;i.add(n),this.onInitCallbacks.set(s,i);const c=this.instances.get(s);return c&&n(c,s),()=>{i.delete(n)}}invokeOnInitCallbacks(n,a){const s=this.onInitCallbacks.get(a);if(s)for(const i of s)try{i(n,a)}catch{}}getOrInitializeService({instanceIdentifier:n,options:a={}}){let s=this.instances.get(n);if(!s&&this.component&&(s=this.component.instanceFactory(this.container,{instanceIdentifier:qR(n),options:a}),this.instances.set(n,s),this.instancesOptions.set(n,a),this.invokeOnInitCallbacks(s,n),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,n,s)}catch{}return s||null}normalizeInstanceIdentifier(n=bh){return this.component?this.component.multipleInstances?n:bh:n}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function qR(t){return t===bh?void 0:t}function VR(t){return t.instantiationMode==="EAGER"}/** 350 * @license 351 * Copyright 2019 Google LLC 352 * 353 * Licensed under the Apache License, Version 2.0 (the "License"); 354 * you may not use this file except in compliance with the License. 355 * You may obtain a copy of the License at 356 * 357 * http://www.apache.org/licenses/LICENSE-2.0 358 * 359 * Unless required by applicable law or agreed to in writing, softw
359are 360 * distributed under the License is distributed on an "AS IS" BASIS, 361 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 362 * See the License for the specific language governing permissions and 363 * limitations under the License. 364 */class HR{constructor(n){this.name=n,this.providers=new Map}addComponent(n){const a=this.getProvider(n.name);if(a.isComponentSet())throw new Error(`Component ${n.name} has already been registered with ${this.name}`);a.setComponent(n)}addOrOverwriteComponent(n){this.getProvider(n.name).isComponentSet()&&this.providers.delete(n.name),this.addComponent(n)}getProvider(n){if(this.providers.has(n))return this.providers.get(n);const a=new zR(n,this);return this.providers.set(n,a),a}getProviders(){return Array.from(this.providers.values())}}/** 365 * @license 366 * Copyright 2017 Google LLC 367 * 368 * Licensed under the Apache License, Version 2.0 (the "License"); 369 * you may not use this file except in compliance with the License. 370 * You may obtain a copy of the License at 371 * 372 * http://www.apache.org/licenses/LICENSE-2.0 373 * 374 * Unless required by applicable law or agreed to in writing, software 375 * distributed under the License is distributed on an "AS IS" BASIS, 376 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 377 * See the License for the specific language governing permissions and 378 * limitations under the License. 379 */var br;(function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"})(br||(br={}));const WR={debug:br.DEBUG,verbose:br.VERBOSE,info:br.INFO,warn:br.WARN,error:br.ERROR,silent:br.SILENT},GR=br.INFO,YR={[br.DEBUG]:"log",[br.VERBOSE]:"log",[br.INFO]:"info",[br.WARN]:"warn",[br.ERROR]:"error"},QR=(t,n,...a)=>{if(n<t.logLevel)return;const s=new Date().toISOString(),i=YR[n];if(i)console[i](`[${s}] ${t.name}:`,...a);else throw new Error(`Attempted to log a message with an invalid logType (value: ${n})`)};class ew{constructor(n){this.name=n,this._logLevel=GR,this._logHandler=QR,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(n){if(!(n in br))throw new TypeError(`Invalid value "${n}" assigned to \`logLevel\``);this._logLevel=n}setLogLevel(n){this._logLevel=typeof n=="string"?WR[n]:n}get logHandler(){return this._logHandler}set logHandler(n){if(typeof n!="function")throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=n}get userLogHandler(){return this._userLogHandler}set userLogHandler(n){this._userLogHandler=n}debug(...n){this._userLogHandler&&this._userLogHandler(this,br.DEBUG,...n),this._logHandler(this,br.DEBUG,...n)}log(...n){this._userLogHandler&&this._userLogHandler(this,br.VERBOSE,...n),this._logHandler(this,br.VERBOSE,...n)}info(...n){this._userLogHandler&&this._userLogHandler(this,br.INFO,...n),this._logHandler(this,br.INFO,...n)}warn(...n){this._userLogHandler&&this._userLogHandler(this,br.WARN,...n
vendor: 4,311 bytes, lines 379-398
379),this._logHandler(this,br.WARN,...n)}error(...n){this._userLogHandler&&this._userLogHandler(this,br.ERROR,...n),this._logHandler(this,br.ERROR,...n)}}const JR=(t,n)=>n.some(a=>t instanceof a);let VS,HS;function KR(){return VS||(VS=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function XR(){return HS||(HS=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const x5=new WeakMap,Qj=new WeakMap,j5=new WeakMap,T0=new WeakMap,tw=new WeakMap;function ZR(t){const n=new Promise((a,s)=>{const i=()=>{t.removeEventListener("success",c),t.removeEventListener("error",l)},c=()=>{a(Du(t.result)),i()},l=()=>{s(t.error),i()};t.addEventListener("success",c),t.addEventListener("error",l)});return n.then(a=>{a instanceof IDBCursor&&x5.set(a,t)}).catch(()=>{}),tw.set(n,t),n}function eT(t){if(Qj.has(t))return;const n=new Promise((a,s)=>{const i=()=>{t.removeEventListener("complete",c),t.removeEventListener("error",l),t.removeEventListener("abort",l)},c=()=>{a(),i()},l=()=>{s(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",c),t.addEventListener("error",l),t.addEventListener("abort",l)});Qj.set(t,n)}let Jj={get(t,n,a){if(t instanceof IDBTransaction){if(n==="done")return Qj.get(t);if(n==="objectStoreNames")return t.objectStoreNames||j5.get(t);if(n==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return Du(t[n])},set(t,n,a){return t[n]=a,!0},has(t,n){return t instanceof IDBTransaction&&(n==="done"||n==="store")?!0:n in t}};function tT(t){Jj=t(Jj)}function nT(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(n,...a){const s=t.call(M0(this),n,...a);return j5.set(s,n.sort?n.sort():[n]),Du(s)}:XR().includes(t)?function(...n){return t.apply(M0(this),n),Du(x5.get(this))}:function(...n){return Du(t.apply(M0(this),n))}}function aT(t){return typeof t=="function"?nT(t):(t instanceof IDBTransaction&&eT(t),JR(t,KR())?new Proxy(t,Jj):t)}function Du(t){if(t instanceof IDBRequest)return ZR(t);if(T0.has(t))return T0.get(t);const n=aT(t);return n!==t&&(T0.set(t,n),tw.set(n,t)),n}const M0=t=>tw.get(t);function sT(t,n,{blocked:a,upgrade:s,blocking:i,terminated:c}={}){const l=indexedDB.open(t,n),m=Du(l);return s&&l.addEventListener("upgradeneeded",d=>{s(Du(l.result),d.oldVersion,d.newVersion,Du(l.transaction),d)}),a&&l.addEventListener("blocked",d=>a(d.oldVersion,d.newVersion,d)),m.then(d=>{c&&d.addEventListener("close",()=>c()),i&&d.addEventListener("versionchange",u=>i(u.oldVersion,u.newVersion,u))}).catch(()=>{}),m}const rT=["get","getKey","getAll","getAllKeys","count"],iT=["put","add","delete","clear"],$0=new Map;function WS(t,n){if(!(t instanceof IDBDatabase&&!(n in t)&&typeof n=="string"))return;if($0.get(n))return $0.get(n);const a=n.replace(/FromIndex$/,""),s=n!==a,i=iT.includes(a);if(!(a in(s?IDBIndex:IDBObjectStore).prototype)||!(i||rT.includes(a)))return;const c=async function(l,...m){const d=this.transaction(l,i?"readwrite":"readonly");let u=d.store;return s&&(u=u.index(m.shift())),(await Promise.all([u[a](...m),i&&d.done]))[0]};return $0.set(n,c),c}tT(t=>({...t,get:(n,a,s)=>WS(n,a)||t.get(n,a,s),has:(n,a)=>!!WS(n,a)||t.has(n,a)}));/** 380 * @license 381 * Copyright 2019 Google LLC 382 * 383 * Licensed under the Apache License, Version 2.0 (the "License"); 384 * you may not use this file except in compliance with the License. 385 * You may obtain a copy of the License at 386 * 387 * http://www.apache.org/licenses/LICENSE-2.0 388 * 389 * Unless required by applicable law or agreed to in writing, software 390 * distributed under the License is distributed on an "AS IS" BASIS, 391 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 392 * See the License for the specific language governing permissions and 393 * limitations under the License. 394 */class oT{constructor(n){this.container=n}getPlatformInfoString(){return this.container.getProviders().map(a=>{if(cT(a)){const s=a.getImmediate();return`${s.library}/${s.version}`}else return null}).filter(a=>a).join(" ")}}function cT(t){const n=t.getComponent();return(n==null?void 0:n.type)==="VERSION"}const Kj="@firebase/app",GS="0.16.1";/** 395 * @license 396 * Copyright 2019 Google LLC 397 * 398 * Licensed under the Apache License, Version 2.0 (the "License");
399 * you may not use this file except in compliance with the License. 400 * You may obtain a copy of the License at 401 * 402 * http://www.apache.org/licenses/LICENSE-2.0 403 * 404 * Unless required by applicable law or agreed to in writing, software 405 * distributed under the License is distributed on an "AS IS" BASIS, 406 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 407 * See the License for the specific language governing permissions and 408 * limitations under the License. 409 */const Ed=new ew("@firebase/app"),lT="@firebase/app-compat",dT="@firebase/analytics-compat",uT="@firebase/analytics",hT="@firebase/app-check-compat",mT="@firebase/app-check",pT="@firebase/auth",fT="@firebase/auth-compat",gT="@firebase/database",yT="@firebase/data-connect",vT="@firebase/database-compat",bT="@firebase/functions",xT="@firebase/functions-compat",jT="@firebase/installations",wT="@firebase/installations-compat",NT="@firebase/messaging",ST="@firebase/messaging-compat",CT="@firebase/performance",AT="@firebase/performance-compat",IT="@firebase/remote-config",_T="@firebase/remote-config-compat",kT="@firebase/storage",DT="@firebase/storage-compat",ET="@firebase/firestore",PT="@firebase/ai",RT="@firebase/firestore-compat",TT="firebase",MT="12.18.0";/** 410 * @license 411 * Copyright 2019 Google LLC 412 * 413 * Licensed under the Apache License, Version 2.0 (the "License"); 414 * you may not use this file except in compliance with the License. 415 * You may obtain a copy of the License at 416 * 417 * http://www.apache.org/licenses/LICENSE-2.0 418 * 419 * Unless required by applicable law or agreed to in writing, software 420 * distributed under the License is distributed on an "AS IS" BASIS, 421 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 422 * See the License for the specific language governing permissions and 423 * limitations under the License. 424 */const Xj="[DEFAULT]",$T={[Kj]:"fire-core",[lT]:"fire-core-compat",[uT]:"fire-analytics",[dT]:"fire-analytics-compat",[mT]:"fire-app-check",[hT]:"fire-app-check-compat",[pT]:"fire-auth",[fT]:"fire-auth-compat",[gT]:"fire-rtdb",[yT]:"fire-data-connect",[vT]:"fire-rtdb-compat",[bT]:"fire-fn",[xT]:"fire-fn-compat",[jT]:"fire-iid",[wT]:"fire-iid-compat",[NT]:"fire-fcm",[ST]:"fire-fcm-compat",[CT]:"fire-perf",[AT]:"fire-perf-compat",[IT]:"fire-rc",[_T]:"fire-rc-compat",[kT]:"fire-gcs",[DT]:"fire-gcs-compat",[ET]:"fire-fst",[RT]:"fire-fst-compat",[PT]:"fire-vertex","fire-js":"fire-js",[TT]:"fire-js-all"};/** 425 * @license 426 * Copyright 2019 Google LLC 427 * 428 * Licensed under the Apache License, Version 2.0 (the "License"); 429 * you may not use this file except in compliance with the License. 430 * You may obtain a copy of the License at 431 * 432 * http://www.apache.org/licenses/LICENSE-2.0 433 * 434 * Unless required by applicable law or agreed to in writing, software 435 * distributed under the License is distributed on an "AS IS" BASIS, 436 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 437 * See the License for the specific language governing permissions and 438 * limitations under the License. 439 */const mp=new Map,Zj=new Map,e1=new Map;function YS(t,n){try{t.container.addComponent(n)}catch(a){Ed.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,a)}}function pp(t){const n=t.name;if(e1.has(n))return Ed.debug(`There were multiple attempts to register component ${n}.`),!1;e1.set(n,t);for(const a of mp.values())YS(a,t);for(const a of Zj.values())YS(a,t);return!0}function nw(t,n){const a=t.container.getProvider("heartbeat").getImmediate({optional:!0});return a&&a.triggerHeartbeat(),t.container.getProvider(n)}function Tc(t){return t==null?!1:t.settings!==void 0}/** 440 * @license 441 * Copyright 2019 Google LLC 442 * 443 * Licensed under the Apache License, Version 2.0 (the "License"); 444 * you may not use this file except in compliance with the License. 445 * You may obtain a copy of the License at 446 * 447 * http://www.apache.org/licenses/LICENSE-2.0 448 * 449 * Unless required by applicable law or agreed to in writing, software 450 * distributed under the License is distributed on an "AS IS" BASIS, 451 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 452 * See the License for the specific language governing permissions and 453 * limitations under the License. 454 */const OT={"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different {$mismatchedParam}. Existing: '{$oldValue}'. New: '{$newValue}'.","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invali
454d-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},bd=new Sg("app","Firebase",OT);/** 455 * @license 456 * Copyright 2019 Google LLC 457 * 458 * Licensed under the Apache License, Version 2.0 (the "License"); 459 * you may not use this file except in compliance with the License. 460 * You may obtain a copy of the License at 461 * 462 * http://www.apache.org/licenses/LICENSE-2.0 463 * 464 * Unless required by applicable law or agreed to in writing, software 465 * distributed under the License is distributed on an "AS IS" BASIS, 466 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 467 * See the License for the specific language governing permissions and 468 * limitations under the License. 469 */class LT{constructor(n,a,s){this._isDeleted=!1,this._options={...n},this._config={...a},this._name=a.name,this._automaticDataCollectionEnabled=a.automaticDataCollectionEnabled,this._container=s,this.container.addComponent(new Fh("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(n){this.checkDestroyed(),this._automaticDataCollectionEnabled=n}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(n){this._isDeleted=n}checkDestroyed(){if(this.isDeleted)throw bd.create("app-deleted",{appName:this._name})}}/** 470 * @license 471 * Copyright 2019 Google LLC 472 * 473 * Licensed under the Apache License, Version 2.0 (the "License"); 474 * you may not use this file except in compliance with the License. 475 * You may obtain a copy of the License at 476 * 477 * http://www.apache.org/licenses/LICENSE-2.0 478 * 479 * Unless required by applicable law or agreed to in writing, software 480 * distributed under the License is distributed on an "AS IS" BASIS, 481 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 482 * See the License for the specific language governing permissions and 483 * limitations under the License. 484 */const Ip=MT;function aw(t,n={}){let a=t;typeof n!="object"&&(n={name:n});const s={name:Xj,automaticDataCollectionEnabled:!0,...n},i=s.name;if(typeof i!="string"||!i)throw bd.create("bad-app-name",{appName:String(i)});if(a||(a=f5()),!a)throw bd.create("no-options");const c=mp.get(i);if(c)if(Bh(a,c.options)){if(Bh(s,c.config))return c;throw bd.create("duplicate-app",{appName:i,mismatchedParam:"config",oldValue:JSON.stringify(c.config),newValue:JSON.stringify(s)})}else throw bd.create("duplicate-app",{appName:i,mismatchedParam:"options",oldValue:JSON.stringify(c.options),newValue:JSON.stringify(a)});const l=new HR(i);for(const d of e1.values())l.addComponent(d);const m=new LT(a,s,l);return mp.set(i,m),m}function w5(t=Xj){const n=mp.get(t);if(!n&&t===Xj&&f5())return aw();if(!n)throw bd.create("no-app",{appName:t});return n}async function QS(t){let n=!1;const a=t.name;mp.has(a)?(n=!0,mp.delete(a)):Zj.has(a)&&t.decRefCount()<=0&&(Zj.delete(a),n=!0),n&&(await Promise.all(t.container.getProviders().map(s=>s.delete())),t.isDeleted=!0)}function Eu(t,n,a){let s=$T[t]??t;a&&(s+=`-${a}`);const i=s.match(/\s|\//),c=n.match(/\s|\//);if(i||c){const l=[`Unable to register library "${s}" with version "${n}":`];i&&l.push(`library name "${s}" contains illegal characters (whitespace or "/")`),i&&c&&l.push("and"),c&&l.push(`version name "${n}" contains illegal characters (whitespace or "/")`),Ed.warn(l.join(" "));return}pp(new Fh(`${s}-version`,()=>({library:s,version:n}),"VERSION"))}/** 485 * @license 486 * Copyright 2021 Google LLC 487 * 488 * Licensed under the Apache License, Version 2.0 (the "License");
489 * you may not use this file except in compliance with the License. 490 * You may obtain a copy of the License at 491 * 492 * http://www.apache.org/licenses/LICENSE-2.0 493 * 494 * Unless required by applicable law or agreed to in writing, software 495 * distributed under the License is distributed on an "AS IS" BASIS, 496 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 497 * See the License for the specific language governing permissions and 498 * limitations under the License. 499 */const BT="firebase-heartbeat-database",FT=1,sg="firebase-heartbeat-store";let O0=null;function N5(){return O0||(O0=sT(BT,FT,{upgrade:(t,n)=>{switch(n){case 0:try{t.createObjectStore(sg)}catch(a){console.warn(a)}}}}).catch(t=>{throw bd.create("idb-open",{originalErrorMessage:t.message})})),O0}async function UT(t){try{const a=(await N5()).transaction(sg),s=await a.objectStore(sg).get(S5(t));return await a.done,s}catch(n){if(n instanceof Yu)Ed.warn(n.message);else{const a=bd.create("idb-get",{originalErrorMessage:n==null?void 0:n.message});Ed.warn(a.message)}}}async function JS(t,n){try{const s=(await N5()).transaction(sg,"readwrite");await s.objectStore(sg).put(n,S5(t)),await s.done}catch(a){if(a instanceof Yu)Ed.warn(a.message);else{const s=bd.create("idb-set",{originalErrorMessage:a==null?void 0:a.message});Ed.warn(s.message)}}}function S5(t){return`${t.name}!${t.options.appId}`}/** 500 * @license 501 * Copyright 2021 Google LLC 502 * 503 * Licensed under the Apache License, Version 2.0 (the "License"); 504 * you may not use this file except in compliance with the License. 505 * You may obtain a copy of the License at 506 * 507 * http://www.apache.org/licenses/LICENSE-2.0 508 * 509 * Unless required by applicable law or agreed to in writing, software 510 * distributed under the License is distributed on an "AS IS" BASIS, 511 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 512 * See the License for the specific language governing permissions and 513 * limitations under the License. 514 */const zT=1024,qT=30;class VT{constructor(n){this.container=n,this._heartbeatsCache=null;const a=this.container.getProvider("app").getImmediate();this._storage=new WT(a),this._heartbeatsCachePromise=this._storage.read().then(s=>(this._heartbeatsCache=s,s))}async triggerHeartbeat(){var n,a;try{const i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),c=KS();if(((n=this._heartbeatsCache)==null?void 0:n.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((a=this._heartbeatsCache)==null?void 0:a.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===c||this._heartbeatsCache.heartbeats.some(l=>l.date===c))return;if(this._heartbeatsCache.heartbeats.push({date:c,agent:i}),this._heartbeatsCache.heartbeats.length>qT){const l=GT(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(l,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(s){Ed.warn(s)}}async getHeartbeatsHeader(){var n;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((n=this._heartbeatsCache)==null?void 0:n.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const a=KS(),{heartbeatsToSend:s,unsentEntries:i}=HT(this._heartbeatsCache.heartbeats),c=ib(JSON.stringify({version:2,heartbeats:s}));return this._heartbeatsCache.lastSentHeartbeatDate=a,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),c}catch(a){return Ed.warn(a),""}}}function KS(){return new Date().toISOString().substring(0,10)}function HT(t,n=zT){const a=[];let s=t.slice();for(const i of t){const c=a.find(l=>l.agent===i.agent);if(c){if(c.dates.push(i.date),XS(a)>n){c.dates.pop();break}}else if(a.push({agent:i.agent,dates:[i.date]}),XS(a)>n){a.pop();break}s=s.slice(1)}return{heartbeatsToSend:a,unsentEntries:s}}class WT{constructor(n){this.app=n,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return ER()?PR().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const a=await UT(this.app);return a!=null&&a.heartbeats?a:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(n){if(await this._canUseIndexedDBPromise){const s=await this.read();return JS(this.app,{lastSentHeartbeatDate:n.lastSentHeartbeatDate??s.lastSentHeartbeatDate,heartbeats:n.heartbeats})}else return}async add(n){if(await this._canUseIndexedDBPromise){const s=await this.read();return JS(this.app,{lastSentHeartbeatDate:n.lastSentHeartbeatDate??s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...n.heartbeats]})}else return}}function XS(t){return ib(JSON.stringify({version:2,heartbeats:t})).length}function GT(t){if(t.length===0)return-1;let n=0,a=t[0].date;for(let s=1;s<t.length;s++)t[s].date<a&&(a=t[s].date,n=s);return n}/** 515 * @license 516 * Copyright 2019 Google LLC 517 * 518 * Licensed under the Apache License, Version 2.0 (the "License");
519 * you may not use this file except in compliance with the License. 520 * You may obtain a copy of the License at 521 * 522 * http://www.apache.org/licenses/LICENSE-2.0 523 * 524 * Unless required by applicable law or agreed to in writing, software 525 * distributed under the License is distributed on an "AS IS" BASIS, 526 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 527 * See the License for the specific language governing permissions and 528 * limitations under the License. 529 */function YT(t){pp(new Fh("platform-logger",n=>new oT(n),"PRIVATE")),pp(new Fh("heartbeat",n=>new VT(n),"PRIVATE")),Eu(Kj,GS,t),Eu(Kj,GS,"esm2020"),Eu("fire-js","")}/** 530 * @license 531 * Copyright 2019 Google LLC 532 * 533 * Licensed under the Apache License, Version 2.0 (the "License"); 534 * you may not use this file except in compliance with the License. 535 * You may obtain a copy of the License at 536 * 537 * http://www.apache.org/licenses/LICENSE-2.0 538 * 539 * Unless required by applicable law or agreed to in writing, software 540 * distributed under the License is distributed on an "AS IS" BASIS, 541 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 542 * See the License for the specific language governing permissions and 543 * limitations under the License. 544 */YT("");function C5(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}const QT=C5,A5=new Sg("auth","Firebase",C5());/** 545 * @license 546 * Copyright 2020 Google LLC 547 * 548 * Licensed under the Apache License, Version 2.0 (the "License"); 549 * you may not use this file except in compliance with the License. 550 * You may obtain a copy of the License at 551 * 552 * http://www.apache.org/licenses/LICENSE-2.0 553 * 554 * Unless required by applicable law or agreed to in writing, software 555 * distributed under the License is distributed on an "AS IS" BASIS, 556 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 557 * See the License for the specific language governing permissions and 558 * limitations under the License. 559 */const lb=new ew("@firebase/auth");function I5(t,...n){lb.logLevel<=br.WARN&&lb.warn(`Auth (${Ip}): ${t}`,...n)}function Kv(t,...n){lb.logLevel<=br.ERROR&&lb.error(`Auth (${Ip}): ${t}`,...n)}/** 560 * @license 561 * Copyright 2020 Google LLC 562 * 563 * Licensed under the Apache License, Version 2.0 (the "License"); 564 * you may not use this file except in compliance with the License. 565 * You may obtain a copy of the License at 566 * 567 * http://www.apache.org/licenses/LICENSE-2.0 568 * 569 * Unless required by applicable law or agreed to in writing, software 570 * distributed under the License is distributed on an "AS IS" BASIS, 571 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 572 * See the License for the specific language governing permissions and 573 * limitations under the License. 574 */function ml(t,...n){throw sw(t,...n)}function Ul(t,...n){return sw(t,...n)}function _5(t,n,a){const s={...QT(),[n]:a};return new Sg("auth","Firebase",s).create(n,{appName:t.name})}function Sd(t){return _5(t,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function sw(t,...n){if(typeof t!="string"){const a=n[0],s=[...n.slice(1)];return s[0]&&(s[0].appName=t.name),t._errorFactory.create(a,...s)}return A5.create(t,...n)}function ss(t,n,...a){if(!t)throw sw(n,...a)}function xd(t){const n="INTERNAL ASSERTION FAILED: "+t;throw Kv(n),new Error(n)}function Pd(t,n){t||xd(n)}/** 575 * @license 576 * Copyright 2020 Google LLC 577 * 578 * Licensed under the Apache License, Version 2.0 (the "License"); 579 * you may not use this file except in compliance with the License. 580 * You may obtain a copy of the License at 581 * 582 * http://www.apache.org/licenses/LICENSE-2.0 583 * 584 * Unless required by applicable law or agreed to in writing, software 585 * distributed under the License is distributed on an "AS IS" BASIS, 586 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 587 * See the License for the specific language governing permissions and 588 * limitations under the License. 589 */function t1(){var t;return typeof self<"u"&&((t=self.location)==null?void 0:t.href)||""}function JT(){return ZS()==="http:"||ZS()==="https:"}function ZS(){var t;return typeof self<"u"&&((t=self.location)==null?void 0:t.protocol)||null}/** 590 * @license 591 * Copyright 2020 Google LLC 592 * 593 * Licensed under the Apache License, Version 2.0 (the "License");
594 * you may not use this file except in compliance with the License. 595 * You may obtain a copy of the License at 596 * 597 * http://www.apache.org/licenses/LICENSE-2.0 598 * 599 * Unless required by applicable law or agreed to in writing, software 600 * distributed under the License is distributed on an "AS IS" BASIS, 601 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 602 * See the License for the specific language governing permissions and 603 * limitations under the License. 604 */function KT(){return typeof navigator<"u"&&navigator&&"onLine"in navigator&&typeof navigator.onLine=="boolean"&&(JT()||_R()||"connection"in navigator)?navigator.onLine:!0}function XT(){if(typeof navigator>"u")return null;const t=navigator;return t.languages&&t.languages[0]||t.language||null}/** 605 * @license 606 * Copyright 2020 Google LLC 607 * 608 * Licensed under the Apache License, Version 2.0 (the "License"); 609 * you may not use this file except in compliance with the License. 610 * You may obtain a copy of the License at 611 * 612 * http://www.apache.org/licenses/LICENSE-2.0 613 * 614 * Unless required by applicable law or agreed to in writing, software 615 * distributed under the License is distributed on an "AS IS" BASIS, 616 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 617 * See the License for the specific language governing permissions and 618 * limitations under the License. 619 */class Ag{constructor(n,a){this.shortDelay=n,this.longDelay=a,Pd(a>n,"Short delay should be less than long delay!"),this.isMobile=Z1()||y5()}get(){return KT()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}/** 620 * @license 621 * Copyright 2020 Google LLC 622 * 623 * Licensed under the Apache License, Version 2.0 (the "License"); 624 * you may not use this file except in compliance with the License. 625 * You may obtain a copy of the License at 626 * 627 * http://www.apache.org/licenses/LICENSE-2.0 628 * 629 * Unless required by applicable law or agreed to in writing, software 630 * distributed under the License is distributed on an "AS IS" BASIS, 631 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 632 * See the License for the specific language governing permissions and 633 * limitations under the License. 634 */function rw(t,n){Pd(t.emulator,"Emulator should always be set here");const{url:a}=t.emulator;return n?`${a}${n.startsWith("/")?n.slice(1):n}`:a}/** 635 * @license 636 * Copyright 2020 Google LLC 637 * 638 * Licensed under the Apache License, Version 2.0 (the "License"); 639 * you may not use this file except in compliance with the License. 640 * You may obtain a copy of the License at 641 * 642 * http://www.apache.org/licenses/LICENSE-2.0 643 * 644 * Unless required by applicable law or agreed to in writing, software 645 * distributed under the License is distributed on an "AS IS" BASIS, 646 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 647 * See the License for the specific language governing permissions and 648 * limitations under the License. 649 */class k5{static initialize(n,a,s){this.fetchImpl=n,a&&(this.headersImpl=a),s&&(this.responseImpl=s)}static fetch(){if(this.fetchImpl)return this.fetchImpl;if(typeof self<"u"&&"fetch"in self)return self.fetch;if(typeof globalThis<"u"&&globalThis.fetch)return globalThis.fetch;if(typeof fetch<"u")return fetch;xd("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl)return this.headersImpl;if(typeof self<"u"&&"Headers"in self)return self.Headers;if(typeof globalThis<"u"&&globalThis.Headers)return globalThis.Headers;if(typeof Headers<"u")return Headers;xd("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl)return this.responseImpl;if(typeof self<"u"&&"Response"in self)return self.Response;if(typeof globalThis<"u"&&globalThis.Response)return globalThis.Response;if(typeof Response<"u")return Response;xd("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}/** 650 * @license 651 * Copyright 2020 Google LLC 652 * 653 * Licensed under the Apache License, Version 2.0 (the "License");
654 * you may not use this file except in compliance with the License. 655 * You may obtain a copy of the License at 656 * 657 * http://www.apache.org/licenses/LICENSE-2.0 658 * 659 * Unless required by applicable law or agreed to in writing, software 660 * distributed under the License is distributed on an "AS IS" BASIS, 661 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 662 * See the License for the specific language governing permissions and 663 * limitations under the License. 664 */const ZT={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"};/** 665 * @license 666 * Copyright 2020 Google LLC 667 * 668 * Licensed under the Apache License, Version 2.0 (the "License"); 669 * you may not use this file except in compliance with the License. 670 * You may obtain a copy of the License at 671 * 672 * http://www.apache.org/licenses/LICENSE-2.0 673 * 674 * Unless required by applicable law or agreed to in writing, software 675 * distributed under the License is distributed on an "AS IS" BASIS, 676 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 677 * See the License for the specific language governing permissions and 678 * limitations under the License. 679 */const eM=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],tM=new Ag(3e4,6e4);function Td(t,n){return t.tenantId&&!n.tenantId?{...n,tenantId:t.tenantId}:n}async function fl(t,n,a,s,i={}){return D5(t,i,async()=>{let c={},l={};s&&(n==="GET"?l=s:c={body:JSON.stringify(s)});const m=Ap({...l,key:t.config.apiKey}).slice(1),d=await t._getAdditionalHeaders();d["Content-Type"]="application/json",t.languageCode&&(d["X-Firebase-Locale"]=t.languageCode);const u={method:n,headers:d,...c};return IR()||(u.referrerPolicy="strict-origin-when-cross-origin"),t.emulatorConfig&&Cg(t.emulatorConfig.host)&&(u.credentials="include"),k5.fetch()(await E5(t,t.config.apiHost,a,m),u)})}async function D5(t,n,a){t._canInitEmulator=!1;const s={...ZT,...n};try{const i=new aM(t),c=await Promise.race([a(),i.promise]);i.clearNetworkTimeout();const l=await c.json();if("needConfirmation"in l)throw Ty(t,"account-exists-with-different-credential",l);if(c.ok&&!("errorMessage"in l))return l;{const m=c.ok?l.errorMessage:l.error.message,[d,u]=m.split(" : ");if(d==="FEDERATED_USER_ID_ALREADY_LINKED")throw Ty(t,"credential-already-in-use",l);if(d==="EMAIL_EXISTS")throw Ty(t,"email-already-in-use",l);if(d==="USER_DISABLED")throw Ty(t,"user-disabled",l);const f=s[d]||d.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw _5(t,f,u);ml(t,f)}}catch(i){if(i instanceof Yu)throw i;ml(t,"network-request-failed",{message:String(i)})}}async function Ig(t,n,a,s,i={}){const c=await fl(t,n,a,s,i);return"mfaPendingCredential"in c&&ml(t,"multi-factor-auth-required",{_serverResponse:c}),c}async function E5(t,n,a,s){const i=`${n}${a}?${s}`,c=t,l=c.config.emulator?rw(t.config,i):`${t.config.apiScheme}://${i}`;return eM.includes(a)&&(await c._persistenceManagerAvailable,c._getPersistenceType()==="COOKIE")?c._getPersistence()._getFinalTarget(l).toString():l}function nM(t){switch(t){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class aM{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(n){this.auth=n,this.timer=null,this.promise=new Promise((a,s)=>{this.timer=setTimeout(()=>s(Ul(this.auth,"network-request-failed")),tM.get())})}}function Ty(t,n,a){const s={appName:t.name};a.email&&(s.email=a.email),a.phoneNumber&&(s.phoneNumber=a.phoneNumber);const i=Ul(t,n,s);return i.customData._tokenResponse=a,i}function eC(t){return t!==void 0&&t.enterprise!==void 0}class sM{constructor(n){if(this.siteKey="",this.recaptchaEnforcementState=[],n.recaptchaKey===void 0)throw new Error("recaptchaKey undefined");this.siteKey=n.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=n.recaptchaEnforcementState}getProviderEnforcementState(n){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0)return null;for(const a of this.recaptchaEnforcementState)if(a.provider&&a.provider===n)return nM(a.enforcementState);return null}isProviderEnabled(n){return this.getProviderEnforcementState(n)==="ENFORCE"||this.getProviderEnforcementState(n)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PRO
679VIDER")}}async function rM(t,n){return fl(t,"GET","/v2/recaptchaConfig",Td(t,n))}/** 680 * @license 681 * Copyright 2020 Google LLC 682 * 683 * Licensed under the Apache License, Version 2.0 (the "License"); 684 * you may not use this file except in compliance with the License. 685 * You may obtain a copy of the License at 686 * 687 * http://www.apache.org/licenses/LICENSE-2.0 688 * 689 * Unless required by applicable law or agreed to in writing, software 690 * distributed under the License is distributed on an "AS IS" BASIS, 691 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 692 * See the License for the specific language governing permissions and 693 * limitations under the License. 694 */async function iM(t,n){return fl(t,"POST","/v1/accounts:delete",n)}async function db(t,n){return fl(t,"POST","/v1/accounts:lookup",n)}/** 695 * @license 696 * Copyright 2020 Google LLC 697 * 698 * Licensed under the Apache License, Version 2.0 (the "License"); 699 * you may not use this file except in compliance with the License. 700 * You may obtain a copy of the License at 701 * 702 * http://www.apache.org/licenses/LICENSE-2.0 703 * 704 * Unless required by applicable law or agreed to in writing, software 705 * distributed under the License is distributed on an "AS IS" BASIS, 706 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 707 * See the License for the specific language governing permissions and 708 * limitations under the License. 709 */function qf(t){if(t)try{const n=new Date(Number(t));if(!isNaN(n.getTime()))return n.toUTCString()}catch{}}async function oM(t,n=!1){const a=Jr(t),s=await a.getIdToken(n),i=iw(s);ss(i&&i.exp&&i.auth_time&&i.iat,a.auth,"internal-error");const c=typeof i.firebase=="object"?i.firebase:void 0,l=c==null?void 0:c.sign_in_provider;return{claims:i,token:s,authTime:qf(L0(i.auth_time)),issuedAtTime:qf(L0(i.iat)),expirationTime:qf(L0(i.exp)),signInProvider:l||null,signInSecondFactor:(c==null?void 0:c.sign_in_second_factor)||null}}function L0(t){return Number(t)*1e3}function iw(t){const[n,a,s]=t.split(".");if(n===void 0||a===void 0||s===void 0)return Kv("JWT malformed, contained fewer than 3 sections"),null;try{const i=ob(a);return i?JSON.parse(i):(Kv("Failed to decode base64 JWT payload"),null)}catch(i){return Kv("Caught error parsing JWT payload as JSON",i==null?void 0:i.toString()),null}}function tC(t){const n=iw(t);return ss(n,"internal-error"),ss(typeof n.exp<"u","internal-error"),ss(typeof n.iat<"u","internal-error"),Number(n.exp)-Number(n.iat)}/** 710 * @license 711 * Copyright 2020 Google LLC 712 * 713 * Licensed under the Apache License, Version 2.0 (the "License"); 714 * you may not use this file except in compliance with the License. 715 * You may obtain a copy of the License at 716 * 717 * http://www.apache.org/licenses/LICENSE-2.0 718 * 719 * Unless required by applicable law or agreed to in writing, software 720 * distributed under the License is distributed on an "AS IS" BASIS, 721 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 722 * See the License for the specific language governing permissions and 723 * limitations under the License. 724 */async function Uh(t,n,a=!1){if(a)return n;try{return await n}catch(s){throw s instanceof Yu&&cM(s)&&t.auth.currentUser===t&&await t.auth.signOut(),s}}function cM({code:t}){return t==="auth/user-disabled"||t==="auth/user-token-expired"}/** 725 * @license 726 * Copyright 2020 Google LLC 727 * 728 * Licensed under the Apache License, Version 2.0 (the "License"); 729 * you may not use this file except in compliance with the License. 730 * You may obtain a copy of the License at 731 * 732 * http://www.apache.org/licenses/LICENSE-2.0 733 * 734 * Unless required by applicable law or agreed to in writing, software 735 * distributed under the License is distributed on an "AS IS" BASIS, 736 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 737 * See the License for the specific language governing permissions and 738 * limitations under the License. 739 */class lM{constructor(n){this.user=n,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,this.timerId!==null&&clearTimeout(this.timerId))}getInterval(n){if(n){const a=this.errorBackoff;return this.errorBackoff=Math.min(this.errorBackoff*2,96e4),a}else{this.errorBackoff=3e4;const s=(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5;return Math.max(0,s)}}schedule(n=!1){if(!this.isRunning)return;const a=this.getInterval(n);this.timerId=setTimeout(async()=>{await this.iteration()},a)}async iteration(){try{await this.user.getIdToken(!0)}catch(n){(n==null?void 0:n.code)==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}/** 740 * @license 741 * Copyright 2020 Google LLC 742 * 743 * Licensed under the Apache License, Version 2.0 (the "License");
744 * you may not use this file except in compliance with the License. 745 * You may obtain a copy of the License at 746 * 747 * http://www.apache.org/licenses/LICENSE-2.0 748 * 749 * Unless required by applicable law or agreed to in writing, software 750 * distributed under the License is distributed on an "AS IS" BASIS, 751 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 752 * See the License for the specific language governing permissions and 753 * limitations under the License. 754 */class n1{constructor(n,a){this.createdAt=n,this.lastLoginAt=a,this._initializeTime()}_initializeTime(){this.lastSignInTime=qf(this.lastLoginAt),this.creationTime=qf(this.createdAt)}_copy(n){this.createdAt=n.createdAt,this.lastLoginAt=n.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}/** 755 * @license 756 * Copyright 2019 Google LLC 757 * 758 * Licensed under the Apache License, Version 2.0 (the "License"); 759 * you may not use this file except in compliance with the License. 760 * You may obtain a copy of the License at 761 * 762 * http://www.apache.org/licenses/LICENSE-2.0 763 * 764 * Unless required by applicable law or agreed to in writing, software 765 * distributed under the License is distributed on an "AS IS" BASIS, 766 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 767 * See the License for the specific language governing permissions and 768 * limitations under the License. 769 */async function ub(t){var g;const n=t.auth,a=await t.getIdToken(),s=await Uh(t,db(n,{idToken:a}));ss(s==null?void 0:s.users.length,n,"internal-error");const i=s.users[0];t._notifyReloadListener(i);const c=(g=i.providerUserInfo)!=null&&g.length?P5(i.providerUserInfo):[],l=uM(t.providerData,c),m=t.isAnonymous,d=!(t.email&&i.passwordHash)&&!(l!=null&&l.length),u=m?d:!1,f={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:l,metadata:new n1(i.createdAt,i.lastLoginAt),isAnonymous:u};Object.assign(t,f)}async function dM(t){const n=Jr(t);await ub(n),await n.auth._persistUserIfCurrent(n),n.auth._notifyListenersIfCurrent(n)}function uM(t,n){return[...t.filter(s=>!n.some(i=>i.providerId===s.providerId)),...n]}function P5(t){return t.map(({providerId:n,...a})=>({providerId:n,uid:a.rawId||"",displayName:a.displayName||null,email:a.email||null,phoneNumber:a.phoneNumber||null,photoURL:a.photoUrl||null}))}/** 770 * @license 771 * Copyright 2020 Google LLC 772 * 773 * Licensed under the Apache License, Version 2.0 (the "License"); 774 * you may not use this file except in compliance with the License. 775 * You may obtain a copy of the License at 776 * 777 * http://www.apache.org/licenses/LICENSE-2.0 778 * 779 * Unless required by applicable law or agreed to in writing, software 780 * distributed under the License is distributed on an "AS IS" BASIS, 781 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 782 * See the License for the specific language governing permissions and 783 * limitations under the License. 784 */async function hM(t,n){const a=await D5(t,{},async()=>{const s=Ap({grant_type:"refresh_token",refresh_token:n}).slice(1),{tokenApiHost:i,apiKey:c}=t.config,l=await E5(t,i,"/v1/token",`key=${c}`),m=await t._getAdditionalHeaders();m["Content-Type"]="application/x-www-form-urlencoded";const d={method:"POST",headers:m,body:s};return t.emulatorConfig&&Cg(t.emulatorConfig.host)&&(d.credentials="include"),k5.fetch()(l,d)});return{accessToken:a.access_token,expiresIn:a.expires_in,refreshToken:a.refresh_token}}async function mM(t,n){return fl(t,"POST","/v2/accounts:revokeToken",Td(t,n))}/** 785 * @license 786 * Copyright 2020 Google LLC 787 * 788 * Licensed under the Apache License, Version 2.0 (the "License"); 789 * you may not use this file except in compliance with the License. 790 * You may obtain a copy of the License at 791 * 792 * http://www.apache.org/licenses/LICENSE-2.0 793 * 794 * Unless required by applicable law or agreed to in writing, software 795 * distributed under the License is distributed on an "AS IS" BASIS, 796 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 797 * See the License for the specific language governing permissions and 798 * limitations under the License. 799 */class cp{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(n){ss(n.idToken,"internal-error"),ss(typeof n.idToken<"u","internal-error"),ss(typeof n.refreshToken<"u","internal-error");const a="expiresIn"in n&&typeof n.expiresIn<"u"?Number(n.expiresIn):tC(n.idToken);this.updateTokensAndExpiration(n.idToken,n.refreshToken,a)}updateFromIdToken(n){ss(n.length!==0,"internal-error");const a=tC(n);this.updateTokensAndExpiration(n,null,a)}async getToken(n,a=!1){return!a&&this.accessToken&&!this.isExpired?this.accessToken:(ss(this.refreshToken,n,"user-token-expired"),this.refreshToken?(await this.refresh(n,this.refreshToken),this.accessToken):null)}clearRefreshToken(){this.refreshToken=null}async refresh(n,a){const{accessToken:s,refreshToken:i,expiresIn:c}=await hM(n,a);this.updateTokensAndExpiration(s,i,Number(c))}updateTokensAndExpiration(n,a,s){this.refreshToken=a||null,this.accessToken=n||null,this.expirationTime=Date.now()+s*1e3}static fromJSON(n,a){const{refreshToken:s,accessToken:i,expirationTime:c}=a,l=new cp;return s&&(ss(typeof s=="string","internal-error",{appName:n}),l.refreshToken=s),i&&(ss(typeof i=="string","internal-error",{appName:n}),l.accessToken=i),c&&(ss(typeof c=="number","internal-error",{appName:n}),l.expirationTime=c),l}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(n){this.accessToken=n.accessToken,this.refreshToken=n.refreshToken,this.expirationTime=n.expirationTime}_clone(){return Object.assign(new cp,this.toJSON())}_performRefresh(){return xd("not implemented")}}/** 800 * @license 801 * Copyright 2020 Google LLC 802 * 803 * Licensed under the Apache License, Version 2.0 (the "License");
804 * you may not use this file except in compliance with the License. 805 * You may obtain a copy of the License at 806 * 807 * http://www.apache.org/licenses/LICENSE-2.0 808 * 809 * Unless required by applicable law or agreed to in writing, software 810 * distributed under the License is distributed on an "AS IS" BASIS, 811 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 812 * See the License for the specific language governing permissions and 813 * limitations under the License. 814 */function su(t,n){ss(typeof t=="string"||typeof t>"u","internal-error",{appName:n})}class ll{constructor({uid:n,auth:a,stsTokenManager:s,...i}){this.providerId="firebase",this.proactiveRefresh=new lM(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=n,this.auth=a,this.stsTokenManager=s,this.accessToken=s.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new n1(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(n){const a=await Uh(this,this.stsTokenManager.getToken(this.auth,n));return ss(a,this.auth,"internal-error"),this.accessToken!==a&&(this.accessToken=a,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),a}getIdTokenResult(n){return oM(this,n)}reload(){return dM(this)}_assign(n){this!==n&&(ss(this.uid===n.uid,this.auth,"internal-error"),this.displayName=n.displayName,this.photoURL=n.photoURL,this.email=n.email,this.emailVerified=n.emailVerified,this.phoneNumber=n.phoneNumber,this.isAnonymous=n.isAnonymous,this.tenantId=n.tenantId,this.providerData=n.providerData.map(a=>({...a})),this.metadata._copy(n.metadata),this.stsTokenManager._assign(n.stsTokenManager))}_clone(n){const a=new ll({...this,auth:n,stsTokenManager:this.stsTokenManager._clone()});return a.metadata._copy(this.metadata),a}_onReload(n){ss(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=n,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(n){this.reloadListener?this.reloadListener(n):this.reloadUserInfo=n}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(n,a=!1){let s=!1;n.idToken&&n.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(n),s=!0),a&&await ub(this),await this.auth._persistUserIfCurrent(this),s&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Tc(this.auth.app))return Promise.reject(Sd(this.auth));const n=await this.getIdToken();return await Uh(this,iM(this.auth,{idToken:n})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(n=>({...n})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(n,a){const s=a.displayName??void 0,i=a.email??void 0,c=a.phoneNumber??void 0,l=a.photoURL??void 0,m=a.tenantId??void 0,d=a._redirectEventId??void 0,u=a.createdAt??void 0,f=a.lastLoginAt??void 0,{uid:g,emailVerified:p,isAnonymous:y,providerData:b,stsTokenManager:N}=a;ss(g&&N,n,"internal-error");const w=cp.fromJSON(this.name,N);ss(typeof g=="string",n,"internal-error"),su(s,n.name),su(i,n.name),ss(typeof p=="boolean",n,"internal-error"),ss(typeof y=="boolean",n,"internal-error"),su(c,n.name),su(l,n.name),su(m,n.name),su(d,n.name),su(u,n.name),su(f,n.name);const C=new ll({uid:g,auth:n,email:i,emailVerified:p,displayName:s,isAnonymous:y,photoURL:l,phoneNumber:c,tenantId:m,stsTokenManager:w,createdAt:u,lastLoginAt:f});return b&&Array.isArray(b)&&(C.providerData=b.map(R=>({...R}))),d&&(C._redirectEventId=d),C}static async _fromIdTokenResponse(n,a,s=!1){const i=new cp;
814i.updateFromServerResponse(a);const c=new ll({uid:a.localId,auth:n,stsTokenManager:i,isAnonymous:s});return await ub(c),c}static async _fromGetAccountInfoResponse(n,a,s){const i=a.users[0];ss(i.localId!==void 0,"internal-error");const c=i.providerUserInfo!==void 0?P5(i.providerUserInfo):[],l=!(i.email&&i.passwordHash)&&!(c!=null&&c.length),m=new cp;m.updateFromIdToken(s);const d=new ll({uid:i.localId,auth:n,stsTokenManager:m,isAnonymous:l}),u={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:c,metadata:new n1(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!(c!=null&&c.length)};return Object.assign(d,u),d}}/** 815 * @license 816 * Copyright 2020 Google LLC 817 * 818 * Licensed under the Apache License, Version 2.0 (the "License"); 819 * you may not use this file except in compliance with the License. 820 * You may obtain a copy of the License at 821 * 822 * http://www.apache.org/licenses/LICENSE-2.0 823 * 824 * Unless required by applicable law or agreed to in writing, software 825 * distributed under the License is distributed on an "AS IS" BASIS, 826 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 827 * See the License for the specific language governing permissions and 828 * limitations under the License. 829 */const nC=new Map;
829function jd(t){Pd(t instanceof Function,"Expected a class definition");let n=nC.get(t);return n?(Pd(n instanceof t,"Instance stored in cache mismatched with class"),n):(n=new t,nC.set(t,n),n)}/** 830 * @license 831 * Copyright 2019 Google LLC 832 * 833 * Licensed under the Apache License, Version 2.0 (the "License"); 834 * you may not use this file except in compliance with the License. 835 * You may obtain a copy of the License at 836 * 837 * http://www.apache.org/licenses/LICENSE-2.0 838 * 839 * Unless required by applicable law or agreed to in writing, software 840 * distributed under the License is distributed on an "AS IS" BASIS, 841 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 842 * See the License for the specific language governing permissions and 843 * limitations under the License. 844 */class R5{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(n,a){this.storage[n]=a}async _get(n){const a=this.storage[n];return a===void 0?null:a}async _remove(n){delete this.storage[n]}_addListener(n,a){}_removeListener(n,a){}}R5.type="NONE";const aC=R5;/** 845 * @license 846 * Copyright 2019 Google LLC 847 * 848 * Licensed under the Apache License, Version 2.0 (the "License"); 849 * you may not use this file except in compliance with the License. 850 * You may obtain a copy of the License at 851 * 852 * http://www.apache.org/licenses/LICENSE-2.0 853 * 854 * Unless required by applicable law or agreed to in writing, software 855 * distributed under the License is distributed on an "AS IS" BASIS, 856 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 857 * See the License for the specific language governing permissions and 858 * limitations under the License. 859 */function Xv(t,n,a){return`firebase:${t}:${n}:${a}`}class lp{constructor(n,a,s){this.persistence=n,this.auth=a,this.userKey=s;const{config:i,name:c}=this.auth;this.fullUserKey=Xv(this.userKey,i.apiKey,c),this.fullPersistenceKey=Xv("persistence",i.apiKey,c),this.boundEventHandler=a._onStorageEvent.bind(a),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(n){return this.persistence._set(this.fullUserKey,n.toJSON())}async getCurrentUser(){const n=await this.persistence._get(this.fullUserKey);if(!n)return null;if(typeof n=="string"){const a=await db(this.auth,{idToken:n}).catch(()=>{});return a?ll._fromGetAccountInfoResponse(this.auth,a,n):null}return ll._fromJSON(this.auth,n)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(n){if(this.persistence===n)return;const a=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=n,a)return this.setCurrentUser(a)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(n,a,s="authUser"){if(!a.length)return new lp(jd(aC),n,s);const i=(await Promise.all(a.map(async u=>{if(await u._isAvailable())return u}))).filter(u=>u);let c=i[0]||jd(aC);const l=Xv(s,n.config.apiKey,n.name);let m=null;for(const u of a)try{const f=await u._get(l);if(f){let g;if(typeof f=="string"){const p=await db(n,{idToken:f}).catch(()=>{});if(!p)break;g=await ll._fromGetAccountInfoResponse(n,p,f)}else g=ll._fromJSON(n,f);u!==c&&(m=g),c=u;break}}catch{}const d=i.filter(u=>u._shouldAllowMigration);return!c._shouldAllowMigration||!d.length?new lp(c,n,s):(c=d[0],m&&await c._set(l,m.toJSON()),await Promise.all(a.map(async u=>{if(u!==c)try{await u._remove(l)}catch{}})),new lp(c,n,s))}}/** 860 * @license 861 * Copyright 2020 Google LLC 862 * 863 * Licensed under the Apache License, Version 2.0 (the "License"); 864 * you may not use this file except in compliance with the License. 865 * You may obtain a copy of the License at 866 * 867 * http://www.apache.org/licenses/LICENSE-2.0 868 * 869 * Unless required by applicable law or agreed to in writing, software 870 * distributed under the License is distributed on an "AS IS" BASIS, 871 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 872 * See the License for the specific language governing permissions and 873 * limitations under the License. 874 */function sC(t){const n=t.toLowerCase();if(n.includes("opera/")||n.includes("opr/")||n.includes("opios/"))return"Opera";if(O5(n))return"IEMobile";if(n.includes("msie")||n.includes("trident/"))return"IE";if(n.includes("edge/"))return"Edge";if(T5(n))return"Firefox";if(n.includes("silk/"))return"Silk";if(B5(n))return"Blackberry";if(F5(n))return"Webos";if(M5(n))return"Safari";if((n.includes("chrome/")||$5(n))&&!n.includes("edge/"))return"Chrome";if(L5(n))return"Android";{const a=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,s=t.match(a);if((s==null?void 0:s.length)===2)return s[1]}return"Other"}function T5(t=Io()){return/firefox\//i.test(t)}function M5(t=Io()){const n=t.toLowerCase();return n.includes("safari/")&&!n.includes("chrome/")&&!n.includes("crios/")&&!n.includes("android")}function $5(t=Io()){return/crios\//i.test(t)}function O5(t=Io()){return/iemobile/i.test(t)}function L5(t=Io()){return/android/i.test(t)}function B5(t=Io()){return/blackberry/i.test(t)}function F5(t=Io()){return/webos/i.test(t)}function ow(t=Io()){return/iphone|ipad|ipod/i.test(t)||/macintosh/i.test(t)&&/mobile/i.test(t)}function pM(t=Io()){var n;return ow(t)&&!!((n=window.navigator)!=null&&n.standalone)}function fM(){return kR()&&document.documentMode===10}
874function U5(t=Io()){return ow(t)||L5(t)||F5(t)||B5(t)||/windows phone/i.test(t)||O5(t)}/** 875 * @license 876 * Copyright 2020 Google LLC 877 * 878 * Licensed under the Apache License, Version 2.0 (the "License"); 879 * you may not use this file except in compliance with the License. 880 * You may obtain a copy of the License at 881 * 882 * http://www.apache.org/licenses/LICENSE-2.0 883 * 884 * Unless required by applicable law or agreed to in writing, software 885 * distributed under the License is distributed on an "AS IS" BASIS, 886 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 887 * See the License for the specific language governing permissions and 888 * limitations under the License. 889 */function z5(t,n=[]){let a;switch(t){case"Browser":a=sC(Io());break;case"Worker":a=`${sC(Io())}-${t}`;break;default:a=t}const s=n.length?n.join(","):"FirebaseCore-web";return`${a}/JsCore/${Ip}/${s}`}/** 890 * @license 891 * Copyright 2022 Google LLC 892 * 893 * Licensed under the Apache License, Version 2.0 (the "License"); 894 * you may not use this file except in compliance with the License. 895 * You may obtain a copy of the License at 896 * 897 * http://www.apache.org/licenses/LICENSE-2.0 898 * 899 * Unless required by applicable law or agreed to in writing, software 900 * distributed under the License is distributed on an "AS IS" BASIS, 901 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 902 * See the License for the specific language governing permissions and 903 * limitations under the License. 904 */class gM{constructor(n){this.auth=n,this.queue=[]}pushCallback(n,a){const s=c=>new Promise((l,m)=>{try{const d=n(c);l(d)}catch(d){m(d)}});s.onAbort=a,this.queue.push(s);const i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(n){if(this.auth.currentUser===n)return;const a=[];try{for(const s of this.queue)await s(n),s.onAbort&&a.push(s.onAbort)}catch(s){a.reverse();for(const i of a)try{i()}catch{}throw this.auth._errorFactory.create("login-blocked",{originalMessage:s==null?void 0:s.message})}}}/** 905 * @license 906 * Copyright 2023 Google LLC 907 * 908 * Licensed under the Apache License, Version 2.0 (the "License"); 909 * you may not use this file except in compliance with the License. 910 * You may obtain a copy of the License at 911 * 912 * http://www.apache.org/licenses/LICENSE-2.0 913 * 914 * Unless required by applicable law or agreed to in writing, software 915 * distributed under the License is distributed on an "AS IS" BASIS, 916 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 917 * See the License for the specific language governing permissions and 918 * limitations under the License. 919 */async function yM(t,n={}){return fl(t,"GET","/v2/passwordPolicy",Td(t,n))}/** 920 * @license 921 * Copyright 2023 Google LLC 922 * 923 * Licensed under the Apache License, Version 2.0 (the "License"); 924 * you may not use this file except in compliance with the License. 925 * You may obtain a copy of the License at 926 * 927 * http://www.apache.org/licenses/LICENSE-2.0 928 * 929 * Unless required by applicable law or agreed to in writing, software 930 * distributed under the License is distributed on an "AS IS" BASIS, 931 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 932 * See the License for the specific language governing permissions and 933 * limitations under the License. 934 */const vM=6;class bM{constructor(n){var s;const a=n.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=a.minPasswordLength??vM,a.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=a.maxPasswordLength),a.containsLowercaseCharacter!==void 0&&(this.customStrengthOptions.containsLowercaseLetter=a.containsLowercaseCharacter),a.containsUppercaseCharacter!==void 0&&(this.customStrengthOptions.containsUppercaseLetter=a.containsUppercaseCharacter),a.containsNumericCharacter!==void 0&&(this.customStrengthOptions.containsNumericCharacter=a.containsNumericCharacter),a.containsNonAlphanumericCharacter!==void 0&&(this.customStrengthOptions.containsNonAlphanumericCharacter=a.containsNonAlphanumericCharacter),this.enforcementState=n.enforcementState,this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=((s=n.allowedNonAlphanumericCharacters)==null?void 0:s.join(""))??"",this.forceUpgradeOnSignin=n.forceUpgradeOnSignin??!1,this.schemaVersion=n.schemaVersion}validatePassword(n){const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(n,a),this.validatePasswordCharacterOptions(n,a),a.isValid&&
934(a.isValid=a.meetsMinPasswordLength??!0),a.isValid&&(a.isValid=a.meetsMaxPasswordLength??!0),a.isValid&&(a.isValid=a.containsLowercaseLetter??!0),a.isValid&&(a.isValid=a.containsUppercaseLetter??!0),a.isValid&&(a.isValid=a.containsNumericCharacter??!0),a.isValid&&(a.isValid=a.containsNonAlphanumericCharacter??!0),a}validatePasswordLengthOptions(n,a){const s=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;s&&(a.meetsMinPasswordLength=n.length>=s),i&&(a.meetsMaxPasswordLength=n.length<=i)}validatePasswordCharacterOptions(n,a){this.updatePasswordCharacterOptionsStatuses(a,!1,!1,!1,!1);let s;for(let i=0;i<n.length;i++)s=n.charAt(i),this.updatePasswordCharacterOptionsStatuses(a,s>="a"&&s<="z",s>="A"&&s<="Z",s>="0"&&s<="9",this.allowedNonAlphanumericCharacters.includes(s))}updatePasswordCharacterOptionsStatuses(n,a,s,i,c){this.customStrengthOptions.containsLowercaseLetter&&(n.containsLowercaseLetter||(n.containsLowercaseLetter=a)),this.customStrengthOptions.containsUppercaseLetter&&(n.containsUppercaseLetter||(n.containsUppercaseLetter=s)),this.customStrengthOptions.containsNumericCharacter&&(n.containsNumericCharacter||(n.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(n.containsNonAlphanumericCharacter||(n.containsNonAlphanumericCharacter=c))}}/** 935 * @license 936 * Copyright 2020 Google LLC 937 * 938 * Licensed under the Apache License, Version 2.0 (the "License"); 939 * you may not use this file except in compliance with the License. 940 * You may obtain a copy of the License at 941 * 942 * http://www.apache.org/licenses/LICENSE-2.0 943 * 944 * Unless required by applicable law or agreed to in writing, software 945 * distributed under the License is distributed on an "AS IS" BASIS, 946 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 947 * See the License for the specific language governing permissions and 948 * limitations under the License. 949 */class xM{constructor(n,a,s,i){this.app=n,this.heartbeatServiceProvider=a,this.appCheckServiceProvider=s,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new rC(this),this.idTokenSubscription=new rC(this),this.beforeStateQueue=new gM(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=A5,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=n.name,this.clientVersion=i.sdkClientVersion,this._persistenceManagerAvailable=new Promise(c=>this._resolvePersistenceManagerAvailable=c)}_initializeWithPersistence(n,a){return a&&(this._popupRedirectResolver=jd(a)),this._initializationPromise=this.queue(async()=>{var s,i,c;if(!this._deleted&&(this.persistenceManager=await lp.create(this,n),(s=this._resolvePersistenceManagerAvailable)==null||s.call(this),!this._deleted)){if((i=this._popupRedirectResolver)!=null&&i._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch{}await this.initializeCurrentUser(a),this.lastNotifiedUid=((c=this.currentUser)==null?void 0:c.uid)||null,!this._deleted&&(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const n=await this.assertedPersistence.getCurrentUser();if(!(!this.currentUser&&!n)){if(this.currentUser&&n&&this.currentUser.uid===n.uid){this._currentUser._assign(n),await this.currentUser.getIdToken();return}await this._updateCurrentUser(n,!0)}}async initializeCurrentUserFromIdToken(n){try{const a=await db(this,{idToken:n}),s=await ll._fromGetAccountInfoResponse(this,a,n);await this.directlySetCurrentUser(s)}catch(a){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",a),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(n){var c;if(Tc(this.app)){const l=this.app.settings.authIdToken;return l?new Promise(m=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(l).then(m,m))}):this.directlySetCurrentUser(null)}const a=await this.assertedPersistence.getCurrentUser();let s=a,i=!1;if(n&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const l=(c=this.redirectUser)==null?void 0:c._redirectEventId,m=s==null?void 0:s._redirectEventId,d=await this.tryRedirectSignIn(n);(!l||l===m)&&(d!=null&&d.user)&&(s=d.user,i=!0)}if(!s)return this.directlySetCurrentUser(null);
949if(!s._redirectEventId){if(i)try{await this.beforeStateQueue.runMiddleware(s)}catch(l){s=a,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(l))}return s?this.reloadAndSetCurrentUserOrClear(s):this.directlySetCurrentUser(null)}return ss(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===s._redirectEventId?this.directlySetCurrentUser(s):this.reloadAndSetCurrentUserOrClear(s)}async tryRedirectSignIn(n){let a=null;try{a=await this._popupRedirectResolver._completeRedirectFn(this,n,!0)}catch{await this._setRedirectUser(null)}return a}async reloadAndSetCurrentUserOrClear(n){try{await ub(n)}catch(a){if((a==null?void 0:a.code)!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(n)}useDeviceLanguage(){this.languageCode=XT()}async _delete(){this._deleted=!0}async updateCurrentUser(n){if(Tc(this.app))return Promise.reject(Sd(this));const a=n?Jr(n):null;return a&&ss(a.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(a&&a._clone(this))}async _updateCurrentUser(n,a=!1){if(!this._deleted)return n&&ss(this.tenantId===n.tenantId,this,"tenant-id-mismatch"),a||await this.beforeStateQueue.runMiddleware(n),this.queue(async()=>{await this.directlySetCurrentUser(n),this.notifyAuthListeners()})}async signOut(){return Tc(this.app)?Promise.reject(Sd(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(n){return Tc(this.app)?Promise.reject(Sd(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(jd(n))})}_getRecaptchaConfig(){return this.tenantId==null?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(n){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const a=this._getPasswordPolicyInternal();return a.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):a.validatePassword(n)}_getPasswordPolicyInternal(){return this.tenantId===null?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const n=await yM(this),a=new bM(n);this.tenantId===null?this._projectPasswordPolicy=a:this._tenantPasswordPolicies[this.tenantId]=a}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(n){this._errorFactory=new Sg("auth","Firebase",n())}onAuthStateChanged(n,a,s){return this.registerStateListener(this.authStateSubscription,n,a,s)}beforeAuthStateChanged(n,a){return this.beforeStateQueue.pushCallback(n,a)}onIdTokenChanged(n,a,s){return this.registerStateListener(this.idTokenSubscription,n,a,s)}authStateReady(){return new Promise((n,a)=>{if(this.currentUser)n();else{const s=this.onAuthStateChanged(()=>{s(),n()},a)}})}async revokeAccessToken(n){if(this.currentUser){const a=await this.currentUser.getIdToken(),s={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:n,idToken:a};this.tenantId!=null&&(s.tenantId=this.tenantId),await mM(this,s)}}toJSON(){var n;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:(n=this._currentUser)==null?void 0:n.toJSON()}}async _setRedirectUser(n,a){const s=await this.getOrInitRedirectPersistenceManager(a);return n===null?s.removeCurrentUser():s.setCurrentUser(n)}async getOrInitRedirectPersistenceManager(n){if(!this.redirectPersistenceManager){const a=n&&jd(n)||this._popupRedirectResolver;ss(a,this,"argument-error"),this.redirectPersistenceManager=await lp.create(this,[jd(a._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(n){var a,s;return this._isInitialized&&await this.queue(async()=>{}),((a=this._currentUser)==null?void 0:a._redirectEventId)===n?this._currentUser:((s=this.redirectUser)==null?void 0:s._redirectEventId)===n?this.redirectUser:null}async _persistUserIfCurrent(n){if(n===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(n))}_notifyListenersIfCurrent(n){n===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var a;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=((a=this.currentUser)==null?void 0:a.uid)??null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(n,a,s,i){if(this._deleted)return()=>{};const c=typeof a=="function"?a:a.next.bind(a);let l=!1;const m=this._isInitialized?Promise.resolve():this._initializationPromise;if(ss(m,this,"internal-error"),m.then(()=>{l||c(this.currentUser)}),typeof a=="function"){const d=n.addObserver(a,s,i);return()=>{l=!0,d()}}else{const d=n.addObserver(a);return()=>{l=!0,d()}}}async directlySetCurrentUser(n){this.currentUser&&this.currentUser!==n&&this._currentUser._stopProactiveRefresh(),n&&this.isProactiveRefreshEnabled&&n._startProactiveRefresh(),this.currentUser=n,n?await this.assertedPersistence.setCurrentUser(n):await this.assertedPersistence.removeCurrentUser()}queue(n){return this.operations=this.operations.then(n,n),this.operations}get assertedPersistence(){return ss(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(n){!n||this.frameworks.includes(n)||(this.frameworks.push(n),this.frameworks.sort(),this.clientVersion=z5(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var i;const n={"X-Client-Version":this.clientVersion};this.app.options.appId&&(n["X-Firebase-gmpid"]=this.app.options.appId);const a=await((i=this.heartbeatServiceProvider.getImmediate({optional:!0}))==null?void 0:i.getHeartbeatsHeader());a&&(n["X-Firebase-Client"]=a);const s=await this._getAppCheckToken();return s&&(n["X-Firebase-AppCheck"]=s),n}async _getAppCheckToken(){var a;if(Tc(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const n=await((a=this.appCheckServiceProvider.getImmediate({optional:!0}))==null?void 0:a.getToken());return n!=null&&n.error&&I5(`Error while retrieving App Check token: ${n.error}`),n==null?void 0:n.token}}function Qu(t){return Jr(t)}class rC{constructor(n){this.auth=n,this.observer=null,this.addObserver=LR(a=>this.observer=a)}get next(){return ss(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}/** 950 * @license 951 * Copyright 2020 Google LLC 952 * 953 * Licensed under the Apache License, Version 2.0 (the "License");
954 * you may not use this file except in compliance with the License. 955 * You may obtain a copy of the License at 956 * 957 * http://www.apache.org/licenses/LICENSE-2.0 958 * 959 * Unless required by applicable law or agreed to in writing, software 960 * distributed under the License is distributed on an "AS IS" BASIS, 961 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 962 * See the License for the specific language governing permissions and 963 * limitations under the License. 964 */let Hb={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function jM(t){Hb=t}function q5(t){return Hb.loadJS(t)}function wM(){return Hb.recaptchaEnterpriseScript}function NM(){return Hb.gapiScript}function SM(t){return`__${t}${Math.floor(Math.random()*1e6)}`}class CM{constructor(){this.enterprise=new AM}ready(n){n()}execute(n,a){return Promise.resolve("token")}render(n,a){return""}}class AM{ready(n){n()}execute(n,a){return Promise.resolve("token")}render(n,a){return""}}/** 965 * @license 966 * Copyright 2022 Google LLC 967 * 968 * Licensed under the Apache License, Version 2.0 (the "License"); 969 * you may not use this file except in compliance with the License. 970 * You may obtain a copy of the License at 971 * 972 * http://www.apache.org/licenses/LICENSE-2.0 973 * 974 * Unless required by applicable law or agreed to in writing, software 975 * distributed under the License is distributed on an "AS IS" BASIS, 976 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 977 * See the License for the specific language governing permissions and 978 * limitations under the License. 979 */const IM="recaptcha-enterprise",V5="NO_RECAPTCHA",iC="onFirebaseAuthREInstanceReady";class xu{constructor(n){this.type=IM,this.auth=Qu(n)}async verify(n="verify",a=!1){async function s(c){if(!a){if(c.tenantId==null&&c._agentRecaptchaConfig!=null)return c._agentRecaptchaConfig.siteKey;if(c.tenantId!=null&&c._tenantRecaptchaConfigs[c.tenantId]!==void 0)return c._tenantRecaptchaConfigs[c.tenantId].siteKey}return new Promise(async(l,m)=>{rM(c,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(d=>{if(d.recaptchaKey===void 0)m(new Error("recaptcha Enterprise site key undefined"));else{const u=new sM(d);return c.tenantId==null?c._agentRecaptchaConfig=u:c._tenantRecaptchaConfigs[c.tenantId]=u,l(u.siteKey)}}).catch(d=>{m(d)})})}function i(c,l,m){const d=window.grecaptcha;eC(d)?d.enterprise.ready(()=>{d.enterprise.execute(c,{action:n}).then(u=>{l(u)}).catch(()=>{l(V5)})}):m(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new CM().execute("siteKey",{action:"verify"}):new Promise((c,l)=>{s(this.auth).then(async m=>{if(!a&&eC(window.grecaptcha)&&xu.scriptInjectionDeferred)await xu.scriptInjectionDeferred.promise,i(m,c,l);else{if(typeof window>"u"){l(new Error("RecaptchaVerifier is only supported in browser"));return}let d=wM();d.length!==0&&(d+=m+`&onload=${iC}`),xu.scriptInjectionDeferred=new Jh,window[iC]=()=>{var u;(u=xu.scriptInjectionDeferred)==null||u.resolve()},q5(d).then(()=>{var u;return(u=xu.scriptInjectionDeferred)==null?void 0:u.promise}).then(()=>{i(m,c,l)}).catch(u=>{l(u)})}}).catch(m=>{l(m)})})}}xu.scriptInjectionDeferred=null;async function oC(t,n,a,s=!1,i=!1){const c=new xu(t);let l;if(i)l=V5;else try{l=await c.verify(a)}catch{l=await c.verify(a,!0)}const m={...n};if(a==="mfaSmsEnrollment"||a==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in m){const d=m.phoneEnrollmentInfo.phoneNumber,u=m.phoneEnrollmentInfo.recaptchaToken;Object.assign(m,{phoneEnrollmentInfo:{phoneNumber:d,recaptchaToken:u,captchaResponse:l,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in m){const d=m.phoneSignInInfo.recaptchaToken;Object.assign(m,{phoneSignInInfo:{recaptchaToken:d,captchaResponse:l,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return m}return s?Object.assign(m,{captchaResp:l}):Object.assign(m,{captchaResponse:l}),Object.assign(m,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(m,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),m}async function hb(t,n,a,s,i){var c;if((c=t._getRecaptchaConfig())!=null&&c.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const l=await oC(t,n,a,a==="getOobCode");return s(t,l)}else return s(t,n).catch(async l=>
979{if(l.code==="auth/missing-recaptcha-token"){console.log(`${a} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const m=await oC(t,n,a,a==="getOobCode");return s(t,m)}else return Promise.reject(l)})}/** 980 * @license 981 * Copyright 2020 Google LLC 982 * 983 * Licensed under the Apache License, Version 2.0 (the "License"); 984 * you may not use this file except in compliance with the License. 985 * You may obtain a copy of the License at 986 * 987 * http://www.apache.org/licenses/LICENSE-2.0 988 * 989 * Unless required by applicable law or agreed to in writing, software 990 * distributed under the License is distributed on an "AS IS" BASIS, 991 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 992 * See the License for the specific language governing permissions and 993 * limitations under the License. 994 */function _M(t,n){const a=nw(t,"auth");if(a.isInitialized()){const i=a.getImmediate(),c=a.getOptions();if(Bh(c,n??{}))return i;ml(i,"already-initialized")}return a.initialize({options:n})}function kM(t,n){const a=(n==null?void 0:n.persistence)||[],s=(Array.isArray(a)?a:[a]).map(jd);n!=null&&n.errorMap&&t._updateErrorMap(n.errorMap),t._initializeWithPersistence(s,n==null?void 0:n.popupRedirectResolver)}function DM(t,n,a){const s=Qu(t);ss(/^https?:\/\//.test(n),s,"invalid-emulator-scheme");const i=!1,c=H5(n),{host:l,port:m}=EM(n),d=m===null?"":`:${m}`,u={url:`${c}//${l}${d}/`},f=Object.freeze({host:l,port:m,protocol:c.replace(":",""),options:Object.freeze({disableWarnings:i})});if(!s._canInitEmulator){ss(s.config.emulator&&s.emulatorConfig,s,"emulator-config-failed"),ss(Bh(u,s.config.emulator)&&Bh(f,s.emulatorConfig),s,"emulator-config-failed");return}s.config.emulator=u,s.emulatorConfig=f,s.settings.appVerificationDisabledForTesting=!0,Cg(l)?b5(`${c}//${l}${d}`):PM()}function H5(t){const n=t.indexOf(":");return n<0?"":t.substr(0,n+1)}function EM(t){const n=H5(t),a=/(\/\/)?([^?#/]+)/.exec(t.substr(n.length));if(!a)return{host:"",port:null};const s=a[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(s);if(i){const c=i[1];return{host:c,port:cC(s.substr(c.length+1))}}else{const[c,l]=s.split(":");return{host:c,port:cC(l)}}}function cC(t){if(!t)return null;const n=Number(t);return isNaN(n)?null:n}function PM(){function t(){const n=document.createElement("p"),a=n.style;n.innerText="Running in emulator mode. Do not use with production credentials.",a.position="fixed",a.width="100%",a.backgroundColor="#ffffff",a.border=".1em solid #000000",a.color="#b50000",a.bottom="0px",a.left="0px",a.margin="0px",a.zIndex="10000",a.textAlign="center",n.classList.add("firebase-emulator-warning"),document.body.appendChild(n)}typeof console<"u"&&typeof console.info=="function"&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?window.addEventListener("DOMContentLoaded",t):t())}/** 995 * @license 996 * Copyright 2020 Google LLC 997 * 998 * Licensed under the Apache License, Version 2.0 (the "License"); 999 * you may not use this file except in compliance with the License. 1000 * You may obtain a copy of the License at 1001 * 1002 * http://www.apache.org/licenses/LICENSE-2.0 1003 * 1004 * Unless required by applicable law or agreed to in writing, software 1005 * distributed under the License is distributed on an "AS IS" BASIS, 1006 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1007 * See the License for the specific language governing permissions and 1008 * limitations under the License. 1009 */class cw{constructor(n,a){this.providerId=n,this.signInMethod=a}toJSON(){return xd("not implemented")}_getIdTokenResponse(n){return xd("not implemented")}_linkToIdToken(n,a){return xd("not implemented")}_getReauthenticationResolver(n){return xd("not implemented")}}async function RM(t,n){return fl(t,"POST","/v1/accounts:update",n)}async function TM(t,n){return fl(t,"POST","/v1/accounts:signUp",n)}/** 1010 * @license 1011 * Copyright 2020 Google LLC 1012 * 1013 * Licensed under the Apache License, Version 2.0 (the "License");
1014 * you may not use this file except in compliance with the License. 1015 * You may obtain a copy of the License at 1016 * 1017 * http://www.apache.org/licenses/LICENSE-2.0 1018 * 1019 * Unless required by applicable law or agreed to in writing, software 1020 * distributed under the License is distributed on an "AS IS" BASIS, 1021 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1022 * See the License for the specific language governing permissions and 1023 * limitations under the License. 1024 */async function MM(t,n){return Ig(t,"POST","/v1/accounts:signInWithPassword",Td(t,n))}async function $M(t,n){return fl(t,"POST","/v1/accounts:sendOobCode",Td(t,n))}async function OM(t,n){return $M(t,n)}/** 1025 * @license 1026 * Copyright 2020 Google LLC 1027 * 1028 * Licensed under the Apache License, Version 2.0 (the "License"); 1029 * you may not use this file except in compliance with the License. 1030 * You may obtain a copy of the License at 1031 * 1032 * http://www.apache.org/licenses/LICENSE-2.0 1033 * 1034 * Unless required by applicable law or agreed to in writing, software 1035 * distributed under the License is distributed on an "AS IS" BASIS, 1036 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1037 * See the License for the specific language governing permissions and 1038 * limitations under the License. 1039 */async function LM(t,n){return Ig(t,"POST","/v1/accounts:signInWithEmailLink",Td(t,n))}async function BM(t,n){return Ig(t,"POST","/v1/accounts:signInWithEmailLink",Td(t,n))}/** 1040 * @license 1041 * Copyright 2020 Google LLC 1042 * 1043 * Licensed under the Apache License, Version 2.0 (the "License"); 1044 * you may not use this file except in compliance with the License. 1045 * You may obtain a copy of the License at 1046 * 1047 * http://www.apache.org/licenses/LICENSE-2.0 1048 * 1049 * Unless required by applicable law or agreed to in writing, software 1050 * distributed under the License is distributed on an "AS IS" BASIS, 1051 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1052 * See the License for the specific language governing permissions and 1053 * limitations under the License. 1054 */class rg extends cw{constructor(n,a,s,i=null){super("password",s),this._email=n,this._password=a,this._tenantId=i}static _fromEmailAndPassword(n,a){return new rg(n,a,"password")}static _fromEmailAndCode(n,a,s=null){return new rg(n,a,"emailLink",s)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(n){const a=typeof n=="string"?JSON.parse(n):n;if(a!=null&&a.email&&(a!=null&&a.password)){if(a.signInMethod==="password")return this._fromEmailAndPassword(a.email,a.password);if(a.signInMethod==="emailLink")return this._fromEmailAndCode(a.email,a.password,a.tenantId)}return null}async _getIdTokenResponse(n){switch(this.signInMethod){case"password":const a={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return hb(n,a,"signInWithPassword",MM);case"emailLink":return LM(n,{email:this._email,oobCode:this._password});default:ml(n,"internal-error")}}async _linkToIdToken(n,a){switch(this.signInMethod){case"password":const s={idToken:a,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return hb(n,s,"signUpPassword",TM);case"emailLink":return BM(n,{idToken:a,email:this._email,oobCode:this._password});default:ml(n,"internal-error")}}_getReauthenticationResolver(n){return this._getIdTokenResponse(n)}}/** 1055 * @license 1056 * Copyright 2020 Google LLC 1057 * 1058 * Licensed under the Apache License, Version 2.0 (the "License"); 1059 * you may not use this file except in compliance with the License. 1060 * You may obtain a copy of the License at 1061 * 1062 * http://www.apache.org/licenses/LICENSE-2.0 1063 * 1064 * Unless required by applicable law or agreed to in writing, software 1065 * distributed under the License is distributed on an "AS IS" BASIS, 1066 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1067 * See the License for the specific language governing permissions and 1068 * limitations under the License. 1069 */async function dp(t,n){return Ig(t,"POST","/v1/accounts:signInWithIdp",Td(t,n))}/** 1070 * @license 1071 * Copyright 2020 Google LLC 1072 * 1073 * Licensed under the Apache License, Version 2.0 (the "License");
1074 * you may not use this file except in compliance with the License. 1075 * You may obtain a copy of the License at 1076 * 1077 * http://www.apache.org/licenses/LICENSE-2.0 1078 * 1079 * Unless required by applicable law or agreed to in writing, software 1080 * distributed under the License is distributed on an "AS IS" BASIS, 1081 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1082 * See the License for the specific language governing permissions and 1083 * limitations under the License. 1084 */const FM="http://localhost";class zh extends cw{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(n){const a=new zh(n.providerId,n.signInMethod);return n.idToken||n.accessToken?(n.idToken&&(a.idToken=n.idToken),n.accessToken&&(a.accessToken=n.accessToken),n.nonce&&!n.pendingToken&&(a.nonce=n.nonce),n.pendingToken&&(a.pendingToken=n.pendingToken)):n.oauthToken&&n.oauthTokenSecret?(a.accessToken=n.oauthToken,a.secret=n.oauthTokenSecret):ml("argument-error"),a}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,n
1084once:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(n){const a=typeof n=="string"?JSON.parse(n):n,{providerId:s,signInMethod:i,...c}=a;if(!s||!i)return null;const l=new zh(s,i);return l.idToken=c.idToken||void 0,l.accessToken=c.accessToken||void 0,l.secret=c.secret,l.nonce=c.nonce,l.pendingToken=c.pendingToken||null,l}_getIdTokenResponse(n){const a=this.buildRequest();return dp(n,a)}_linkToIdToken(n,a){const s=this.buildRequest();return s.idToken=a,dp(n,s)}_getReauthenticationResolver(n){const a=this.buildRequest();return a.autoCreate=!1,dp(n,a)}buildRequest(){const n={requestUri:FM,returnSecureToken:!0};if(this.pendingToken)n.pendingToken=this.pendingToken;else{const a={};this.idToken&&(a.id_token=this.idToken),this.accessToken&&(a.access_token=this.accessToken),this.secret&&(a.oauth_token_secret=this.secret),a.providerId=this.providerId,this.nonce&&!this.pendingToken&&(a.nonce=this.nonce),n.postBody=Ap(a)}return n}}/** 1085 * @license 1086 * Copyright 2020 Google LLC 1087 * 1088 * Licensed under the Apache License, Version 2.0 (the "License"); 1089 * you may not use this file except in compliance with the License. 1090 * You may obtain a copy of the License at 1091 * 1092 * http://www.apache.org/licenses/LICENSE-2.0 1093 * 1094 * Unless required by applicable law or agreed to in writing, software 1095 * distributed under the License is distributed on an "AS IS" BASIS, 1096 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1097 * See the License for the specific language governing permissions and 1098 * limitations under the License. 1099 */function UM(t){switch(t){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}function zM(t){const n=Bf(Ff(t)).link,a=n?Bf(Ff(n)).deep_link_id:null,s=Bf(Ff(t)).deep_link_id;return(s?Bf(Ff(s)).link:null)||s||a||n||t}class lw{constructor(n){const a=Bf(Ff(n)),s=a.apiKey??null,i=a.oobCode??null,c=UM(a.mode??null);ss(s&&i&&c,"argument-error"),this.apiKey=s,this.operation=c,this.code=i,this.continueUrl=a.continueUrl??null,this.languageCode=a.lang??null,this.tenantId=a.tenantId??null}static parseLink(n){const a=zM(n);try{return new lw(a)}catch{return null}}}/** 1100 * @license 1101 * Copyright 2020 Google LLC 1102 * 1103 * Licensed under the Apache License, Version 2.0 (the "License"); 1104 * you may not use this file except in compliance with the License. 1105 * You may obtain a copy of the License at 1106 * 1107 * http://www.apache.org/licenses/LICENSE-2.0 1108 * 1109 * Unless required by applicable law or agreed to in writing, software 1110 * distributed under the License is distributed on an "AS IS" BASIS, 1111 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1112 * See the License for the specific language governing permissions and 1113 * limitations under the License. 1114 */class Cd{constructor(){this.providerId=Cd.PROVIDER_ID}static credential(n,a){return rg._fromEmailAndPassword(n,a)}static credentialWithLink(n,a){const s=lw.parseLink(a);return ss(s,"argument-error"),rg._fromEmailAndCode(n,s.code,s.tenantId)}}Cd.PROVIDER_ID="password";Cd.EMAIL_PASSWORD_SIGN_IN_METHOD="password";Cd.EMAIL_LINK_SIGN_IN_METHOD="emailLink";/** 1115 * @license 1116 * Copyright 2020 Google LLC 1117 * 1118 * Licensed under the Apache License, Version 2.0 (the "License"); 1119 * you may not use this file except in compliance with the License. 1120 * You may obtain a copy of the License at 1121 * 1122 * http://www.apache.org/licenses/LICENSE-2.0 1123 * 1124 * Unless required by applicable law or agreed to in writing, software 1125 * distributed under the License is distributed on an "AS IS" BASIS, 1126 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1127 * See the License for the specific language governing permissions and 1128 * limitations under the License. 1129 */class W5{constructor(n){this.providerId=n,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(n){this.defaultLanguageCode=n}setCustomParameters(n){return this.customParameters=n,this}getCustomParameters(){return this.customParameters}}/** 1130 * @license 1131 * Copyright 2019 Google LLC 1132 * 1133 * Licensed under the Apache License, Version 2.0 (the "License");
1134 * you may not use this file except in compliance with the License. 1135 * You may obtain a copy of the License at 1136 * 1137 * http://www.apache.org/licenses/LICENSE-2.0 1138 * 1139 * Unless required by applicable law or agreed to in writing, software 1140 * distributed under the License is distributed on an "AS IS" BASIS, 1141 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1142 * See the License for the specific language governing permissions and 1143 * limitations under the License. 1144 */class _g extends W5{constructor(){super(...arguments),this.scopes=[]}addScope(n){return this.scopes.includes(n)||this.scopes.push(n),this}getScopes(){return[...this.scopes]}}/** 1145 * @license 1146 * Copyright 2020 Google LLC 1147 * 1148 * Licensed under the Apache License, Version 2.0 (the "License"); 1149 * you may not use this file except in compliance with the License. 1150 * You may obtain a copy of the License at 1151 * 1152 * http://www.apache.org/licenses/LICENSE-2.0 1153 * 1154 * Unless required by applicable law or agreed to in writing, software 1155 * distributed under the License is distributed on an "AS IS" BASIS, 1156 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1157 * See the License for the specific language governing permissions and 1158 * limitations under the License. 1159 */class ju extends _g{constructor(){super("facebook.com")}static credential(n){return zh._fromParams({providerId:ju.PROVIDER_ID,signInMethod:ju.FACEBOOK_SIGN_IN_METHOD,accessToken:n})}static credentialFromResult(n){return ju.credentialFromTaggedObject(n)}static credentialFromError(n){return ju.credentialFromTaggedObject(n.customData||{})}static credentialFromTaggedObject({_tokenResponse:n}){if(!n||!("oauthAccessToken"in n)||!n.oauthAccessToken)return null;try{return ju.credential(n.oauthAccessToken)}catch{return null}}}ju.FACEBOOK_SIGN_IN_METHOD="facebook.com";ju.PROVIDER_ID="facebook.com";/** 1160 * @license 1161 * Copyright 2020 Google LLC 1162 * 1163 * Licensed under the Apache License, Version 2.0 (the "License"); 1164 * you may not use this file except in compliance with the License. 1165 * You may obtain a copy of the License at 1166 * 1167 * http://www.apache.org/licenses/LICENSE-2.0 1168 * 1169 * Unless required by applicable law or agreed to in writing, software 1170 * distributed under the License is distributed on an "AS IS" BASIS, 1171 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1172 * See the License for the specific language governing permissions and 1173 * limitations under the License. 1174 */class wu extends _g{constructor(){super("google.com"),this.addScope("profile")}static credential(n,a){return zh._fromParams({providerId:wu.PROVIDER_ID,signInMethod:wu.GOOGLE_SIGN_IN_METHOD,idToken:n,accessToken:a})}static credentialFromResult(n){return wu.credentialFromTaggedObject(n)}static credentialFromError(n){return wu.credentialFromTaggedObject(n.customData||{})}static credentialFromTaggedObject({_tokenResponse:n}){if(!n)return null;const{oauthIdToken:a,oauthAccessToken:s}=n;if(!a&&!s)return null;try{return wu.credential(a,s)}catch{return null}}}wu.GOOGLE_SIGN_IN_METHOD="google.com";wu.PROVIDER_ID="google.com";/** 1175 * @license 1176 * Copyright 2020 Google LLC 1177 * 1178 * Licensed under the Apache License, Version 2.0 (the "License"); 1179 * you may not use this file except in compliance with the License. 1180 * You may obtain a copy of the License at 1181 * 1182 * http://www.apache.org/licenses/LICENSE-2.0 1183 * 1184 * Unless required by applicable law or agreed to in writing, software 1185 * distributed under the License is distributed on an "AS IS" BASIS, 1186 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1187 * See the License for the specific language governing permissions and 1188 * limitations under the License. 1189 */class Nu extends _g{constructor(){super("github.com")}static credential(n){return zh._fromParams({providerId:Nu.PROVIDER_ID,signInMethod:Nu.GITHUB_SIGN_IN_METHOD,accessToken:n})}static credentialFromResult(n){return Nu.credentialFromTaggedObject(n)}static credentialFromError(n){return Nu.credentialFromTaggedObject(n.customData||{})}static credentialFromTaggedObject({_tokenResponse:n}){if(!n||!("oauthAccessToken"in n)||!n.oauthAccessToken)return null;try{return Nu.credential(n.oauthAccessToken)}catch{return null}}}Nu.GITHUB_SIGN_IN_METHOD="github.com";Nu.PROVIDER_ID="github.com";/** 1190 * @license 1191 * Copyright 2020 Google LLC 1192 * 1193 * Licensed under the Apache License, Version 2.0 (the "License");
1194 * you may not use this file except in compliance with the License. 1195 * You may obtain a copy of the License at 1196 * 1197 * http://www.apache.org/licenses/LICENSE-2.0 1198 * 1199 * Unless required by applicable law or agreed to in writing, software 1200 * distributed under the License is distributed on an "AS IS" BASIS, 1201 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1202 * See the License for the specific language governing permissions and 1203 * limitations under the License. 1204 */class Su extends _g{constructor(){super("twitter.com")}static credential(n,a){return zh._fromParams({providerId:Su.PROVIDER_ID,signInMethod:Su.TWITTER_SIGN_IN_METHOD,oauthToken:n,oauthTokenSecret:a})}static credentialFromResult(n){return Su.credentialFromTaggedObject(n)}static credentialFromError(n){return Su.credentialFromTaggedObject(n.customData||{})}static credentialFromTaggedObject({_tokenResponse:n}){if(!n)return null;const{oauthAccessToken:a,oauthTokenSecret:s}=n;if(!a||!s)return null;try{return Su.credential(a,s)}catch{return null}}}Su.TWITTER_SIGN_IN_METHOD="twitter.com";Su.PROVIDER_ID="twitter.com";/** 1205 * @license 1206 * Copyright 2020 Google LLC 1207 * 1208 * Licensed under the Apache License, Version 2.0 (the "License"); 1209 * you may not use this file except in compliance with the License. 1210 * You may obtain a copy of the License at 1211 * 1212 * http://www.apache.org/licenses/LICENSE-2.0 1213 * 1214 * Unless required by applicable law or agreed to in writing, software 1215 * distributed under the License is distributed on an "AS IS" BASIS, 1216 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1217 * See the License for the specific language governing permissions and 1218 * limitations under the License. 1219 */async function qM(t,n){return Ig(t,"POST","/v1/accounts:signUp",Td(t,n))}/** 1220 * @license 1221 * Copyright 2020 Google LLC 1222 * 1223 * Licensed under the Apache License, Version 2.0 (the "License"); 1224 * you may not use this file except in compliance with the License. 1225 * You may obtain a copy of the License at 1226 * 1227 * http://www.apache.org/licenses/LICENSE-2.0 1228 * 1229 * Unless required by applicable law or agreed to in writing, software 1230 * distributed under the License is distributed on an "AS IS" BASIS, 1231 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1232 * See the License for the specific language governing permissions and 1233 * limitations under the License. 1234 */class qh{constructor(n){this.user=n.user,this.providerId=n.providerId,this._tokenResponse=n._tokenResponse,this.operationType=n.operationType}static async _fromIdTokenResponse(n,a,s,i=!1){const c=await ll._fromIdTokenResponse(n,s,i),l=lC(s);return new qh({user:c,providerId:l,_tokenResponse:s,operationType:a})}static async _forOperation(n,a,s){await n._updateTokensIfNecessary(s,!0);const i=lC(s);return new qh({user:n,providerId:i,_tokenResponse:s,operationType:a})}}function lC(t){return t.providerId?t.providerId:"phoneNumber"in t?"phone":null}/** 1235 * @license 1236 * Copyright 2020 Google LLC 1237 * 1238 * Licensed under the Apache License, Version 2.0 (the "License"); 1239 * you may not use this file except in compliance with the License. 1240 * You may obtain a copy of the License at 1241 * 1242 * http://www.apache.org/licenses/LICENSE-2.0 1243 * 1244 * Unless required by applicable law or agreed to in writing, software 1245 * distributed under the License is distributed on an "AS IS" BASIS, 1246 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1247 * See the License for the specific language governing permissions and 1248 * limitations under the License. 1249 */class mb extends Yu{constructor(n,a,s,i){super(a.code,a.message),this.operationType=s,this.user=i,Object.setPrototypeOf(this,mb.prototype),this.customData={appName:n.name,tenantId:n.tenantId??void 0,_serverResponse:a.customData._serverResponse,operationType:s}}static _fromErrorAndOperation(n,a,s,i){return new mb(n,a,s,i)}}function G5(t,n,a,s){return(n==="reauthenticate"?a._getReauthenticationResolver(t):a._getIdTokenResponse(t)).catch(c=>{throw c.code==="auth/multi-factor-auth-required"?mb._fromErrorAndOperation(t,c,n,s):c})}
1249async function VM(t,n,a=!1){const s=await Uh(t,n._linkToIdToken(t.auth,await t.getIdToken()),a);return qh._forOperation(t,"link",s)}/** 1250 * @license 1251 * Copyright 2019 Google LLC 1252 * 1253 * Licensed under the Apache License, Version 2.0 (the "License"); 1254 * you may not use this file except in compliance with the License. 1255 * You may obtain a copy of the License at 1256 * 1257 * http://www.apache.org/licenses/LICENSE-2.0 1258 * 1259 * Unless required by applicable law or agreed to in writing, software 1260 * distributed under the License is distributed on an "AS IS" BASIS, 1261 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1262 * See the License for the specific language governing permissions and 1263 * limitations under the License. 1264 */async function Y5(t,n,a=!1){const{auth:s}=t;if(Tc(s.app))return Promise.reject(Sd(s));const i="reauthenticate";try{const c=await Uh(t,G5(s,i,n,t),a);ss(c.idToken,s,"internal-error");const l=iw(c.idToken);ss(l,s,"internal-error");const{sub:m}=l;return ss(t.uid===m,s,"user-mismatch"),qh._forOperation(t,i,c)}catch(c){throw(c==null?void 0:c.code)==="auth/user-not-found"&&ml(s,"user-mismatch"),c}}/** 1265 * @license 1266 * Copyright 2020 Google LLC 1267 * 1268 * Licensed under the Apache License, Version 2.0 (the "License"); 1269 * you may not use this file except in compliance with the License. 1270 * You may obtain a copy of the License at 1271 * 1272 * http://www.apache.org/licenses/LICENSE-2.0 1273 * 1274 * Unless required by applicable law or agreed to in writing, software 1275 * distributed under the License is distributed on an "AS IS" BASIS, 1276 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1277 * See the License for the specific language governing permissions and 1278 * limitations under the License. 1279 */async function Q5(t,n,a=!1){if(Tc(t.app))return Promise.reject(Sd(t));const s="signIn",i=await G5(t,s,n),c=await qh._fromIdTokenResponse(t,s,i);return a||await t._updateCurrentUser(c.user),c}async function HM(t,n){return Q5(Qu(t),n)}async function B0(t,n){return Y5(Jr(t),n)}/** 1280 * @license 1281 * Copyright 2020 Google LLC 1282 * 1283 * Licensed under the Apache License, Version 2.0 (the "License"); 1284 * you may not use this file except in compliance with the License. 1285 * You may obtain a copy of the License at 1286 * 1287 * http://www.apache.org/licenses/LICENSE-2.0 1288 * 1289 * Unless required by applicable law or agreed to in writing, software 1290 * distributed under the License is distributed on an "AS IS" BASIS, 1291 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1292 * See the License for the specific language governing permissions and 1293 * limitations under the License. 1294 */async function J5(t){const n=Qu(t);n._getPasswordPolicyInternal()&&await n._updatePasswordPolicy()}async function a1(t,n,a){const s=Qu(t);await hb(s,{requestType:"PASSWORD_RESET",email:n,clientType:"CLIENT_TYPE_WEB"},"getOobCode",OM)}async function WM(t,n,a){if(Tc(t.app))return Promise.reject(Sd(t));const s=Qu(t),l=await hb(s,{returnSecureToken:!0,email:n,password:a,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",qM).catch(d=>{throw d.code==="auth/password-does-not-meet-requirements"&&J5(t),d}),m=await qh._fromIdTokenResponse(s,"signIn",l);return await s._updateCurrentUser(m.user),m}function GM(t,n,a){return Tc(t.app)?Promise.reject(Sd(t)):HM(Jr(t),Cd.credential(n,a)).catch(async s=>{throw s.code==="auth/password-does-not-meet-requirements"&&J5(t),s})}/** 1295 * @license 1296 * Copyright 2020 Google LLC 1297 * 1298 * Licensed under the Apache License, Version 2.0 (the "License"); 1299 * you may not use this file except in compliance with the License. 1300 * You may obtain a copy of the License at 1301 * 1302 * http://www.apache.org/licenses/LICENSE-2.0 1303 * 1304 * Unless required by applicable law or agreed to in writing, software 1305 * distributed under the License is distributed on an "AS IS" BASIS, 1306 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1307 * See the License for the specific language governing permissions and 1308 * limitations under the License. 1309 */async function YM(t,n){return fl(t,"POST","/v1/accounts:update",n)}/** 1310 * @license 1311 * Copyright 2020 Google LLC 1312 * 1313 * Licensed under the Apache License, Version 2.0 (the "License");
1314 * you may not use this file except in compliance with the License. 1315 * You may obtain a copy of the License at 1316 * 1317 * http://www.apache.org/licenses/LICENSE-2.0 1318 * 1319 * Unless required by applicable law or agreed to in writing, software 1320 * distributed under the License is distributed on an "AS IS" BASIS, 1321 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1322 * See the License for the specific language governing permissions and 1323 * limitations under the License. 1324 */async function QM(t,{displayName:n,photoURL:a}){if(n===void 0&&a===void 0)return;const s=Jr(t),c={idToken:await s.getIdToken(),displayName:n,photoUrl:a,returnSecureToken:!0},l=await Uh(s,YM(s.auth,c));s.displayName=l.displayName||null,s.photoURL=l.photoUrl||null;const m=s.providerData.find(({providerId:d})=>d==="password");m&&(m.displayName=s.displayName,m.photoURL=s.photoURL),await s._updateTokensIfNecessary(l)}function JM(t,n){return KM(Jr(t),null,n)}async function KM(t,n,a){const{auth:s}=t,c={idToken:await t.getIdToken(),returnSecureToken:!0};a&&(c.password=a);const l=await Uh(t,RM(s,c));await t._updateTokensIfNecessary(l,!0)}/** 1325 * @license 1326 * Copyright 2020 Google LLC 1327 * 1328 * Licensed under the Apache License, Version 2.0 (the "License"); 1329 * you may not use this file except in compliance with the License. 1330 * You may obtain a copy of the License at 1331 * 1332 * http://www.apache.org/licenses/LICENSE-2.0 1333 * 1334 * Unless required by applicable law or agreed to in writing, software 1335 * distributed under the License is distributed on an "AS IS" BASIS, 1336 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1337 * See the License for the specific language governing permissions and 1338 * limitations under the License. 1339 */function XM(t,n){return Jr(t).setPersistence(n)}function ZM(t,n,a,s){return Jr(t).onIdTokenChanged(n,a,s)}function e$(t,n,a){return Jr(t).beforeAuthStateChanged(n,a)}function K5(t,n,a,s){return Jr(t).onAuthStateChanged(n,a,s)}function dl(t){return Jr(t).signOut()}async function t$(t){return Jr(t).delete()}const pb="__sak";/** 1340 * @license 1341 * Copyright 2019 Google LLC 1342 * 1343 * Licensed under the Apache License, Version 2.0 (the "License"); 1344 * you may not use this file except in compliance with the License. 1345 * You may obtain a copy of the License at 1346 * 1347 * http://www.apache.org/licenses/LICENSE-2.0 1348 * 1349 * Unless required by applicable law or agreed to in writing, software 1350 * distributed under the License is distributed on an "AS IS" BASIS, 1351 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1352 * See the License for the specific language governing permissions and 1353 * limitations under the License. 1354 */class X5{constructor(n,a){this.storageRetriever=n,this.type=a}_isAvailable(){try{return this.storage?(this.storage.setItem(pb,"1"),this.storage.removeItem(pb),Promise.resolve(!0)):Promise.resolve(!1)}catch{return Promise.resolve(!1)}}_set(n,a){return this.storage.setItem(n,JSON.stringify(a)),Promise.resolve()}_get(n){const a=this.storage.getItem(n);return Promise.resolve(a?JSON.parse(a):null)}_remove(n){return this.storage.removeItem(n),Promise.resolve()}get storage(){return this.storageRetriever()}}/** 1355 * @license 1356 * Copyright 2020 Google LLC 1357 * 1358 * Licensed under the Apache License, Version 2.0 (the "License"); 1359 * you may not use this file except in compliance with the License. 1360 * You may obtain a copy of the License at 1361 * 1362 * http://www.apache.org/licenses/LICENSE-2.0 1363 * 1364 * Unless required by applicable law or agreed to in writing, software 1365 * distributed under the License is distributed on an "AS IS" BASIS, 1366 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1367 * See the License for the specific language governing permissions and 1368 * limitations under the License. 1369 */const n$=1e3,a$=10;class Z5 extends X5{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(n,a)=>this.onStorageEvent(n,a),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=U5(),this._shouldAllowMigration=!0}forAllChangedKeys(n){for(const a of Object.keys(this.listeners)){const s=this.storage.getItem(a),i=this.localCache[a];s!==i&&n(a,i,s)}}onStorageEvent(n,a=!1){if(!n.key){this.forAllChangedKeys((l,m,d)=>{this.notifyListeners(l,d)});return}const s=n.key;a?this.detachListener():this.stopPolling();const i=()=>{const l=this.storage.getItem(s);!a&&this.localCache[s]===l||this.notifyListeners(s,l)},c=this.storage.getItem(s);fM()&&c!==n.newValue&&n.newValue!==n.oldValue?setTimeout(i,a$):i()}notifyListeners(n,a){this.localCache[n]=a;const s=this.listeners[n];if(s)for(const i of Array.from(s))i(a&&JSON.parse(a))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((n,a,s)=>{this.onStorageEvent(new StorageEvent("storage",{key:n,oldValue:a,newValue:s}),!0)})},n$)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(n,a){Object.keys(this.listeners).length===0&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[n]||(this.listeners[n]=new Set,this.localCache[n]=this.storage.getItem(n)),this.listeners[n].add(a)}_removeListener(n,a){this.listeners[n]&&(this.listeners[n].delete(a),this.listeners[n].size===0&&delete this.listeners[n]),Object.keys(this.listeners).length===0&&(this.detachListener(),this.stopPolling())}async _set(n,a){await super._set(n,a),this.localCache[n]=JSON.stringify(a)}async _get(n){const a=await super._get(n);return this.localCache[n]=JSON.stringify(a),a}async _remove(n){await super._remove(n),delete this.localCache[n]}}Z5.type="LOCAL";const ek=Z5;/** 1370 * @license 1371 * Copyright 2020 Google LLC 1372 * 1373 * Licensed under the Apache License, Version 2.0 (the "License");
1374 * you may not use this file except in compliance with the License. 1375 * You may obtain a copy of the License at 1376 * 1377 * http://www.apache.org/licenses/LICENSE-2.0 1378 * 1379 * Unless required by applicable law or agreed to in writing, software 1380 * distributed under the License is distributed on an "AS IS" BASIS, 1381 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1382 * See the License for the specific language governing permissions and 1383 * limitations under the License. 1384 */class tk extends X5{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(n,a){}_removeListener(n,a){}}tk.type="SESSION";const nk=tk;/** 1385 * @license 1386 * Copyright 2019 Google LLC 1387 * 1388 * Licensed under the Apache License, Version 2.0 (the "License"); 1389 * you may not use this file except in compliance with the License. 1390 * You may obtain a copy of the License at 1391 * 1392 * http://www.apache.org/licenses/LICENSE-2.0 1393 * 1394 * Unless required by applicable law or agreed to in writing, software 1395 * distributed under the License is distributed on an "AS IS" BASIS, 1396 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1397 * See the License for the specific language governing permissions and 1398 * limitations under the License. 1399 */function s$(t){return Promise.all(t.map(async n=>{try{return{fulfilled:!0,value:await n}}catch(a){return{fulfilled:!1,reason:a}}}))}/** 1400 * @license 1401 * Copyright 2019 Google LLC 1402 * 1403 * Licensed under the Apache License, Version 2.0 (the "License"); 1404 * you may not use this file except in compliance with the License. 1405 * You may obtain a copy of the License at 1406 * 1407 * http://www.apache.org/licenses/LICENSE-2.0 1408 * 1409 * Unless required by applicable law or agreed to in writing, software 1410 * distributed under the License is distributed on an "AS IS" BASIS, 1411 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1412 * See the License for the specific language governing permissions and 1413 * limitations under the License. 1414 */class Wb{constructor(n){this.eventTarget=n,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(n){const a=this.receivers.find(i=>i.isListeningto(n));if(a)return a;const s=new Wb(n);return this.receivers.push(s),s}isListeningto(n){return this.eventTarget===n}async handleEvent(n){const a=n,{eventId:s,eventType:i,data:c}=a.data,l=this.handlersMap[i];if(!(l!=null&&l.size))return;a.ports[0].postMessage({status:"ack",eventId:s,eventType:i});const m=Array.from(l).map(async u=>u(a.origin,c)),d=await s$(m);a.ports[0].postMessage({status:"done",eventId:s,eventType:i,response:d})}_subscribe(n,a){Object.keys(this.handlersMap).length===0&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[n]||(this.handlersMap[n]=new Set),this.handlersMap[n].add(a)}_unsubscribe(n,a){this.handlersMap[n]&&a&&this.handlersMap[n].delete(a),(!a||this.handlersMap[n].size===0)&&delete this.handlersMap[n],Object.keys(this.handlersMap).length===0&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}Wb.receivers=[];/** 1415 * @license 1416 * Copyright 2020 Google LLC 1417 * 1418 * Licensed under the Apache License, Version 2.0 (the "License"); 1419 * you may not use this file except in compliance with the License. 1420 * You may obtain a copy of the License at 1421 * 1422 * http://www.apache.org/licenses/LICENSE-2.0 1423 * 1424 * Unless required by applicable law or agreed to in writing, software 1425 * distributed under the License is distributed on an "AS IS" BASIS, 1426 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1427 * See the License for the specific language governing permissions and 1428 * limitations under the License. 1429 */function dw(t="",n=10){let a="";for(let s=0;s<n;s++)a+=Math.floor(Math.random()*10);return t+a}/** 1430 * @license 1431 * Copyright 2019 Google LLC 1432 * 1433 * Licensed under the Apache License, Version 2.0 (the "License"); 1434 * you may not use this file except in compliance with the License. 1435 * You may obtain a copy of the License at 1436 * 1437 * http://www.apache.org/licenses/LICENSE-2.0 1438 * 1439 * Unless required by applicable law or agreed to in writing, softw
1439are 1440 * distributed under the License is distributed on an "AS IS" BASIS, 1441 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1442 * See the License for the specific language governing permissions and 1443 * limitations under the License. 1444 */class r${constructor(n){this.target=n,this.handlers=new Set}removeMessageHandler(n){n.messageChannel&&(n.messageChannel.port1.removeEventListener("message",n.onMessage),n.messageChannel.port1.close()),this.handlers.delete(n)}async _send(n,a,s=50){const i=typeof MessageChannel<"u"?new MessageChannel:null;if(!i)throw new Error("connection_unavailable");let c,l;return new Promise((m,d)=>{const u=dw("",20);i.port1.start();const f=setTimeout(()=>{d(new Error("unsupported_event"))},s);l={messageChannel:i,onMessage(g){const p=g;if(p.data.eventId===u)switch(p.data.status){case"ack":clearTimeout(f),c=setTimeout(()=>{d(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),m(p.data.response);break;default:clearTimeout(f),clearTimeout(c),d(new Error("invalid_response"));break}}},this.handlers.add(l),i.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:n,eventId:u,data:a},[i.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}/** 1445 * @license 1446 * Copyright 2020 Google LLC 1447 * 1448 * Licensed under the Apache License, Version 2.0 (the "License"); 1449 * you may not use this file except in compliance with the License. 1450 * You may obtain a copy of the License at 1451 * 1452 * http://www.apache.org/licenses/LICENSE-2.0 1453 * 1454 * Unless required by applicable law or agreed to in writing, software 1455 * distributed under the License is distributed on an "AS IS" BASIS, 1456 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1457 * See the License for the specific language governing permissions and 1458 * limitations under the License. 1459 */function zl(){return window}function i$(t){zl().location.href=t}/** 1460 * @license 1461 * Copyright 2020 Google LLC. 1462 * 1463 * Licensed under the Apache License, Version 2.0 (the "License"); 1464 * you may not use this file except in compliance with the License. 1465 * You may obtain a copy of the License at 1466 * 1467 * http://www.apache.org/licenses/LICENSE-2.0 1468 * 1469 * Unless required by applicable law or agreed to in writing, software 1470 * distributed under the License is distributed on an "AS IS" BASIS, 1471 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1472 * See the License for the specific language governing permissions and 1473 * limitations under the License. 1474 */function ak(){return typeof zl().WorkerGlobalScope<"u"&&typeof zl().importScripts=="function"}async function o$(){if(!(navigator!=null&&navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}function c$(){var t;return((t=navigator==null?void 0:navigator.serviceWorker)==null?void 0:t.controller)||null}function l$(){return ak()?self:null}/** 1475 * @license 1476 * Copyright 2019 Google LLC 1477 * 1478 * Licensed under the Apache License, Version 2.0 (the "License"); 1479 * you may not use this file except in compliance with the License. 1480 * You may obtain a copy of the License at 1481 * 1482 * http://www.apache.org/licenses/LICENSE-2.0 1483 * 1484 * Unless required by applicable law or agreed to in writing, software 1485 * distributed under the License is distributed on an "AS IS" BASIS, 1486 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1487 * See the License for the specific language governing permissions and 1488 * limitations under the License. 1489 */const sk="firebaseLocalStorageDb",d$=1,fb="firebaseLocalStorage",rk="fbase_key";class kg{constructor(n){this.request=n}toPromise(){return new Promise((n,a)=>{this.request.addEventListener("success",()=>{n(this.request.result)}),this.request.addEventListener("error",()=>{a(this.request.error)})})}}function Gb(t,n){return t.transaction([fb],n?"readwrite":"readonly").objectStore(fb)}function u$(){const t=indexedDB.deleteDatabase(sk);return new kg(t).toPromise()}function ik(){const t=indexedDB.open(sk,d$);return new Promise((n,a)=>{t.addEventListener("error",()=>{a(t.error)}),t.addEventListener("upgradeneeded",()=>{const s=t.result;try{s.createObjectStore(fb,{keyPath:rk})}catch(i){a(i)}}),t.addEventListener("success",async()=>{const s=t.result;s.objectStoreNames.contains(fb)?n(s):(s.close(),await u$(),n(await ik()))})})}async function dC(t,n,a){const s=Gb(t,!0).put({[rk]:n,value:a});return new kg(s).toPromise()}async function h$(t,n){const a=Gb(t,!1).get(n),s=await new kg(a).toPromise();return s===void 0?null:s.value}function uC(t,n){const a=Gb(t,!0).delete(n);return new kg(a).toPromise()}const m$=800,p$=3;class ok{registerLifecycleListeners(){typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("pagehide",this.onPageHide),window.addEventListener("pageshow",this.onPageShow))}unregisterLifecycleListeners(){typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("pagehide",this.onPageHide),window.removeEventListener("pageshow",this.onPageShow))}constructor(){this.type="LOCAL",this.dbPromise=null,this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.isClosing=!1,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this.onPageHide=()=>{this.isClosing=!0,this.stopPolling(),this.dbPromise&&(this.dbPromise.then(n=>n.close()).catch(()=>{}),this.dbPromise=null)},this.onPageShow=()=>{this.isClosing&&(this.isClosing=!1,Object.keys(this.listeners).length>0&&this.startPolling())},this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){if(this.isClosing)throw new Error("Database is closing");return this.dbPromise?this.dbPromise:(this.dbPromise=ik(),this.dbPromise.catch(()=>{this.dbPromise=null}),this.dbPromise)}async _withRetries(n){let a=0;for(;;)try{const s=await this._openDb();return await n(s)}catch(s){if(this.isClosing||a++>p$)throw s;this.dbPromise&&((await this.dbPromise).close(),this.dbPromise=null)}}async initializeServiceWorkerMessaging(){return ak()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Wb._getInstance(l$()),this.receiver._subscribe("keyChanged",async(n,a)=>({keyProcessed:(await this._poll()).includes(a.key)})),this.receiver._subscribe("ping",async(n,a)=>["keyChanged"])}async initializeSender(){var a,s;if(this.activeServiceWorker=await o$(),!this.activeServiceWorker)return;this.sender=new r$(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(a=n[0])!=null&&a.fulfilled&&(s=n[0])!=null&&s.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(n){if(!(!this.sender||!this.activeServiceWorker||c$()!==this.activeServiceWorker))try{await this.sender._send("keyChanged",{key:n},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{return indexedDB?(await this._withRetries(async n=>{await dC(n,pb,"1"),await uC(n,pb)}),!0):!1}catch{}return!1}async _withPendingWrite(n){this.pendingWrites++;try{await n()}finally{this.pendingWrites--}}async _set(n,a){return this._withPendingWrite(async()=>(await this._withRetries(s=>dC(s,n,a)),this.localCache[n]=a,this.notifyServiceWorker(n)))}async _get(n){const a=await this._withRetries(s=>h$(s,n));return this.localCache[n]=a,a}async _remove(n){return this._withPendingWrite(async()=>(await this._withRetries(a=>uC(a,n)),delete this.localCache[n],this.notifyServiceWorker(n)))}async _poll(){if(this.isClosing)return[];try{const n=await this._withRetries(i=>{const c=Gb(i,!1).getAll();return new kg(c).toPromise()});if(this.isClosing)return[];if(!n)return[];if(this.pendingWrites!==0)return[];const a=[],s=new Set;if(n.length!==0)for(const{fbase_key:i,value:c}of n)s.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(c)&&(this.notifyListeners(i,c),a.push(i));for(const i of Object.keys(this.localCache))this.localCache[i]&&!s.has(i)&&(this.notifyListeners(i,null),a.push(i));return a}catch(n){return this.isClosing||I5(`Firebase Auth cross-tab polling failed with error: ${n}`),[]}}notifyListeners(n,a){this.localCache[n]=a;const s=this.listeners[n];if(s)for(const i of Array.from(s))i(a)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),m$)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(n,a){Object.keys(this.listeners).length===0&&(this.startPolling(),this.registerLifecycleListeners()),this.listeners[n]||(this.listeners[n]=new Set,this._get(n)),this.listeners[n].add(a)}_removeListener(n,a){this.listeners[n]&&(this.listeners[n].delete(a),this.listeners[n].size===0&&delete this.listeners[n]),Object.keys(this.listeners).length===0&&(this.stopPolling(),this.unregisterLifecycleListeners())}}ok.type="LOCAL";const f$=ok;new Ag(3e4,6e4);/** 1490 * @license 1491 * Copyright 2021 Google LLC 1492 * 1493 * Licensed under the Apache License, Version 2.0 (the "License");
1494 * you may not use this file except in compliance with the License. 1495 * You may obtain a copy of the License at 1496 * 1497 * http://www.apache.org/licenses/LICENSE-2.0 1498 * 1499 * Unless required by applicable law or agreed to in writing, software 1500 * distributed under the License is distributed on an "AS IS" BASIS, 1501 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1502 * See the License for the specific language governing permissions and 1503 * limitations under the License. 1504 */function g$(t,n){return n?jd(n):(ss(t._popupRedirectResolver,t,"argument-error"),t._popupRedirectResolver)}/** 1505 * @license 1506 * Copyright 2019 Google LLC 1507 * 1508 * Licensed under the Apache License, Version 2.0 (the "License"); 1509 * you may not use this file except in compliance with the License. 1510 * You may obtain a copy of the License at 1511 * 1512 * http://www.apache.org/licenses/LICENSE-2.0 1513 * 1514 * Unless required by applicable law or agreed to in writing, software 1515 * distributed under the License is distributed on an "AS IS" BASIS, 1516 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1517 * See the License for the specific language governing permissions and 1518 * limitations under the License. 1519 */class uw extends cw{constructor(n){super("custom","custom"),this.params=n}_getIdTokenResponse(n){return dp(n,this._buildIdpRequest())}_linkToIdToken(n,a){return dp(n,this._buildIdpRequest(a))}_getReauthenticationResolver(n){return dp(n,this._buildIdpRequest())}_buildIdpRequest(n){const a={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return n&&(a.idToken=n),a}}function y$(t){return Q5(t.auth,new uw(t),t.bypassAuthState)}function v$(t){const{auth:n,user:a}=t;return ss(a,n,"internal-error"),Y5(a,new uw(t),t.bypassAuthState)}async function b$(t){const{auth:n,user:a}=t;return ss(a,n,"internal-error"),VM(a,new uw(t),t.bypassAuthState)}/** 1520 * @license 1521 * Copyright 2020 Google LLC 1522 * 1523 * Licensed under the Apache License, Version 2.0 (the "License"); 1524 * you may not use this file except in compliance with the License. 1525 * You may obtain a copy of the License at 1526 * 1527 * http://www.apache.org/licenses/LICENSE-2.0 1528 * 1529 * Unless required by applicable law or agreed to in writing, software 1530 * distributed under the License is distributed on an "AS IS" BASIS, 1531 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1532 * See the License for the specific language governing permissions and 1533 * limitations under the License. 1534 */class ck{constructor(n,a,s,i,c=!1){this.auth=n,this.resolver=s,this.user=i,this.bypassAuthState=c,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(a)?a:[a]}execute(){return new Promise(async(n,a)=>{this.pendingPromise={resolve:n,reject:a};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(s){this.reject(s)}})}async onAuthEvent(n){const{urlResponse:a,sessionId:s,postBody:i,tenantId:c,error:l,type:m}=n;if(l){this.reject(l);return}const d={auth:this.auth,requestUri:a,sessionId:s,tenantId:c||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(m)(d))}catch(u){this.reject(u)}}onError(n){this.reject(n)}getIdpTask(n){switch(n){case"signInViaPopup":case"signInViaRedirect":return y$;case"linkViaPopup":case"linkViaRedirect":return b$;case"reauthViaPopup":case"reauthViaRedirect":return v$;default:ml(this.auth,"internal-error")}}resolve(n){Pd(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(n),this.unregisterAndCleanUp()}reject(n){Pd(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(n),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}/** 1535 * @license 1536 * Copyright 2020 Google LLC 1537 * 1538 * Licensed under the Apache License, Version 2.0 (the "License");
1539 * you may not use this file except in compliance with the License. 1540 * You may obtain a copy of the License at 1541 * 1542 * http://www.apache.org/licenses/LICENSE-2.0 1543 * 1544 * Unless required by applicable law or agreed to in writing, software 1545 * distributed under the License is distributed on an "AS IS" BASIS, 1546 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1547 * See the License for the specific language governing permissions and 1548 * limitations under the License. 1549 */const x$=new Ag(2e3,1e4);class tp extends ck{constructor(n,a,s,i,c){super(n,a,i,c),this.provider=s,this.authWindow=null,this.pollId=null,tp.currentPopupAction&&tp.currentPopupAction.cancel(),tp.currentPopupAction=this}async executeNotNull(){const n=await this.execute();return ss(n,this.auth,"internal-error"),n}async onExecution(){Pd(this.filter.length===1,"Popup operations only handle one event");const n=dw();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],n),this.authWindow.associatedEvent=n,this.resolver._originValidation(this.auth).catch(a=>{this.reject(a)}),this.resolver._isIframeWebStorageSupported(this.auth,a=>{a||this.reject(Ul(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var n;return((n=this.authWindow)==null?void 0:n.associatedEvent)||null}cancel(){this.reject(Ul(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,tp.currentPopupAction=null}pollUserCancellation(){const n=()=>{var a,s;if((s=(a=this.authWindow)==null?void 0:a.window)!=null&&s.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Ul(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(n,x$.get())};n()}}tp.currentPopupAction=null;/** 1550 * @license 1551 * Copyright 2020 Google LLC 1552 * 1553 * Licensed under the Apache License, Version 2.0 (the "License"); 1554 * you may not use this file except in compliance with the License. 1555 * You may obtain a copy of the License at 1556 * 1557 * http://www.apache.org/licenses/LICENSE-2.0 1558 * 1559 * Unless required by applicable law or agreed to in writing, software 1560 * distributed under the License is distributed on an "AS IS" BASIS, 1561 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1562 * See the License for the specific language governing permissions and 1563 * limitations under the License. 1564 */const j$="pendingRedirect",Zv=new Map;class w$ extends ck{constructor(n,a,s=!1){super(n,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],a,void 0,s),this.eventId=null}async execute(){let n=Zv.get(this.auth._key());if(!n){try{const s=await N$(this.resolver,this.auth)?await super.execute():null;n=()=>Promise.resolve(s)}catch(a){n=()=>Promise.reject(a)}Zv.set(this.auth._key(),n)}return this.bypassAuthState||Zv.set(this.auth._key(),()=>Promise.resolve(null)),n()}async onAuthEvent(n){if(n.type==="signInViaRedirect")return super.onAuthEvent(n);if(n.type==="unknown"){this.resolve(null);return}if(n.eventId){const a=await this.auth._redirectUserForId(n.eventId);if(a)return this.user=a,super.onAuthEvent(n);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function N$(t,n){const a=A$(n),s=C$(t);if(!await s._isAvailable())return!1;const i=await s._get(a)==="true";return await s._remove(a),i}function S$(t,n){Zv.set(t._key(),n)}function C$(t){return jd(t._redirectPersistence)}function A$(t){return Xv(j$,t.config.apiKey,t.name)}async function I$(t,n,a=!1){if(Tc(t.app))return Promise.reject(Sd(t));const s=Qu(t),i=g$(s,n),l=await new w$(s,i,a).execute();return l&&!a&&(delete l.user._redirectEventId,await s._persistUserIfCurrent(l.user),await s._setRedirectUser(null,n)),l}/** 1565 * @license 1566 * Copyright 2020 Google LLC 1567 * 1568 * Licensed under the Apache License, Version 2.0 (the "License"); 1569 * you may not use this file except in compliance with the License. 1570 * You may obtain a copy of the License at 1571 * 1572 * http://www.apache.org/licenses/LICENSE-2.0 1573 * 1574 * Unless required by applicable law or agreed to in writing, softw
1574are 1575 * distributed under the License is distributed on an "AS IS" BASIS, 1576 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1577 * See the License for the specific language governing permissions and 1578 * limitations under the License. 1579 */const _$=600*1e3;class k${constructor(n){this.auth=n,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(n){this.consumers.add(n),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,n)&&(this.sendToConsumer(this.queuedRedirectEvent,n),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(n){this.consumers.delete(n)}onEvent(n){if(this.hasEventBeenHandled(n))return!1;let a=!1;return this.consumers.forEach(s=>{this.isEventForConsumer(n,s)&&(a=!0,this.sendToConsumer(n,s),this.saveEventToCache(n))}),this.hasHandledPotentialRedirect||!D$(n)||(this.hasHandledPotentialRedirect=!0,a||(this.queuedRedirectEvent=n,a=!0)),a}sendToConsumer(n,a){var s;if(n.error&&!lk(n)){const i=((s=n.error.code)==null?void 0:s.split("auth/")[1])||"internal-error";a.onError(Ul(this.auth,i))}else a.onAuthEvent(n)}isEventForConsumer(n,a){const s=a.eventId===null||!!n.eventId&&n.eventId===a.eventId;return a.filter.includes(n.type)&&s}hasEventBeenHandled(n){return Date.now()-this.lastProcessedEventTime>=_$&&this.cachedEventUids.clear(),this.cachedEventUids.has(hC(n))}saveEventToCache(n){this.cachedEventUids.add(hC(n)),this.lastProcessedEventTime=Date.now()}}function hC(t){return[t.type,t.eventId,t.sessionId,t.tenantId].filter(n=>n).join("-")}function lk({type:t,error:n}){return t==="unknown"&&(n==null?void 0:n.code)==="auth/no-auth-event"}function D$(t){switch(t.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return lk(t);default:return!1}}/** 1580 * @license 1581 * Copyright 2020 Google LLC 1582 * 1583 * Licensed under the Apache License, Version 2.0 (the "License"); 1584 * you may not use this file except in compliance with the License. 1585 * You may obtain a copy of the License at 1586 * 1587 * http://www.apache.org/licenses/LICENSE-2.0 1588 * 1589 * Unless required by applicable law or agreed to in writing, software 1590 * distributed under the License is distributed on an "AS IS" BASIS, 1591 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1592 * See the License for the specific language governing permissions and 1593 * limitations under the License. 1594 */async function E$(t,n={}){return fl(t,"GET","/v1/projects",n)}/** 1595 * @license 1596 * Copyright 2020 Google LLC 1597 * 1598 * Licensed under the Apache License, Version 2.0 (the "License"); 1599 * you may not use this file except in compliance with the License. 1600 * You may obtain a copy of the License at 1601 * 1602 * http://www.apache.org/licenses/LICENSE-2.0 1603 * 1604 * Unless required by applicable law or agreed to in writing, software 1605 * distributed under the License is distributed on an "AS IS" BASIS, 1606 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1607 * See the License for the specific language governing permissions and 1608 * limitations under the License. 1609 */const P$=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,R$=/^https?/;async function T$(t){if(t.config.emulator)return;const{authorizedDomains:n}=await E$(t);for(const a of n)try{if(M$(a))return}catch{}ml(t,"unauthorized-domain")}function M$(t){const n=t1(),{protocol:a,hostname:s}=new URL(n);if(t.startsWith("chrome-extension://")){const l=new URL(t);return l.hostname===""&&s===""?a==="chrome-extension:"&&t.replace("chrome-extension://","")===n.replace("chrome-extension://",""):a==="chrome-extension:"&&l.hostname===s}if(!R$.test(a))return!1;if(P$.test(t))return s===t;const i=t.replace(/\./g,"\\.");return new RegExp("^(.+\\."+i+"|"+i+")$","i").test(s)}/** 1610 * @license 1611 * Copyright 2020 Google LLC. 1612 * 1613 * Licensed under the Apache License, Version 2.0 (the "License"); 1614 * you may not use this file except in compliance with the License. 1615 * You may obtain a copy of the License at 1616 * 1617 * http://www.apache.org/licenses/LICENSE-2.0 1618 * 1619 * Unless required by applicable law or agreed to in writing, softw
1619are 1620 * distributed under the License is distributed on an "AS IS" BASIS, 1621 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1622 * See the License for the specific language governing permissions and 1623 * limitations under the License. 1624 */const $$=new Ag(3e4,6e4);function mC(){const t=zl().___jsl;if(t!=null&&t.H){for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let a=0;a<t.CP.length;a++)t.CP[a]=null}}function O$(t){return new Promise((n,a)=>{var i,c,l;function s(){mC(),gapi.load("gapi.iframes",{callback:()=>{n(gapi.iframes.getContext())},ontimeout:()=>{mC(),a(Ul(t,"network-request-failed"))},timeout:$$.get()})}if((c=(i=zl().gapi)==null?void 0:i.iframes)!=null&&c.Iframe)n(gapi.iframes.getContext());else if((l=zl().gapi)!=null&&l.load)s();else{const m=SM("iframefcb");return zl()[m]=()=>{gapi.load?s():a(Ul(t,"network-request-failed"))},q5(`${NM()}?onload=${m}`).catch(d=>a(d))}}).catch(n=>{throw eb=null,n})}let eb=null;function L$(t){return eb=eb||O$(t),eb}/** 1625 * @license 1626 * Copyright 2020 Google LLC. 1627 * 1628 * Licensed under the Apache License, Version 2.0 (the "License"); 1629 * you may not use this file except in compliance with the License. 1630 * You may obtain a copy of the License at 1631 * 1632 * http://www.apache.org/licenses/LICENSE-2.0 1633 * 1634 * Unless required by applicable law or agreed to in writing, software 1635 * distributed under the License is distributed on an "AS IS" BASIS, 1636 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1637 * See the License for the specific language governing permissions and 1638 * limitations under the License. 1639 */const B$=new Ag(5e3,15e3),F$="__/auth/iframe",U$="emulator/auth/iframe",z$={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},q$=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function V$(t){const n=t.config;ss(n.authDomain,t,"auth-domain-config-required");const a=n.emulator?rw(n,U$):`https://${t.config.authDomain}/${F$}`,s={apiKey:n.apiKey,appName:t.name,v:Ip},i=q$.get(t.config.apiHost);i&&(s.eid=i);const c=t._getFrameworks();return c.length&&(s.fw=c.join(",")),`${a}?${Ap(s).slice(1)}`}async function H$(t){const n=await L$(t),a=zl().gapi;return ss(a,t,"internal-error"),n.open({where:document.body,url:V$(t),messageHandlersFilter:a.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:z$,dontclear:!0},s=>new Promise(async(i,c)=>{await s.restyle({setHideOnLeave:!1});const l=Ul(t,"network-request-failed"),m=zl().setTimeout(()=>{c(l)},B$.get());function d(){zl().clearTimeout(m),i(s)}s.ping(d).then(d,()=>{c(l)})}))}/** 1640 * @license 1641 * Copyright 2020 Google LLC. 1642 * 1643 * Licensed under the Apache License, Version 2.0 (the "License"); 1644 * you may not use this file except in compliance with the License. 1645 * You may obtain a copy of the License at 1646 * 1647 * http://www.apache.org/licenses/LICENSE-2.0 1648 * 1649 * Unless required by applicable law or agreed to in writing, software 1650 * distributed under the License is distributed on an "AS IS" BASIS, 1651 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1652 * See the License for the specific language governing permissions and 1653 * limitations under the License. 1654 */const W$={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"},G$=500,Y$=600,Q$="_blank",J$="http://localhost";class pC{constructor(n){this.window=n,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch{}}}function K$(t,n,a,s=G$,i=Y$){const c=Math.max((window.screen.availHeight-i)/2,0).toString(),l=Math.max((window.screen.availWidth-s)/2,0).toString();let m="";const d={...W$,width:s.toString(),height:i.toString(),top:c,left:l},u=Io().toLowerCase();a&&(m=$5(u)?Q$:a),T5(u)&&(n=n||J$,d.scrollbars="yes");const f=Object.entries(d).reduce((p,[y,b])=>`${p}${y}=${b},`,"");if(pM(u)&&m!=="_self")return X$(n||"",m),new pC(null);const g=window.open(n||"",m,f);ss(g,t,"popup-blocked");try{g.focus()}catch{}return new pC(g)}
1654function X$(t,n){const a=document.createElement("a");a.href=t,a.target=n;const s=document.createEvent("MouseEvent");s.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),a.dispatchEvent(s)}/** 1655 * @license 1656 * Copyright 2021 Google LLC 1657 * 1658 * Licensed under the Apache License, Version 2.0 (the "License"); 1659 * you may not use this file except in compliance with the License. 1660 * You may obtain a copy of the License at 1661 * 1662 * http://www.apache.org/licenses/LICENSE-2.0 1663 * 1664 * Unless required by applicable law or agreed to in writing, software 1665 * distributed under the License is distributed on an "AS IS" BASIS, 1666 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1667 * See the License for the specific language governing permissions and 1668 * limitations under the License. 1669 */const Z$="__/auth/handler",eO="emulator/auth/handler",tO=encodeURIComponent("fac");async function fC(t,n,a,s,i,c){ss(t.config.authDomain,t,"auth-domain-config-required"),ss(t.config.apiKey,t,"invalid-api-key");const l={apiKey:t.config.apiKey,appName:t.name,authType:a,redirectUrl:s,v:Ip,eventId:i};if(n instanceof W5){n.setDefaultLanguage(t.languageCode),l.providerId=n.providerId||"",Yj(n.getCustomParameters())||(l.customParameters=JSON.stringify(n.getCustomParameters()));for(const[f,g]of Object.entries({}))l[f]=g}if(n instanceof _g){const f=n.getScopes().filter(g=>g!=="");f.length>0&&(l.scopes=f.join(","))}t.tenantId&&(l.tid=t.tenantId);const m=l;for(const f of Object.keys(m))m[f]===void 0&&delete m[f];const d=await t._getAppCheckToken(),u=d?`#${tO}=${encodeURIComponent(d)}`:"";return`${nO(t)}?${Ap(m).slice(1)}${u}`}function nO({config:t}){return t.emulator?rw(t,eO):`https://${t.authDomain}/${Z$}`}/** 1670 * @license 1671 * Copyright 2020 Google LLC 1672 * 1673 * Licensed under the Apache License, Version 2.0 (the "License"); 1674 * you may not use this file except in compliance with the License. 1675 * You may obtain a copy of the License at 1676 * 1677 * http://www.apache.org/licenses/LICENSE-2.0 1678 * 1679 * Unless required by applicable law or agreed to in writing, software 1680 * distributed under the License is distributed on an "AS IS" BASIS, 1681 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1682 * See the License for the specific language governing permissions and 1683 * limitations under the License. 1684 */const F0="webStorageSupport";class aO{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=nk,this._completeRedirectFn=I$,this._overrideRedirectResult=S$}async _openPopup(n,a,s,i){var l;Pd((l=this.eventManagers[n._key()])==null?void 0:l.manager,"_initialize() not called before _openPopup()");const c=await fC(n,a,s,t1(),i);return K$(n,c,dw())}async _openRedirect(n,a,s,i){await this._originValidation(n);const c=await fC(n,a,s,t1(),i);return i$(c),new Promise(()=>{})}_initialize(n){const a=n._key();if(this.eventManagers[a]){const{manager:i,promise:c}=this.eventManagers[a];return i?Promise.resolve(i):(Pd(c,"If manager is not set, promise should be"),c)}const s=this.initAndGetManager(n);return this.eventManagers[a]={promise:s},s.catch(()=>{delete this.eventManagers[a]}),s}async initAndGetManager(n){const a=await H$(n),s=new k$(n);return a.register("authEvent",i=>(ss(i==null?void 0:i.authEvent,n,"invalid-auth-event"),{status:s.onEvent(i.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[n._key()]={manager:s},this.iframes[n._key()]=a,s}_isIframeWebStorageSupported(n,a){this.iframes[n._key()].send(F0,{type:F0},i=>{var l;const c=(l=i==null?void 0:i[0])==null?void 0:l[F0];c!==void 0&&a(!!c),ml(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(n){const a=n._key();return this.originValidationPromises[a]||(this.originValidationPromises[a]=T$(n)),this.originValidationPromises[a]}get _shouldInitProactively(){return U5()||M5()||ow()}}const sO=aO;var gC="@firebase/auth",yC="1.13.5";/** 1685 * @license 1686 * Copyright 2020 Google LLC 1687 * 1688 * Licensed under the Apache License, Version 2.0 (the "License"); 1689 * you may not use this file except in compliance with the License. 1690 * You may obtain a copy of the License at 1691 * 1692 * http://www.apache.org/licenses/LICENSE-2.0 1693 * 1694 * Unless required by applicable law or agreed to in writing, softw
1694are 1695 * distributed under the License is distributed on an "AS IS" BASIS, 1696 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1697 * See the License for the specific language governing permissions and 1698 * limitations under the License. 1699 */class rO{constructor(n){this.auth=n,this.internalListeners=new Map}getUid(){var n;return this.assertAuthConfigured(),((n=this.auth.currentUser)==null?void 0:n.uid)||null}async getToken(n){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(n)}:null}addAuthTokenListener(n){if(this.assertAuthConfigured(),this.internalListeners.has(n))return;const a=this.auth.onIdTokenChanged(s=>{n((s==null?void 0:s.stsTokenManager.accessToken)||null)});this.internalListeners.set(n,a),this.updateProactiveRefresh()}removeAuthTokenListener(n){this.assertAuthConfigured();const a=this.internalListeners.get(n);a&&(this.internalListeners.delete(n),a(),this.updateProactiveRefresh())}assertAuthConfigured(){ss(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}/** 1700 * @license 1701 * Copyright 2020 Google LLC 1702 * 1703 * Licensed under the Apache License, Version 2.0 (the "License"); 1704 * you may not use this file except in compliance with the License. 1705 * You may obtain a copy of the License at 1706 * 1707 * http://www.apache.org/licenses/LICENSE-2.0 1708 * 1709 * Unless required by applicable law or agreed to in writing, software 1710 * distributed under the License is distributed on an "AS IS" BASIS, 1711 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1712 * See the License for the specific language governing permissions and 1713 * limitations under the License. 1714 */function iO(t){switch(t){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}function oO(t){pp(new Fh("auth",(n,{options:a})=>{const s=n.getProvider("app").getImmediate(),i=n.getProvider("heartbeat"),c=n.getProvider("app-check-internal"),{apiKey:l,authDomain:m}=s.options;ss(l&&!l.includes(":"),"invalid-api-key",{appName:s.name});const d={apiKey:l,authDomain:m,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:z5(t)},u=new xM(s,i,c,d);return kM(u,a),u},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((n,a,s)=>{n.getProvider("auth-internal").initialize()})),pp(new Fh("auth-internal",n=>{const a=Qu(n.getProvider("auth").getImmediate());return(s=>new rO(s))(a)},"PRIVATE").setInstantiationMode("EXPLICIT")),Eu(gC,yC,iO(t)),Eu(gC,yC,"esm2020")}/** 1715 * @license 1716 * Copyright 2021 Google LLC 1717 * 1718 * Licensed under the Apache License, Version 2.0 (the "License"); 1719 * you may not use this file except in compliance with the License. 1720 * You may obtain a copy of the License at 1721 * 1722 * http://www.apache.org/licenses/LICENSE-2.0 1723 * 1724 * Unless required by applicable law or agreed to in writing, software 1725 * distributed under the License is distributed on an "AS IS" BASIS, 1726 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1727 * See the License for the specific language governing permissions and 1728 * limitations under the License. 1729 */const cO=300,lO=g5("authIdTokenMaxAge")||cO;let vC=null;const dO=t=>async n=>{const a=n&&await n.getIdTokenResult(),s=a&&(new Date().getTime()-Date.parse(a.issuedAtTime))/1e3;if(s&&s>lO)return;const i=a==null?void 0:a.token;vC!==i&&(vC=i,await fetch(t,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))};function gb(t=w5()){const n=nw(t,"auth");if(n.isInitialized())return n.getImmediate();const a=_M(t,{popupRedirectResolver:sO,persistence:[f$,ek,nk]}),s=g5("authTokenSyncURL");if(s&&typeof isSecureContext=="boolean"&&isSecureContext){const c=new URL(s,location.origin);if(location.origin===c.origin){const l=dO(c.toString());e$(a,l,()=>l(a.currentUser)),ZM(a,m=>l(m))}}const i=p5("auth");return i&&DM(a,`http://${i}`),a}function uO(){var t;return((t=document.getElementsByTagName("head"))==null?void 0:t[0])??document}jM({loadJS(t){return new Promise((n,a)=>{const s=document.createElement("script");s.setAttribute("src",t),s.onload=n,s.onerror=i=>{const c=Ul("internal-error");c.customData=i,a(c)},s.type="text/javascript",s.charset="UTF-8",uO().appendChild(s)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="});oO("Browser");var bC={};const xC="@firebase/database",jC="1.1.5";/** 1730 * @license 1731 * Copyright 2019 Google LLC 1732 * 1733 * Licensed under the Apache License, Version 2.0 (the "License");
1734 * you may not use this file except in compliance with the License. 1735 * You may obtain a copy of the License at 1736 * 1737 * http://www.apache.org/licenses/LICENSE-2.0 1738 * 1739 * Unless required by applicable law or agreed to in writing, software 1740 * distributed under the License is distributed on an "AS IS" BASIS, 1741 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1742 * See the License for the specific language governing permissions and 1743 * limitations under the License. 1744 */let dk="";function hO(t){dk=t}/** 1745 * @license 1746 * Copyright 2017 Google LLC 1747 * 1748 * Licensed under the Apache License, Version 2.0 (the "License"); 1749 * you may not use this file except in compliance with the License. 1750 * You may obtain a copy of the License at 1751 * 1752 * http://www.apache.org/licenses/LICENSE-2.0 1753 * 1754 * Unless required by applicable law or agreed to in writing, software 1755 * distributed under the License is distributed on an "AS IS" BASIS, 1756 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1757 * See the License for the specific language governing permissions and 1758 * limitations under the License. 1759 */class mO{constructor(n){this.domStorage_=n,this.prefix_="firebase:"}set(n,a){a==null?this.domStorage_.removeItem(this.prefixedName_(n)):this.domStorage_.setItem(this.prefixedName_(n),Ri(a))}get(n){const a=this.domStorage_.getItem(this.prefixedName_(n));return a==null?null:ag(a)}remove(n){this.domStorage_.removeItem(this.prefixedName_(n))}prefixedName_(n){return this.prefix_+n}toString(){return this.domStorage_.toString()}}/** 1760 * @license 1761 * Copyright 2017 Google LLC 1762 * 1763 * Licensed under the Apache License, Version 2.0 (the "License"); 1764 * you may not use this file except in compliance with the License. 1765 * You may obtain a copy of the License at 1766 * 1767 * http://www.apache.org/licenses/LICENSE-2.0 1768 * 1769 * Unless required by applicable law or agreed to in writing, software 1770 * distributed under the License is distributed on an "AS IS" BASIS, 1771 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1772 * See the License for the specific language governing permissions and 1773 * limitations under the License. 1774 */class pO{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(n,a){a==null?delete this.cache_[n]:this.cache_[n]=a}get(n){return pl(this.cache_,n)?this.cache_[n]:null}remove(n){delete this.cache_[n]}}/** 1775 * @license 1776 * Copyright 2017 Google LLC 1777 * 1778 * Licensed under the Apache License, Version 2.0 (the "License"); 1779 * you may not use this file except in compliance with the License. 1780 * You may obtain a copy of the License at 1781 * 1782 * http://www.apache.org/licenses/LICENSE-2.0 1783 * 1784 * Unless required by applicable law or agreed to in writing, software 1785 * distributed under the License is distributed on an "AS IS" BASIS, 1786 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1787 * See the License for the specific language governing permissions and 1788 * limitations under the License. 1789 */const uk=function(t){try{if(typeof window<"u"&&typeof window[t]<"u"){const n=window[t];return n.setItem("firebase:sentinel","cache"),n.removeItem("firebase:sentinel"),new mO(n)}}catch{}return new pO},Sh=uk("localStorage"),fO=uk("sessionStorage");/** 1790 * @license 1791 * Copyright 2017 Google LLC 1792 * 1793 * Licensed under the Apache License, Version 2.0 (the "License"); 1794 * you may not use this file except in compliance with the License. 1795 * You may obtain a copy of the License at 1796 * 1797 * http://www.apache.org/licenses/LICENSE-2.0 1798 * 1799 * Unless required by applicable law or agreed to in writing, software 1800 * distributed under the License is distributed on an "AS IS" BASIS, 1801 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1802 * See the License for the specific language governing permissions and 1803 * limitations under the License. 1804 */const up=new ew("@firebase/database"),hk=(function(){let t=1;return function(){return t++}})(),mk=function(t){const n=UR(t),a=new OR;a.update(n);const s=a.digest();return K1.encodeByteArray(s)},Dg=function(...t){let n="";for(let a=0;a<t.length;a++){const s=t[a];Array.isArray(s)||s&&typeof s=="object"&&typeof s.length=="number"?n+=Dg.apply(null,s):typeof s=="object"?n+=Ri(s):n+=s,n+=" "}return n};let Vf=null,wC=!0;const gO=function(t,n){la(!0,"Can't turn on custom loggers persistently."),up.logLevel=br.VERBOSE,Vf=up.log.bind(up)},Xi=function(...t){if(wC===!0&&(wC=!1,Vf===null&&fO.get("logging_enabled")===!0&&gO()),Vf){const n=Dg.apply(null,t);Vf(n)}},Eg=function(t){return function(...n){Xi(t,...n)}},s1=function(...t){const n="FIREBASE INTERNAL ERROR: "+Dg(...t);up.error(n)},Rd=function(...t){const n=`FIREBASE FATAL ERROR: ${Dg(...t)}`;throw up.error(n),new Error(n)},Co=function(...t){const n="FIREBASE WARNING: "+Dg(...t);up.warn(n)},yO=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&Co("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},hw=function(t){return typeof t=="number"&&(t!==t||t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)}
1804,vO=function(t){if(document.readyState==="complete")t();else{let n=!1;const a=function(){if(!document.body){setTimeout(a,Math.floor(10));return}n||(n=!0,t())};document.addEventListener?(document.addEventListener("DOMContentLoaded",a,!1),window.addEventListener("load",a,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&a()}),window.attachEvent("onload",a))}},Vh="[MIN_NAME]",$u="[MAX_NAME]",Kh=function(t,n){if(t===n)return 0;if(t===Vh||n===$u)return-1;if(n===Vh||t===$u)return 1;{const a=NC(t),s=NC(n);return a!==null?s!==null?a-s===0?t.length-n.length:a-s:-1:s!==null?1:t<n?-1:1}},bO=function(t,n){return t===n?0:t<n?-1:1},pf=function(t,n){if(n&&t in n)return n[t];throw new Error("Missing required key ("+t+") in object: "+Ri(n))},mw=function(t){if(typeof t!="object"||t===null)return Ri(t);const n=[];for(const s in t)n.push(s);n.sort();let a="{";for(let s=0;s<n.length;s++)s!==0&&(a+=","),a+=Ri(n[s]),a+=":",a+=mw(t[n[s]]);return a+="}",a},pk=function(t,n){const a=t.length;if(a<=n)return[t];const s=[];for(let i=0;i<a;i+=n)i+n>a?s.push(t.substring(i,a)):s.push(t.substring(i,i+n));return s};function eo(t,n){for(const a in t)t.hasOwnProperty(a)&&n(a,t[a])}const fk=function(t){la(!hw(t),"Invalid JSON number");const n=11,a=52,s=(1<<n-1)-1;let i,c,l,m,d;t===0?(c=0,l=0,i=1/t===-1/0?1:0):(i=t<0,t=Math.abs(t),t>=Math.pow(2,1-s)?(m=Math.min(Math.floor(Math.log(t)/Math.LN2),s),c=m+s,l=Math.round(t*Math.pow(2,a-m)-Math.pow(2,a))):(c=0,l=Math.round(t/Math.pow(2,1-s-a))));const u=[];for(d=a;d;d-=1)u.push(l%2?1:0),l=Math.floor(l/2);for(d=n;d;d-=1)u.push(c%2?1:0),c=Math.floor(c/2);u.push(i?1:0),u.reverse();const f=u.join("");let g="";for(d=0;d<64;d+=8){let p=parseInt(f.substr(d,8),2).toString(16);p.length===1&&(p="0"+p),g=g+p}return g.toLowerCase()},xO=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},jO=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function wO(t,n){let a="Unknown Error";t==="too_big"?a="The data requested exceeds the maximum size that can be accessed with a single request.":t==="permission_denied"?a="Client doesn't have permission to access the desired data.":t==="unavailable"&&(a="The service is unavailable");const s=new Error(t+" at "+n._path.toString()+": "+a);return s.code=t.toUpperCase(),s}const NO=new RegExp("^-?(0*)\\d{1,10}$"),SO=-2147483648,CO=2147483647,NC=function(t){if(NO.test(t)){const n=Number(t);if(n>=SO&&n<=CO)return n}return null},_p=function(t){try{t()}catch(n){setTimeout(()=>{const a=n.stack||"";throw Co("Exception was thrown by user callback.",a),n},Math.floor(0))}},AO=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},Hf=function(t,n){const a=setTimeout(t,n);return typeof a=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(a):typeof a=="object"&&a.unref&&a.unref(),a};/** 1805 * @license 1806 * Copyright 2021 Google LLC 1807 * 1808 * Licensed under the Apache License, Version 2.0 (the "License"); 1809 * you may not use this file except in compliance with the License. 1810 * You may obtain a copy of the License at 1811 * 1812 * http://www.apache.org/licenses/LICENSE-2.0 1813 * 1814 * Unless required by applicable law or agreed to in writing, software 1815 * distributed under the License is distributed on an "AS IS" BASIS, 1816 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1817 * See the License for the specific language governing permissions and 1818 * limitations under the License. 1819 */class IO{constructor(n,a){this.appCheckProvider=a,this.appName=n.name,Tc(n)&&n.settings.appCheckToken&&(this.serverAppAppCheckToken=n.settings.appCheckToken),this.appCheck=a==null?void 0:a.getImmediate({optional:!0}),this.appCheck||a==null||a.get().then(s=>this.appCheck=s)}getToken(n){if(this.serverAppAppCheckToken){if(n)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(n):new Promise((a,s)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(a,s):a(null)},0)})}addTokenChangeListener(n){var a;(a=this.appCheckProvider)==null||a.get().then(s=>s.addTokenListener(n))}notifyForInvalidToken(){Co(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}/** 1820 * @license 1821 * Copyright 2017 Google LLC 1822 * 1823 * Licensed under the Apache License, Version 2.0 (the "License");
1824 * you may not use this file except in compliance with the License. 1825 * You may obtain a copy of the License at 1826 * 1827 * http://www.apache.org/licenses/LICENSE-2.0 1828 * 1829 * Unless required by applicable law or agreed to in writing, software 1830 * distributed under the License is distributed on an "AS IS" BASIS, 1831 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1832 * See the License for the specific language governing permissions and 1833 * limitations under the License. 1834 */class _O{constructor(n,a,s){this.appName_=n,this.firebaseOptions_=a,this.authProvider_=s,this.auth_=null,this.auth_=s.getImmediate({optional:!0}),this.auth_||s.onInit(i=>this.auth_=i)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(a=>a&&a.code==="auth/token-not-initialized"?(Xi("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(a)):new Promise((a,s)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(a,s):a(null)},0)})}addTokenChangeListener(n){this.auth_?this.auth_.addAuthTokenListener(n):this.authProvider_.get().then(a=>a.addAuthTokenListener(n))}removeTokenChangeListener(n){this.authProvider_.get().then(a=>a.removeAuthTokenListener(n))}notifyForInvalidToken(){let n='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?n+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?n+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':n+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Co(n)}}class tb{constructor(n){this.accessToken=n}getToken(n){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(n){n(this.accessToken)}removeTokenChangeListener(n){}notifyForInvalidToken(){}}tb.OWNER="owner";/** 1835 * @license 1836 * Copyright 2017 Google LLC 1837 * 1838 * Licensed under the Apache License, Version 2.0 (the "License"); 1839 * you may not use this file except in compliance with the License. 1840 * You may obtain a copy of the License at 1841 * 1842 * http://www.apache.org/licenses/LICENSE-2.0 1843 * 1844 * Unless required by applicable law or agreed to in writing, software 1845 * distributed under the License is distributed on an "AS IS" BASIS, 1846 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1847 * See the License for the specific language governing permissions and 1848 * limitations under the License. 1849 */const pw="5",gk="v",yk="s",vk="r",bk="f",xk=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,jk="ls",wk="p",r1="ac",Nk="websocket",Sk="long_polling";/** 1850 * @license 1851 * Copyright 2017 Google LLC 1852 * 1853 * Licensed under the Apache License, Version 2.0 (the "License"); 1854 * you may not use this file except in compliance with the License. 1855 * You may obtain a copy of the License at 1856 * 1857 * http://www.apache.org/licenses/LICENSE-2.0 1858 * 1859 * Unless required by applicable law or agreed to in writing, software 1860 * distributed under the License is distributed on an "AS IS" BASIS, 1861 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1862 * See the License for the specific language governing permissions and 1863 * limitations under the License. 1864 */class Ck{constructor(n,a,s,i,c=!1,l="",m=!1,d=!1,u=null){this.secure=a,this.namespace=s,this.webSocketOnly=i,this.nodeAdmin=c,this.persistenceKey=l,this.includeNamespaceInQueryParams=m,this.isUsingEmulator=d,this.emulatorOptions=u,this._host=n.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Sh.get("host:"+n)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(n){n!==this.internalHost&&(this.internalHost=n,this.isCacheableHost()&&Sh.set("host:"+this._host,this.internalHost))}toString(){let n=this.toURLString();return this.persistenceKey&&(n+="<"+this.persistenceKey+">"),n}toURLString(){const n=this.secure?"https://":"http://",a=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${n}${this.host}/${a}`}}function kO(t){return t.host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams}function Ak(t,n,a){la(typeof n=="string","typeof type must == string"),la(typeof a=="object","typeof params must == object");let s;if(n===Nk)s=(t.secure?"wss://":"ws://")+t.internalHost+"/.ws?";else if(n===Sk)s=(t.secure?"https://":"http://")+t.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+n);kO(t)&&(a.ns=t.namespace);const i=[];return eo(a,(c,l)=>{i.push(c+"="+l)}),s+i.join("&")}/** 1865 * @license 1866 * Copyright 2017 Google LLC 1867 * 1868 * Licensed under the Apache License, Version 2.0 (the "License");
1869 * you may not use this file except in compliance with the License. 1870 * You may obtain a copy of the License at 1871 * 1872 * http://www.apache.org/licenses/LICENSE-2.0 1873 * 1874 * Unless required by applicable law or agreed to in writing, software 1875 * distributed under the License is distributed on an "AS IS" BASIS, 1876 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1877 * See the License for the specific language governing permissions and 1878 * limitations under the License. 1879 */class DO{constructor(){this.counters_={}}incrementCounter(n,a=1){pl(this.counters_,n)||(this.counters_[n]=0),this.counters_[n]+=a}get(){return bR(this.counters_)}}/** 1880 * @license 1881 * Copyright 2017 Google LLC 1882 * 1883 * Licensed under the Apache License, Version 2.0 (the "License"); 1884 * you may not use this file except in compliance with the License. 1885 * You may obtain a copy of the License at 1886 * 1887 * http://www.apache.org/licenses/LICENSE-2.0 1888 * 1889 * Unless required by applicable law or agreed to in writing, software 1890 * distributed under the License is distributed on an "AS IS" BASIS, 1891 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1892 * See the License for the specific language governing permissions and 1893 * limitations under the License. 1894 */const U0={},z0={};function fw(t){const n=t.toString();return U0[n]||(U0[n]=new DO),U0[n]}function EO(t,n){const a=t.toString();return z0[a]||(z0[a]=n()),z0[a]}/** 1895 * @license 1896 * Copyright 2017 Google LLC 1897 * 1898 * Licensed under the Apache License, Version 2.0 (the "License"); 1899 * you may not use this file except in compliance with the License. 1900 * You may obtain a copy of the License at 1901 * 1902 * http://www.apache.org/licenses/LICENSE-2.0 1903 * 1904 * Unless required by applicable law or agreed to in writing, software 1905 * distributed under the License is distributed on an "AS IS" BASIS, 1906 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1907 * See the License for the specific language governing permissions and 1908 * limitations under the License. 1909 */class PO{constructor(n){this.onMessage_=n,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(n,a){this.closeAfterResponse=n,this.onClose=a,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(n,a){for(this.pendingResponses[n]=a;this.pendingResponses[this.currentResponseNum];){const s=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<s.length;++i)s[i]&&_p(()=>{this.onMessage_(s[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/** 1910 * @license 1911 * Copyright 2017 Google LLC 1912 * 1913 * Licensed under the Apache License, Version 2.0 (the "License"); 1914 * you may not use this file except in compliance with the License. 1915 * You may obtain a copy of the License at 1916 * 1917 * http://www.apache.org/licenses/LICENSE-2.0 1918 * 1919 * Unless required by applicable law or agreed to in writing, software 1920 * distributed under the License is distributed on an "AS IS" BASIS, 1921 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1922 * See the License for the specific language governing permissions and 1923 * limitations under the License. 1924 */const SC="start",RO="close",TO="pLPCommand",MO="pRTLPCB",Ik="id",_k="pw",kk="ser",$O="cb",OO="seg",LO="ts",BO="d",FO="dframe",Dk=1870,Ek=30,UO=Dk-Ek,zO=25e3,qO=3e4;class np{constructor(n,a,s,i,c,l,m){this.connId=n,this.repoInfo=a,this.applicationId=s,this.appCheckToken=i,this.authToken=c,this.transportSessionId=l,this.lastSessionId=m,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Eg(n),this.stats_=fw(a),this.urlFn=d=>(this.appCheckToken&&(d[r1]=this.appCheckToken),Ak(a,Sk,d))}open(n,a){this.curSegmentNum=0,this.onDisconnect_=a,this.myPacketOrderer=new PO(n),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(qO)),vO(()=>{if(this.isClosed_)return;this.scriptTagHolder=new gw((...c)=>{const[l,m,d,u,f]=c;if(this.incrementIncomingBytes_(c),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,l===SC)this.id=m,this.password=d;else if(l===RO)m?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(m,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+l)},(...c)=>{const[l,m]=c;this.incrementIncomingBytes_(c),this.myPacketOrderer.handleResponse(l,m)}
vendor: 5,053 bytes, lines 1924-1928
1924,()=>{this.onClosed_()},this.urlFn);const s={};s[SC]="t",s[kk]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(s[$O]=this.scriptTagHolder.uniqueCallbackIdentifier),s[gk]=pw,this.transportSessionId&&(s[yk]=this.transportSessionId),this.lastSessionId&&(s[jk]=this.lastSessionId),this.applicationId&&(s[wk]=this.applicationId),this.appCheckToken&&(s[r1]=this.appCheckToken),typeof location<"u"&&location.hostname&&xk.test(location.hostname)&&(s[vk]=bk);const i=this.urlFn(s);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){np.forceAllow_=!0}static forceDisallow(){np.forceDisallow_=!0}static isAvailable(){return np.forceAllow_?!0:!np.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!xO()&&!jO()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(n){const a=Ri(n);this.bytesSent+=a.length,this.stats_.incrementCounter("bytes_sent",a.length);const s=h5(a),i=pk(s,UO);for(let c=0;c<i.length;c++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[c]),this.curSegmentNum++}addDisconnectPingFrame(n,a){this.myDisconnFrame=document.createElement("iframe");const s={};s[FO]="t",s[Ik]=n,s[_k]=a,this.myDisconnFrame.src=this.urlFn(s),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(n){const a=Ri(n).length;this.bytesReceived+=a,this.stats_.incrementCounter("bytes_received",a)}}class gw{constructor(n,a,s,i){this.onDisconnect=s,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=hk(),window[TO+this.uniqueCallbackIdentifier]=n,window[MO+this.uniqueCallbackIdentifier]=a,this.myIFrame=gw.createIFrame_();let c="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(c='<script>document.domain="'+document.domain+'";<\/script>');const l="<html><body>"+c+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(l),this.myIFrame.doc.close()}catch(m){Xi("frame writing exception"),m.stack&&Xi(m.stack),Xi(m)}}}static createIFrame_(){const n=document.createElement("iframe");if(n.style.display="none",document.body){document.body.appendChild(n);try{n.contentWindow.document||Xi("No IE domain setting required")}catch{const s=document.domain;n.src="javascript:void((function(){document.open();document.domain='"+s+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return n.contentDocument?n.doc=n.contentDocument:n.contentWindow?n.doc=n.contentWindow.document:n.document&&(n.doc=n.document),n}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const n=this.onDisconnect;n&&(this.onDisconnect=null,n())}startLongPoll(n,a){for(this.myID=n,this.myPW=a,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const n={};n[Ik]=this.myID,n[_k]=this.myPW,n[kk]=this.currentSerial;let a=this.urlFn(n),s="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+Ek+s.length<=Dk;){const l=this.pendingSegs.shift();s=s+"&"+OO+i+"="+l.seg+"&"+LO+i+"="+l.ts+"&"+BO+i+"="+l.d,i++}return a=a+s,this.addLongPollTag_(a,this.currentSerial),!0}else return!1}enqueueSegment(n,a,s){this.pendingSegs.push({seg:n,ts:a,d:s}),this.alive&&this.newRequest_()}addLongPollTag_(n,a){this.outstandingRequests.add(a);const s=()=>{this.outstandingRequests.delete(a),this.newRequest_()},i=setTimeout(s,Math.floor(zO)),c=()=>{clearTimeout(i),s()};this.addTag(n,c)}addTag(n,a){setTimeout(()=>{try{if(!this.sendNewPolls)return;const s=this.myIFrame.doc.createElement("script");s.type="text/javascript",s.async=!0,s.src=n,s.onload=s.onreadystatechange=function(){const i=s.readyState;(!i||i==="loaded"||i==="complete")&&(s.onload=s.onreadystatechange=null,s.parentNode&&s.parentNode.removeChild(s),a())},s.onerror=()=>{Xi("Long-poll script failed to load: "+n),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(s)}catch{}},Math.floor(1))}}/** 1925 * @license 1926 * Copyright 2017 Google LLC 1927 * 1928 * Licensed under the Apache License, Version 2.0 (the "License");
1929 * you may not use this file except in compliance with the License. 1930 * You may obtain a copy of the License at 1931 * 1932 * http://www.apache.org/licenses/LICENSE-2.0 1933 * 1934 * Unless required by applicable law or agreed to in writing, software 1935 * distributed under the License is distributed on an "AS IS" BASIS, 1936 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1937 * See the License for the specific language governing permissions and 1938 * limitations under the License. 1939 */const VO=16384,HO=45e3;let yb=null;typeof MozWebSocket<"u"?yb=MozWebSocket:typeof WebSocket<"u"&&(yb=WebSocket);class ol{constructor(n,a,s,i,c,l,m){this.connId=n,this.applicationId=s,this.appCheckToken=i,this.authToken=c,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Eg(this.connId),this.stats_=fw(a),this.connURL=ol.connectionURL_(a,l,m,i,s),this.nodeAdmin=a.nodeAdmin}static connectionURL_(n,a,s,i,c){const l={};return l[gk]=pw,typeof location<"u"&&location.hostname&&xk.test(location.hostname)&&(l[vk]=bk),a&&(l[yk]=a),s&&(l[jk]=s),i&&(l[r1]=i),c&&(l[wk]=c),Ak(n,Nk,l)}open(n,a){this.onDisconnect=a,this.onMessage=n,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Sh.set("previous_websocket_failure",!0);try{let s;DR(),this.mySock=new yb(this.connURL,[],s)}catch(s){this.log_("Error instantiating WebSocket.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=s=>{this.handleIncomingFrame(s)},this.mySock.onerror=s=>{this.log_("WebSocket error. Closing connection.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){ol.forceDisallow_=!0}static isAvailable(){let n=!1;if(typeof navigator<"u"&&navigator.userAgent){const a=/Android ([0-9]{0,}\.[0-9]{0,})/,s=navigator.userAgent.match(a);s&&s.length>1&&parseFloat(s[1])<4.4&&(n=!0)}return!n&&yb!==null&&!ol.forceDisallow_}static previouslyFailed(){return Sh.isInMemoryStorage||Sh.get("previous_websocket_failure")===!0}markConnectionHealthy(){Sh.remove("previous_websocket_failure")}appendFrame_(n){if(this.frames.push(n),this.frames.length===this.totalFrames){const a=this.frames.join("");this.frames=null;const s=ag(a);this.onMessage(s)}}handleNewFrameCount_(n){this.totalFrames=n,this.frames=[]}extractFrameCount_(n){if(la(this.frames===null,"We already have a frame buffer"),n.length<=6){const a=Number(n);if(!isNaN(a))return this.handleNewFrameCount_(a),null}return this.handleNewFrameCount_(1),n}handleIncomingFrame(n){if(this.mySock===null)return;const a=n.data;if(this.bytesReceived+=a.length,this.stats_.incrementCounter("bytes_received",a.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(a);else{const s=this.extractFrameCount_(a);s!==null&&this.appendFrame_(s)}}send(n){this.resetKeepAlive();const a=Ri(n);this.bytesSent+=a.length,this.stats_.incrementCounter("bytes_sent",a.length);const s=pk(a,VO);s.length>1&&this.sendString_(String(s.length));for(let i=0;i<s.length;i++)this.sendString_(s[i])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(HO))}sendString_(n){try{this.mySock.send(n)}catch(a){this.log_("Exception thrown from WebSocket.send():",a.message||a.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}ol.responsesRequiredToBeHealthy=2;ol.healthyTimeout=3e4;/** 1940 * @license 1941 * Copyright 2017 Google LLC 1942 * 1943 * Licensed under the Apache License, Version 2.0 (the "License");
1944 * you may not use this file except in compliance with the License. 1945 * You may obtain a copy of the License at 1946 * 1947 * http://www.apache.org/licenses/LICENSE-2.0 1948 * 1949 * Unless required by applicable law or agreed to in writing, software 1950 * distributed under the License is distributed on an "AS IS" BASIS, 1951 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1952 * See the License for the specific language governing permissions and 1953 * limitations under the License. 1954 */class ig{static get ALL_TRANSPORTS(){return[np,ol]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(n){this.initTransports_(n)}initTransports_(n){const a=ol&&ol.isAvailable();let s=a&&!ol.previouslyFailed();if(n.webSocketOnly&&(a||Co("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),s=!0),s)this.transports_=[ol];else{const i=this.transports_=[];for(const c of ig.ALL_TRANSPORTS)c&&c.isAvailable()&&i.push(c);ig.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}ig.globalTransportInitialized_=!1;/** 1955 * @license 1956 * Copyright 2017 Google LLC 1957 * 1958 * Licensed under the Apache License, Version 2.0 (the "License"); 1959 * you may not use this file except in compliance with the License. 1960 * You may obtain a copy of the License at 1961 * 1962 * http://www.apache.org/licenses/LICENSE-2.0 1963 * 1964 * Unless required by applicable law or agreed to in writing, software 1965 * distributed under the License is distributed on an "AS IS" BASIS, 1966 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1967 * See the License for the specific language governing permissions and 1968 * limitations under the License. 1969 */const WO=6e4,GO=5e3,YO=10*1024,QO=100*1024,q0="t",CC="d",JO="s",AC="r",KO="e",IC="o",_C="a",kC="n",DC="p",XO="h";class ZO{constructor(n,a,s,i,c,l,m,d,u,f){this.id=n,this.repoInfo_=a,this.applicationId_=s,this.appCheckToken_=i,this.authToken_=c,this.onMessage_=l,this.onReady_=m,this.onDisconnect_=d,this.onKill_=u,this.lastSessionId=f,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Eg("c:"+this.id+":"),this.transportManager_=new ig(a),this.log_("Connection created"),this.start_()}start_(){const n=this.transportManager_.initialTransport();this.conn_=new n(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=n.responsesRequiredToBeHealthy||0;const a=this.connReceiver_(this.conn_),s=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(a,s)},Math.floor(0));const i=n.healthyTimeout||0;i>0&&(this.healthyTimeout_=Hf(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>QO?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>YO?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(n){return a=>{n===this.conn_?this.onConnectionLost_(a):n===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(n){return a=>{this.state_!==2&&(n===this.rx_?this.onPrimaryMessageReceived_(a):n===this.secondaryConn_?this.onSecondaryMessageReceived_(a):this.log_("message on old connection"))}}sendRequest(n){const a={t:"d",d:n};this.sendData_(a)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(n){if(q0 in n){const a=n[q0];a===_C?this.upgradeIfSecondaryHealthy_():a===AC?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):a===IC&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}
vendor: 4,488 bytes, lines 1969-1973
1969onSecondaryMessageReceived_(n){const a=pf("t",n),s=pf("d",n);if(a==="c")this.onSecondaryControl_(s);else if(a==="d")this.pendingDataMessages.push(s);else throw new Error("Unknown protocol layer: "+a)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:DC,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:_C,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:kC,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(n){const a=pf("t",n),s=pf("d",n);a==="c"?this.onControl_(s):a==="d"&&this.onDataMessage_(s)}onDataMessage_(n){this.onPrimaryResponse_(),this.onMessage_(n)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(n){const a=pf(q0,n);if(CC in n){const s=n[CC];if(a===XO){const i={...s};this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(a===kC){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else a===JO?this.onConnectionShutdown_(s):a===AC?this.onReset_(s):a===KO?s1("Server Error: "+s):a===IC?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):s1("Unknown control packet command: "+a)}}onHandshake_(n){const a=n.ts,s=n.v,i=n.h;this.sessionId=n.s,this.repoInfo_.host=i,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,a),pw!==s&&Co("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const n=this.transportManager_.upgradeTransport();n&&this.startUpgrade_(n)}startUpgrade_(n){this.secondaryConn_=new n(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=n.responsesRequiredToBeHealthy||0;const a=this.connReceiver_(this.secondaryConn_),s=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(a,s),Hf(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(WO))}onReset_(n){this.log_("Reset packet received. New host: "+n),this.repoInfo_.host=n,this.state_===1?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(n,a){this.log_("Realtime connection established."),this.conn_=n,this.state_=1,this.onReady_&&(this.onReady_(a,this.sessionId),this.onReady_=null),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Hf(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(GO))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:DC,d:{}}}))}onSecondaryConnectionLost_(){const n=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===n||this.rx_===n)&&this.close()}onConnectionLost_(n){this.conn_=null,!n&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(Sh.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),this.close()}onConnectionShutdown_(n){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(n),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(n){if(this.state_!==1)throw"Connection is not connected";this.tx_.send(n)}close(){this.state_!==2&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}/** 1970 * @license 1971 * Copyright 2017 Google LLC 1972 * 1973 * Licensed under the Apache License, Version 2.0 (the "License");
1974 * you may not use this file except in compliance with the License. 1975 * You may obtain a copy of the License at 1976 * 1977 * http://www.apache.org/licenses/LICENSE-2.0 1978 * 1979 * Unless required by applicable law or agreed to in writing, software 1980 * distributed under the License is distributed on an "AS IS" BASIS, 1981 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1982 * See the License for the specific language governing permissions and 1983 * limitations under the License. 1984 */class Pk{put(n,a,s,i){}merge(n,a,s,i){}refreshAuthToken(n){}refreshAppCheckToken(n){}onDisconnectPut(n,a,s){}onDisconnectMerge(n,a,s){}onDisconnectCancel(n,a){}reportStats(n){}}/** 1985 * @license 1986 * Copyright 2017 Google LLC 1987 * 1988 * Licensed under the Apache License, Version 2.0 (the "License"); 1989 * you may not use this file except in compliance with the License. 1990 * You may obtain a copy of the License at 1991 * 1992 * http://www.apache.org/licenses/LICENSE-2.0 1993 * 1994 * Unless required by applicable law or agreed to in writing, software 1995 * distributed under the License is distributed on an "AS IS" BASIS, 1996 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1997 * See the License for the specific language governing permissions and 1998 * limitations under the License. 1999 */class Rk{constructor(n){this.allowedEvents_=n,this.listeners_={},la(Array.isArray(n)&&n.length>0,"Requires a non-empty array")}trigger(n,...a){if(Array.isArray(this.listeners_[n])){const s=[...this.listeners_[n]];for(let i=0;i<s.length;i++)s[i].callback.apply(s[i].context,a)}}on(n,a,s){this.validateEventType_(n),this.listeners_[n]=this.listeners_[n]||[],this.listeners_[n].push({callback:a,context:s});const i=this.getInitialEvent(n);i&&a.apply(s,i)}off(n,a,s){this.validateEventType_(n);const i=this.listeners_[n]||[];for(let c=0;c<i.length;c++)if(i[c].callback===a&&(!s||s===i[c].context)){i.splice(c,1);return}}validateEventType_(n){la(this.allowedEvents_.find(a=>a===n),"Unknown event: "+n)}}/** 2000 * @license 2001 * Copyright 2017 Google LLC 2002 * 2003 * Licensed under the Apache License, Version 2.0 (the "License"); 2004 * you may not use this file except in compliance with the License. 2005 * You may obtain a copy of the License at 2006 * 2007 * http://www.apache.org/licenses/LICENSE-2.0 2008 * 2009 * Unless required by applicable law or agreed to in writing, software 2010 * distributed under the License is distributed on an "AS IS" BASIS, 2011 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2012 * See the License for the specific language governing permissions and 2013 * limitations under the License. 2014 */class vb extends Rk{static getInstance(){return new vb}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!Z1()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(n){return la(n==="online","Unknown event type: "+n),[this.online_]}currentlyOnline(){return this.online_}}/** 2015 * @license 2016 * Copyright 2017 Google LLC 2017 * 2018 * Licensed under the Apache License, Version 2.0 (the "License"); 2019 * you may not use this file except in compliance with the License. 2020 * You may obtain a copy of the License at 2021 * 2022 * http://www.apache.org/licenses/LICENSE-2.0 2023 * 2024 * Unless required by applicable law or agreed to in writing, software 2025 * distributed under the License is distributed on an "AS IS" BASIS, 2026 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2027 * See the License for the specific language governing permissions and 2028 * limitations under the License. 2029 */const EC=32,PC=768;class mr{constructor(n,a){if(a===void 0){this.pieces_=n.split("/");let s=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[s]=this.pieces_[i],s++);this.pieces_.length=s,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=a}toString(){let n="";for(let a=this.pieceNum_;a<this.pieces_.length;a++)this.pieces_[a]!==""&&(n+="/"+this.pieces_[a]);return n||"/"}}function Qs(){return new mr("")}function xs(t){return t.pieceNum_>=t.pieces_.length?null:t.pieces_[t.pieceNum_]}function Ou(t){return t.pieces_.length-t.pieceNum_}function Pr(t){let n=t.pieceNum_;return n<t.pieces_.length&&n++,new mr(t.pieces_,n)}function yw(t){return t.pieceNum_<t.pieces_.length?t.pieces_[t.pieces_.length-1]:null}function e3(t){let n="";for(let a=t.pieceNum_;a<t.pieces_.length;a++)t.pieces_[a]!==""&&(n+="/"+encodeURIComponent(String(t.pieces_[a])));return n||"/"}function og(t,n=0){return t.pieces_.slice(t.pieceNum_+n)}function Tk(t){if(t.pieceNum_>=t.pieces_.length)return null;const n=[];for(let a=t.pieceNum_;a<t.pieces_.length-1;a++)n.push(t.pieces_[a]);return new mr(n,0)}function si(t,n){const a=[];for(let s=t.pieceNum_;s<t.pieces_.length;s++)a.push(t.pieces_[s]);if(n instanceof mr)for(let s=n.pieceNum_;s<n.pieces_.length;s++)a.push(n.pieces_[s]);else{const s=n.split("/");for(let i=0;i<s.length;i++)s[i].length>0&&a.push(s[i])}return new mr(a,0)}function js(t){return t.pieceNum_>=t.pieces_.length}function So(t,n){const a=xs(t),s=xs(n);if(a===null)return n;if(a===s)return So(Pr(t),Pr(n));
vendor: 28,267 bytes, lines 2029-2167
2029throw new Error("INTERNAL ERROR: innerPath ("+n+") is not within outerPath ("+t+")")}function t3(t,n){const a=og(t,0),s=og(n,0);for(let i=0;i<a.length&&i<s.length;i++){const c=Kh(a[i],s[i]);if(c!==0)return c}return a.length===s.length?0:a.length<s.length?-1:1}function vw(t,n){if(Ou(t)!==Ou(n))return!1;for(let a=t.pieceNum_,s=n.pieceNum_;a<=t.pieces_.length;a++,s++)if(t.pieces_[a]!==n.pieces_[s])return!1;return!0}function $c(t,n){let a=t.pieceNum_,s=n.pieceNum_;if(Ou(t)>Ou(n))return!1;for(;a<t.pieces_.length;){if(t.pieces_[a]!==n.pieces_[s])return!1;++a,++s}return!0}class n3{constructor(n,a){this.errorPrefix_=a,this.parts_=og(n,0),this.byteLength_=Math.max(1,this.parts_.length);for(let s=0;s<this.parts_.length;s++)this.byteLength_+=Vb(this.parts_[s]);Mk(this)}}function a3(t,n){t.parts_.length>0&&(t.byteLength_+=1),t.parts_.push(n),t.byteLength_+=Vb(n),Mk(t)}function s3(t){const n=t.parts_.pop();t.byteLength_-=Vb(n),t.parts_.length>0&&(t.byteLength_-=1)}function Mk(t){if(t.byteLength_>PC)throw new Error(t.errorPrefix_+"has a key path longer than "+PC+" bytes ("+t.byteLength_+").");if(t.parts_.length>EC)throw new Error(t.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+EC+") or object contains a cycle "+xh(t))}function xh(t){return t.parts_.length===0?"":"in property '"+t.parts_.join(".")+"'"}/** 2030 * @license 2031 * Copyright 2017 Google LLC 2032 * 2033 * Licensed under the Apache License, Version 2.0 (the "License"); 2034 * you may not use this file except in compliance with the License. 2035 * You may obtain a copy of the License at 2036 * 2037 * http://www.apache.org/licenses/LICENSE-2.0 2038 * 2039 * Unless required by applicable law or agreed to in writing, software 2040 * distributed under the License is distributed on an "AS IS" BASIS, 2041 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2042 * See the License for the specific language governing permissions and 2043 * limitations under the License. 2044 */class bw extends Rk{static getInstance(){return new bw}constructor(){super(["visible"]);let n,a;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(a="visibilitychange",n="hidden"):typeof document.mozHidden<"u"?(a="mozvisibilitychange",n="mozHidden"):typeof document.msHidden<"u"?(a="msvisibilitychange",n="msHidden"):typeof document.webkitHidden<"u"&&(a="webkitvisibilitychange",n="webkitHidden")),this.visible_=!0,a&&document.addEventListener(a,()=>{const s=!document[n];s!==this.visible_&&(this.visible_=s,this.trigger("visible",s))},!1)}getInitialEvent(n){return la(n==="visible","Unknown event type: "+n),[this.visible_]}}/** 2045 * @license 2046 * Copyright 2017 Google LLC 2047 * 2048 * Licensed under the Apache License, Version 2.0 (the "License"); 2049 * you may not use this file except in compliance with the License. 2050 * You may obtain a copy of the License at 2051 * 2052 * http://www.apache.org/licenses/LICENSE-2.0 2053 * 2054 * Unless required by applicable law or agreed to in writing, software 2055 * distributed under the License is distributed on an "AS IS" BASIS, 2056 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2057 * See the License for the specific language governing permissions and 2058 * limitations under the License. 2059 */const ff=1e3,r3=300*1e3,RC=30*1e3,i3=1.3,o3=3e4,c3="server_kill",TC=3;class Ad extends Pk{constructor(n,a,s,i,c,l,m,d){if(super(),this.repoInfo_=n,this.applicationId_=a,this.onDataUpdate_=s,this.onConnectStatus_=i,this.onServerInfoUpdate_=c,this.authTokenProvider_=l,this.appCheckTokenProvider_=m,this.authOverride_=d,this.id=Ad.nextPersistentConnectionId_++,this.log_=Eg("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=ff,this.maxReconnectDelay_=r3,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,d)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");bw.getInstance().on("visible",this.onVisible_,this),n.host.indexOf("fblocal")===-1&&vb.getInstance().on("online",this.onOnline_,this)}sendRequest(n,a,s){const i=++this.requestNumber_,c={r:i,a:n,b:a};this.log_(Ri(c)),la(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(c),s&&(this.requestCBHash_[i]=s)}get(n){this.initConnection_();const a=new Jh,i={action:"g",request:{p:n._path.toString(),q:n._queryObject},onComplete:l=>{const m=l.d;l.s==="ok"?a.resolve(m):a.reject(m)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;const c=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(c),a.promise}listen(n,a,s,i){this.initConnection_();const c=n._queryIdentifier,l=n._path.toString();this.log_("Listen called for "+l+" "+c),this.listens.has(l)||this.listens.set(l,new Map),la(n._queryParams.isDefault()||!n._queryParams.loadsAllData(),"listen() called for non-default but complete query"),la(!this.listens.get(l).has(c),"listen() called twice for same path/queryId.");const m={onComplete:i,hashFn:a,query:n,tag:s};this.listens.get(l).set(c,m),this.connected_&&this.sendListen_(m)}sendGet_(n){const a=this.outstandingGets_[n];this.sendRequest("g",a.request,s=>{delete this.outstandingGets_[n],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),a.onComplete&&a.onComplete(s)})}sendListen_(n){const a=n.query,s=a._path.toString(),i=a._queryIdentifier;this.log_("Listen on "+s+" for "+i);const c={p:s},l="q";n.tag&&(c.q=a._queryObject,c.t=n.tag),c.h=n.hashFn(),this.sendRequest(l,c,m=>{const d=m.d,u=m.s;Ad.warnOnListenWarnings_(d,a),(this.listens.get(s)&&this.listens.get(s).get(i))===n&&(this.log_("listen response",m),u!=="ok"&&this.removeListen_(s,i),n.onComplete&&n.onComplete(u,d))})}static warnOnListenWarnings_(n,a){if(n&&typeof n=="object"&&pl(n,"w")){const s=Lh(n,"w");if(Array.isArray(s)&&~s.indexOf("no_index")){const i='".indexOn": "'+a._queryParams.getIndex().toString()+'"',c=a._path.toString();Co(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${c} to your security rules for better performance.`)}}}refreshAuthToken(n){this.authToken_=n,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(n)}reduceReconnectDelayIfAdminCredential_(n){(n&&n.length===40||$R(n))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=RC)}refreshAppCheckToken(n){this.appCheckToken_=n,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const n=this.authToken_,a=MR(n)?"auth":"gauth",s={cred:n};this.authOverride_===null?s.noauth=!0:typeof this.authOverride_=="object"&&(s.authvar=this.authOverride_),this.sendRequest(a,s,i=>{const c=i.s,l=i.d||"error";this.authToken_===n&&(c==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(c,l))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},n=>{const a=n.s,s=n.d||"error";a==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(a,s)})}unlisten(n,a){const s=n._path.toString(),i=n._queryIdentifier;this.log_("Unlisten called for "+s+" "+i),la(n._queryParams.isDefault()||!n._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(s,i)&&this.connected_&&this.sendUnlisten_(s,i,n._queryObject,a)}sendUnlisten_(n,a,s,i){this.log_("Unlisten on "+n+" for "+a);const c={p:n},l="n";i&&(c.q=s,c.t=i),this.sendRequest(l,c)}onDisconnectPut(n,a,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",n,a,s):this.onDisconnectRequestQueue_.push({pathString:n,action:"o",data:a,onComplete:s})}onDisconnectMerge(n,a,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",n,a,s):this.onDisconnectRequestQueue_.push({pathString:n,action:"om",data:a,onComplete:s})}onDisconnectCancel(n,a){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",n,null,a):this.onDisconnectRequestQueue_.push({pathString:n,action:"oc",data:null,onComplete:a})}sendOnDisconnect_(n,a,s,i){const c={p:a,d:s};this.log_("onDisconnect "+n,c),this.sendRequest(n,c,l=>{i&&setTimeout(()=>{i(l.s,l.d)},Math.floor(0))})}put(n,a,s,i){this.putInternal("p",n,a,s,i)}merge(n,a,s,i){this.putInternal("m",n,a,s,i)}putInternal(n,a,s,i,c){this.initConnection_();const l={p:a,d:s};c!==void 0&&(l.h=c),this.outstandingPuts_.push({action:n,request:l,onComplete:i}),this.outstandingPutCount_++;const m=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(m):this.log_("Buffering put: "+a)}sendPut_(n){const a=this.outstandingPuts_[n].action,s=this.outstandingPuts_[n].request,i=this.outstandingPuts_[n].onComplete;this.outstandingPuts_[n].queued=this.connected_,this.sendRequest(a,s,c=>{this.log_(a+" response",c),delete this.outstandingPuts_[n],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(c.s,c.d)})}reportStats(n){if(this.connected_){const a={c:n};this.log_("reportStats",a),this.sendRequest("s",a,s=>{if(s.s!=="ok"){const c=s.d;this.log_("reportStats","Error sending stats: "+c)}})}}onDataMessage_(n){if("r"in n){this.log_("from server: "+Ri(n));const a=n.r,s=this.requestCBHash_[a];s&&(delete this.requestCBHash_[a],s(n.b))}else{if("error"in n)throw"A server-side error has occurred: "+n.error;"a"in n&&this.onDataPush_(n.a,n.b)}}onDataPush_(n,a){this.log_("handleServerMessage",n,a),n==="d"?this.onDataUpdate_(a.p,a.d,!1,a.t):n==="m"?this.onDataUpdate_(a.p,a.d,!0,a.t):n==="c"?this.onListenRevoked_(a.p,a.q):n==="ac"?this.onAuthRevoked_(a.s,a.d):n==="apc"?this.onAppCheckRevoked_(a.s,a.d):n==="sd"?this.onSecurityDebugPacket_(a):s1("Unrecognized action received from server: "+Ri(n)+` 2060Are you using the latest client?`)}onReady_(n,a){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(n),this.lastSessionId=a,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(n){la(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(n))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(n){n&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=ff,this.realtime_||this.scheduleConnect_(0)),this.visible_=n}onOnline_(n){n?(this.log_("Browser went online."),this.reconnectDelay_=ff,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>o3&&(this.reconnectDelay_=ff),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const n=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_);let a=Math.max(0,this.reconnectDelay_-n);a=Math.random()*a,this.log_("Trying to reconnect in "+a+"ms"),this.scheduleConnect_(a),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*i3)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;const n=this.onDataMessage_.bind(this),a=this.onReady_.bind(this),s=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+Ad.nextConnectionId_++,c=this.lastSessionId;let l=!1,m=null;const d=function(){m?m.close():(l=!0,s())},u=function(g){la(m,"sendRequest call when we're not connected not allowed."),m.sendRequest(g)};this.realtime_={close:d,sendRequest:u};const f=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[g,p]=await Promise.all([this.authTokenProvider_.getToken(f),this.appCheckTokenProvider_.getToken(f)]);l?Xi("getToken() completed but was canceled"):(Xi("getToken() completed. Creating connection."),this.authToken_=g&&g.accessToken,this.appCheckToken_=p&&p.token,m=new ZO(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,n,a,s,y=>{Co(y+" ("+this.repoInfo_.toString()+")"),this.interrupt(c3)},c))}catch(g){this.log_("Failed to get token: "+g),l||(this.repoInfo_.nodeAdmin&&Co(g),d())}}}interrupt(n){Xi("Interrupting connection for reason: "+n),this.interruptReasons_[n]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(n){Xi("Resuming connection for reason: "+n),delete this.interruptReasons_[n],Yj(this.interruptReasons_)&&(this.reconnectDelay_=ff,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(n){const a=n-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:a})}cancelSentTransactions_(){for(let n=0;n<this.outstandingPuts_.length;n++){const a=this.outstandingPuts_[n];a&&"h"in a.request&&a.queued&&(a.onComplete&&a.onComplete("disconnect"),delete this.outstandingPuts_[n],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(n,a){let s;a?s=a.map(c=>mw(c)).join("$"):s="default";const i=this.removeListen_(n,s);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(n,a){const s=new mr(n).toString();let i;if(this.listens.has(s)){const c=this.listens.get(s);i=c.get(a),c.delete(a),c.size===0&&this.listens.delete(s)}else i=void 0;return i}onAuthRevoked_(n,a){Xi("Auth token revoked: "+n+"/"+a),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(n==="invalid_token"||n==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=TC&&(this.reconnectDelay_=RC,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(n,a){Xi("App check token revoked: "+n+"/"+a),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(n==="invalid_token"||n==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=TC&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(n){this.securityDebugCallback_?this.securityDebugCallback_(n):"msg"in n&&console.log("FIREBASE: "+n.msg.replace(` 2061`,` 2062FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const n of this.listens.values())for(const a of n.values())this.sendListen_(a);for(let n=0;n<this.outstandingPuts_.length;n++)this.outstandingPuts_[n]&&this.sendPut_(n);for(;this.onDisconnectRequestQueue_.length;){const n=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(n.action,n.pathString,n.data,n.onComplete)}for(let n=0;n<this.outstandingGets_.length;n++)this.outstandingGets_[n]&&this.sendGet_(n)}sendConnectStats_(){const n={};let a="js";n["sdk."+a+"."+dk.replace(/\./g,"-")]=1,Z1()?n["framework.cordova"]=1:y5()&&(n["framework.reactnative"]=1),this.reportStats(n)}shouldReconnect_(){const n=vb.getInstance().currentlyOnline();return Yj(this.interruptReasons_)&&n}}Ad.nextPersistentConnectionId_=0;Ad.nextConnectionId_=0;/** 2063 * @license 2064 * Copyright 2017 Google LLC 2065 * 2066 * Licensed under the Apache License, Version 2.0 (the "License"); 2067 * you may not use this file except in compliance with the License. 2068 * You may obtain a copy of the License at 2069 * 2070 * http://www.apache.org/licenses/LICENSE-2.0 2071 * 2072 * Unless required by applicable law or agreed to in writing, software 2073 * distributed under the License is distributed on an "AS IS" BASIS, 2074 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2075 * See the License for the specific language governing permissions and 2076 * limitations under the License. 2077 */class ws{constructor(n,a){this.name=n,this.node=a}static Wrap(n,a){return new ws(n,a)}}/** 2078 * @license 2079 * Copyright 2017 Google LLC 2080 * 2081 * Licensed under the Apache License, Version 2.0 (the "License"); 2082 * you may not use this file except in compliance with the License. 2083 * You may obtain a copy of the License at 2084 * 2085 * http://www.apache.org/licenses/LICENSE-2.0 2086 * 2087 * Unless required by applicable law or agreed to in writing, software 2088 * distributed under the License is distributed on an "AS IS" BASIS, 2089 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2090 * See the License for the specific language governing permissions and 2091 * limitations under the License. 2092 */class Yb{getCompare(){return this.compare.bind(this)}indexedValueChanged(n,a){const s=new ws(Vh,n),i=new ws(Vh,a);return this.compare(s,i)!==0}minPost(){return ws.MIN}}/** 2093 * @license 2094 * Copyright 2017 Google LLC 2095 * 2096 * Licensed under the Apache License, Version 2.0 (the "License"); 2097 * you may not use this file except in compliance with the License. 2098 * You may obtain a copy of the License at 2099 * 2100 * http://www.apache.org/licenses/LICENSE-2.0 2101 * 2102 * Unless required by applicable law or agreed to in writing, software 2103 * distributed under the License is distributed on an "AS IS" BASIS, 2104 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2105 * See the License for the specific language governing permissions and 2106 * limitations under the License. 2107 */let My;class $k extends Yb{static get __EMPTY_NODE(){return My}static set __EMPTY_NODE(n){My=n}compare(n,a){return Kh(n.name,a.name)}isDefinedOn(n){throw Cp("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(n,a){return!1}minPost(){return ws.MIN}maxPost(){return new ws($u,My)}makePost(n,a){return la(typeof n=="string","KeyIndex indexValue must always be a string."),new ws(n,My)}toString(){return".key"}}const kh=new $k;/** 2108 * @license 2109 * Copyright 2017 Google LLC 2110 * 2111 * Licensed under the Apache License, Version 2.0 (the "License"); 2112 * you may not use this file except in compliance with the License. 2113 * You may obtain a copy of the License at 2114 * 2115 * http://www.apache.org/licenses/LICENSE-2.0 2116 * 2117 * Unless required by applicable law or agreed to in writing, software 2118 * distributed under the License is distributed on an "AS IS" BASIS, 2119 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2120 * See the License for the specific language governing permissions and 2121 * limitations under the License. 2122 */class $y{constructor(n,a,s,i,c=null){this.isReverse_=i,this.resultGenerator_=c,this.nodeStack_=[];let l=1;for(;!n.isEmpty();)if(n=n,l=a?s(n.key,a):1,i&&(l*=-1),l<0)this.isReverse_?n=n.left:n=n.right;else if(l===0){this.nodeStack_.push(n);break}else this.nodeStack_.push(n),this.isReverse_?n=n.right:n=n.left}getNext(){if(this.nodeStack_.length===0)return null;let n=this.nodeStack_.pop(),a;if(this.resultGenerator_?a=this.resultGenerator_(n.key,n.value):a={key:n.key,value:n.value},this.isReverse_)for(n=n.left;!n.isEmpty();)this.nodeStack_.push(n),n=n.right;else for(n=n.right;!n.isEmpty();)this.nodeStack_.push(n),n=n.left;return a}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;const n=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(n.key,n.value):{key:n.key,value:n.value}}}class Vi{constructor(n,a,s,i,c){this.key=n,this.value=a,this.color=s??Vi.RED,this.left=i??Wo.EMPTY_NODE,this.right=c??Wo.EMPTY_NODE}copy(n,a,s,i,c){return new Vi(n??this.key,a??this.value,s??this.color,i??this.left,c??this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(n){return this.left.inorderTraversal(n)||!!n(this.key,this.value)||this.right.inorderTraversal(n)}reverseTraversal(n){return this.right.reverseTraversal(n)||n(this.key,this.value)||this.left.reverseTraversal(n)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(n,a,s){let i=this;const c=s(n,i.key);return c<0?i=i.copy(null,null,null,i.left.insert(n,a,s),null):c===0?i=i.copy(null,a,null,null,null):i=i.copy(null,null,null,null,i.right.insert(n,a,s)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Wo.EMPTY_NODE;let n=this;return!n.left.isRed_()&&!n.left.left.isRed_()&&(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.removeMin_(),null),n.fixUp_()}remove(n,a){let s,i;if(s=this,a(n,s.key)<0)!s.left.isEmpty()&&!s.left.isRed_()&&!s.left.left.isRed_()&&(s=s.moveRedLeft_()),s=s.copy(null,null,null,s.left.remove(n,a),null);else{if(s.left.isRed_()&&(s=s.rotateRight_()),!s.right.isEmpty()&&!s.right.isRed_()&&!s.right.left.isRed_()&&(s=s.moveRedRight_()),a(n,s.key)===0){if(s.right.isEmpty())return Wo.EMPTY_NODE;i=s.right.min_(),s=s.copy(i.key,i.value,null,null,s.right.removeMin_())}s=s.copy(null,null,null,null,s.right.remove(n,a))}return s.fixUp_()}isRed_(){return this.color}fixUp_(){let n=this;return n.right.isRed_()&&!n.left.isRed_()&&(n=n.rotateLeft_()),n.left.isRed_()&&n.left.left.isRed_()&&(n=n.rotateRight_()),n.left.isRed_()&&n.right.isRed_()&&(n=n.colorFlip_()),n}moveRedLeft_(){let n=this.colorFlip_();return n.right.left.isRed_()&&(n=n.copy(null,null,null,null,n.right.rotateRight_()),n=n.rotateLeft_(),n=n.colorFlip_()),n}moveRedRight_(){let n=this.colorFlip_();return n.left.left.isRed_()&&(n=n.rotateRight_(),n=n.colorFlip_()),n}rotateLeft_(){const n=this.copy(null,null,Vi.RED,null,this.right.left);return this.right.copy(null,null,this.color,n,null)}rotateRight_(){const n=this.copy(null,null,Vi.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,n)}colorFlip_(){const n=this.left.copy(null,null,!this.left.color,null,null),a=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,n,a)}checkMaxDepth_(){const n=this.check_();return Math.pow(2,n)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const n=this.left.check_();if(n!==this.right.check_())throw new Error("Black depths differ");return n+(this.isRed_()?0:1)}}Vi.RED=!0;Vi.BLACK=!1;class l3{copy(n,a,s,i,c){return this}insert(n,a,s){return new Vi(n,a,null)}remove(n,a){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(n){return!1}reverseTraversal(n){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}}class Wo{constructor(n,a=Wo.EMPTY_NODE){this.comparator_=n,this.root_=a}insert(n,a){return new Wo(this.comparator_,this.root_.insert(n,a,this.comparator_).copy(null,null,Vi.BLACK,null,null))}remove(n){return new Wo(this.comparator_,this.root_.remove(n,this.comparator_).copy(null,null,Vi.BLACK,null,null))}get(n){let a,s=this.root_;for(;!s.isEmpty();){if(a=this.comparator_(n,s.key),a===0)return s.value;a<0?s=s.left:a>0&&(s=s.right)}return null}getPredecessorKey(n){let a,s=this.root_,i=null;for(;!s.isEmpty();)if(a=this.comparator_(n,s.key),a===0){if(s.left.isEmpty())return i?i.key:null;for(s=s.left;!s.right.isEmpty();)s=s.right;return s.key}else a<0?s=s.left:a>0&&(i=s,s=s.right);throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(n){return this.root_.inorderTraversal(n)}reverseTraversal(n){return this.root_.reverseTraversal(n)}getIterator(n){return new $y(this.root_,null,this.comparator_,!1,n)}getIteratorFrom(n,a){return new $y(this.root_,n,this.comparator_,!1,a)}getReverseIteratorFrom(n,a){return new $y(this.root_,n,this.comparator_,!0,a)}getReverseIterator(n){return new $y(this.root_,null,this.comparator_,!0,n)}}Wo.EMPTY_NODE=new l3;/** 2123 * @license 2124 * Copyright 2017 Google LLC 2125 * 2126 * Licensed under the Apache License, Version 2.0 (the "License"); 2127 * you may not use this file except in compliance with the License. 2128 * You may obtain a copy of the License at 2129 * 2130 * http://www.apache.org/licenses/LICENSE-2.0 2131 * 2132 * Unless required by applicable law or agreed to in writing, software 2133 * distributed under the License is distributed on an "AS IS" BASIS, 2134 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2135 * See the License for the specific language governing permissions and 2136 * limitations under the License. 2137 */function d3(t,n){return Kh(t.name,n.name)}function xw(t,n){return Kh(t,n)}/** 2138 * @license 2139 * Copyright 2017 Google LLC 2140 * 2141 * Licensed under the Apache License, Version 2.0 (the "License"); 2142 * you may not use this file except in compliance with the License. 2143 * You may obtain a copy of the License at 2144 * 2145 * http://www.apache.org/licenses/LICENSE-2.0 2146 * 2147 * Unless required by applicable law or agreed to in writing, software 2148 * distributed under the License is distributed on an "AS IS" BASIS, 2149 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2150 * See the License for the specific language governing permissions and 2151 * limitations under the License. 2152 */let i1;function u3(t){i1=t}const Ok=function(t){return typeof t=="number"?"number:"+fk(t):"string:"+t},Lk=function(t){if(t.isLeafNode()){const n=t.val();la(typeof n=="string"||typeof n=="number"||typeof n=="object"&&pl(n,".sv"),"Priority must be a string or number.")}else la(t===i1||t.isEmpty(),"priority of unexpected type.");la(t===i1||t.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};/** 2153 * @license 2154 * Copyright 2017 Google LLC 2155 * 2156 * Licensed under the Apache License, Version 2.0 (the "License"); 2157 * you may not use this file except in compliance with the License. 2158 * You may obtain a copy of the License at 2159 * 2160 * http://www.apache.org/licenses/LICENSE-2.0 2161 * 2162 * Unless required by applicable law or agreed to in writing, software 2163 * distributed under the License is distributed on an "AS IS" BASIS, 2164 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2165 * See the License for the specific language governing permissions and 2166 * limitations under the License. 2167 */let MC;class qi{static set __childrenNodeConstructor(n){MC=n}static get __childrenNodeConstructor(){return MC}constructor(n,a=qi.__childrenNodeConstructor.EMPTY_NODE){this.value_=n,this.priorityNode_=a,this.lazyHash_=null,la(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),Lk(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(n){return new qi(this.value_,n)}getImmediateChild(n){return n===".priority"?this.priorityNode_:qi.__childrenNodeConstructor.EMPTY_NODE}getChild(n){return js(n)?this:xs(n)===".priority"?this.priorityNode_:qi.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(n,a){return null}updateImmediateChild(n,a){return n===".priority"?this.updatePriority(a):a.isEmpty()&&n!==".priority"?this:qi.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(n,a).updatePriority(this.priorityNode_)}updateChild(n,a){const s=xs(n);return s===null?a:a.isEmpty()&&s!==".priority"?this:(la(s!==".priority"||Ou(n)===1,".priority must be the last token in a path"),this.updateImmediateChild(s,qi.__childrenNodeConstructor.EMPTY_NODE.updateChild(Pr(n),a)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(n,a){return!1}
2167val(n){return n&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let n="";this.priorityNode_.isEmpty()||(n+="priority:"+Ok(this.priorityNode_.val())+":");const a=typeof this.value_;n+=a+":",a==="number"?n+=fk(this.value_):n+=this.value_,this.lazyHash_=mk(n)}return this.lazyHash_}getValue(){return this.value_}compareTo(n){return n===qi.__childrenNodeConstructor.EMPTY_NODE?1:n instanceof qi.__childrenNodeConstructor?-1:(la(n.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(n))}compareToLeafNode_(n){const a=typeof n.value_,s=typeof this.value_,i=qi.VALUE_TYPE_ORDER.indexOf(a),c=qi.VALUE_TYPE_ORDER.indexOf(s);return la(i>=0,"Unknown leaf type: "+a),la(c>=0,"Unknown leaf type: "+s),i===c?s==="object"?0:this.value_<n.value_?-1:this.value_===n.value_?0:1:c-i}withIndex(){return this}isIndexed(){return!0}equals(n){if(n===this)return!0;if(n.isLeafNode()){const a=n;return this.value_===a.value_&&this.priorityNode_.equals(a.priorityNode_)}else return!1}}qi.VALUE_TYPE_ORDER=["object","boolean","number","string"];/** 2168 * @license 2169 * Copyright 2017 Google LLC 2170 * 2171 * Licensed under the Apache License, Version 2.0 (the "License"); 2172 * you may not use this file except in compliance with the License. 2173 * You may obtain a copy of the License at 2174 * 2175 * http://www.apache.org/licenses/LICENSE-2.0 2176 * 2177 * Unless required by applicable law or agreed to in writing, software 2178 * distributed under the License is distributed on an "AS IS" BASIS, 2179 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2180 * See the License for the specific language governing permissions and 2181 * limitations under the License. 2182 */let Bk,Fk;function h3(t){Bk=t}function m3(t){Fk=t}class p3 extends Yb{compare(n,a){const s=n.node.getPriority(),i=a.node.getPriority(),c=s.compareTo(i);return c===0?Kh(n.name,a.name):c}isDefinedOn(n){return!n.getPriority().isEmpty()}indexedValueChanged(n,a){return!n.getPriority().equals(a.getPriority())}minPost(){return ws.MIN}maxPost(){return new ws($u,new qi("[PRIORITY-POST]",Fk))}makePost(n,a){const s=Bk(n);return new ws(a,new qi("[PRIORITY-POST]",s))}toString(){return".priority"}}const Hr=new p3;/** 2183 * @license 2184 * Copyright 2017 Google LLC 2185 * 2186 * Licensed under the Apache License, Version 2.0 (the "License"); 2187 * you may not use this file except in compliance with the License. 2188 * You may obtain a copy of the License at 2189 * 2190 * http://www.apache.org/licenses/LICENSE-2.0 2191 * 2192 * Unless required by applicable law or agreed to in writing, software 2193 * distributed under the License is distributed on an "AS IS" BASIS, 2194 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2195 * See the License for the specific language governing permissions and 2196 * limitations under the License. 2197 */const f3=Math.log(2);class g3{constructor(n){const a=c=>parseInt(Math.log(c)/f3,10),s=c=>parseInt(Array(c+1).join("1"),2);this.count=a(n+1),this.current_=this.count-1;const i=s(this.count);this.bits_=n+1&i}nextBitIsOne(){const n=!(this.bits_&1<<this.current_);return this.current_--,n}}const bb=function(t,n,a,s){t.sort(n);const i=function(d,u){const f=u-d;let g,p;if(f===0)return null;if(f===1)return g=t[d],p=a?a(g):g,new Vi(p,g.node,Vi.BLACK,null,null);{const y=parseInt(f/2,10)+d,b=i(d,y),N=i(y+1,u);return g=t[y],p=a?a(g):g,new Vi(p,g.node,Vi.BLACK,b,N)}},c=function(d){let u=null,f=null,g=t.length;const p=function(b,N){const w=g-b,C=g;g-=b;const R=i(w+1,C),I=t[w],_=a?a(I):I;y(new Vi(_,I.node,N,null,R))},y=function(b){u?(u.left=b,u=b):(f=b,u=b)};for(let b=0;b<d.count;++b){const N=d.nextBitIsOne(),w=Math.pow(2,d.count-(b+1));N?p(w,Vi.BLACK):(p(w,Vi.BLACK),p(w,Vi.RED))}return f},l=new g3(t.length),m=c(l);return new Wo(s||n,m)};/** 2198 * @license 2199 * Copyright 2017 Google LLC 2200 * 2201 * Licensed under the Apache License, Version 2.0 (the "License"); 2202 * you may not use this file except in compliance with the License. 2203 * You may obtain a copy of the License at 2204 * 2205 * http://www.apache.org/licenses/LICENSE-2.0 2206 * 2207 * Unless required by applicable law or agreed to in writing, softw
2207are 2208 * distributed under the License is distributed on an "AS IS" BASIS, 2209 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2210 * See the License for the specific language governing permissions and 2211 * limitations under the License. 2212 */let V0;const Rm={};class wd{static get Default(){return la(Rm&&Hr,"ChildrenNode.ts has not been loaded"),V0=V0||new wd({".priority":Rm},{".priority":Hr}),V0}constructor(n,a){this.indexes_=n,this.indexSet_=a}get(n){const a=Lh(this.indexes_,n);if(!a)throw new Error("No index defined for "+n);return a instanceof Wo?a:null}hasIndex(n){return pl(this.indexSet_,n.toString())}addIndex(n,a){la(n!==kh,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const s=[];let i=!1;const c=a.getIterator(ws.Wrap);let l=c.getNext();for(;l;)i=i||n.isDefinedOn(l.node),s.push(l),l=c.getNext();let m;i?m=bb(s,n.getCompare()):m=Rm;const d=n.toString(),u={...this.indexSet_};u[d]=n;const f={...this.indexes_};return f[d]=m,new wd(f,u)}addToIndexes(n,a){const s=cb(this.indexes_,(i,c)=>{const l=Lh(this.indexSet_,c);if(la(l,"Missing index implementation for "+c),i===Rm)if(l.isDefinedOn(n.node)){const m=[],d=a.getIterator(ws.Wrap);let u=d.getNext();for(;u;)u.name!==n.name&&m.push(u),u=d.getNext();return m.push(n),bb(m,l.getCompare())}else return Rm;else{const m=a.get(n.name);let d=i;return m&&(d=d.remove(new ws(n.name,m))),d.insert(n,n.node)}});return new wd(s,this.indexSet_)}removeFromIndexes(n,a){const s=cb(this.indexes_,i=>{if(i===Rm)return i;{const c=a.get(n.name);return c?i.remove(new ws(n.name,c)):i}});return new wd(s,this.indexSet_)}}/** 2213 * @license 2214 * Copyright 2017 Google LLC 2215 * 2216 * Licensed under the Apache License, Version 2.0 (the "License"); 2217 * you may not use this file except in compliance with the License. 2218 * You may obtain a copy of the License at 2219 * 2220 * http://www.apache.org/licenses/LICENSE-2.0 2221 * 2222 * Unless required by applicable law or agreed to in writing, software 2223 * distributed under the License is distributed on an "AS IS" BASIS, 2224 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2225 * See the License for the specific language governing permissions and 2226 * limitations under the License. 2227 */let gf;class ts{static get EMPTY_NODE(){return gf||(gf=new ts(new Wo(xw),null,wd.Default))}constructor(n,a,s){this.children_=n,this.priorityNode_=a,this.indexMap_=s,this.lazyHash_=null,this.priorityNode_&&Lk(this.priorityNode_),this.children_.isEmpty()&&la(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||gf}updatePriority(n){return this.children_.isEmpty()?this:new ts(this.children_,n,this.indexMap_)}getImmediateChild(n){if(n===".priority")return this.getPriority();{const a=this.children_.get(n);return a===null?gf:a}}getChild(n){const a=xs(n);return a===null?this:this.getImmediateChild(a).getChild(Pr(n))}hasChild(n){return this.children_.get(n)!==null}updateImmediateChild(n,a){if(la(a,"We should always be passing snapshot nodes"),n===".priority")return this.updatePriority(a);{const s=new ws(n,a);let i,c;a.isEmpty()?(i=this.children_.remove(n),c=this.indexMap_.removeFromIndexes(s,this.children_)):(i=this.children_.insert(n,a),c=this.indexMap_.addToIndexes(s,this.children_));const l=i.isEmpty()?gf:this.priorityNode_;return new ts(i,l,c)}}updateChild(n,a){const s=xs(n);if(s===null)return a;{la(xs(n)!==".priority"||Ou(n)===1,".priority must be the last token in a path");const i=this.getImmediateChild(s).updateChild(Pr(n),a);return this.updateImmediateChild(s,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const a={};let s=0,i=0,c=!0;if(this.forEachChild(Hr,(l,m)=>{a[l]=m.val(n),s++,c&&ts.INTEGER_REGEXP_.test(l)?i=Math.max(i,Number(l)):c=!1}),!n&&c&&i<2*s){const l=[];for(const m in a)l[m]=a[m];return l}else return n&&!this.getPriority().isEmpty()&&(a[".priority"]=this.getPriority().val()),a}hash(){if(this.lazyHash_===null){let n="";
2227this.getPriority().isEmpty()||(n+="priority:"+Ok(this.getPriority().val())+":"),this.forEachChild(Hr,(a,s)=>{const i=s.hash();i!==""&&(n+=":"+a+":"+i)}),this.lazyHash_=n===""?"":mk(n)}return this.lazyHash_}getPredecessorChildName(n,a,s){const i=this.resolveIndex_(s);if(i){const c=i.getPredecessorKey(new ws(n,a));return c?c.name:null}else return this.children_.getPredecessorKey(n)}getFirstChildName(n){const a=this.resolveIndex_(n);if(a){const s=a.minKey();return s&&s.name}else return this.children_.minKey()}getFirstChild(n){const a=this.getFirstChildName(n);return a?new ws(a,this.children_.get(a)):null}getLastChildName(n){const a=this.resolveIndex_(n);if(a){const s=a.maxKey();return s&&s.name}else return this.children_.maxKey()}getLastChild(n){const a=this.getLastChildName(n);return a?new ws(a,this.children_.get(a)):null}forEachChild(n,a){const s=this.resolveIndex_(n);return s?s.inorderTraversal(i=>a(i.name,i.node)):this.children_.inorderTraversal(a)}getIterator(n){return this.getIteratorFrom(n.minPost(),n)}getIteratorFrom(n,a){const s=this.resolveIndex_(a);if(s)return s.getIteratorFrom(n,i=>i);{const i=this.children_.getIteratorFrom(n.name,ws.Wrap);let c=i.peek();for(;c!=null&&a.compare(c,n)<0;)i.getNext(),c=i.peek();return i}}getReverseIterator(n){return this.getReverseIteratorFrom(n.maxPost(),n)}getReverseIteratorFrom(n,a){const s=this.resolveIndex_(a);if(s)return s.getReverseIteratorFrom(n,i=>i);{const i=this.children_.getReverseIteratorFrom(n.name,ws.Wrap);let c=i.peek();for(;c!=null&&a.compare(c,n)>0;)i.getNext(),c=i.peek();return i}}compareTo(n){return this.isEmpty()?n.isEmpty()?0:-1:n.isLeafNode()||n.isEmpty()?1:n===Pg?-1:0}withIndex(n){if(n===kh||this.indexMap_.hasIndex(n))return this;{const a=this.indexMap_.addIndex(n,this.children_);return new ts(this.children_,this.priorityNode_,a)}}isIndexed(n){return n===kh||this.indexMap_.hasIndex(n)}equals(n){if(n===this)return!0;if(n.isLeafNode())return!1;{const a=n;if(this.getPriority().equals(a.getPriority()))if(this.children_.count()===a.children_.count()){const s=this.getIterator(Hr),i=a.getIterator(Hr);let c=s.getNext(),l=i.getNext();for(;c&&l;){if(c.name!==l.name||!c.node.equals(l.node))return!1;c=s.getNext(),l=i.getNext()}return c===null&&l===null}else return!1;else return!1}}resolveIndex_(n){return n===kh?null:this.indexMap_.get(n.toString())}}ts.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class y3 extends ts{constructor(){super(new Wo(xw),ts.EMPTY_NODE,wd.Default)}compareTo(n){return n===this?0:1}equals(n){return n===this}getPriority(){return this}getImmediateChild(n){return ts.EMPTY_NODE}isEmpty(){return!1}}const Pg=new y3;Object.defineProperties(ws,{MIN:{value:new ws(Vh,ts.EMPTY_NODE)},MAX:{value:new ws($u,Pg)}});$k.__EMPTY_NODE=ts.EMPTY_NODE;qi.__childrenNodeConstructor=ts;u3(Pg);m3(Pg);/** 2228 * @license 2229 * Copyright 2017 Google LLC 2230 * 2231 * Licensed under the Apache License, Version 2.0 (the "License"); 2232 * you may not use this file except in compliance with the License. 2233 * You may obtain a copy of the License at 2234 * 2235 * http://www.apache.org/licenses/LICENSE-2.0 2236 * 2237 * Unless required by applicable law or agreed to in writing, software 2238 * distributed under the License is distributed on an "AS IS" BASIS, 2239 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2240 * See the License for the specific language governing permissions and 2241 * limitations under the License. 2242 */const v3=!0;function ji(t,n=null){if(t===null)return ts.EMPTY_NODE;if(typeof t=="object"&&".priority"in t&&(n=t[".priority"]),la(n===null||typeof n=="string"||typeof n=="number"||typeof n=="object"&&".sv"in n,"Invalid priority type found: "+typeof n),typeof t=="object"&&".value"in t&&t[".value"]!==null&&(t=t[".value"]),typeof t!="object"||".sv"in t){const a=t;return new qi(a,ji(n))}if(!(t instanceof Array)&&v3){const a=[];let s=!1;if(eo(t,(l,m)=>{if(l.substring(0,1)!=="."){const d=ji(m);d.isEmpty()||(s=s||!d.getPriority().isEmpty(),a.push(new ws(l,d)))}}),a.length===0)return ts.EMPTY_NODE;const c=bb(a,d3,l=>l.name,xw);if(s){const l=bb(a,Hr.getCompare());return new ts(c,ji(n),new wd({".priority":l},{".priority":Hr}))}else return new ts(c,ji(n),wd.Default)}else{let a=ts.EMPTY_NODE;return eo(t,(s,i)=>{if(pl(t,s)&&s.substring(0,1)!=="."){const c=ji(i);(c.isLeafNode()||!c.isEmpty())&&(a=a.updateImmediateChild(s,c))}}),a.updatePriority(ji(n))}}h3(ji);/** 2243 * @license 2244 * Copyright 2017 Google LLC 2245 * 2246 * Licensed under the Apache License, Version 2.0 (the "License");
2247 * you may not use this file except in compliance with the License. 2248 * You may obtain a copy of the License at 2249 * 2250 * http://www.apache.org/licenses/LICENSE-2.0 2251 * 2252 * Unless required by applicable law or agreed to in writing, software 2253 * distributed under the License is distributed on an "AS IS" BASIS, 2254 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2255 * See the License for the specific language governing permissions and 2256 * limitations under the License. 2257 */class jw extends Yb{constructor(n){super(),this.indexPath_=n,la(!js(n)&&xs(n)!==".priority","Can't create PathIndex with empty path or .priority key")}extractChild(n){return n.getChild(this.indexPath_)}isDefinedOn(n){return!n.getChild(this.indexPath_).isEmpty()}compare(n,a){const s=this.extractChild(n.node),i=this.extractChild(a.node),c=s.compareTo(i);return c===0?Kh(n.name,a.name):c}makePost(n,a){const s=ji(n),i=ts.EMPTY_NODE.updateChild(this.indexPath_,s);return new ws(a,i)}maxPost(){const n=ts.EMPTY_NODE.updateChild(this.indexPath_,Pg);return new ws($u,n)}toString(){return og(this.indexPath_,0).join("/")}}/** 2258 * @license 2259 * Copyright 2017 Google LLC 2260 * 2261 * Licensed under the Apache License, Version 2.0 (the "License"); 2262 * you may not use this file except in compliance with the License. 2263 * You may obtain a copy of the License at 2264 * 2265 * http://www.apache.org/licenses/LICENSE-2.0 2266 * 2267 * Unless required by applicable law or agreed to in writing, software 2268 * distributed under the License is distributed on an "AS IS" BASIS, 2269 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2270 * See the License for the specific language governing permissions and 2271 * limitations under the License. 2272 */class b3 extends Yb{compare(n,a){const s=n.node.compareTo(a.node);return s===0?Kh(n.name,a.name):s}isDefinedOn(n){return!0}indexedValueChanged(n,a){return!n.equals(a)}minPost(){return ws.MIN}maxPost(){return ws.MAX}makePost(n,a){const s=ji(n);return new ws(a,s)}toString(){return".value"}}const Uk=new b3;/** 2273 * @license 2274 * Copyright 2017 Google LLC 2275 * 2276 * Licensed under the Apache License, Version 2.0 (the "License"); 2277 * you may not use this file except in compliance with the License. 2278 * You may obtain a copy of the License at 2279 * 2280 * http://www.apache.org/licenses/LICENSE-2.0 2281 * 2282 * Unless required by applicable law or agreed to in writing, software 2283 * distributed under the License is distributed on an "AS IS" BASIS, 2284 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2285 * See the License for the specific language governing permissions and 2286 * limitations under the License. 2287 */function zk(t){return{type:"value",snapshotNode:t}}function fp(t,n){return{type:"child_added",snapshotNode:n,childName:t}}function cg(t,n){return{type:"child_removed",snapshotNode:n,childName:t}}function lg(t,n,a){return{type:"child_changed",snapshotNode:n,childName:t,oldSnap:a}}function x3(t,n){return{type:"child_moved",snapshotNode:n,childName:t}}/** 2288 * @license 2289 * Copyright 2017 Google LLC 2290 * 2291 * Licensed under the Apache License, Version 2.0 (the "License"); 2292 * you may not use this file except in compliance with the License. 2293 * You may obtain a copy of the License at 2294 * 2295 * http://www.apache.org/licenses/LICENSE-2.0 2296 * 2297 * Unless required by applicable law or agreed to in writing, software 2298 * distributed under the License is distributed on an "AS IS" BASIS, 2299 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2300 * See the License for the specific language governing permissions and 2301 * limitations under the License. 2302 */class ww{constructor(n){this.index_=n}updateChild(n,a,s,i,c,l){la(n.isIndexed(this.index_),"A node must be indexed if only a child is updated");const m=n.getImmediateChild(a);return m.getChild(i).equals(s.getChild(i))&&m.isEmpty()===s.isEmpty()||(l!=null&&(s.isEmpty()?n.hasChild(a)?l.trackChildChange(cg(a,m)):la(n.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):m.isEmpty()?l.trackChildChange(fp(a,s)):l.trackChildChange(lg(a,s,m))),n.isLeafNode()&&s.isEmpty())?n:n.updateImmediateChild(a,s).withIndex(this.index_)}
vendor: 5,101 bytes, lines 2302-2332
2302updateFullNode(n,a,s){return s!=null&&(n.isLeafNode()||n.forEachChild(Hr,(i,c)=>{a.hasChild(i)||s.trackChildChange(cg(i,c))}),a.isLeafNode()||a.forEachChild(Hr,(i,c)=>{if(n.hasChild(i)){const l=n.getImmediateChild(i);l.equals(c)||s.trackChildChange(lg(i,c,l))}else s.trackChildChange(fp(i,c))})),a.withIndex(this.index_)}updatePriority(n,a){return n.isEmpty()?ts.EMPTY_NODE:n.updatePriority(a)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/** 2303 * @license 2304 * Copyright 2017 Google LLC 2305 * 2306 * Licensed under the Apache License, Version 2.0 (the "License"); 2307 * you may not use this file except in compliance with the License. 2308 * You may obtain a copy of the License at 2309 * 2310 * http://www.apache.org/licenses/LICENSE-2.0 2311 * 2312 * Unless required by applicable law or agreed to in writing, software 2313 * distributed under the License is distributed on an "AS IS" BASIS, 2314 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2315 * See the License for the specific language governing permissions and 2316 * limitations under the License. 2317 */class dg{constructor(n){this.indexedFilter_=new ww(n.getIndex()),this.index_=n.getIndex(),this.startPost_=dg.getStartPost_(n),this.endPost_=dg.getEndPost_(n),this.startIsInclusive_=!n.startAfterSet_,this.endIsInclusive_=!n.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(n){const a=this.startIsInclusive_?this.index_.compare(this.getStartPost(),n)<=0:this.index_.compare(this.getStartPost(),n)<0,s=this.endIsInclusive_?this.index_.compare(n,this.getEndPost())<=0:this.index_.compare(n,this.getEndPost())<0;return a&&s}updateChild(n,a,s,i,c,l){return this.matches(new ws(a,s))||(s=ts.EMPTY_NODE),this.indexedFilter_.updateChild(n,a,s,i,c,l)}updateFullNode(n,a,s){a.isLeafNode()&&(a=ts.EMPTY_NODE);let i=a.withIndex(this.index_);i=i.updatePriority(ts.EMPTY_NODE);const c=this;return a.forEachChild(Hr,(l,m)=>{c.matches(new ws(l,m))||(i=i.updateImmediateChild(l,ts.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(n,i,s)}updatePriority(n,a){return n}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(n){if(n.hasStart()){const a=n.getIndexStartName();return n.getIndex().makePost(n.getIndexStartValue(),a)}else return n.getIndex().minPost()}static getEndPost_(n){if(n.hasEnd()){const a=n.getIndexEndName();return n.getIndex().makePost(n.getIndexEndValue(),a)}else return n.getIndex().maxPost()}}/** 2318 * @license 2319 * Copyright 2017 Google LLC 2320 * 2321 * Licensed under the Apache License, Version 2.0 (the "License"); 2322 * you may not use this file except in compliance with the License. 2323 * You may obtain a copy of the License at 2324 * 2325 * http://www.apache.org/licenses/LICENSE-2.0 2326 * 2327 * Unless required by applicable law or agreed to in writing, software 2328 * distributed under the License is distributed on an "AS IS" BASIS, 2329 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2330 * See the License for the specific language governing permissions and 2331 * limitations under the License. 2332 */class j3{constructor(n){this.withinDirectionalStart=a=>this.reverse_?this.withinEndPost(a):this.withinStartPost(a),this.withinDirectionalEnd=a=>this.reverse_?this.withinStartPost(a):this.withinEndPost(a),this.withinStartPost=a=>{const s=this.index_.compare(this.rangedFilter_.getStartPost(),a);return this.startIsInclusive_?s<=0:s<0},this.withinEndPost=a=>{const s=this.index_.compare(a,this.rangedFilter_.getEndPost());return this.endIsInclusive_?s<=0:s<0},this.rangedFilter_=new dg(n),this.index_=n.getIndex(),this.limit_=n.getLimit(),this.reverse_=!n.isViewFromLeft(),this.startIsInclusive_=!n.startAfterSet_,this.endIsInclusive_=!n.endBeforeSet_}updateChild(n,a,s,i,c,l){return this.rangedFilter_.matches(new ws(a,s))||(s=ts.EMPTY_NODE),n.getImmediateChild(a).equals(s)?n:n.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(n,a,s,i,c,l):this.fullLimitUpdateChild_(n,a,s,c,l)}updateFullNode(n,a,s){let i;if(a.isLeafNode()||a.isEmpty())i=ts.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<a.numChildren()&&a.isIndexed(this.index_)){i=ts.EMPTY_NODE.withIndex(this.index_);let c;this.reverse_?c=a.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):c=a.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let l=0;for(;c.hasNext()&&l<this.limit_;){const m=c.getNext();if(this.withinDirectionalStart(m))if(this.withinDirectionalEnd(m))i=i.updateImmediateChild(m.name,m.node),l++;else break;else continue}}else{i=a.withIndex(this.index_),i=i.updatePriority(ts.EMPTY_NODE);let c;this.reverse_?c=i.getReverseIterator(this.index_):c=i.getIterator(this.index_);let l=0;for(;c.hasNext();){const m=c.getNext();l<this.limit_&&this.withinDirectionalStart(m)&&this.withinDirectionalEnd(m)?l++:i=i.updateImmediateChild(m.name,ts.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(n,i,s)}updatePriority(n,a){return n}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}
2332fullLimitUpdateChild_(n,a,s,i,c){let l;if(this.reverse_){const g=this.index_.getCompare();l=(p,y)=>g(y,p)}else l=this.index_.getCompare();const m=n;la(m.numChildren()===this.limit_,"");const d=new ws(a,s),u=this.reverse_?m.getFirstChild(this.index_):m.getLastChild(this.index_),f=this.rangedFilter_.matches(d);if(m.hasChild(a)){const g=m.getImmediateChild(a);let p=i.getChildAfterChild(this.index_,u,this.reverse_);for(;p!=null&&(p.name===a||m.hasChild(p.name));)p=i.getChildAfterChild(this.index_,p,this.reverse_);const y=p==null?1:l(p,d);if(f&&!s.isEmpty()&&y>=0)return c!=null&&c.trackChildChange(lg(a,s,g)),m.updateImmediateChild(a,s);{c!=null&&c.trackChildChange(cg(a,g));const N=m.updateImmediateChild(a,ts.EMPTY_NODE);return p!=null&&this.rangedFilter_.matches(p)?(c!=null&&c.trackChildChange(fp(p.name,p.node)),N.updateImmediateChild(p.name,p.node)):N}}else return s.isEmpty()?n:f&&l(u,d)>=0?(c!=null&&(c.trackChildChange(cg(u.name,u.node)),c.trackChildChange(fp(a,s))),m.updateImmediateChild(a,s).updateImmediateChild(u.name,ts.EMPTY_NODE)):n}}/** 2333 * @license 2334 * Copyright 2017 Google LLC 2335 * 2336 * Licensed under the Apache License, Version 2.0 (the "License"); 2337 * you may not use this file except in compliance with the License. 2338 * You may obtain a copy of the License at 2339 * 2340 * http://www.apache.org/licenses/LICENSE-2.0 2341 * 2342 * Unless required by applicable law or agreed to in writing, software 2343 * distributed under the License is distributed on an "AS IS" BASIS, 2344 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2345 * See the License for the specific language governing permissions and 2346 * limitations under the License. 2347 */class Nw{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=Hr}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return la(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return la(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Vh}hasEnd(){return this.endSet_}getIndexEndValue(){return la(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return la(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:$u}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return la(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===Hr}copy(){const n=new Nw;return n.limitSet_=this.limitSet_,n.limit_=this.limit_,n.startSet_=this.startSet_,n.startAfterSet_=this.startAfterSet_,n.indexStartValue_=this.indexStartValue_,n.startNameSet_=this.startNameSet_,n.indexStartName_=this.indexStartName_,n.endSet_=this.endSet_,n.endBeforeSet_=this.endBeforeSet_,n.indexEndValue_=this.indexEndValue_,n.endNameSet_=this.endNameSet_,n.indexEndName_=this.indexEndName_,n.index_=this.index_,n.viewFrom_=this.viewFrom_,n}}function w3(t){return t.loadsAllData()?new ww(t.getIndex()):t.hasLimit()?new j3(t):new dg(t)}function N3(t,n){const a=t.copy();return a.limitSet_=!0,a.limit_=n,a.viewFrom_="r",a}function S3(t,n,a){const s=t.copy();return s.startSet_=!0,n===void 0&&(n=null),s.indexStartValue_=n,a!=null?(s.startNameSet_=!0,s.indexStartName_=a):(s.startNameSet_=!1,s.indexStartName_=""),s}function C3(t,n,a){const s=t.copy();return s.endSet_=!0,n===void 0&&(n=null),s.indexEndValue_=n,a!==void 0?(s.endNameSet_=!0,s.indexEndName_=a):(s.endNameSet_=!1,s.indexEndName_=""),s}function A3(t,n){const a=t.copy();return a.index_=n,a}function $C(t){const n={};if(t.isDefault())return n;let a;if(t.index_===Hr?a="$priority":t.index_===Uk?a="$value":t.index_===kh?a="$key":(la(t.index_ instanceof jw,"Unrecognized index type!"),a=t.index_.toString()),n.orderBy=Ri(a),t.startSet_){const s=t.startAfterSet_?"startAfter":"startAt";
vendor: 4,117 bytes, lines 2347-2381
2347n[s]=Ri(t.indexStartValue_),t.startNameSet_&&(n[s]+=","+Ri(t.indexStartName_))}if(t.endSet_){const s=t.endBeforeSet_?"endBefore":"endAt";n[s]=Ri(t.indexEndValue_),t.endNameSet_&&(n[s]+=","+Ri(t.indexEndName_))}return t.limitSet_&&(t.isViewFromLeft()?n.limitToFirst=t.limit_:n.limitToLast=t.limit_),n}function OC(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_),n.sin=!t.startAfterSet_),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_),n.ein=!t.endBeforeSet_),t.limitSet_){n.l=t.limit_;let a=t.viewFrom_;a===""&&(t.isViewFromLeft()?a="l":a="r"),n.vf=a}return t.index_!==Hr&&(n.i=t.index_.toString()),n}/** 2348 * @license 2349 * Copyright 2017 Google LLC 2350 * 2351 * Licensed under the Apache License, Version 2.0 (the "License"); 2352 * you may not use this file except in compliance with the License. 2353 * You may obtain a copy of the License at 2354 * 2355 * http://www.apache.org/licenses/LICENSE-2.0 2356 * 2357 * Unless required by applicable law or agreed to in writing, software 2358 * distributed under the License is distributed on an "AS IS" BASIS, 2359 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2360 * See the License for the specific language governing permissions and 2361 * limitations under the License. 2362 */class xb extends Pk{reportStats(n){throw new Error("Method not implemented.")}static getListenId_(n,a){return a!==void 0?"tag$"+a:(la(n._queryParams.isDefault(),"should have a tag if it's not a default query."),n._path.toString())}constructor(n,a,s,i){super(),this.repoInfo_=n,this.onDataUpdate_=a,this.authTokenProvider_=s,this.appCheckTokenProvider_=i,this.log_=Eg("p:rest:"),this.listens_={}}listen(n,a,s,i){const c=n._path.toString();this.log_("Listen called for "+c+" "+n._queryIdentifier);const l=xb.getListenId_(n,s),m={};this.listens_[l]=m;const d=$C(n._queryParams);this.restRequest_(c+".json",d,(u,f)=>{let g=f;if(u===404&&(g=null,u=null),u===null&&this.onDataUpdate_(c,g,!1,s),Lh(this.listens_,l)===m){let p;u?u===401?p="permission_denied":p="rest_error:"+u:p="ok",i(p,null)}})}unlisten(n,a){const s=xb.getListenId_(n,a);delete this.listens_[s]}get(n){const a=$C(n._queryParams),s=n._path.toString(),i=new Jh;return this.restRequest_(s+".json",a,(c,l)=>{let m=l;c===404&&(m=null,c=null),c===null?(this.onDataUpdate_(s,m,!1,null),i.resolve(m)):i.reject(new Error(m))}),i.promise}refreshAuthToken(n){}restRequest_(n,a={},s){return a.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,c])=>{i&&i.accessToken&&(a.auth=i.accessToken),c&&c.token&&(a.ac=c.token);const l=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+n+"?ns="+this.repoInfo_.namespace+Ap(a);this.log_("Sending REST request for "+l);const m=new XMLHttpRequest;m.onreadystatechange=()=>{if(s&&m.readyState===4){this.log_("REST Response for "+l+" received. status:",m.status,"response:",m.responseText);let d=null;if(m.status>=200&&m.status<300){try{d=ag(m.responseText)}catch{Co("Failed to parse JSON response for "+l+": "+m.responseText)}s(null,d)}else m.status!==401&&m.status!==404&&Co("Got unsuccessful REST response for "+l+" Status: "+m.status),s(m.status);s=null}},m.open("GET",l,!0),m.send()})}}/** 2363 * @license 2364 * Copyright 2017 Google LLC 2365 * 2366 * Licensed under the Apache License, Version 2.0 (the "License"); 2367 * you may not use this file except in compliance with the License. 2368 * You may obtain a copy of the License at 2369 * 2370 * http://www.apache.org/licenses/LICENSE-2.0 2371 * 2372 * Unless required by applicable law or agreed to in writing, software 2373 * distributed under the License is distributed on an "AS IS" BASIS, 2374 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2375 * See the License for the specific language governing permissions and 2376 * limitations under the License. 2377 */class I3{constructor(){this.rootNode_=ts.EMPTY_NODE}getNode(n){return this.rootNode_.getChild(n)}updateSnapshot(n,a){this.rootNode_=this.rootNode_.updateChild(n,a)}}/** 2378 * @license 2379 * Copyright 2017 Google LLC 2380 * 2381 * Licensed under the Apache License, Version 2.0 (the "License");
2382 * you may not use this file except in compliance with the License. 2383 * You may obtain a copy of the License at 2384 * 2385 * http://www.apache.org/licenses/LICENSE-2.0 2386 * 2387 * Unless required by applicable law or agreed to in writing, software 2388 * distributed under the License is distributed on an "AS IS" BASIS, 2389 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2390 * See the License for the specific language governing permissions and 2391 * limitations under the License. 2392 */function jb(){return{value:null,children:new Map}}function qk(t,n,a){if(js(n))t.value=a,t.children.clear();else if(t.value!==null)t.value=t.value.updateChild(n,a);else{const s=xs(n);t.children.has(s)||t.children.set(s,jb());const i=t.children.get(s);n=Pr(n),qk(i,n,a)}}function o1(t,n,a){t.value!==null?a(n,t.value):_3(t,(s,i)=>{const c=new mr(n.toString()+"/"+s);o1(i,c,a)})}function _3(t,n){t.children.forEach((a,s)=>{n(s,a)})}/** 2393 * @license 2394 * Copyright 2017 Google LLC 2395 * 2396 * Licensed under the Apache License, Version 2.0 (the "License"); 2397 * you may not use this file except in compliance with the License. 2398 * You may obtain a copy of the License at 2399 * 2400 * http://www.apache.org/licenses/LICENSE-2.0 2401 * 2402 * Unless required by applicable law or agreed to in writing, software 2403 * distributed under the License is distributed on an "AS IS" BASIS, 2404 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2405 * See the License for the specific language governing permissions and 2406 * limitations under the License. 2407 */class k3{constructor(n){this.collection_=n,this.last_=null}get(){const n=this.collection_.get(),a={...n};return this.last_&&eo(this.last_,(s,i)=>{a[s]=a[s]-i}),this.last_=n,a}}/** 2408 * @license 2409 * Copyright 2017 Google LLC 2410 * 2411 * Licensed under the Apache License, Version 2.0 (the "License"); 2412 * you may not use this file except in compliance with the License. 2413 * You may obtain a copy of the License at 2414 * 2415 * http://www.apache.org/licenses/LICENSE-2.0 2416 * 2417 * Unless required by applicable law or agreed to in writing, software 2418 * distributed under the License is distributed on an "AS IS" BASIS, 2419 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2420 * See the License for the specific language governing permissions and 2421 * limitations under the License. 2422 */const LC=10*1e3,D3=30*1e3,E3=300*1e3;class P3{constructor(n,a){this.server_=a,this.statsToReport_={},this.statsListener_=new k3(n);const s=LC+(D3-LC)*Math.random();Hf(this.reportStats_.bind(this),Math.floor(s))}reportStats_(){const n=this.statsListener_.get(),a={};let s=!1;eo(n,(i,c)=>{c>0&&pl(this.statsToReport_,i)&&(a[i]=c,s=!0)}),s&&this.server_.reportStats(a),Hf(this.reportStats_.bind(this),Math.floor(Math.random()*2*E3))}}/** 2423 * @license 2424 * Copyright 2017 Google LLC 2425 * 2426 * Licensed under the Apache License, Version 2.0 (the "License"); 2427 * you may not use this file except in compliance with the License. 2428 * You may obtain a copy of the License at 2429 * 2430 * http://www.apache.org/licenses/LICENSE-2.0 2431 * 2432 * Unless required by applicable law or agreed to in writing, software 2433 * distributed under the License is distributed on an "AS IS" BASIS, 2434 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2435 * See the License for the specific language governing permissions and 2436 * limitations under the License. 2437 */var ul;(function(t){t[t.OVERWRITE=0]="OVERWRITE",t[t.MERGE=1]="MERGE",t[t.ACK_USER_WRITE=2]="ACK_USER_WRITE",t[t.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(ul||(ul={}));function Sw(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Cw(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Aw(t){return{fromUser:!1,fromServer:!0,queryId:t,tagged:!0}}/** 2438 * @license 2439 * Copyright 2017 Google LLC 2440 * 2441 * Licensed under the Apache License, Version 2.0 (the "License"); 2442 * you may not use this file except in compliance with the License. 2443 * You may obtain a copy of the License at 2444 * 2445 * http://www.apache.org/licenses/LICENSE-2.0 2446 * 2447 * Unless required by applicable law or agreed to in writing, software 2448 * distributed under the License is distributed on an "AS IS" BASIS, 2449 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2450 * See the License for the specific language governing permissions and 2451 * limitations under the License. 2452 */class wb{constructor(n,a,s){this.path=n,this.affectedTree=a,this.revert=s,this.type=ul.ACK_USER_WRITE,this.source=Sw()}operationForChild(n){if(js(this.path)){if(this.affectedTree.value!=null)return la(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const a=this.affectedTree.subtree(new mr(n));return new wb(Qs(),a,this.revert)}}else return la(xs(this.path)===n,"operationForChild called for unrelated child."),new wb(Pr(this.path),this.affectedTree,this.revert)}}/** 2453 * @license 2454 * Copyright 2017 Google LLC 2455 * 2456 * Licensed under the Apache License, Version 2.0 (the "License");
2457 * you may not use this file except in compliance with the License. 2458 * You may obtain a copy of the License at 2459 * 2460 * http://www.apache.org/licenses/LICENSE-2.0 2461 * 2462 * Unless required by applicable law or agreed to in writing, software 2463 * distributed under the License is distributed on an "AS IS" BASIS, 2464 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2465 * See the License for the specific language governing permissions and 2466 * limitations under the License. 2467 */class ug{constructor(n,a){this.source=n,this.path=a,this.type=ul.LISTEN_COMPLETE}operationForChild(n){return js(this.path)?new ug(this.source,Qs()):new ug(this.source,Pr(this.path))}}/** 2468 * @license 2469 * Copyright 2017 Google LLC 2470 * 2471 * Licensed under the Apache License, Version 2.0 (the "License"); 2472 * you may not use this file except in compliance with the License. 2473 * You may obtain a copy of the License at 2474 * 2475 * http://www.apache.org/licenses/LICENSE-2.0 2476 * 2477 * Unless required by applicable law or agreed to in writing, software 2478 * distributed under the License is distributed on an "AS IS" BASIS, 2479 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2480 * See the License for the specific language governing permissions and 2481 * limitations under the License. 2482 */class Hh{constructor(n,a,s){this.source=n,this.path=a,this.snap=s,this.type=ul.OVERWRITE}operationForChild(n){return js(this.path)?new Hh(this.source,Qs(),this.snap.getImmediateChild(n)):new Hh(this.source,Pr(this.path),this.snap)}}/** 2483 * @license 2484 * Copyright 2017 Google LLC 2485 * 2486 * Licensed under the Apache License, Version 2.0 (the "License"); 2487 * you may not use this file except in compliance with the License. 2488 * You may obtain a copy of the License at 2489 * 2490 * http://www.apache.org/licenses/LICENSE-2.0 2491 * 2492 * Unless required by applicable law or agreed to in writing, software 2493 * distributed under the License is distributed on an "AS IS" BASIS, 2494 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2495 * See the License for the specific language governing permissions and 2496 * limitations under the License. 2497 */class gp{constructor(n,a,s){this.source=n,this.path=a,this.children=s,this.type=ul.MERGE}operationForChild(n){if(js(this.path)){const a=this.children.subtree(new mr(n));return a.isEmpty()?null:a.value?new Hh(this.source,Qs(),a.value):new gp(this.source,Qs(),a)}else return la(xs(this.path)===n,"Can't get a merge for a child not on the path of the operation"),new gp(this.source,Pr(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}/** 2498 * @license 2499 * Copyright 2017 Google LLC 2500 * 2501 * Licensed under the Apache License, Version 2.0 (the "License"); 2502 * you may not use this file except in compliance with the License. 2503 * You may obtain a copy of the License at 2504 * 2505 * http://www.apache.org/licenses/LICENSE-2.0 2506 * 2507 * Unless required by applicable law or agreed to in writing, software 2508 * distributed under the License is distributed on an "AS IS" BASIS, 2509 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2510 * See the License for the specific language governing permissions and 2511 * limitations under the License. 2512 */class Lu{constructor(n,a,s){this.node_=n,this.fullyInitialized_=a,this.filtered_=s}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(n){if(js(n))return this.isFullyInitialized()&&!this.filtered_;const a=xs(n);return this.isCompleteForChild(a)}isCompleteForChild(n){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(n)}getNode(){return this.node_}}/** 2513 * @license 2514 * Copyright 2017 Google LLC 2515 * 2516 * Licensed under the Apache License, Version 2.0 (the "License"); 2517 * you may not use this file except in compliance with the License. 2518 * You may obtain a copy of the License at 2519 * 2520 * http://www.apache.org/licenses/LICENSE-2.0 2521 * 2522 * Unless required by applicable law or agreed to in writing, software 2523 * distributed under the License is distributed on an "AS IS" BASIS, 2524 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2525 * See the License for the specific language governing permissions and 2526 * limitations under the License. 2527 */class R3{constructor(n){this.query_=n,this.index_=this.query_._queryParams.getIndex()}}function T3(t,n,a,s){const i=[],c=[];
2527return n.forEach(l=>{l.type==="child_changed"&&t.index_.indexedValueChanged(l.oldSnap,l.snapshotNode)&&c.push(x3(l.childName,l.snapshotNode))}),yf(t,i,"child_removed",n,s,a),yf(t,i,"child_added",n,s,a),yf(t,i,"child_moved",c,s,a),yf(t,i,"child_changed",n,s,a),yf(t,i,"value",n,s,a),i}function yf(t,n,a,s,i,c){const l=s.filter(m=>m.type===a);l.sort((m,d)=>$3(t,m,d)),l.forEach(m=>{const d=M3(t,m,c);i.forEach(u=>{u.respondsTo(m.type)&&n.push(u.createEvent(d,t.query_))})})}function M3(t,n,a){return n.type==="value"||n.type==="child_removed"||(n.prevName=a.getPredecessorChildName(n.childName,n.snapshotNode,t.index_)),n}function $3(t,n,a){if(n.childName==null||a.childName==null)throw Cp("Should only compare child_ events.");const s=new ws(n.childName,n.snapshotNode),i=new ws(a.childName,a.snapshotNode);return t.index_.compare(s,i)}/** 2528 * @license 2529 * Copyright 2017 Google LLC 2530 * 2531 * Licensed under the Apache License, Version 2.0 (the "License"); 2532 * you may not use this file except in compliance with the License. 2533 * You may obtain a copy of the License at 2534 * 2535 * http://www.apache.org/licenses/LICENSE-2.0 2536 * 2537 * Unless required by applicable law or agreed to in writing, software 2538 * distributed under the License is distributed on an "AS IS" BASIS, 2539 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2540 * See the License for the specific language governing permissions and 2541 * limitations under the License. 2542 */function Qb(t,n){return{eventCache:t,serverCache:n}}function Wf(t,n,a,s){return Qb(new Lu(n,a,s),t.serverCache)}function Vk(t,n,a,s){return Qb(t.eventCache,new Lu(n,a,s))}function Nb(t){return t.eventCache.isFullyInitialized()?t.eventCache.getNode():null}function Wh(t){return t.serverCache.isFullyInitialized()?t.serverCache.getNode():null}/** 2543 * @license 2544 * Copyright 2017 Google LLC 2545 * 2546 * Licensed under the Apache License, Version 2.0 (the "License"); 2547 * you may not use this file except in compliance with the License. 2548 * You may obtain a copy of the License at 2549 * 2550 * http://www.apache.org/licenses/LICENSE-2.0 2551 * 2552 * Unless required by applicable law or agreed to in writing, software 2553 * distributed under the License is distributed on an "AS IS" BASIS, 2554 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2555 * See the License for the specific language governing permissions and 2556 * limitations under the License. 2557 */let H0;const O3=()=>(H0||(H0=new Wo(bO)),H0);class Er{static fromObject(n){let a=new Er(null);return eo(n,(s,i)=>{a=a.set(new mr(s),i)}),a}constructor(n,a=O3()){this.value=n,this.children=a}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(n,a){if(this.value!=null&&a(this.value))return{path:Qs(),value:this.value};if(js(n))return null;{const s=xs(n),i=this.children.get(s);if(i!==null){const c=i.findRootMostMatchingPathAndValue(Pr(n),a);return c!=null?{path:si(new mr(s),c.path),value:c.value}:null}else return null}}findRootMostValueAndPath(n){return this.findRootMostMatchingPathAndValue(n,()=>!0)}subtree(n){if(js(n))return this;{const a=xs(n),s=this.children.get(a);return s!==null?s.subtree(Pr(n)):new Er(null)}}set(n,a){if(js(n))return new Er(a,this.children);{const s=xs(n),c=(this.children.get(s)||new Er(null)).set(Pr(n),a),l=this.children.insert(s,c);return new Er(this.value,l)}}remove(n){if(js(n))return this.children.isEmpty()?new Er(null):new Er(null,this.children);{const a=xs(n),s=this.children.get(a);if(s){const i=s.remove(Pr(n));let c;return i.isEmpty()?c=this.children.remove(a):c=this.children.insert(a,i),this.value===null&&c.isEmpty()?new Er(null):new Er(this.value,c)}else return this}}get(n){if(js(n))return this.value;{const a=xs(n),s=this.children.get(a);return s?s.get(Pr(n)):null}}setTree(n,a){if(js(n))return a;{const s=xs(n),c=(this.children.get(s)||new Er(null)).setTree(Pr(n),a);let l;return c.isEmpty()?l=this.children.remove(s):l=this.children.insert(s,c),new Er(this.value,l)}}fold(n){return this.fold_(Qs(),n)}fold_(n,a){const s={};return this.children.inorderTraversal((i,c)=>{s[i]=c.fold_(si(n,i),a)}),a(n,this.value,s)}findOnPath(n,a){return this.findOnPath_(n,Qs(),a)}findOnPath_(n,a,s){const i=this.value?s(a,this.value):!1;if(i)return i;if(js(n))return null;{const c=xs(n),l=this.children.get(c);return l?l.findOnPath_(Pr(n),si(a,c),s):null}}foreachOnPath(n,a){return this.foreachOnPath_(n,Qs(),a)}
vendor: 5,073 bytes, lines 2557-2587
2557foreachOnPath_(n,a,s){if(js(n))return this;{this.value&&s(a,this.value);const i=xs(n),c=this.children.get(i);return c?c.foreachOnPath_(Pr(n),si(a,i),s):new Er(null)}}foreach(n){this.foreach_(Qs(),n)}foreach_(n,a){this.children.inorderTraversal((s,i)=>{i.foreach_(si(n,s),a)}),this.value&&a(n,this.value)}foreachChild(n){this.children.inorderTraversal((a,s)=>{s.value&&n(a,s.value)})}}/** 2558 * @license 2559 * Copyright 2017 Google LLC 2560 * 2561 * Licensed under the Apache License, Version 2.0 (the "License"); 2562 * you may not use this file except in compliance with the License. 2563 * You may obtain a copy of the License at 2564 * 2565 * http://www.apache.org/licenses/LICENSE-2.0 2566 * 2567 * Unless required by applicable law or agreed to in writing, software 2568 * distributed under the License is distributed on an "AS IS" BASIS, 2569 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2570 * See the License for the specific language governing permissions and 2571 * limitations under the License. 2572 */class hl{constructor(n){this.writeTree_=n}static empty(){return new hl(new Er(null))}}function Gf(t,n,a){if(js(n))return new hl(new Er(a));{const s=t.writeTree_.findRootMostValueAndPath(n);if(s!=null){const i=s.path;let c=s.value;const l=So(i,n);return c=c.updateChild(l,a),new hl(t.writeTree_.set(i,c))}else{const i=new Er(a),c=t.writeTree_.setTree(n,i);return new hl(c)}}}function c1(t,n,a){let s=t;return eo(a,(i,c)=>{s=Gf(s,si(n,i),c)}),s}function BC(t,n){if(js(n))return hl.empty();{const a=t.writeTree_.setTree(n,new Er(null));return new hl(a)}}function l1(t,n){return Xh(t,n)!=null}function Xh(t,n){const a=t.writeTree_.findRootMostValueAndPath(n);return a!=null?t.writeTree_.get(a.path).getChild(So(a.path,n)):null}function FC(t){const n=[],a=t.writeTree_.value;return a!=null?a.isLeafNode()||a.forEachChild(Hr,(s,i)=>{n.push(new ws(s,i))}):t.writeTree_.children.inorderTraversal((s,i)=>{i.value!=null&&n.push(new ws(s,i.value))}),n}function Pu(t,n){if(js(n))return t;{const a=Xh(t,n);return a!=null?new hl(new Er(a)):new hl(t.writeTree_.subtree(n))}}function d1(t){return t.writeTree_.isEmpty()}function yp(t,n){return Hk(Qs(),t.writeTree_,n)}function Hk(t,n,a){if(n.value!=null)return a.updateChild(t,n.value);{let s=null;return n.children.inorderTraversal((i,c)=>{i===".priority"?(la(c.value!==null,"Priority writes must always be leaf nodes"),s=c.value):a=Hk(si(t,i),c,a)}),!a.getChild(t).isEmpty()&&s!==null&&(a=a.updateChild(si(t,".priority"),s)),a}}/** 2573 * @license 2574 * Copyright 2017 Google LLC 2575 * 2576 * Licensed under the Apache License, Version 2.0 (the "License"); 2577 * you may not use this file except in compliance with the License. 2578 * You may obtain a copy of the License at 2579 * 2580 * http://www.apache.org/licenses/LICENSE-2.0 2581 * 2582 * Unless required by applicable law or agreed to in writing, software 2583 * distributed under the License is distributed on an "AS IS" BASIS, 2584 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2585 * See the License for the specific language governing permissions and 2586 * limitations under the License. 2587 */function Jb(t,n){return Qk(n,t)}function L3(t,n,a,s,i){la(s>t.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),t.allWrites.push({path:n,snap:a,writeId:s,visible:i}),i&&(t.visibleWrites=Gf(t.visibleWrites,n,a)),t.lastWriteId=s}function B3(t,n,a,s){la(s>t.lastWriteId,"Stacking an older merge on top of newer ones"),t.allWrites.push({path:n,children:a,writeId:s,visible:!0}),t.visibleWrites=c1(t.visibleWrites,n,a),t.lastWriteId=s}function F3(t,n){for(let a=0;a<t.allWrites.length;a++){const s=t.allWrites[a];if(s.writeId===n)return s}return null}function U3(t,n){const a=t.allWrites.findIndex(m=>m.writeId===n);la(a>=0,"removeWrite called with nonexistent writeId.");const s=t.allWrites[a];t.allWrites.splice(a,1);let i=s.visible,c=!1,l=t.allWrites.length-1;for(;i&&l>=0;){const m=t.allWrites[l];m.visible&&(l>=a&&z3(m,s.path)?i=!1:$c(s.path,m.path)&&(c=!0)),l--}if(i){if(c)return q3(t),!0;if(s.snap)t.visibleWrites=BC(t.visibleWrites,s.path);else{const m=s.children;eo(m,d=>{t.visibleWrites=BC(t.visibleWrites,si(s.path,d))})}return!0}else return!1}function z3(t,n){if(t.snap)return $c(t.path,n);for(const a in t.children)if(t.children.hasOwnProperty(a)&&$c(si(t.path,a),n))return!0;return!1}function q3(t){t.visibleWrites=Wk(t.allWrites,V3,Qs()),t.allWrites.length>0?t.lastWriteId=t.allWrites[t.allWrites.length-1].writeId:t.lastWriteId=-1}function V3(t){return t.visible}function Wk(t,n,a){let s=hl.empty();for(let i=0;i<t.length;++i){const c=t[i];if(n(c)){const l=c.path;let m;if(c.snap)$c(a,l)?(m=So(a,l),s=Gf(s,m,c.snap)):$c(l,a)&&(m=So(l,a),s=Gf(s,Qs(),c.snap.getChild(m)));else if(c.children){if($c(a,l))m=So(a,l),s=c1(s,m,c.children);else if($c(l,a))if(m=So(l,a),js(m))s=c1(s,Qs(),c.children);else{const d=Lh(c.children,xs(m));if(d){const u=d.getChild(Pr(m));s=Gf(s,Qs(),u)}}}else throw Cp("WriteRecord should have .snap or .children")}}return s}function Gk(t,n,a,s,i){if(!s&&!i){const c=Xh(t.visibleWrites,n);if(c!=null)return c;{const l=Pu(t.visibleWrites,n);if(d1(l))return a;
2587if(a==null&&!l1(l,Qs()))return null;{const m=a||ts.EMPTY_NODE;return yp(l,m)}}}else{const c=Pu(t.visibleWrites,n);if(!i&&d1(c))return a;if(!i&&a==null&&!l1(c,Qs()))return null;{const l=function(u){return(u.visible||i)&&(!s||!~s.indexOf(u.writeId))&&($c(u.path,n)||$c(n,u.path))},m=Wk(t.allWrites,l,n),d=a||ts.EMPTY_NODE;return yp(m,d)}}}function H3(t,n,a){let s=ts.EMPTY_NODE;const i=Xh(t.visibleWrites,n);if(i)return i.isLeafNode()||i.forEachChild(Hr,(c,l)=>{s=s.updateImmediateChild(c,l)}),s;if(a){const c=Pu(t.visibleWrites,n);return a.forEachChild(Hr,(l,m)=>{const d=yp(Pu(c,new mr(l)),m);s=s.updateImmediateChild(l,d)}),FC(c).forEach(l=>{s=s.updateImmediateChild(l.name,l.node)}),s}else{const c=Pu(t.visibleWrites,n);return FC(c).forEach(l=>{s=s.updateImmediateChild(l.name,l.node)}),s}}function W3(t,n,a,s,i){la(s||i,"Either existingEventSnap or existingServerSnap must exist");const c=si(n,a);if(l1(t.visibleWrites,c))return null;{const l=Pu(t.visibleWrites,c);return d1(l)?i.getChild(a):yp(l,i.getChild(a))}}function G3(t,n,a,s){const i=si(n,a),c=Xh(t.visibleWrites,i);if(c!=null)return c;if(s.isCompleteForChild(a)){const l=Pu(t.visibleWrites,i);return yp(l,s.getNode().getImmediateChild(a))}else return null}function Y3(t,n){return Xh(t.visibleWrites,n)}function Q3(t,n,a,s,i,c,l){let m;const d=Pu(t.visibleWrites,n),u=Xh(d,Qs());if(u!=null)m=u;else if(a!=null)m=yp(d,a);else return[];if(m=m.withIndex(l),!m.isEmpty()&&!m.isLeafNode()){const f=[],g=l.getCompare(),p=c?m.getReverseIteratorFrom(s,l):m.getIteratorFrom(s,l);let y=p.getNext();for(;y&&f.length<i;)g(y,s)!==0&&f.push(y),y=p.getNext();return f}else return[]}function J3(){return{visibleWrites:hl.empty(),allWrites:[],lastWriteId:-1}}function Sb(t,n,a,s){return Gk(t.writeTree,t.treePath,n,a,s)}function Iw(t,n){return H3(t.writeTree,t.treePath,n)}function UC(t,n,a,s){return W3(t.writeTree,t.treePath,n,a,s)}function Cb(t,n){return Y3(t.writeTree,si(t.treePath,n))}function K3(t,n,a,s,i,c){return Q3(t.writeTree,t.treePath,n,a,s,i,c)}function _w(t,n,a){return G3(t.writeTree,t.treePath,n,a)}function Yk(t,n){return Qk(si(t.treePath,n),t.writeTree)}function Qk(t,n){return{treePath:t,writeTree:n}}/** 2588 * @license 2589 * Copyright 2017 Google LLC 2590 * 2591 * Licensed under the Apache License, Version 2.0 (the "License"); 2592 * you may not use this file except in compliance with the License. 2593 * You may obtain a copy of the License at 2594 * 2595 * http://www.apache.org/licenses/LICENSE-2.0 2596 * 2597 * Unless required by applicable law or agreed to in writing, software 2598 * distributed under the License is distributed on an "AS IS" BASIS, 2599 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2600 * See the License for the specific language governing permissions and 2601 * limitations under the License. 2602 */class X3{constructor(){this.changeMap=new Map}trackChildChange(n){const a=n.type,s=n.childName;la(a==="child_added"||a==="child_changed"||a==="child_removed","Only child changes supported for tracking"),la(s!==".priority","Only non-priority child changes can be tracked.");const i=this.changeMap.get(s);if(i){const c=i.type;if(a==="child_added"&&c==="child_removed")this.changeMap.set(s,lg(s,n.snapshotNode,i.snapshotNode));else if(a==="child_removed"&&c==="child_added")this.changeMap.delete(s);else if(a==="child_removed"&&c==="child_changed")this.changeMap.set(s,cg(s,i.oldSnap));else if(a==="child_changed"&&c==="child_added")this.changeMap.set(s,fp(s,n.snapshotNode));else if(a==="child_changed"&&c==="child_changed")this.changeMap.set(s,lg(s,n.snapshotNode,i.oldSnap));else throw Cp("Illegal combination of changes: "+n+" occurred after "+i)}else this.changeMap.set(s,n)}getChanges(){return Array.from(this.changeMap.values())}}/** 2603 * @license 2604 * Copyright 2017 Google LLC 2605 * 2606 * Licensed under the Apache License, Version 2.0 (the "License"); 2607 * you may not use this file except in compliance with the License. 2608 * You may obtain a copy of the License at 2609 * 2610 * http://www.apache.org/licenses/LICENSE-2.0 2611 * 2612 * Unless required by applicable law or agreed to in writing, software 2613 * distributed under the License is distributed on an "AS IS" BASIS, 2614 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2615 * See the License for the specific language governing permissions and 2616 * limitations under the License. 2617 */class Z3{getCompleteChild(n){return null}getChildAfterChild(n,a,s){return null}}const Jk=new Z3;class kw{constructor(n,a,s=null){this.writes_=n,this.viewCache_=a,this.optCompleteServerCache_=s}getCompleteChild(n){const a=this.viewCache_.eventCache;if(a.isCompleteForChild(n))return a.getNode().getImmediateChild(n);{const s=this.optCompleteServerCache_!=null?new Lu(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return _w(this.writes_,n,s)}}getChildAfterChild(n,a,s){const i=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:Wh(this.viewCache_),c=K3(this.writes_,i,a,1,s,n);return c.length===0?null:c[0]}}/** 2618 * @license 2619 * Copyright 2017 Google LLC 2620 * 2621 * Licensed under the Apache License, Version 2.0 (the "License");
2622 * you may not use this file except in compliance with the License. 2623 * You may obtain a copy of the License at 2624 * 2625 * http://www.apache.org/licenses/LICENSE-2.0 2626 * 2627 * Unless required by applicable law or agreed to in writing, software 2628 * distributed under the License is distributed on an "AS IS" BASIS, 2629 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2630 * See the License for the specific language governing permissions and 2631 * limitations under the License. 2632 */function eL(t){return{filter:t}}function tL(t,n){la(n.eventCache.getNode().isIndexed(t.filter.getIndex()),"Event snap not indexed"),la(n.serverCache.getNode().isIndexed(t.filter.getIndex()),"Server snap not indexed")}function nL(t,n,a,s,i){const c=new X3;let l,m;if(a.type===ul.OVERWRITE){const u=a;u.source.fromUser?l=u1(t,n,u.path,u.snap,s,i,c):(la(u.source.fromServer,"Unknown source."),m=u.source.tagged||n.serverCache.isFiltered()&&!js(u.path),l=Ab(t,n,u.path,u.snap,s,i,m,c))}else if(a.type===ul.MERGE){const u=a;u.source.fromUser?l=sL(t,n,u.path,u.children,s,i,c):(la(u.source.fromServer,"Unknown source."),m=u.source.tagged||n.serverCache.isFiltered(),l=h1(t,n,u.path,u.children,s,i,m,c))}else if(a.type===ul.ACK_USER_WRITE){const u=a;u.revert?l=oL(t,n,u.path,s,i,c):l=rL(t,n,u.path,u.affectedTree,s,i,c)}else if(a.type===ul.LISTEN_COMPLETE)l=iL(t,n,a.path,s,c);else throw Cp("Unknown operation type: "+a.type);const d=c.getChanges();return aL(n,l,d),{viewCache:l,changes:d}}function aL(t,n,a){const s=n.eventCache;if(s.isFullyInitialized()){const i=s.getNode().isLeafNode()||s.getNode().isEmpty(),c=Nb(t);(a.length>0||!t.eventCache.isFullyInitialized()||i&&!s.getNode().equals(c)||!s.getNode().getPriority().equals(c.getPriority()))&&a.push(zk(Nb(n)))}}function Kk(t,n,a,s,i,c){const l=n.eventCache;if(Cb(s,a)!=null)return n;{let m,d;if(js(a))if(la(n.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),n.serverCache.isFiltered()){const u=Wh(n),f=u instanceof ts?u:ts.EMPTY_NODE,g=Iw(s,f);m=t.filter.updateFullNode(n.eventCache.getNode(),g,c)}else{const u=Sb(s,Wh(n));m=t.filter.updateFullNode(n.eventCache.getNode(),u,c)}else{const u=xs(a);if(u===".priority"){la(Ou(a)===1,"Can't have a priority with additional path components");const f=l.getNode();d=n.serverCache.getNode();const g=UC(s,a,f,d);g!=null?m=t.filter.updatePriority(f,g):m=l.getNode()}else{const f=Pr(a);let g;if(l.isCompleteForChild(u)){d=n.serverCache.getNode();const p=UC(s,a,l.getNode(),d);p!=null?g=l.getNode().getImmediateChild(u).updateChild(f,p):g=l.getNode().getImmediateChild(u)}else g=_w(s,u,n.serverCache);g!=null?m=t.filter.updateChild(l.getNode(),u,g,f,i,c):m=l.getNode()}}return Wf(n,m,l.isFullyInitialized()||js(a),t.filter.filtersNodes())}}function Ab(t,n,a,s,i,c,l,m){const d=n.serverCache;let u;const f=l?t.filter:t.filter.getIndexedFilter();if(js(a))u=f.updateFullNode(d.getNode(),s,null);else if(f.filtersNodes()&&!d.isFiltered()){const y=d.getNode().updateChild(a,s);u=f.updateFullNode(d.getNode(),y,null)}else{const y=xs(a);if(!d.isCompleteForPath(a)&&Ou(a)>1)return n;const b=Pr(a),w=d.getNode().getImmediateChild(y).updateChild(b,s);y===".priority"?u=f.updatePriority(d.getNode(),w):u=f.updateChild(d.getNode(),y,w,b,Jk,null)}const g=Vk(n,u,d.isFullyInitialized()||js(a),f.filtersNodes()),p=new kw(i,g,c);return Kk(t,g,a,i,p,m)}function u1(t,n,a,s,i,c,l){const m=n.eventCache;let d,u;const f=new kw(i,n,c);if(js(a))u=t.filter.updateFullNode(n.eventCache.getNode(),s,l),d=Wf(n,u,!0,t.filter.filtersNodes());else{const g=xs(a);if(g===".priority")u=t.filter.updatePriority(n.eventCache.getNode(),s),d=Wf(n,u,m.isFullyInitialized(),m.isFiltered());else{const p=Pr(a),y=m.getNode().getImmediateChild(g);let b;if(js(p))b=s;else{const N=f.getCompleteChild(g);N!=null?yw(p)===".priority"&&N.getChild(Tk(p)).isEmpty()?b=N:b=N.updateChild(p,s):b=ts.EMPTY_NODE}if(y.equals(b))d=n;else{const N=t.filter.updateChild(m.getNode(),g,b,p,f,l);d=Wf(n,N,m.isFullyInitialized(),t.filter.filtersNodes())}}}return d}function zC(t,n){return t.eventCache.isCompleteForChild(n)}function sL(t,n,a,s,i,c,l){let m=n;return s.foreach((d,u)=>{const f=si(a,d);zC(n,xs(f))&&(m=u1(t,m,f,u,i,c,l))}),s.foreach((d,u)=>{const f=si(a,d);zC(n,xs(f))||(m=u1(t,m,f,u,i,c,l))}),m}function qC(t,n,a){return a.foreach((s,i)=>{n=n.updateChild(s,i)}),n}function h1(t,n,a,s,i,c,l,m){if(n.serverCache.getNode().isEmpty()&&!n.serverCache.isFullyInitialized())return n;let d=n,u;js(a)?u=s:u=new Er(null).setTree(a,s);const f=n.serverCache.getNode();return u.children.inorderTraversal((g,p)=>
vendor: 4,309 bytes, lines 2632-2647
2632{if(f.hasChild(g)){const y=n.serverCache.getNode().getImmediateChild(g),b=qC(t,y,p);d=Ab(t,d,new mr(g),b,i,c,l,m)}}),u.children.inorderTraversal((g,p)=>{const y=!n.serverCache.isCompleteForChild(g)&&p.value===null;if(!f.hasChild(g)&&!y){const b=n.serverCache.getNode().getImmediateChild(g),N=qC(t,b,p);d=Ab(t,d,new mr(g),N,i,c,l,m)}}),d}function rL(t,n,a,s,i,c,l){if(Cb(i,a)!=null)return n;const m=n.serverCache.isFiltered(),d=n.serverCache;if(s.value!=null){if(js(a)&&d.isFullyInitialized()||d.isCompleteForPath(a))return Ab(t,n,a,d.getNode().getChild(a),i,c,m,l);if(js(a)){let u=new Er(null);return d.getNode().forEachChild(kh,(f,g)=>{u=u.set(new mr(f),g)}),h1(t,n,a,u,i,c,m,l)}else return n}else{let u=new Er(null);return s.foreach((f,g)=>{const p=si(a,f);d.isCompleteForPath(p)&&(u=u.set(f,d.getNode().getChild(p)))}),h1(t,n,a,u,i,c,m,l)}}function iL(t,n,a,s,i){const c=n.serverCache,l=Vk(n,c.getNode(),c.isFullyInitialized()||js(a),c.isFiltered());return Kk(t,l,a,s,Jk,i)}function oL(t,n,a,s,i,c){let l;if(Cb(s,a)!=null)return n;{const m=new kw(s,n,i),d=n.eventCache.getNode();let u;if(js(a)||xs(a)===".priority"){let f;if(n.serverCache.isFullyInitialized())f=Sb(s,Wh(n));else{const g=n.serverCache.getNode();la(g instanceof ts,"serverChildren would be complete if leaf node"),f=Iw(s,g)}f=f,u=t.filter.updateFullNode(d,f,c)}else{const f=xs(a);let g=_w(s,f,n.serverCache);g==null&&n.serverCache.isCompleteForChild(f)&&(g=d.getImmediateChild(f)),g!=null?u=t.filter.updateChild(d,f,g,Pr(a),m,c):n.eventCache.getNode().hasChild(f)?u=t.filter.updateChild(d,f,ts.EMPTY_NODE,Pr(a),m,c):u=d,u.isEmpty()&&n.serverCache.isFullyInitialized()&&(l=Sb(s,Wh(n)),l.isLeafNode()&&(u=t.filter.updateFullNode(u,l,c)))}return l=n.serverCache.isFullyInitialized()||Cb(s,Qs())!=null,Wf(n,u,l,t.filter.filtersNodes())}}/** 2633 * @license 2634 * Copyright 2017 Google LLC 2635 * 2636 * Licensed under the Apache License, Version 2.0 (the "License"); 2637 * you may not use this file except in compliance with the License. 2638 * You may obtain a copy of the License at 2639 * 2640 * http://www.apache.org/licenses/LICENSE-2.0 2641 * 2642 * Unless required by applicable law or agreed to in writing, software 2643 * distributed under the License is distributed on an "AS IS" BASIS, 2644 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2645 * See the License for the specific language governing permissions and 2646 * limitations under the License. 2647 */class cL{constructor(n,a){this.query_=n,this.eventRegistrations_=[];const s=this.query_._queryParams,i=new ww(s.getIndex()),c=w3(s);this.processor_=eL(c);const l=a.serverCache,m=a.eventCache,d=i.updateFullNode(ts.EMPTY_NODE,l.getNode(),null),u=c.updateFullNode(ts.EMPTY_NODE,m.getNode(),null),f=new Lu(d,l.isFullyInitialized(),i.filtersNodes()),g=new Lu(u,m.isFullyInitialized(),c.filtersNodes());this.viewCache_=Qb(g,f),this.eventGenerator_=new R3(this.query_)}get query(){return this.query_}}function lL(t){return t.viewCache_.serverCache.getNode()}function dL(t){return Nb(t.viewCache_)}function uL(t,n){const a=Wh(t.viewCache_);return a&&(t.query._queryParams.loadsAllData()||!js(n)&&!a.getImmediateChild(xs(n)).isEmpty())?a.getChild(n):null}function VC(t){return t.eventRegistrations_.length===0}function hL(t,n){t.eventRegistrations_.push(n)}function HC(t,n,a){const s=[];if(a){la(n==null,"A cancel should cancel all event registrations.");const i=t.query._path;t.eventRegistrations_.forEach(c=>{const l=c.createCancelEvent(a,i);l&&s.push(l)})}if(n){let i=[];for(let c=0;c<t.eventRegistrations_.length;++c){const l=t.eventRegistrations_[c];if(!l.matches(n))i.push(l);else if(n.hasAnyCallback()){i=i.concat(t.eventRegistrations_.slice(c+1));break}}t.eventRegistrations_=i}else t.eventRegistrations_=[];return s}function WC(t,n,a,s){n.type===ul.MERGE&&n.source.queryId!==null&&(la(Wh(t.viewCache_),"We should always have a full cache before handling merges"),la(Nb(t.viewCache_),"Missing event cache, even though we have a server cache"));const i=t.viewCache_,c=nL(t.processor_,i,n,a,s);return tL(t.processor_,c.viewCache),la(c.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),t.viewCache_=c.viewCache,Xk(t,c.changes,c.viewCache.eventCache.getNode(),null)}function mL(t,n){const a=t.viewCache_.eventCache,s=[];
2647return a.getNode().isLeafNode()||a.getNode().forEachChild(Hr,(c,l)=>{s.push(fp(c,l))}),a.isFullyInitialized()&&s.push(zk(a.getNode())),Xk(t,s,a.getNode(),n)}function Xk(t,n,a,s){const i=s?[s]:t.eventRegistrations_;return T3(t.eventGenerator_,n,a,i)}/** 2648 * @license 2649 * Copyright 2017 Google LLC 2650 * 2651 * Licensed under the Apache License, Version 2.0 (the "License"); 2652 * you may not use this file except in compliance with the License. 2653 * You may obtain a copy of the License at 2654 * 2655 * http://www.apache.org/licenses/LICENSE-2.0 2656 * 2657 * Unless required by applicable law or agreed to in writing, software 2658 * distributed under the License is distributed on an "AS IS" BASIS, 2659 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2660 * See the License for the specific language governing permissions and 2661 * limitations under the License. 2662 */let Ib;class Zk{constructor(){this.views=new Map}}function pL(t){la(!Ib,"__referenceConstructor has already been defined"),Ib=t}function fL(){return la(Ib,"Reference.ts has not been loaded"),Ib}function gL(t){return t.views.size===0}function Dw(t,n,a,s){const i=n.source.queryId;if(i!==null){const c=t.views.get(i);return la(c!=null,"SyncTree gave us an op for an invalid query."),WC(c,n,a,s)}else{let c=[];for(const l of t.views.values())c=c.concat(WC(l,n,a,s));return c}}function eD(t,n,a,s,i){const c=n._queryIdentifier,l=t.views.get(c);if(!l){let m=Sb(a,i?s:null),d=!1;m?d=!0:s instanceof ts?(m=Iw(a,s),d=!1):(m=ts.EMPTY_NODE,d=!1);const u=Qb(new Lu(m,d,!1),new Lu(s,i,!1));return new cL(n,u)}return l}function yL(t,n,a,s,i,c){const l=eD(t,n,s,i,c);return t.views.has(n._queryIdentifier)||t.views.set(n._queryIdentifier,l),hL(l,a),mL(l,a)}function vL(t,n,a,s){const i=n._queryIdentifier,c=[];let l=[];const m=Bu(t);if(i==="default")for(const[d,u]of t.views.entries())l=l.concat(HC(u,a,s)),VC(u)&&(t.views.delete(d),u.query._queryParams.loadsAllData()||c.push(u.query));else{const d=t.views.get(i);d&&(l=l.concat(HC(d,a,s)),VC(d)&&(t.views.delete(i),d.query._queryParams.loadsAllData()||c.push(d.query)))}return m&&!Bu(t)&&c.push(new(fL())(n._repo,n._path)),{removed:c,events:l}}function tD(t){const n=[];for(const a of t.views.values())a.query._queryParams.loadsAllData()||n.push(a);return n}function Ru(t,n){let a=null;for(const s of t.views.values())a=a||uL(s,n);return a}function nD(t,n){if(n._queryParams.loadsAllData())return Kb(t);{const s=n._queryIdentifier;return t.views.get(s)}}function aD(t,n){return nD(t,n)!=null}function Bu(t){return Kb(t)!=null}function Kb(t){for(const n of t.views.values())if(n.query._queryParams.loadsAllData())return n;return null}/** 2663 * @license 2664 * Copyright 2017 Google LLC 2665 * 2666 * Licensed under the Apache License, Version 2.0 (the "License"); 2667 * you may not use this file except in compliance with the License. 2668 * You may obtain a copy of the License at 2669 * 2670 * http://www.apache.org/licenses/LICENSE-2.0 2671 * 2672 * Unless required by applicable law or agreed to in writing, software 2673 * distributed under the License is distributed on an "AS IS" BASIS, 2674 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2675 * See the License for the specific language governing permissions and 2676 * limitations under the License. 2677 */let _b;function bL(t){la(!_b,"__referenceConstructor has already been defined"),_b=t}function xL(){return la(_b,"Reference.ts has not been loaded"),_b}let jL=1;class GC{constructor(n){this.listenProvider_=n,this.syncPointTree_=new Er(null),this.pendingWriteTree_=J3(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ew(t,n,a,s,i){return L3(t.pendingWriteTree_,n,a,s,i),i?kp(t,new Hh(Sw(),n,a)):[]}function wL(t,n,a,s){B3(t.pendingWriteTree_,n,a,s);const i=Er.fromObject(a);return kp(t,new gp(Sw(),n,i))}function Au(t,n,a=!1){const s=F3(t.pendingWriteTree_,n);if(U3(t.pendingWriteTree_,n)){let c=new Er(null);return s.snap!=null?c=c.set(Qs(),!0):eo(s.children,l=>{c=c.set(new mr(l),!0)}),kp(t,new wb(s.path,c,a))}else return[]}function Rg(t,n,a){return kp(t,new Hh(Cw(),n,a))}function NL(t,n,a){const s=Er.fromObject(a);return kp(t,new gp(Cw(),n,s))}function SL(t,n){return kp(t,new ug(Cw(),n))}function CL(t,n,a){const s=Pw(t,a);if(s){const i=Rw(s),c=i.path,l=i.queryId,m=So(c,n),d=new ug(Aw(l),m);return Tw(t,c,d)}else return[]}function kb(t,n,a,s,i=!1){const c=n._path,l=t.syncPointTree_.get(c);let m=[];
2677if(l&&(n._queryIdentifier==="default"||aD(l,n))){const d=vL(l,n,a,s);gL(l)&&(t.syncPointTree_=t.syncPointTree_.remove(c));const u=d.removed;if(m=d.events,!i){const f=u.findIndex(p=>p._queryParams.loadsAllData())!==-1,g=t.syncPointTree_.findOnPath(c,(p,y)=>Bu(y));if(f&&!g){const p=t.syncPointTree_.subtree(c);if(!p.isEmpty()){const y=_L(p);for(let b=0;b<y.length;++b){const N=y[b],w=N.query,C=oD(t,N);t.listenProvider_.startListening(Yf(w),hg(t,w),C.hashFn,C.onComplete)}}}!g&&u.length>0&&!s&&(f?t.listenProvider_.stopListening(Yf(n),null):u.forEach(p=>{const y=t.queryToTagMap.get(Zb(p));t.listenProvider_.stopListening(Yf(p),y)}))}kL(t,u)}return m}function sD(t,n,a,s){const i=Pw(t,s);if(i!=null){const c=Rw(i),l=c.path,m=c.queryId,d=So(l,n),u=new Hh(Aw(m),d,a);return Tw(t,l,u)}else return[]}function AL(t,n,a,s){const i=Pw(t,s);if(i){const c=Rw(i),l=c.path,m=c.queryId,d=So(l,n),u=Er.fromObject(a),f=new gp(Aw(m),d,u);return Tw(t,l,f)}else return[]}function m1(t,n,a,s=!1){const i=n._path;let c=null,l=!1;t.syncPointTree_.foreachOnPath(i,(p,y)=>{const b=So(p,i);c=c||Ru(y,b),l=l||Bu(y)});let m=t.syncPointTree_.get(i);m?(l=l||Bu(m),c=c||Ru(m,Qs())):(m=new Zk,t.syncPointTree_=t.syncPointTree_.set(i,m));let d;c!=null?d=!0:(d=!1,c=ts.EMPTY_NODE,t.syncPointTree_.subtree(i).foreachChild((y,b)=>{const N=Ru(b,Qs());N&&(c=c.updateImmediateChild(y,N))}));const u=aD(m,n);if(!u&&!n._queryParams.loadsAllData()){const p=Zb(n);la(!t.queryToTagMap.has(p),"View does not exist, but we have a tag");const y=DL();t.queryToTagMap.set(p,y),t.tagToQueryMap.set(y,p)}const f=Jb(t.pendingWriteTree_,i);let g=yL(m,n,a,f,c,d);if(!u&&!l&&!s){const p=nD(m,n);g=g.concat(EL(t,n,p))}return g}function Xb(t,n,a){const i=t.pendingWriteTree_,c=t.syncPointTree_.findOnPath(n,(l,m)=>{const d=So(l,n),u=Ru(m,d);if(u)return u});return Gk(i,n,c,a,!0)}function IL(t,n){const a=n._path;let s=null;t.syncPointTree_.foreachOnPath(a,(u,f)=>{const g=So(u,a);s=s||Ru(f,g)});let i=t.syncPointTree_.get(a);i?s=s||Ru(i,Qs()):(i=new Zk,t.syncPointTree_=t.syncPointTree_.set(a,i));const c=s!=null,l=c?new Lu(s,!0,!1):null,m=Jb(t.pendingWriteTree_,n._path),d=eD(i,n,m,c?l.getNode():ts.EMPTY_NODE,c);return dL(d)}
vendor: 1,448 bytes, line 2677
2677function kp(t,n){return rD(n,t.syncPointTree_,null,Jb(t.pendingWriteTree_,Qs()))}function rD(t,n,a,s){if(js(t.path))return iD(t,n,a,s);{const i=n.get(Qs());a==null&&i!=null&&(a=Ru(i,Qs()));let c=[];const l=xs(t.path),m=t.operationForChild(l),d=n.children.get(l);if(d&&m){const u=a?a.getImmediateChild(l):null,f=Yk(s,l);c=c.concat(rD(m,d,u,f))}return i&&(c=c.concat(Dw(i,t,s,a))),c}}function iD(t,n,a,s){const i=n.get(Qs());a==null&&i!=null&&(a=Ru(i,Qs()));let c=[];return n.children.inorderTraversal((l,m)=>{const d=a?a.getImmediateChild(l):null,u=Yk(s,l),f=t.operationForChild(l);f&&(c=c.concat(iD(f,m,d,u)))}),i&&(c=c.concat(Dw(i,t,s,a))),c}function oD(t,n){const a=n.query,s=hg(t,a);return{hashFn:()=>(lL(n)||ts.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return s?CL(t,a._path,s):SL(t,a._path);{const c=wO(i,a);return kb(t,a,null,c)}}}}function hg(t,n){const a=Zb(n);return t.queryToTagMap.get(a)}function Zb(t){return t._path.toString()+"$"+t._queryIdentifier}function Pw(t,n){return t.tagToQueryMap.get(n)}function Rw(t){const n=t.indexOf("$");return la(n!==-1&&n<t.length-1,"Bad queryKey."),{queryId:t.substr(n+1),path:new mr(t.substr(0,n))}}function Tw(t,n,a){const s=t.syncPointTree_.get(n);la(s,"Missing sync point for query tag that we're tracking");const i=Jb(t.pendingWriteTree_,n);return Dw(s,a,i,null)}function _L(t){return t.fold((n,a,s)=>{if(a&&Bu(a))return[Kb(a)];{let i=[];return a&&(i=tD(a)),eo(s,(c,l)=>{i=i.concat(l)}),i}})}
2677function Yf(t){return t._queryParams.loadsAllData()&&!t._queryParams.isDefault()?new(xL())(t._repo,t._path):t}function kL(t,n){for(let a=0;a<n.length;++a){const s=n[a];if(!s._queryParams.loadsAllData()){const i=Zb(s),c=t.queryToTagMap.get(i);t.queryToTagMap.delete(i),t.tagToQueryMap.delete(c)}}}function DL(){return jL++}function EL(t,n,a){const s=n._path,i=hg(t,n),c=oD(t,a),l=t.listenProvider_.startListening(Yf(n),i,c.hashFn,c.onComplete),m=t.syncPointTree_.subtree(s);if(i)la(!Bu(m.value),"If we're adding a query, it shouldn't be shadowed");else{const d=m.fold((u,f,g)=>{if(!js(u)&&f&&Bu(f))return[Kb(f).query];{let p=[];return f&&(p=p.concat(tD(f).map(y=>y.query))),eo(g,(y,b)=>{p=p.concat(b)}),p}});for(let u=0;u<d.length;++u){const f=d[u];t.listenProvider_.stopListening(Yf(f),hg(t,f))}}return l}/** 2678 * @license 2679 * Copyright 2017 Google LLC 2680 * 2681 * Licensed under the Apache License, Version 2.0 (the "License"); 2682 * you may not use this file except in compliance with the License. 2683 * You may obtain a copy of the License at 2684 * 2685 * http://www.apache.org/licenses/LICENSE-2.0 2686 * 2687 * Unless required by applicable law or agreed to in writing, software 2688 * distributed under the License is distributed on an "AS IS" BASIS, 2689 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2690 * See the License for the specific language governing permissions and 2691 * limitations under the License. 2692 */class Mw{constructor(n){this.node_=n}getImmediateChild(n){const a=this.node_.getImmediateChild(n);return new Mw(a)}node(){return this.node_}}class $w{constructor(n,a){this.syncTree_=n,this.path_=a}getImmediateChild(n){const a=si(this.path_,n);return new $w(this.syncTree_,a)}node(){return Xb(this.syncTree_,this.path_)}}const PL=function(t){return t=t||{},t.timestamp=t.timestamp||new Date().getTime(),t},YC=function(t,n,a){if(!t||typeof t!="object")return t;if(la(".sv"in t,"Unexpected leaf node or priority contents"),typeof t[".sv"]=="string")return RL(t[".sv"],n,a);if(typeof t[".sv"]=="object")return TL(t[".sv"],n);la(!1,"Unexpected server value: "+JSON.stringify(t,null,2))},RL=function(t,n,a){switch(t){case"timestamp":return a.timestamp;default:la(!1,"Unexpected server value: "+t)}},TL=function(t,n,a){t.hasOwnProperty("increment")||la(!1,"Unexpected server value: "+JSON.stringify(t,null,2));const s=t.increment;typeof s!="number"&&la(!1,"Unexpected increment value: "+s);const i=n.node();if(la(i!==null&&typeof i<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return s;const l=i.getValue();return typeof l!="number"?s:l+s},cD=function(t,n,a,s){return Lw(n,new $w(a,t),s)},Ow=function(t,n,a){return Lw(t,new Mw(n),a)};function Lw(t,n,a){const s=t.getPriority().val(),i=YC(s,n.getImmediateChild(".priority"),a);let c;if(t.isLeafNode()){const l=t,m=YC(l.getValue(),n,a);return m!==l.getValue()||i!==l.getPriority().val()?new qi(m,ji(i)):t}else{const l=t;return c=l,i!==l.getPriority().val()&&(c=c.updatePriority(new qi(i))),l.forEachChild(Hr,(m,d)=>{const u=Lw(d,n.getImmediateChild(m),a);u!==d&&(c=c.updateImmediateChild(m,u))}),c}}/** 2693 * @license 2694 * Copyright 2017 Google LLC 2695 * 2696 * Licensed under the Apache License, Version 2.0 (the "License"); 2697 * you may not use this file except in compliance with the License. 2698 * You may obtain a copy of the License at 2699 * 2700 * http://www.apache.org/licenses/LICENSE-2.0 2701 * 2702 * Unless required by applicable law or agreed to in writing, software 2703 * distributed under the License is distributed on an "AS IS" BASIS, 2704 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2705 * See the License for the specific language governing permissions and 2706 * limitations under the License. 2707 */class Bw{constructor(n="",a=null,s={children:{},childCount:0}){this.name=n,this.parent=a,this.node=s}}function ex(t,n){let a=n instanceof mr?n:new mr(n),s=t,i=xs(a);for(;i!==null;){const c=Lh(s.node.children,i)||{children:{},childCount:0};s=new Bw(i,s,c),a=Pr(a),i=xs(a)}return s}function Zh(t){return t.node.value}function Fw(t,n){t.node.value=n,p1(t)}function lD(t){return t.node.childCount>0}function ML(t){return Zh(t)===void 0&&!lD(t)}function tx(t,n){eo(t.node.children,(a,s)=>{n(new Bw(a,t,s))})}function dD(t,n,a,s){a&&n(t),tx(t,i=>{dD(i,n,!0)})}function $L(t,n,a){let s=t.parent;for(;s!==null;){if(n(s))return!0;s=s.parent}return!1}function Tg(t){return new mr(t.parent===null?t.name:Tg(t.parent)+"/"+t.name)}function p1(t){t.parent!==null&&OL(t.parent,t.name,t)}function OL(t,n,a){const s=ML(a),i=pl(t.node.children,n);s&&i?(delete t.node.children[n],t.node.childCount--,p1(t)):!s&&!i&&(t.node.children[n]=a.node,t.node.childCount++,p1(t))}/** 2708 * @license 2709 * Copyright 2017 Google LLC 2710 * 2711 * Licensed under the Apache License, Version 2.0 (the "License");
vendor: 4,885 bytes, lines 2712-2741
2712 * you may not use this file except in compliance with the License. 2713 * You may obtain a copy of the License at 2714 * 2715 * http://www.apache.org/licenses/LICENSE-2.0 2716 * 2717 * Unless required by applicable law or agreed to in writing, software 2718 * distributed under the License is distributed on an "AS IS" BASIS, 2719 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2720 * See the License for the specific language governing permissions and 2721 * limitations under the License. 2722 */const LL=/[\[\].#$\/\u0000-\u001F\u007F]/,BL=/[\[\].#$\u0000-\u001F\u007F]/,W0=10*1024*1024,Uw=function(t){return typeof t=="string"&&t.length!==0&&!LL.test(t)},uD=function(t){return typeof t=="string"&&t.length!==0&&!BL.test(t)},FL=function(t){return t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),uD(t)},Db=function(t){return t===null||typeof t=="string"||typeof t=="number"&&!hw(t)||t&&typeof t=="object"&&pl(t,".sv")},Mg=function(t,n,a,s){s&&n===void 0||$g(qb(t,"value"),n,a)},$g=function(t,n,a){const s=a instanceof mr?new n3(a,t):a;if(n===void 0)throw new Error(t+"contains undefined "+xh(s));if(typeof n=="function")throw new Error(t+"contains a function "+xh(s)+" with contents = "+n.toString());if(hw(n))throw new Error(t+"contains "+n.toString()+" "+xh(s));if(typeof n=="string"&&n.length>W0/3&&Vb(n)>W0)throw new Error(t+"contains a string greater than "+W0+" utf8 bytes "+xh(s)+" ('"+n.substring(0,50)+"...')");if(n&&typeof n=="object"){let i=!1,c=!1;if(eo(n,(l,m)=>{if(l===".value")i=!0;else if(l!==".priority"&&l!==".sv"&&(c=!0,!Uw(l)))throw new Error(t+" contains an invalid key ("+l+") "+xh(s)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);a3(s,l),$g(t,m,s),s3(s)}),i&&c)throw new Error(t+' contains ".value" child '+xh(s)+" in addition to actual children.")}},UL=function(t,n){let a,s;for(a=0;a<n.length;a++){s=n[a];const c=og(s);for(let l=0;l<c.length;l++)if(!(c[l]===".priority"&&l===c.length-1)){if(!Uw(c[l]))throw new Error(t+"contains an invalid key ("+c[l]+") in path "+s.toString()+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)}}n.sort(t3);let i=null;for(a=0;a<n.length;a++){if(s=n[a],i!==null&&$c(i,s))throw new Error(t+"contains a path "+i.toString()+" that is ancestor of another path "+s.toString());i=s}},zL=function(t,n,a,s){const i=qb(t,"values");if(!(n&&typeof n=="object")||Array.isArray(n))throw new Error(i+" must be an object containing the children to replace.");const c=[];eo(n,(l,m)=>{const d=new mr(l);if($g(i,m,si(a,d)),yw(d)===".priority"&&!Db(m))throw new Error(i+"contains an invalid value for '"+d.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");c.push(d)}),UL(i,c)},zw=function(t,n,a,s){if(!uD(a))throw new Error(qb(t,n)+'was an invalid path = "'+a+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},qL=function(t,n,a,s){a&&(a=a.replace(/^\/*\.info(\/|$)/,"/")),zw(t,n,a)},nx=function(t,n){if(xs(n)===".info")throw new Error(t+" failed = Can't modify data under /.info/")},VL=function(t,n){const a=n.path.toString();if(typeof n.repoInfo.host!="string"||n.repoInfo.host.length===0||!Uw(n.repoInfo.namespace)&&n.repoInfo.host.split(":")[0]!=="localhost"||a.length!==0&&!FL(a))throw new Error(qb(t,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};/** 2723 * @license 2724 * Copyright 2017 Google LLC 2725 * 2726 * Licensed under the Apache License, Version 2.0 (the "License"); 2727 * you may not use this file except in compliance with the License. 2728 * You may obtain a copy of the License at 2729 * 2730 * http://www.apache.org/licenses/LICENSE-2.0 2731 * 2732 * Unless required by applicable law or agreed to in writing, software 2733 * distributed under the License is distributed on an "AS IS" BASIS, 2734 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2735 * See the License for the specific language governing permissions and 2736 * limitations under the License. 2737 */class HL{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function ax(t,n){let a=null;for(let s=0;s<n.length;s++){const i=n[s],c=i.getPath();a!==null&&!vw(c,a.path)&&(t.eventLists_.push(a),a=null),a===null&&(a={events:[],path:c}),a.events.push(i)}a&&t.eventLists_.push(a)}function hD(t,n,a){ax(t,a),mD(t,s=>vw(s,n))}function yc(t,n,a){ax(t,a),mD(t,s=>$c(s,n)||$c(n,s))}function mD(t,n){t.recursionDepth_++;let a=!0;for(let s=0;s<t.eventLists_.length;s++){const i=t.eventLists_[s];if(i){const c=i.path;n(c)?(WL(t.eventLists_[s]),t.eventLists_[s]=null):a=!1}}a&&(t.eventLists_=[]),t.recursionDepth_--}function WL(t){for(let n=0;n<t.events.length;n++){const a=t.events[n];if(a!==null){t.events[n]=null;const s=a.getEventRunner();Vf&&Xi("event: "+a.toString()),_p(s)}}}/** 2738 * @license 2739 * Copyright 2017 Google LLC 2740 * 2741 * Licensed under the Apache License, Version 2.0 (the "License");
2742 * you may not use this file except in compliance with the License. 2743 * You may obtain a copy of the License at 2744 * 2745 * http://www.apache.org/licenses/LICENSE-2.0 2746 * 2747 * Unless required by applicable law or agreed to in writing, software 2748 * distributed under the License is distributed on an "AS IS" BASIS, 2749 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2750 * See the License for the specific language governing permissions and 2751 * limitations under the License. 2752 */const GL="repo_interrupt",YL=25;class QL{constructor(n,a,s,i){this.repoInfo_=n,this.forceRestClient_=a,this.authTokenProvider_=s,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new HL,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=jb(),this.transactionQueueTree_=new Bw,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function JL(t,n,a){if(t.stats_=fw(t.repoInfo_),t.forceRestClient_||AO())t.server_=new xb(t.repoInfo_,(s,i,c,l)=>{QC(t,s,i,c,l)},t.authTokenProvider_,t.appCheckProvider_),setTimeout(()=>JC(t,!0),0);else{if(typeof a<"u"&&a!==null){if(typeof a!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{Ri(a)}catch(s){throw new Error("Invalid authOverride provided: "+s)}}t.persistentConnection_=new Ad(t.repoInfo_,n,(s,i,c,l)=>{QC(t,s,i,c,l)},s=>{JC(t,s)},s=>{KL(t,s)},t.authTokenProvider_,t.appCheckProvider_,a),t.server_=t.persistentConnection_}t.authTokenProvider_.addTokenChangeListener(s=>{t.server_.refreshAuthToken(s)}),t.appCheckProvider_.addTokenChangeListener(s=>{t.server_.refreshAppCheckToken(s.token)}),t.statsReporter_=EO(t.repoInfo_,()=>new P3(t.stats_,t.server_)),t.infoData_=new I3,t.infoSyncTree_=new GC({startListening:(s,i,c,l)=>{let m=[];const d=t.infoData_.getNode(s._path);return d.isEmpty()||(m=Rg(t.infoSyncTree_,s._path,d),setTimeout(()=>{l("ok")},0)),m},stopListening:()=>{}}),qw(t,"connected",!1),t.serverSyncTree_=new GC({startListening:(s,i,c,l)=>(t.server_.listen(s,c,i,(m,d)=>{const u=l(m,d);yc(t.eventQueue_,s._path,u)}),[]),stopListening:(s,i)=>{t.server_.unlisten(s,i)}})}function pD(t){const a=t.infoData_.getNode(new mr(".info/serverTimeOffset")).val()||0;return new Date().getTime()+a}function Og(t){return PL({timestamp:pD(t)})}function QC(t,n,a,s,i){t.dataUpdateCount++;const c=new mr(n);a=t.interceptServerDataCallback_?t.interceptServerDataCallback_(n,a):a;let l=[];if(i)if(s){const d=cb(a,u=>ji(u));l=AL(t.serverSyncTree_,c,d,i)}else{const d=ji(a);l=sD(t.serverSyncTree_,c,d,i)}else if(s){const d=cb(a,u=>ji(u));l=NL(t.serverSyncTree_,c,d)}else{const d=ji(a);l=Rg(t.serverSyncTree_,c,d)}let m=c;l.length>0&&(m=vp(t,c)),yc(t.eventQueue_,m,l)}function JC(t,n){qw(t,"connected",n),n===!1&&t4(t)}function KL(t,n){eo(n,(a,s)=>{qw(t,a,s)})}function qw(t,n,a){const s=new mr("/.info/"+n),i=ji(a);t.infoData_.updateSnapshot(s,i);const c=Rg(t.infoSyncTree_,s,i);yc(t.eventQueue_,s,c)}function sx(t){return t.nextWriteId_++}function XL(t,n,a){const s=IL(t.serverSyncTree_,n);return s!=null?Promise.resolve(s):t.server_.get(n).then(i=>{const c=ji(i).withIndex(n._queryParams.getIndex());m1(t.serverSyncTree_,n,a,!0);let l;if(n._queryParams.loadsAllData())l=Rg(t.serverSyncTree_,n._path,c);else{const m=hg(t.serverSyncTree_,n);l=sD(t.serverSyncTree_,n._path,c,m)}return yc(t.eventQueue_,n._path,l),kb(t.serverSyncTree_,n,a,null,!0),c},i=>(Dp(t,"get for query "+Ri(n)+" failed: "+i),Promise.reject(new Error(i))))}function ZL(t,n,a,s,i){Dp(t,"set",{path:n.toString(),value:a,priority:s});const c=Og(t),l=ji(a,s),m=Xb(t.serverSyncTree_,n),d=Ow(l,m,c),u=sx(t),f=Ew(t.serverSyncTree_,n,d,u,!0);ax(t.eventQueue_,f),t.server_.put(n.toString(),l.val(!0),(p,y)=>{const b=p==="ok";b||Co("set at "+n+" failed: "+p);const N=Au(t.serverSyncTree_,u,!b);yc(t.eventQueue_,n,N),f1(t,i,p,y)});const g=Hw(t,n);vp(t,g),yc(t.eventQueue_,g,[])}function e4(t,n,a,s){Dp(t,"update",{path:n.toString(),value:a});let i=!0;const c=Og(t),l={};if(eo(a,(m,d)=>{i=!1,l[m]=cD(si(n,m),ji(d),t.serverSyncTree_,c)}),i)Xi("update() called with empty data. Don't do anything."),f1(t,s,"ok",void 0);else{const m=sx(t),d=wL(t.serverSyncTree_,n,l,m);ax(t.eventQueue_,d),t.server_.merge(n.toString(),a,(u,f)=>{const g=u==="ok";g||Co("update at "+n+" failed: "+u);const p=Au(t.serverSyncTree_,m,!g),y=p.length>0?vp(t,n):n;yc(t.eventQueue_,y,p),f1(t,s,u,f)}),eo(a,u=>{const f=Hw(t,si(n,u));vp(t,f)}),yc(t.eventQueue_,n,[])}}function t4(t){Dp(t,"onDisconnectEvents");const n=Og(t),a=jb();o1(t.onDisconnect_,Qs(),(i,c)=>{const l=cD(i,c,t.serverSyncTree_,n);qk(a,i,l)});let s=[];o1(a,Qs(),(i,c)=>{s=s.concat(Rg(t.serverSyncTree_,i,c));const l=Hw(t,i);vp(t,l)}),t.onDisconnect_=jb(),yc(t.eventQueue_,Qs(),s)}function n4(t,n,a){let s;xs(n._path)===".info"?s=m1(t.infoSyncTree_,n,a):s=m1(t.serverSyncTree_,n,a),hD(t.eventQueue_,n._path,s)}function KC(t,n,a){let s;xs(n._path)===".info"?s=kb(t.infoSyncTree_,n,a):s=kb(t.serverSyncTree_,n,a),hD(t.eventQueue_,n._path,s)}function a4(t){t.persistentConnection_&&t.persistentConnection_.interrupt(GL)}function Dp(t,...n){let a="";t.persistentConnection_&&(a=t.persistentConnection_.id+":"),Xi(a,...n)}function f1(t,n,a,s){n&&_p(()=>
2752{if(a==="ok")n(null);else{const i=(a||"error").toUpperCase();let c=i;s&&(c+=": "+s);const l=new Error(c);l.code=i,n(l)}})}function s4(t,n,a,s,i,c){Dp(t,"transaction on "+n);const l={path:n,update:a,onComplete:s,status:null,order:hk(),applyLocally:c,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},m=Vw(t,n,void 0);l.currentInputSnapshot=m;const d=l.update(m.val());if(d===void 0)l.unwatcher(),l.currentOutputSnapshotRaw=null,l.currentOutputSnapshotResolved=null,l.onComplete&&l.onComplete(null,!1,l.currentInputSnapshot);else{$g("transaction failed: Data returned ",d,l.path),l.status=0;const u=ex(t.transactionQueueTree_,n),f=Zh(u)||[];f.push(l),Fw(u,f);let g;typeof d=="object"&&d!==null&&pl(d,".priority")?(g=Lh(d,".priority"),la(Db(g),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):g=(Xb(t.serverSyncTree_,n)||ts.EMPTY_NODE).getPriority().val();const p=Og(t),y=ji(d,g),b=Ow(y,m,p);l.currentOutputSnapshotRaw=y,l.currentOutputSnapshotResolved=b,l.currentWriteId=sx(t);const N=Ew(t.serverSyncTree_,n,b,l.currentWriteId,l.applyLocally);yc(t.eventQueue_,n,N),rx(t,t.transactionQueueTree_)}}function Vw(t,n,a){return Xb(t.serverSyncTree_,n,a)||ts.EMPTY_NODE}function rx(t,n=t.transactionQueueTree_){if(n||ix(t,n),Zh(n)){const a=gD(t,n);la(a.length>0,"Sending zero length transaction queue"),a.every(i=>i.status===0)&&r4(t,Tg(n),a)}else lD(n)&&tx(n,a=>{rx(t,a)})}function r4(t,n,a){const s=a.map(u=>u.currentWriteId),i=Vw(t,n,s);let c=i;const l=i.hash();for(let u=0;u<a.length;u++){const f=a[u];la(f.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),f.status=1,f.retryCount++;const g=So(n,f.path);c=c.updateChild(g,f.currentOutputSnapshotRaw)}const m=c.val(!0),d=n;t.server_.put(d.toString(),m,u=>{Dp(t,"transaction put response",{path:d.toString(),status:u});let f=[];if(u==="ok"){const g=[];for(let p=0;p<a.length;p++)a[p].status=2,f=f.concat(Au(t.serverSyncTree_,a[p].currentWriteId)),a[p].onComplete&&g.push(()=>a[p].onComplete(null,!0,a[p].currentOutputSnapshotResolved)),a[p].unwatcher();ix(t,ex(t.transactionQueueTree_,n)),rx(t,t.transactionQueueTree_),yc(t.eventQueue_,n,f);for(let p=0;p<g.length;p++)_p(g[p])}else{if(u==="datastale")for(let g=0;g<a.length;g++)a[g].status===3?a[g].status=4:a[g].status=0;else{Co("transaction at "+d.toString()+" failed: "+u);for(let g=0;g<a.length;g++)a[g].status=4,a[g].abortReason=u}vp(t,n)}},l)}function vp(t,n){const a=fD(t,n),s=Tg(a),i=gD(t,a);return i4(t,i,s),s}function i4(t,n,a){if(n.length===0)return;const s=[];let i=[];const l=n.filter(m=>m.status===0).map(m=>m.currentWriteId);for(let m=0;m<n.length;m++){const d=n[m],u=So(a,d.path);let f=!1,g;if(la(u!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),d.status===4)f=!0,g=d.abortReason,i=i.concat(Au(t.serverSyncTree_,d.currentWriteId,!0));else if(d.status===0)if(d.retryCount>=YL)f=!0,g="maxretry",i=i.concat(Au(t.serverSyncTree_,d.currentWriteId,!0));else{const p=Vw(t,d.path,l);d.currentInputSnapshot=p;const y=n[m].update(p.val());if(y!==void 0){$g("transaction failed: Data returned ",y,d.path);let b=ji(y);typeof y=="object"&&y!=null&&pl(y,".priority")||(b=b.updatePriority(p.getPriority()));const w=d.currentWriteId,C=Og(t),R=Ow(b,p,C);d.currentOutputSnapshotRaw=b,d.currentOutputSnapshotResolved=R,d.currentWriteId=sx(t),l.splice(l.indexOf(w),1),i=i.concat(Ew(t.serverSyncTree_,d.path,R,d.currentWriteId,d.applyLocally)),i=i.concat(Au(t.serverSyncTree_,w,!0))}else f=!0,g="nodata",i=i.concat(Au(t.serverSyncTree_,d.currentWriteId,!0))}yc(t.eventQueue_,a,i),i=[],f&&(n[m].status=2,(function(p){setTimeout(p,Math.floor(0))})(n[m].unwatcher),n[m].onComplete&&(g==="nodata"?s.push(()=>n[m].onComplete(null,!1,n[m].currentInputSnapshot)):s.push(()=>n[m].onComplete(new Error(g),!1,null))))}ix(t,t.transactionQueueTree_);for(let m=0;m<s.length;m++)_p(s[m]);rx(t,t.transactionQueueTree_)}function fD(t,n){let a,s=t.transactionQueueTree_;for(a=xs(n);a!==null&&Zh(s)===void 0;)s=ex(s,a),n=Pr(n),a=xs(n);return s}function gD(t,n){const a=[];return yD(t,n,a),a.sort((s,i)=>s.order-i.order),a}function yD(t,n,a){const s=Zh(n);if(s)for(let i=0;i<s.length;i++)a.push(s[i]);tx(n,i=>{yD(t,i,a)})}function ix(t,n){const a=Zh(n);if(a){let s=0;for(let i=0;i<a.length;i++)a[i].status!==2&&(a[s]=a[i],s++);a.length=s,Fw(n,a.length>0?a:void 0)}tx(n,s=>{ix(t,s)})}function Hw(t,n){const a=Tg(fD(t,n)),s=ex(t.transactionQueueTree_,n);return $L(s,i=>{G0(t,i)}),G0(t,s),dD(s,i=>{G0(t,i)}),a}function G0(t,n){const a=Zh(n);if(a){const s=[];let i=[],c=-1;for(let l=0;l<a.length;l++)a[l].status===3||(a[l].status===1?(la(c===l-1,"All SENT items should be at beginning of queue."),c=l,a[l].status=3,a[l].abortReason="set"):(la(a[l].status===0,"Unexpected transaction status in abort"),a[l].unwatcher(),i=i.
2752concat(Au(t.serverSyncTree_,a[l].currentWriteId,!0)),a[l].onComplete&&s.push(a[l].onComplete.bind(null,new Error("set"),!1,null))));c===-1?Fw(n,void 0):a.length=c+1,yc(t.eventQueue_,Tg(n),i);for(let l=0;l<s.length;l++)_p(s[l])}}/** 2753 * @license 2754 * Copyright 2017 Google LLC 2755 * 2756 * Licensed under the Apache License, Version 2.0 (the "License"); 2757 * you may not use this file except in compliance with the License. 2758 * You may obtain a copy of the License at 2759 * 2760 * http://www.apache.org/licenses/LICENSE-2.0 2761 * 2762 * Unless required by applicable law or agreed to in writing, software 2763 * distributed under the License is distributed on an "AS IS" BASIS, 2764 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2765 * See the License for the specific language governing permissions and 2766 * limitations under the License. 2767 */function o4(t){let n="";const a=t.split("/");for(let s=0;s<a.length;s++)if(a[s].length>0){let i=a[s];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}n+="/"+i}return n}function c4(t){const n={};t.charAt(0)==="?"&&(t=t.substring(1));for(const a of t.split("&")){if(a.length===0)continue;const s=a.split("=");s.length===2?n[decodeURIComponent(s[0])]=decodeURIComponent(s[1]):Co(`Invalid query segment '${a}' in query '${t}'`)}return n}const XC=function(t,n){const a=l4(t),s=a.namespace;a.domain==="firebase.com"&&Rd(a.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!s||s==="undefined")&&a.domain!=="localhost"&&Rd("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),a.secure||yO();const i=a.scheme==="ws"||a.scheme==="wss";return{repoInfo:new Ck(a.host,a.secure,s,i,n,"",s!==a.subdomain),path:new mr(a.pathString)}},l4=function(t){let n="",a="",s="",i="",c="",l=!0,m="https",d=443;if(typeof t=="string"){let u=t.indexOf("//");u>=0&&(m=t.substring(0,u-1),t=t.substring(u+2));let f=t.indexOf("/");f===-1&&(f=t.length);let g=t.indexOf("?");g===-1&&(g=t.length),n=t.substring(0,Math.min(f,g)),f<g&&(i=o4(t.substring(f,g)));const p=c4(t.substring(Math.min(t.length,g)));u=n.indexOf(":"),u>=0?(l=m==="https"||m==="wss",d=parseInt(n.substring(u+1),10)):u=n.length;const y=n.slice(0,u);if(y.toLowerCase()==="localhost")a="localhost";else if(y.split(".").length<=2)a=y;else{const b=n.indexOf(".");s=n.substring(0,b).toLowerCase(),a=n.substring(b+1),c=s}"ns"in p&&(c=p.ns)}return{host:n,port:d,domain:a,subdomain:s,secure:l,scheme:m,pathString:i,namespace:c}};/** 2768 * @license 2769 * Copyright 2017 Google LLC 2770 * 2771 * Licensed under the Apache License, Version 2.0 (the "License"); 2772 * you may not use this file except in compliance with the License. 2773 * You may obtain a copy of the License at 2774 * 2775 * http://www.apache.org/licenses/LICENSE-2.0 2776 * 2777 * Unless required by applicable law or agreed to in writing, software 2778 * distributed under the License is distributed on an "AS IS" BASIS, 2779 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2780 * See the License for the specific language governing permissions and 2781 * limitations under the License. 2782 */const ZC="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",d4=(function(){let t=0;const n=[];return function(a){const s=a===t;t=a;let i;const c=new Array(8);for(i=7;i>=0;i--)c[i]=ZC.charAt(a%64),a=Math.floor(a/64);la(a===0,"Cannot push at time == 0");let l=c.join("");if(s){for(i=11;i>=0&&n[i]===63;i--)n[i]=0;n[i]++}else for(i=0;i<12;i++)n[i]=Math.floor(Math.random()*64);for(i=0;i<12;i++)l+=ZC.charAt(n[i]);return la(l.length===20,"nextPushId: Length should be 20."),l}})();/** 2783 * @license 2784 * Copyright 2017 Google LLC 2785 * 2786 * Licensed under the Apache License, Version 2.0 (the "License"); 2787 * you may not use this file except in compliance with the License. 2788 * You may obtain a copy of the License at 2789 * 2790 * http://www.apache.org/licenses/LICENSE-2.0 2791 * 2792 * Unless required by applicable law or agreed to in writing, software 2793 * distributed under the License is distributed on an "AS IS" BASIS, 2794 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2795 * See the License for the specific language governing permissions and 2796 * limitations under the License. 2797 */class u4{constructor(n,a,s,i){this.eventType=n,this.eventRegistration=a,this.snapshot=s,this.prevName=i}getPath(){const n=this.snapshot.ref;return this.eventType==="value"?n._path:n.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+Ri(this.snapshot.exportVal())}}class h4{constructor(n,a,s){this.eventRegistration=n,this.error=a,this.path=s}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/** 2798 * @license 2799 * Copyright 2017 Google LLC 2800 * 2801 * Licensed under the Apache License, Version 2.0 (the "License");
2802 * you may not use this file except in compliance with the License. 2803 * You may obtain a copy of the License at 2804 * 2805 * http://www.apache.org/licenses/LICENSE-2.0 2806 * 2807 * Unless required by applicable law or agreed to in writing, software 2808 * distributed under the License is distributed on an "AS IS" BASIS, 2809 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2810 * See the License for the specific language governing permissions and 2811 * limitations under the License. 2812 */class vD{constructor(n,a){this.snapshotCallback=n,this.cancelCallback=a}onValue(n,a){this.snapshotCallback.call(null,n,a)}onCancel(n){return la(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,n)}get hasCancelCallback(){return!!this.cancelCallback}matches(n){return this.snapshotCallback===n.snapshotCallback||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===n.snapshotCallback.userCallback&&this.snapshotCallback.context===n.snapshotCallback.context}}/** 2813 * @license 2814 * Copyright 2020 Google LLC 2815 * 2816 * Licensed under the Apache License, Version 2.0 (the "License"); 2817 * you may not use this file except in compliance with the License. 2818 * You may obtain a copy of the License at 2819 * 2820 * http://www.apache.org/licenses/LICENSE-2.0 2821 * 2822 * Unless required by applicable law or agreed to in writing, software 2823 * distributed under the License is distributed on an "AS IS" BASIS, 2824 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2825 * See the License for the specific language governing permissions and 2826 * limitations under the License. 2827 */class em{constructor(n,a,s,i){this._repo=n,this._path=a,this._queryParams=s,this._orderByCalled=i}get key(){return js(this._path)?null:yw(this._path)}get ref(){return new Wl(this._repo,this._path)}get _queryIdentifier(){const n=OC(this._queryParams),a=mw(n);return a==="{}"?"default":a}get _queryObject(){return OC(this._queryParams)}isEqual(n){if(n=Jr(n),!(n instanceof em))return!1;const a=this._repo===n._repo,s=vw(this._path,n._path),i=this._queryIdentifier===n._queryIdentifier;return a&&s&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+e3(this._path)}}function m4(t,n){if(t._orderByCalled===!0)throw new Error(n+": You can't combine multiple orderBy calls.")}function Ww(t){let n=null,a=null;if(t.hasStart()&&(n=t.getIndexStartValue()),t.hasEnd()&&(a=t.getIndexEndValue()),t.getIndex()===kh){const s="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(t.hasStart()){if(t.getIndexStartName()!==Vh)throw new Error(s);if(typeof n!="string")throw new Error(i)}if(t.hasEnd()){if(t.getIndexEndName()!==$u)throw new Error(s);if(typeof a!="string")throw new Error(i)}}else if(t.getIndex()===Hr){if(n!=null&&!Db(n)||a!=null&&!Db(a))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(la(t.getIndex()instanceof jw||t.getIndex()===Uk,"unknown index type."),n!=null&&typeof n=="object"||a!=null&&typeof a=="object")throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function bD(t){if(t.hasStart()&&t.hasEnd()&&t.hasLimit()&&!t.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class Wl extends em{constructor(n,a){super(n,a,new Nw,!1)}get parent(){const n=Tk(this._path);return n===null?null:new Wl(this._repo,n)}get root(){let n=this;for(;n.parent!==null;)n=n.parent;return n}}class bp{constructor(n,a,s){this._node=n,this.ref=a,this._index=s}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(n){const a=new mr(n),s=mg(this.ref,n);return new bp(this._node.getChild(a),s,Hr)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(s,i)=>n(new bp(i,mg(this.ref,s),Hr)))}hasChild(n){const a=new mr(n);return!this._node.getChild(a).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function re(t,n){return t=Jr(t),t._checkNotDeleted("ref"),n!==void 0?mg(t._root,n):t._root}function mg(t,n){return t=Jr(t),xs(t._path)===null?qL("child","path",n):zw("child","path",n),new Wl(t._repo,si(t._path,n))}function Ta(t,n){t=Jr(t),nx("push",t._path),Mg("push",n,t._path,!0);const a=pD(t._repo),s=d4(a),i=mg(t,s),c=mg(t,s);let l;return l=Promise.resolve(c),i.then=l.then.bind(l),i.catch=l.then.bind(l,void 0),i}function Ao(t){return nx("remove",t._path),Pn(t,null)}function Pn(t,n){t=Jr(t),nx("set",t._path),Mg("set",n,t._path,!1);const a=new Jh;return ZL(t._repo,t._path,n,null,a.wrapCallback(()=>{})),a.promise}function yn(t,n){zL("update",n,t._path);const a=new Jh;return e4(t._repo,t._path,n,a.wrapCallback(()=>{})),a.promise}function mn(t){t=Jr(t);const n=new vD(()=>{}),a=new ox(n);return XL(t._repo,t,a).then(s=>new bp(s,new Wl(t._repo,t._path),t._queryParams.getIndex()))}class ox{constructor(n){this.callbackContext=n}respondsTo(n){return n==="value"}createEvent(n,a){const s=a._queryParams.getIndex();return new u4("value",this,new bp(n.snapshotNode,new Wl(a._repo,a._path),s)
2827)}getEventRunner(n){return n.getEventType()==="cancel"?()=>this.callbackContext.onCancel(n.error):()=>this.callbackContext.onValue(n.snapshot,null)}createCancelEvent(n,a){return this.callbackContext.hasCancelCallback?new h4(this,n,a):null}matches(n){return n instanceof ox?!n.callbackContext||!this.callbackContext?!0:n.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}function p4(t,n,a,s,i){let c;if(typeof s=="object"&&(c=void 0,i=s),typeof s=="function"&&(c=s),i&&i.onlyOnce){const d=a,u=(f,g)=>{KC(t._repo,t,m),d(f,g)};u.userCallback=a.userCallback,u.context=a.context,a=u}const l=new vD(a,c||void 0),m=new ox(l);return n4(t._repo,t,m),()=>KC(t._repo,t,m)}function qt(t,n,a,s){return p4(t,"value",n,a,s)}class Lg{}class f4 extends Lg{constructor(n,a){super(),this._value=n,this._key=a,this.type="endAt"}_apply(n){Mg("endAt",this._value,n._path,!0);const a=C3(n._queryParams,this._value,this._key);if(bD(a),Ww(a),n._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new em(n._repo,n._path,a,n._orderByCalled)}}class xD extends Lg{constructor(n,a){super(),this._value=n,this._key=a,this.type="startAt"}_apply(n){Mg("startAt",this._value,n._path,!0);const a=S3(n._queryParams,this._value,this._key);if(bD(a),Ww(a),n._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new em(n._repo,n._path,a,n._orderByCalled)}}function g4(t=null,n){return new xD(t,n)}class y4 extends Lg{constructor(n){super(),this._limit=n,this.type="limitToLast"}_apply(n){if(n._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new em(n._repo,n._path,N3(n._queryParams,this._limit),n._orderByCalled)}}function jD(t){if(typeof t!="number"||Math.floor(t)!==t||t<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new y4(t)}class v4 extends Lg{constructor(n){super(),this._path=n,this.type="orderByChild"}_apply(n){m4(n,"orderByChild");const a=new mr(this._path);if(js(a))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const s=new jw(a),i=A3(n._queryParams,s);return Ww(i),new em(n._repo,n._path,i,!0)}}function ql(t){if(t==="$key")throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if(t==="$priority")throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if(t==="$value")throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return zw("orderByChild","path",t),new v4(t)}class b4 extends Lg{constructor(n,a){super(),this._value=n,this._key=a,this.type="equalTo"}_apply(n){if(Mg("equalTo",this._value,n._path,!1),n._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(n._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new f4(this._value,this._key)._apply(new xD(this._value,this._key)._apply(n))}}function Dh(t,n){return new b4(t,n)}function Vl(t,...n){let a=Jr(t);for(const s of n)a=s._apply(a);return a}pL(Wl);bL(Wl);/** 2828 * @license 2829 * Copyright 2020 Google LLC 2830 * 2831 * Licensed under the Apache License, Version 2.0 (the "License"); 2832 * you may not use this file except in compliance with the License. 2833 * You may obtain a copy of the License at 2834 * 2835 * http://www.apache.org/licenses/LICENSE-2.0 2836 * 2837 * Unless required by applicable law or agreed to in writing, software 2838 * distributed under the License is distributed on an "AS IS" BASIS, 2839 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2840 * See the License for the specific language governing permissions and 2841 * limitations under the License. 2842 */const x4="FIREBASE_DATABASE_EMULATOR_HOST",g1={};let j4=!1;function w4(t,n,a,s){const i=n.lastIndexOf(":"),c=n.substring(0,i),l=Cg(c);t.repoInfo_=new Ck(n,l,t.repoInfo_.namespace,t.repoInfo_.webSocketOnly,t.repoInfo_.nodeAdmin,t.repoInfo_.persistenceKey,t.repoInfo_.includeNamespaceInQueryParams,!0,a),s&&(t.authTokenProvider_=s)}function N4(t,n,a,s,i){let c=s||t.options.databaseURL;c===void 0&&(t.options.projectId||Rd("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Xi("Using default host for project ",t.options.projectId),c=`${t.options.projectId}-default-rtdb.firebaseio.com`);let l=XC(c,i),m=l.repoInfo,d;typeof process<"u"&&bC&&(d=bC[x4]),d?(c=`http://${d}?ns=${m.namespace}`,l=XC(c,i),m=l.repoInfo):l.repoInfo.secure;const u=new _O(t.name,t.options,n);VL("Invalid Firebase Database URL",l),js(l.path)||Rd("Database URL must point to the root of a Firebase Database (not including a child path).");const f=C4(m,t,u,new IO(t,a));return new A4(f,t)}function S4(t,n){const a=g1[n];(!a||a[t.key]!==t)&&Rd(`Database ${n}(${t.repoInfo_}) has already been deleted.`),a4(t),delete a[t.key]}function C4(t,n,a,s){let i=g1[n.name];i||(i={},g1[n.name]=i);let c=i[t.toURLString()];return c&&Rd("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),c=new QL(t,j4,a,s),i[t.toURLString()]=c,c}class A4{constructor(n,a){this._repoInternal=n,this.app=a,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(JL(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Wl(this._repo,Qs())),this._rootInternal}_delete(){return this._rootInternal!==null&&(S4(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(n){this._rootInternal===null&&Rd("Cannot call "+n+" on a deleted database.")}}function I4(t=w5(),n){const a=nw(t,"database").getImmediate({identifier:n});if(!a._instanceStarted){const s=CR("database");
2842s&&_4(a,...s)}return a}function _4(t,n,a,s={}){t=Jr(t),t._checkNotDeleted("useEmulator");const i=`${n}:${a}`,c=t._repoInternal;if(t._instanceStarted){if(i===t._repoInternal.repoInfo_.host&&Bh(s,c.repoInfo_.emulatorOptions))return;Rd("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let l;if(c.repoInfo_.nodeAdmin)s.mockUserToken&&Rd('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),l=new tb(tb.OWNER);else if(s.mockUserToken){const m=typeof s.mockUserToken=="string"?s.mockUserToken:AR(s.mockUserToken,t.app.options.projectId);l=new tb(m)}Cg(n)&&b5(n),w4(c,i,s,l)}/** 2843 * @license 2844 * Copyright 2021 Google LLC 2845 * 2846 * Licensed under the Apache License, Version 2.0 (the "License"); 2847 * you may not use this file except in compliance with the License. 2848 * You may obtain a copy of the License at 2849 * 2850 * http://www.apache.org/licenses/LICENSE-2.0 2851 * 2852 * Unless required by applicable law or agreed to in writing, software 2853 * distributed under the License is distributed on an "AS IS" BASIS, 2854 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2855 * See the License for the specific language governing permissions and 2856 * limitations under the License. 2857 */function k4(t){hO(Ip),pp(new Fh("database",(n,{instanceIdentifier:a})=>{const s=n.getProvider("app").getImmediate(),i=n.getProvider("auth-internal"),c=n.getProvider("app-check-internal");return N4(s,i,c,a)},"PUBLIC").setMultipleInstances(!0)),Eu(xC,jC,t),Eu(xC,jC,"esm2020")}/** 2858 * @license 2859 * Copyright 2020 Google LLC 2860 * 2861 * Licensed under the Apache License, Version 2.0 (the "License"); 2862 * you may not use this file except in compliance with the License. 2863 * You may obtain a copy of the License at 2864 * 2865 * http://www.apache.org/licenses/LICENSE-2.0 2866 * 2867 * Unless required by applicable law or agreed to in writing, software 2868 * distributed under the License is distributed on an "AS IS" BASIS, 2869 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2870 * See the License for the specific language governing permissions and 2871 * limitations under the License. 2872 */class D4{constructor(n,a){this.committed=n,this.snapshot=a}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function Ep(t,n,a){if(t=Jr(t),nx("Reference.transaction",t._path),t.key===".length"||t.key===".keys")throw"Reference.transaction failed: "+t.key+" is a read-only object.";const s=(a==null?void 0:a.applyLocally)??!0,i=new Jh,c=(m,d,u)=>{let f=null;m?i.reject(m):(f=new bp(u,new Wl(t._repo,t._path),Hr),i.resolve(new D4(d,f)))},l=qt(t,()=>{});return s4(t._repo,t._path,n,c,l,s),i.promise}/** 2873 * @license 2874 * Copyright 2017 Google LLC 2875 * 2876 * Licensed under the Apache License, Version 2.0 (the "License"); 2877 * you may not use this file except in compliance with the License. 2878 * You may obtain a copy of the License at 2879 * 2880 * http://www.apache.org/licenses/LICENSE-2.0 2881 * 2882 * Unless required by applicable law or agreed to in writing, software 2883 * distributed under the License is distributed on an "AS IS" BASIS, 2884 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2885 * See the License for the specific language governing permissions and 2886 * limitations under the License. 2887 */Ad.prototype.simpleListen=function(t,n){this.sendRequest("q",{p:t},n)};Ad.prototype.echo=function(t,n){this.sendRequest("echo",{d:t},n)};k4();/** 2888 * @license lucide-react v0.468.0 - ISC 2889 * 2890 * This source code is licensed under the ISC license. 2891 * See the LICENSE file in the root directory of this source tree. 2892 */const E4=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),wD=(...t)=>t.filter((n,a,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===a).join(" ").trim();/** 2893 * @license lucide-react v0.468.0 - ISC 2894 * 2895 * This source code is licensed under the ISC license. 2896 * See the LICENSE file in the root directory of this source tree. 2897 */var P4={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** 2898 * @license lucide-react v0.468.0 - ISC 2899 * 2900 * This source code is licensed under the ISC license. 2901 * See the LICENSE file in the root directory of this source tree. 2902 */const R4=x.forwardRef(({color:t="currentColor",size:n=24,strokeWidth:a=2,absoluteStrokeWidth:s,className:i="",children:c,iconNode:l,...m},d)=>x.createElement("svg",{ref:d,...P4,width:n,height:n,stroke:t,strokeWidth:s?Number(a)*24/Number(n):a,className:wD("lucide",i),...m},[...l.map(([u,f])=>
2902x.createElement(u,f)),...Array.isArray(c)?c:[c]]));/** 2903 * @license lucide-react v0.468.0 - ISC 2904 * 2905 * This source code is licensed under the ISC license. 2906 * See the LICENSE file in the root directory of this source tree. 2907 */const Gn=(t,n)=>{const a=x.forwardRef(({className:s,...i},c)=>x.createElement(R4,{ref:c,iconNode:n,className:wD(`lucide-${E4(t)}`,s),...i}));return a.displayName=`${t}`,a};/** 2908 * @license lucide-react v0.468.0 - ISC 2909 * 2910 * This source code is licensed under the ISC license. 2911 * See the LICENSE file in the root directory of this source tree. 2912 */const ND=Gn("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/** 2913 * @license lucide-react v0.468.0 - ISC 2914 * 2915 * This source code is licensed under the ISC license. 2916 * See the LICENSE file in the root directory of this source tree. 2917 */const SD=Gn("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** 2918 * @license lucide-react v0.468.0 - ISC 2919 * 2920 * This source code is licensed under the ISC license. 2921 * See the LICENSE file in the root directory of this source tree. 2922 */const y1=Gn("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** 2923 * @license lucide-react v0.468.0 - ISC 2924 * 2925 * This source code is licensed under the ISC license. 2926 * See the LICENSE file in the root directory of this source tree. 2927 */const T4=Gn("Award",[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]]);/** 2928 * @license lucide-react v0.468.0 - ISC 2929 * 2930 * This source code is licensed under the ISC license. 2931 * See the LICENSE file in the root directory of this source tree. 2932 */const Oy=Gn("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** 2933 * @license lucide-react v0.468.0 - ISC 2934 * 2935 * This source code is licensed under the ISC license. 2936 * See the LICENSE file in the root directory of this source tree. 2937 */const CD=Gn("BadgePercent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** 2938 * @license lucide-react v0.468.0 - ISC 2939 * 2940 * This source code is licensed under the ISC license. 2941 * See the LICENSE file in the root directory of this source tree. 2942 */const M4=Gn("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** 2943 * @license lucide-react v0.468.0 - ISC 2944 * 2945 * This source code is licensed under the ISC license. 2946 * See the LICENSE file in the root directory of this source tree. 2947 */const $4=Gn("Bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]);/** 2948 * @license lucide-react v0.468.0 - ISC 2949 * 2950 * This source code is licensed under the ISC license. 2951 * See the LICENSE file in the root directory of this source tree. 2952 */const eA=Gn("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/** 2953 * @license lucide-react v0.468.0 - ISC 2954 * 2955 * This source code is licensed under the ISC license. 2956 * See the LICENSE file in the root directory of this source tree. 2957 */const Tu=Gn("Boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);/** 2958 * @license lucide-react v0.468.0 - ISC 2959 * 2960 * This source code is licensed under the ISC license. 2961 * See the LICENSE file in the root directory of this source tree. 2962 */const Gw=Gn("BriefcaseBusiness",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M22 13a18.15 18.15 0 0 1-20 0",key:"12hx5q"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** 2963 * @license lucide-react v0.468.0 - ISC 2964 * 2965 * This source code is licensed under the ISC license. 2966 * See the LICENSE file in the root directory of this source tree. 2967 */const Fu=Gn("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}
2967],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** 2968 * @license lucide-react v0.468.0 - ISC 2969 * 2970 * This source code is licensed under the ISC license. 2971 * See the LICENSE file in the root directory of this source tree. 2972 */const v1=Gn("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** 2973 * @license lucide-react v0.468.0 - ISC 2974 * 2975 * This source code is licensed under the ISC license. 2976 * See the LICENSE file in the root directory of this source tree. 2977 */const nb=Gn("CalendarCheck2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 14V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"bce9hv"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** 2978 * @license lucide-react v0.468.0 - ISC 2979 * 2980 * This source code is licensed under the ISC license. 2981 * See the LICENSE file in the root directory of this source tree. 2982 */const tA=Gn("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/** 2983 * @license lucide-react v0.468.0 - ISC 2984 * 2985 * This source code is licensed under the ISC license. 2986 * See the LICENSE file in the root directory of this source tree. 2987 */const wi=Gn("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** 2988 * @license lucide-react v0.468.0 - ISC 2989 * 2990 * This source code is licensed under the ISC license. 2991 * See the LICENSE file in the root directory of this source tree. 2992 */const O4=Gn("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** 2993 * @license lucide-react v0.468.0 - ISC 2994 * 2995 * This source code is licensed under the ISC license. 2996 * See the LICENSE file in the root directory of this source tree. 2997 */const xp=Gn("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** 2998 * @license lucide-react v0.468.0 - ISC 2999 * 3000 * This source code is licensed under the ISC license. 3001 * See the LICENSE file in the root directory of this source tree. 3002 */const ap=Gn("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** 3003 * @license lucide-react v0.468.0 - ISC 3004 * 3005 * This source code is licensed under the ISC license. 3006 * See the LICENSE file in the root directory of this source tree. 3007 */const Yw=Gn("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** 3008 * @license lucide-react v0.468.0 - ISC 3009 * 3010 * This source code is licensed under the ISC license. 3011 * See the LICENSE file in the root directory of this source tree. 3012 */const Ei=Gn("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** 3013 * @license lucide-react v0.468.0 - ISC 3014 * 3015 * This source code is licensed under the ISC license. 3016 * See the LICENSE file in the root directory of this source tree. 3017 */const L4=Gn("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** 3018 * @license lucide-react v0.468.0 - ISC 3019 * 3020 * This source code is licensed under the ISC license. 3021 * See the LICENSE file in the root directory of this source tree. 3022 */const Ms=Gn("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** 3023 * @license lucide-react v0.468.0 - ISC 3024 * 3025 * This source code is licensed under the ISC license. 3026 * See the LICENSE file in the root directory of this source tree. 3027 */const Ch=Gn("CircleDollarSign",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** 3028 * @license lucide-react v0.468.0 - ISC 3029 * 3030 * This source code is licensed under the ISC license. 3031 * See the LICENSE file in the root directory of this source tree. 3032 */const Eb=Gn("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** 3033 * @license lucide-react v0.468.0 - ISC 3034 * 3035 * This source code is licensed under the ISC license. 3036 * See the LICENSE file in the root directory of this source tree. 3037 */const AD=Gn("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** 3038 * @license lucide-react v0.468.0 - ISC 3039 * 3040 * This source code is licensed under the ISC license. 3041 * See the LICENSE file in the root directory of this source tree.
3042 */const b1=Gn("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]);/** 3043 * @license lucide-react v0.468.0 - ISC 3044 * 3045 * This source code is licensed under the ISC license. 3046 * See the LICENSE file in the root directory of this source tree. 3047 */const Qw=Gn("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** 3048 * @license lucide-react v0.468.0 - ISC 3049 * 3050 * This source code is licensed under the ISC license. 3051 * See the LICENSE file in the root directory of this source tree. 3052 */const Ho=Gn("Clock3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16.5 12",key:"1aq6pp"}]]);/** 3053 * @license lucide-react v0.468.0 - ISC 3054 * 3055 * This source code is licensed under the ISC license. 3056 * See the LICENSE file in the root directory of this source tree. 3057 */const B4=Gn("Contact",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M7 22v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1waht3"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"11",r:"3",key:"itu57m"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** 3058 * @license lucide-react v0.468.0 - ISC 3059 * 3060 * This source code is licensed under the ISC license. 3061 * See the LICENSE file in the root directory of this source tree. 3062 */const sp=Gn("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** 3063 * @license lucide-react v0.468.0 - ISC 3064 * 3065 * This source code is licensed under the ISC license. 3066 * See the LICENSE file in the root directory of this source tree. 3067 */const Ly=Gn("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}
3067],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/** 3068 * @license lucide-react v0.468.0 - ISC 3069 * 3070 * This source code is licensed under the ISC license. 3071 * See the LICENSE file in the root directory of this source tree. 3072 */const F4=Gn("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** 3073 * @license lucide-react v0.468.0 - ISC 3074 * 3075 * This source code is licensed under the ISC license. 3076 * See the LICENSE file in the root directory of this source tree. 3077 */const Uf=Gn("DatabaseBackup",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 12a9 3 0 0 0 5 2.69",key:"1ui2ym"}],["path",{d:"M21 9.3V5",key:"6k6cib"}],["path",{d:"M3 5v14a9 3 0 0 0 6.47 2.88",key:"i62tjy"}],["path",{d:"M12 12v4h4",key:"1bxaet"}],["path",{d:"M13 20a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L12 16",key:"1f4ei9"}]]);/** 3078 * @license lucide-react v0.468.0 - ISC 3079 * 3080 * This source code is licensed under the ISC license. 3081 * See the LICENSE file in the root directory of this source tree. 3082 */const Mi=Gn("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** 3083 * @license lucide-react v0.468.0 - ISC 3084 * 3085 * This source code is licensed under the ISC license. 3086 * See the LICENSE file in the root directory of this source tree. 3087 */const Pb=Gn("Earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** 3088 * @license lucide-react v0.468.0 - ISC 3089 * 3090 * This source code is licensed under the ISC license. 3091 * See the LICENSE file in the root directory of this source tree. 3092 */const ID=Gn("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** 3093 * @license lucide-react v0.468.0 - ISC 3094 * 3095 * This source code is licensed under the ISC license. 3096 * See the LICENSE file in the root directory of this source tree. 3097 */const ui=Gn("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** 3098 * @license lucide-react v0.468.0 - ISC 3099 * 3100 * This source code is licensed under the ISC license. 3101 * See the LICENSE file in the root directory of this source tree. 3102 */const jp=Gn("FileCheck2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3 15 2 2 4-4",key:"1lhrkk"}]]);/** 3103 * @license lucide-react v0.468.0 - ISC 3104 * 3105 * This source code is licensed under the ISC license. 3106 * See the LICENSE file in the root directory of this source tree. 3107 */const Uu=Gn("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** 3108 * @license lucide-react v0.468.0 - ISC 3109 * 3110 * This source code is licensed under the ISC license. 3111 * See the LICENSE file in the root directory of this source tree. 3112 */const U4=Gn("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/** 3113 * @license lucide-react v0.468.0 - ISC 3114 * 3115 * This source code is licensed under the ISC license. 3116 * See the LICENSE file in the root directory of this source tree. 3117 */const Zs=Gn("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** 3118 * @license lucide-react v0.468.0 - ISC 3119 * 3120 * This source code is licensed under the ISC license. 3121 * See the LICENSE file in the root directory of this source tree. 3122 */const wp=Gn("FileUp",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]]);/** 3123 * @license lucide-react v0.468.0 - ISC 3124 * 3125 * This source code is licensed under the ISC license. 3126 * See the LICENSE file in the root directory of this source tree. 3127 */const _D=Gn("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** 3128 * @license lucide-react v0.468.0 - ISC 3129 * 3130 * This source code is licensed under the ISC license. 3131 * See the LICENSE file in the root directory of this source tree. 3132 */const Eh=Gn("HandCoins",[["path",{d:"M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17",key:"geh8rc"}],["path",{d:"m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"1fto5m"}],["path",{d:"m2 16 6 6",key:"1pfhp9"}],["circle",{cx:"16",cy:"9",r:"2.9",key:"1n0dlu"}],["circle",{cx:"6",cy:"5",r:"3",key:"151irh"}]]);/** 3133 * @license lucide-react v0.468.0 - ISC 3134 * 3135 * This source code is licensed under the ISC license. 3136 * See the LICENSE file in the root directory of this source tree. 3137 */const kD=Gn("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/** 3138 * @license lucide-react v0.468.0 - ISC 3139 * 3140 * This source code is licensed under the ISC license. 3141 * See the LICENSE file in the root directory of this source tree. 3142 */const Rb=Gn("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** 3143 * @license lucide-react v0.468.0 - ISC 3144 * 3145 * This source code is licensed under the ISC license. 3146 * See the LICENSE file in the root directory of this source tree. 3147 */const Gh=Gn("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** 3148 * @license lucide-react v0.468.0 - ISC 3149 * 3150 * This source code is licensed under the ISC license. 3151 * See the LICENSE file in the root directory of this source tree. 3152 */const Nd=Gn("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** 3153 * @license lucide-react v0.468.0 - ISC 3154 * 3155 * This source code is licensed under the ISC license. 3156 * See the LICENSE file in the root directory of this source tree.
3157 */const x1=Gn("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** 3158 * @license lucide-react v0.468.0 - ISC 3159 * 3160 * This source code is licensed under the ISC license. 3161 * See the LICENSE file in the root directory of this source tree. 3162 */const nA=Gn("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** 3163 * @license lucide-react v0.468.0 - ISC 3164 * 3165 * This source code is licensed under the ISC license. 3166 * See the LICENSE file in the root directory of this source tree. 3167 */const pg=Gn("LockKeyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);/** 3168 * @license lucide-react v0.468.0 - ISC 3169 * 3170 * This source code is licensed under the ISC license. 3171 * See the LICENSE file in the root directory of this source tree. 3172 */const z4=Gn("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** 3173 * @license lucide-react v0.468.0 - ISC 3174 * 3175 * This source code is licensed under the ISC license. 3176 * See the LICENSE file in the root directory of this source tree. 3177 */const q4=Gn("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** 3178 * @license lucide-react v0.468.0 - ISC 3179 * 3180 * This source code is licensed under the ISC license. 3181 * See the LICENSE file in the root directory of this source tree. 3182 */const aA=Gn("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** 3183 * @license lucide-react v0.468.0 - ISC 3184 * 3185 * This source code is licensed under the ISC license. 3186 * See the LICENSE file in the root directory of this source tree. 3187 */const DD=Gn("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** 3188 * @license lucide-react v0.468.0 - ISC 3189 * 3190 * This source code is licensed under the ISC license. 3191 * See the LICENSE file in the root directory of this source tree. 3192 */const ED=Gn("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** 3193 * @license lucide-react v0.468.0 - ISC 3194 * 3195 * This source code is licensed under the ISC license. 3196 * See the LICENSE file in the root directory of this source tree. 3197 */const V4=Gn("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** 3198 * @license lucide-react v0.468.0 - ISC 3199 * 3200 * This source code is licensed under the ISC license. 3201 * See the LICENSE file in the root directory of this source tree. 3202 */const zu=Gn("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** 3203 * @license lucide-react v0.468.0 - ISC 3204 * 3205 * This source code is licensed under the ISC license. 3206 * See the LICENSE file in the root directory of this source tree. 3207 */const H4=Gn("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** 3208 * @license lucide-react v0.468.0 - ISC 3209 * 3210 * This source code is licensed under the ISC license. 3211 * See the LICENSE file in the root directory of this source tree. 3212 */const Jw=Gn("PackageCheck",[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** 3213 * @license lucide-react v0.468.0 - ISC 3214 * 3215 * This source code is licensed under the ISC license. 3216 * See the LICENSE file in the root directory of this source tree. 3217 */const W4=Gn("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);/** 3218 * @license lucide-react v0.468.0 - ISC 3219 * 3220 * This source code is licensed under the ISC license. 3221 * See the LICENSE file in the root directory of this source tree. 3222 */const Kw=Gn("PackagePlus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** 3223 * @license lucide-react v0.468.0 - ISC 3224 * 3225 * This source code is licensed under the ISC license. 3226 * See the LICENSE file in the root directory of this source tree. 3227 */const yu=Gn("PackageSearch",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["circle",{cx:"18.5",cy:"15.5",r:"2.5",key:"b5zd12"}],["path",{d:"M20.27 17.27 22 19",key:"1l4muz"}]]);/** 3228 * @license lucide-react v0.468.0 - ISC 3229 * 3230 * This source code is licensed under the ISC license. 3231 * See the LICENSE file in the root directory of this source tree. 3232 */const PD=Gn("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** 3233 * @license lucide-react v0.468.0 - ISC 3234 * 3235 * This source code is licensed under the ISC license. 3236 * See the LICENSE file in the root directory of this source tree. 3237 */const Tb=Gn("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/** 3238 * @license lucide-react v0.468.0 - ISC 3239 * 3240 * This source code is licensed under the ISC license. 3241 * See the LICENSE file in the root directory of this source tree. 3242 */const Zi=Gn("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** 3243 * @license lucide-react v0.468.0 - ISC 3244 * 3245 * This source code is licensed under the ISC license. 3246 * See the LICENSE file in the root directory of this source tree. 3247 */const fg=Gn("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** 3248 * @license lucide-react v0.468.0 - ISC 3249 * 3250 * This source code is licensed under the ISC license. 3251 * See the LICENSE file in the root directory of this source tree. 3252 */const as=Gn("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** 3253 * @license lucide-react v0.468.0 - ISC 3254 * 3255 * This source code is licensed under the ISC license. 3256 * See the LICENSE file in the root directory of this source tree. 3257 */const Wi=Gn("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/** 3258 * @license lucide-react v0.468.0 - ISC 3259 * 3260 * This source code is licensed under the ISC license. 3261 * See the LICENSE file in the root directory of this source tree. 3262 */const RD=Gn("ReceiptText",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}
3262],["path",{d:"M13 16H8",key:"wsln4y"}]]);/** 3263 * @license lucide-react v0.468.0 - ISC 3264 * 3265 * This source code is licensed under the ISC license. 3266 * See the LICENSE file in the root directory of this source tree. 3267 */const Hi=Gn("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** 3268 * @license lucide-react v0.468.0 - ISC 3269 * 3270 * This source code is licensed under the ISC license. 3271 * See the LICENSE file in the root directory of this source tree. 3272 */const Id=Gn("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** 3273 * @license lucide-react v0.468.0 - ISC 3274 * 3275 * This source code is licensed under the ISC license. 3276 * See the LICENSE file in the root directory of this source tree. 3277 */const hr=Gn("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** 3278 * @license lucide-react v0.468.0 - ISC 3279 * 3280 * This source code is licensed under the ISC license. 3281 * See the LICENSE file in the root directory of this source tree. 3282 */const G4=Gn("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/** 3283 * @license lucide-react v0.468.0 - ISC 3284 * 3285 * This source code is licensed under the ISC license. 3286 * See the LICENSE file in the root directory of this source tree. 3287 */const Xw=Gn("ScanLine",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 12h10",key:"b7w52i"}]]);/** 3288 * @license lucide-react v0.468.0 - ISC 3289 * 3290 * This source code is licensed under the ISC license. 3291 * See the LICENSE file in the root directory of this source tree. 3292 */const xr=Gn("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** 3293 * @license lucide-react v0.468.0 - ISC 3294 * 3295 * This source code is licensed under the ISC license. 3296 * See the LICENSE file in the root directory of this source tree. 3297 */const Zw=Gn("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** 3298 * @license lucide-react v0.468.0 - ISC 3299 * 3300 * This source code is licensed under the ISC license. 3301 * See the LICENSE file in the root directory of this source tree. 3302 */const vu=Gn("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** 3303 * @license lucide-react v0.468.0 - ISC 3304 * 3305 * This source code is licensed under the ISC license. 3306 * See the LICENSE file in the root directory of this source tree. 3307 */const TD=Gn("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** 3308 * @license lucide-react v0.468.0 - ISC 3309 * 3310 * This source code is licensed under the ISC license. 3311 * See the LICENSE file in the root directory of this source tree. 3312 */const Y4=Gn("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
3312y:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** 3313 * @license lucide-react v0.468.0 - ISC 3314 * 3315 * This source code is licensed under the ISC license. 3316 * See the LICENSE file in the root directory of this source tree. 3317 */const gs=Gn("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** 3318 * @license lucide-react v0.468.0 - ISC 3319 * 3320 * This source code is licensed under the ISC license. 3321 * See the LICENSE file in the root directory of this source tree. 3322 */const Iu=Gn("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** 3323 * @license lucide-react v0.468.0 - ISC 3324 * 3325 * This source code is licensed under the ISC license. 3326 * See the LICENSE file in the root directory of this source tree. 3327 */const Y0=Gn("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/** 3328 * @license lucide-react v0.468.0 - ISC 3329 * 3330 * This source code is licensed under the ISC license. 3331 * See the LICENSE file in the root directory of this source tree. 3332 */const j1=Gn("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** 3333 * @license lucide-react v0.468.0 - ISC 3334 * 3335 * This source code is licensed under the ISC license. 3336 * See the LICENSE file in the root directory of this source tree. 3337 */const Q4=Gn("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** 3338 * @license lucide-react v0.468.0 - ISC 3339 * 3340 * This source code is licensed under the ISC license. 3341 * See the LICENSE file in the root directory of this source tree. 3342 */const J4=Gn("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/** 3343 * @license lucide-react v0.468.0 - ISC 3344 * 3345 * This source code is licensed under the ISC license. 3346 * See the LICENSE file in the root directory of this source tree. 3347 */const Mc=Gn("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** 3348 * @license lucide-react v0.468.0 - ISC 3349 * 3350 * This source code is licensed under the ISC license. 3351 * See the LICENSE file in the root directory of this source tree. 3352 */const K4=Gn("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/** 3353 * @license lucide-react v0.468.0 - ISC 3354 * 3355 * This source code is licensed under the ISC license. 3356 * See the LICENSE file in the root directory of this source tree. 3357 */const X4=Gn("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/** 3358 * @license lucide-react v0.468.0 - ISC 3359 * 3360 * This source code is licensed under the ISC license. 3361 * See the LICENSE file in the root directory of this source tree. 3362 */const Z4=Gn("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/** 3363 * @license lucide-react v0.468.0 - ISC 3364 * 3365 * This source code is licensed under the ISC license. 3366 * See the LICENSE file in the root directory of this source tree. 3367 */const e6=Gn("ToggleRight",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}]]);/** 3368 * @license lucide-react v0.468.0 - ISC 3369 * 3370 * This source code is licensed under the ISC license. 3371 * See the LICENSE file in the root directory of this source tree. 3372 */const po=Gn("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}
3372],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** 3373 * @license lucide-react v0.468.0 - ISC 3374 * 3375 * This source code is licensed under the ISC license. 3376 * See the LICENSE file in the root directory of this source tree. 3377 */const MD=Gn("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** 3378 * @license lucide-react v0.468.0 - ISC 3379 * 3380 * This source code is licensed under the ISC license. 3381 * See the LICENSE file in the root directory of this source tree. 3382 */const qu=Gn("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** 3383 * @license lucide-react v0.468.0 - ISC 3384 * 3385 * This source code is licensed under the ISC license. 3386 * See the LICENSE file in the root directory of this source tree. 3387 */const sA=Gn("Trophy",[["path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6",key:"17hqa7"}],["path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18",key:"lmptdp"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22",key:"1nw9bq"}],["path",{d:"M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22",key:"1np0yb"}],["path",{d:"M18 2H6v7a6 6 0 0 0 12 0V2Z",key:"u46fv3"}]]);/** 3388 * @license lucide-react v0.468.0 - ISC 3389 * 3390 * This source code is licensed under the ISC license. 3391 * See the LICENSE file in the root directory of this source tree. 3392 */const t6=Gn("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** 3393 * @license lucide-react v0.468.0 - ISC 3394 * 3395 * This source code is licensed under the ISC license. 3396 * See the LICENSE file in the root directory of this source tree. 3397 */const vd=Gn("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** 3398 * @license lucide-react v0.468.0 - ISC 3399 * 3400 * This source code is licensed under the ISC license. 3401 * See the LICENSE file in the root directory of this source tree. 3402 */const Q0=Gn("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** 3403 * @license lucide-react v0.468.0 - ISC 3404 * 3405 * This source code is licensed under the ISC license. 3406 * See the LICENSE file in the root directory of this source tree. 3407 */const w1=Gn("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** 3408 * @license lucide-react v0.468.0 - ISC 3409 * 3410 * This source code is licensed under the ISC license. 3411 * See the LICENSE file in the root directory of this source tree. 3412 */const e2=Gn("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** 3413 * @license lucide-react v0.468.0 - ISC 3414 * 3415 * This source code is licensed under the ISC license. 3416 * See the LICENSE file in the root directory of this source tree. 3417 */const n6=Gn("UserRoundCog",[["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}]]);/** 3418 * @license lucide-react v0.468.0 - ISC 3419 * 3420 * This source code is licensed under the ISC license. 3421 * See the LICENSE file in the root directory of this source tree. 3422 */const a6=Gn("UserRoundSearch",[["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}
3422],["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.9-1.9",key:"1e5ubv"}]]);/** 3423 * @license lucide-react v0.468.0 - ISC 3424 * 3425 * This source code is licensed under the ISC license. 3426 * See the LICENSE file in the root directory of this source tree. 3427 */const s6=Gn("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);/** 3428 * @license lucide-react v0.468.0 - ISC 3429 * 3430 * This source code is licensed under the ISC license. 3431 * See the LICENSE file in the root directory of this source tree. 3432 */const t2=Gn("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** 3433 * @license lucide-react v0.468.0 - ISC 3434 * 3435 * This source code is licensed under the ISC license. 3436 * See the LICENSE file in the root directory of this source tree. 3437 */const mc=Gn("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** 3438 * @license lucide-react v0.468.0 - ISC 3439 * 3440 * This source code is licensed under the ISC license. 3441 * See the LICENSE file in the root directory of this source tree. 3442 */const Ll=Gn("WalletCards",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2",key:"4125el"}],["path",{d:"M3 11h3c.8 0 1.6.3 2.1.9l1.1.9c1.6 1.6 4.1 1.6 5.7 0l1.1-.9c.5-.5 1.3-.9 2.1-.9H21",key:"1dpki6"}]]);/** 3443 * @license lucide-react v0.468.0 - ISC 3444 * 3445 * This source code is licensed under the ISC license. 3446 * See the LICENSE file in the root directory of this source tree. 3447 */const r6=Gn("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** 3448 * @license lucide-react v0.468.0 - ISC 3449 * 3450 * This source code is licensed under the ISC license. 3451 * See the LICENSE file in the root directory of this source tree. 3452 */const i6=Gn("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** 3453 * @license lucide-react v0.468.0 - ISC 3454 * 3455 * This source code is licensed under the ISC license. 3456 * See the LICENSE file in the root directory of this source tree. 3457 */const Go=Gn("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** 3458 * @license lucide-react v0.468.0 - ISC 3459 * 3460 * This source code is licensed under the ISC license. 3461 * See the LICENSE file in the root directory of this source tree. 3462 */const ja=Gn("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var By={},vf={},Fy={},rA;function vc(){if(rA)return Fy;rA=1,Object.defineProperty(Fy,"__esModule",{value:!0});function t(a,s){if(!(a instanceof s))throw new TypeError("Cannot call a class as a function")}var n=function a(s,i){t(this,a),this.data=s,this.text=i.text||s,this.options=i};return Fy.default=n,Fy}var iA;function o6(){if(iA)return vf;iA=1,Object.defineProperty(vf,"__esModule",{value:!0}),vf.CODE39=void 0;var t=(function(){function N(w,C){for(var R=0;R<C.length;R++){var I=C[R];I.enumerable=I.enumerable||!1,I.configurable=!0,"value"in I&&(I.writable=!0),Object.defineProperty(w,I.key,I)}}return function(w,C,R){return C&&N(w.prototype,C),R&&N(w,R),w}})(),n=vc(),a=s(n);function s(N){return N&&N.__esModule?N:{default:N}}function i(N,w){if(!(N instanceof w))throw new TypeError("Cannot call a class as a function")}
3462function c(N,w){if(!N)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return w&&(typeof w=="object"||typeof w=="function")?w:N}function l(N,w){if(typeof w!="function"&&w!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof w);N.prototype=Object.create(w&&w.prototype,{constructor:{value:N,enumerable:!1,writable:!0,configurable:!0}}),w&&(Object.setPrototypeOf?Object.setPrototypeOf(N,w):N.__proto__=w)}var m=(function(N){l(w,N);function w(C,R){return i(this,w),C=C.toUpperCase(),R.mod43&&(C+=p(b(C))),c(this,(w.__proto__||Object.getPrototypeOf(w)).call(this,C,R))}return t(w,[{key:"encode",value:function(){for(var R=f("*"),I=0;I<this.data.length;I++)R+=f(this.data[I])+"0";return R+=f("*"),{data:R,text:this.text}}},{key:"valid",value:function(){return this.data.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/)!==-1}}]),w})(a.default),d=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","-","."," ","$","/","+","%","*"],u=[20957,29783,23639,30485,20951,29813,23669,20855,29789,23645,29975,23831,30533,22295,30149,24005,21623,29981,23837,22301,30023,23879,30545,22343,30161,24017,21959,30065,23921,22385,29015,18263,29141,17879,29045,18293,17783,29021,18269,17477,17489,17681,20753,35770];function f(N){return g(y(N))}function g(N){return u[N].toString(2)}function p(N){return d[N]}function y(N){return d.indexOf(N)}function b(N){for(var w=0,C=0;C<N.length;C++)w+=y(N[C]);return w=w%43,w}return vf.CODE39=m,vf}var el={},Uy={},zy={},ti={},oA;function Bg(){if(oA)return ti;oA=1,Object.defineProperty(ti,"__esModule",{value:!0});var t;function n(d,u,f){return u in d?Object.defineProperty(d,u,{value:f,enumerable:!0,configurable:!0,writable:!0}):d[u]=f,d}var a=ti.SET_A=0,s=ti.SET_B=1,i=ti.SET_C=2;ti.SHIFT=98;var c=ti.START_A=103,l=ti.START_B=104,m=ti.START_C=105;return ti.MODULO=103,ti.STOP=106,ti.FNC1=207,ti.SET_BY_CODE=(t={},n(t,c,a),n(t,l,s),n(t,m,i),t),ti.SWAP={101:a,100:s,99:i},ti.A_START_CHAR="Ã",ti.B_START_CHAR="Ã",ti.C_START_CHAR="Ã",ti.A_CHARS="[\0-_Ã-Ã]",ti.B_CHARS="[ -�Ã-Ã]",ti.C_CHARS="(Ã*[0-9]{2}Ã*)",ti.BARS=[11011001100,11001101100,11001100110,10010011e3,10010001100,10001001100,10011001e3,10011000100,10001100100,11001001e3,11001000100,11000100100,10110011100,10011011100,10011001110,10111001100,10011101100,10011100110,11001110010,11001011100,11001001110,11011100100,11001110100,11101101110,11101001100,11100101100,11100100110,11101100100,11100110100,11100110010,11011011e3,11011000110,11000110110,10100011e3,10001011e3,10001000110,10110001e3,10001101e3,10001100010,11010001e3,11000101e3,11000100010,10110111e3,10110001110,10001101110,10111011e3,10111000110,10001110110,11101110110,11010001110,11000101110,11011101e3,11011100010,11011101110,11101011e3,11101000110,11100010110,11101101e3,11101100010,11100011010,11101111010,11001000010,11110001010,1010011e4,10100001100,1001011e4,10010000110,10000101100,10000100110,1011001e4,10110000100,1001101e4,10011000010,10000110100,10000110010,11000010010,1100101e4,11110111010,11000010100,10001111010,10100111100,10010111100,10010011110,10111100100,10011110100,10011110010,11110100100,11110010100,11110010010,11011011110,11011110110,11110110110,10101111e3,10100011110,10001011110,10111101e3,10111100010,11110101e3,11110100010,10111011110,10111101110,11101011110,11110101110,11010000100,1101001e4,11010011100,1100011101011],ti}var cA;function cx(){if(cA)return zy;cA=1,Object.defineProperty(zy,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=vc(),a=i(n),s=Bg();function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(g,p){c(this,f);var y=l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,g.substring(1),p));return y.bytes=g.split("").map(function(b){return b.charCodeAt(0)}),y}return t(f,[{key:"valid",value:function(){return/^[\x00-\x7F\xC8-\xD3]+$/.test(this.data)}},{key:"encode",value:function(){var p=this.bytes,y=p.shift()-105,b=s.SET_BY_CODE[y];if(b===void 0)throw new RangeError("The encoding does not start with a start character.");this.shouldEncodeAsEan128()===!0&&p.unshift(s.FNC1);var N=f.next(p,1,b);return{text:this.text===this.data?this.text.replace(/[^\x20-\x7E]/g,""):this.text,data:f.getBar(y)+N.result+f.getBar((N.checksum+y)%s.MODULO)+f.getBar(s.STOP)}}},{key:"shouldEncodeAsEan128",value:function(){var p=this.options.ean128||!1;return typeof p=="string"&&(p=p.toLowerCase()==="true"),p}}],[{key:"getBar",value:function(p){return s.BARS[p]?s.BARS[p].toString():""}}
3462,{key:"correctIndex",value:function(p,y){if(y===s.SET_A){var b=p.shift();return b<32?b+64:b-32}else return y===s.SET_B?p.shift()-32:(p.shift()-48)*10+p.shift()-48}},{key:"next",value:function(p,y,b){if(!p.length)return{result:"",checksum:0};var N=void 0,w=void 0;if(p[0]>=200){w=p.shift()-105;var C=s.SWAP[w];C!==void 0?N=f.next(p,y+1,C):((b===s.SET_A||b===s.SET_B)&&w===s.SHIFT&&(p[0]=b===s.SET_A?p[0]>95?p[0]-96:p[0]:p[0]<32?p[0]+96:p[0]),N=f.next(p,y+1,b))}else w=f.correctIndex(p,b),N=f.next(p,y+1,b);var R=f.getBar(w),I=w*y;return{result:R+N.result,checksum:I+N.checksum}}}]),f})(a.default);return zy.default=d,zy}var qy={},lA;function c6(){if(lA)return qy;lA=1,Object.defineProperty(qy,"__esModule",{value:!0});var t=Bg(),n=function(m){return m.match(new RegExp("^"+t.A_CHARS+"*"))[0].length},a=function(m){return m.match(new RegExp("^"+t.B_CHARS+"*"))[0].length},s=function(m){return m.match(new RegExp("^"+t.C_CHARS+"*"))[0]};function i(l,m){var d=m?t.A_CHARS:t.B_CHARS,u=l.match(new RegExp("^("+d+"+?)(([0-9]{2}){2,})([^0-9]|$)"));if(u)return u[1]+"Ã"+c(l.substring(u[1].length));var f=l.match(new RegExp("^"+d+"+"))[0];return f.length===l.length?l:f+String.fromCharCode(m?205:206)+i(l.substring(f.length),!m)}function c(l){var m=s(l),d=m.length;if(d===l.length)return l;l=l.substring(d);var u=n(l)>=a(l);return m+String.fromCharCode(u?206:205)+i(l,u)}return qy.default=function(l){var m=void 0,d=s(l).length;if(d>=2)m=t.C_START_CHAR+c(l);else{var u=n(l)>a(l);m=(u?t.A_START_CHAR:t.B_START_CHAR)+i(l,u)}return m.replace(/[\xCD\xCE]([^])[\xCD\xCE]/,function(f,g){return"Ã"+g})},qy}var dA;function l6(){if(dA)return Uy;dA=1,Object.defineProperty(Uy,"__esModule",{value:!0});var t=cx(),n=i(t),a=c6(),s=i(a);function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(g,p){if(c(this,f),/^[\x00-\x7F\xC8-\xD3]+$/.test(g))var y=l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,(0,s.default)(g),p));else var y=l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,g,p));return l(y)}return f})(n.default);return Uy.default=d,Uy}var Vy={},uA;function d6(){if(uA)return Vy;uA=1,Object.defineProperty(Vy,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=cx(),a=i(n),s=Bg();function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(g,p){return c(this,f),l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,s.A_START_CHAR+g,p))}return t(f,[{key:"valid",value:function(){return new RegExp("^"+s.A_CHARS+"+$").test(this.data)}}]),f})(a.default);return Vy.default=d,Vy}var Hy={},hA;function u6(){if(hA)return Hy;hA=1,Object.defineProperty(Hy,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=cx(),a=i(n),s=Bg();
3462function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(g,p){return c(this,f),l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,s.B_START_CHAR+g,p))}return t(f,[{key:"valid",value:function(){return new RegExp("^"+s.B_CHARS+"+$").test(this.data)}}]),f})(a.default);return Hy.default=d,Hy}var Wy={},mA;function h6(){if(mA)return Wy;mA=1,Object.defineProperty(Wy,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=cx(),a=i(n),s=Bg();function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(g,p){return c(this,f),l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,s.C_START_CHAR+g,p))}return t(f,[{key:"valid",value:function(){return new RegExp("^"+s.C_CHARS+"+$").test(this.data)}}]),f})(a.default);return Wy.default=d,Wy}var pA;function m6(){if(pA)return el;
3462pA=1,Object.defineProperty(el,"__esModule",{value:!0}),el.CODE128C=el.CODE128B=el.CODE128A=el.CODE128=void 0;var t=l6(),n=d(t),a=d6(),s=d(a),i=u6(),c=d(i),l=h6(),m=d(l);function d(u){return u&&u.__esModule?u:{default:u}}return el.CODE128=n.default,el.CODE128A=s.default,el.CODE128B=c.default,el.CODE128C=m.default,el}var jo={},Gy={},hd={},fA;function Fg(){return fA||(fA=1,Object.defineProperty(hd,"__esModule",{value:!0}),hd.SIDE_BIN="101",hd.MIDDLE_BIN="01010",hd.BINARIES={L:["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],G:["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"],R:["1110010","1100110","1101100","1000010","1011100","1001110","1010000","1000100","1001000","1110100"],O:["0001101","0011001","0010011","0111101","0100011","0110001","0101111","0111011","0110111","0001011"],E:["0100111","0110011","0011011","0100001","0011101","0111001","0000101","0010001","0001001","0010111"]},hd.EAN2_STRUCTURE=["LL","LG","GL","GG"],hd.EAN5_STRUCTURE=["GGLLL","GLGLL","GLLGL","GLLLG","LGGLL","LLGGL","LLLGG","LGLGL","LGLLG","LLGLG"],hd.EAN13_STRUCTURE=["LLLLLL","LLGLGG","LLGGLG","LLGGGL","LGLLGG","LGGLLG","LGGGLL","LGLGLG","LGLGGL","LGGLGL"]),hd}var Yy={},Qy={},gA;function Ug(){if(gA)return Qy;gA=1,Object.defineProperty(Qy,"__esModule",{value:!0});var t=Fg(),n=function(s,i,c){var l=s.split("").map(function(d,u){return t.BINARIES[i[u]]}).map(function(d,u){return d?d[s[u]]:""});if(c){var m=s.length-1;l=l.map(function(d,u){return u<m?d+c:d})}return l.join("")};return Qy.default=n,Qy}var yA;function $D(){if(yA)return Yy;yA=1,Object.defineProperty(Yy,"__esModule",{value:!0});var t=(function(){function g(p,y){for(var b=0;b<y.length;b++){var N=y[b];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(p,N.key,N)}}return function(p,y,b){return y&&g(p.prototype,y),b&&g(p,b),p}})(),n=Fg(),a=Ug(),s=l(a),i=vc(),c=l(i);function l(g){return g&&g.__esModule?g:{default:g}}function m(g,p){if(!(g instanceof p))throw new TypeError("Cannot call a class as a function")}function d(g,p){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p&&(typeof p=="object"||typeof p=="function")?p:g}function u(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof p);g.prototype=Object.create(p&&p.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),p&&(Object.setPrototypeOf?Object.setPrototypeOf(g,p):g.__proto__=p)}var f=(function(g){u(p,g);function p(y,b){m(this,p);var N=d(this,(p.__proto__||Object.getPrototypeOf(p)).call(this,y,b));return N.fontSize=!b.flat&&b.fontSize>b.width*10?b.width*10:b.fontSize,N.guardHeight=b.height+N.fontSize/2+b.textMargin,N}return t(p,[{key:"encode",value:function(){return this.options.flat?this.encodeFlat():this.encodeGuarded()}},{key:"leftText",value:function(b,N){return this.text.substr(b,N)}},{key:"leftEncode",value:function(b,N){return(0,s.default)(b,N)}},{key:"rightText",value:function(b,N){return this.text.substr(b,N)}},{key:"rightEncode",value:function(b,N){return(0,s.default)(b,N)}},{key:"encodeGuarded",value:function(){var b={fontSize:this.fontSize},N={height:this.guardHeight};return[{data:n.SIDE_BIN,options:N},{data:this.leftEncode(),text:this.leftText(),options:b},{data:n.MIDDLE_BIN,options:N},{data:this.rightEncode(),text:this.rightText(),options:b},{data:n.SIDE_BIN,options:N}]}},{key:"encodeFlat",value:function(){var b=[n.SIDE_BIN,this.leftEncode(),n.MIDDLE_BIN,this.rightEncode(),n.SIDE_BIN];return{data:b.join(""),text:this.text}}}]),p})(c.default);return Yy.default=f,Yy}var vA;function p6(){if(vA)return Gy;vA=1,Object.defineProperty(Gy,"__esModule",{value:!0});var t=(function(){function g(p,y){for(var b=0;b<y.length;b++){var N=y[b];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(p,N.key,N)}}return function(p,y,b){return y&&g(p.prototype,y),b&&g(p,b),p}})(),n=function g(p,y,b){p===null&&(p=Function.prototype);var N=Object.getOwnPropertyDescriptor(p,y);if(N===void 0){var w=Object.getPrototypeOf(p);return w===null?void 0:g(w,y,b)}else{if("value"in N)return N.value;var C=N.get;return C===void 0?void 0:C.call(b)}},a=Fg(),s=$D(),i=c(s);function c(g){return g&&g.__esModule?g:{default:g}}function l(g,p){if(!(g instanceof p))throw new TypeError("Cannot call a class as a function")}function m(g,p){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p&&(typeof p=="object"||typeof p=="function")?p:g}function d(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof p);g.prototype=Object.create(p&&p.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),p&&(Object.setPrototypeOf?Object.setPrototypeOf(g,p):g.__proto__=p)}var u=function(p){var y=p.substr(0,12).split("").map(function(b){return+b}).reduce(function(b,N,w){return w%2?b+N*3:b+N},0);return(10-y%10)%10},f=(function(g){d(p,g);function p(y,b){l(this,p),y.search(/^[0-9]{12}$/)!==-1&&(y+=u(y));
3462var N=m(this,(p.__proto__||Object.getPrototypeOf(p)).call(this,y,b));return N.lastChar=b.lastChar,N}return t(p,[{key:"valid",value:function(){return this.data.search(/^[0-9]{13}$/)!==-1&&+this.data[12]===u(this.data)}},{key:"leftText",value:function(){return n(p.prototype.__proto__||Object.getPrototypeOf(p.prototype),"leftText",this).call(this,1,6)}},{key:"leftEncode",value:function(){var b=this.data.substr(1,6),N=a.EAN13_STRUCTURE[this.data[0]];return n(p.prototype.__proto__||Object.getPrototypeOf(p.prototype),"leftEncode",this).call(this,b,N)}},{key:"rightText",value:function(){return n(p.prototype.__proto__||Object.getPrototypeOf(p.prototype),"rightText",this).call(this,7,6)}},{key:"rightEncode",value:function(){var b=this.data.substr(7,6);return n(p.prototype.__proto__||Object.getPrototypeOf(p.prototype),"rightEncode",this).call(this,b,"RRRRRR")}},{key:"encodeGuarded",value:function(){var b=n(p.prototype.__proto__||Object.getPrototypeOf(p.prototype),"encodeGuarded",this).call(this);return this.options.displayValue&&(b.unshift({data:"000000000000",text:this.text.substr(0,1),options:{textAlign:"left",fontSize:this.fontSize}}),this.options.lastChar&&(b.push({data:"00"}),b.push({data:"00000",text:this.options.lastChar,options:{fontSize:this.fontSize}}))),b}}]),p})(i.default);return Gy.default=f,Gy}var Jy={},bA;function f6(){if(bA)return Jy;bA=1,Object.defineProperty(Jy,"__esModule",{value:!0});var t=(function(){function f(g,p){for(var y=0;y<p.length;y++){var b=p[y];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(g,b.key,b)}}return function(g,p,y){return p&&f(g.prototype,p),y&&f(g,y),g}})(),n=function f(g,p,y){g===null&&(g=Function.prototype);var b=Object.getOwnPropertyDescriptor(g,p);if(b===void 0){var N=Object.getPrototypeOf(g);return N===null?void 0:f(N,p,y)}else{if("value"in b)return b.value;var w=b.get;return w===void 0?void 0:w.call(y)}},a=$D(),s=i(a);function i(f){return f&&f.__esModule?f:{default:f}}function c(f,g){if(!(f instanceof g))throw new TypeError("Cannot call a class as a function")}function l(f,g){if(!f)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return g&&(typeof g=="object"||typeof g=="function")?g:f}function m(f,g){if(typeof g!="function"&&g!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof g);f.prototype=Object.create(g&&g.prototype,{constructor:{value:f,enumerable:!1,writable:!0,configurable:!0}}),g&&(Object.setPrototypeOf?Object.setPrototypeOf(f,g):f.__proto__=g)}var d=function(g){var p=g.substr(0,7).split("").map(function(y){return+y}).reduce(function(y,b,N){return N%2?y+b:y+b*3},0);return(10-p%10)%10},u=(function(f){m(g,f);function g(p,y){return c(this,g),p.search(/^[0-9]{7}$/)!==-1&&(p+=d(p)),l(this,(g.__proto__||Object.getPrototypeOf(g)).call(this,p,y))}return t(g,[{key:"valid",value:function(){return this.data.search(/^[0-9]{8}$/)!==-1&&+this.data[7]===d(this.data)}},{key:"leftText",value:function(){return n(g.prototype.__proto__||Object.getPrototypeOf(g.prototype),"leftText",this).call(this,0,4)}},{key:"leftEncode",value:function(){var y=this.data.substr(0,4);return n(g.prototype.__proto__||Object.getPrototypeOf(g.prototype),"leftEncode",this).call(this,y,"LLLL")}},{key:"rightText",value:function(){return n(g.prototype.__proto__||Object.getPrototypeOf(g.prototype),"rightText",this).call(this,4,4)}},{key:"rightEncode",value:function(){var y=this.data.substr(4,4);return n(g.prototype.__proto__||Object.getPrototypeOf(g.prototype),"rightEncode",this).call(this,y,"RRRR")}}]),g})(s.default);return Jy.default=u,Jy}var Ky={},xA;function g6(){if(xA)return Ky;xA=1,Object.defineProperty(Ky,"__esModule",{value:!0});var t=(function(){function p(y,b){for(var N=0;N<b.length;N++){var w=b[N];w.enumerable=w.enumerable||!1,w.configurable=!0,"value"in w&&(w.writable=!0),Object.defineProperty(y,w.key,w)}}return function(y,b,N){return b&&p(y.prototype,b),N&&p(y,N),y}})(),n=Fg(),a=Ug(),s=l(a),i=vc(),c=l(i);function l(p){return p&&p.__esModule?p:{default:p}}function m(p,y){if(!(p instanceof y))throw new TypeError("Cannot call a class as a function")}
3462function d(p,y){if(!p)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return y&&(typeof y=="object"||typeof y=="function")?y:p}function u(p,y){if(typeof y!="function"&&y!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof y);p.prototype=Object.create(y&&y.prototype,{constructor:{value:p,enumerable:!1,writable:!0,configurable:!0}}),y&&(Object.setPrototypeOf?Object.setPrototypeOf(p,y):p.__proto__=y)}var f=function(y){var b=y.split("").map(function(N){return+N}).reduce(function(N,w,C){return C%2?N+w*9:N+w*3},0);return b%10},g=(function(p){u(y,p);function y(b,N){return m(this,y),d(this,(y.__proto__||Object.getPrototypeOf(y)).call(this,b,N))}return t(y,[{key:"valid",value:function(){return this.data.search(/^[0-9]{5}$/)!==-1}},{key:"encode",value:function(){var N=n.EAN5_STRUCTURE[f(this.data)];return{data:"1011"+(0,s.default)(this.data,N,"01"),text:this.text}}}]),y})(c.default);return Ky.default=g,Ky}var Xy={},jA;function y6(){if(jA)return Xy;jA=1,Object.defineProperty(Xy,"__esModule",{value:!0});var t=(function(){function g(p,y){for(var b=0;b<y.length;b++){var N=y[b];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(p,N.key,N)}}return function(p,y,b){return y&&g(p.prototype,y),b&&g(p,b),p}})(),n=Fg(),a=Ug(),s=l(a),i=vc(),c=l(i);function l(g){return g&&g.__esModule?g:{default:g}}function m(g,p){if(!(g instanceof p))throw new TypeError("Cannot call a class as a function")}function d(g,p){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p&&(typeof p=="object"||typeof p=="function")?p:g}function u(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof p);g.prototype=Object.create(p&&p.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),p&&(Object.setPrototypeOf?Object.setPrototypeOf(g,p):g.__proto__=p)}var f=(function(g){u(p,g);function p(y,b){return m(this,p),d(this,(p.__proto__||Object.getPrototypeOf(p)).call(this,y,b))}return t(p,[{key:"valid",value:function(){return this.data.search(/^[0-9]{2}$/)!==-1}},{key:"encode",value:function(){var b=n.EAN2_STRUCTURE[parseInt(this.data)%4];return{data:"1011"+(0,s.default)(this.data,b,"01"),text:this.text}}}]),p})(c.default);return Xy.default=f,Xy}var bf={},wA;function OD(){if(wA)return bf;wA=1,Object.defineProperty(bf,"__esModule",{value:!0});var t=(function(){function g(p,y){for(var b=0;b<y.length;b++){var N=y[b];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(p,N.key,N)}}return function(p,y,b){return y&&g(p.prototype,y),b&&g(p,b),p}})();bf.checksum=f;var n=Ug(),a=c(n),s=vc(),i=c(s);function c(g){return g&&g.__esModule?g:{default:g}}function l(g,p){if(!(g instanceof p))throw new TypeError("Cannot call a class as a function")}function m(g,p){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return p&&(typeof p=="object"||typeof p=="function")?p:g}function d(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof p);g.prototype=Object.create(p&&p.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),p&&(Object.setPrototypeOf?Object.setPrototypeOf(g,p):g.__proto__=p)}var u=(function(g){d(p,g);function p(y,b){l(this,p),y.search(/^[0-9]{11}$/)!==-1&&(y+=f(y));var N=m(this,(p.__proto__||Object.getPrototypeOf(p)).call(this,y,b));return N.displayValue=b.displayValue,b.fontSize>b.width*10?N.fontSize=b.width*10:N.fontSize=b.fontSize,N.guardHeight=b.height+N.fontSize/2+b.textMargin,N}return t(p,[{key:"valid",value:function(){return this.data.search(/^[0-9]{12}$/)!==-1&&this.data[11]==f(this.data)}},{key:"encode",value:function(){return this.options.flat?this.flatEncoding():this.guardedEncoding()}},{key:"flatEncoding",value:function(){var b="";return b+="101",b+=(0,a.default)(this.data.substr(0,6),"LLLLLL"),b+="01010",b+=(0,a.default)(this.data.substr(6,6),"RRRRRR"),b+="101",{data:b,text:this.text}}},{key:"guardedEncoding",value:function(){var b=[];
3462return this.displayValue&&b.push({data:"00000000",text:this.text.substr(0,1),options:{textAlign:"left",fontSize:this.fontSize}}),b.push({data:"101"+(0,a.default)(this.data[0],"L"),options:{height:this.guardHeight}}),b.push({data:(0,a.default)(this.data.substr(1,5),"LLLLL"),text:this.text.substr(1,5),options:{fontSize:this.fontSize}}),b.push({data:"01010",options:{height:this.guardHeight}}),b.push({data:(0,a.default)(this.data.substr(6,5),"RRRRR"),text:this.text.substr(6,5),options:{fontSize:this.fontSize}}),b.push({data:(0,a.default)(this.data[11],"R")+"101",options:{height:this.guardHeight}}),this.displayValue&&b.push({data:"00000000",text:this.text.substr(11,1),options:{textAlign:"right",fontSize:this.fontSize}}),b}}]),p})(i.default);function f(g){var p=0,y;for(y=1;y<11;y+=2)p+=parseInt(g[y]);for(y=0;y<11;y+=2)p+=parseInt(g[y])*3;return(10-p%10)%10}return bf.default=u,bf}var Zy={},NA;function v6(){if(NA)return Zy;NA=1,Object.defineProperty(Zy,"__esModule",{value:!0});var t=(function(){function b(N,w){for(var C=0;C<w.length;C++){var R=w[C];R.enumerable=R.enumerable||!1,R.configurable=!0,"value"in R&&(R.writable=!0),Object.defineProperty(N,R.key,R)}}return function(N,w,C){return w&&b(N.prototype,w),C&&b(N,C),N}})(),n=Ug(),a=l(n),s=vc(),i=l(s),c=OD();function l(b){return b&&b.__esModule?b:{default:b}}function m(b,N){if(!(b instanceof N))throw new TypeError("Cannot call a class as a function")}function d(b,N){if(!b)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return N&&(typeof N=="object"||typeof N=="function")?N:b}function u(b,N){if(typeof N!="function"&&N!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof N);b.prototype=Object.create(N&&N.prototype,{constructor:{value:b,enumerable:!1,writable:!0,configurable:!0}}),N&&(Object.setPrototypeOf?Object.setPrototypeOf(b,N):b.__proto__=N)}var f=["XX00000XXX","XX10000XXX","XX20000XXX","XXX00000XX","XXXX00000X","XXXXX00005","XXXXX00006","XXXXX00007","XXXXX00008","XXXXX00009"],g=[["EEEOOO","OOOEEE"],["EEOEOO","OOEOEE"],["EEOOEO","OOEEOE"],["EEOOOE","OOEEEO"],["EOEEOO","OEOOEE"],["EOOEEO","OEEOOE"],["EOOOEE","OEEEOO"],["EOEOEO","OEOEOE"],["EOEOOE","OEOEEO"],["EOOEOE","OEEOEO"]],p=(function(b){u(N,b);function N(w,C){m(this,N);var R=d(this,(N.__proto__||Object.getPrototypeOf(N)).call(this,w,C));if(R.isValid=!1,w.search(/^[0-9]{6}$/)!==-1)R.middleDigits=w,R.upcA=y(w,"0"),R.text=C.text||""+R.upcA[0]+w+R.upcA[R.upcA.length-1],R.isValid=!0;else if(w.search(/^[01][0-9]{7}$/)!==-1)if(R.middleDigits=w.substring(1,w.length-1),R.upcA=y(R.middleDigits,w[0]),R.upcA[R.upcA.length-1]===w[w.length-1])R.isValid=!0;else return d(R);else return d(R);return R.displayValue=C.displayValue,C.fontSize>C.width*10?R.fontSize=C.width*10:R.fontSize=C.fontSize,R.guardHeight=C.height+R.fontSize/2+C.textMargin,R}return t(N,[{key:"valid",value:function(){return this.isValid}},{key:"encode",value:function(){return this.options.flat?this.flatEncoding():this.guardedEncoding()}},{key:"flatEncoding",value:function(){var C="";return C+="101",C+=this.encodeMiddleDigits(),C+="010101",{data:C,text:this.text}}},{key:"guardedEncoding",value:function(){var C=[];return this.displayValue&&C.push({data:"00000000",text:this.text[0],options:{textAlign:"left",fontSize:this.fontSize}}),C.push({data:"101",options:{height:this.guardHeight}}),C.push({data:this.encodeMiddleDigits(),text:this.text.substring(1,7),options:{fontSize:this.fontSize}}),C.push({data:"010101",options:{height:this.guardHeight}}),this.displayValue&&C.push({data:"00000000",text:this.text[7],options:{textAlign:"right",fontSize:this.fontSize}}),C}},{key:"encodeMiddleDigits",value:function(){var C=this.upcA[0],R=this.upcA[this.upcA.length-1],I=g[parseInt(R)][parseInt(C)];return(0,a.default)(this.middleDigits,I)}}]),N})(i.default);function y(b,N){for(var w=parseInt(b[b.length-1]),C=f[w],R="",I=0,_=0;_<C.length;_++){var J=C[_];J==="X"?R+=b[I++]:R+=J}return R=""+N+R,""+R+(0,c.checksum)(R)}return Zy.default=p,Zy}var SA;function b6(){if(SA)return jo;SA=1,Object.defineProperty(jo,"__esModule",{value:!0}),jo.UPCE=jo.UPC=jo.EAN2=jo.EAN5=jo.EAN8=jo.EAN13=void 0;var t=p6(),n=p(t),a=f6(),s=p(a),i=g6(),c=p(i),l=y6(),m=p(l),d=OD(),u=p(d),f=v6(),g=p(f);function p(y){return y&&y.__esModule?y:{default:y}}return jo.EAN13=n.default,jo.EAN8=s.default,jo.EAN5=c.default,jo.EAN2=m.default,jo.UPC=u.default,jo.UPCE=g.default,jo}var ch={},ev={},Tm={},CA;
3462function x6(){return CA||(CA=1,Object.defineProperty(Tm,"__esModule",{value:!0}),Tm.START_BIN="1010",Tm.END_BIN="11101",Tm.BINARIES=["00110","10001","01001","11000","00101","10100","01100","00011","10010","01010"]),Tm}var AA;function LD(){if(AA)return ev;AA=1,Object.defineProperty(ev,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=x6(),a=vc(),s=i(a);function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(){return c(this,f),l(this,(f.__proto__||Object.getPrototypeOf(f)).apply(this,arguments))}return t(f,[{key:"valid",value:function(){return this.data.search(/^([0-9]{2})+$/)!==-1}},{key:"encode",value:function(){var p=this,y=this.data.match(/.{2}/g).map(function(b){return p.encodePair(b)}).join("");return{data:n.START_BIN+y+n.END_BIN,text:this.text}}},{key:"encodePair",value:function(p){var y=n.BINARIES[p[1]];return n.BINARIES[p[0]].split("").map(function(b,N){return(b==="1"?"111":"1")+(y[N]==="1"?"000":"0")}).join("")}}]),f})(s.default);return ev.default=d,ev}var tv={},IA;function j6(){if(IA)return tv;IA=1,Object.defineProperty(tv,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=LD(),a=s(n);function s(u){return u&&u.__esModule?u:{default:u}}function i(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function c(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function l(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var m=function(f){var g=f.substr(0,13).split("").map(function(p){return parseInt(p,10)}).reduce(function(p,y,b){return p+y*(3-b%2*2)},0);return Math.ceil(g/10)*10-g},d=(function(u){l(f,u);function f(g,p){return i(this,f),g.search(/^[0-9]{13}$/)!==-1&&(g+=m(g)),c(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,g,p))}return t(f,[{key:"valid",value:function(){return this.data.search(/^[0-9]{14}$/)!==-1&&+this.data[13]===m(this.data)}}]),f})(a.default);return tv.default=d,tv}var _A;function w6(){if(_A)return ch;_A=1,Object.defineProperty(ch,"__esModule",{value:!0}),ch.ITF14=ch.ITF=void 0;var t=LD(),n=i(t),a=j6(),s=i(a);function i(c){return c&&c.__esModule?c:{default:c}}return ch.ITF=n.default,ch.ITF14=s.default,ch}var ic={},nv={},kA;function zg(){if(kA)return nv;kA=1,Object.defineProperty(nv,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=vc(),a=s(n);function s(u){return u&&u.__esModule?u:{default:u}}function i(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function c(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function l(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var m=(function(u){l(f,u);function f(g,p){return i(this,f),c(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,g,p))}return t(f,[{key:"encode",value:function(){for(var p="110",y=0;y<this.data.length;y++){var b=parseInt(this.data[y]),N=b.toString(2);N=d(N,4-N.length);for(var w=0;w<N.length;w++)p+=N[w]=="0"?"100":"110"}return p+="1001",{data:p,text:this.text}}},{key:"valid",value:function(){return this.data.search(/^[0-9]+$/)!==-1}}]),f})(a.default);function d(u,f){for(var g=0;g<f;g++)u="0"+u;return u}return nv.default=m,nv}var av={},xf={},DA;function lx(){if(DA)return xf;
3462DA=1,Object.defineProperty(xf,"__esModule",{value:!0}),xf.mod10=t,xf.mod11=n;function t(a){for(var s=0,i=0;i<a.length;i++){var c=parseInt(a[i]);(i+a.length)%2===0?s+=c:s+=c*2%10+Math.floor(c*2/10)}return(10-s%10)%10}function n(a){for(var s=0,i=[2,3,4,5,6,7],c=0;c<a.length;c++){var l=parseInt(a[a.length-1-c]);s+=i[c%i.length]*l}return(11-s%11)%11}return xf}var EA;function N6(){if(EA)return av;EA=1,Object.defineProperty(av,"__esModule",{value:!0});var t=zg(),n=s(t),a=lx();function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){return i(this,u),c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f+(0,a.mod10)(f),g))}return u})(n.default);return av.default=m,av}var sv={},PA;function S6(){if(PA)return sv;PA=1,Object.defineProperty(sv,"__esModule",{value:!0});var t=zg(),n=s(t),a=lx();function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){return i(this,u),c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f+(0,a.mod11)(f),g))}return u})(n.default);return sv.default=m,sv}var rv={},RA;function C6(){if(RA)return rv;RA=1,Object.defineProperty(rv,"__esModule",{value:!0});var t=zg(),n=s(t),a=lx();function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){return i(this,u),f+=(0,a.mod10)(f),f+=(0,a.mod10)(f),c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f,g))}return u})(n.default);return rv.default=m,rv}var iv={},TA;function A6(){if(TA)return iv;TA=1,Object.defineProperty(iv,"__esModule",{value:!0});var t=zg(),n=s(t),a=lx();function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){return i(this,u),f+=(0,a.mod11)(f),f+=(0,a.mod10)(f),c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f,g))}return u})(n.default);return iv.default=m,iv}var MA;function I6(){if(MA)return ic;MA=1,Object.defineProperty(ic,"__esModule",{value:!0}),ic.MSI1110=ic.MSI1010=ic.MSI11=ic.MSI10=ic.MSI=void 0;var t=zg(),n=f(t),a=N6(),s=f(a),i=S6(),c=f(i),l=C6(),m=f(l),d=A6(),u=f(d);function f(g){return g&&g.__esModule?g:{default:g}}return ic.MSI=n.default,ic.MSI10=s.default,ic.MSI11=c.default,ic.MSI1010=m.default,ic.MSI1110=u.default,ic}var jf={},$A;
3462function _6(){if($A)return jf;$A=1,Object.defineProperty(jf,"__esModule",{value:!0}),jf.pharmacode=void 0;var t=(function(){function d(u,f){for(var g=0;g<f.length;g++){var p=f[g];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(u,p.key,p)}}return function(u,f,g){return f&&d(u.prototype,f),g&&d(u,g),u}})(),n=vc(),a=s(n);function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){i(this,u);var p=c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f,g));return p.number=parseInt(f,10),p}return t(u,[{key:"encode",value:function(){for(var g=this.number,p="";!isNaN(g)&&g!=0;)g%2===0?(p="11100"+p,g=(g-2)/2):(p="100"+p,g=(g-1)/2);return p=p.slice(0,-2),{data:p,text:this.text}}},{key:"valid",value:function(){return this.number>=3&&this.number<=131070}}]),u})(a.default);return jf.pharmacode=m,jf}var wf={},OA;function k6(){if(OA)return wf;OA=1,Object.defineProperty(wf,"__esModule",{value:!0}),wf.codabar=void 0;var t=(function(){function d(u,f){for(var g=0;g<f.length;g++){var p=f[g];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(u,p.key,p)}}return function(u,f,g){return f&&d(u.prototype,f),g&&d(u,g),u}})(),n=vc(),a=s(n);function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){i(this,u),f.search(/^[0-9\-\$\:\.\+\/]+$/)===0&&(f="A"+f+"A");var p=c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f.toUpperCase(),g));return p.text=p.options.text||p.text.replace(/[A-D]/g,""),p}return t(u,[{key:"valid",value:function(){return this.data.search(/^[A-D][0-9\-\$\:\.\+\/]+[A-D]$/)!==-1}},{key:"encode",value:function(){for(var g=[],p=this.getEncodings(),y=0;y<this.data.length;y++)g.push(p[this.data.charAt(y)]),y!==this.data.length-1&&g.push("0");return{text:this.text,data:g.join("")}}},{key:"getEncodings",value:function(){return{0:"101010011",1:"101011001",2:"101001011",3:"110010101",4:"101101001",5:"110101001",6:"100101011",7:"100101101",8:"100110101",9:"110100101","-":"101001101",$:"101100101",":":"1101011011","/":"1101101011",".":"1101101101","+":"1011011011",A:"1011001001",B:"1001001011",C:"1010010011",D:"1010011001"}}}]),u})(a.default);return wf.codabar=m,wf}var lh={},ov={},Mm={},LA;function D6(){return LA||(LA=1,Object.defineProperty(Mm,"__esModule",{value:!0}),Mm.SYMBOLS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","-","."," ","$","/","+","%","($)","(%)","(/)","(+)","ÿ"],Mm.BINARIES=["100010100","101001000","101000100","101000010","100101000","100100100","100100010","101010000","100010010","100001010","110101000","110100100","110100010","110010100","110010010","110001010","101101000","101100100","101100010","100110100","100011010","101011000","101001100","101000110","100101100","100010110","110110100","110110010","110101100","110100110","110010110","110011010","101101100","101100110","100110110","100111010","100101110","111010100","111010010","111001010","101101110","101110110","110101110","100100110","111011010","111010110","100110010","101011110"],Mm.MULTI_SYMBOLS={"\0":["(%)","U"],"�":["($)","A"],"�":["($)","B"],"�":["($)","C"],"�":["($)","D"],"�":["($)","E"],"�":["($)","F"],"\x07":["($)","G"],"\b":["($)","H"]," ":["($)","I"],"\n":["($)","J"],"\v":["($)","K"],"\f":["($)","L"],"\r":["($)","M"],"�":["($)","N"],"�":["($)","O"],"�":["($)","P"],"�":["($)","Q"],"�":["($)","R"],"�":["($)","S"],"�":["($)","T"],"�":["($)","U"],"�":["($)","V"],"�":["($)","W"],"�":["($)","X"],"�":["($)","Y"],"�":["($)","Z"],"\x1B":["(%)","A"],"�":["(%)","B"],"�":["(%)","C"],"�":["(%)","D"],"�":["(%)","E"],"!":["(/)","A"],'"':["(/)","B"],"#":["(/)","C"],"&":["(/)","F"],"'"
3462:["(/)","G"],"(":["(/)","H"],")":["(/)","I"],"*":["(/)","J"],",":["(/)","L"],":":["(/)","Z"],";":["(%)","F"],"<":["(%)","G"],"=":["(%)","H"],">":["(%)","I"],"?":["(%)","J"],"@":["(%)","V"],"[":["(%)","K"],"\\":["(%)","L"],"]":["(%)","M"],"^":["(%)","N"],_:["(%)","O"],"`":["(%)","W"],a:["(+)","A"],b:["(+)","B"],c:["(+)","C"],d:["(+)","D"],e:["(+)","E"],f:["(+)","F"],g:["(+)","G"],h:["(+)","H"],i:["(+)","I"],j:["(+)","J"],k:["(+)","K"],l:["(+)","L"],m:["(+)","M"],n:["(+)","N"],o:["(+)","O"],p:["(+)","P"],q:["(+)","Q"],r:["(+)","R"],s:["(+)","S"],t:["(+)","T"],u:["(+)","U"],v:["(+)","V"],w:["(+)","W"],x:["(+)","X"],y:["(+)","Y"],z:["(+)","Z"],"{":["(%)","P"],"|":["(%)","Q"],"}":["(%)","R"],"~":["(%)","S"],"�":["(%)","T"]}),Mm}var BA;function BD(){if(BA)return ov;BA=1,Object.defineProperty(ov,"__esModule",{value:!0});var t=(function(){function u(f,g){for(var p=0;p<g.length;p++){var y=g[p];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(f,y.key,y)}}return function(f,g,p){return g&&u(f.prototype,g),p&&u(f,p),f}})(),n=D6(),a=vc(),s=i(a);function i(u){return u&&u.__esModule?u:{default:u}}function c(u,f){if(!(u instanceof f))throw new TypeError("Cannot call a class as a function")}function l(u,f){if(!u)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f&&(typeof f=="object"||typeof f=="function")?f:u}function m(u,f){if(typeof f!="function"&&f!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof f);u.prototype=Object.create(f&&f.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),f&&(Object.setPrototypeOf?Object.setPrototypeOf(u,f):u.__proto__=f)}var d=(function(u){m(f,u);function f(g,p){return c(this,f),l(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,g,p))}return t(f,[{key:"valid",value:function(){return/^[0-9A-Z\-. $/+%]+$/.test(this.data)}},{key:"encode",value:function(){var p=this.data.split("").flatMap(function(w){return n.MULTI_SYMBOLS[w]||w}),y=p.map(function(w){return f.getEncoding(w)}).join(""),b=f.checksum(p,20),N=f.checksum(p.concat(b),15);return{text:this.text,data:f.getEncoding("ÿ")+y+f.getEncoding(b)+f.getEncoding(N)+f.getEncoding("ÿ")+"1"}}}],[{key:"getEncoding",value:function(p){return n.BINARIES[f.symbolValue(p)]}},{key:"getSymbol",value:function(p){return n.SYMBOLS[p]}},{key:"symbolValue",value:function(p){return n.SYMBOLS.indexOf(p)}},{key:"checksum",value:function(p,y){var b=p.slice().reverse().reduce(function(N,w,C){var R=C%y+1;return N+f.symbolValue(w)*R},0);return f.getSymbol(b%47)}}]),f})(s.default);return ov.default=d,ov}var cv={},FA;function E6(){if(FA)return cv;FA=1,Object.defineProperty(cv,"__esModule",{value:!0});var t=(function(){function d(u,f){for(var g=0;g<f.length;g++){var p=f[g];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(u,p.key,p)}}return function(u,f,g){return f&&d(u.prototype,f),g&&d(u,g),u}})(),n=BD(),a=s(n);function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){return i(this,u),c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f,g))}return t(u,[{key:"valid",value:function(){return/^[\x00-\x7f]+$/.test(this.data)}}]),u})(a.default);return cv.default=m,cv}var UA;function P6(){if(UA)return lh;UA=1,Object.defineProperty(lh,"__esModule",{value:!0}),lh.CODE93FullASCII=lh.CODE93=void 0;var t=BD(),n=i(t),a=E6(),s=i(a);function i(c){return c&&c.__esModule?c:{default:c}}return lh.CODE93=n.default,lh.CODE93FullASCII=s.default,lh}var Nf={},zA;function R6(){if(zA)return Nf;
3462zA=1,Object.defineProperty(Nf,"__esModule",{value:!0}),Nf.GenericBarcode=void 0;var t=(function(){function d(u,f){for(var g=0;g<f.length;g++){var p=f[g];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(u,p.key,p)}}return function(u,f,g){return f&&d(u.prototype,f),g&&d(u,g),u}})(),n=vc(),a=s(n);function s(d){return d&&d.__esModule?d:{default:d}}function i(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}function c(d,u){if(!d)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return u&&(typeof u=="object"||typeof u=="function")?u:d}function l(d,u){if(typeof u!="function"&&u!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof u);d.prototype=Object.create(u&&u.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),u&&(Object.setPrototypeOf?Object.setPrototypeOf(d,u):d.__proto__=u)}var m=(function(d){l(u,d);function u(f,g){return i(this,u),c(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,f,g))}return t(u,[{key:"encode",value:function(){return{data:"10101010101010101010101010101010101010101",text:this.text}}},{key:"valid",value:function(){return!0}}]),u})(a.default);return Nf.GenericBarcode=m,Nf}var qA;function T6(){if(qA)return By;qA=1,Object.defineProperty(By,"__esModule",{value:!0});var t=o6(),n=m6(),a=b6(),s=w6(),i=I6(),c=_6(),l=k6(),m=P6(),d=R6();return By.default={CODE39:t.CODE39,CODE128:n.CODE128,CODE128A:n.CODE128A,CODE128B:n.CODE128B,CODE128C:n.CODE128C,EAN13:a.EAN13,EAN8:a.EAN8,EAN5:a.EAN5,EAN2:a.EAN2,UPC:a.UPC,UPCE:a.UPCE,ITF14:s.ITF14,ITF:s.ITF,MSI:i.MSI,MSI10:i.MSI10,MSI11:i.MSI11,MSI1010:i.MSI1010,MSI1110:i.MSI1110,pharmacode:c.pharmacode,codabar:l.codabar,CODE93:m.CODE93,CODE93FullASCII:m.CODE93FullASCII,GenericBarcode:d.GenericBarcode},By}var lv={},VA;function dx(){if(VA)return lv;
3462VA=1,Object.defineProperty(lv,"__esModule",{value:!0});var t=Object.assign||function(n){for(var a=1;a<arguments.length;a++){var s=arguments[a];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(n[i]=s[i])}return n};return lv.default=function(n,a){return t({},n,a)},lv}var dv={},HA;function M6(){if(HA)return dv;HA=1,Object.defineProperty(dv,"__esModule",{value:!0}),dv.default=t;function t(n){var a=[];function s(i){if(Array.isArray(i))for(var c=0;c<i.length;c++)s(i[c]);else i.text=i.text||"",i.data=i.data||"",a.push(i)}return s(n),a}return dv}var uv={},WA;function $6(){if(WA)return uv;WA=1,Object.defineProperty(uv,"__esModule",{value:!0}),uv.default=t;function t(n){return n.marginTop=n.marginTop||n.margin,n.marginBottom=n.marginBottom||n.margin,n.marginRight=n.marginRight||n.margin,n.marginLeft=n.marginLeft||n.margin,n}return uv}var hv={},mv={},pv={},GA;function FD(){if(GA)return pv;GA=1,Object.defineProperty(pv,"__esModule",{value:!0}),pv.default=t;function t(n){var a=["width","height","textMargin","fontSize","margin","marginTop","marginBottom","marginLeft","marginRight"];for(var s in a)a.hasOwnProperty(s)&&(s=a[s],typeof n[s]=="string"&&(n[s]=parseInt(n[s],10)));return typeof n.displayValue=="string"&&(n.displayValue=n.displayValue!="false"),n}return pv}var fv={},YA;function UD(){if(YA)return fv;YA=1,Object.defineProperty(fv,"__esModule",{value:!0});var t={width:2,height:100,format:"auto",displayValue:!0,fontOptions:"",font:"monospace",text:void 0,textAlign:"center",textPosition:"bottom",textMargin:2,fontSize:20,background:"#ffffff",lineColor:"#000000",margin:10,marginTop:void 0,marginBottom:void 0,marginLeft:void 0,marginRight:void 0,valid:function(){}};return fv.default=t,fv}var QA;function O6(){if(QA)return mv;QA=1,Object.defineProperty(mv,"__esModule",{value:!0});var t=FD(),n=i(t),a=UD(),s=i(a);function i(l){return l&&l.__esModule?l:{default:l}}function c(l){var m={};for(var d in s.default)s.default.hasOwnProperty(d)&&(l.hasAttribute("jsbarcode-"+d.toLowerCase())&&(m[d]=l.getAttribute("jsbarcode-"+d.toLowerCase())),l.hasAttribute("data-"+d.toLowerCase())&&(m[d]=l.getAttribute("data-"+d.toLowerCase())));return m.value=l.getAttribute("jsbarcode-value")||l.getAttribute("data-value"),m=(0,n.default)(m),m}return mv.default=c,mv}var gv={},yv={},oc={},JA;function zD(){if(JA)return oc;JA=1,Object.defineProperty(oc,"__esModule",{value:!0}),oc.getTotalWidthOfEncodings=oc.calculateEncodingAttributes=oc.getBarcodePadding=oc.getEncodingHeight=oc.getMaximumHeightOfEncodings=void 0;var t=dx(),n=a(t);function a(u){return u&&u.__esModule?u:{default:u}}function s(u,f){return f.height+(f.displayValue&&u.text.length>0?f.fontSize+f.textMargin:0)+f.marginTop+f.marginBottom}function i(u,f,g){if(g.displayValue&&f<u){if(g.textAlign=="center")return Math.floor((u-f)/2);if(g.textAlign=="left")return 0;if(g.textAlign=="right")return Math.floor(u-f)}return 0}function c(u,f,g){for(var p=0;p<u.length;p++){var y=u[p],b=(0,n.default)(f,y.options),N;b.displayValue?N=d(y.text,b,g):N=0;var w=y.data.length*b.width;y.width=Math.ceil(Math.max(N,w)),y.height=s(y,b),y.barcodePadding=i(N,w,b)}}function l(u){for(var f=0,g=0;g<u.length;g++)f+=u[g].width;return f}function m(u){for(var f=0,g=0;g<u.length;g++)u[g].height>f&&(f=u[g].height);return f}function d(u,f,g){var p;if(g)p=g;else if(typeof document<"u")p=document.createElement("canvas").getContext("2d");else return 0;p.font=f.fontOptions+" "+f.fontSize+"px "+f.font;var y=p.measureText(u);if(!y)return 0;var b=y.width;return b}return oc.getMaximumHeightOfEncodings=m,oc.getEncodingHeight=s,oc.getBarcodePadding=i,oc.calculateEncodingAttributes=c,oc.getTotalWidthOfEncodings=l,oc}var KA;function L6(){if(KA)return yv;KA=1,Object.defineProperty(yv,"__esModule",{value:!0});var t=(function(){function m(d,u){for(var f=0;f<u.length;f++){var g=u[f];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(d,g.key,g)}}return function(d,u,f){return u&&m(d.prototype,u),f&&m(d,f),d}})(),n=dx(),a=i(n),s=zD();function i(m){return m&&m.__esModule?m:{default:m}}function c(m,d){if(!(m instanceof d))throw new TypeError("Cannot call a class as a function")}var l=(function(){function m(d,u,f){c(this,m),this.canvas=d,this.encodings=u,this.options=f}return t(m,[{key:"render",value:function(){if(!this.canvas.getContext)throw new Error("The browser does not support canvas.");this.prepareCanvas();for(var u=0;u<this.encodings.length;u++){var f=(0,a.default)(this.options,this.encodings[u].options);this.drawCanvasBarcode(f,this.encodings[u]),this.drawCanvasText(f,this.encodings[u]),this.moveCanvasDrawing(this.encodings[u])}this.restoreCanvas()}},{key:"prepareCanvas",value:function(){var u=this.canvas.getContext("2d");u.save(),(0,s.calculateEncodingAttributes)(this.encodings,this.options,u);var f=(0,s.getTotalWidthOfEncodings)(this.encodings),g=(0,s.getMaximumHeightOfEncodings)(this.encodings);this.canvas.width=f+this.options.marginLeft+this.options.marginRight,this.canvas.height=g,u.clearRect(0,0,this.canvas.width,this.canvas.height),this.options.background&&(u.fillStyle=this.options.background,u.fillRect(0,0,this.canvas.width,this.canvas.height)),u.translate(this.options.marginLeft,0)}},{key:"drawCanvasBarcode",value:function(u,f){var g=this.canvas.getContext("2d"),p=f.data,y;u.textPosition=="top"?y=u.marginTop+u.fontSize+u.textMargin:y=u.marginTop,g.fillStyle=u.lineColor;for(var b=0;b<p.length;b++){var N=b*u.width+f.barcodePadding;p[b]==="1"?g.fillRect(N,y,u.width,u.height):p[b]&&g.fillRect(N,y,u.width,u.height*p[b])}}},{key:"drawCanvasText",value:function(u,f){var g=this.canvas.getContext("2d"),p=u.fontOptions+" "+u.fontSize+"px "+u.font;if(u.displayValue){var y,b;u.textPosition=="top"?b=u.marginTop+u.fontSize-u.textMargin:b=u.height+u.textMargin+u.marginTop+u.fontSize,g.font=p,u.textAlign=="left"||f.barcodePadding>0?(y=0,g.textAlign="left"):u.textAlign=="right"?(y=f.width-1,g.textAlign="right"):(y=f.width/2,g.textAlign="center"),g.fillText(f.text,y,b)}}},{key:"moveCanvasDrawing",value:function(u){var f=this.canvas.getContext("2d");f.translate(u.width,0)}},{key:"restoreCanvas",value:function(){var u=this.canvas.getContext("2d");
3462u.restore()}}]),m})();return yv.default=l,yv}var vv={},XA;function B6(){if(XA)return vv;XA=1,Object.defineProperty(vv,"__esModule",{value:!0});var t=(function(){function d(u,f){for(var g=0;g<f.length;g++){var p=f[g];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(u,p.key,p)}}return function(u,f,g){return f&&d(u.prototype,f),g&&d(u,g),u}})(),n=dx(),a=i(n),s=zD();function i(d){return d&&d.__esModule?d:{default:d}}function c(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}var l="http://www.w3.org/2000/svg",m=(function(){function d(u,f,g){c(this,d),this.svg=u,this.encodings=f,this.options=g,this.document=g.xmlDocument||document}return t(d,[{key:"render",value:function(){var f=this.options.marginLeft;this.prepareSVG();for(var g=0;g<this.encodings.length;g++){var p=this.encodings[g],y=(0,a.default)(this.options,p.options),b=this.createGroup(f,y.marginTop,this.svg);this.setGroupOptions(b,y),this.drawSvgBarcode(b,y,p),this.drawSVGText(b,y,p),f+=p.width}}},{key:"prepareSVG",value:function(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);(0,s.calculateEncodingAttributes)(this.encodings,this.options);var f=(0,s.getTotalWidthOfEncodings)(this.encodings),g=(0,s.getMaximumHeightOfEncodings)(this.encodings),p=f+this.options.marginLeft+this.options.marginRight;this.setSvgAttributes(p,g),this.options.background&&this.drawRect(0,0,p,g,this.svg).setAttribute("fill",this.options.background)}},{key:"drawSvgBarcode",value:function(f,g,p){var y=p.data,b;g.textPosition=="top"?b=g.fontSize+g.textMargin:b=0;for(var N=0,w=0,C=0;C<y.length;C++)w=C*g.width+p.barcodePadding,y[C]==="1"?N++:N>0&&(this.drawRect(w-g.width*N,b,g.width*N,g.height,f),N=0);N>0&&this.drawRect(w-g.width*(N-1),b,g.width*N,g.height,f)}},{key:"drawSVGText",value:function(f,g,p){var y=this.document.createElementNS(l,"text");if(g.displayValue){var b,N;y.setAttribute("font-family",g.font),y.setAttribute("font-size",g.fontSize),g.fontOptions.includes("bold")&&y.setAttribute("font-weight","bold"),g.fontOptions.includes("italic")&&y.setAttribute("font-style","italic"),g.textPosition=="top"?N=g.fontSize-g.textMargin:N=g.height+g.textMargin+g.fontSize,g.textAlign=="left"||p.barcodePadding>0?(b=0,y.setAttribute("text-anchor","start")):g.textAlign=="right"?(b=p.width-1,y.setAttribute("text-anchor","end")):(b=p.width/2,y.setAttribute("text-anchor","middle")),y.setAttribute("x",b),y.setAttribute("y",N),y.appendChild(this.document.createTextNode(p.text)),f.appendChild(y)}}},{key:"setSvgAttributes",value:function(f,g){var p=this.svg;p.setAttribute("width",f+"px"),p.setAttribute("height",g+"px"),p.setAttribute("x","0px"),p.setAttribute("y","0px"),p.setAttribute("viewBox","0 0 "+f+" "+g),p.setAttribute("xmlns",l),p.setAttribute("version","1.1")}},{key:"createGroup",value:function(f,g,p){var y=this.document.createElementNS(l,"g");return y.setAttribute("transform","translate("+f+", "+g+")"),p.appendChild(y),y}},{key:"setGroupOptions",value:function(f,g){f.setAttribute("fill",g.lineColor)}},{key:"drawRect",value:function(f,g,p,y,b){var N=this.document.createElementNS(l,"rect");return N.setAttribute("x",f),N.setAttribute("y",g),N.setAttribute("width",p),N.setAttribute("height",y),b.appendChild(N),N}}]),d})();return vv.default=m,vv}var bv={},ZA;function F6(){if(ZA)return bv;ZA=1,Object.defineProperty(bv,"__esModule",{value:!0});var t=(function(){function s(i,c){for(var l=0;l<c.length;l++){var m=c[l];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(i,m.key,m)}}return function(i,c,l){return c&&s(i.prototype,c),l&&s(i,l),i}})();function n(s,i){if(!(s instanceof i))throw new TypeError("Cannot call a class as a function")}var a=(function(){function s(i,c,l){n(this,s),this.object=i,this.encodings=c,this.options=l}return t(s,[{key:"render",value:function(){this.object.encodings=this.encodings}}]),s})();return bv.default=a,bv}var eI;function U6(){if(eI)return gv;eI=1,Object.defineProperty(gv,"__esModule",{value:!0});var t=L6(),n=l(t),a=B6(),s=l(a),i=F6(),c=l(i);
3462function l(m){return m&&m.__esModule?m:{default:m}}return gv.default={CanvasRenderer:n.default,SVGRenderer:s.default,ObjectRenderer:c.default},gv}var $m={},tI;function qD(){if(tI)return $m;tI=1,Object.defineProperty($m,"__esModule",{value:!0});function t(l,m){if(!(l instanceof m))throw new TypeError("Cannot call a class as a function")}function n(l,m){if(!l)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m&&(typeof m=="object"||typeof m=="function")?m:l}function a(l,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);l.prototype=Object.create(m&&m.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(l,m):l.__proto__=m)}var s=(function(l){a(m,l);function m(d,u){t(this,m);var f=n(this,(m.__proto__||Object.getPrototypeOf(m)).call(this));return f.name="InvalidInputException",f.symbology=d,f.input=u,f.message='"'+f.input+'" is not a valid input for '+f.symbology,f}return m})(Error),i=(function(l){a(m,l);function m(){t(this,m);var d=n(this,(m.__proto__||Object.getPrototypeOf(m)).call(this));return d.name="InvalidElementException",d.message="Not supported type to render on",d}return m})(Error),c=(function(l){a(m,l);function m(){t(this,m);var d=n(this,(m.__proto__||Object.getPrototypeOf(m)).call(this));return d.name="NoElementException",d.message="No element to render on.",d}return m})(Error);return $m.InvalidInputException=s,$m.InvalidElementException=i,$m.NoElementException=c,$m}var nI;function z6(){if(nI)return hv;nI=1,Object.defineProperty(hv,"__esModule",{value:!0});var t=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(f){return typeof f}:function(f){return f&&typeof Symbol=="function"&&f.constructor===Symbol&&f!==Symbol.prototype?"symbol":typeof f},n=O6(),a=l(n),s=U6(),i=l(s),c=qD();function l(f){return f&&f.__esModule?f:{default:f}}function m(f){if(typeof f=="string")return d(f);if(Array.isArray(f)){for(var g=[],p=0;p<f.length;p++)g.push(m(f[p]));return g}else{if(typeof HTMLCanvasElement<"u"&&f instanceof HTMLImageElement)return u(f);if(f&&f.nodeName&&f.nodeName.toLowerCase()==="svg"||typeof SVGElement<"u"&&f instanceof SVGElement)return{element:f,options:(0,a.default)(f),renderer:i.default.SVGRenderer};if(typeof HTMLCanvasElement<"u"&&f instanceof HTMLCanvasElement)return{element:f,options:(0,a.default)(f),renderer:i.default.CanvasRenderer};if(f&&f.getContext)return{element:f,renderer:i.default.CanvasRenderer};if(f&&(typeof f>"u"?"undefined":t(f))==="object"&&!f.nodeName)return{element:f,renderer:i.default.ObjectRenderer};throw new c.InvalidElementException}}function d(f){var g=document.querySelectorAll(f);if(g.length!==0){for(var p=[],y=0;y<g.length;y++)p.push(m(g[y]));return p}}function u(f){var g=document.createElement("canvas");return{element:g,options:(0,a.default)(f),renderer:i.default.CanvasRenderer,afterRender:function(){f.setAttribute("src",g.toDataURL())}}}return hv.default=m,hv}var xv={},aI;function q6(){if(aI)return xv;aI=1,Object.defineProperty(xv,"__esModule",{value:!0});var t=(function(){function s(i,c){for(var l=0;l<c.length;l++){var m=c[l];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(i,m.key,m)}}return function(i,c,l){return c&&s(i.prototype,c),l&&s(i,l),i}})();function n(s,i){if(!(s instanceof i))throw new TypeError("Cannot call a class as a function")}var a=(function(){function s(i){n(this,s),this.api=i}return t(s,[{key:"handleCatch",value:function(c){if(c.name==="InvalidInputException")if(this.api._options.valid!==this.api._defaults.valid)this.api._options.valid(!1);else throw c.message;else throw c;this.api.render=function(){}}},{key:"wrapBarcodeCall",value:function(c){try{var l=c.apply(void 0,arguments);return this.api._options.valid(!0),l}catch(m){return this.handleCatch(m),this.api}}}]),s})();return xv.default=a,xv}var J0,sI;function V6(){if(sI)return J0;sI=1;var t=T6(),n=C(t),a=dx(),s=C(a),i=M6(),c=C(i),l=$6(),m=C(l),d=z6(),u=C(d),f=FD(),g=C(f),p=q6(),y=C(p),b=qD(),N=UD(),w=C(N);function C(H){return H&&H.__esModule?H:{default:H}}var R=function(){},I=function(K,L,D){var M=new R;if(typeof K>"u")throw Error("No element to render on was provided.");return M._renderProperties=(0,u.default)(K),M._encodings=[],M._options=w.default,M._errorHandler=new y.default(M),typeof L<"u"&&(D=D||{},D.format||(D.format=G()),M.options(D)[D.format](L,D).render()),M};I.getModule=function(H){return n.default[H]};for(var _ in n.default)n.default.hasOwnProperty(_)&&J(n.default,_);function J(H,K){R.prototype[K]=R.prototype[K.toUpperCase()]=R.prototype[K.toLowerCase()]=function(L,D){var M=this;return M._errorHandler.wrapBarcodeCall(function(){D.text=typeof D.text>"u"?void 0:""+D.text;var Z=(0,s.default)(M._options,D);Z=(0,g.default)(Z);var fe=H[K],q=T(L,fe,Z);return M._encodings.push(q),M})}}function T(H,K,L){H=""+H;var D=new K(H,L);if(!D.valid())throw new b.InvalidInputException(D.constructor.name,H);var M=D.encode();M=(0,c.default)(M);for(var Z=0;Z<M.length;Z++)M[Z].options=(0,s.default)(L,M[Z].options);return M}function G(){return n.default.CODE128?"CODE128":Object.keys(n.default)[0]}R.prototype.options=function(H){return this._options=(0,s.default)(this._options,H),this},R.prototype.blank=function(H){var K=new Array(H+1).join("0");return this._encodings.push({data:K}),this},R.prototype.init=function(){if(this._renderProperties){Array.isArray(this._renderProperties)||(this._renderProperties=[this._renderProperties]);var H;for(var K in this._renderProperties){H=this._renderProperties[K];var L=(0,s.default)(this._options,H.options);L.format=="auto"&&(L.format=G()),this._errorHandler.wrapBarcodeCall(function(){var D=L.value,M=n.default[L.format.toUpperCase()],Z=T(D,M,L);z(H,Z,L)})}}},R.prototype.render=function(){if(!this._renderProperties)throw new b.NoElementException;if(Array.isArray(this._renderProperties))for(var H=0;H<this._renderProperties.length;H++)z(this._renderProperties[H],this._encodings,this._options);else z(this._renderProperties,this._encodings,this._options);return this},R.prototype._defaults=w.default;function z(H,K,L){K=(0,c.default)(K);for(var D=0;D<K.length;D++)K[D].options=(0,s.default)(L,K[D].options),(0,m.default)(K[D].options);(0,m.default)(L);var M=H.renderer,Z=new M(H.element,K,L);Z.render(),H.afterRender&&H.afterRender()}return typeof window<"u"&&(window.JsBarcode=I),typeof jQuery<"u"&&(jQuery.fn.Js
3462Barcode=function(H,K){var L=[];return jQuery(this).each(function(){L.push(this)}),I(L,H,K)}),J0=I,J0}var K0={exports:{}},X0,rI;function H6(){if(rI)return X0;rI=1;var t="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return X0=t,X0}var Z0,iI;function W6(){if(iI)return Z0;iI=1;var t=H6();function n(){}function a(){}return a.resetWarningCache=n,Z0=function(){function s(l,m,d,u,f,g){if(g!==t){var p=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw p.name="Invariant Violation",p}}s.isRequired=s;function i(){return s}var c={array:s,bigint:s,bool:s,func:s,number:s,object:s,string:s,symbol:s,any:s,arrayOf:i,element:s,elementType:s,instanceOf:i,node:s,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:a,resetWarningCache:n};return c.PropTypes=c,c},Z0}var oI;function G6(){return oI||(oI=1,K0.exports=W6()()),K0.exports}var ej,cI;function Y6(){if(cI)return ej;cI=1;function t(w){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?t=function(R){return typeof R}:t=function(R){return R&&typeof Symbol=="function"&&R.constructor===Symbol&&R!==Symbol.prototype?"symbol":typeof R},t(w)}var n=i(zb()),a=i(V6()),s=i(G6());function i(w){return w&&w.__esModule?w:{default:w}}function c(w,C){if(!(w instanceof C))throw new TypeError("Cannot call a class as a function")}function l(w,C){for(var R=0;R<C.length;R++){var I=C[R];I.enumerable=I.enumerable||!1,I.configurable=!0,"value"in I&&(I.writable=!0),Object.defineProperty(w,I.key,I)}}function m(w,C,R){return C&&l(w.prototype,C),w}function d(w,C){return C&&(t(C)==="object"||typeof C=="function")?C:f(w)}function u(w){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(R){return R.__proto__||Object.getPrototypeOf(R)},u(w)}function f(w){if(w===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return w}function g(w,C){if(typeof C!="function"&&C!==null)throw new TypeError("Super expression must either be null or a function");w.prototype=Object.create(C&&C.prototype,{constructor:{value:w,writable:!0,configurable:!0}}),C&&p(w,C)}function p(w,C){return p=Object.setPrototypeOf||function(I,_){return I.__proto__=_,I},p(w,C)}var y,b=n.default.version.split(/[.-]/);b[0]==="0"&&(b[1]==="13"||b[1]==="12")?y=function(C){return C.getDOMNode()}:y=function(C){return C};var N=(function(w){g(C,w);function C(R){var I;return c(this,C),I=d(this,u(C).call(this,R)),I.renderElementRef=n.default.createRef(),I.update=I.update.bind(f(I)),I}return m(C,[{key:"shouldComponentUpdate",value:function(I){var _=this;return Object.keys(C.propTypes).some(function(J){return _.props[J]!==I[J]})}},{key:"componentDidMount",value:function(){this.update()}},{key:"componentDidUpdate",value:function(){this.update()}},{key:"update",value:function(){var I=y(this.renderElementRef.current);try{new a.default(I,this.props.value,Object.assign({text:this.props.text||this.props.value},this.props))}catch(_){window.console.error(_)}}},{key:"render",value:function(){var I=this.props,_=I.id,J=I.className;if(this.props.renderer==="svg")return n.default.createElement("svg",{ref:this.renderElementRef,id:_,className:J});if(this.props.renderer==="canvas")return n.default.createElement("canvas",{ref:this.renderElementRef,id:_,className:J});if(this.props.renderer==="img")return n.default.createElement("img",{ref:this.renderElementRef,id:_,className:J})}}]),C})(n.default.Component);return N.propTypes={value:s.default.string.isRequired,text:s.default.string,renderer:s.default.string,format:s.default.string,width:s.default.number,height:s.default.number,displayValue:s.default.bool,fontOptions:s.default.string,font:s.default.string,textAlign:s.default.string,textPosition:s.default.string,textMargin:s.default.number,fontSize:s.default.number,background:s.default.string,lineColor:s.default.string,margin:s.default.number,marginTop:s.default.number,marginBottom:s.default.number,marginLeft:s.default.number,marginRight:s.default.number,id:s.default.string,className:s.default.string,ean128:s.default.bool},N.defaultProps={format:"CODE128",renderer:"svg",width:2,height:100,displayValue:!0,fontOptions:"",font:"monospace",textAlign:"center",textPosition:"bottom",textMargin:2,fontSize:20,background:"#ffffff",lineColor:"#000000",margin:10,className:"",ean128:!1},ej=N,ej}var Q6=Y6();const J6=Ub(Q6);var K6=Object.defineProperty,Mb=Object.getOwnPropertySymbols,VD=Object.prototype.hasOwnProperty,HD=Object.prototype.propertyIsEnumerable,lI=(t,n,a)=>n in t?K6(t,n,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[n]=a,N1=(t,n)=>{for(var a in n||(n={}))VD.call(n,a)&&lI(t,a,n[a]);if(Mb)for(var a of Mb(n))HD.call(n,a)&&lI(t,a,n[a]);return t},S1=(t,n)=>{var a={};for(var s in t)VD.call(t,s)&&n.indexOf(s)<0&&(a[s]=t[s]);if(t!=null&&Mb)for(var s of Mb(t))n.indexOf(s)<0&&HD.call(t,s)&&(a[s]=t[s]);return a};/** 3463 * @license QR Code generator library (TypeScript) 3464 * Copyright (c) Project Nayuki. 3465 * SPDX-License-Identifier: MIT 3466 */var Yh;(t=>{const n=class ks{constructor(d,u,f,g){if(this.version=d,this.errorCorrectionLevel=u,this.modules=[],this.isFunction=[],d<ks.MIN_VERSION||d>ks.MAX_VERSION)throw new RangeError("Version value out of range");if(g<-1||g>7)throw new RangeError("Mask value out of range");this.size=d*4+17;let p=[];for(let b=0;b<this.size;b++)p.push(!1);for(let b=0;b<this.size;b++)this.modules.push(p.slice()),this.isFunction.push(p.slice());this.drawFunctionPatterns();const y=this.addEccAndInterleave(f);if(this.drawCodewords(y),g==-1){let b=1e9;for(let N=0;N<8;N++){this.applyMask(N),this.drawFormatBits(N);const w=this.getPenaltyScore();w<b&&(g=N,b=w),this.applyMask(N)}}i(0<=g&&g<=7),this.mask=g,this.applyMask(g),this.drawFormatBits(g),this.isFunction=[]}static encodeText(d,u){const f=t.QrSegment.makeSegments(d);return ks.encodeSegments(f,u)}static encodeBinary(d,u){const f=t.QrSegment.makeBytes(d);return ks.encodeSegments([f],u)}static encodeSegments(d,u,f=1,g=40,p=-1,y=!0){if(!(ks.MIN_VERSION<=f&&f<=g&&g<=ks.MAX_VERSION)||p<-1||p>7)throw new RangeError("Invalid value");let b,N;for(b=f;;b++){const I=ks.getNumDataCodewords(b,u)*8,_=l.getTotalBits(d,b);if(_<=I){N=_;break}if(b>=g)throw new RangeError("Data too long")}for(const I of[ks.Ecc.MEDIUM,ks.Ecc.QUARTILE,ks.Ecc.HIGH])y&&N<=ks.getNumDataCodewords(b,I)*8&&(u=I);let w=[];for(const I of d){a(I.mode.modeBits,4,w),a(I.numChars,I.mode.numCharCountBits(b),w);for(const _ of I.getData())w.push(_)}i(w.length==N);const C=ks.getNumDataCodewords(b,u)*8;i(w.length<=C),a(0,Math.min(4,C-w.length),w),a(0,(8-w.length%8)%8,w),i(w.length%8==0);for(let I=236;w.length<C;I^=253)a(I,8,w);let R=[];for(;R.length*8<w.length;)R.push(0);
vendor: 7,667 bytes, line 3466
3466return w.forEach((I,_)=>R[_>>>3]|=I<<7-(_&7)),new ks(b,u,R,p)}getModule(d,u){return 0<=d&&d<this.size&&0<=u&&u<this.size&&this.modules[u][d]}getModules(){return this.modules}drawFunctionPatterns(){for(let f=0;f<this.size;f++)this.setFunctionModule(6,f,f%2==0),this.setFunctionModule(f,6,f%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const d=this.getAlignmentPatternPositions(),u=d.length;for(let f=0;f<u;f++)for(let g=0;g<u;g++)f==0&&g==0||f==0&&g==u-1||f==u-1&&g==0||this.drawAlignmentPattern(d[f],d[g]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(d){const u=this.errorCorrectionLevel.formatBits<<3|d;let f=u;for(let p=0;p<10;p++)f=f<<1^(f>>>9)*1335;const g=(u<<10|f)^21522;i(g>>>15==0);for(let p=0;p<=5;p++)this.setFunctionModule(8,p,s(g,p));this.setFunctionModule(8,7,s(g,6)),this.setFunctionModule(8,8,s(g,7)),this.setFunctionModule(7,8,s(g,8));for(let p=9;p<15;p++)this.setFunctionModule(14-p,8,s(g,p));for(let p=0;p<8;p++)this.setFunctionModule(this.size-1-p,8,s(g,p));for(let p=8;p<15;p++)this.setFunctionModule(8,this.size-15+p,s(g,p));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let d=this.version;for(let f=0;f<12;f++)d=d<<1^(d>>>11)*7973;const u=this.version<<12|d;i(u>>>18==0);for(let f=0;f<18;f++){const g=s(u,f),p=this.size-11+f%3,y=Math.floor(f/3);this.setFunctionModule(p,y,g),this.setFunctionModule(y,p,g)}}drawFinderPattern(d,u){for(let f=-4;f<=4;f++)for(let g=-4;g<=4;g++){const p=Math.max(Math.abs(g),Math.abs(f)),y=d+g,b=u+f;0<=y&&y<this.size&&0<=b&&b<this.size&&this.setFunctionModule(y,b,p!=2&&p!=4)}}drawAlignmentPattern(d,u){for(let f=-2;f<=2;f++)for(let g=-2;g<=2;g++)this.setFunctionModule(d+g,u+f,Math.max(Math.abs(g),Math.abs(f))!=1)}setFunctionModule(d,u,f){this.modules[u][d]=f,this.isFunction[u][d]=!0}addEccAndInterleave(d){const u=this.version,f=this.errorCorrectionLevel;if(d.length!=ks.getNumDataCodewords(u,f))throw new RangeError("Invalid argument");const g=ks.NUM_ERROR_CORRECTION_BLOCKS[f.ordinal][u],p=ks.ECC_CODEWORDS_PER_BLOCK[f.ordinal][u],y=Math.floor(ks.getNumRawDataModules(u)/8),b=g-y%g,N=Math.floor(y/g);let w=[];const C=ks.reedSolomonComputeDivisor(p);for(let I=0,_=0;I<g;I++){let J=d.slice(_,_+N-p+(I<b?0:1));_+=J.length;const T=ks.reedSolomonComputeRemainder(J,C);I<b&&J.push(0),w.push(J.concat(T))}let R=[];for(let I=0;I<w[0].length;I++)w.forEach((_,J)=>{(I!=N-p||J>=b)&&R.push(_[I])});return i(R.length==y),R}drawCodewords(d){if(d.length!=Math.floor(ks.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let u=0;for(let f=this.size-1;f>=1;f-=2){f==6&&(f=5);for(let g=0;g<this.size;g++)for(let p=0;p<2;p++){const y=f-p,N=(f+1&2)==0?this.size-1-g:g;!this.isFunction[N][y]&&u<d.length*8&&(this.modules[N][y]=s(d[u>>>3],7-(u&7)),u++)}}i(u==d.length*8)}applyMask(d){if(d<0||d>7)throw new RangeError("Mask value out of range");for(let u=0;u<this.size;u++)for(let f=0;f<this.size;f++){let g;switch(d){case 0:g=(f+u)%2==0;break;case 1:g=u%2==0;break;case 2:g=f%3==0;break;case 3:g=(f+u)%3==0;break;case 4:g=(Math.floor(f/3)+Math.floor(u/2))%2==0;break;case 5:g=f*u%2+f*u%3==0;break;case 6:g=(f*u%2+f*u%3)%2==0;break;case 7:g=((f+u)%2+f*u%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[u][f]&&g&&(this.modules[u][f]=!this.modules[u][f])}}getPenaltyScore(){let d=0;for(let p=0;p<this.size;p++){let y=!1,b=0,N=[0,0,0,0,0,0,0];for(let w=0;w<this.size;w++)this.modules[p][w]==y?(b++,b==5?d+=ks.PENALTY_N1:b>5&&d++):(this.finderPenaltyAddHistory(b,N),y||(d+=this.finderPenaltyCountPatterns(N)*ks.PENALTY_N3),y=this.modules[p][w],b=1);d+=this.finderPenaltyTerminateAndCount(y,b,N)*ks.PENALTY_N3}for(let p=0;p<this.size;p++){let y=!1,b=0,N=[0,0,0,0,0,0,0];for(let w=0;w<this.size;w++)this.modules[w][p]==y?(b++,b==5?d+=ks.PENALTY_N1:b>5&&d++):(this.finderPenaltyAddHistory(b,N),y||(d+=this.finderPenaltyCountPatterns(N)*ks.PENALTY_N3),y=this.modules[w][p],b=1);d+=this.finderPenaltyTerminateAndCount(y,b,N)*ks.PENALTY_N3}for(let p=0;p<this.size-1;p++)for(let y=0;y<this.size-1;y++){const b=this.modules[p][y];b==this.modules[p][y+1]&&b==this.modules[p+1][y]&&b==this.modules[p+1][y+1]&&(d+=ks.PENALTY_N2)}let u=0;for(const p of this.modules)u=p.reduce((y,b)=>y+(b?1:0),u);const f=this.size*this.size,g=Math.ceil(Math.abs(u*20-f*10)/f)-1;return i(0<=g&&g<=9),d+=g*ks.PENALTY_N4,i(0<=d&&d<=2568888),d}getAlignmentPatternPositions(){if(this.version==1)return[];{const d=Math.floor(this.version/7)+2,u=this.version==32?26:Math.ceil((this.version*4+4)/(d*2-2))*2;let f=[6];for(let g=this.size-7;f.length<d;g-=u)f.splice(1,0,g);return f}}static getNumRawDataModules(d){if(d<ks.MIN_VERSION||d>ks.MAX_VERSION)throw new RangeError("Version number out of range");let u=(16*d+128)*d+64;if(d>=2){const f=Math.floor(d/7)+2;u-=(25*f-10)*f-55,d>=7&&(u-=36)}return i(208<=u&&u<=29648),u}static getNumDataCodewords(d,u){return Math.floor(ks.getNumRawDataModules(d)/8)-ks.ECC_CODEWORDS_PER_BLOCK[u.ordinal][d]*ks.NUM_ERROR_CORRECTION_BLOCKS[u.ordinal][d]}static reedSolomonComputeDivisor(d){if(d<1||d>255)throw new RangeError("Degree out of range");let u=[];for(let g=0;g<d-1;g++)u.push(0);u.push(1);let f=1;for(let g=0;g<d;g++){for(let p=0;p<u.length;p++)u[p]=ks.reedSolomonMultiply(u[p],f),p+1<u.length&&(u[p]^=u[p+1]);f=ks.reedSolomonMultiply(f,2)}return u}static reedSolomonComputeRemainder(d,u){let f=u.map(g=>0);for(const g of d){const p=g^f.shift();f.push(0),u.forEach((y,b)=>f[b]^=ks.reedSolomonMultiply(y,p))}return f}static reedSolomonMultiply(d,u){if(d>>>8||u>>>8)throw new RangeError("Byte out of range");let f=0;for(let g=7;g>=0;g--)f=f<<1^(f>>>7)*285,f^=(u>>>g&1)*d;return i(f>>>8==0),f}finderPenaltyCountPatterns(d){const u=d[1];i(u<=this.size*3);const f=u>0&&d[2]==u&&d[3]==u*3&&d[4]==u&&d[5]==u;return(f&&d[0]>=u*4&&d[6]>=u?1:0)+(f&&d[6]>=u*4&&d[0]>=u?1:0)}finderPenaltyTerminateAndCount(d,u,f){return d&&(this.finderPenaltyAddHistory(u,f),u=0),u+=this.size,this.finderPenaltyAddHistory(u,f),this.finderPenaltyCountPatterns(f)}finderPenaltyAddHistory(d,u){u[0]==0&&(d+=this.size),u.pop(),u.unshift(d)}};n.MIN_VERSION=1,n.MAX_VERSION=40,n.PENALTY_N1=3,n.PENALTY_N2=3,n.PENALTY_N3=40,n.PENALTY_N4=10,n.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],n.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],t.QrCode=n;function a(m,d,u){if(d<0||d>31||m>>>d)throw new RangeError("Value out of range");for(let f=d-1;f>=0;f--)u.push(m>>>f&1)}function s(m,d){return(m>>>d&1)!=0}function i(m){if(!m)throw new Error("Assertion error")}const c=class ni{constructor(d,u,f){if(this.mode=d,this.numChars=u,this.bitData=f,u<0)throw new RangeError("Invalid argument");this.bitData=f.slice()}static makeBytes(d){let u=[];for(const f of d)a(f,8,u);return new ni(ni.Mode.BYTE,d.length,u)}
3466static makeNumeric(d){if(!ni.isNumeric(d))throw new RangeError("String contains non-numeric characters");let u=[];for(let f=0;f<d.length;){const g=Math.min(d.length-f,3);a(parseInt(d.substring(f,f+g),10),g*3+1,u),f+=g}return new ni(ni.Mode.NUMERIC,d.length,u)}static makeAlphanumeric(d){if(!ni.isAlphanumeric(d))throw new RangeError("String contains unencodable characters in alphanumeric mode");let u=[],f;for(f=0;f+2<=d.length;f+=2){let g=ni.ALPHANUMERIC_CHARSET.indexOf(d.charAt(f))*45;g+=ni.ALPHANUMERIC_CHARSET.indexOf(d.charAt(f+1)),a(g,11,u)}return f<d.length&&a(ni.ALPHANUMERIC_CHARSET.indexOf(d.charAt(f)),6,u),new ni(ni.Mode.ALPHANUMERIC,d.length,u)}static makeSegments(d){return d==""?[]:ni.isNumeric(d)?[ni.makeNumeric(d)]:ni.isAlphanumeric(d)?[ni.makeAlphanumeric(d)]:[ni.makeBytes(ni.toUtf8ByteArray(d))]}static makeEci(d){let u=[];if(d<0)throw new RangeError("ECI assignment value out of range");if(d<128)a(d,8,u);else if(d<16384)a(2,2,u),a(d,14,u);else if(d<1e6)a(6,3,u),a(d,21,u);else throw new RangeError("ECI assignment value out of range");return new ni(ni.Mode.ECI,0,u)}static isNumeric(d){return ni.NUMERIC_REGEX.test(d)}static isAlphanumeric(d){return ni.ALPHANUMERIC_REGEX.test(d)}getData(){return this.bitData.slice()}static getTotalBits(d,u){let f=0;for(const g of d){const p=g.mode.numCharCountBits(u);if(g.numChars>=1<<p)return 1/0;f+=4+p+g.bitData.length}return f}static toUtf8ByteArray(d){d=encodeURI(d);let u=[];for(let f=0;f<d.length;f++)d.charAt(f)!="%"?u.push(d.charCodeAt(f)):(u.push(parseInt(d.substring(f+1,f+3),16)),f+=2);return u}};c.NUMERIC_REGEX=/^[0-9]*$/,c.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,c.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let l=c;t.QrSegment=c})(Yh||(Yh={}));(t=>{(n=>{const a=class{constructor(i,c){this.ordinal=i,this.formatBits=c}};a.LOW=new a(0,1),a.MEDIUM=new a(1,0),a.QUARTILE=new a(2,3),a.HIGH=new a(3,2),n.Ecc=a})(t.QrCode||(t.QrCode={}))})(Yh||(Yh={}));(t=>{(n=>{const a=class{constructor(i,c){this.modeBits=i,this.numBitsCharCount=c}numCharCountBits(i){return this.numBitsCharCount[Math.floor((i+7)/17)]}};a.NUMERIC=new a(1,[10,12,14]),a.ALPHANUMERIC=new a(2,[9,11,13]),a.BYTE=new a(4,[8,16,16]),a.KANJI=new a(8,[8,10,12]),a.ECI=new a(7,[0,0,0]),n.Mode=a})(t.QrSegment||(t.QrSegment={}))})(Yh||(Yh={}));var rp=Yh;
3466/** 3467 * @license qrcode.react 3468 * Copyright (c) Paul O'Shannessy 3469 * SPDX-License-Identifier: ISC 3470 */var X6={L:rp.QrCode.Ecc.LOW,M:rp.QrCode.Ecc.MEDIUM,Q:rp.QrCode.Ecc.QUARTILE,H:rp.QrCode.Ecc.HIGH},WD=128,GD="L",YD="#FFFFFF",QD="#000000",JD=!1,KD=1,Z6=4,eB=0,tB=.1;function XD(t,n=0){const a=[];return t.forEach(function(s,i){let c=null;s.forEach(function(l,m){if(!l&&c!==null){a.push(`M${c+n} ${i+n}h${m-c}v1H${c+n}z`),c=null;return}if(m===s.length-1){if(!l)return;c===null?a.push(`M${m+n},${i+n} h1v1H${m+n}z`):a.push(`M${c+n},${i+n} h${m+1-c}v1H${c+n}z`);return}l&&c===null&&(c=m)})}),a.join("")}function ZD(t,n){return t.slice().map((a,s)=>s<n.y||s>=n.y+n.h?a:a.map((i,c)=>c<n.x||c>=n.x+n.w?i:!1))}function nB(t,n,a,s){if(s==null)return null;const i=t.length+a*2,c=Math.floor(n*tB),l=i/n,m=(s.width||c)*l,d=(s.height||c)*l,u=s.x==null?t.length/2-m/2:s.x*l,f=s.y==null?t.length/2-d/2:s.y*l,g=s.opacity==null?1:s.opacity;let p=null;if(s.excavate){let b=Math.floor(u),N=Math.floor(f),w=Math.ceil(m+u-b),C=Math.ceil(d+f-N);p={x:b,y:N,w,h:C}}const y=s.crossOrigin;return{x:u,y:f,h:d,w:m,excavation:p,opacity:g,crossOrigin:y}}function aB(t,n){return n!=null?Math.max(Math.floor(n),0):t?Z6:eB}function eE({value:t,level:n,minVersion:a,includeMargin:s,marginSize:i,imageSettings:c,size:l,boostLevel:m}){let d=xi.useMemo(()=>{const b=(Array.isArray(t)?t:[t]).reduce((N,w)=>(N.push(...rp.QrSegment.makeSegments(w)),N),[]);return rp.QrCode.encodeSegments(b,X6[n],a,void 0,void 0,m)},[t,n,a,m]);const{cells:u,margin:f,numCells:g,calculatedImageSettings:p}=xi.useMemo(()=>{let y=d.getModules();const b=aB(s,i),N=y.length+b*2,w=nB(y,l,b,c);return{cells:y,margin:b,numCells:N,calculatedImageSettings:w}},[d,l,c,s,i]);return{qrcode:d,margin:f,cells:u,numCells:g,calculatedImageSettings:p}}var sB=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),rB=xi.forwardRef(function(n,a){const s=n,{value:i,size:c=WD,level:l=GD,bgColor:m=YD,fgColor:d=QD,includeMargin:u=JD,minVersion:f=KD,boostLevel:g,marginSize:p,imageSettings:y}=s,N=S1(s,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:w}=N,C=S1(N,["style"]),R=y==null?void 0:y.src,I=xi.useRef(null),_=xi.useRef(null),J=xi.useCallback(Z=>{I.current=Z,typeof a=="function"?a(Z):a&&(a.current=Z)},[a]),[T,G]=xi.useState(!1),{margin:z,cells:H,numCells:K,calculatedImageSettings:L}=eE({value:i,level:l,minVersion:f,boostLevel:g,includeMargin:u,marginSize:p,imageSettings:y,size:c});xi.useEffect(()=>{if(I.current!=null){const Z=I.current,fe=Z.getContext("2d");if(!fe)return;let q=H;const ne=_.current,ae=L!=null&&ne!==null&&ne.complete&&ne.naturalHeight!==0&&ne.naturalWidth!==0;ae&&L.excavation!=null&&(q=ZD(H,L.excavation));const Y=window.devicePixelRatio||1;Z.height=Z.width=c*Y;const je=c/K*Y;fe.scale(je,je),fe.fillStyle=m,fe.fillRect(0,0,K,K),fe.fillStyle=d,sB?fe.fill(new Path2D(XD(q,z))):H.forEach(function(V,$){V.forEach(function(F,P){F&&fe.fillRect(P+z,$+z,1,1)})}),L&&(fe.globalAlpha=L.opacity),ae&&fe.drawImage(ne,L.x+z,L.y+z,L.w,L.h)}}),xi.useEffect(()=>{G(!1)},[R]);const D=N1({height:c,width:c},w);let M=null;return R!=null&&(M=xi.createElement("img",{src:R,key:R,style:{display:"none"},onLoad:()=>{G(!0)},ref:_,crossOrigin:L==null?void 0:L.crossOrigin})),xi.createElement(xi.Fragment,null,xi.createElement("canvas",N1({style:D,height:c,width:c,ref:J,role:"img"},C)),M)});rB.displayName="QRCodeCanvas";var n2=xi.forwardRef(function(n,a){const s=n,{value:i,size:c=WD,level:l=GD,bgColor:m=YD,fgColor:d=QD,includeMargin:u=JD,minVersion:f=KD,boostLevel:g,title:p,marginSize:y,imageSettings:b}=s,N=S1(s,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:w,cells:C,numCells:R,calculatedImageSettings:I}=eE({value:i,level:l,minVersion:f,boostLevel:g,includeMargin:u,marginSize:y,imageSettings:b,size:c});let _=C,J=null;b!=null&&I!=null&&(I.excavation!=null&&(_=ZD(C,I.excavation)),J=xi.createElement("image",{href:b.src,height:I.h,width:I.w,x:I.x+w,y:I.y+w,preserveAspectRatio:"none",opacity:I.opacity,crossOrigin:I.crossOrigin}));const T=XD(_,w);return xi.createElement("svg",N1({height:c,width:c,viewBox:`0 0 ${R} ${R}`,ref:a,role:"img"},N),!!p&&xi.createElement("title",null,p),xi.createElement("path",{fill:m,d:`M0,0 h${R}v${R}H0z`,shapeRendering:"crispEdges"}),xi.createElement("path",{fill:d,d:T,shapeRendering:"crispEdges"}),J)});n2.displayName="QRCodeSVG";const iB=["Mouse","Keyboard","Power Cable","Adapter","Charger","Battery","Bag"],oB=["Good","Scratch","Dent","Broken","Missing Parts"];function cB(t){const n=new Date(t),a=n.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),s=n.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!0});return`${a} · ${s}`}function dI(t){return[...new Set(t.map(n=>
3470n.trim()).filter(Boolean))]}function lB(t){return t?t.split(/[,;\n]/).map(n=>n.trim()).filter(Boolean):[]}function uI({standardItems:t,selectedItems:n}){const a=new Set(n.map(i=>i.toLowerCase())),s=n.filter(i=>!t.some(c=>c.toLowerCase()===i.toLowerCase()));return e.jsxs("ul",{className:"receive-check-list",children:[[...t,...s].map(i=>{const c=a.has(i.toLowerCase());return e.jsxs("li",{className:c?"checked":"",children:[e.jsx("i",{children:c?"â":""}),i]},i)}),e.jsxs("li",{className:"other-line",children:[e.jsx("i",{}),"Other: ",e.jsx("span",{})]})]})}function C1({copyType:t,job:n,customer:a,companyName:s,companyPhone:i,companyAddress:c,companyLogoUrl:l,branchName:m,trackingUrl:d}){const u=dI([...n.accessoriesList??[],...lB(n.accessories)]),f=dI(n.physicalConditions??[]),g=s.trim().charAt(0).toUpperCase()||"S",p=[n.deviceCategory,n.brand,n.model].filter(Boolean).join(" â ");return e.jsxs("section",{className:"receive-slip",children:[e.jsxs("header",{className:"receive-slip-header",children:[e.jsxs("div",{className:"receive-brand",children:[l?e.jsx("img",{className:"receive-company-logo",src:l,alt:"",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"receive-brand-mark",children:g}),e.jsxs("div",{children:[e.jsx("strong",{className:"receive-company-name",children:s}),e.jsx("span",{className:"receive-document-name",children:"Service Receive Slip"}),(i||c)&&e.jsx("small",{children:[i,c].filter(Boolean).join(" · ")})]})]}),e.jsx("b",{className:`receive-copy-badge ${t==="Customer Copy"?"customer":"office"}`,children:t})]}),e.jsxs("section",{className:"receive-job-identity",children:[e.jsx("div",{className:"receive-barcode",children:e.jsx(J6,{value:n.jobNumber,format:"CODE128",width:1.55,height:34,margin:0,fontSize:11,displayValue:!0,background:"#ffffff",lineColor:"#000000"})}),e.jsxs("div",{className:"receive-qr",children:[e.jsx(n2,{value:d,size:43,level:"M",marginSize:0,bgColor:"#ffffff",fgColor:"#000000",title:`Track ${n.jobNumber}`}),e.jsx("small",{children:"Scan to Track"})]})]}),e.jsxs("div",{className:"receive-meta-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Job No"}),e.jsx("strong",{children:n.jobNumber})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Created"}),e.jsx("strong",{children:cB(n.createdAt)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:(a==null?void 0:a.name)||"Unknown"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Phone"}),e.jsx("strong",{children:(a==null?void 0:a.phone)||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device"}),e.jsx("strong",{children:p||"Not recorded"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:m})]})]}),e.jsxs("div",{className:"receive-detail-block receive-problem-block",children:[e.jsx("span",{children:"Problem"}),e.jsx("p",{children:n.problem||"Not recorded"})]}),e.jsxs("div",{className:"receive-two-column",children:[e.jsxs("div",{className:"receive-detail-block receive-check-section",children:[e.jsx("span",{children:"Accessories"}),e.jsx(uI,{standardItems:iB,selectedItems:u})]}),e.jsxs("div",{className:"receive-detail-block receive-check-section",children:[e.jsx("span",{children:"Physical Condition"}),e.jsx(uI,{standardItems:oB,selectedItems:f})]})]}),e.jsxs("footer",{className:"receive-slip-footer",children:[e.jsxs("div",{children:[e.jsx("i",{}),e.jsx("span",{children:"Customer Signature"}),e.jsx("em",{children:"Name: ____________________"})]}),e.jsxs("div",{children:[e.jsx("i",{}),e.jsx("span",{children:"Receiver Signature"}),e.jsx("em",{children:"Name: ____________________"})]})]}),e.jsx("div",{className:`receive-note ${t==="Office Copy"?"office":""}`,children:t==="Customer Copy"?"Keep this receipt or the WhatsApp digital copy. Show its QR code, barcode, or Job Number during device collection.":"Office Use Only"}),t==="Office Copy"&&e.jsxs("div",{className:"office-use-area",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Received By"}),e.jsx("i",{})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Delivered By"}),e.jsx("i",{})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Date"}),e.jsx("i",{})]}),e.jsx("div",{className:"office-seal-box",children:e.jsx("span",{children:"Office Seal / Internal Reference"})})]})]})}var dB="firebase",uB="12.18.0";/** 3471 * @license 3472 * Copyright 2020 Google LLC 3473 * 3474 * Licensed under the Apache License, Version 2.0 (the "License");
3475 * you may not use this file except in compliance with the License. 3476 * You may obtain a copy of the License at 3477 * 3478 * http://www.apache.org/licenses/LICENSE-2.0 3479 * 3480 * Unless required by applicable law or agreed to in writing, software 3481 * distributed under the License is distributed on an "AS IS" BASIS, 3482 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 3483 * See the License for the specific language governing permissions and 3484 * limitations under the License. 3485 */Eu(dB,uB,"app");const hB={},ru=hB,iu=(t,n)=>String(t||n).trim(),ux={firebase:{apiKey:iu(ru.VITE_FIREBASE_API_KEY,"AIzaSyDRSb5EoDIm5xdHee69D_iO1ZBsJlubxsE"),authDomain:iu(ru.VITE_FIREBASE_AUTH_DOMAIN,"service-center-cloud.firebaseapp.com"),databaseURL:iu(ru.VITE_FIREBASE_DATABASE_URL,"https://service-center-cloud-default-rtdb.asia-southeast1.firebasedatabase.app"),projectId:iu(ru.VITE_FIREBASE_PROJECT_ID,"service-center-cloud"),storageBucket:iu(ru.VITE_FIREBASE_STORAGE_BUCKET,"service-center-cloud.firebasestorage.app"),messagingSenderId:iu(ru.VITE_FIREBASE_MESSAGING_SENDER_ID,"638379126320"),appId:iu(ru.VITE_FIREBASE_APP_ID,"1:638379126320:web:53cfb7f869d08ba68447f5")},publicAppUrl:iu(ru.VITE_PUBLIC_APP_URL,"https://service-center-cloud.web.app")},tE=aw(ux.firebase),Ti=gb(tE),ie=I4(tE),hI=[["overall","Overall experience"],["repairQuality","Repair quality"],["technicianBehaviour","Technician behaviour"],["communication","Communication"],["deliveryExperience","Delivery experience"]],tj=[{key:"received",label:"Received"},{key:"diagnosing",label:"Diagnosing"},{key:"waiting_approval",label:"Waiting Approval"},{key:"approved",label:"Approved"},{key:"repairing",label:"Repairing"},{key:"quality_check",label:"Quality Check"},{key:"qc_completed",label:"QC Completed"},{key:"ready",label:"Ready for Delivery"},{key:"delivered",label:"Delivered"},{key:"closed",label:"Closed"}],mB={received:"Your device has been received and entered into our service workflow.",diagnosing:"Our team is checking the device and identifying the cause of the problem.",waiting_approval:"Diagnosis is complete and the service centre is waiting for approval.",approved:"The required work has been approved and is ready to proceed.",repairing:"Repair work is currently in progress.",quality_check:"Repair is complete and the device is undergoing final testing.",qc_completed:"Quality Check has been completed. The service team is preparing the device for Ready for Delivery status.",ready:"Your device is ready for collection.",delivered:"The device has been delivered to the customer.",closed:"This service job has been completed and closed.",cancelled:"This service job has been cancelled. Please contact the service centre for assistance."};function mI(t){return t?new Date(t).toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0}):"Not available"}function pB(t){if(!t)return"Not confirmed yet";const n=new Date(`${t}T00:00:00`);return Number.isNaN(n.getTime())?t:n.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})}function fB(t){const n=t.trim().split(/\s+/);return n.length<=1?t:`${n[0]} ${n.slice(1).map(a=>`${a.charAt(0)}.`).join(" ")}`}function gB(t){return(t??"").replace(/[^\d+]/g,"")}function yB({companyId:t,jobId:n}){const[a,s]=x.useState(null),[i,c]=x.useState(!0),[l,m]=x.useState(!1),[d,u]=x.useState(null),[f,g]=x.useState(null),[p,y]=x.useState({overall:0,repairQuality:0,technicianBehaviour:0,communication:0,deliveryExperience:0,comment:""}),[b,N]=x.useState(!1),[w,C]=x.useState("");x.useEffect(()=>{const G=re(ie,`publicTracking/${t}/${n}`);return qt(G,z=>{if(c(!1),u(Date.now()),!z.exists()){s(null),m(!0);return}s(z.val()),m(!1)},()=>{c(!1),m(!0)})},[t,n]),x.useEffect(()=>{mn(re(ie,`publicJobReviews/${t}/${n}`)).then(G=>g(G.exists()?G.val():null)).catch(()=>g(null))},[t,n]);const R=async()=>{if(!a||!["delivered","closed"].includes(a.status))return;if(hI.some(([z])=>p[z]<1)){C("সবà¦à§à¦²à§ rating দিন।");return}N(!0),C("");const G={...p,comment:p.comment.trim().slice(0,500),technicianId:a.assignedTechnicianId||"",technicianName:a.assignedTechnician||"Unassigned",jobNumber:a.jobNumber,submittedAt:Date.now()};try{await Pn(re(ie,`publicJobReviews/${t}/${n}`),G),g(G),C("à¦à¦ªà¦¨à¦¾à¦° review সফলà¦à¦¾à¦¬à§ à¦à§à¦°à¦¹à¦£ à¦à¦°à¦¾ হà§à§à¦à§à¥¤ ধনà§à¦¯à¦¬à¦¾à¦¦à¥¤")}catch(z){console.error("Customer review submit failed:",z),C("Review save à¦à¦°à¦¾ যাà§à¦¨à¦¿ ঠথবা à¦à¦ job-à¦à¦° review à¦à¦à§à¦ দà§à¦à§à¦¾ হà§à§à¦à§à¥¤")}finally{N(!1)}},I=x.useMemo(()=>!a||a.status==="cancelled"?-1:tj.findIndex(G=>G.key===a.status),[a]),_=x.useMemo(()=>!a||I<0?0:a.status==="ready"||a.status==="delivered"||a.status==="closed"?100:Math.round((I+1)/tj.length*100),[a,I]);if(i)return e.jsx("main",{className:"public-track-page",children:e.jsxs("section",{className:"public-track-card public-track-loading-card",children:[e.jsx(Hi,{className:"public-spin",size:30}),e.jsx("h1",{children:"Loading service status"}),e.jsx("p",{children:"Please wait while we retrieve the latest update."})]})});if(l||!a)return e.jsx("main",{className:"public-track-page",children:e.jsxs("section",{className:"public-track-card public-track-not-found",children:[e.jsx(Go,{size:36}),e.jsx("h1",{children:"Service job not found"}),e.jsx("p",{children:"The QR link may be invalid, expired, or the job has not yet been published for customer tracking."})]})});const J=gB(a.companyPhone),T=mB[a.status]??"Please contact the service centre for the latest information.";return e.jsx("main",{className:"public-track-page",children:e.jsxs("section",{className:"public-track-shell",children:[e.jsxs("header",{className:"public-track-header",children:[e.jsxs("div",{className:"public-track-brand",children:[a.companyLogoUrl?e.jsx("img",{src:a.c
3485ompanyLogoUrl,alt:""}):e.jsx("div",{children:a.companyName.charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("strong",{children:a.companyName}),e.jsx("span",{children:"Customer Service Tracking"})]})]}),e.jsxs("div",{className:"public-secure-badge",children:[e.jsx(gs,{size:18}),"Secure tracking"]})]}),e.jsxs("section",{className:`public-track-hero status-${a.status}`,children:[e.jsxs("div",{className:"public-track-hero-content",children:[e.jsx("p",{children:"Current service status"}),e.jsx("h1",{children:a.statusLabel}),e.jsx("p",{className:"public-status-message",children:T}),e.jsxs("div",{className:"public-live-row",children:[e.jsxs("span",{className:"public-status-pill",children:[e.jsx(Ho,{size:15}),"Live status"]}),e.jsxs("span",{children:["Auto-refreshed"," ",d?new Date(d).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!0}):""]})]})]}),e.jsxs("div",{className:"public-progress-ring","aria-label":`${_}% complete`,children:[e.jsxs("strong",{children:[_,"%"]}),e.jsx("span",{children:"Progress"})]})]}),e.jsxs("section",{className:"public-track-details",children:[e.jsxs("div",{className:"public-detail-emphasis",children:[e.jsx("span",{children:"Job Number"}),e.jsx("strong",{children:a.jobNumber})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:fB(a.customerName)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device"}),e.jsx("strong",{children:a.device})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:a.branchName})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Received"}),e.jsx("strong",{children:mI(a.receivedAt)})]}),e.jsxs("div",{className:"public-detail-emphasis",children:[e.jsx("span",{children:"Expected Delivery"}),e.jsx("strong",{children:pB(a.expectedDelivery)})]})]}),e.jsxs("section",{className:"public-track-problem",children:[e.jsx("span",{children:"Reported Problem"}),e.jsx("p",{children:a.problem})]}),e.jsxs("section",{className:"public-progress-card",children:[e.jsxs("div",{className:"public-section-title",children:[e.jsx(Jw,{size:21}),e.jsxs("div",{children:[e.jsx("h2",{children:"Repair progress"}),e.jsx("p",{children:"This timeline updates automatically when the job status changes."})]})]}),a.status==="cancelled"?e.jsx("div",{className:"public-cancelled",children:"This service job has been cancelled. Please contact the service centre for assistance."}):e.jsx("div",{className:"public-progress-list",children:tj.map((G,z)=>{const H=z<=I,K=z===I;return e.jsxs("article",{className:`${H?"completed":""} ${K?"current":""}`,children:[e.jsx("div",{className:"public-step-icon",children:H?e.jsx(ap,{size:14}):e.jsx("span",{})}),e.jsx("strong",{children:G.label}),K&&e.jsx("small",{children:"Current"})]},G.key)})})]}),e.jsxs("section",{className:"public-help-card",children:[e.jsxs("div",{className:"public-section-title",children:[e.jsx(kD,{size:21}),e.jsxs("div",{children:[e.jsx("h2",{children:"Need help?"}),e.jsx("p",{children:"Contact the service centre and mention your Job Number."})]})]}),e.jsxs("div",{className:"public-help-actions",children:[J?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"public-call-button",href:`tel:${J}`,children:[e.jsx(fg,{size:18}),"Call service centre"]}),e.jsxs("a",{className:"public-whatsapp-button",href:`https://wa.me/${J.replace("+","")}?text=${encodeURIComponent(`Hello, I need help regarding Job ${a.jobNumber}.`)}`,target:"_blank",rel:"noreferrer",children:[e.jsx(zu,{size:18}),"Chat on WhatsApp"]})]}):e.jsxs("div",{className:"public-contact-line",children:[e.jsx(fg,{size:18}),"Contact the service centre"]}),e.jsxs("div",{className:"public-contact-line",children:[e.jsx(ED,{size:18}),e.jsx("span",{children:a.companyAddress||a.branchName})]})]})]}),["delivered","closed"].includes(a.status)&&e.jsxs("section",{className:"public-review-card",children:[e.jsxs("div",{className:"public-section-title",children:[e.jsx(j1,{size:21}),e.jsxs("div",{children:[e.jsx("h2",{children:"Share your feedback"}),e.jsx("p",{children:"Your feedback helps us improve our service quality and customer experience."})]})]}),f?e.jsxs("div",{className:"public-review-thanks",children:[e.jsx("strong",{children:"Thank y
3485ou for your feedback"}),e.jsxs("span",{children:[f.overall,"/5 overall rating"]}),f.comment&&e.jsx("p",{children:f.comment})]}):e.jsxs("div",{className:"public-review-form",children:[hI.map(([G,z])=>e.jsxs("div",{className:"public-rating-row",children:[e.jsx("span",{children:z}),e.jsx("div",{children:[1,2,3,4,5].map(H=>e.jsx("button",{type:"button",className:p[G]>=H?"selected":"",onClick:()=>y(K=>({...K,[G]:H})),"aria-label":`${z}: ${H} star`,children:e.jsx(j1,{size:22,fill:"currentColor"})},H))})]},G)),e.jsxs("label",{className:"public-review-comment",children:[e.jsx("span",{children:"Comment (optional)"}),e.jsx("textarea",{rows:3,maxLength:500,value:p.comment,onChange:G=>y(z=>({...z,comment:G.target.value})),placeholder:"Tell us what went well or what we can improve"})]}),w&&e.jsx("p",{className:"public-review-message",children:w}),e.jsx("button",{className:"public-review-submit",type:"button",disabled:b,onClick:()=>void R(),children:b?"Submittingâ¦":"Submit Feedback"})]})]}),e.jsxs("section",{className:"public-privacy-note",children:[e.jsx(gs,{size:17}),e.jsx("p",{children:"For privacy and security, internal notes, technician records and business costing are not shown on this page."})]}),e.jsxs("footer",{className:"public-track-footer",children:["Last service update: ",mI(a.updatedAt)]})]})})}function vB(t){let n=t.replace(/\D/g,"");return n.startsWith("880")&&(n=n.slice(2)),n.startsWith("88")&&n.length>11&&(n=n.slice(2)),n}async function bB(t){const n=new TextEncoder().encode(t),a=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(a)).map(s=>s.toString(16).padStart(2,"0")).join("")}function xB({companySlug:t}){const[n,a]=x.useState(null),[s,i]=x.useState(!0),[c,l]=x.useState(""),[m,d]=x.useState(!1),[u,f]=x.useState(""),[g,p]=x.useState([]);x.useEffect(()=>{let w=!0;return i(!0),mn(re(ie,`companyDirectory/${t}`)).then(C=>{w&&a(C.exists()?C.val():null)}).catch(()=>{w&&a(null)}).finally(()=>{w&&i(!1)}),()=>{w=!1}},[t]);const y=x.useMemo(()=>((n==null?void 0:n.name)||t||"V").trim().charAt(0).toUpperCase(),[n==null?void 0:n.name,t]),b=w=>{!(n!=null&&n.id)||!w||window.location.assign(`/track/${encodeURIComponent(n.id)}/${encodeURIComponent(w)}`)},N=async w=>{if(w.preventDefault(),f(""),p([]),!(n!=null&&n.id)||!n.active){f("à¦à¦ Customer Portal বরà§à¦¤à¦®à¦¾à¦¨à§ পাà¦à§à¦¾ যাà¦à§à¦à§ না।");return}const C=vB(c);if(C.length<10){f("সঠিঠmobile number লিà¦à§à¦¨à¥¤");return}d(!0);try{const R=await bB(C),I=await mn(re(ie,`publicPortalPhoneLookup/${n.id}/${R}`));if(!I.exists()){f("à¦à¦ mobile number-à¦à¦° à¦à§à¦¨à§ service job পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}const _=I.val(),J=Object.values(_||{}).filter(T=>(T==null?void 0:T.active)&&T.jobId).sort((T,G)=>(G.updatedAt||0)-(T.updatedAt||0));if(!J.length){f("à¦à¦ mobile number-à¦à¦° à¦à§à¦¨à§ active service job পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}if(J.length===1){b(J[0].jobId);return}p(J)}catch(R){console.error("Customer portal lookup failed:",R),f("à¦à¦ মà§à¦¹à§à¦°à§à¦¤à§ তথà§à¦¯ à¦à§à¦à¦à¦¾ যাà¦à§à¦à§ না। à¦à¦¿à¦à§à¦à§à¦·à¦£ পরৠà¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤")}finally{d(!1)}};return s?e.jsxs("main",{className:"customer-portal-page customer-portal-centered",children:[e.jsx(nA,{className:"customer-portal-spinner",size:34}),e.jsx("p",{children:"Customer Portal loadingâ¦"})]}):!n||!n.active?e.jsx("main",{className:"customer-portal-page customer-portal-centered",children:e.jsxs("div",{className:"customer-portal-error-card",children:[e.jsx(Gw,{size:34}),e.jsx("h1",{children:"Portal not available"}),e.jsx("p",{children:"à¦à¦ company-à¦à¦° Customer Portal পাà¦à§à¦¾ যাà§à¦¨à¦¿ ঠথবা বরà§à¦¤à¦®à¦¾à¦¨à§ বনà§à¦§ à¦à¦à§à¥¤"})]})}):e.jsx("main",{className:"customer-portal-page",children:e.jsxs("div",{className:"customer-portal-shell",children:[e.jsxs("header",{className:"customer-portal-header",children:[e.jsxs("div",{className:"customer-portal-brand",children:[n.logoUrl?e.jsx("img",{src:n.logoUrl,alt:`${n.name} logo`}):e.jsx("div",{children:y}),e.jsxs("div",{children:[e.jsx("strong",{children:n.name}),e.jsx("span",{children:"Customer Service Portal"})]})]}),e.jsxs("span",{className:"customer-portal-secure",children:[e.jsx(gs,{size:17})," Secure access"]})]}),e.jsxs("section",{className:"customer-portal-hero",children:[e.jsxs("div",{children:[e.jsx("p",{children:"Service tracking"}),e.jsx("h1",{children:"à¦à¦ªà¦¨à¦¾à¦° service job-à¦à¦° live update দà§à¦à§à¦¨"}),e.jsx("span",{children:"Receive-à¦à¦° সমৠদà§à¦à§à¦¾ mobile number বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤ Job Number মনৠরাà¦à¦¾à¦° পà§à¦°à§à§à¦à¦¨ নà§à¦à¥¤"})]}),e.jsx(xr,{size:54,strokeWidth:1.5})]}),e.jsxs("section",{className:"customer-portal-form-card",children:[e.jsxs("form",{onSubmit:N,children:[e.jsxs("label",{children:[e.jsx("span",{children:"Mobile Number"}),e.jsx("input",{value:c,onChange:w=>l(w.target.value),placeholder:"যà§à¦®à¦¨: 01XXXXXXXXX",inputMode:"tel",autoComplete:"tel"})]}),u&&e.jsx("div",{className:"customer-portal-form-error",children:u}),e.jsx("button",{type:"submit",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(nA,{className:"customer-portal-spinner",size:19}),"Checkingâ¦"]}):e.jsxs(e.Fragment,{children:["Track Service ",e.jsx(y1,{size:19})]})})]}),g.length>1&&e.jsxs("div",{className:"customer-portal-results",children:[e.jsxs("div",{className:"customer-portal-results-heading",children:[e.jsx("strong",{children:"à¦à¦ªà¦¨à¦¾à¦° service jobs"}),e.jsxs("span",{children:[g.length,"à¦à¦¿ job পাà¦à§à¦¾ à¦à§à¦à§à¥¤ যà§à¦à¦¿à¦° update দà§à¦à¦¤à§ à¦à¦¾à¦¨ সà§à¦à¦¿ à¦à§à¦²à§à¦¨à¥¤"]})]}),e.jsx("div",{className:"customer-portal-results-list",children:g.map(w=>e.jsxs("button",{type:"button",className:"customer-portal-result-item",onClick:()=>b(w.jobId),children:[e.jsxs("div",{children:[e.jsx("strong",{children:w.device||"Service Device"}),e.jsx("span",{children:w.jobNumber})]}),e.jsxs("div",{children:[e.jsx("strong",{children:w.statusLabel||w.status||"In Service"}),e.jsx(y1,{size:18})]})]},w.jobId))})]}),e.jsxs("div",{className:"customer-portal-privacy",children:[e.jsx(pg,{size:17}),e.jsx("p",{children:"Mobile number যাà¦à¦¾à¦ à¦à¦¾à§à¦¾ service status দà§à¦à¦¾à¦¨à§ হবৠনা। Internal notes, employee information à¦à¦¬à¦ ঠনà§à¦¯ customer-à¦à¦° data দà§à¦à¦¾à¦¨à§ হৠনা।"})]})]}),e.jsxs("section",{className:"customer-portal-help",children:[e.jsx(kD,{size:21}),e.jsxs("div",{children:[e.jsx("strong",{children:"তথà§à¦¯ à¦à§à¦à¦à§ পাà¦à§à¦à§à¦¨ না?"}),e.jsx("p",{children:"Receive-à¦à¦° সমৠযৠmobile number দà§à¦à§à¦¾ হà§à§à¦à¦¿à¦² সà§à¦à¦¿ লিà¦à§à¦¨ ঠথবা service centre-ঠযà§à¦à¦¾à¦¯à§à¦ à¦à¦°à§à¦¨à¥¤"})]})]}),e.jsx("footer",{children:"Powered by VERIXO"})]})})}function jB(t){let n=(t||"").replace(/\D/g,"");return n.startsWith("0")&&(n=`88${n}`),n}function wB({companyId:t,jobId:n}){const[a,s]=x.useState(null),[i,c]=x.useState(!0);if(x.useEffect(()=>qt(re(ie,`publicTracking/${t}/${n}`),g=>{c(!1),s(g.exists()?g.val():null)}),[t,n]),i)return e.jsxs("main",{className:"public-receipt-state",children:[e.jsx(Go,{size:30}),e.jsx("h1",{children:"Loading receiptâ¦"})]});if(!a)return e.jsxs("main",{className:"public-receipt-state",children:[e.jsx(Go,{size:34}),e.jsx("h1",{children:"Receipt not found"}),e.jsx("p",{children:"Please contact the service centre."})]});const l=window.location.origin,m=`${l}/track/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,d=`${l}/receipt/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,u=jB(a.customerWhatsapp||a.customerPhone),f=encodeURIComponent(`Service receipt: ${a.jobNumber} 3486${d} 3487 3488You may show the QR code or barcode from this receipt during delivery.`);return e.jsxs("main",{className:"public-receipt-page",children:[e.jsxs("div",{className:"public-receipt-toolbar no-print",children:[e.jsxs("div",{children:[e.jsx("strong",{children:a.jobNumber}),e.jsx("span",{children:"Digital Service Receive Receipt"})]}),e.jsxs("div",{children:[u&&e.jsxs("a",{href:`https://wa.me/${u}?text=${f}`,target:"_blank",rel:"noreferrer",children:[e.jsx(zu,{size:17})," WhatsApp Link"]}),e.jsxs("button",{onClick:()=>window.print(),children:[e.jsx(Wi,{size:17})," Print"]}),e.jsxs("button",{onClick:()=>window.print(),children:[e.jsx(Mi,{size:17})," Download PDF"]})]})]}),e.jsx("div",{className:"public-receipt-sheet",children:e.jsx(C1,{copyType:"Customer Copy",job:{jobNumber:a.jobNumber,createdAt:a.receivedAt,deviceCategory:a.deviceCategory,brand:a.brand,model:a.model,problem:a.problem,accessories:a.accessories,accessoriesList:a.accessoriesList,physicalConditions:a.physicalConditions},customer:{name:a.customerName,phone:a.customerPhone||"â"},companyName:a.companyName,companyPhone:a.companyPhone,companyAddress:a.companyAddress,companyLogoUrl:a.companyLogoUrl,branchName:a.branchName,trackingUrl:m})})]})}
3488function Pl(t){return`à§³${Number(t||0).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function NB(t){let n=(t||"").replace(/\D/g,"");return n.startsWith("0")&&(n=`88${n}`),n}function SB({companyId:t,invoiceId:n}){const[a,s]=x.useState(null),[i,c]=x.useState(!0);if(x.useEffect(()=>qt(re(ie,`publicInvoices/${t}/${n}`),d=>{c(!1),s(d.exists()?d.val():null)}),[t,n]),i)return e.jsxs("main",{className:"public-invoice-state",children:[e.jsx(Zs,{size:34}),e.jsx("h1",{children:"Loading invoiceâ¦"})]});if(!a)return e.jsxs("main",{className:"public-invoice-state",children:[e.jsx(Zs,{size:34}),e.jsx("h1",{children:"Invoice not found"}),e.jsx("p",{children:"Please contact the service centre."})]});const l=NB(a.customerPhone),m=encodeURIComponent(`Invoice ${a.invoiceNumber} 3489Service Job ${a.jobNumber} 3490Grand Total ${Pl(a.grandTotal)} 3491Due ${Pl(a.dueAmount)} 3492${window.location.href}`);return e.jsxs("main",{className:"public-invoice-page",children:[e.jsxs("div",{className:"public-invoice-toolbar no-print",children:[e.jsxs("div",{children:[e.jsx("strong",{children:a.invoiceNumber}),e.jsx("span",{children:"Digital Service Invoice"})]}),e.jsxs("div",{children:[l&&e.jsxs("a",{href:`https://wa.me/${l}?text=${m}`,target:"_blank",rel:"noreferrer",children:[e.jsx(zu,{size:17})," WhatsApp Link"]}),e.jsxs("button",{onClick:()=>window.print(),children:[e.jsx(Wi,{size:17})," Print"]}),e.jsxs("button",{onClick:()=>window.print(),children:[e.jsx(Mi,{size:17})," Download PDF"]})]})]}),e.jsxs("article",{className:"public-invoice-sheet",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h1",{children:a.companyName}),e.jsx("p",{children:a.companyAddress||""}),e.jsx("p",{children:a.companyPhone||""})]}),e.jsxs("div",{children:[e.jsx("h2",{children:"INVOICE"}),e.jsx("strong",{children:a.invoiceNumber}),e.jsx("span",{children:new Date(a.createdAt).toLocaleString("en-GB")})]})]}),e.jsxs("section",{className:"public-invoice-reference",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Service Job"}),e.jsx("strong",{children:a.jobNumber})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:a.branchName||"â"})]})]}),e.jsxs("section",{className:"public-invoice-parties",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:a.customerName}),e.jsx("p",{children:a.customerPhone||""}),e.jsx("p",{children:a.customerAddress||""})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device / Technician"}),e.jsx("strong",{children:a.deviceLabel||"Service Device"}),e.jsxs("p",{children:["Technician: ",a.technicianName||"Unassigned"]})]})]}),e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Description"}),e.jsx("th",{children:"Amount"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("td",{children:"Service Charges"}),e.jsx("td",{children:Pl(a.labourCharge||0)})]}),e.jsxs("tr",{children:[e.jsx("td",{children:"Parts & Accessories"}),e.jsx("td",{children:Pl(a.partsTotal||0)})]})]})]}),e.jsxs("section",{className:"public-invoice-totals",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Subtotal"}),e.jsx("strong",{children:Pl(a.subtotal)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Discount"}),e.jsxs("strong",{children:["â ",Pl(a.discount)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"VAT"}),e.jsxs("strong",{children:["+ ",Pl(a.vat)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Advance / Collected"}),e.jsxs("strong",{children:["â ",Pl(a.collectedAmount)]})]}),e.jsxs("div",{className:"grand",children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:Pl(a.grandTotal)})]}),e.jsxs("div",{className:"due",children:[e.jsx("span",{children:"Amount Due"}),e.jsx("strong",{children:Pl(a.dueAmount)})]})]}),a.notes&&e.jsx("p",{className:"public-invoice-notes",children:a.notes}),e.jsx("footer",{children:"Generated by Verixo ERP"})]})]})}async function ia(t){const n=Ta(re(ie,`auditLogs/${t.companyId}`));await Pn(n,{...t,id:n.key,createdAt:Date.now()})}function CB(t){return(t||"").replace(/\D/g,"").slice(-4)}function AB(t){const n=t.trim(),a=n.match(/\/(?:track|receipt)\/[^/]+\/([^/?#]+)/i);return a?{jobId:decodeURIComponent(a[1])}:{jobNumber:n}}function IB({profile:t}){const[n,a]=x.useState([]),[s,i]=x.useState([]),[c,l]=x.useState(""),[m,d]=x.useState(null),[u,f]=x.use
3492State(""),[g,p]=x.useState(!1),[y,b]=x.useState(""),[N,w]=x.useState(!1),[C,R]=x.useState(!1),I=x.useRef(null),_=x.useRef(null);x.useEffect(()=>qt(re(ie,`serviceJobs/${t.companyId}`),Y=>{if(!Y.exists())return a([]);const je=Y.val();a(Object.entries(je).map(([V,$])=>({id:V,...$})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`customers/${t.companyId}`),Y=>{if(!Y.exists())return i([]);const je=Y.val();i(Object.entries(je).map(([V,$])=>({id:V,...$})))}),[t.companyId]);const J=x.useMemo(()=>s.find(Y=>Y.id===(m==null?void 0:m.customerId)),[s,m]),T=x.useMemo(()=>{const Y=c.trim().toLowerCase();return Y?n.map(je=>{const V=s.find(F=>F.id===je.customerId),$=[je.jobNumber,je.jobNumber.split("-").pop(),V==null?void 0:V.name,V==null?void 0:V.phone,je.deviceCategory,je.brand,je.model,je.serialNumber].filter(Boolean).join(" ").toLowerCase();return{job:je,customer:V,searchableText:$}}).filter(je=>je.searchableText.includes(Y)).sort((je,V)=>V.job.jobNumber.localeCompare(je.job.jobNumber)).slice(0,20):[]},[n,s,c]),G=Y=>{d(Y),l(Y.jobNumber),f(""),w(!1)},z=Y=>{const je=AB(Y);if(je.jobId){const $=n.find(F=>F.id===je.jobId);if($){G($);return}}const V=n.find($=>$.jobNumber.toLowerCase()===(je.jobNumber||"").toLowerCase());if(V){G(V);return}if(T.length===1){G(T[0].job);return}if(d(null),f(""),T.length>1){w(!0),window.alert("à¦à¦à¦¾à¦§à¦¿à¦ Service Job পাà¦à§à¦¾ à¦à§à¦à§à¥¤ নিà¦à§à¦° তালিà¦à¦¾ থà§à¦à§ সঠিঠJob select à¦à¦°à§à¦¨à¥¤");return}window.alert("Service Job পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤")},H=()=>{var Y;(Y=_.current)==null||Y.getTracks().forEach(je=>je.stop()),_.current=null,p(!1)},K=async()=>{const Y=window.BarcodeDetector;if(!Y){window.alert("à¦à¦ browser-ঠcamera barcode scanning support নà§à¦à¥¤ Job Number লিà¦à§ Search à¦à¦°à§à¦¨, à¦
থবা Chrome/Edge বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤");return}try{const je=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment"}});_.current=je,p(!0),b("QR বা barcode camera-à¦à¦° সামনৠধরà§à¦¨à¥¤"),window.setTimeout(async()=>{if(!I.current)return;I.current.srcObject=je,await I.current.play();const V=new Y({formats:["qr_code","code_128"]}),$=async()=>{if(!(!_.current||!I.current)){try{const F=await V.detect(I.current);if(F!=null&&F.length){const P=F[0].rawValue||"";l(P),H(),z(P);return}}catch{}requestAnimationFrame($)}};requestAnimationFrame($)},50)}catch(je){console.error(je),b("Camera access পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤")}};x.useEffect(()=>()=>H(),[]);const L=(m==null?void 0:m.status)==="ready",D=Number((m==null?void 0:m.dueAmount)||0)<=0,M=m?Math.max(0,Number(m.labourCharge||0)+Number(m.partsTotal||0)+Number(m.onsiteVisitCharge||0)+Number(m.onsiteTransportCharge||0)+Number(m.onsiteOtherCharge||0)-Number(m.discountAmount||0)||Number(m.estimatedCost||0)-Number(m.discountAmount||0)):0,Z=m?Number(m.labourCharge||0)>0||Number(m.partsTotal||0)>0||Number(m.onsiteVisitCharge||0)>0||Number(m.onsiteTransportCharge||0)>0||Number(m.onsiteOtherCharge||0)>0||Number(m.estimatedCost||0)>0:!1,fe=!!(m!=null&&m.invoiceId&&(m!=null&&m.invoiceNumber)),q=!Z||fe,ne=!!J&&u.length===4&&u===CB(J.phone),ae=async()=>{if(!(!m||!J||!L||!D||!q||!ne)){R(!0);try{const Y=Date.now();await yn(re(ie,`serviceJobs/${t.companyId}/${m.id}`),{status:"delivered",deliveredAt:Y,deliveredBy:t.name,updatedAt:Y}),await yn(re(ie,`publicTracking/${t.companyId}/${m.id}`),{status:"delivered",statusLabel:"Delivered",updatedAt:Y});const je=Ta(re(ie,`jobTimeline/${t.companyId}/${m.id}`));await Pn(je,{id:je.key,companyId:t.companyId,jobId:m.id,jobNumber:m.jobNumber,branchId:m.branchId,status:"delivered",title:"Device delivered",note:`Customer verified by mobile last 4 digits. Delivered by ${t.name}.`,actorUid:t.uid,actorName:t.name,createdAt:Y}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"job.status_changed",entityType:"serviceJob",entityId:m.id,branchId:m.branchId,summary:`Delivered service job ${m.jobNumber}`,metadata:{verification:"mobile_last_4",customerId:J.id}}),d({...m,status:"delivered",updatedAt:Y}),window.alert(`${m.jobNumber} delivery completed.`)}finally{R(!1)}}};return e.jsxs("section",{className:"delivery-scan-page",children:[e.jsx("header",{className:"page-header delivery-scan-header",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Operations"}),e.jsx("h1",{children:"Delivery Scan"}),e.jsx("p",{children:"Customer-à¦à¦° phone receipt থà§à¦à§ QR/barcode scan à¦à¦°à§ device delivery দিন।"})]})}),e.jsx("section",{className:"delivery-scan-card",children:e.jsxs("div",{className:"delivery-lookup",children:[e.jsx(Xw,{size:24}),e.jsxs("div",{children:[e.jsx("strong",{children:"Scan or enter Job Number"}),e.jsx("span",{children:"QR URL à¦à¦¬à¦ CODE128 barcodeâদà§à¦à§à¦ support à¦à¦°à§à¥¤"})]}),e.jsxs("div",{className:"delivery-search-select",children:[e.jsxs("div",{className:"delivery-search-input",children:[e.jsx("input",{value:c,onFocus:()=>w(!0),onChange:Y=>{l(Y.target.value),d(null),f(""),w(!0)},onKeyDown:Y=>{Y.key==="Enter"&&z(c),Y.key==="Escape"&&w(!1)},placeholder:"Job No, last digits, customer or phone"}),e.jsx("button",{type:"button","aria-label":"Toggle matching jobs",onClick:()=>w(Y=>!Y),children:e.jsx(Yw,{size:18,className:N?"rotated":""})})]}),N&&c.trim()&&e.jsxs("div",{className:"delivery-search-options",children:[T.map(({job:Y,customer:je})=>e.jsxs("button",{type:"button",onClick:()=>G(Y),children:[e.jsxs("div",{children:[e.jsx("strong",{children:Y.jobNumber}),e.jsxs("span",{children:[(je==null?void 0:je.name)||"Unknown Customer"," ·"," ",(je==null?void 0:je.ph
3492one)||"No phone"]})]}),e.jsx("small",{children:[Y.deviceCategory,Y.brand,Y.model].filter(Boolean).join(" â ")})]},Y.id)),!T.length&&e.jsx("div",{className:"delivery-search-empty",children:"No matching Service Job found."})]})]}),e.jsxs("button",{className:"vx-button vx-button-secondary",onClick:K,children:[e.jsx(O4,{size:17})," Camera Scan"]}),e.jsxs("button",{className:"vx-button vx-button-primary",onClick:()=>z(c),children:[e.jsx(xr,{size:17})," Find Job"]})]})}),g&&e.jsx("div",{className:"modal-backdrop",onMouseDown:H,children:e.jsxs("section",{className:"modal delivery-camera-modal",onMouseDown:Y=>Y.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Camera Scanner"}),e.jsx("h2",{children:"Scan Receipt"})]}),e.jsx("button",{onClick:H,children:e.jsx(ja,{size:20})})]}),e.jsx("video",{ref:I,playsInline:!0,muted:!0}),e.jsx("p",{children:y})]})}),m&&e.jsxs("section",{className:"delivery-result-card",children:[e.jsxs("div",{className:"delivery-result-title",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Service Job"}),e.jsx("h2",{children:m.jobNumber})]}),e.jsx("span",{className:`job-status status-${m.status}`,children:m.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:"delivery-info-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:(J==null?void 0:J.name)||"Unknown"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Mobile"}),e.jsx("strong",{children:(J==null?void 0:J.phone)||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device"}),e.jsx("strong",{children:[m.deviceCategory,m.brand,m.model].filter(Boolean).join(" â ")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Serial"}),e.jsx("strong",{children:m.serialNumber||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Current Status"}),e.jsx("strong",{children:m.status.replaceAll("_"," ")})]}),e.jsxs("div",{className:D?"ok":"blocked",children:[e.jsx("span",{children:"Outstanding Due"}),e.jsxs("strong",{children:["à§³",Number(m.dueAmount||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{className:q?"ok":"blocked",children:[e.jsx("span",{children:"Invoice Control"}),e.jsx("strong",{children:Z?fe?m.invoiceNumber||"Invoice Generated":`Required · à§³${M.toLocaleString("en-GB")}`:"Not Required · Free Job"})]})]}),e.jsxs("div",{className:"delivery-verification",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Customer Verification"}),e.jsx("span",{children:"Customer mobile number-à¦à¦° শà§à¦· ৪ digit লিà¦à§à¦¨à¥¤"})]}),e.jsx("input",{inputMode:"numeric",maxLength:4,value:u,onChange:Y=>f(Y.target.value.replace(/\D/g,"").slice(0,4)),placeholder:"Last 4 digits"}),ne&&e.jsx(Ms,{size:22})]}),!L&&e.jsx("div",{className:"delivery-warning",children:"Delivery blocked: Job status must be Ready for Delivery."}),!q&&e.jsxs("div",{className:"delivery-warning",children:["Delivery blocked: This job has a payable amount of à§³",M.toLocaleString("en-GB"),". Generate the invoice before delivery."]}),!D&&e.jsx("div",{className:"delivery-warning",children:"Delivery blocked: Outstanding due must be à§³0."}),e.jsx("div",{className:"delivery-actions",children:e.jsxs("button",{className:"vx-button vx-button-primary",disabled:!L||!D||!q||!ne||C||m.status==="delivered",onClick:ae,children:[e.jsx(Jw,{size:18}),C?"Deliveringâ¦":m.status==="delivered"?"Already Delivered":"Confirm Delivery"]})})]})]})}function Om(t){return`à§³${Number(t||0).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function pI(t){return new Date(t).toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!0})}function fI(t){const n=(t??"").replace(/\D/g,"");return n?n.startsWith("880")?n:n.startsWith("0")?`88${n}`:n:""}function _B({companyId:t,token:n}){const[a,s]=x.useState(null),[i,c]=x.useState(null),[l,m]=x.useState(!0),[d,u]=x.useState(!1),[f,g]=x.useState(!1);x.useEffect(()=>{const b=re(ie,`publicEstimates/${t}/${n}`);return qt(b,N=>{if(m(!1),!N.exists()){g(!0),s(null);return}s(N.val()),g(!1)},()=>{m(!1),g(!0)})},[t,n]),x.useEffect(()=>{const b=re(ie,`publicEstimateDecisions/${t}/${n}`);return qt(b,N=>{c(N.exists()?N.val():null)})},[t,n]);const p=async b=>{if(!a||i||d)return;const N=b==="approved"?`Approve ${a.estimateNumber} for ${Om(a.total)}?`:`Reject ${a.estimateNumber}?`;if(window.confirm(N)){u(!0);try{const w=re(ie,`publicEstimateDecisions/${t}/${n}`),C=await mn(w);if(C.exists()){c(C.val());return}await Pn(w,{decision:b,decidedAt:Date.now()})}finally{u(!1)}}};if(l)return e.jsx("main",{className:"public-estimate-page",children:e.jsxs("section",{className:"public-estimate-state",children:[e.jsx(Ho,{size:32}),e.jsx("h1",{children:"Loading estimate"}),e.jsx("p",{children:"Please wait while we retrieve the latest quotation."})]})});
3492if(f||!a)return e.jsx("main",{className:"public-estimate-page",children:e.jsxs("section",{className:"public-estimate-state",children:[e.jsx(Go,{size:34}),e.jsx("h1",{children:"Estimate not found"}),e.jsx("p",{children:"The approval link may be invalid or no longer available."})]})});const y=Date.now()>a.expiresAt;return e.jsx("main",{className:"public-estimate-page",children:e.jsxs("section",{className:"public-estimate-shell",children:[e.jsxs("header",{className:"public-estimate-header",children:[e.jsxs("div",{children:[e.jsx("strong",{children:a.companyName}),e.jsx("span",{children:"Service Estimate Approval"})]}),e.jsxs("div",{className:"public-estimate-secure",children:[e.jsx(gs,{size:17}),"Secure link"]})]}),e.jsxs("section",{className:"public-estimate-hero",children:[e.jsx("p",{children:"Estimate Number"}),e.jsx("h1",{children:a.estimateNumber}),a.jobNumber&&e.jsxs("span",{children:["Job: ",a.jobNumber]})]}),e.jsxs("section",{className:"public-estimate-meta",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:a.customerName})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device"}),e.jsx("strong",{children:a.device||"Service item"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Created"}),e.jsx("strong",{children:pI(a.createdAt)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Validity"}),e.jsxs("strong",{children:[a.validityDays," Days"]})]})]}),e.jsxs("section",{className:"public-estimate-items",children:[e.jsxs("div",{className:"public-estimate-row heading",children:[e.jsx("span",{children:"Description"}),e.jsx("span",{children:"Qty"}),e.jsx("span",{children:"Rate"}),e.jsx("span",{children:"Amount"})]}),a.items.map(b=>e.jsxs("div",{className:"public-estimate-row",children:[e.jsx("strong",{children:b.description}),e.jsx("span",{children:b.quantity}),e.jsx("span",{children:Om(b.unitPrice)}),e.jsx("span",{children:Om(b.amount)})]},b.id))]}),e.jsxs("section",{className:"public-estimate-summary",children:[e.jsxs("p",{children:[e.jsx("span",{children:"Subtotal"}),e.jsx("strong",{children:Om(a.subtotal)})]}),e.jsxs("p",{children:[e.jsx("span",{children:"Discount"}),e.jsx("strong",{children:Om(a.discount)})]}),e.jsxs("p",{className:"total",children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:Om(a.total)})]})]}),a.notes&&e.jsxs("section",{className:"public-estimate-notes",children:[e.jsx("span",{children:"Terms & Notes"}),e.jsx("p",{children:a.notes})]}),i?e.jsxs("section",{className:`public-decision-result ${i.decision}`,children:[e.jsx(Ms,{size:28}),e.jsxs("div",{children:[e.jsxs("h2",{children:["Estimate ",i.decision==="approved"?"Approved":"Rejected"]}),e.jsxs("p",{children:["Decision recorded on ",pI(i.decidedAt),".",i.decision==="approved"?" The service centre may now proceed with the approved work.":" The service centre will not proceed without further discussion."]})]})]}):y?e.jsx("section",{className:"public-estimate-expired",children:"This estimate approval link has expired. Please contact the service centre for a revised estimate."}):e.jsxs("section",{className:"public-estimate-actions",children:[e.jsxs("button",{className:"approve",disabled:d,onClick:()=>p("approved"),children:[e.jsx(X4,{size:19}),"Approve Estimate"]}),e.jsxs("button",{className:"reject",disabled:d,onClick:()=>p("rejected"),children:[e.jsx(K4,{size:19}),"Reject Estimate"]})]}),(a.companyPhone||a.jobNumber)&&e.jsxs("section",{className:"public-estimate-help",children:[e.jsx("h2",{children:"Need clarification?"}),e.jsx("p",{children:"Ask the service centre before approving or rejecting."}),e.jsxs("div",{children:[fI(a.companyPhone)&&e.jsxs("a",{className:"public-estimate-whatsapp",href:`https://wa.me/${fI(a.companyPhone)}?text=${encodeURIComponent(`Hello, I need help regarding Estimate ${a.estimateNumber}${a.jobNumber?` / Job ${a.jobNumber}`:""}.`)}`,target:"_blank",rel:"noreferrer",children:[e.jsx(zu,{size:18}),"Chat on WhatsApp"]}),a.companyPhone&&e.jsxs("a",{className:"public-estimate-call",href:`tel:${a.companyPhone.replace(/[^\d+]/g,"")}`,children:[e.jsx(fg,{size:18}),"Call Service Centre"]})]})]}),e.jsxs("section",{className:"public-estimate-warning",children:[e.jsx(jp,{size:18}),e.jsx("p",{children:"Approval authorises the service centre to proceed up to the stated amount. Additional work requires a revised estimate."})]}),e.jsx("footer",{children:[a.companyPhone,a.companyAddress].filter(
3492Boolean).join(" · ")})]})})}const gg={serviceJob:"SJ",quotation:"QT",estimate:"EST",invoice:"INV",collection:"COL",moneyReceipt:"MR",paymentVoucher:"PV",purchaseOrder:"PO",journalVoucher:"JV"};function hx(t){return(t||"VRX").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"VRX"}function a2(t,n){return(t||n).toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||n}function nE({branchCode:t,companyCode:n,documentCode:a,year:s,sequence:i}){const c=hx(t||n),l=a2(a,a);return`${c}-${l}-${s}-${String(i).padStart(6,"0")}`}function aE({branchCode:t,companyCode:n,documentType:a,prefixes:s,year:i=new Date().getFullYear()}){const c=a2(s==null?void 0:s[a],gg[a]);return nE({branchCode:t||n,documentCode:c,year:i,sequence:1})}async function Qf({companyId:t,branchCode:n,companyCode:a,documentType:s,prefixes:i,timestamp:c=Date.now(),minimumLastNumber:l=0}){const m=new Date(c).getFullYear(),d=hx(n||a),u=a2(i==null?void 0:i[s],gg[s]),f=`${d}-${u}-${m}`,g=re(ie,`documentCounters/${t}/${f}`),p=await Ep(g,b=>({lastNumber:Math.max(Number((b==null?void 0:b.lastNumber)||0),Number(l||0))+1,branchCode:d,documentCode:u,year:m,updatedAt:c}));if(!p.committed||!p.snapshot.exists())throw new Error("Document number could not be generated.");const y=Number(p.snapshot.val().lastNumber||0);return nE({branchCode:d,documentCode:u,year:m,sequence:y})}function $b(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return t.randomUUID();const n=new Uint8Array(16);if(t&&typeof t.getRandomValues=="function")t.getRandomValues(n);else{const s=Date.now()^Math.floor(Math.random()*2147483647);for(let i=0;i<n.length;i+=1)n[i]=Math.floor(Math.random()*256)^s>>>i%4*8&255}n[6]=n[6]&15|64,n[8]=n[8]&63|128;const a=Array.from(n,s=>s.toString(16).padStart(2,"0"));return`${a.slice(0,4).join("")}-${a.slice(4,6).join("")}-${a.slice(6,8).join("")}-${a.slice(8,10).join("")}-${a.slice(10,16).join("")}`}const jv=()=>({id:$b(),description:"",quantity:1,unitPrice:0});function cc(t){return`à§³${Number(t||0).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function nj(){const t=new Uint8Array(18);return crypto.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function kB(t){return{draft:"Draft",sent:"Sent",approved:"Approved",rejected:"Rejected"}[t]}function DB({companyId:t,branches:n,selectedBranchId:a,companyName:s,companyCode:i,documentPrefixes:c,companyPhone:l,companyAddress:m,actorUid:d,actorName:u}){var wt,ct,Ce,De,Te;const[f,g]=x.useState([]),[p,y]=x.useState([]),[b,N]=x.useState([]),[w,C]=x.useState(""),[R,I]=x.useState(!1),[_,J]=x.useState(null),[T,G]=x.useState(null),[z,H]=x.useState(""),[K,L]=x.useState(""),[D,M]=x.useState(""),[Z,fe]=x.useState("draft"),[q,ne]=x.useState([jv()]),[ae,Y]=x.useState(0),[je,V]=x.useState(15),[$,F]=x.useState("");x.useEffect(()=>qt(re(ie,`estimates/${t}`),ce=>{if(!ce.exists()){g([]);return}const Ye=ce.val();g(Object.entries(Ye).map(([Je,le])=>({id:Je,...le})).sort((Je,le)=>le.createdAt-Je.createdAt))}),[t]),x.useEffect(()=>qt(re(ie,`customers/${t}`),ce=>{if(!ce.exists()){y([]);return}const Ye=ce.val();y(Object.entries(Ye).map(([Je,le])=>({...le,id:Je})))}),[t]),x.useEffect(()=>qt(re(ie,`serviceJobs/${t}`),ce=>{if(!ce.exists()){N([]);return}const Ye=ce.val();N(Object.entries(Ye).map(([Je,le])=>({...le,id:Je})))}),[t]);const P=x.useMemo(()=>q.reduce((ce,Ye)=>ce+Number(Ye.quantity||0)*Number(Ye.unitPrice||0),0),[q]),ue=Math.max(0,P-Number(ae||0)),me=x.useMemo(()=>{const ce=w.trim().toLowerCase();return f.filter(Ye=>{if(a!=="all"&&Ye.branchId!==a)return!1;if(!ce)return!0;const Je=p.find(nt=>nt.id===Ye.customerId),le=b.find(nt=>nt.id===Ye.serviceJobId);return[Ye.estimateNumber,Ye.status,Je==null?void 0:Je.name,Je==null?void 0:Je.phone,le==null?void 0:le.jobNumber].filter(Boolean).some(nt=>String(nt).toLowerCase().includes(ce))})},[f,p,b,w,a]),ge=()=>{var ce;G(null),H(""),L(""),M(a!=="all"?a:((ce=n[0])==null?void 0:ce.id)??""),fe("draft"),ne([jv()]),Y(0),V(15),F("")},de=()=>{ge(),I(!0)},Pe=ce=>{var Ye;G(ce),H(ce.customerId),L(ce.serviceJobId??""),M(ce.branchId),fe(ce.status),ne((Ye=ce.items)!=null&&Ye.length?ce.items:[jv()]),Y(Number(ce.discount||0)),V(Number(ce.validityDays||15)),F(ce.notes??""),I(!0)},Re=ce=>{L(ce);const Ye=b.find(Je=>Je.id===ce);Ye&&(H(Ye.customerId),M(Ye.branchId),ne([{id:$b(),description:[`${Ye.deviceCategory}${Ye.brand?` â ${Ye.brand}`:""}
3492`,Ye.model,Ye.problem].filter(Boolean).join(" | "),quantity:1,unitPrice:0}]))},Ee=(ce,Ye,Je)=>{ne(le=>le.map(nt=>nt.id===ce?{...nt,[Ye]:Je}:nt))},Be=ce=>`${window.location.origin}/estimate/${encodeURIComponent(t)}/${encodeURIComponent(ce)}`,We=ce=>{const Ye=(ce??"").replace(/\D/g,"");return Ye?Ye.startsWith("880")?Ye:Ye.startsWith("0")?`88${Ye}`:Ye:""},it=async ce=>{const Ye=p.find(st=>st.id===ce.customerId),Je=We(Ye==null?void 0:Ye.phone);if(!Je){window.alert("Customer WhatsApp phone number পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}let le=ce.approvalToken||nj();const nt=Be(le),xt=Date.now(),te={...ce,approvalToken:le,status:ce.status==="draft"?"sent":ce.status,clientDecision:ce.clientDecision||"pending"};await yn(re(ie,`estimates/${t}/${ce.id}`),{approvalToken:le,approvalUrl:nt,status:te.status,clientDecision:te.clientDecision,updatedAt:xt}),await _e(te),ce.serviceJobId&&await yn(re(ie,`serviceJobs/${t}/${ce.serviceJobId}`),{approvalPath:"estimate_required",approvalStatus:"pending",status:"waiting_approval",updatedAt:xt});const Ge=b.find(st=>st.id===ce.serviceJobId),pt=[`Hello ${(Ye==null?void 0:Ye.name)||"Customer"},`,"","Your service estimate is ready.",`Estimate: ${ce.estimateNumber}`,Ge!=null&&Ge.jobNumber?`Job No: ${Ge.jobNumber}`:"",`Total: ${cc(ce.total)}`,"","Please review and approve or reject using this secure link:",nt,"","Thank you,",s].filter(Boolean).join(` 3493`),$e=`https://wa.me/${Je}?text=${encodeURIComponent(pt)}`;window.open($e,"_blank","noopener,noreferrer")},_e=async ce=>{var te;const Ye=p.find(Ge=>Ge.id===ce.customerId),Je=b.find(Ge=>Ge.id===ce.serviceJobId);if(!ce.approvalToken)return;const le=n.find(Ge=>Ge.id===ce.branchId),nt=(te=le==null?void 0:le.contacts)!=null&&te.length?le.contacts.map(Ge=>`${Ge.label}: ${Ge.phone}`).join(" · "):(le==null?void 0:le.phone)||l||"",xt=ce.createdAt+Number(ce.validityDays||15)*24*60*60*1e3;await Pn(re(ie,`publicEstimates/${t}/${ce.approvalToken}`),{companyName:s,companyPhone:nt,companyAddress:(le==null?void 0:le.address)||m||"",estimateNumber:ce.estimateNumber,jobNumber:(Je==null?void 0:Je.jobNumber)||"",customerName:(Ye==null?void 0:Ye.name)||"Customer",device:Je?[Je.deviceCategory,Je.brand,Je.model].filter(Boolean).join(" â "):"Service item",items:ce.items.map(Ge=>({...Ge,amount:Number(Ge.quantity||0)*Number(Ge.unitPrice||0)})),subtotal:ce.subtotal,discount:ce.discount,total:ce.total,validityDays:ce.validityDays,notes:ce.notes||"",createdAt:ce.createdAt,expiresAt:xt})},ee=async ce=>{var xt;if(ce.preventDefault(),!z||!D){alert("Customer and Branch are required.");return}const Ye=q.map(te=>({...te,description:te.description.trim(),quantity:Number(te.quantity||0),unitPrice:Number(te.unitPrice||0)})).filter(te=>te.description&&te.quantity>0);if(!Ye.length){alert("Add at least one estimate item.");return}const Je=Date.now(),le={companyId:t,branchId:D,customerId:z,serviceJobId:K||"",estimateNumber:(T==null?void 0:T.estimateNumber)??await Qf({companyId:t,branchCode:(xt=n.find(te=>te.id===D))==null?void 0:xt.code,documentType:"estimate",prefixes:c}),status:Z,items:Ye,subtotal:P,discount:Number(ae||0),total:ue,validityDays:Number(je||15),notes:$.trim(),approvalToken:(T==null?void 0:T.approvalToken)??(Z==="sent"||Z==="approved"?nj():""),clientDecision:(T==null?void 0:T.clientDecision)??(Z==="approved"?"approved":Z==="rejected"?"rejected":"pending"),createdAt:(T==null?void 0:T.createdAt)??Je,updatedAt:Je};let nt;if(T)nt={...T,...le},await yn(re(ie,`estimates/${t}/${T.id}`),le);else{const te=Ta(re(ie,`estimates/${t}`));nt={...le,id:te.key??""},await Pn(te,nt),await ia({companyId:t,actorUid:d,actorName:u,action:"estimate.created",entityType:"estimate",entityId:te.key||"",summary:`Created estimate ${nt.estimateNumber}`,metadata:{estimateNumber:nt.estimateNumber,customerId:nt.customerId,serviceJobId:nt.serviceJobId||"",total:nt.total}})}nt.status==="approved"&&(T==null?void 0:T.status)!=="approved"&&await se(nt),nt.approvalToken&&["sent","approved"].includes(nt.status)&&await _e(nt),I(!1),ge()},qe=async ce=>{confirm(`Delete ${ce.estimateNumber}?`)&&await Ao(re(ie,`estimates/${t}/${ce.id}`))},se=async ce=>{if(!ce.serviceJobId)return;const Ye=b.find(xt=>xt.id===ce.serviceJobId);if(!Ye)return;const Je=Date.now(),le=Math.max(0,Number(ce.total||0)-Number(Ye.advanceAmount||0)-Number(Ye.discountAmount||0));await yn(re(ie,`serviceJobs/${t}/${ce.serviceJobId}`),{estimatedCost:Number(ce.total||0),dueAmount:le,approvalPath:"estimate_required",approvalStatus:"approved",approvedEstimateId:ce.id,status:"approved",updatedAt:Je});const nt=Ta(re(ie,`jobTimeline/${t}/${ce.serviceJobId}`));await Pn(nt,{id:nt.key,companyId:t,jobId:ce.serviceJobId,jobNumber:Ye.jobNumber,branchId:Ye.branchId,status:"approved",title:`Client approved estimate: ${ce.estimateNumber}`,note:`Estimated amount updated to ${cc(ce.total)}.`,actorUid:d,actorName:u,createdAt:Je})},pe=async(ce,Ye)=>{const Je=Date.now(),le=ce.approvalToken||(Ye==="sent"||Ye==="approved"?nj():""),nt={...ce,approvalToken:le,approvalUrl:le?Be(le):"",clientDecision:Ye==="approved"?"approved":Ye==="rejected"?"rejected":"pending"};await yn(re(ie,`estimates/${t}/${ce.id}`),{status:Ye,approvalToken:le,approvalUrl:nt.approvalUrl,clientDecision:nt.clientDecision,updatedAt:Je}),le&&["sent","approved"].includes(Ye)&&(await _e(nt),ce.serviceJobId&&await yn(re(ie,`serviceJobs/${t}/${ce.serviceJobId}`),{approvalPath:"estimate_required",approvalStatus:Ye==="approved"?"approved":"pending",status:Ye==="approved"?"approved":"waiting_approval",updatedAt:Je})),Ye==="approved"&&ce.status!=="approved"&&await se({...ce})},Se=_?p.find(ce=>ce.id===_.customerId):void 0,Me=_?b.find(ce=>ce.id===_.serviceJobId):void 0,ot=_?n.find(ce=>ce.id===_.branchId):void 0;return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"estimate-page",children:[e.jsxs("header",{className:"estimate-page-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Commercial Documents"}),e.jsx("h1",{children:"Estimates & Quotations"}),e.jsx("p",{children:"Create repair estimates, send for approval and track customer decisions."})]}),e.jsxs("button",{className:"primary-button",onClick:de,children:[e.jsx(as,{size:18}),"New Estimate"]})]}),e.jsxs("section",{className:"estimate-summary-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Total Estimates"}),e.jsx("strong",{children:f.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Awaiting Decision"}),e.jsx("strong",{children:f.filter(ce=>ce.status==="draft"||ce.status==="sent").length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Approved Value"}),e.jsx("strong",{children:cc(f.filter(ce=>ce.status==="approved").reduce((ce,Ye)=>ce+Ye.total,0))})]})]}),e.jsxs("section",{className:"estimate-list-card",children:[e.jsxs("div",{className:"estimate-toolbar",children:[e.jsx("input",{value:w,onChange:ce=>C(ce.target.value),placeholder:"Search estimate, customer, phone or job number"}),e.jsxs("span",{children:[me.length," estimate found"]}
3493)]}),me.length?e.jsx("div",{className:"estimate-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Estimate"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Service Job"}),e.jsx("th",{children:"Total"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:me.map(ce=>{const Ye=p.find(le=>le.id===ce.customerId),Je=b.find(le=>le.id===ce.serviceJobId);return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:ce.estimateNumber}),e.jsxs("small",{children:["Valid ",ce.validityDays||15," days"]})]}),e.jsxs("td",{children:[e.jsx("strong",{children:(Ye==null?void 0:Ye.name)||"Unknown"}),e.jsx("small",{children:(Ye==null?void 0:Ye.phone)||"â"})]}),e.jsx("td",{children:(Je==null?void 0:Je.jobNumber)||"Independent"}),e.jsx("td",{children:e.jsx("strong",{children:cc(ce.total)})}),e.jsx("td",{children:e.jsx("span",{className:`estimate-status ${ce.status}`,children:kB(ce.status)})}),e.jsx("td",{children:new Date(ce.updatedAt).toLocaleDateString("en-GB")}),e.jsx("td",{children:e.jsxs("div",{className:"estimate-actions",children:[e.jsx("button",{title:"Preview",onClick:()=>J(ce),children:e.jsx(ui,{size:16})}),e.jsx("button",{title:"Send via WhatsApp",onClick:()=>it(ce),children:e.jsx(zu,{size:16})}),e.jsx("button",{title:"Edit",onClick:()=>Pe(ce),children:e.jsx(Zi,{size:16})}),ce.status==="draft"&&e.jsx("button",{title:"Mark Sent",onClick:()=>pe(ce,"sent"),children:e.jsx(Zw,{size:16})}),ce.status==="sent"&&e.jsx("button",{title:"Approve",onClick:()=>pe(ce,"approved"),children:e.jsx(Ms,{size:16})}),e.jsx("button",{title:"Delete",onClick:()=>qe(ce),children:e.jsx(po,{size:16})})]})})]},ce.id)})})]})}):e.jsxs("div",{className:"estimate-empty",children:[e.jsx(Zs,{size:42}),e.jsx("h3",{children:"No estimate found"}),e.jsx("p",{children:"Create the first repair estimate or quotation."})]})]})]}),R&&e.jsx("div",{className:"modal-backdrop",children:e.jsxs("section",{className:"modal estimate-modal",children:[e.jsxs("header",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:T?"Edit Estimate":"New Estimate"}),e.jsx("h2",{children:T?T.estimateNumber:aE({companyCode:i,documentType:"estimate",prefixes:c})})]}),e.jsx("button",{onClick:()=>I(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:ee,className:"estimate-form",children:[e.jsxs("div",{className:"estimate-form-grid",children:[e.jsxs("label",{children:["Service Job",e.jsxs("select",{value:K,onChange:ce=>Re(ce.target.value),children:[e.jsx("option",{value:"",children:"Independent estimate"}),b.map(ce=>e.jsxs("option",{value:ce.id,children:[ce.jobNumber," â ",ce.deviceCategory]},ce.id))]})]}),e.jsxs("label",{children:["Customer",e.jsxs("select",{required:!0,value:z,onChange:ce=>H(ce.target.value),children:[e.jsx("option",{value:"",children:"Select customer"}),p.map(ce=>e.jsxs("option",{value:ce.id,children:[ce.name," â ",ce.phone]},ce.id))]})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{required:!0,value:D,onChange:ce=>M(ce.target.value),children:[e.jsx("option",{value:"",children:"Select branch"}),n.map(ce=>e.jsx("option",{value:ce.id,children:ce.name},ce.id))]})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:Z,onChange:ce=>fe(ce.target.value),children:[e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"sent",children:"Sent"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"rejected",children:"Rejected"})]})]})]}),e.jsxs("section",{className:"estimate-items-section",children:[e.jsxs("div",{className:"estimate-section-title",children:[e.jsx("h3",{children:"Estimate Items"}),e.jsxs("button",{type:"button",onClick:()=>ne(ce=>[...ce,jv()]),children:[e.jsx(as,{size:15}),"Add Parts / Service"]})]}),e.jsxs("div",{className:"estimate-item-headings","aria-hidden":"true",children:[e.jsx("span",{children:"SL"}),e.jsx("span",{children:"Description"}),e.jsx("span",{children:"Qty"}),e.jsx("span",{children:"Rate (à§³)"}),e.jsx("span",{children:"Amount (à§³)"}),e.jsx("span",{})]}),q.map((ce,Ye)=>e.jsxs("div",{className:"estimate-item-row",children:[e.jsx("span",{children:Ye+1}),e.jsx("input",{required:!0,value:ce.description,onChange:Je=>Ee(ce.id,"description",Je.target.value),placeholder:"Repair work, replacement part or service"}),e.jsx("input",{type:"number",min:"1",step:"1",value:ce.quantity,onChange:Je=>Ee(ce.id,"quantity",Number(Je.target.value))}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:ce.unitPrice,onChange:Je=>Ee(ce.id,"unitPrice",Number(Je.target.value))}
3493),e.jsx("output",{className:"estimate-line-amount","aria-label":"Calculated amount",children:cc(ce.quantity*ce.unitPrice)}),e.jsx("button",{type:"button",onClick:()=>ne(Je=>Je.length>1?Je.filter(le=>le.id!==ce.id):Je),children:e.jsx(po,{size:15})})]},ce.id))]}),e.jsxs("section",{className:"estimate-bottom-grid",children:[e.jsxs("label",{className:"estimate-notes-field",children:["Terms & Notes",e.jsx("textarea",{value:$,onChange:ce=>F(ce.target.value),placeholder:"Warranty, delivery time, exclusions or payment terms..."})]}),e.jsxs("div",{className:"estimate-totals",children:[e.jsxs("label",{children:["Validity",e.jsxs("select",{value:je,onChange:ce=>V(Number(ce.target.value)),children:[e.jsx("option",{value:7,children:"7 Days"}),e.jsx("option",{value:15,children:"15 Days"}),e.jsx("option",{value:30,children:"30 Days"}),e.jsx("option",{value:45,children:"45 Days"}),e.jsx("option",{value:60,children:"60 Days"})]})]}),e.jsxs("p",{children:[e.jsx("span",{children:"Items"}),e.jsx("strong",{children:q.filter(ce=>ce.description.trim()&&Number(ce.quantity||0)>0).length})]}),e.jsxs("p",{children:[e.jsx("span",{children:"Subtotal"}),e.jsx("strong",{children:cc(P)})]}),e.jsxs("label",{children:["Discount",e.jsx("input",{type:"number",min:"0",step:"0.01",value:ae,onChange:ce=>Y(Number(ce.target.value))})]}),e.jsxs("p",{children:[e.jsx("span",{children:"VAT"}),e.jsx("strong",{children:cc(0)})]}),e.jsxs("p",{className:"grand-total",children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:cc(ue)})]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>I(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",type:"submit",children:"Save Estimate"})]})]})]})}),_&&e.jsx("div",{className:"modal-backdrop estimate-preview-backdrop",children:e.jsxs("section",{className:"estimate-preview-modal",children:[e.jsxs("div",{className:"estimate-preview-actions",children:[e.jsxs("button",{onClick:()=>window.print(),children:[e.jsx(Wi,{size:17}),"Print"]}),e.jsxs("button",{onClick:()=>it(_),children:[e.jsx(zu,{size:17}),"WhatsApp"]}),e.jsx("button",{onClick:()=>J(null),children:e.jsx(ja,{size:18})})]}),e.jsxs("article",{className:"estimate-print-document",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h1",{children:s}),e.jsxs("p",{children:[e.jsx("strong",{children:"Invoiced Location :"})," ",((wt=n.find(ce=>ce.id===_.branchId))==null?void 0:wt.name)||""]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Invoiced Location Address :"})," ",((ct=n.find(ce=>ce.id===_.branchId))==null?void 0:ct.address)||m||""," ",((De=(Ce=n.find(ce=>ce.id===_.branchId))==null?void 0:Ce.contacts)!=null&&De.length?n.find(ce=>ce.id===_.branchId).contacts.map(ce=>`${ce.label}: ${ce.phone}`).join(" · "):((Te=n.find(ce=>ce.id===_.branchId))==null?void 0:Te.phone)||l)||""]})]}),e.jsxs("div",{className:"estimate-print-identity",children:[e.jsx("strong",{children:"ESTIMATE"}),e.jsx("span",{children:_.estimateNumber}),_.approvalToken&&e.jsxs("div",{className:"estimate-approval-qr",children:[e.jsx(n2,{value:Be(_.approvalToken),size:72,level:"M"}),e.jsx("small",{children:"Scan to Approve / Reject"})]})]})]}),e.jsxs("section",{className:"estimate-print-meta",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Prepared For"}),e.jsx("strong",{children:(Se==null?void 0:Se.name)||"Unknown"}),e.jsx("p",{children:(Se==null?void 0:Se.phone)||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Service Job"}),e.jsx("strong",{children:(Me==null?void 0:Me.jobNumber)||"Independent"}),e.jsx("p",{children:(Me==null?void 0:Me.deviceCategory)||""})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:(ot==null?void 0:ot.name)||"Unknown"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Validity"}),e.jsxs("strong",{children:[_.validityDays||15," Days"]})]})]}),e.jsxs("table",{className:"estimate-print-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"SL"}),e.jsx("th",{children:"Description"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Unit Price"}),e.jsx("th",{children:"Total"})]})}),e.jsx("tbody",{children:_.items.map((ce,Ye)=>e.jsxs("tr",{children:[e.jsx("td",{children:Ye+1}),e.jsx("td",{children:ce.description}),e.jsx("td",{children:ce.quantity}),e.jsx("td",{children:cc(ce.unitPrice)}),e.jsx("td",{children:cc(ce.quantity*ce.unitPrice)})]},ce.id))})]}),e.jsxs("section",{className:"estimate-print-summary",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Notes"}),e.jsx("p",{children:_.notes||"No additional notes."})]}),e.jsxs("div",{children:[e.jsxs("p",{children:[e.jsx("span",{children:"Subtotal"}),e.jsx("strong",{children:cc(_.subtotal)})]}),e.jsxs("p",{children:[e.jsx("span",{children:"Discount"}),e.jsx("strong",{children:cc(_.discount)})]}),e.jsxs("p",{className:"grand-total",children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:cc(_.total)})]})]})]}),e.jsxs("footer",{children:[e.jsxs("div",{children:[e.jsx("i",{}),e.jsx("span",{children:"Authorised Signature"})]}),e.jsxs("p",{children:["This estimate is valid for ",_.validityDays||15," days."]})]})]})]})})]})}function sE(t){const n=new Date(t),a=n.getFullYear(),s=String(n.getMonth()+1).padStart(2,"0"),i=String(n.getDate()).padStart(2,"0");return`${a}-${s}-${i}`}function pc(t){return Number(Number(t||0).toFixed(2))}async function qg(t){var u;const[n,a]=await Promise.all([mn(re(ie,`accountingAccounts/${t}`)),mn(re(ie,`accountingSettings/${t}`))]),s=n.exists()?Object.entries(n.val()).map(([f,g])=>({id:f,...g})):[],i=(f,g)=>s.find(p=>
3493p.active!==!1&&!p.isGroup&&(p.systemKey===f||p.code===g)),c=i("accounts_receivable","1200"),l=i("service_revenue","4200"),m=i("cash","1110"),d=i("bank","1120");if(!c)throw new Error("Accounts Receivable (1200) account is missing.");if(!l)throw new Error("Service Revenue (4200) account is missing.");if(!m)throw new Error("Cash in Hand (1110) account is missing.");if(!d)throw new Error("Bank Account (1120) account is missing.");return{ar:c,serviceRevenue:l,cash:m,bank:d,lockedThrough:String(((u=a.val())==null?void 0:u.lockedThrough)||"")}}function rE(t,n){const a=n.slice(0,7);if(t.lockedThrough&&a<=t.lockedThrough)throw new Error(`Accounting period ${a} is locked. Service Finance posting is blocked.`)}function A1(t,n){return n==="cash"?t.cash:t.bank}async function yg(t){if((await mn(re(ie,`accountingVouchers/${t.companyId}/${t.voucherId}`))).exists())return{};const a=sE(t.timestamp),s=await qg(t.companyId);rE(s,a);const i=t.lines.filter(u=>pc(u.debit)>0||pc(u.credit)>0),c=pc(i.reduce((u,f)=>u+f.debit,0)),l=pc(i.reduce((u,f)=>u+f.credit,0));if(i.length<2||Math.abs(c-l)>=.005||c<=0)throw new Error("Automatic service accounting entry is not balanced.");const m=i.map((u,f)=>({id:`line_${String(f+1).padStart(3,"0")}`,accountId:u.account.id,accountCode:u.account.code,accountName:u.account.name,debit:pc(u.debit),credit:pc(u.credit),narration:u.narration})),d={};return d[`accountingVouchers/${t.companyId}/${t.voucherId}`]={voucherNo:t.voucherNo,type:t.type,status:"posted",voucherDate:a,branchId:t.branchId,reference:t.reference,narration:t.narration,lines:m,totalDebit:c,totalCredit:l,createdAt:t.timestamp,createdByUid:t.actorUid,createdByName:t.actorName,updatedAt:t.timestamp,postedAt:t.timestamp,postedByUid:t.actorUid,postedByName:t.actorName,sourceType:t.sourceType,sourceId:t.sourceId,autoPosted:!0},m.forEach((u,f)=>{const g=`${t.voucherId}_${String(f+1).padStart(3,"0")}`;d[`accountingLedgerEntries/${t.companyId}/${g}`]={id:g,voucherId:t.voucherId,voucherNo:t.voucherNo,voucherType:t.type,voucherDate:a,branchId:t.branchId,reference:t.reference,narration:u.narration,accountId:u.accountId,accountCode:u.accountCode,accountName:u.accountName,debit:u.debit,credit:u.credit,status:"posted",createdAt:t.timestamp,postedByUid:t.actorUid,postedByName:t.actorName,sourceType:t.sourceType,sourceId:t.sourceId,autoPosted:!0}}),d}async function iE(t){const n=await qg(t.companyId),a=sE(t.timestamp);rE(n,a);const s={},i=pc(t.grandTotal);i>0&&Object.assign(s,await yg({...t,voucherId:`svc_invoice_${t.invoiceId}`,voucherNo:`AUTO-${t.invoiceNumber}`,type:"journal",reference:t.invoiceNumber,narration:`Service invoice recognized · ${t.invoiceNumber}`,sourceType:"service_invoice",sourceId:t.invoiceId,lines:[{account:n.ar,debit:i,credit:0,narration:`Service invoice receivable · ${t.invoiceNumber}`},{account:n.serviceRevenue,debit:0,credit:i,narration:`Service revenue · ${t.invoiceNumber}`}]}));const c=pc(t.advanceAmount);return c>0&&Object.assign(s,await yg({...t,voucherId:`svc_invoice_advance_${t.invoiceId}`,voucherNo:`AUTO-ADV-${t.invoiceNumber}`,type:"receipt",reference:t.invoiceNumber,narration:`Service advance applied on invoice · ${t.invoiceNumber}`,sourceType:"service_invoice_advance",sourceId:t.invoiceId,lines:[{account:n.cash,debit:c,credit:0,narration:`Service advance received/applied · ${t.invoiceNumber}`},{account:n.ar,debit:0,credit:c,narration:`Advance applied against receivable · ${t.invoiceNumber}`}]})),s}async function oE(t){const n=await qg(t.companyId),a=pc(t.amount);if(a<=0)return{};const s=A1(n,t.method);return yg({...t,voucherId:`svc_collection_${t.collectionId}`,voucherNo:`AUTO-${t.collectionNumber}`,type:"receipt",reference:t.invoiceNumber,narration:`Customer collection · ${t.collectionNumber} · ${t.invoiceNumber}`,sourceType:"service_collection",sourceId:t.collectionId,lines:[{account:s,debit:a,credit:0,narration:`Customer collection via ${t.method} · ${t.collectionNumber}`},{account:n.ar,debit:0,credit:a,narration:`Receivable settled · ${t.invoiceNumber}`}]})}async function gI(t){const n=await qg(t.companyId),a=[],s=pc(t.newGrandTotal-t.oldGrandTotal);if(s>0)a.push({account:n.ar,debit:s,credit:0,narration:`Invoice correction increase · ${t.invoiceNumber}`}),a.push({account:n.serviceRevenue,debit:0,credit:s,narration:`Service revenue correction increase · ${t.invoiceNumber}`});else if(s<0){const c=Math.abs(s);a.push({account:n.serviceRevenue,debit:c,credit:0,narration:`Service revenue correction decrease · ${t.invoiceNumber}`}),a.push({account:n.ar,debit:0,credit:c,narration:`Invoice receivable correction decrease · ${t.invoiceNumber}`})}const i=pc(t.newAdvance-t.oldAdvance);if(i>0)a.push({account:n.cash,debit:i,credit:0,narration:`Additional service advance · ${t.invoiceNumber}`}),a.push({account:n.ar,debit:0,credit:i,narration:`Additional advance applied · ${t.invoiceNumber}`});else if(i<0){const c=Math.abs(i);a.push({account:n.ar,debit:c,credit:0,narration:`Service advance reduction · ${t.invoiceNumber}`}),a.push({account:n.cash,debit:0,credit:c,narration:`Service advance refund/reduction · ${t.invoiceNumber}`})}return a.length?yg({...t,voucherId:`svc_invoice_adjust_${t.invoiceId}_${t.token}`,voucherNo:`AUTO-ADJ-${t.invoiceNumber}-${t.token.slice(-6)}`,type:"journal",reference:t.invoiceNumber,narration:`Service invoice correction · ${t.invoiceNumber}`,sourceType:"service_invoice_adjustment",sourceId:t.invoiceId,lines:a}):{}}async function EB(t){const n=await qg(t.companyId),a=pc(t.oldAmount),s=pc(t.newAmount);if(Math.abs(a-s)<.005&&t.oldMethod===t.newMethod)return{};const i=A1(n,t.oldMethod),c=A1(n,t.newMethod),l=[];return a>0&&(l.push({account:n.ar,debit:a,credit:0,narration:`Reverse prior collection value · ${t.collectionNumber}`}),l.push({account:i,debit:0,credit:a,narration:`Reverse prior ${t.oldMethod} collection · ${t.collectionNumber}`})),s>0&&(l.push({account:c,debit:s,credit:0,narration:`Corrected ${t.newMethod} collection · ${t.collectionNumber}`}),l.push({account:n.ar,debit:0,credit:s,narration:`Corrected receivable settlement · ${t.invoiceNumber}`})),yg({...t,voucherId:`svc_collection_adjust_${t.collectionId}_${t.token}`,voucherNo:`AUTO-ADJ-${t.collectionNumber}-${t.token.slice(-6)}`,type:"journal",reference:t.invoiceNumber,narration:`Service collection correction · ${t.collectionNumber}`,sourceType:"service_collection_adjustment",sourceId:t.collectionId,lines:l})}
3493function Xa(t){return`à§³${Number(t||0).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function I1(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function PB(t){let n=(t||"").replace(/\D/g,"");return n.startsWith("0")&&(n=`88${n}`),n}function RB(){return window.location.origin}function yI(t,n){return`${RB()}/invoice/${encodeURIComponent(t)}/${encodeURIComponent(n)}`}function aj(t){return{draft:"Draft",uncollected:"Uncollected",partially_collected:"Partially Collected",fully_collected:"Fully Collected",void:"Void / Cancelled"}[t]}function wv(t){return{cash:"Cash",bkash:"bKash",nagad:"Nagad",card:"Card",bank_transfer:"Bank Transfer",cheque:"Cheque",mixed:"Mixed"}[t]}function vI(t,n,a=""){const s=window.open("","_blank","width=900,height=900");if(!s){window.alert("Please allow pop-ups to print this document.");return}try{s.opener=null}catch{}s.document.write(`<!doctype html> 3494<html> 3495<head> 3496<meta charset="utf-8" /> 3497<title>${I1(t)}</title> 3498<style> 3499 * { box-sizing: border-box; -webkit-print-color-adjust:exact; print-color-adjust:exact; } 3500 :root { --navy:#073b5c; --gold:#b98216; --ink:#10263b; --muted:#667b8e; --line:#d8e3eb; --soft:#f4f8fb; } 3501 body { margin:0; padding:26px; font-family:Arial,Helvetica,sans-serif; color:var(--ink); background:#fff; } 3502 .document { width:100%; max-width:100%; margin:0 auto; } 3503 .top-accent { height:7px; background:var(--navy); border-radius:6px 6px 0 0; } 3504 .header { display:grid; grid-template-columns:minmax(0,1.45fr) minmax(250px,.75fr); gap:24px; padding:20px; border:1px solid var(--line); border-top:0; } 3505 .brand h1 { margin:0 0 7px; color:var(--navy); font-size:27px; } 3506 .brand p,.meta p { margin:4px 0; color:var(--muted); font-size:13px; line-height:1.45; } 3507 .branch-line { margin-top:10px!important; color:var(--ink)!important; } 3508 .meta { text-align:right; border-left:1px solid var(--line); padding-left:20px; } 3509 .doc-title { margin:0 0 8px; color:var(--navy); font-size:25px; letter-spacing:1px; } 3510 .doc-no { font-size:13px!important; color:var(--ink)!important; font-weight:700; } 3511 .status-pill { display:inline-block; margin-top:7px; padding:5px 10px; border-radius:999px; background:#e8f5ee; color:#207247; font-size:10px; font-weight:700; text-transform:uppercase; } 3512 .section { margin-top:16px; } .section-title { margin:0 0 8px; color:var(--gold); font-size:10px; font-weight:800; letter-spacing:1.4px; text-transform:uppercase; } 3513 .grid { display:grid; grid-template-columns:1fr 1fr; gap:12px; } 3514 .box { border:1px solid var(--line); border-radius:8px; padding:13px 14px; } 3515 .box span,.label { display:block; color:var(--muted); font-size:9px; font-weight:700; text-transform:uppercase; letter-spacing:.7px; margin-bottom:5px; } 3516 .box strong { font-size:14px; } .box p { margin:4px 0 0; font-size:13px; color:#41596d; } 3517 table { width:100%; border-collapse:collapse; margin-top:10px; } 3518 th { padding:9px 10px; background:var(--navy); color:#fff; border:1px solid var(--navy); font-size:10px; text-transform:uppercase; } 3519 td { padding:10px; border:1px solid var(--line); font-size:13px; vertical-align:top; } .num{text-align:right;white-space:nowrap} 3520 .summary-wrap { display:grid; grid-template-columns:1fr 350px; gap:18px; margin-top:14px; } 3521 .note-card { border:1px solid var(--line); border-radius:8px; padding:13px; background:var(--soft); font-size:13px; line-height:1.5; } 3522 .amounts { width:100%; border:1px solid var(--line); border-radius:8px; overflow:hidden; } 3523 .amount-row { display:flex; justify-content:space-between; padding:8px 12px; border-bottom:1px solid var(--line); font-size:13px; } 3524 .grand { padding:12px; background:var(--navy); color:#fff; font-size:14px; font-weight:700; } .paid{color:#207247;font-weight:700} 3525 .receipt-hero { margin-top:16px; display:grid; grid-template-columns:1fr 230px; gap:12px; } 3526 .amount-card { border-radius:9px; background:var(--navy); color:#fff; padding:17px; } 3527 .amount-card span { display:block; opacity:.78; font-size:10px; text-transform:uppercase; } .amount-card strong{display:block;margin-top:6px;font-size:24px} 3528 .signatures { display:grid; grid-template-columns:repeat(3,1fr); gap:24px; margin-top:54px; } 3529 .signature { border-top:1px solid #8fa0ad; padding-top:7px; text-align:center; font-size:10px; color:var(--muted); } 3530 .footer { margin-top:30px; padding-top:10px; border-top:1px solid var(--line); display:flex; justify-content:space-between; font-size:9px; color:#7b8c99; } 3531 @page { size:A4 portrait; margin:8mm; } 3532 @media print { 3533 html, body { 3534 margin:0!important; 3535 padding:0!important; 3536 width:100%!important; 3537 max-width:none!important; 3538 background:#fff; 3539 overflow:visible!important; 3540 } 3541 body { 3542 min-height:auto; 3543 } 3544 .document { 3545 width:100%!important; 3546 max-width:100%!important; 3547 margin:0!important; 3548 padding:0!important; 3549 overflow:visible!important; 3550 transform:none!important; 3551 zoom:1!important; 3552 break-inside:auto; 3553 page-break-inside:auto; 3554 } 3555 .header { 3556 width:100%; 3557 grid-template-columns:minmax(0,1.45fr) minmax(0,.75fr); 3558 gap:20px; 3559 padding:18px; 3560 } 3561 .brand, .meta, .grid > *, .summary-wrap > *, .receipt-hero > * { 3562 min-width:0; 3563 } 3564 .brand h1 { 3565 font-size:27px; 3566 } 3567 .brand p, .meta p { 3568 font-size:11px; 3569 line-height:1.4; 3570 } 3571 .doc-title { 3572 font-size:25px; 3573 } 3574 .doc-no { 3575 font-size:12px!important; 3576 overflow-wrap:anywhere; 3577 word-break:break-word; 3578 } 3579 .grid { 3580 grid-template-columns:minmax(0,1fr) minmax(0,1fr); 3581 gap:12px; 3582 } 3583 .box { 3584 padding:12px 14px; 3585 } 3586 .box strong { 3587 font-size:13px; 3588 } 3589 .box p { 3590 font-size:11px; 3591 } 3592 table { 3593 width:100%; 3594 max-width:100%; 3595 table-layout:fixed; 3596 } 3597 th, td { 3598 overflow-wrap:anywhere; 3599 word-break:break-word; 3600 } 3601 th { 3602 padding:8px 10px; 3603 font-size:9px; 3604 } 3605 td { 3606 padding:9px 10px; 3607 font-size:11px; 3608 } 3609 .num { 3610 white-space:nowrap; 3611 } 3612 .summary-wrap { 3613 grid-template-columns:minmax(0,1fr) minmax(0,38%); 3614 gap:14px; 3615 margin-top:12px; 3616 } 3617 .note-card { 3618 min-height:72px; 3619 } 3620 .amount-row { 3621 padding:7px 10px; 3622 font-size:10px; 3623 } 3624 .grand { 3625 padding:9px 10px; 3626 font-size:13px; 3627 } 3628 .signatures { 3629 width:100%; 3630 gap:24px; 3631 margin-top:40px; 3632 } 3633 .signature { 3634 font-size:9px; 3635 } 3636 .footer { 3637 width:100%; 3638 margin-top:22px; 3639 padding-top:8px; 3640 font-size:8px; 3641 } 3642 3643 } 3644 3645 /* v5.4.235 print readability polish */ 3646 .info-card, .note-card, .summary, .amount-card, .payment-card { border-color:#8f9baa!important; } 3647 table, th, td { border-color:#8f9baa!important; } 3648 .signature-line, .signature-box { border-color:#566575!important; } 3649 .muted, .meta, .address, .contact, .company-meta { color:#34495e!important; opacity:1!important; } 3650</style> 3651</head> 3652<body> 3653<div class="document ${a}">${n}</div> 3654<script> 3655window.onload = async () => { 3656 try { 3657 if (document.fonts && document.fonts.ready) await document.fonts.ready; 3658 } catch (e) {} 3659 requestAnimationFrame(() => { 3660 requestAnimationFrame(() => { 3661 setTimeout(() => window.print(), 80); 3662 }); 3663 }); 3664}; 3665<\/script> 3666</body> 3667</html>`),s.document.close()}function _1({view:t,companyId:n,companyName:a,companyCode:s,documentPrefixes:i,companyPhone:c,companyAddress:l,branches:m,selectedBranchId:d,actorUid:u,actorName:f,salesEntryMode:g=!1}){const[p,y]=x.useState([]),[b,N]=x.useState([]),[w,C]=x.useState([]),[R,I]=x.useState([]),[_,J]=x.useState(""),[T,G]=x.use
3667State(g),[z,H]=x.useState(null),[K,L]=x.useState(!1),[D,M]=x.useState(""),[Z,fe]=x.useState(null),[q,ne]=x.useState(null),[ae,Y]=x.useState(!1),[je,V]=x.useState(""),[$,F]=x.useState(""),[P,ue]=x.useState(""),[me,ge]=x.useState(!1),[de,Pe]=x.useState(0),[Re,Ee]=x.useState(0),[Be,We]=x.useState(0),[it,_e]=x.useState(0),[ee,qe]=x.useState(0),[se,pe]=x.useState(""),[Se,Me]=x.useState(()=>{const Ae=new Date,oe=Ae.getFullYear(),Ve=String(Ae.getMonth()+1).padStart(2,"0"),he=String(Ae.getDate()).padStart(2,"0");return`${oe}-${Ve}-${he}`}),[ot,wt]=x.useState(0),[ct,Ce]=x.useState("cash"),[De,Te]=x.useState(""),[ce,Ye]=x.useState(""),[Je,le]=x.useState(()=>{const Ae=new Date,oe=Ae.getFullYear(),Ve=String(Ae.getMonth()+1).padStart(2,"0"),he=String(Ae.getDate()).padStart(2,"0");return`${oe}-${Ve}-${he}`}),[nt,xt]=x.useState(null),[te,Ge]=x.useState(0),[pt,$e]=x.useState(0),[st,Nt]=x.useState(0),[be,jt]=x.useState(0),[bt,tn]=x.useState(0),[B,xe]=x.useState(""),[tt,ht]=x.useState(""),[dt,we]=x.useState(null),[rt,St]=x.useState(0),[Qt,gn]=x.useState("cash"),[An,Sn]=x.useState(""),[Xt,Wt]=x.useState(""),[Gt,$t]=x.useState("");x.useEffect(()=>qt(re(ie,`invoices/${n}`),Ae=>{if(!Ae.exists()){y([]);return}const oe=Ae.val();y(Object.entries(oe).map(([Ve,he])=>({id:Ve,...he})).sort((Ve,he)=>he.createdAt-Ve.createdAt))}),[n]),x.useEffect(()=>qt(re(ie,`collections/${n}`),Ae=>{if(!Ae.exists()){N([]);return}const oe=Ae.val();N(Object.entries(oe).map(([Ve,he])=>({id:Ve,...he})).sort((Ve,he)=>he.createdAt-Ve.createdAt))}),[n]),x.useEffect(()=>qt(re(ie,`customers/${n}`),Ae=>{if(!Ae.exists()){C([]);return}const oe=Ae.val();C(Object.entries(oe).map(([Ve,he])=>({...he,id:Ve})))}),[n]),x.useEffect(()=>qt(re(ie,`serviceJobs/${n}`),Ae=>{if(!Ae.exists()){I([]);return}const oe=Ae.val();I(Object.entries(oe).map(([Ve,he])=>({...he,id:Ve})))}),[n]),x.useEffect(()=>{const Ae=new Date,oe=b.filter(It=>{const Pt=new Date(It.collectedAt);return Pt.getFullYear()===Ae.getFullYear()&&Pt.getMonth()===Ae.getMonth()&&Pt.getDate()===Ae.getDate()}).reduce((It,Pt)=>It+Number(Pt.amount||0),0),Ve=p.reduce((It,Pt)=>It+Number(Pt.dueAmount||0),0),he=b.filter(It=>{const Pt=new Date(It.collectedAt||It.createdAt);return Pt.getFullYear()===Ae.getFullYear()&&Pt.getMonth()===Ae.getMonth()}).reduce((It,Pt)=>It+Number(Pt.amount||0),0),Oe=p.filter(It=>{const Pt=new Date(It.createdAt);return Pt.getFullYear()===Ae.getFullYear()&&Pt.getMonth()===Ae.getMonth()}).reduce((It,Pt)=>It+Number(Pt.grandTotal||0),0),ut=`${Ae.getFullYear()}-${String(Ae.getMonth()+1).padStart(2,"0")}-${String(Ae.getDate()).padStart(2,"0")}`,At=ut.slice(0,7);yn(re(ie,`dashboardStats/${n}`),{schemaVersion:2,aggregateDay:ut,aggregateMonth:At,todayCollection:oe,monthlyCollection:he,totalDue:Ve,totalInvoiceValue:Oe,invoiceCount:p.length,updatedAt:Date.now()}),Array.from(new Set([...p.map(It=>It.branchId),...b.map(It=>It.branchId)].filter(Boolean))).forEach(It=>{const Pt=p.filter(ga=>ga.branchId===It),Jn=b.filter(ga=>ga.branchId===It),na=Jn.filter(ga=>{const zn=new Date(ga.collectedAt||ga.createdAt);return zn.getFullYear()===Ae.getFullYear()&&zn.getMonth()===Ae.getMonth()&&zn.getDate()===Ae.getDate()}).reduce((ga,zn)=>ga+Number(zn.amount||0),0),Mn=Jn.filter(ga=>{const zn=new Date(ga.collectedAt||ga.createdAt);return zn.getFullYear()===Ae.getFullYear()&&zn.getMonth()===Ae.getMonth()}).reduce((ga,zn)=>ga+Number(zn.amount||0),0),Ea=Pt.filter(ga=>{const zn=new Date(ga.createdAt);return zn.getFullYear()===Ae.getFullYear()&&zn.getMonth()===Ae.getMonth()}).reduce((ga,zn)=>ga+Number(zn.grandTotal||0),0);yn(re(ie,`dashboardStats/${n}/branches/${It}`),{schemaVersion:2,aggregateDay:ut,aggregateMonth:At,todayCollection:na,monthlyCollection:Mn,totalDue:Pt.reduce((ga,zn)=>ga+Number(zn.dueAmount||0),0),totalInvoiceValue:Ea,invoiceCount:Pt.length,updatedAt:Date.now()})})},[b,p,n]);const Vt=new Set(["ready","quality_check","delivered"]),sn=Ae=>{const oe=Ae.trim(),Ve=oe.match(/\/(?:track|receipt)\/[^/]+\/([^/?#]+)/i);return{jobId:Ve?decodeURIComponent(Ve[1]):"",jobNumber:Ve?"":oe}},on=Ae=>{if(!Ae)return{eligible:!1,reason:"Service Job পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ Job Number à¦à¦¬à¦¾à¦° check à¦à¦°à§à¦¨à¥¤"};if(d!=="all"&&Ae.branchId!==d)return{eligible:!1,reason:"à¦à¦ Job selected branch-à¦à¦° নà§à¥¤"};const oe=p.find(Ve=>Ve.serviceJobId===Ae.id);return oe?{eligible:!1,reason:`Invoice already generated: ${oe.invoiceNumber}`}:Vt.has(Ae.status||"")?{eligible:!0,reason:"Job is eligible for invoice."}:{eligible:!1,reason:"Job invoice-à¦à¦° à¦à¦¨à§à¦¯ eligible নà§à¥¤ Quality Check complete à¦à¦°à§ Ready status à¦à¦°à§à¦¨à¥¤"}},ke=x.useMemo(()=>{const Ae=$.trim().toLowerCase();return R.filter(oe=>d==="all"||oe.branchId===d).map(oe=>{const Ve=w.find(ut=>ut.id===oe.customerId),he=p.find(ut=>ut.serviceJobId===oe.id),Oe=on(oe);return{job:oe,customer:Ve,existingInvoice:he,eligibility:Oe,searchText:[oe.jobNumber,Ve==null?void 0:Ve.name,Ve==null?void 0:Ve.phone,oe.deviceCategory,oe.brand,oe.model,oe.serialNumber].filter(
3667Boolean).join(" ").toLowerCase()}}).filter(oe=>!Ae||oe.searchText.includes(Ae)).sort((oe,Ve)=>oe.eligibility.eligible!==Ve.eligibility.eligible?oe.eligibility.eligible?-1:1:Ve.job.jobNumber.localeCompare(oe.job.jobNumber)).slice(0,30)},[R,w,p,d,$]),Ct=Ae=>{const oe=on(Ae);if(!oe.eligible){V(""),F(Ae.jobNumber),ue(oe.reason),ge(!1);return}V(Ae.id),F(Ae.jobNumber),ue(oe.reason),ge(!1)},Et=()=>{const Ae=sn($),oe=Ae.jobId?R.find(Ve=>Ve.id===Ae.jobId):R.find(Ve=>Ve.jobNumber.toLowerCase()===Ae.jobNumber.toLowerCase());if(oe){Ct(oe);return}if(ke.length===1){Ct(ke[0].job);return}V(""),ue(ke.length?"à¦à¦à¦¾à¦§à¦¿à¦ Job পাà¦à§à¦¾ à¦à§à¦à§à¥¤ Dropdown থà§à¦à§ সঠিঠJob select à¦à¦°à§à¦¨à¥¤":"Service Job পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ Job Number, Customer বা Phone à¦à¦¬à¦¾à¦° check à¦à¦°à§à¦¨à¥¤"),ge(!0)},Rt=R.find(Ae=>Ae.id===je),xn=w.find(Ae=>Ae.id===(Rt==null?void 0:Rt.customerId)),dn=Number(de||0)+Number(Re||0),Ln=Math.max(0,dn-Number(Be||0)+Number(it||0)),wa=Math.max(0,Ln-Number(ee||0));x.useEffect(()=>{if(!Rt)return;const Ae=Number(Rt.estimatedCost||0),oe=Number(Rt.labourCharge||0),Ve=Number(Rt.partsTotal||0);Pe(oe||(Ve?0:Ae)),Ee(Ve),We(Number(Rt.discountAmount||0)),qe(Number(Rt.advanceAmount||0)),pe(Rt.partsUsedDetails?`Prepared parts/product details: ${Rt.partsUsedDetails}`:""),_e(0)},[je]);const Ca=x.useMemo(()=>{const Ae=_.trim().toLowerCase();return p.filter(oe=>{if(d!=="all"&&oe.branchId!==d)return!1;if(!Ae)return!0;const Ve=w.find(he=>he.id===oe.customerId);return[oe.invoiceNumber,oe.jobNumber,oe.status,Ve==null?void 0:Ve.name,Ve==null?void 0:Ve.phone].filter(Boolean).some(he=>String(he).toLowerCase().includes(Ae))})},[p,w,_,d]),In=x.useMemo(()=>{const Ae=_.trim().toLowerCase();return b.filter(oe=>{if(d!=="all"&&oe.branchId!==d)return!1;if(!Ae)return!0;const Ve=w.find(he=>he.id===oe.customerId);return[oe.collectionNumber,oe.moneyReceiptNumber,oe.invoiceNumber,oe.method,Ve==null?void 0:Ve.name,Ve==null?void 0:Ve.phone].filter(Boolean).some(he=>String(he).toLowerCase().includes(Ae))})},[b,w,_,d]),Sa=x.useMemo(()=>{const Ae=D.trim().toLowerCase();return p.filter(oe=>{if(Number(oe.dueAmount||0)<=0||d!=="all"&&oe.branchId!==d)return!1;const Ve=w.find(Oe=>Oe.id===oe.customerId),he=[oe.invoiceNumber,oe.jobNumber,Ve==null?void 0:Ve.name,Ve==null?void 0:Ve.phone].filter(Boolean).join(" ").toLowerCase();return!Ae||he.includes(Ae)}).sort((oe,Ve)=>Ve.createdAt-oe.createdAt)},[p,w,D,d]),aa=x.useMemo(()=>p.filter(oe=>d==="all"||!d||oe.branchId===d).reduce((oe,Ve)=>{const he=Math.max(Number(Ve.grandTotal||0),0),Oe=Math.min(Math.max(Number(Ve.collectedAmount||0),0),he),ut=Math.max(he-Oe,0);return oe.invoiced+=he,oe.collected+=Oe,oe.due+=ut,oe},{invoiced:0,collected:0,due:0}),[p,d]),$a=()=>{V(""),F(""),ue(""),ge(!1),Pe(0),Ee(0),We(0),_e(0),qe(0),pe("");const Ae=new Date;Me(`${Ae.getFullYear()}-${String(Ae.getMonth()+1).padStart(2,"0")}-${String(Ae.getDate()).padStart(2,"0")}`)},jn=(Ae,oe,Ve,he,Oe,ut)=>{const At=PB(he.whatsapp||he.phone);if(!At){window.alert("Customer WhatsApp বা mobile number পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}const en=yI(n,Ae),It=[`Hello ${he.name},`,"","Your service invoice is ready.",`Invoice: ${oe}`,`Service Job: ${Ve}`,`Grand Total: ${Xa(Oe)}`,`Amount Due: ${Xa(ut)}`,"",`Digital Invoice: ${en}`,"","You may open, print or save the invoice as PDF from this link.","",a].join(` 3668`);window.open(`https://wa.me/${At}?text=${encodeURIComponent(It)}`,"_blank","noopener,noreferrer")},vs=async Ae=>{var he;if(Ae.preventDefault(),!Rt||!xn){window.alert("Please select a service job.");return}if(!Se){window.alert("Please select Invoice Date.");return}const oe=new Date(`${Se}T12:00:00`);if(Number.isNaN(oe.getTime())){window.alert("Invalid Invoice Date.");return}const Ve=new Date;if(Ve.setHours(23,59,59,999),oe.getTime()>Ve.getTime()){window.alert("Invoice Date cannot be in the future.");return}Y(!0);try{const Oe=oe.getTime(),ut=await Qf({companyId:n,companyCode:"VRX",documentType:"invoice",prefixes:i,timestamp:Oe}),At=Ta(re(ie,`invoices/${n}`)),en=wa<=0?"fully_collected":"uncollected",It={companyId:n,branchId:Rt.branchId,customerId:Rt.customerId,serviceJobId:Rt.id,invoiceNumber:ut,jobNumber:Rt.jobNumber,subtotal:dn,discount:Number(Be||0),vat:Number(it||0),advanceAmount:Number(ee||0),grandTotal:Ln,collectedAmount:Number(ee||0),dueAmount:wa,status:en,notes:se.trim(),labourCharge:Number(de||0),partsTotal:Number(Re||0),technicianName:Rt.assignedTechnician||"",technicianPhone:Rt.assignedTechnicianPhone||"",deviceLabel:[Rt.deviceCategory,Rt.brand,Rt.model].filter(
3668Boolean).join(" â "),publicInvoiceUrl:yI(n,At.key||""),invoiceDate:Se,createdAt:Oe,updatedAt:Oe},Pt=m.find(Xn=>Xn.id===Rt.branchId),Jn=(he=Pt==null?void 0:Pt.contacts)!=null&&he.length?Pt.contacts.map(Xn=>`${Xn.label}: ${Xn.phone}`).join(" · "):(Pt==null?void 0:Pt.phone)||c||"",na=Number(xn.dueAmount||0),Mn=At.key||"",Ea=await iE({companyId:n,branchId:Rt.branchId,actorUid:u,actorName:f,timestamp:Oe,invoiceId:Mn,invoiceNumber:ut,grandTotal:Ln,advanceAmount:Number(ee||0)}),ga={[`invoices/${n}/${Mn}`]:{id:Mn,...It,accountingPosted:!0},[`publicInvoices/${n}/${Mn}`]:{id:Mn,...It,accountingPosted:!0,companyName:a,companyPhone:Jn,companyAddress:(Pt==null?void 0:Pt.address)||l||"",customerName:xn.name,customerPhone:xn.phone,customerAddress:xn.address||"",branchName:(Pt==null?void 0:Pt.name)||""},[`serviceJobs/${n}/${Rt.id}/invoiceId`]:Mn,[`serviceJobs/${n}/${Rt.id}/invoiceNumber`]:ut,[`serviceJobs/${n}/${Rt.id}/dueAmount`]:wa,[`serviceJobs/${n}/${Rt.id}/updatedAt`]:Oe,[`customers/${n}/${xn.id}/dueAmount`]:na+wa,[`customers/${n}/${xn.id}/updatedAt`]:Oe,...Ea};await yn(re(ie),ga),await ia({companyId:n,actorUid:u,actorName:f,action:"invoice.created",entityType:"invoice",entityId:At.key||"",summary:`Created invoice ${ut}`,branchId:Rt.branchId,metadata:{invoiceNumber:ut,invoiceDate:Se,serviceJobId:Rt.id,jobNumber:Rt.jobNumber,grandTotal:Ln,dueAmount:wa}});const zn={id:At.key||"",...It};fe(zn),G(!1),$a(),jn(zn.id,zn.invoiceNumber,zn.jobNumber,xn,zn.grandTotal,zn.dueAmount)}catch(Oe){console.error(Oe),window.alert(Oe instanceof Error?Oe.message:"Invoice could not be created.")}finally{Y(!1)}},ka=async Ae=>{var he;if(Ae.status==="void")return;const oe=b.filter(Oe=>Oe.invoiceId===Ae.id&&Number(Oe.amount||0)>.005);if(oe.length){window.alert(`This invoice has ${oe.length} recorded collection(s) totalling ${Xa(oe.reduce((Oe,ut)=>Oe+Number(ut.amount||0),0))}. 3669 3670Correct those Collection(s) to 0 first, then Void the invoice. This safeguard prevents Cash/Bank and A/R from being reversed twice.`);return}const Ve=(he=window.prompt(`Void / cancel ${Ae.invoiceNumber}? 3671 3672This will reverse its invoice accounting and remove its outstanding due without deleting the audit history. 3673 3674Enter cancellation reason:`))==null?void 0:he.trim();if(Ve&&window.confirm(`Final confirmation 3675 3676Invoice: ${Ae.invoiceNumber} 3677Amount: ${Xa(Ae.grandTotal)} 3678Reason: ${Ve} 3679 3680Void this invoice?`)){Y(!0);try{const Oe=Date.now(),ut=Math.max(0,Number(Ae.dueAmount||0)),At=Ae.accountingPosted!==!1?await gI({companyId:n,branchId:Ae.branchId,actorUid:u,actorName:f,timestamp:Oe,invoiceId:Ae.id,invoiceNumber:Ae.invoiceNumber,oldGrandTotal:Number(Ae.grandTotal||0),newGrandTotal:0,oldAdvance:Number(Ae.advanceAmount||0),newAdvance:0,token:`void_${Oe}`}):{},en={[`invoices/${n}/${Ae.id}/subtotal`]:0,[`invoices/${n}/${Ae.id}/labourCharge`]:0,[`invoices/${n}/${Ae.id}/partsTotal`]:0,[`invoices/${n}/${Ae.id}/discount`]:0,[`invoices/${n}/${Ae.id}/vat`]:0,[`invoices/${n}/${Ae.id}/advanceAmount`]:0,[`invoices/${n}/${Ae.id}/grandTotal`]:0,[`invoices/${n}/${Ae.id}/collectedAmount`]:0,[`invoices/${n}/${Ae.id}/dueAmount`]:0,[`invoices/${n}/${Ae.id}/status`]:"void",[`invoices/${n}/${Ae.id}/voidedAt`]:Oe,[`invoices/${n}/${Ae.id}/voidedBy`]:f,[`invoices/${n}/${Ae.id}/voidReason`]:Ve,[`invoices/${n}/${Ae.id}/updatedAt`]:Oe,[`publicInvoices/${n}/${Ae.id}/subtotal`]:0,[`publicInvoices/${n}/${Ae.id}/labourCharge`]:0,[`publicInvoices/${n}/${Ae.id}/partsTotal`]:0,[`publicInvoices/${n}/${Ae.id}/discount`]:0,[`publicInvoices/${n}/${Ae.id}/vat`]:0,[`publicInvoices/${n}/${Ae.id}/advanceAmount`]:0,[`publicInvoices/${n}/${Ae.id}/grandTotal`]:0,[`publicInvoices/${n}/${Ae.id}/collectedAmount`]:0,[`publicInvoices/${n}/${Ae.id}/dueAmount`]:0,[`publicInvoices/${n}/${Ae.id}/status`]:"void",[`publicInvoices/${n}/${Ae.id}/voidedAt`]:Oe,[`publicInvoices/${n}/${Ae.id}/voidReason`]:Ve,[`publicInvoices/${n}/${Ae.id}/updatedAt`]:Oe,...At},It=w.find(Pt=>Pt.id===Ae.customerId);It&&(en[`customers/${n}/${It.id}/dueAmount`]=Math.max(0,Number(It.dueAmount||0)-ut),en[`customers/${n}/${It.id}/updatedAt`]=Oe),await yn(re(ie),en),await ia({companyId:n,actorUid:u,actorName:f,action:"invoice.updated",entityType:"invoice",entityId:Ae.id,summary:`Voided invoice ${Ae.invoiceNumber}`,branchId:Ae.branchId,metadata:{reason:Ve,oldGrandTotal:Ae.grandTotal,oldAdvance:Ae.advanceAmount,oldDue:ut,voided:!0}})}catch(Oe){console.error(Oe),window.alert(Oe instanceof Error?Oe.message:"Invoice void failed.")}finally{Y(!1)}}},Ja=Ae=>{xt(Ae),Ge(Number(Ae.labourCharge||0)),$e(Number(Ae.partsTotal||0)),Nt(Number(Ae.discount||0)),jt(Number(Ae.vat||0)),tn(Number(Ae.advanceAmount||0)),xe(Ae.notes||""),ht("")},_n=async Ae=>{if(Ae.preventDefault(),!nt)return;const oe=tt.trim();if(!oe){window.alert("Correction reason is required.");return}const Ve=Math.max(0,Number(te||0)),he=Math.max(0,Number(pt||0)),Oe=Math.max(0,Number(st||0)),ut=Math.max(0,Number(be||0)),At=Math.max(0,Number(bt||0
3680)),en=Ve+he,It=Math.max(0,en-Oe+ut),Jn=b.filter(zn=>zn.invoiceId===nt.id).reduce((zn,Xn)=>zn+Math.max(0,Number(Xn.amount||0)),0),na=At+Jn;if(It<na){window.alert(`Invoice total cannot be lower than already collected amount (${Xa(na)}). Edit/reduce the related Collection first.`);return}const Mn=Math.max(0,Number(nt.dueAmount||0)),Ea=Math.max(0,It-na),ga=Ea<=0?"fully_collected":na>0?"partially_collected":"uncollected";if(window.confirm(`Correct invoice ${nt.invoiceNumber}? 3681 3682Total: ${Xa(nt.grandTotal)} â ${Xa(It)} 3683Advance: ${Xa(nt.advanceAmount)} â ${Xa(At)} 3684Due: ${Xa(Mn)} â ${Xa(Ea)} 3685 3686Reason: ${oe}`)){Y(!0);try{const zn=Date.now(),Xn={subtotal:en,labourCharge:Ve,partsTotal:he,discount:Oe,vat:ut,advanceAmount:At,grandTotal:It,collectedAmount:na,dueAmount:Ea,status:ga,notes:B.trim(),updatedAt:zn,lastEditedAt:zn,lastEditedBy:f,lastEditReason:oe},Vn=nt.accountingPosted!==!1?await gI({companyId:n,branchId:nt.branchId,actorUid:u,actorName:f,timestamp:zn,invoiceId:nt.id,invoiceNumber:nt.invoiceNumber,oldGrandTotal:Number(nt.grandTotal||0),newGrandTotal:It,oldAdvance:Number(nt.advanceAmount||0),newAdvance:At,token:String(zn)}):{},ua={[`invoices/${n}/${nt.id}`]:{...nt,...Xn,accountingPosted:!0},[`publicInvoices/${n}/${nt.id}/subtotal`]:en,[`publicInvoices/${n}/${nt.id}/labourCharge`]:Ve,[`publicInvoices/${n}/${nt.id}/partsTotal`]:he,[`publicInvoices/${n}/${nt.id}/discount`]:Oe,[`publicInvoices/${n}/${nt.id}/vat`]:ut,[`publicInvoices/${n}/${nt.id}/advanceAmount`]:At,[`publicInvoices/${n}/${nt.id}/grandTotal`]:It,[`publicInvoices/${n}/${nt.id}/collectedAmount`]:na,[`publicInvoices/${n}/${nt.id}/dueAmount`]:Ea,[`publicInvoices/${n}/${nt.id}/status`]:ga,[`publicInvoices/${n}/${nt.id}/notes`]:B.trim(),[`publicInvoices/${n}/${nt.id}/updatedAt`]:zn,[`serviceJobs/${n}/${nt.serviceJobId}/labourCharge`]:Ve,[`serviceJobs/${n}/${nt.serviceJobId}/partsTotal`]:he,[`serviceJobs/${n}/${nt.serviceJobId}/discountAmount`]:Oe,[`serviceJobs/${n}/${nt.serviceJobId}/advanceAmount`]:At,[`serviceJobs/${n}/${nt.serviceJobId}/estimatedCost`]:It,[`serviceJobs/${n}/${nt.serviceJobId}/dueAmount`]:Ea,[`serviceJobs/${n}/${nt.serviceJobId}/updatedAt`]:zn,...Vn},Ma=w.find(Xe=>Xe.id===nt.customerId);Ma&&(ua[`customers/${n}/${Ma.id}/dueAmount`]=Math.max(0,Number(Ma.dueAmount||0)+(Ea-Mn)),ua[`customers/${n}/${Ma.id}/updatedAt`]=zn),await yn(re(ie),ua),await ia({companyId:n,actorUid:u,actorName:f,action:"invoice.updated",entityType:"invoice",entityId:nt.id,summary:`Corrected invoice ${nt.invoiceNumber}`,branchId:nt.branchId,metadata:{reason:oe,oldGrandTotal:nt.grandTotal,newGrandTotal:It,oldAdvance:nt.advanceAmount,newAdvance:At,oldDue:Mn,newDue:Ea}}),xt(null),ht("")}catch(zn){console.error(zn),window.alert(zn instanceof Error?zn.message:"Invoice correction failed.")}finally{Y(!1)}}},ha=Ae=>{we(Ae),St(Number(Ae.amount||0)),gn(Ae.method),Sn(Ae.reference||""),Wt(Ae.notes||""),$t("")},ta=async Ae=>{if(Ae.preventDefault(),!dt)return;const oe=Gt.trim(),Ve=Math.max(0,Number(rt||0));if(!oe){window.alert("Correction reason is required.");return}const he=p.find(Pt=>Pt.id===dt.invoiceId);if(!he){window.alert("Linked invoice could not be found.");return}const Oe=b.filter(Pt=>Pt.invoiceId===he.id&&Pt.id!==dt.id).reduce((Pt,Jn)=>Pt+Math.max(0,Number(Jn.amount||0)),0),ut=Math.max(0,Number(he.advanceAmount||0))+Oe+Ve;if(ut>Number(he.grandTotal||0)){window.alert(`Edited collection would exceed invoice total. Maximum allowed for this receipt is ${Xa(Math.max(0,Number(he.grandTotal||0)-Number(he.advanceAmount||0)-Oe))}.`);return}const At=Math.max(0,Number(he.dueAmount||0)),en=Math.max(0,Number(he.grandTotal||0)-ut),It=en<=0?"fully_collected":ut>0?"partially_collected":"uncollected";if(window.confirm(`Correct collection ${dt.collectionNumber}? 3687 3688Amount: ${Xa(dt.amount)} â ${Xa(Ve)} 3689Invoice Due: ${Xa(At)} â ${Xa(en)} 3690 3691Reason: ${oe}`)){Y(!0);try{const Pt=Date.now(),Jn={amount:Ve,method:Qt,reference:An.trim(),notes:Xt.trim(),updatedAt:Pt,lastEditedAt:Pt,lastEditedBy:f,lastEditReason:oe},na=await mn(re(ie,`moneyReceipts/${n}`)),Mn=na.exists()?Object.entries(na.val()).find(([,Xn])=>
3691(Xn==null?void 0:Xn.collectionId)===dt.id||(Xn==null?void 0:Xn.moneyReceiptNumber)===dt.moneyReceiptNumber):void 0,Ea=dt.accountingPosted!==!1?await EB({companyId:n,branchId:dt.branchId,actorUid:u,actorName:f,timestamp:Pt,collectionId:dt.id,collectionNumber:dt.collectionNumber,invoiceNumber:dt.invoiceNumber,oldAmount:Number(dt.amount||0),newAmount:Ve,oldMethod:dt.method,newMethod:Qt,token:String(Pt)}):{},ga={[`collections/${n}/${dt.id}`]:{...dt,...Jn,accountingPosted:!0},[`invoices/${n}/${he.id}/collectedAmount`]:ut,[`invoices/${n}/${he.id}/dueAmount`]:en,[`invoices/${n}/${he.id}/status`]:It,[`invoices/${n}/${he.id}/updatedAt`]:Pt,[`publicInvoices/${n}/${he.id}/collectedAmount`]:ut,[`publicInvoices/${n}/${he.id}/dueAmount`]:en,[`publicInvoices/${n}/${he.id}/status`]:It,[`publicInvoices/${n}/${he.id}/updatedAt`]:Pt,[`serviceJobs/${n}/${he.serviceJobId}/dueAmount`]:en,[`serviceJobs/${n}/${he.serviceJobId}/updatedAt`]:Pt,...Ea};Mn&&(ga[`moneyReceipts/${n}/${Mn[0]}`]={...Mn[1],...Jn,accountingPosted:!0});const zn=w.find(Xn=>Xn.id===he.customerId);zn&&(ga[`customers/${n}/${zn.id}/dueAmount`]=Math.max(0,Number(zn.dueAmount||0)+(en-At)),ga[`customers/${n}/${zn.id}/updatedAt`]=Pt),await yn(re(ie),ga),await ia({companyId:n,actorUid:u,actorName:f,action:"collection.updated",entityType:"collection",entityId:dt.id,summary:`Corrected collection ${dt.collectionNumber}`,branchId:dt.branchId,metadata:{reason:oe,invoiceNumber:dt.invoiceNumber,oldAmount:dt.amount,newAmount:Ve,oldInvoiceDue:At,newInvoiceDue:en}}),we(null),$t("")}catch(Pt){console.error(Pt),window.alert(Pt instanceof Error?Pt.message:"Collection correction failed.")}finally{Y(!1)}}},W=Ae=>{H(Ae),wt(Number(Ae.dueAmount||0)),Ce("cash"),Te(""),Ye("");const oe=new Date;le(`${oe.getFullYear()}-${String(oe.getMonth()+1).padStart(2,"0")}-${String(oe.getDate()).padStart(2,"0")}`)},ft=async Ae=>{var Ve;if(Ae.preventDefault(),!z)return;const oe=Number(ot||0);if(oe<=0){window.alert("Collection amount must be greater than zero.");return}if(oe>z.dueAmount){window.alert("Collection amount cannot exceed invoice due.");return}Y(!0);try{const[he,Oe,ut]=Je.split("-").map(Number),At=new Date,en=new Date(he,Oe-1,ut,At.getHours(),At.getMinutes(),At.getSeconds(),At.getMilliseconds());if(!Je||Number.isNaN(en.getTime())||en.getFullYear()!==he||en.getMonth()!==Oe-1||en.getDate()!==ut){window.alert("Please select a valid collection date.");return}const It=en.getTime(),Pt=await Qf({companyId:n,branchCode:(Ve=m.find(Ht=>Ht.id===z.branchId))==null?void 0:Ve.code,documentType:"collection",prefixes:i,timestamp:It}),Jn=await Qf({companyId:n,companyCode:"VRX",documentType:"moneyReceipt",prefixes:i,timestamp:It}),na=Ta(re(ie,`collections/${n}`)),Mn=Ta(re(ie,`moneyReceipts/${n}`)),Ea={companyId:n,branchId:z.branchId,customerId:z.customerId,serviceJobId:z.serviceJobId,invoiceId:z.id,invoiceNumber:z.invoiceNumber,collectionNumber:Pt,moneyReceiptNumber:Jn,amount:oe,method:ct,reference:De.trim(),notes:ce.trim(),collectedAt:It,createdAt:It,createdBy:f},ga=Number(z.collectedAmount||0)+oe,zn=Math.max(0,Number(z.grandTotal||0)-ga),Xn=zn<=0?"fully_collected":"partially_collected",Vn=na.key||"",ua=Mn.key||"",Ma=await oE({companyId:n,branchId:z.branchId,actorUid:u,actorName:f,timestamp:It,collectionId:Vn,collectionNumber:Pt,invoiceId:z.id,invoiceNumber:z.invoiceNumber,amount:oe,method:ct}),Xe=w.find(Ht=>Ht.id===z.customerId),Jt={[`collections/${n}/${Vn}`]:{id:Vn,...Ea,accountingPosted:!0},[`moneyReceipts/${n}/${ua}`]:{id:ua,...Ea,collectionId:Vn,accountingPosted:!0},[`invoices/${n}/${z.id}/collectedAmount`]:ga,[`invoices/${n}/${z.id}/dueAmount`]:zn,[`invoices/${n}/${z.id}/status`]:Xn,[`invoices/${n}/${z.id}/updatedAt`]:It,[`publicInvoices/${n}/${z.id}/collectedAmount`]:ga,[`publicInvoices/${n}/${z.id}/dueAmount`]:zn,[`publicInvoices/${n}/${z.id}/status`]:Xn,[`publicInvoices/${n}/${z.id}/updatedAt`]:It,[`serviceJobs/${n}/${z.serviceJobId}/dueAmount`]:zn,[`serviceJobs/${n}/${z.serviceJobId}/updatedAt`]:It,...Ma};if(ct==="cheque"){if(!De.trim())throw new Error("Cheque No. / Reference is required for cheque collection.");Jt[`chequeManagement/${n}/${Vn}`]={id:Vn,direction:"receivable",party:(Xe==null?void 0:Xe.name)||z.customerName||"Customer",chequeNo:De.trim(),bank:"",amount:oe,chequeDate:Je,promisedDate:Je,status:"pending",reference:Pt,sourceType:"collection",sourceId:Vn,branchId:z.branchId,createdAt:It,createdByUid:u,createdByName:f,history:{[String(It)]:{at:It,by:f,action:"created_from_collection",to:"pending",date:Je}}}}Xe&&(Jt[`customers/${n}/${Xe.id}/dueAmount`]=Math.max(0,Number(Xe.dueAmount||0)-oe),Jt[`customers/${n}/${Xe.id}/updatedAt`]=It),await yn(re(ie),Jt),await ia({companyId:n,actorUid:u,actorName:f,action:"collection.recorded",entityType:"collection",entityId:na.key||"",summary:`Recorded collection ${Pt}`,branchId:z.branchId,metadata:{collectionNumber:Pt,moneyReceiptNumber:Jn,invoiceNumber:z.invoiceNumber,amount:oe,method:ct}}),ne({id:na.key||"",...Ea}),H(null)}catch(he){console.error(he),window.alert(he instanceof Error?he.message:"Collection could not be recorded.")}finally{Y(!1)}},Zt=Ae=>{var Ht;const oe=w.find(xa=>xa.id===Ae.customerId),Ve=R.find(xa=>xa.id===Ae.serviceJobId),he=m.find(xa=>xa.id===Ae.branchId),Oe=I1,ut=Oe(a),At=Oe((he==null?void 0:he.name)||""),en=Oe((he==null?void 0:he.address)||l||""),It=Oe(Ae.invoiceNumber),Pt=Oe(Ae.jobNumber),Jn=Oe((oe==null?void 0:oe.name)||Ae.customerName||"Customer"),na=Oe((oe==null?void 0:oe.phone)||Ae.customerPhone||""),Mn=Oe((oe==null?void 0:oe.address)||""),Ea=Oe([Ve==null?void 0:Ve.deviceCategory,Ve==null?void 0:Ve.brand,Ve==null?void 0:Ve.model].filter(
3691Boolean).join(" â ")||"Service Job"),ga=Oe((Ve==null?void 0:Ve.serialNumber)||""),zn=Oe(Ae.technicianName||(Ve==null?void 0:Ve.assignedTechnician)||"Unassigned"),Xn=Oe(Ae.notes||"Thank you for choosing our service."),Vn=Oe(aj(Ae.status)),ua=(Ht=he==null?void 0:he.contacts)!=null&&Ht.length?he.contacts.map(xa=>`<strong>${Oe(xa.label)}:</strong> ${Oe(xa.phone)}`).join(" · "):he!=null&&he.phone||c?`<strong>Phone:</strong> ${Oe((he==null?void 0:he.phone)||c||"")}`:"",Ma=Number(Ae.labourCharge??Math.max(0,Ae.subtotal-Number((Ve==null?void 0:Ve.partsTotal)||0))),Xe=Number(Ae.partsTotal??(Ve==null?void 0:Ve.partsTotal)??0),Jt=[Ma>0?`<tr><td><strong>Service Charges</strong><br><span style="color:#718294">Service job ${Pt}</span></td><td class="num">${Xa(Ma)}</td></tr>`:"",Xe>0?`<tr><td><strong>Parts & Accessories</strong></td><td class="num">${Xa(Xe)}</td></tr>`:""].filter(Boolean);vI(Ae.invoiceNumber,` 3692 <div class="top-accent"></div> 3693 <div class="header"><div class="brand"><h1>${ut}</h1> 3694 <p class="branch-line"><strong>Invoiced Location:</strong> ${At}</p> 3695 <p><strong>Address:</strong> ${en}</p> 3696 <p>${ua}</p> 3697 </div><div class="meta"><h2 class="doc-title">INVOICE</h2><p class="doc-no">${It}</p><p>${new Date(Ae.createdAt).toLocaleString("en-GB")}</p><span class="status-pill">${Vn}</span></div></div> 3698 <div class="section"><p class="section-title">Customer & Service Information</p><div class="grid"> 3699 <div class="box"><span>Bill To</span><strong>${Jn}</strong><p>${na}</p><p>${Mn}</p></div> 3700 <div class="box"><span>Service Reference</span><strong>${Pt}</strong><p>${Ea}</p>${ga?`<p>Serial: ${ga}</p>`:""}<p>Technician: ${zn}</p></div> 3701 </div></div> 3702 <div class="section"><p class="section-title">Invoice Details</p><table><thead><tr><th>Description</th><th class="num">Amount</th></tr></thead><tbody> 3703 ${Jt.join("")||`<tr><td><strong>Service Invoice</strong></td><td class="num">${Xa(Ae.grandTotal)}</td></tr>`}</tbody></table></div> 3704 <div class="summary-wrap"><div class="note-card"><span class="label">Notes</span>${Xn}<div style="margin-top:18px;text-align:center"><span style="display:inline-block;border:4px solid ${Number(Ae.dueAmount||0)<=0?"#16834a":"#b42318"};color:${Number(Ae.dueAmount||0)<=0?"#16834a":"#b42318"};font-size:30px;font-weight:900;letter-spacing:2px;padding:6px 14px;transform:rotate(-5deg)">${Number(Ae.dueAmount||0)<=0?"PAID":"DUE"}</span></div></div> 3705 <div class="amounts"><div class="amount-row"><span>Subtotal</span><strong>${Xa(Ae.subtotal)}</strong></div><div class="amount-row"><span>Discount</span><strong>${Xa(Ae.discount)}</strong></div><div class="amount-row"><span>VAT</span><strong>${Xa(Ae.vat)}</strong></div><div class="amount-row"><span>Grand Total</span><strong>${Xa(Ae.grandTotal)}</strong></div><div class="amount-row"><span>Collected</span><strong class="paid">${Xa(Ae.collectedAmount)}</strong></div><div class="amount-row grand"><span>Amount Due</span><strong>${Xa(Ae.dueAmount)}</strong></div></div></div> 3706 <div class="signatures"><div class="signature">Received By</div><div class="signature">Checked By</div><div class="signature">Authorized By</div></div> 3707 <div class="footer"><span>Generated by VERIXO ERP</span><span>${It}</span></div> 3708 `)},vt=Ae=>{var Vn;const oe=w.find(ua=>ua.id===Ae.customerId),Ve=m.find(ua=>ua.id===Ae.branchId),he=I1,Oe=he(a),ut=he((Ve==null?void 0:Ve.name)||""),At=he((Ve==null?void 0:Ve.address)||l||""),en=he(Ae.moneyReceiptNumber),It=he((oe==null?void 0:oe.name)||Ae.customerName||"Customer"),Pt=he((oe==null?void 0:oe.phone)||Ae.customerPhone||""),Jn=he((oe==null?void 0:oe.address)||""),na=he(Ae.invoiceNumber),Mn=he(Ae.collectionNumber),Ea=he(Ae.createdBy),ga=he(Ae.reference||""),zn=he(Ae.notes||""),Xn=(Vn=Ve==null?void 0:Ve.contacts)!=null&&Vn.length?Ve.contacts.map(ua=>`<strong>${he(ua.label)}:</strong> ${he(ua.phone)}`).join(" · "):Ve!=null&&Ve.phone||c?`<strong>Phone:</strong> ${he((Ve==null?void 0:Ve.phone)||c||"")}`:"";vI(Ae.moneyReceiptNumber,` 3709 <div class="top-accent"></div> 3710 <div class="header"><div class="brand"><h1>${Oe}</h1><p class="branch-line"><strong>Collection Location:</strong> ${ut}</p><p><strong>Address:</strong> ${At}</p><p>${Xn}</p></div> 3711 <div class="meta"><h2 class="doc-title">MONEY RECEIPT</h2><p class="doc-no">${en}</p><p>
3711${new Date(Ae.collectedAt).toLocaleString("en-GB")}</p><span class="status-pill">Received</span></div></div> 3712 <div class="section"><p class="section-title">Collection Information</p><div class="grid"><div class="box"><span>Received From</span><strong>${It}</strong><p>${Pt}</p><p>${Jn}</p></div><div class="box"><span>Settled With</span><strong>${na}</strong><p>Collection: ${Mn}</p><p>Collected by: ${Ea}</p></div></div></div> 3713 <div class="receipt-hero"><div class="amount-card"><span>Amount Received</span><strong>${Xa(Ae.amount)}</strong></div><div class="box"><span>Payment Method</span><strong>${wv(Ae.method)}</strong>${ga?`<p>Reference: ${ga}</p>`:""}</div></div> 3714 <div class="section"><table><thead><tr><th>Against</th><th>Mode</th><th class="num">Amount</th></tr></thead><tbody><tr><td>${na}</td><td>${wv(Ae.method)}</td><td class="num"><strong>${Xa(Ae.amount)}</strong></td></tr></tbody></table></div> 3715 ${zn?`<div class="section note-card"><span class="label">Remarks</span>${zn}</div>`:""} 3716 <div class="signatures"><div class="signature">Received By</div><div class="signature">Checked By</div><div class="signature">Authorized By</div></div> 3717 <div class="footer"><span>Generated by VERIXO ERP · ${Ea}</span><span>${en}</span></div> 3718 `)};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-header finance-page-header",style:g?{display:"none"}:void 0,children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Finance"}),e.jsx("h1",{children:t==="invoices"?g?"Service Sale":"Invoices":"Collections"}),e.jsx("p",{children:t==="invoices"?g?"Create a service invoice from an eligible Service Job. Invoice Preparation values preload automatically.":"Generate service invoices and track outstanding dues.":"Record customer collections and print money receipts."})]}),t==="invoices"?e.jsxs("button",{className:"primary-action-button",onClick:()=>G(!0),children:[e.jsx(as,{size:18})," Generate Invoice"]}):e.jsxs("button",{className:"primary-action-button",onClick:()=>{M(""),L(!0)},children:[e.jsx(as,{size:18})," Record Collection"]})]}),e.jsxs("section",{className:"finance-summary-grid",style:g?{display:"none"}:void 0,children:[e.jsxs("article",{children:[e.jsx("span",{children:"Total Invoiced"}),e.jsx("strong",{children:Xa(aa.invoiced)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Collected"}),e.jsx("strong",{children:Xa(aa.collected)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Due"}),e.jsx("strong",{children:Xa(aa.due)})]})]}),e.jsxs("section",{className:"data-card finance-data-card",style:g?{display:"none"}:void 0,children:[e.jsx("div",{className:"table-toolbar",children:e.jsx("div",{className:"table-search",children:e.jsx("input",{value:_,onChange:Ae=>J(Ae.target.value),placeholder:t==="invoices"?"Search invoice, job or customer":"Search collection, receipt or customer"})})}),t==="invoices"?e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Invoice"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Job"}),e.jsx("th",{children:"Total"}),e.jsx("th",{children:"Advance"}),e.jsx("th",{children:"Collected"}),e.jsx("th",{children:"Due"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Actions"})]})}),e.jsxs("tbody",{children:[Ca.map(Ae=>{const oe=w.find(Ve=>Ve.id===Ae.customerId);return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:Ae.invoiceNumber}),e.jsx("small",{children:new Date(Ae.createdAt).toLocaleDateString("en-GB")})]}),e.jsxs("td",{children:[e.jsx("strong",{children:(oe==null?void 0:oe.name)||Ae.customerName||"Customer"}),e.jsx("small",{children:(oe==null?void 0:oe.phone)||Ae.customerPhone||""})]}),e.jsx("td",{children:Ae.jobNumber}),e.jsx("td",{children:Xa(Ae.grandTotal)}),e.jsx("td",{children:Xa(Math.max(Number(Ae.advanceAmount||0),0))}),e.jsx("td",{children:Xa(Ae.collectedAmount)}),e.jsx("td",{children:Xa(Ae.dueAmount)}),e.jsx("td",{children:e.jsx("span",{className:`finance-status ${Ae.status}`,children:aj(Ae.status)})}),e.jsx("td",{children:e.jsxs("div",{className:"action-buttons",children:[e.jsx("button",{title:"View",onClick:()=>fe(Ae),children:e.jsx(ui,{size:17})}),e.jsx("button",{title:"Print invoice",onClick:()=>Zt(Ae),children:e.jsx(Wi,{size:17})}),e.jsx("button",{title:"Edit / correct invoice",onClick:()=>Ja(Ae),children:e.jsx(Zi,{size:17})}),e.jsx("button",{title:"Record collection",disabled:Ae.dueAmount<=0||Ae.status==="void",onClick:()=>W(Ae),children:e.jsx(Ch,{size:17})}),e.jsx("button",{title:"Void / cancel wrong invoice",disabled:ae||Ae.status==="void",onClick:()=>ka(Ae),children:e.jsx(M4,{size:17})})]})})]},Ae.id)}),!Ca.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"empty-table",children:"No invoices found."})})]})]})}):e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Collection"}),e.jsx("th",{children:"Money Receipt"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Invoice"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Actions"})]})}),e.jsxs("tbody",{children:[In.map(Ae=>{const oe=w.find(Ve=>Ve.id===Ae.customerId);return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:Ae.collectionNumber})}),e.jsx("td",{children:Ae.moneyReceiptNumber}),e.jsxs("td",{children:[e.jsx("strong",{children:(oe==null?void 0:oe.name)||Ae.customerName||"Customer"}),e.jsx("small",{children:(oe==null?void 0:oe.phone)||Ae.customerPhone||""})]}),e.jsx("td",{children:Ae.invoiceNumber}),e.jsx("td",{children:Xa(Ae.amount)}),e.jsx("td",{children:wv(Ae.method)}),e.jsx("td",{children:new Date(Ae.collectedAt).toLocaleDateString("en-GB")}),e.jsx("td",{children:e.jsxs("div",{className:"action-buttons",children:[e.jsx("button",{title:"View receipt",onClick:()=>ne(Ae),children:e.jsx(ui,{size:17})}),e.jsx("button",{title:"Print receipt",onClick:()=>vt(Ae),children:e.jsx(Wi,{size:17})}),e.jsx("button",{title:"Edit / correct collection",onClick:()=>ha(Ae),children:e.jsx(Zi,{size:17})})]})})]},Ae.id)}),!In.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty-table",children:"No collections foun
3718d."})})]})]})})]}),T&&e.jsx("div",{className:g?"service-sale-inline-shell":"modal-backdrop",onMouseDown:()=>{g||G(!1)},children:e.jsxs("section",{className:g?"service-sale-inline-form":"modal finance-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[!g&&e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Finance"}),e.jsx("h2",{children:"Generate Invoice"})]}),e.jsx("button",{onClick:()=>G(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:vs,className:"invoice-create-form",children:[e.jsxs("div",{className:"invoice-create-layout",children:[e.jsxs("div",{className:"invoice-form-fields",children:[e.jsxs("section",{className:"invoice-date-control full-field",children:[e.jsxs("div",{className:"invoice-date-control-copy",children:[e.jsx("span",{children:"Invoice Date"}),e.jsx("small",{children:"Defaults to today. Backdated invoices must be in an unlocked accounting period."})]}),e.jsx("input",{type:"date",value:Se,max:`${new Date().getFullYear()}-${String(new Date().getMonth()+1).padStart(2,"0")}-${String(new Date().getDate()).padStart(2,"0")}`,onChange:Ae=>Me(Ae.target.value),required:!0})]}),e.jsxs("section",{className:"invoice-job-search full-field",children:[e.jsxs("div",{className:"invoice-job-search-heading",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Invoice Eligible Job"}),e.jsx("strong",{children:"Search by Job No, Customer, Phone or Device"})]}),e.jsx(Xw,{size:22})]}),e.jsxs("div",{className:"invoice-searchable-select",children:[e.jsxs("div",{className:"invoice-searchable-input",children:[e.jsx(xr,{size:17}
3718),e.jsx("input",{value:$,onFocus:()=>ge(!0),onChange:Ae=>{F(Ae.target.value),V(""),ue(""),ge(!0)},onKeyDown:Ae=>{Ae.key==="Enter"&&(Ae.preventDefault(),Et()),Ae.key==="Escape"&&ge(!1)},placeholder:"Search or scan Service Job"}),e.jsx("button",{type:"button","aria-label":"Toggle job list",onClick:()=>ge(Ae=>!Ae),children:e.jsx(Yw,{size:18,className:me?"rotated":""})})]}),me&&e.jsxs("div",{className:"invoice-job-options",children:[ke.map(({job:Ae,customer:oe,existingInvoice:Ve,eligibility:he})=>{var Oe;return e.jsxs("button",{type:"button",className:`invoice-job-option ${he.eligible?"eligible":"disabled"}`,onClick:()=>Ct(Ae),children:[e.jsxs("div",{className:"invoice-job-option-main",children:[e.jsxs("div",{children:[e.jsx("strong",{children:Ae.jobNumber}),e.jsxs("span",{children:[(oe==null?void 0:oe.name)||"Unknown Customer"," ·"," ",(oe==null?void 0:oe.phone)||"No phone"]})]}),he.eligible?e.jsx(Ms,{size:18}):e.jsx("span",{className:"invoice-job-option-status",children:Ve?Ve.invoiceNumber:(Oe=Ae.status)==null?void 0:Oe.replaceAll("_"," ")})]}),e.jsx("small",{children:[Ae.deviceCategory,Ae.brand,Ae.model].filter(Boolean).join(" â ")}),!he.eligible&&e.jsx("em",{children:he.reason})]},Ae.id)}),!ke.length&&e.jsx("div",{className:"invoice-job-empty",children:"No matching Service Job found."})]})]}),e.jsx("div",{className:"invoice-search-actions",children:e.jsxs("button",{type:"button",className:"vx-button vx-button-secondary",onClick:Et,children:[e.jsx(xr,{size:17}),"Find Exact Match"]})}),P&&e.jsx("div",{className:`invoice-eligibility-message ${Rt?"eligible":"blocked"}`,children:P})]}),Rt&&xn&&e.jsxs("section",{className:"invoice-job-reference",children:[e.jsxs("div",{className:"invoice-job-reference-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Service Job Reference"}),e.jsx("strong",{children:Rt.jobNumber})]}),e.jsx("span",{className:"job-status status-ready",children:"Ready"})]}),Rt.status==="delivered"&&e.jsx("div",{className:"invoice-delivered-warning",children:"Warning: Job already Delivered. Invoice generation should normally happen before delivery."}),e.jsxs("div",{className:"invoice-job-reference-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:xn.name}),e.jsx("small",{children:xn.phone})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device"}),e.jsx("strong",{children:[Rt.deviceCategory,Rt.brand,Rt.model].filter(Boolean).join(" â ")}),e.jsx("small",{children:Rt.serialNumber||"No serial"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Technician"}),e.jsx("strong",{children:Rt.assignedTechnician||"Unassigned"}),e.jsx("small",{children:Rt.assignedTechnicianPhone||""})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Service Type"}),e.jsx("strong",{children:Rt.serviceType||"Service Job"}),e.jsx("small",{children:"Invoice will be linked automatically"})]})]})]}),e.jsxs("div",{className:"invoice-field-grid",children:[e.jsxs("label",{children:["Service Charges",e.jsx("input",{type:"number",min:"0",step:"0.01",value:de,onChange:Ae=>Pe(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Parts & Accessories",e.jsx("input",{type:"number",min:"0",step:"0.01",value:Re,onChange:Ae=>Ee(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Discount",e.jsx("input",{type:"number",min:"0",step:"0.01",value:Be,onChange:Ae=>We(Number(Ae.target.value))})]}),e.jsxs("label",{children:["VAT",e.jsx("input",{type:"number",min:"0",step:"0.01",value:it,onChange:Ae=>_e(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Advance Collected",e.jsx("input",{type:"number",min:"0",step:"0.01",value:ee,onChange:Ae=>qe(Number(Ae.target.value))})]}),e.jsxs("label",{className:"invoice-notes-field",children:["Notes",e.jsx("textarea",{rows:3,value:se,onChange:Ae=>pe(Ae.target.value),placeholder:"Optional invoice note..."})]})]})]}),e.jsxs("aside",{className:"invoice-summary-panel",children:[e.jsxs("div",{className:"invoice-summary-heading",children:[e.jsx("span",{children:"Invoice Summary"}),e.jsx("small",{children:"Live calculation"})]}),e.jsxs("div",{className:"invoice-summary-row",children:[e.jsx("span",{children:"Service Charges"}),e.jsx("strong",{children:Xa(Number(de||0))})]}),e.jsxs("div",{className:"invoice-summary-row",children:[e.jsx("span",{children:"Parts & Accessories"}),e.jsx("strong",{children:Xa(Number(Re||0))})]}),e.jsxs("div",{className:"invoice-summary-row subtotal",children:[e.jsx("span",{children:"Subtotal"}),e.jsx("strong",{children:Xa(dn)})]}),e.jsxs("div",{className:"invoice-summary-row",children:[e.jsx("span",{children:"Discount"}),e.jsxs("strong",{children:["â ",Xa(Number(Be||0))]})]}),e.jsxs("div",{className:"invoice-summary-row",children:[e.jsx("span",{children:"VAT"}),e.jsxs("strong",{children:["+ ",Xa(Number(it||0))]})]}),e.jsxs("div",{className:"invoice-summary-row",children:[e.jsx("span",{children:"Advance Collected"}),e.jsxs("strong",{children:["â ",Xa(Number(ee||0))]})]}),e.jsxs("div",{className:"invoice-summary-total",children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:Xa(Ln)})]}),e.jsxs("div",{className:"invoice-summary-due",children:[e.jsx("span",{children:"Amount Due"}),e.jsx("strong",{children:Xa(wa)})]})]})]}),e.jsxs("div",{className:"invoice-modal-actions",children:[!g&&e.jsx("button",{type:"button",className:"invoice-cancel-button",onClick:()=>G(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"invoice-submit-button",disabled:ae||!Rt,children:[e.jsx(Zs,{size:18}),ae?"Generating...":"Generate Invoice"]})]})]})]})}),nt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>xt(null),children:e.jsxs("section",{className:"modal finance-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Invoice correction"}),e.jsx("h2",{children:"Edit Invoice"}),e.jsxs("span",{children:[nt.invoiceNumber," · ",nt.jobNumber]})]}),e.jsx("button",{onClick:()=>xt(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:_n,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Service / Labour Charge",e.jsx("input",{type:"number",min:"0",step:"0.01",value:te,onChange:Ae=>Ge(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Parts Total",e.jsx("input",{type:"number",min:"0",step:"0.01",value:pt,onChange:Ae=>$e(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Discount",e.jsx("input",{type:"number",min:"0",step:"0.01",value:st,onChange:Ae=>Nt(Number(Ae.target.value))})]}),e.jsxs("label",{children:["VAT",e.jsx("input",{type:"number",min:"0",step:"0.01",value:be,onChange:Ae=>jt(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Advance",e.jsx("input",{type:"number",min:"0",step:"0.01",value:bt,onCh
3718ange:Ae=>tn(Number(Ae.target.value))})]}),e.jsxs("label",{className:"full-field",children:["Notes",e.jsx("textarea",{rows:3,value:B,onChange:Ae=>xe(Ae.target.value)})]}),e.jsxs("label",{className:"full-field",children:["Correction Reason *",e.jsx("textarea",{rows:2,required:!0,value:tt,onChange:Ae=>ht(Ae.target.value),placeholder:"Why is this invoice being corrected?"})]})]}),e.jsxs("div",{className:"finance-edit-summary",children:[e.jsxs("span",{children:["Revised Total ",e.jsx("b",{children:Xa(Math.max(0,te+pt-st+be))})]}),e.jsxs("span",{children:["Recorded Collections ",e.jsx("b",{children:Xa(b.filter(Ae=>Ae.invoiceId===nt.id).reduce((Ae,oe)=>Ae+Number(oe.amount||0),0))})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>xt(null),children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:ae,children:[e.jsx(hr,{size:17}),ae?"Saving...":"Save Correction"]})]})]})]})}),dt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>we(null),children:e.jsxs("section",{className:"modal finance-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Collection correction"}),e.jsx("h2",{children:"Edit Collection"}),e.jsxs("span",{children:[dt.collectionNumber," · ",dt.invoiceNumber]})]}),e.jsx("button",{onClick:()=>we(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:ta,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Collection Amount",e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:rt,onChange:Ae=>St(Number(Ae.target.value))})]}),e.jsxs("label",{children:["Collection Method",e.jsxs("select",{value:Qt,onChange:Ae=>gn(Ae.target.value),children:[e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bkash",children:"bKash"}),e.jsx("option",{value:"nagad",children:"Nagad"}),e.jsx("option",{value:"card",children:"Card"}),e.jsx("option",{value:"bank_transfer",children:"Bank Transfer"}),e.jsx("option",{value:"cheque",children:"Cheque"}),e.jsx("option",{value:"mixed",children:"Mixed"})]})]}),e.jsxs("label",{children:["Reference",e.jsx("input",{value:An,onChange:Ae=>Sn(Ae.target.value)})]}),e.jsxs("label",{className:"full-field",children:["Notes",e.jsx("textarea",{rows:3,value:Xt,onChange:Ae=>Wt(Ae.target.value)})]}),e.jsxs("label",{className:"full-field",children:["Correction Reason *",e.jsx("textarea",{rows:2,required:!0,value:Gt,onChange:Ae=>$t(Ae.target.value),placeholder:"Why is this collection being corrected/cancelled? (Set amount to 0 to cancel)"})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>we(null),children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:ae,children:[e.jsx(hr,{size:17}),ae?"Saving...":"Save Correction"]})]})]})]})}),K&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>L(!1),children:e.jsxs("section",{className:"modal finance-modal due-invoice-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Customer Collection"}),e.jsx("h2",{children:"Select Due Invoice"}),e.jsx("span",{children:"Only invoices with an outstanding due are shown."})]}),e.jsx("button",{onClick:()=>L(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"due-invoice-search",children:[e.jsx("input",{autoFocus:!0,value:D,onChange:Ae=>M(Ae.target.value),placeholder:"Search by Invoice No, Mobile No, Customer or Job No"}),e.jsx("small",{children:"You can enter a full or partial mobile number."})]}),e.jsxs("div",{className:"due-invoice-results",children:[Sa.map(Ae=>{const oe=w.find(Ve=>Ve.id===Ae.customerId);return e.jsxs("button",{type:"button",className:"due-invoice-result",onClick:()=>{L(!1),W(Ae)},children:[e.jsxs("div",{className:"due-invoice-result-main",children:[e.jsx("strong",{children:Ae.invoiceNumber}),e.jsx("span",{children:(oe==null?void 0:oe.name)||"Customer"}),e.jsxs("small",{children:[(oe==null?void 0:oe.phone)||"No mobile"," · ",Ae.jobNumber]})]}),e.jsxs("div",{className:"due-invoice-result-finance",children:[e.jsxs("span",{children:["Total ",Xa(Ae.grandTotal)]}),e.jsxs("span",{children:["Collected ",Xa(Ae.collectedAmount)]}),e.jsxs("strong",{children:["Due ",Xa(Ae.dueAmount)]})]})]},Ae.id)}),!Sa.length&&e.jsx("div",{className:"empty-table",children:"No due invoice found for this search."})]})]})}),z&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>H(null),children:e.jsxs("section",{className:"modal finance-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Customer collection"}),e.jsx("h2",{children:"Record Collection"}),e.jsx("span",{children:z.invoiceNumber})]}),e.jsx("button",{onClick:()=>H(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:ft,children:[e.jsxs("div",{className:"collection-balance",children:[e.jsx("span",{children:"Invoice Due"}),e.jsx("strong",{children:Xa(z.dueAmount)})]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Collection Date",e.jsx("input",{type:"date",value:Je,onChange:Ae=>le(Ae.target.value),required:!0})]}),e.jsxs("label",{children:["Collection Amount",e.jsx("input",{type:"number",min:"0.01",max:z.dueAmount,step:"0.01",value:ot,onChange:Ae=>wt(Number(Ae.target.value)),required:!0})]}),e.jsxs("label",{children:["Collection Method",e.jsxs("select",{value:ct,onChange:Ae=>Ce(Ae.target.value),children:[e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bkash",children:"bKash"}),e.jsx("option",{value:"nagad",children:"Nagad"}),e.jsx("option",{value:"card",children:"Card"}),e.jsx("option",{value:"bank_transfer",children:"Bank Transfer"}),e.jsx("option",{value:"cheque",children:"Cheque"}),e.jsx("option",{value:"mixed",children:"Mixed"})]})]}),e.jsxs("label",{children:["Reference",e.jsx("input",{value:De,onChange:Ae=>Te(Ae.target.value),placeholder:"Transaction / cheque reference"})]}),e.jsxs("label",{className:"full-field",children:["Notes",e.jsx("textarea",{rows:3,value:ce,onChange:Ae=>Ye(Ae.target.value)})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>H(null),children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:ae,children:[e.jsx(Ll,{size:17}),ae?"Saving...":"Record Collection"]})]})]})]})}),Z&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>fe(null),children:e.jsxs("section",{className:"modal finance-preview-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Invoice"}),e.jsx("h2",{children:Z.invoiceNumber})]}),e.jsx("button",{onClick:()=>fe(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"finance-preview-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Job"}),e.jsx("strong",{children:Z.jobNumber})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Status"}),e.jsx("strong",{children:aj(Z.status)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:Xa(Z.grandTotal)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Collected"}),e.jsx("strong",{children:Xa(Z.collectedAmount)})]}),e.jsxs("div",{className:"full",children:[e.jsx("span",{children:"Due"}),e.jsx("strong",{children:Xa(Z.dueAmount)})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("button",{className:"secondary-button",onClick:()=>Zt(Z),children:[e.jsx(Wi,{size:17})," Print Invoice"]}),Z.dueAmount>0&&e.jsxs("button",{onClick:()=>{fe(null),W(Z)},children:[e.jsx(Ch,{size:17})," Record Collection"]})]})]})}),q&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>ne(null),children:e.jsxs("section",{className:"modal finance-preview-modal",onMouseDown:Ae=>Ae.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Money Receipt"}),e.jsx("h2",{children:q.moneyReceiptNumber})]}),e.jsx("button",{onClick:()=>ne(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"receipt-amount",children:[e.jsx(RD,{size:25}),e.jsx("span",{children:"Amount Collected"}),e.jsx("strong",{children:Xa(q.amount)}),e.jsx("small",{children:wv(q.method)})]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{onClick:()=>vt(q),children:[e.jsx(Wi,{size:17})," Print Money Receipt"]})})]})})]})}const ab=["company.manage","branch.manage","user.manage","settings.manage","customer.read","customer.manage","crmConnector.read","crmConnector.manage","job.read","job.manage","job.delete","estimate.read","estimate.manage","finance.read","finance.manage","purchase.read","purchase.manage","promotion.read","promotion.manage","dataMigration.manage","employee.read","employee.manage","performance.read","performance.manage","appraisal.view","appraisal.create","appraisal.edit_draft","a
3718ppraisal.submit","appraisal.approve","appraisal.finalize","appraisal.view_team","appraisal.view_all","appraisal.settings","attendance.read","attendance.manage","attendance.device.manage","payroll.read","payroll.manage","payroll.payment.record","payroll.payment.reverse","payroll.statutory.record","payroll.statutory.reverse","delivery.manage","audit.read"],cE={super_admin:ab,owner:ab,admin:ab,branch_manager:["customer.read","customer.manage","job.read","job.manage","estimate.read","estimate.manage","finance.read","finance.manage","purchase.read","purchase.manage","employee.read","performance.read","performance.manage","appraisal.view","appraisal.create","appraisal.edit_draft","appraisal.submit","appraisal.approve","appraisal.view_team","attendance.read","attendance.manage","payroll.read","delivery.manage","audit.read"],service_incharge:["customer.read","customer.manage","job.read","job.manage","estimate.read","estimate.manage","finance.read","finance.manage","performance.read","performance.manage","appraisal.view","appraisal.create","appraisal.edit_draft","a
3718ppraisal.submit","appraisal.approve","appraisal.view_team","delivery.manage","audit.read"],reception:["customer.read","customer.manage","job.read","job.manage","estimate.read","estimate.manage","delivery.manage"],operator:["customer.read","customer.manage","job.read","job.manage","estimate.read","estimate.manage","delivery.manage"],branch_operator:["customer.read","customer.manage","job.read","job.manage","estimate.read","estimate.manage","finance.read","finance.manage","performance.read","delivery.manage"],technician:["customer.read","job.read","job.manage"],accountant:["customer.read","job.read","estimate.read","finance.read","finance.manage","purchase.read","payroll.read","payroll.payment.record","payroll.statutory.record"],sales:["customer.read","customer.manage","estimate.read","estimate.manage","finance.read","performance.read"],store:["job.read","purchase.read","purchase.manage"],hr:["employee.read","employee.manage","performance.read","performance.manage","appraisal.view","appraisal.create","appraisal.edit_draft","a
3718ppraisal.submit","appraisal.approve","appraisal.finalize","appraisal.view_team","appraisal.view_all","appraisal.settings","attendance.read","attendance.manage","payroll.read","payroll.manage"],viewer:["customer.read","job.read","estimate.read","finance.read","employee.read","performance.read","attendance.read","payroll.read","audit.read"]},Lm=[...ab],bI={"company.manage":"Company Settings","branch.manage":"Branch Management","user.manage":"User & Permission Management","settings.manage":"System / Organization Settings","customer.read":"View Customers","customer.manage":"Manage Customers","crmConnector.read":"CRM Website Connectors · View","crmConnector.manage":"CRM Website Connectors · Manage","job.read":"View Service Jobs","job.manage":"Manage Service Jobs","job.delete":"Delete Service Jobs","estimate.read":"View Estimates","estimate.manage":"Manage Estimates","finance.read":"View Finance","finance.manage":"Manage Finance","purchase.read":"View Purchase & Inventory","purchase.manage":"Manage Purchase & Inventory","promotion.read":"Promotions · View & PDF Report","promotion.manage":"Promotions · Create / Manage","dataMigration.manage":"Data Migration · Access & Import","employee.read":"View Employees","employee.manage":"Manage Employees","performance.read":"View Performance","performance.manage":"Manage Performance","appraisal.view":"Appraisal · View","appraisal.create":"Appraisal · Create","appraisal.edit_draft":"Appraisal · Edit Draft","appraisal.submit":"Appraisal · Submit for Approval","appraisal.approve":"Appraisal · Approve / Return","appraisal.finalize":"Appraisal · Finalize & Lock","appraisal.view_team":"Appraisal · View Team","appraisal.view_all":"Appraisal · View All","appraisal.settings":"Appraisal · Settings","attendance.read":"View Attendance","attendance.manage":"Manage Attendance","attendance.device.manage":"Attendance Device Manager","payroll.read":"View Payroll","payroll.manage":"Manage Payroll","payroll.payment.record":"Record Salary Payment","payroll.payment.reverse":"Reverse Salary Payment","payroll.statutory.record":"Record Tax / PF Settlement","payroll.statutory.reverse":"Reverse Tax / PF Settlement","delivery.manage":"Delivery / Scan","audit.read":"View Audit Log"};function sa(t,n){var i,c,l,m,d,u;if(t.role==="owner"||t.role==="super_admin"||n==="crmConnector.read"&&((i=t.permissionOverrides)==null?void 0:i["crmConnector.manage"])===!0||n==="promotion.read"&&(((c=t.permissionOverrides)==null?void 0:c["promotion.manage"])??((l=t.permissionOverrides)==null?void 0:l.promotion__dot__manage))===!0)return!0;const a=n.replaceAll(".","__dot__"),s=((m=t.permissionOverrides)==null?void 0:m[n])??((d=t.permissionOverrides)==null?void 0:d[a]);return typeof s=="boolean"?s:((u=cE[t.role])==null?void 0:u.includes(n))??!1}function Bm(t){return[...cE[t]||[]]}const jh={super_admin:"Super Admin",owner:"Owner",admin:"Admin",branch_manager:"Branch Manager",service_incharge:"Service In-Charge",reception:"Reception",operator:"Operator",branch_operator:"Branch Executive",technician:"Technician",accountant:"Accounts",sales:"Sales",store:"Store",hr:"HR",viewer:"Viewer"};function TB(t,n){return t.parentId?n.get(t.parentId):void 0}function MB(t,n){const a=new Map(n.map(l=>[l.id,l])),s=new Set;let i=t,c=0;for(;i!=null&&i.parentId&&!s.has(i.id);){s.add(i.id);const l=TB(i,a);if(!l)break;c+=1,i=l}return c}function $B(t,n){return!t.parentId&&t.isGroup?"Control":t.isGroup?"Subsidiary":"Ledger Account"}function lE(t,n){const a=new Set;let s=t;for(;s.parentId&&!a.has(s.id);){a.add(s.id);const i=n.get(s.parentId);if(!i)break;s=i}return s}function OB(t,n){const a=lE(t,n);if(a.id===t.id)return t;const s=new Set;let i=t,c=t;for(;i.parentId&&!s.has(i.id);){s.add(i.id);const l=n.get(i.parentId);if(!l)break;if(l.id===a.id)return c;c=l,i=l}return c}function Jf(t,n,a){const s=new Map(t.map(c=>[c.id,c])),i=new Map;for(const c of n){const l=a==="accounts"?c:a==="control"?lE(c,s):OB(c,s),m=l.id,d=i.get(m),u=a==="control"?"control":a==="subsidiary"?"subsidiary":"account";i.set(m,{id:m,sourceAccountId:l.id,code:l.code,name:l.name,amount:Number((d==null?void 0:d.amount)||0)+Number(c.amount||0),level:u})}return[...i.values()].sort((c,l)=>c.code.localeCompare(l.code,void 0,{numeric:!0}))}const xI={asset:"Assets",liability:"Liabilities",equity:"Equity",income:"Income",expense:"Expenses"},sj=[{code:"1000",name:"Assets",type:"asset",isGroup:!0,normalBalance:"debit",active:!0},{code:"1100",name:"Cash & Bank",type:"asset",parentId:"acct_1000",isGroup:!0,normalBalance:"debit",active:!0},{code:"1110",name:"Cash in Hand",type:"asset",parentId:"acct_1100",isGroup:!1,normalBalance:"debit",systemKey:"cash",active:!0},{code:"1120",name:"Bank Account",type:"asset",parentId:"acct_1100",isGroup:!1,normalBalance:"debit",systemKey:"bank",active:!0},{code:"1200",name:"Accounts Receivable",type:"asset",parentId:"acct_1000",isGroup:!1,normalBalance:"debit",systemKey:"accounts_receivable",active:!0},{code:"1300",name:"Inventory",type:"asset",parentId:"acct_1000",isGroup:!1,normalBalance:"debit",systemKey:"inventory",active:!0},{code:"1400",name:"Advances & Deposits",type:"asset",parentId:"acct_1000",isGroup:!0,normalBalance:"debit",active:!0},{code:"1990",name:"Migration Opening Clearing",type:"asset",parentId:"acct_1000",isGroup:!1,normalBalance:"debit",systemKey:"migration_opening_clearing",active:!0},{code:"1410",name:"Employee Salary Advance Receivable",type:"asset",parentId:"acct_1400",isGroup:!1,normalBalance:"debit",systemKey:"employee_salary_advance_receivable",active:!0},{code:"1420",name:"Employee Loan Receivable",type:"asset",parentId:"acct_1400",isGroup:!1,normalBalance:"debit",systemKey:"employee_loan_receivable",active:!0},{code:"2000",name:"Liabilities",type:"liability",isGroup:!0,normalBalance:"credit",active:!0},{code:"2100",name:"Accounts Payable",type:"liability",parentId:"acct_2000",isGroup:!1,normalBalance:"credit",systemKey:"accounts_payable",active:!0},{code:"2200",name:"Salary Payable",type:"liability",parentId:"acct_2000",isGroup:!1,normalBalance:"credit",systemKey:"salary_payable",active:!0},{code:"2300",name:"Gratuity Payable",type:"liability",parentId:"acct_2000",isGroup:!1,normalBalance:"credit",systemKey:"gratuity_payable",active:!0},{code:"2400",name:"Tax Payable",type:"liability",parentId:"acct_2000",isGroup:!1,normalBalance:"credit",systemKey:"tax_payable",active:!0},{code:"2500",name:"Provident Fund Payable",type:"liability",parentId:"acct_2000",isGroup:!1,normalBalance:"credit",systemKey:"pf_payable",active:!0},{code:"3000",name:"Equity",type:"equity",isGroup:!0,normalBalance:"credit",active:!0},{code:"3100",name:"Owner's Capital",type:"equity",parentId:"acct_3000",isGroup:!1,normalBalance:"credit",systemKey:"capital",active:!0},{code:"3200",name:"Retained Earnings",type:"equity",parentId:"acct_3000",isGroup:!1,normalBalance:"credit",systemKey:"retained_earnings",active:!0},{code:"4000",name:"Income",type:"income",isGroup:!0,normalBalance:"credit",active:!0},{code:"4100",name:"Sales Revenue",type:"income",parentId:"acct_4000",isGroup:!1,normalBalance:"credit",systemKey:"sales_revenue",active:!0},{code:"4200",name:"Service Revenue",type:"income",parentId:"acct_4000",isGroup:!1,normalBalance:"credit",systemKey:"service_revenue",active:!0},{code:"4300",name:"Other Income",type:"income",parentId:"acct_4000",isGroup:!1,normalBalance:"credit",active:!0},{code:"5000",name:"Cost of Sales",type:"expense",isGroup:!0,normalBalance:"debit",active:!0},{code:"5100",name:"Cost of Goods Sold",type:"expense",parentId:"acct_5000",isGroup:!1,normalBalance:"debit",systemKey:"cogs",active:!0},{code:"5200",name:"Service / Repair Cost",type:"expense",parentId:"acct_5000",isGroup:!1,normalBalance:"debit",systemKey:"service_cost",active:!0},{code:"6000",name:"Operating Expenses",type:"expense",isGroup:!0,normalBalance:"debit",active:!0},{code:"6100",name:"Salary & Wages",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",systemKey:"salary_expense",active:!0},{code:"6200",name:"Rent Expense",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0},{code:"6300",name:"Utilities Expense",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0}
3718,{code:"6400",name:"Transport Expense",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0},{code:"6500",name:"Office & Administration",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0},{code:"6600",name:"Bank Charges",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0},{code:"6700",name:"Depreciation Expense",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0},{code:"6800",name:"Other Expense",type:"expense",parentId:"acct_6000",isGroup:!1,normalBalance:"debit",active:!0}];function md(){return new Date().toISOString().slice(0,10)}function tl(t){return`৳${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`}function jI(t){const n=new Date(t);return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}`}function wI({profile:t,initialTab:n="chart"}){const a=sa(t,"finance.manage"),[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState({}),[u,f]=x.useState({fiscalYearStartMonth:7,openingBalanceDate:md()}),[g,p]=x.useState(""),[y,b]=x.useState(n),[N,w]=x.useState(()=>`${new Date().getFullYear()}-01-01`),[C,R]=x.useState(md()),[I,_]=x.useState(null),[J,T]=x.useState(!1),[G,z]=x.useState(""),[H,K]=x.useState(!1),[L,D]=x.useState(""),[M,Z]=x.useState(""),[fe,q]=x.useState(!1),[ne,ae]=x.useState(!1),[Y,je]=x.useState(""),[V,$]=x.useState(""),[F,P]=x.useState(""),[ue,me]=x.useState("asset"),[ge,de]=x.useState(""),[Pe,Re]=x.useState(!1);x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),le=>{const nt=le.exists()?Object.entries(le.val()).map(([xt,te])=>({id:xt,...te})):[];i(nt.sort((xt,te)=>xt.code.localeCompare(te.code,void 0,{numeric:!0})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`branches/${t.companyId}`),le=>{const nt=le.exists()?Object.entries(le.val()).map(([xt,te])=>({id:xt,...te})):[];l(nt.filter(xt=>xt.active!==!1).sort((xt,te)=>xt.name.localeCompare(te.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingOpeningBalances/${t.companyId}`),le=>{d(le.exists()?le.val():{})}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingSettings/${t.companyId}`),le=>{if(le.exists()){const nt=le.val();f({...nt,fiscalYearStartMonth:nt.fiscalYearStartMonth??7,openingBalanceDate:nt.openingBalanceDate||md()}),p(String(nt.lockedThrough||""))}}),[t.companyId]);const Ee=x.useMemo(()=>{const le=L.trim().toLowerCase();return le?s.filter(nt=>`${nt.code} ${nt.name} ${xI[nt.type]}`.toLowerCase().includes(le)):s},[s,L]),Be=x.useMemo(()=>Object.values(m).reduce((le,nt)=>(le.debit+=Number(nt.debit||0),le.credit+=Number(nt.credit||0),le),{debit:0,credit:0}),[m]),We=s.length>0,it=Math.abs(Be.debit-Be.credit),_e=it<.005,ee=()=>{je(""),$(""),P(""),me("asset"),de(""),Re(!1)},qe=()=>{ee(),ae(!0),Z("")},se=le=>{je(le.id),$(le.code),P(le.name),me(le.type),de(le.parentId||""),Re(le.isGroup),ae(!0),Z("")},pe=async()=>{if(!(!a||fe||s.length)){q(!0),Z("");try{const le=Date.now(),nt={};sj.forEach(xt=>{const te=`acct_${xt.code}`;nt[`accountingAccounts/${t.companyId}/${te}`]={...xt,createdAt:le,updatedAt:le}}),nt[`accountingSettings/${t.companyId}`]={...u,initializedAt:le,initializedByUid:t.uid,initializedByName:t.name||t.email||"User",updatedAt:le},await yn(re(ie),nt),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.chart_initialized",entityType:"accounting",entityId:"chart",summary:"Standard Chart of Accounts initialized.",metadata:{accounts:sj.length}}),Z(`Standard Chart of Accounts created (${sj.length} accounts).`)}catch(le){console.error(le),Z(`Chart initialization failed: ${le instanceof Error?le.message:"Unknown error"}`)}finally{q(!1)}}},Se=async le=>{if(le.preventDefault(),!a||fe)return;const nt=V.trim(),xt=F.trim();if(!nt||!xt){Z("Account Code and Account Name are required.");return}const te=s.find(pt=>pt.id!==Y&&pt.code.toLowerCase()===nt.toLowerCase());if(te){Z(`Account code ${nt} is already used by ${te.name}.`);return}const Ge=s.find(pt=>pt.id===ge);if(Ge&&Ge.type!==ue){Z("Parent account must have the same Account Type.");return}q(!0),Z("");try{const pt=Date.now(),$e=Y||Ta(re(ie,`accountingAccounts/${t.companyId}`)).key,st=s.find(Nt=>Nt.id===Y);await Pn(re(ie,`accountingAccounts/${t.companyId}/${$e}`),{code:nt,name:xt,type:ue,parentId:ge||"",isGroup:Pe,normalBalance:ue==="asset"||ue==="expense"?"debit":"credit",systemKey:(st==null?void 0:st.systemKey)||"",active:(st==null?void 0:st.active)!==!1,createdAt:(st==null?void 0:st.createdAt)||pt,updatedAt:pt}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:Y?"accounting.account_updated":"accounting.account_created",entityType:"accounting",entityId:$e,summary:`Account ${nt} · ${xt} ${Y?"updated":"created"}.`}),ae(!1),ee(),Z(`Account ${nt} saved successfully.`)}catch(pt){console.error(pt),Z(`Account save failed: ${pt instanceof Error?pt.message:"Unknown error"}`)}finally{q(!1)}},Me=async le=>{if(!(!a||fe||le.systemKey)){q(!0);try{await yn(re(ie,`accountingAccounts/${t.companyId}
3718/${le.id}`),{active:le.active===!1,updatedAt:Date.now()}),Z(`${le.name} ${le.active===!1?"activated":"deactivated"}.`)}catch(nt){console.error(nt),Z("Account status could not be updated.")}finally{q(!1)}}},ot=(le,nt,xt)=>{const Ge={...m[le]||{accountId:le,debit:0,credit:0,asOfDate:u.openingBalanceDate||md(),updatedAt:0,updatedByUid:"",updatedByName:""},[nt]:Math.max(0,Number(xt||0))};nt==="debit"&&Ge.debit>0&&(Ge.credit=0),nt==="credit"&&Ge.credit>0&&(Ge.debit=0),d({...m,[le]:Ge})},wt=async()=>{if(!(!a||fe||!We)){if(!_e){Z(`Opening Balance cannot be saved until Debit and Credit are equal. Difference: ${tl(it)}.`);return}q(!0),Z("");try{const le=Date.now(),nt={};s.filter(xt=>!xt.isGroup).forEach(xt=>{const te=m[xt.id]||{debit:0,credit:0};nt[`accountingOpeningBalances/${t.companyId}/${xt.id}`]={accountId:xt.id,debit:Number(te.debit||0),credit:Number(te.credit||0),asOfDate:u.openingBalanceDate||md(),note:te.note||"",updatedAt:le,updatedByUid:t.uid,updatedByName:t.name||t.email||"User"}}),await yn(re(ie),nt),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.opening_balances_updated",entityType:"accounting",entityId:"opening",summary:"Accounting opening balances updated.",metadata:{debit:Be.debit,credit:Be.credit}}),Z("Opening balances saved and balanced.")}catch(le){console.error(le),Z(`Opening balance save failed: ${le instanceof Error?le.message:"Unknown error"}`)}finally{q(!1)}}},ct=async()=>{if(!a||fe)return;const le=String(u.lockedThrough||"").trim(),nt=md().slice(0,7),xt=String(u.currentPeriod||"").trim();if(le&&le>nt){Z(`Locked Through cannot be a future month. Current month is ${nt}.`);return}if(g&&le<g){Z(`Locked Through cannot be reduced from ${g}. Period unlock requires the controlled Authorized Unlock workflow.`);return}if(xt&&le&&xt<=le){Z(`Current Period ${xt} must be later than Locked Through ${le}.`);return}q(!0),Z("");try{const te={...u,lockedThrough:le,updatedAt:Date.now()};await Pn(re(ie,`accountingSettings/${t.companyId}`),te),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.settings_updated",entityType:"accounting",entityId:"settings",summary:le!==g?`Accounting period lock updated: ${g||"Not set"} â ${le||"Not set"}.`:"Accounting period settings updated.",metadata:{...te,previousLockedThrough:g}}),p(le),Z(le?`Accounting settings saved. Period locked through ${le}.`:"Accounting settings saved successfully.")}catch(te){console.error(te),Z(`Accounting settings save failed: ${te instanceof Error?te.message:"Unknown error"}`)}finally{q(!1)}},Ce=le=>{var nt;return((nt=c.find(xt=>xt.id===le))==null?void 0:nt.name)||"Unknown Branch"},De=le=>!!(le&&c.some(nt=>nt.id===le)),Te=async()=>{if(!(!a||J)){if(!N||!C||N>C){z("Select a valid From and To date.");return}T(!0),z("");try{const[le,nt,xt]=await Promise.all([mn(re(ie,`invoices/${t.companyId}`)),mn(re(ie,`collections/${t.companyId}`)),mn(re(ie,`accountingVouchers/${t.companyId}`))]),te=le.exists()?Object.entries(le.val()).map(([tt,ht])=>({id:tt,...ht})):[],Ge=nt.exists()?Object.entries(nt.val()).map(([tt,ht])=>({id:tt,...ht})):[],pt=xt.exists()?xt.val():{},$e=new Date(`${N}T00:00:00`).getTime(),st=new Date(`${C}T23:59:59.999`).getTime(),Nt=tt=>Number(tt||0)>=$e&&Number(tt||0)<=st;let be=0,jt=0,bt=0;const tn=new Set,B=te.filter(tt=>{if(!Nt(tt.createdAt))return!1;const ht=Math.max(Number(tt.grandTotal||0),0),dt=Math.max(Number(tt.advanceAmount||0),0),we=ht>0&&!pt[`svc_invoice_${tt.id}`],rt=dt>0&&!pt[`svc_invoice_advance_${tt.id}`];return!we&&!rt?(be++,!1):(De(tt.branchId)||tn.add(tt.branchId||"(missing)"),g&&jI(tt.createdAt)<=g&&bt++,!0)}),xe=Ge.filter(tt=>{const ht=Number(tt.collectedAt||tt.createdAt||0);return Nt(ht)?Number(tt.amount||0)<=0||pt[`svc_collection_${tt.id}`]?(jt++,!1):(De(tt.branchId)||tn.add(tt.branchId||"(missing)"),g&&jI(ht)<=g&&bt++,!0):!1});_({invoiceCandidates:B,collectionCandidates:xe,skippedInvoices:be,skippedCollections:jt,blockedByLock:bt,unresolvedBranches:tn.size,invoiceAmount:B.reduce((tt,ht)=>tt+Math.max(Number(ht.grandTotal||0),0),0),collectionAmount:xe.reduce((tt,ht)=>tt+Math.max(Number(ht.amount||0),0),0)}),z("Preview ready. No accounting data has been changed.")}catch(le){console.error(le),z(`Preview failed: ${le instanceof Error?le.message:"Unknown error"}`)}finally{T(!1)}}},ce=async()=>
3718{if(!(!a||J||!I)){if(I.blockedByLock>0){z(`Backfill blocked: ${I.blockedByLock} candidate(s) fall inside the locked accounting period through ${g}. Use an unlocked date range or the controlled period-unlock workflow first.`);return}if(I.unresolvedBranches>0){z(`Backfill blocked: ${I.unresolvedBranches} branch ID(s) could not be matched to the active Branch master. Resolve branch mapping before posting historical accounting.`);return}if(!I.invoiceCandidates.length&&!I.collectionCandidates.length){z("Nothing to backfill. All matching historical records are already linked to accounting.");return}K(!0)}},Ye=async()=>{if(!a||J||!I)return;K(!1),T(!0),z("");let le=0,nt=0,xt=0;const te=[];try{for(const Ge of I.invoiceCandidates)try{const pt=await iE({companyId:t.companyId,branchId:Ge.branchId,actorUid:t.uid,actorName:t.name||t.email||"User",timestamp:Ge.createdAt,invoiceId:Ge.id,invoiceNumber:Ge.invoiceNumber,grandTotal:Number(Ge.grandTotal||0),advanceAmount:Number(Ge.advanceAmount||0)});Object.keys(pt).length&&(pt[`invoices/${t.companyId}/${Ge.id}/accountingPosted`]=!0,pt[`invoices/${t.companyId}/${Ge.id}/accountingBackfilledAt`]=Date.now(),pt[`invoices/${t.companyId}/${Ge.id}/accountingBackfilledBy`]=t.uid,await yn(re(ie),pt),le++)}catch(pt){xt++,te.push(`${Ge.invoiceNumber}: ${pt instanceof Error?pt.message:"Unknown error"}`)}for(const Ge of I.collectionCandidates)try{const pt=Number(Ge.collectedAt||Ge.createdAt||Date.now()),$e=await oE({companyId:t.companyId,branchId:Ge.branchId,actorUid:t.uid,actorName:t.name||t.email||"User",timestamp:pt,collectionId:Ge.id,collectionNumber:Ge.collectionNumber,invoiceId:Ge.invoiceId,invoiceNumber:Ge.invoiceNumber,amount:Number(Ge.amount||0),method:Ge.method});Object.keys($e).length&&($e[`collections/${t.companyId}/${Ge.id}/accountingPosted`]=!0,$e[`collections/${t.companyId}/${Ge.id}/accountingBackfilledAt`]=Date.now(),$e[`collections/${t.companyId}/${Ge.id}/accountingBackfilledBy`]=t.uid,await yn(re(ie),$e),nt++)}catch(pt){xt++,te.push(`${Ge.collectionNumber}: ${pt instanceof Error?pt.message:"Unknown error"}`)}await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.service_history_backfilled",entityType:"accounting",entityId:`${N}_${C}`,summary:`Historical service accounting backfill completed: ${le} invoice(s), ${nt} collection(s), ${xt} failed.`,metadata:{from:N,to:C,postedInvoices:le,postedCollections:nt,failed:xt}}),z(`Backfill completed. Invoice postings: ${le}. Collection postings: ${nt}. Failed: ${xt}.`+(te.length?` First issue: ${te[0]}`:"")),_(null)}catch(Ge){console.error(Ge),z(`Backfill stopped: ${Ge instanceof Error?Ge.message:"Unknown error"}`)}finally{T(!1)}},Je=s.filter(le=>le.isGroup&&le.active!==!1&&le.type===ue);return e.jsxs("section",{className:"accounting-foundation-page",children:[e.jsxs("header",{className:"accounting-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h1",{children:"Accounting Foundation"}),e.jsx("p",{children:"Chart of Accounts, opening balances and accounting-period controls. Double-entry posting is active through Vouchers & Journal."})]}),e.jsxs("span",{className:"accounting-foundation-badge",children:[e.jsx(gs,{size:17})," Posting Active"]})]}),M&&e.jsx("div",{className:"accounting-message",children:M}),e.jsxs("nav",{className:"accounting-tabs",children:[e.jsxs("button",{className:y==="chart"?"active":"",onClick:()=>b("chart"),children:[e.jsx(eA,{size:17})," Chart of Accounts"]}),e.jsx("button",{className:y==="opening"?"active":"",disabled:!We,title:We?void 0:"Initialize Chart of Accounts first",onClick:()=>b("opening"),children:"Opening Balances"}),e.jsxs("button",{className:y==="period"?"active":"",disabled:!We,title:We?void 0:"Initialize Chart of Accounts first",onClick:()=>b("period"),children:[e.jsx(pg,{size:17})," Accounting Period"]}),e.jsxs("button",{className:y==="backfill"?"active":"",disabled:!We||!a,title:a?We?void 0:"Initialize Chart of Accounts first":"Finance Manage permission required",onClick:()=>b("backfill"),children:[e.jsx(Uf,{size:17})," Historical Backfill"]})]}),y==="chart"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"accounting-toolbar",children:[e.jsxs("label",{className:"accounting-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{placeholder:"Search account code or name...",value:L,onChange:le=>D(le.target.value)})]}),a&&s.length===0&&e.jsxs("button",{className:"primary",disabled:fe,onClick:pe,children:[e.jsx(Eb,{size:17})," Initialize Standard Chart"]}),a&&s.length>0&&e.jsxs("button",{className:"primary",onClick:qe,children:[e.jsx(Eb,{size:17})," New Account"]})]}),s.length===0?e.jsxs("div",{className:"accounting-empty",children:[e.jsx(eA,{size:34}),e.jsx("h2",{children:"No Chart of Accounts yet"}),e.jsx("p",{children:"Initialize the standard VERIXO chart to create the accounting foundation. Existing Invoice, Collection and Payroll data will not be changed."})]}):e.jsx("div",{className:"accounting-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"CODE"}),e.jsx("th",{children:"ACCOUNT"}),e.jsx("th",{children:"HIERARCHY"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"NORMAL"}),e.jsx("th",{children:"SYSTEM LINK"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:Ee.map(le=>{var te;const nt=MB(le,s),xt=$B(le);return e.jsxs("tr",{className:le.isGroup?"group-row":"",children:[e.jsx("td",{children:e.jsx("strong",{children:le.code})}),e.jsx("td",{children:e.jsxs("div",{style:{paddingLeft:`${Math.min(nt,3)*16}px`},children:[e.jsx("strong",{children:le.name}),le.parentId&&e.jsx("small",{children:((te=s.find(Ge=>Ge.id===le.parentId))==null?void 0:te.name)||"Parent"})]})}),e.jsx("td",{children:e.jsx("span",{className:`account-hierarchy-badge hierarchy-${xt.toLowerCase().replace(" ","-")}`,children:xt})}),e.jsx("td",{children:xI[le.type]}),e.jsx("td",{children:le.normalBalance==="debit"?"Debit":"Credit"}
3718),e.jsx("td",{children:le.systemKey?e.jsx("span",{className:"system-link",children:le.systemKey.replaceAll("_"," ")}):"â"}),e.jsx("td",{children:e.jsx("span",{className:le.active===!1?"status-off":"status-on",children:le.active===!1?"Inactive":"Active"})}),e.jsx("td",{children:e.jsxs("div",{className:"accounting-actions",children:[a&&e.jsxs("button",{onClick:()=>se(le),children:[e.jsx(Zi,{size:15})," Edit"]}),a&&!le.systemKey&&e.jsx("button",{onClick:()=>Me(le),children:le.active===!1?"Activate":"Deactivate"})]})})]},le.id)})})]})})]}),y==="opening"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"opening-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Total Debit"}),e.jsx("strong",{children:tl(Be.debit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Credit"}),e.jsx("strong",{children:tl(Be.credit)})]}),e.jsxs("article",{className:_e?"balanced":"unbalanced",children:[e.jsx("span",{children:"Difference"}),e.jsx("strong",{children:tl(it)}),e.jsx("small",{children:_e?"Balanced":"Needs balancing before save"})]})]}),e.jsx("div",{className:"accounting-inline-setting",children:e.jsxs("label",{children:["Opening Balance Date",e.jsx("input",{type:"date",value:u.openingBalanceDate||md(),onChange:le=>f({...u,openingBalanceDate:le.target.value}),disabled:!a})]})}),e.jsx("div",{className:"accounting-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"CODE"}),e.jsx("th",{children:"ACCOUNT"}),e.jsx("th",{children:"DEBIT"}),e.jsx("th",{children:"CREDIT"})]})}),e.jsxs("tbody",{children:[s.filter(le=>!le.isGroup&&le.active!==!1).map(le=>{const nt=m[le.id]||{debit:0,credit:0};return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:le.code})}),e.jsx("td",{children:le.name}),e.jsx("td",{children:e.jsx("input",{className:"money-input",type:"number",min:"0",value:nt.debit||"",disabled:!a,onChange:xt=>ot(le.id,"debit",Number(xt.target.value))})}),e.jsx("td",{children:e.jsx("input",{className:"money-input",type:"number",min:"0",value:nt.credit||"",disabled:!a,onChange:xt=>ot(le.id,"credit",Number(xt.target.value))})})]},le.id)}),!s.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"empty",children:"Initialize Chart of Accounts first."})})]})]})}),a&&We&&e.jsx("div",{className:"accounting-footer-actions",children:e.jsxs("button",{className:"primary",disabled:fe||!_e,title:_e?void 0:"Debit and Credit must be equal before saving",onClick:wt,children:[e.jsx(hr,{size:17})," Save Opening Balances"]})})]}),y==="period"&&e.jsxs("div",{className:"accounting-period-card",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTING CONTROL"}),e.jsx("h2",{children:"Financial Period Settings"}),e.jsx("p",{children:"This establishes the company accounting calendar. Locked months are enforced immediately by the active Vouchers & Journal posting engine."})]}),e.jsxs("div",{className:"accounting-period-grid",children:[e.jsxs("label",{children:["Financial Year Starts",e.jsx("select",{value:u.fiscalYearStartMonth||7,onChange:le=>f({...u,fiscalYearStartMonth:Number(le.target.value)}),disabled:!a,children:["January","February","March","April","May","June","July","August","September","October","November","December"].map((le,nt)=>e.jsx("option",{value:nt+1,children:le},le))})]}),e.jsxs("label",{children:["Opening Balance Date",e.jsx("input",{type:"date",value:u.openingBalanceDate||md(),onChange:le=>f({...u,openingBalanceDate:le.target.value}),disabled:!a})]}),e.jsxs("label",{children:["Current Period",e.jsx("input",{type:"month",value:u.currentPeriod||"",onChange:le=>f({...u,currentPeriod:le.target.value}),disabled:!a})]}),e.jsxs("label",{children:["Locked Through",e.jsx("input",{type:"month",max:md().slice(0,7),value:u.lockedThrough||"",onChange:le=>f({...u,lockedThrough:le.target.value}),disabled:!a}),e.jsx("small",{children:"Vouchers dated in or before this month are blocked from Draft save and Post. Once saved, the lock cannot be reduced without Authorized Unlock."})]})]}),e.jsxs("div",{className:"accounting-period-status",children:[e.jsx("span",{children:"Chart Status"}),e.jsx("strong",{children:We?`${s.length} accounts ready`:"Not initialized"}),e.jsx("span",{children:"Period Lock"}),e.jsx("strong",{children:u.lockedThrough?`Locked through ${u.lockedThrough}`:"Not set"}),e.jsx("span",{children:"Posting Engine"}),e.jsx("strong",{children:"Active · Vouchers & Journal"})]}),a&&e.jsx("div",{className:"accounting-footer-actions",children:e.jsxs("button",{className:"primary",disabled:fe||!We,onClick:ct,children:[e.jsx(hr,{size:17})," Save Accounting Settings"]})})]}),y==="backfill"&&e.jsxs("div",{className:"accounting-backfill-card",children:[e.jsxs("div",{className:"backfill-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HISTORICAL MIGRATION"}),e.jsx("h2",{children:"Service Accounting Backfill Center"}),e.jsx("p",{children:"Preview old Service Invoices and Collections that do not yet have source-linked accounting vouchers. Preview never changes accounting data."})]}),e.jsxs("span",{className:"backfill-safety",children:[e.jsx(gs,{size:16})," Duplicate Safe"]})]}),e.jsxs("div",{className:"backfill-date-grid",children:[e.jsxs("label",{children:["From Date",e.jsx("input",{type:"date",value:N,onChange:le=>{w(le.target.value),_(null)}})]}),e.jsxs("label",{children:["To Date",e.jsx("input",{type:"date",value:C,onChange:le=>{R(le.target.value),_(null)}})]}),e.jsx("div",{className:"backfill-action-cell",children:e.jsxs("button",{className:"primary",disabled:J,onClick:Te,children:[e.jsx(xr,{size:17})," ",J?"Checking...":"Preview Backfill"]})})]}),G&&e.jsx("div",{className:"accounting-message",children:G}),I&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"backfill-summary-grid",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Invoice Candidates"}),e.jsx("strong",{children:I.invoiceCandidates.length}),e.jsx("small",{children:tl(I.invoiceAmount)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Collection Candidates"}),e.jsx("strong",{children:I.collectionCandidates.length}),e.jsx("small",{children:tl(I.collectionAmount)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Already Posted / Skipped"}),e.jsx("strong",{children:I.skippedInvoices+I.skippedCollections}),e.jsx("small",{children:"Duplicate-safe skip"})]}),e.jsxs("article",{className:I.blockedByLock?"warning":"",children:[e.jsx("span",{children:"Locked-Period Candidates"}),e.jsx("strong",{children:I.blockedByLock}),e.jsx("small",{children:g?`Locked through ${g}`:"No period lock"})]}),e.jsxs("article",{className:I.unresolvedBranches?"warning":"",children:[e.jsx("span",{children:"Unresolved Branches"}),e.jsx("strong",{children:I.unresolvedBranches}),e.jsx("small",{children:I.unresolvedBranches?"Backfill blocked until resolved":"All branch IDs verified"})]})]}),e.jsxs("div",{className:"backfill-preview-table",children:[e.jsxs("div",{className:"backfill-preview-section",children:[e.jsx("h3",{children:"Invoices to Backfill"}),e.jsx("div",{className:"accounting-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"INVOICE"}),e.jsx("th",{children:"BRANCH"}),e.jsx("th",{children:"GRAND TOTAL"}),e.jsx("th",{children:"ADVANCE"})]})}),e.jsxs("tbody",{children:[I.invoiceCandidates.slice(0,100).map(le=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(le.createdAt).toLocaleDateString("en-GB")}),e.jsx("td",{children:e.jsx("strong",{children:le.invoiceNumber})}),e.jsxs("td",{children:[e.jsx("strong",{children:Ce(le.branchId)}),e.jsx("small",{className:"backfill-branch-id",children:le.branchId})]}),e.jsx("td",{children:tl(le.grandTotal)}),e.jsx("td",{children:tl(Number(le.advanceAmount||0))})]},le.id)),!I.invoiceCandidates.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"empty",children:"No missing historical invoice postings in this range."})})]})]})})]}),e.jsxs("div",{className:"backfill-preview-section",children:[e.jsx("h3",{children:"Collections to Backfill"}),e.jsx("div",{className:"accounting-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"COLLECTION"}),e.jsx("th",{children:"INVOICE"}),e.jsx("th",{children:"BRANCH"}),e.jsx("th",{children:"METHOD"}),e.jsx("th",{children:"AMOUNT"})]})}),e.jsxs("tbody",{children:[I.collectionCandidates.slice(0,100).map(le=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(Number(le.collectedAt||le.createdAt)).toLocaleDateString("en-GB")}),e.jsx("td",{children:e.jsx("strong",{children:le.collectionNumber})}),e.jsx("td",{children:le.invoiceNumber}),e.jsxs("td",{children:[e.jsx("strong",{children:Ce(le.branchId)}),e.jsx("small",{className:"backfill-branch-id",children:le.branchId})]}),e.jsx("td",{children:le.method}),e.jsx("td",{children:tl(le.amount)})]},le.id)),!I.collectionCandidates.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty",children:"No missing historical collection postings in this range."})})]})]})})]})]}),I.blockedByLock>0&&e.jsxs("div",{className:"backfill-lock-warning",children:[e.jsx(pg,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Locked period protection is active."}),e.jsxs("p",{children:[I.blockedByLock," candidate(s) cannot be posted while the accounting period is locked through ",g,". This center will not silently bypass period lock."]})]})]}),I.unresolvedBranches>0&&e.jsxs("div",{className:"backfill-lock-warning",children:[e.jsx(gs,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Branch mapping requires attention."}),e.jsxs("p",{children:[I.unresolvedBranches," branch ID(s) used by historical records are not present in the active Branch master. Backfill is blocked so no voucher can be posted to an unknown branch."]})]})]}),e.jsx("div",{className:"accounting-footer-actions",children:e.jsxs("button",{className:"primary",disabled:J||I.blockedByLock>0||I.unresolvedBranches>0||!I.invoiceCandidates.length&&!I.collectionCandidates.length,onClick:ce,children:[e.jsx(Uf,{size:17})," ",J?"Backfilling...":"Run Backfill"]})})]})]}),H&&I&&e.jsx("div",{className:"accounting-modal-bg backfill-confirm-bg",onMouseDown:le=>{le.currentTarget===le.target&&!J&&K(!1)},children:e.jsxs("div",{className:"accounting-modal backfill-confirm-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HISTORICAL MIGRATION"}),e.jsx("h2",{children:"Confirm Backfill"}),e.jsx("p",{children:"Review the historical accounting action before posting."})]}),e.jsx("button",{type:"button",disabled:J,onClick:()=>K(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"backfill-confirm-body",children:[e.jsxs("div",{className:"backfill-confirm-question",children:[e.jsx(Uf,{size:28}),e.jsxs("div",{children:[e.jsx("strong",{children:"Run historical accounting backfill?"}),e.jsxs("p",{children:[I.invoiceCandidates.length," invoice(s) and ",I.collectionCandidates.length," collection(s) are ready to post."]})]})]}),e.jsxs("div",{className:"backfill-confirm-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Invoice Candidates"}),e.jsx("strong",{children:I.invoiceCandidates.length}),e.jsx("small",{children:tl(I.invoiceAmount)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Collection Candidates"}),e.jsx("strong",{children:I.collectionCandidates.length}),e.jsx("small",{children:tl(I.collectionAmount)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Already Posted / Skipped"}),e.jsx("strong",{children:I.skippedInvoices+I.skippedCollections}),e.jsx("small",{children:"Duplicate-safe skip"})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Locked-Period Candidates"}),e.jsx("strong",{children:I.blockedByLock}),e.jsx("small",{children:I.blockedByLock?"Action blocked":"No period lock"})]})]}),e.jsxs("div",{className:"backfill-confirm-safe",children:[e.jsx(gs,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Duplicate Safe"}),e.jsx("p",{children:"Existing source-linked vouchers will be skipped automatically. Only missing accounting vouchers will be created."})]})]})]}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",disabled:J,onClick:()=>K(!1),children:"Cancel"}),e.jsxs("button",{type:"button",className:"primary",disabled:J,onClick:Ye,children:[e.jsx(Uf,{size:17})," ",J?"Running...":"Run Backfill"]})]})]})}),ne&&e.jsx("div",{className:"accounting-modal-bg",onMouseDown:le=>{le.currentTarget===le.target&&ae(!1)},children:e.jsxs("form",{className:"accounting-modal",onSubmit:Se,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:Y?"EDIT ACCOUNT":"NEW ACCOUNT"}),e.jsx("h2",{children:Y?"Update Account":"Create Account"})]}),e.jsx("button",{type:"button",onClick:()=>ae(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"accounting-form-grid",children:[e.jsxs("label",{children:["Account Code",e.jsx("input",{value:V,onChange:le=>$(le.target.value),required:!0})]}),e.jsxs("label",{children:["Account Name",e.jsx("input",{value:F,onChange:le=>P(le.target.value),required:!0})]}),e.jsxs("label",{children:["Account Type",e.jsxs("select",{value:ue,onChange:le=>{me(le.target.value),de("")},children:[e.jsx("option",{value:"asset",children:"Asset"}),e.jsx("option",{value:"liability",children:"Liability"}),e.jsx("option",{value:"equity",children:"Equity"}),e.jsx("option",{value:"income",children:"Income"}),e.jsx("option",{value:"expense",children:"Expense"})]})]}),e.jsxs("label",{children:["Parent Account",e.jsxs("select",{value:ge,onChange:le=>de(le.target.value),children:[e.jsx("option",{value:"",children:"No Parent"}),Je.filter(le=>le.id!==Y).map(le=>e.jsxs("option",{value:le.id,children:[le.code," · ",le.name]},le.id))]})]}),e.jsxs("label",{className:"check-label",children:[e.jsx("input",{type:"checkbox",checked:Pe,onChange:le=>Re(le.target.checked)})," Group / Header Account"]})]}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",onClick:()=>ae(!1),children:"Cancel"}),e.jsxs("button",{className:"primary",disabled:fe,children:[e.jsx(hr,{size:17})," Save Account"]})]})]})})]})}function LB({profile:t}){const n=sa(t,"finance.manage"),[a,s]=x.useState([]),[i,c]=x.useState([]),[l,m]=x.useState([]),[d,u]=x.useState(""),[f,g]=x.use
3718State("bank"),[p,y]=x.useState(""),[b,N]=x.useState(""),[w,C]=x.useState(""),[R,I]=x.useState(""),[_,J]=x.useState("current"),[T,G]=x.useState(!0),[z,H]=x.useState(""),[K,L]=x.useState(""),[D,M]=x.useState(""),[Z,fe]=x.useState("");x.useEffect(()=>qt(re(ie,`accountingBankAccounts/${t.companyId}`),P=>{const ue=P.val()||{};s(Object.entries(ue).map(([me,ge])=>({id:me,...ge})).sort((me,ge)=>(me.bankName||me.name||"").localeCompare(ge.bankName||ge.name||"")))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingBankMasters/${t.companyId}`),P=>{const ue=P.val()||{};c(Object.entries(ue).map(([me,ge])=>({id:me,...ge})).filter(me=>me.active!==!1).sort((me,ge)=>me.name.localeCompare(ge.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),P=>{const ue=P.val()||{};m(Object.entries(ue).map(([me,ge])=>({id:me,...ge})).filter(me=>me.type==="asset"&&!me.isGroup&&me.active!==!1).sort((me,ge)=>me.code.localeCompare(ge.code,void 0,{numeric:!0})))}),[t.companyId]);const q=x.useMemo(()=>i.find(P=>P.id===p),[i,p]),ne=()=>{const P=l.map(ue=>{var me;return(me=/^1120\.(\d+)$/.exec(String(ue.code||"")))==null?void 0:me[1]}).filter(Boolean).map(Number);return`1120.${String((P.length?Math.max(...P):0)+1).padStart(3,"0")}`},ae=P=>`${P.bankName||P.name}${P.accountNumber?` (${P.accountNumber})`:""}`;async function Y(P){if(!n)return;if(P.ledgerAccountId&&P.ledgerCode&&P.ledgerCode!=="1120"&&!a.some(it=>it.id!==P.id&&it.ledgerAccountId===P.ledgerAccountId)){window.alert("This account already has a dedicated ledger.");return}if(!window.confirm(`Create a dedicated ledger for ${P.bankName||P.name}${P.accountNumber?` · ${P.accountNumber}`:""}? Future postings will use it, and identifiable salary postings will be moved from the shared Bank Account ledger.`))return;const ue=Date.now(),me=`bank_${P.id.replace(/[^A-Za-z0-9_-]/g,"_")}`,ge=ne(),de=ae(P),Pe={[`accountingAccounts/${t.companyId}/${me}`]:{code:ge,name:de,type:"asset",isGroup:!1,normalBalance:"debit",active:!0,createdAt:ue,updatedAt:ue},[`accountingBankAccounts/${t.companyId}/${P.id}/ledgerAccountId`]:me,[`accountingBankAccounts/${t.companyId}/${P.id}/ledgerCode`]:ge,[`accountingBankAccounts/${t.companyId}/${P.id}/ledgerName`]:de,[`accountingBankAccounts/${t.companyId}/${P.id}/updatedAt`]:ue},[Re,Ee]=await Promise.all([mn(re(ie,`payrollPayments/${t.companyId}`)),mn(re(ie,`accountingLedgerEntries/${t.companyId}`))]),Be=Re.val()||{},We=Ee.val()||{};for(const[it,_e]of Object.entries(Be))for(const[ee,qe]of Object.entries(_e||{}))for(const[se,pe]of Object.entries(qe||{})){const Se=pe;if((Se==null?void 0:Se.method)!=="bank"||(Se==null?void 0:Se.sourceBankAccountId)!==P.id||Se!=null&&Se.reversedAt||Se!=null&&Se.reversed)continue;Pe[`payrollPayments/${t.companyId}/${it}/${ee}/${se}/sourceBankLedgerAccountId`]=me,Pe[`payrollPayments/${t.companyId}/${it}/${ee}/${se}/sourceBankLedgerCode`]=ge,Pe[`payrollPayments/${t.companyId}/${it}/${ee}/${se}/sourceBankLedgerName`]=de;const Me=String(Se.accountingVoucherId||"");if(!Me)continue;const wt=(await mn(re(ie,`accountingVouchers/${t.companyId}/${Me}`))).val();if((wt==null?void 0:wt.status)!=="posted")continue;(Array.isArray(wt.lines)?wt.lines:Object.values(wt.lines||{})).forEach((Ce,De)=>{Number(Ce.credit||0)>0&&String(Ce.accountId||"")===String(P.ledgerAccountId||"")&&(Pe[`accountingVouchers/${t.companyId}/${Me}/lines/${De}/accountId`]=me,Pe[`accountingVouchers/${t.companyId}/${Me}/lines/${De}/accountCode`]=ge,Pe[`accountingVouchers/${t.companyId}/${Me}/lines/${De}/accountName`]=de)});for(const[Ce,De]of Object.entries(We)){const Te=De;Te.voucherId===Me&&Number(Te.credit||0)>0&&String(Te.accountId||"")===String(P.ledgerAccountId||"")&&(Pe[`accountingLedgerEntries/${t.companyId}/${Ce}/accountId`]=me,Pe[`accountingLedgerEntries/${t.companyId}/${Ce}/accountCode`]=ge,Pe[`accountingLedgerEntries/${t.companyId}/${Ce}/accountName`]=de)}}await yn(re(ie),Pe),window.alert(`Dedicated ledger ${ge} · ${de} is ready.`)}async function je(P){P.preventDefault();const ue=d.trim();if(!n||!ue)return;if(i.some(de=>de.name.toLowerCase()===ue.toLowerCase())){u("");return}const me=Ta(re(ie,`accountingBankMasters/${t.companyId}`)),ge=Date.now();await Pn(me,{name:ue,active:!0,createdAt:ge,updatedAt:ge}),u("")}async function V(P){if(P.preventDefault(),!n)return;const ue=l.find(Pe=>Pe.id===z);if(f==="bank"&&(!q||!R.trim()||!b.trim()||!w.trim()||!ue)||f==="mfs"&&(!b.trim()||!w.trim()||!ue))return;const me=Ta(re(ie,`accountingBankAccounts/${t.companyId}`)),ge=Date.now(),de=f==="bank"?`${q.name} · ${b.trim()}`:b.trim();await Pn(me,{name:de,kind:f,bankId:f==="bank"?p:"",bankName:f==="bank"?q.name:"",bankBranch:f==="bank"?R.trim():"",accountName:b.trim(),accountNumber:w.trim(),accountType:f==="bank"?_:"other",ownAccount:T,ledgerAccountId:ue.id,ledgerCode:ue.code,ledgerName:ue.name,routingNo:K.trim(),swiftCode:D.trim(),note:Z.trim(),active:!0,createdAt:ge,updatedAt:ge}),y(""),N(""),C(""),I(""),H(""),L(""),M(""),fe("")}
3718async function $(P){!n||!window.confirm("Remove this bank/payment account from setup?")||await Ao(re(ie,`accountingBankAccounts/${t.companyId}/${P}`))}async function F(P,ue){n&&await yn(re(ie,`accountingBankAccounts/${t.companyId}/${P}`),{active:!ue,updatedAt:Date.now()})}return e.jsxs("div",{className:"page-shell",children:[e.jsx("div",{className:"page-header",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Setup · Accounts · Bank & Cash"}),e.jsx("h1",{children:"Bank Account Master"}),e.jsx("p",{className:"muted",children:"Bank accounts are linked to the Chart of Accounts now so Collections, Historical Migration, Bank Reconciliation and future Cheque Management can use one accounting-safe source."})]})}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("form",{className:"card",onSubmit:je,children:[e.jsxs("h3",{children:[e.jsx(Fu,{size:18})," Bank Master"]}),e.jsx("div",{className:"form-grid",children:e.jsxs("label",{children:["New Bank Name",e.jsx("input",{value:d,onChange:P=>u(P.target.value),placeholder:"e.g. Al-Arafah Islami Bank PLC",required:!0})]})}),e.jsx("div",{className:"form-actions",children:e.jsxs("button",{className:"btn secondary",type:"submit",children:[e.jsx(as,{size:16})," Add Bank"]})})]}),e.jsxs("form",{className:"card",onSubmit:V,children:[e.jsxs("h3",{children:[e.jsx(Nd,{size:18})," Bank / Payment Account"]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Type *",e.jsxs("select",{value:f,onChange:P=>g(P.target.value),children:[e.jsx("option",{value:"bank",children:"Bank Account"}),e.jsx("option",{value:"mfs",children:"MFS / Mobile Wallet"})]})]}),f==="bank"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Bank *",e.jsxs("select",{value:p,onChange:P=>y(P.target.value),required:!0,children:[e.jsx("option",{value:"",children:"Select Bank..."}),i.map(P=>e.jsx("option",{value:P.id,children:P.name},P.id))]})]}),e.jsxs("label",{children:["Bank Branch *",e.jsx("input",{value:R,onChange:P=>I(P.target.value),required:!0,placeholder:"Branch name"})]})]}),e.jsxs("label",{children:["A/C Name *",e.jsx("input",{value:b,onChange:P=>N(P.target.value),required:!0,placeholder:f==="bank"?"Account title":"Wallet name"})]}),e.jsxs("label",{children:[f==="bank"?"Bank A/C No. *":"Wallet No. *",e.jsx("input",{value:w,onChange:P=>C(P.target.value),required:!0})]}),f==="bank"&&e.jsxs("label",{children:["Account Type *",e.jsxs("select",{value:_,onChange:P=>J(P.target.value),children:[e.jsx("option",{value:"current",children:"Current"}),e.jsx("option",{value:"savings",children:"Savings"}),e.jsx("option",{value:"snd",children:"SND"}),e.jsx("option",{value:"cc",children:"CC"}),e.jsx("option",{value:"od",children:"OD"}),e.jsx("option",{value:"other",children:"Other"})]})]}),e.jsxs("label",{children:["A/C Ledger *",e.jsxs("select",{value:z,onChange:P=>H(P.target.value),required:!0,children:[e.jsx("option",{value:"",children:"Select asset ledger..."}),l.map(P=>e.jsxs("option",{value:P.id,children:[P.code," · ",P.name]},P.id))]})]}),f==="bank"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Routing No.",e.jsx("input",{value:K,onChange:P=>L(P.target.value)})]}),e.jsxs("label",{children:["SWIFT Code",e.jsx("input",{value:D,onChange:P=>M(P.target.value)})]})]}),e.jsxs("label",{children:["Note",e.jsx("input",{value:Z,onChange:P=>fe(P.target.value)})]}),e.jsxs("label",{className:"checkbox-label",style:{display:"flex",alignItems:"center",gap:8,justifyContent:"flex-start",alignSelf:"end",minHeight:42},children:[e.jsx("input",{type:"checkbox",checked:T,onChange:P=>G(P.target.checked),style:{width:16,height:16,margin:0,flex:"0 0 auto"}}),e.jsxs("span",{children:["Own ",f==="bank"?"Bank A/C":"Payment A/C"]})]})]}),e.jsx("div",{className:"form-actions",children:e.jsxs("button",{className:"btn primary",type:"submit",children:[e.jsx(as,{size:16})," Add Account"]})})]})]}),e.jsxs("div",{className:"card",children:[e.jsxs("h3",{children:[e.jsx(Nd,{size:18})," Configured Accounts"]}),e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Type"}
3718),e.jsx("th",{children:"Bank / Account"}),e.jsx("th",{children:"A/C No."}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"A/C Ledger"}),e.jsx("th",{children:"Status"}),n&&e.jsx("th",{children:"Ledger Action"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("td",{children:"Cash"}),e.jsx("td",{children:"Cash in Hand"}),e.jsx("td",{children:"â"}),e.jsx("td",{children:"â"}),e.jsx("td",{children:"1110 · Cash in Hand"}),e.jsx("td",{children:"Active"}),n&&e.jsx("td",{})]}),a.map(P=>e.jsxs("tr",{children:[e.jsx("td",{children:P.kind==="bank"?"Bank":"MFS"}),e.jsxs("td",{children:[P.bankName||P.name,P.accountName&&P.bankName?e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsxs("span",{className:"muted",children:[P.accountName," · ",String(P.accountType||"").toUpperCase()]})]}):null]}),e.jsx("td",{children:P.accountNumber||"â"}),e.jsx("td",{children:P.bankBranch||P.branch||"â"}),e.jsx("td",{children:P.ledgerAccountId?`${P.ledgerCode||""} · ${P.ledgerName||"Linked ledger"}`:e.jsx("span",{className:"muted",children:"Legacy · ledger link required"})}),e.jsx("td",{children:e.jsx("button",{className:"btn-link",onClick:()=>void F(P.id,P.active),children:P.active?"Active":"Inactive"})}),n&&e.jsxs("td",{children:[e.jsxs("button",{className:"btn secondary",type:"button",onClick:()=>void Y(P),title:"Create/use a dedicated ledger for this exact bank account",children:[e.jsx(Hi,{size:14})," ",P.ledgerCode&&P.ledgerCode!=="1120"?"Dedicated":"Create Dedicated"]})," ",e.jsx("button",{className:"icon-btn",onClick:()=>void $(P.id),title:"Remove",children:e.jsx(po,{size:15})})]})]},P.id)),!a.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:n?7:6,className:"muted",children:"No Bank/MFS account added yet."})})]})]})})]})]})}const BB="2026-08-01",NI="01 Aug 2026",FB="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.min.mjs",UB="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.mjs",Sf=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,zB={jan:"01",feb:"02",mar:"03",apr:"04",may:"05",jun:"06",jul:"07",aug:"08",sep:"09",oct:"10",nov:"11",dec:"12"};function qB(t){const n=t.match(/(\d{1,2})-([A-Za-z]{3})-(\d{4})/);return n?`${n[3]}-${zB[n[2].toLowerCase()]||"01"}-${n[1].padStart(2,"0")}`:""}function Ol(t){return Number(t.replace(/,/g,""))||0}function VB(t){return t.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120)}function HB(t){const n=t.filter(i=>String(i.str||"").trim()).map(i=>{var c,l;return{text:String(i.str||"").replace(/\s+/g," ").trim(),x:Number(((c=i.transform)==null?void 0:c[4])||0),y:Number(((l=i.transform)==null?void 0:l[5])||0)}}),a=[],s=2.8;for(const i of n){let c=a.find(l=>Math.abs(l.y-i.y)<=s);c||(c={y:i.y,cells:[]},a.push(c)),c.cells.push({x:i.x,text:i.text})}return a.sort((i,c)=>c.y-i.y).map(i=>{const c=i.cells.sort((l,m)=>l.x-m.x);return{y:i.y,cells:c,text:c.map(l=>l.text).join(" ").replace(/\s+/g," ").trim()}}).filter(i=>i.text)}function Nv(t,n,a){return t.cells.filter(s=>s.x>=n&&s.x<a).map(s=>s.text).join(" ").replace(/\s+/g," ").trim()}function WB(t){const n=t.find(J=>/\bAccounts\b/i.test(J.text)&&/\bProject\b/i.test(J.text)&&/\bParticular\b/i.test(J.text)&&/\bDr\b/i.test(J.text)&&/\bCr\b/i.test(J.text));if(!n)return[];const a=J=>{var T;return(T=n.cells.find(G=>J.test(G.text)))==null?void 0:T.x},s=a(/^Accounts$/i),i=a(/^Project$/i),c=a(/^Particular$/i),l=a(/^Dr$/i),m=a(/^Cr$/i);if([s,i,c,l,m].some(J=>J===void 0))return[];const d=s,u=i,f=c,g=l,p=m,y=d-20,b=(d+u)/2,N=(u+f)/2,w=(f+g)/2,C=(g+p)/2,R=p+120,I=[],_=t.indexOf(n);for(let J=_+1;J<t.length;J++){const T=t[J];
3718if(/^Total\b/i.test(T.text)||/\bTotal\s*\(/i.test(T.text)||/^In Word\b/i.test(T.text))break;const G=Nv(T,y,b),z=Nv(T,N,w),H=Nv(T,w,C),K=Nv(T,C,R),L=H.match(/[\d,]+\.\d{2}/),D=K.match(/[\d,]+\.\d{2}/);G&&(L||D)&&I.push({sourceAccount:G.trim(),particular:z.trim(),debit:Ol((L==null?void 0:L[0])||"0"),credit:Ol((D==null?void 0:D[0])||"0"),accountId:""})}return I}function Sv(t,n){const a=t.find(c=>c.cells.some(l=>n.test(l.text.trim())));if(!a)return"";const s=a.cells.find(c=>n.test(c.text.trim()));return s?a.cells.filter(c=>c.x>s.x+5).map(c=>c.text.trim()).filter(c=>c&&c!==":").join(" ").replace(/^:\s*/,"").trim():""}function GB(t){const n=t.toUpperCase().match(/DV-[A-Z0-9-]+/g)||[];if(n.length)return n[0]||"";const a=t.replace(/\s+/g," ").trim(),s=a.split(" ").filter(Boolean);return s.length>1&&s.every(i=>i===s[0])?s[0]:a}function YB(t){const n=t.findIndex(c=>c.cells.some(l=>/^Description$/i.test(l.text.trim())));if(n<0)return"";const a=[],s=t[n],i=s.cells.find(c=>/^Description$/i.test(c.text.trim()));i&&a.push(...s.cells.filter(c=>c.x>i.x+5).map(c=>c.text.trim()).filter(c=>c&&c!==":"));for(let c=n+1;c<t.length;c++){const l=t[c];if(l.cells.some(d=>/^Accounts$/i.test(d.text.trim()))||l.cells.some(d=>/^(Voucher No\.?|Date|Status|Approved By|Approved Date|Entry By)$/i.test(d.text.trim())))break;const m=l.text.replace(/^:\s*/,"").trim();m&&a.push(m)}return a.join(" ").replace(/\s+/g," ").trim()}function Cv(t,n){var i,c;const a=new RegExp(`^${n.replace(/[.*+?^${}()|[\\]\\]/g,"\\$&")}\\s*:\\s*(.*)$`,"i"),s=t.find(l=>a.test(l));return((c=(i=s==null?void 0:s.match(a))==null?void 0:i[1])==null?void 0:c.trim())||""}function QB(t,n=[]){var b,N,w,C,R,I;const a=t.split(/\r?\n/).map(_=>_.replace(/\s+/g," ").trim()).filter(Boolean),s=a.join(" ");if(!/Debit Voucher Report/i.test(s))throw new Error("This PDF is not recognized as a Takeplus/Oner Debit Voucher Report.");const i=GB((Sv(n,/^Voucher No\.?$/i)||Cv(a,"Voucher No.")||((b=s.match(/(?:^|\s)Voucher No\.\s*:\s*(DV-[A-Z0-9-]+)/i))==null?void 0:b[1])||"").replace(/^:\s*/,"").trim()),l=((w=(Sv(n,/^Date$/i)||Cv(a,"Date")||((N=s.match(/(?:^|\s)Date\s*:\s*(\d{1,2}-[A-Za-z]{3}-\d{4})/i))==null?void 0:N[1])||"").match(/\d{1,2}-[A-Za-z]{3}-\d{4}/))==null?void 0:w[0])||"",m=(Sv(n,/^Status$/i)||Cv(a,"Status")||((C=s.match(/(?:^|\s)Status\s*:\s*([A-Za-z]+)/i))==null?void 0:C[1])||"").replace(/^:\s*/,"").trim(),d=(Sv(n,/^Approved By$/i)||Cv(a,"Approved By")||((R=s.match(/(?:^|\s)Approved By\s*:\s*([^\s]+)/i))==null?void 0:R[1])||"").replace(/^:\s*/,"").trim();let u=YB(n);if(!u){const _=a.findIndex(J=>/^Description\s*:/i.test(J));if(_>=0){u=a[_].replace(/^Description\s*:\s*/i,"").trim();for(let J=_+1;J<a.length&&!(/^Accounts\s+Project\s+Particular\s+Dr\s+Cr$/i.test(a[J])||/^(Accounts|Voucher No\.|Date|Status|Approved By|Approved Date|Entry By)\s*:/i.test(a[J]));J++)u.length<240&&(u=`${u} ${a[J]}`.trim())}}const f=a.findIndex(_=>/^Accounts\s+Project\s+Particular\s+Dr\s+Cr$/i.test(_)),g=WB(n);if(g.length<2&&f>=0)for(let _=f+1;_<a.length;_++){const J=a[_];if(/^Total\b/i.test(J)||/\bTotal\s*\(/i.test(J)||/^In Word\s*:/i.test(J))break;const T=J.match(/^(.+?)\s+General Project\s+(.+?)\s+([\d,]+\.\d{2})\s+([\d,]+\.\d{2})$/i);T&&g.push({sourceAccount:T[1].trim(),particular:T[2].trim(),debit:Ol(T[3]),credit:Ol(T[4]),accountId:""})}if(g.length<2){const _=((I=s.match(/Accounts\s+Project\s+Particular\s+Dr\s+Cr\s+(.+?)(?:\s+Total\s*\(|\s+In Word\s*:)/i))==null?void 0:I[1])||"",J=/(.+?)\s+General Project\s+(.+?)\s+([\d,]+\.\d{2})\s+([\d,]+\.\d{2})(?=\s+.+?\s+General Project|$)/g;let T;for(;T=J.exec(_);)g.push({sourceAccount:T[1].trim(),particular:T[2].trim(),debit:Ol(T[3]),credit:Ol(T[4]),accountId:""})}if(g.length<2){const _=t.replace(/\s+/g," ").trim(),J=[{name:"Office Expenses",rx:/Office Expenses(?:\s+General Project)?\s+.+?\s+([\d,]+\.\d{2})\s+([\d,]+\.\d{2})/i},{name:"Cash In Hand",rx:/(Cash In Hand(?:\s*\([^)]+\))?)(?:\s+General Project)?\s+.+?\s+([\d,]+\.\d{2})\s+([\d,]+\.\d{2})/i}],T=_.match(J[0].rx);T&&g.push({sourceAccount:"Office Expenses",particular:u,debit:Ol(T[1]),credit:Ol(T[2]),accountId:""});const G=_.match(J[1].rx);G&&g.push({sourceAccount:G[1].trim(),particular:u,debit:Ol(G[2]),credit:Ol(G[3]),accountId:""})}if(!i||!l||g.length<2)throw new Error("Voucher header/table could not be read safely. Nothing has been imported.");const p=g.reduce((_,J)=>_+J.debit,0),y=g.reduce((_,J)=>_+J.credit,0);return{sourceVoucherNo:i,voucherDate:qB(l),status:m,approvedBy:d,description:u,lines:g,totalDebit:p,totalCredit:y,rawText:t}}function JB({profile:t,branches:n}){var z;const[a,s]=x.useState([]),[i,c]=x.useState(""),[l,m]=x.useState(null),[d,u]=x.useState(""),[f,g]=x.use
3718State(""),[p,y]=x.useState(""),[b,N]=x.useState(!1),w=x.useMemo(()=>a.filter(H=>H.active!==!1&&!H.isGroup),[a]);x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),H=>s(H.exists()?Object.entries(H.val()).map(([K,L])=>({id:K,...L})).sort((K,L)=>K.code.localeCompare(L.code,void 0,{numeric:!0})):[])),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingSettings/${t.companyId}`),H=>{var K;return c(String(((K=H.val())==null?void 0:K.lockedThrough)||""))}),[t.companyId]);const C=H=>{var D,M,Z,fe;const K=H.toLowerCase();if(K.includes("cash in hand"))return((D=w.find(q=>q.systemKey==="cash"))==null?void 0:D.id)||"";if(K.includes("bank"))return((M=w.find(q=>q.systemKey==="bank"))==null?void 0:M.id)||"";if(K.includes("office expense"))return((Z=w.find(q=>q.code==="6500"))==null?void 0:Z.id)||((fe=w.find(q=>q.name.toLowerCase().includes("office")))==null?void 0:fe.id)||"";const L=w.find(q=>q.name.toLowerCase()===K);return(L==null?void 0:L.id)||""},R=async H=>{var L,D;const K=(L=H.target.files)==null?void 0:L[0];if(H.target.value="",!!K){if(K.type!=="application/pdf"&&!K.name.toLowerCase().endsWith(".pdf")){y("Please select a PDF file.");return}N(!0),y(""),m(null),g(K.name);try{const M=await import(FB);M.GlobalWorkerOptions.workerSrc=UB;const Z=await M.getDocument({data:new Uint8Array(await K.arrayBuffer())}).promise;let fe="";const q=[];for(let V=1;V<=Z.numPages;V++){const F=await(await Z.getPage(V)).getTextContent(),P=HB(F.items);q.push(...P),fe+=P.map(ue=>ue.text).join(` 3719`)+` 3720`}const ne=QB(fe,q);ne.lines=ne.lines.map(V=>({...V,accountId:C(V.sourceAccount)})),m(ne);const ae=ne.lines.find(V=>/cash in hand/i.test(V.sourceAccount)),Y=((D=ae==null?void 0:ae.sourceAccount.match(/\(([^)]+)\)/))==null?void 0:D[1])||"",je=n.find(V=>V.name.toLowerCase().includes(Y.toLowerCase())||String(V.code||"").toLowerCase().includes(Y.toLowerCase()));u((je==null?void 0:je.id)||""),y("PDF read successfully. Review branch and account mapping before import.")}catch(M){console.error(M),y(`PDF preview failed: ${M instanceof Error?M.message:"Unknown error"}`)}finally{N(!1)}}},I=(H,K)=>m(L=>L&&{...L,lines:L.lines.map((D,M)=>M===H?{...D,accountId:K}:D)}),_=!!(l&&Math.abs(l.totalDebit-l.totalCredit)<.005&&l.totalDebit>0),J=!!(l&&l.lines.every(H=>H.accountId)),T=!!(l&&i&&l.voucherDate.slice(0,7)<=i),G=async()=>{if(!(!l||b)){if(l.status.toLowerCase()!=="approved"){y(`Import blocked: source voucher status is ${l.status||"unknown"}, not Approved.`);return}if(!d){y("Select the VERIXO Branch for this voucher.");return}if(!J){y("Map every source account to a VERIXO ledger account before import.");return}if(!_){y("Import blocked: source Debit and Credit are not balanced.");return}if(T){y(`Import blocked: ${l.voucherDate.slice(0,7)} is inside locked period through ${i}.`);return}if(l.voucherDate<BB){y(`Current migration accepts documents from ${NI} onward. Earlier history can be added later through Historical Backfill.`);return}N(!0),y("");try{const H=VB(`takeplus_${l.sourceVoucherNo}`);if((await mn(re(ie,`accountingPdfImports/${t.companyId}/${H}`))).exists()){y(`Duplicate blocked: ${l.sourceVoucherNo} was already imported.`);return}const L=Date.now(),D=`pdf_${H}`,M=`MIG-${l.sourceVoucherNo}`,Z=l.lines.map((ne,ae)=>{const Y=w.find(je=>je.id===ne.accountId);return{id:`line_${ae+1}`,accountId:Y.id,accountCode:Y.code,accountName:Y.name,debit:ne.debit,credit:ne.credit,narration:ne.particular||l.description}}),fe={[`accountingVouchers/${t.companyId}/${D}`]:{voucherNo:M,type:"payment",status:"posted",voucherDate:l.voucherDate,branchId:d,reference:l.sourceVoucherNo,narration:l.description,lines:Z,totalDebit:l.totalDebit,totalCredit:l.totalCredit,createdAt:L,createdByUid:t.uid,createdByName:t.name||t.email||"User",updatedAt:L,postedAt:L,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"pdf_migration",sourceId:l.sourceVoucherNo,sourceFile:f},[`accountingPdfImports/${t.companyId}/${H}`]:{sourceSystem:"Oner ERP Suite / Takeplus",sourceVoucherNo:l.sourceVoucherNo,sourceFile:f,voucherId:D,voucherNo:M,voucherDate:l.voucherDate,branchId:d,status:"posted",importedAt:L,importedByUid:t.uid,importedByName:t.name||t.email||"User"}};Z.forEach((ne,ae)=>
3720fe[`accountingLedgerEntries/${t.companyId}/${D}_${String(ae+1).padStart(3,"0")}`]={id:`${D}_${String(ae+1).padStart(3,"0")}`,voucherId:D,voucherNo:M,voucherType:"payment",voucherDate:l.voucherDate,branchId:d,reference:l.sourceVoucherNo,narration:ne.narration,accountId:ne.accountId,accountCode:ne.accountCode,accountName:ne.accountName,debit:ne.debit,credit:ne.credit,status:"posted",createdAt:L,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"pdf_migration"}),await yn(re(ie),fe);let q="";try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.pdf_voucher_imported",entityType:"accounting",entityId:D,summary:`${l.sourceVoucherNo} imported from PDF.`,branchId:d,metadata:{fileName:f,sourceVoucherNo:l.sourceVoucherNo,total:l.totalDebit}})}catch(ne){console.error("PDF import audit log failed after atomic accounting post",ne),q=" Accounting posted successfully, but the audit log could not be written."}y(`${l.sourceVoucherNo} imported successfully as ${M}. Expense and Cash ledger updated.${q}`),m(null),g("")}catch(H){console.error("PDF atomic import failed",H);const K=H instanceof Error?H.message:"Unknown error";y(`PDF import failed before posting completed: ${K}. Voucher, ledger and import registry were not partially saved.`)}finally{N(!1)}}};return e.jsxs("div",{className:"accounting-pdf-import-card",children:[e.jsxs("div",{className:"pdf-import-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"DATA MIGRATION CENTER"}),e.jsx("h2",{children:"PDF Accounting Import"}),e.jsx("p",{children:"Upload an old accounting voucher PDF, preview extracted Debit/Credit lines, map them to VERIXO ledgers, then post safely."})]}),e.jsxs("span",{className:"backfill-safety",children:[e.jsx(gs,{size:16})," Preview First"]})]}),e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(jp,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Supported in this release: Takeplus / Oner ERP Debit Voucher Report"}),e.jsx("p",{children:"PDFs are read in the browser. Nothing is posted until you review the preview and click Import Voucher."})]})]}),e.jsxs("div",{className:"pdf-cutover-notice",children:[e.jsxs("strong",{children:["Current migration start: ",NI]}),e.jsx("span",{children:"Aug 2026 onward for now. This is not an irreversible cutover lock; earlier history can be added later through Historical Backfill."})]}),e.jsxs("label",{className:"pdf-upload-box",children:[e.jsx(wp,{size:26}),e.jsx("strong",{children:b?"Reading PDF...":"Choose Debit Voucher PDF"}),e.jsx("span",{children:f||"PDF only · one voucher per file"}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf",disabled:b,onChange:R})]}),p&&e.jsx("div",{className:"accounting-message",children:p}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"pdf-import-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Source Voucher"}),e.jsx("strong",{children:l.sourceVoucherNo})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Date"}),e.jsx("strong",{children:l.voucherDate})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Status"}),e.jsx("strong",{children:l.status})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total"}),e.jsx("strong",{children:Sf(l.totalDebit)})]})]}),e.jsxs("div",{className:"pdf-import-description",children:[e.jsx("strong",{children:"Description"}),e.jsx("span",{children:l.description||"â"})]}),e.jsxs("div",{className:"pdf-import-branch",children:[e.jsxs("label",{children:["VERIXO Branch",e.jsxs("select",{value:d,onChange:H=>u(H.target.value),children:[e.jsx("option",{value:"",children:"Select branch..."}),n.filter(H=>H.active!==!1).map(H=>e.jsx("option",{value:H.id,children:H.name},H.id))]})]}),e.jsx("small",{children:"The selected VERIXO Branch controls where this voucher and its Cash/Expense ledger entries are posted. The source text inside brackets (for example BGC Complex) is only a migration hint and does not override your selected VERIXO Branch."}),d&&e.jsxs("strong",{className:"pdf-branch-confirm",children:["Will post to: ",((z=n.find(H=>H.id===d))==null?void 0:z.name)||"Selected Branch"]})]}),e.jsx("div",{className:"accounting-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"SOURCE ACCOUNT"}),e.jsx("th",{children:"VERIXO LEDGER MAPPING"}),e.jsx("th",{children:"DEBIT"}),e.jsx("th",{children:"CREDIT"})]})}),e.jsx("tbody",{children:l.lines.map((H,K)=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:H.sourceAccount}),e.jsx("small",{children:H.particular})]}),e.jsx("td",{children:e.jsxs("select",{value:H.accountId,onChange:L=>I(K,L.target.value),children:[e.jsx("option",{value:"",children:"Map account..."}),w.map(L=>e.jsxs("option",{value:L.id,children:[L.code," · ",L.name]},L.id))]})}),e.jsx("td",{children:H.debit?Sf(H.debit):"â"}),e.jsx("td",{children:H.credit?Sf(H.credit):"â"})]},`${H.sourceAccount}_${K}`))}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("th",{colSpan:2,children:"TOTAL"}),e.jsx("th",{children:Sf(l.totalDebit)}),e.jsx("th",{children:Sf(l.totalCredit)})]})})]})}),e.jsxs("div",{className:`pdf-import-validation ${_&&J&&!T?"ok":"warn"}`,children:[_?e.jsx(jp,{size:18}):e.jsx(AD,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:_?"Debit/Credit balanced":"Debit/Credit mismatch"}),e.jsxs("p",{children:[J?"":"Map all source accounts. ",T?`Perio
3720d is locked through ${i}. `:"","Duplicate source voucher numbers are blocked automatically."]})]})]}),e.jsx("div",{className:"accounting-footer-actions",children:e.jsxs("button",{className:"primary",disabled:b||!_||!J||!d||T,onClick:G,children:[e.jsx(wp,{size:17})," ",b?"Importing...":"Import Voucher"]})})]})]})}const KB="PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR";function XB(t){return String(t||"").toUpperCase().replace(/[^A-Z0-9]+/g,"")}function ZB(t){return t.replace(/(.)\1/g,"$1")}function s2(t){const n=XB(t),a=ZB(n);if(!n)return!0;const s=/BGCCOMPLEX|PRINTDATE|ONERERPSUITE|PAGE\d+OF\d+|CURRENTSTOCK|LOCATIONWISESTOCK|UNITLEVELPRIMARY/;return s.test(n)||s.test(a)||/PRODUCT/.test(a)&&/QTY/.test(a)&&/COST/.test(a)}function dE(t){const n=[...String(t||"").matchAll(new RegExp(`\\b(?:${KB})\\b`,"gi"))],a=n[n.length-1];if(!a||a.index===void 0)return!1;const s=t.slice(a.index+a[0].length);return/(?:^|\s)-?[\d,]+(?:\.\d+)?(?:\s|$)/.test(s)}function e8(t){return String(t||"").replace(/^.*?Serial\s*(?:No\.?|Number)?(?:\(s\))?\s*[:#-]?\s*/i,"").split(/[\s,;|]+/).map(n=>n.trim().replace(/^[()\[\]{}]+|[()\[\]{}]+$/g,"")).filter(n=>n.length<4||!/[0-9]/.test(n)||/^N\/?A$/i.test(n)||/^[-+à§³â¹$â¬Â£]?[\d,]+\.\d{1,4}$/.test(n)?!1:/^[A-Za-z0-9_:#./+-]+$/.test(n))}const t8="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.min.mjs",n8="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.mjs",ou=t=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return t||"Not detected";const[n,a,s]=t.split("-").map(Number);return new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",timeZone:"UTC"}).format(new Date(Date.UTC(n,a-1,s)))},a8=t=>{const[n,a,s]=t.split("-").map(Number),i=new Date(Date.UTC(n,a-1,s+1));return`${i.getUTCFullYear()}-${String(i.getUTCMonth()+1).padStart(2,"0")}-${String(i.getUTCDate()).padStart(2,"0")}`},Ds=t=>t.toUpperCase().replace(/[^A-Z0-9]+/g," ").replace(/\s+/g," ").trim(),s8=t=>t.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,160),rj=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`;function SI(t,n){const a=n.slice(0,4).flat().map(y=>y.text).join(" "),s=`${t} ${a}`.replace(/[\u00A0\u200B-\u200D\uFEFF]/g," ").replace(/\s+/g," "),i=s.replace(/[^A-Za-z0-9]+/g," ").replace(/\s+/g," ").trim(),c=/Date\s*Wise\s*Stock/i.test(s)||/DATE WISE STOCK/i.test(i),l=/Back\s*Dated(?:\s*Stock)?/i.test(s)||/BACK DATED(?: STOCK)?/i.test(i),m={JAN:"01",FEB:"02",MAR:"03",APR:"04",MAY:"05",JUN:"06",JUL:"07",AUG:"08",SEP:"09",OCT:"10",NOV:"11",DEC:"12"},d=(y,b,N)=>y<2e3||y>2100||b<1||b>12||N<1||N>31?"":`${y}-${String(b).padStart(2,"0")}-${String(N).padStart(2,"0")}`;let u="";const f=s.match(/As\s*On\s*[:\-]?\s*(\d{1,2})\s*[-\/. ]\s*([A-Za-z]{3,9})\s*[-\/. ]\s*(\d{4})/i);if(f){const y=m[f[2].slice(0,3).toUpperCase()];y&&(u=d(Number(f[3]),Number(y),Number(f[1])))}if(!u){const y=s.match(/As\s*On\s*[:\-]?\s*(\d{1,2})\s*[-\/. ]\s*(\d{1,2})\s*[-\/. ]\s*(\d{4})/i);y&&(u=d(Number(y[3]),Number(y[2]),Number(y[1])))}if(!u){const y=s.match(/As\s*On\s*[:\-]?\s*(\d{4})\s*[-\/. ]\s*(\d{1,2})\s*[-\/. ]\s*(\d{1,2})/i);y&&(u=d(Number(y[1]),Number(y[2]),Number(y[3])))}if(!u&&c){const y=s.match(/\b(\d{1,2})\s*[-\/. ]\s*(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[A-Za-z]*\s*[-\/. ]\s*(\d{4})\b/i);if(y){const b=m[y[2].slice(0,3).toUpperCase()];b&&(u=d(Number(y[3]),Number(b),Number(y[1])))}}const g=!!u;return{hasDateWise:c,hasBackDated:l,hasReportDate:g,reportDate:u,valid:c&&g}}function r8(t){const n=t.filter(s=>String(s.str||"").trim()).map(s=>{var i,c;return{text:String(s.str||"").replace(/\s+/g," ").trim(),x:Number(((i=s.transform)==null?void 0:i[4])||0),y:Number(((c=s.transform)==null?void 0:c[5])||0)}}),a=[];for(const s of n){let i=a.find(c=>Math.abs(c.y-s.y)<=2.8);i||(i={y:s.y,cells:[]},a.push(i)),i.cells.push({x:s.x,text:s.text})}return a.sort((s,i)=>i.y-s.y).map(s=>{const i=s.cells.sort((c,l)=>c.x-l.x);return{y:s.y,cells:i,text:i.map(c=>c.text).join(" ").replace(/\s+/g," ").trim()}}).filter(s=>s.text)}function r2(t){const n=t.cells.find(l=>/^N\s*ame$/i.test(l.text)),a=t.cells.find(l=>/C\s*ategory/i.test(l.text)),s=t.cells.find(l=>/^M\s*odel$/i.test(l.text)),i=t.cells.find(l=>/^U\s*nit$/i.test(l.text)),c=t.cells.find(l=>/^Q\s*ty\.?$/i.test(l.text));return!n||!a||!s||!i||!c?null:{nameStart:n.x-10,catStart:a.x-6,modelStart:s.x-6,unitStart:i.x-6,qtyStart:c.x-8}}function CI(t,n,a=!1){const s=[];let i=null,c=[],l=[],m=[],d=[];const u=()=>{c=[],l=[],m=[],d=[]},f=(y,b)=>{const N=b.replace(/\s+/g," ").trim();N&&y[y.length-1]!==N&&y.push(N)},g=(y,b,N)=>y.cells.filter(w=>w.x>=b&&w.x<N).map(w=>w.text).join(" ").replace(/\s+/g," ").trim();for(const y of t)for(const b of y){const N=r2(b);if(N){i=N,u();continue}if(/^Print Date/i.test(b.text)){u();continue}if(!i)continue;if(/Total\s+Q\s*ty/i.test(b.text)||/Total\s+Qty/i.test(b.text)){u();continue}if(/^(TAKEPLUS|Oner ERP|Back Dated|Date Wise|Location Wise|Unit Level|As On|Page\s*:)/i.test(b.text))continue;const w=g(b,i.nameStart,i.catStart),C=g(b,i.catStart,i.modelStart),R=g(b,i.modelStart,i.unitStart),I=g(b,i.unitStart,i.qtyStart),_=b.cells.filter(D=>D.x>=i.qtyStart).map(D=>D.text).join(" ").replace(/\s+/g," ").trim();f(c,w),f(l,C),f(m,R),f(d,I);const J=_.match(/^\s*([+-]?[\d,]+(?:\.\d+)?)\s*$/),T=/^\s*-\s*$/.test(_);
3720if(!J&&!T)continue;const G=J?Number(J[1].replace(/,/g,"")):0,z=c.join(" ").replace(/\s+/g," ").trim(),H=l.join(" ").replace(/\s+/g," ").trim(),K=m.join(" ").replace(/\s+/g," ").trim(),L=d.join(" ").replace(/\s+/g," ").trim()||"PCS";if(z&&(G>0||a)){const D=`${z}|${H}|${K}|${L}`;s.push({id:s8(D),sourceName:z,category:H,model:K,unit:L,qty:G,openingDate:n})}u()}const p=new Map;for(const y of s){const b=p.get(y.id);p.set(y.id,b?{...b,qty:b.qty+y.qty}:y)}return[...p.values()]}function i8(t,n){const a=[];let s=null;const i=(c,l,m)=>c.cells.filter(d=>d.x>=l&&d.x<m).map(d=>d.text).join(" ").replace(/\s+/g," ").trim();for(const c of t)for(const l of c){const m=r2(l);if(m){s=m;continue}if(!s||/^Print Date/i.test(l.text)||/Total\s+Q\s*ty/i.test(l.text)||/Total\s+Qty/i.test(l.text))continue;const u=l.cells.filter(N=>N.x>=s.qtyStart).map(N=>N.text).join(" ").trim().match(/^([\d,]+(?:\.\d+)?)$/);if(!u)continue;const f=Number(u[1].replace(/,/g,""));if(!(f>0))continue;const g=i(l,s.nameStart,s.catStart),p=i(l,s.catStart,s.modelStart),y=i(l,s.modelStart,s.unitStart),b=i(l,s.unitStart,s.qtyStart)||"PCS";g&&a.push({id:`physical_${a.length+1}`,sourceName:g,category:p,model:y,unit:b,qty:f,openingDate:n})}return a}function o8(t){let n=null,a=0,s=0;for(const i of t)for(const c of i){const l=r2(c);if(l){n=l;continue}if(!n||/^Print Date/i.test(c.text)||/Total\s+Q\s*ty/i.test(c.text)||/Total\s+Qty/i.test(c.text))continue;const d=c.cells.filter(f=>f.x>=n.qtyStart).map(f=>f.text).join(" ").trim().match(/^\s*(-[\d,]+(?:\.\d+)?)\s*$/);if(!d)continue;const u=Number(d[1].replace(/,/g,""));Number.isFinite(u)&&u<0&&(a++,s+=u)}return{rows:a,qty:s}}function i2(t){const n=t.replace(/,/g,"").replace(/[^0-9.-]/g,""),a=Number(n);return Number.isFinite(a)?a:NaN}function vg(t){return e8(t)}function c8(t){const n=[];let a=[],s=[],i=!1,c=-1;const l=/^(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)$/i,m=w=>/(product|item|description).*(qty|quantity)|(qty|quantity).*(cost|rate|value)|cost\s*\/?\s*unit|unit\s*cost|current\s+stock|location\s+wise\s+stock|stock\s*with\s*cost/i.test(w),d=w=>s2(w)||/^(page\s+\d+|print(?:ed)?\s+date|as\s+on\b|unit\s+level\s*:|location\s*:|branch\s*:|warehouse\s*:|grand\s+total|total\s*:)/i.test(w.trim())||/Oner\s+ERP\s+Suite/i.test(w),u=w=>(w.match(/-?[\d,]+(?:\.\d+)?/g)||[]).map(i2).filter(Number.isFinite),f=()=>s.join(" ").replace(/\s+/g," ").trim(),g=w=>{const C=w.replace(/\s+/g," ").trim();C&&s[s.length-1]!==C&&s.push(C)},p=()=>{s=[]},y=(w,C)=>{const R=w.replace(/\s+/g," ").trim();if(!R||C.length<3)return;const I=C[C.length-3],_=C[C.length-2],J=C[C.length-1];if(!(!Number.isFinite(I)||I<0||!Number.isFinite(_)||_<0))return{sourceName:R,qty:I,costPerUnit:_,totalCost:Number.isFinite(J)?J:I*_,serials:[]}};for(const w of t){const C=w.text.replace(/\u00a0/g," ").replace(/\s+/g," ").trim();if(!C)continue;if(/Serial\s*(?:No\.?|Number)?(?:\(s\))?\s*[:#-]?/i.test(C)){i=!0,c=n.length-1,p();const J=vg(C);J.length&&(c>=0?n[c].serials.push(...J):a.push(...J));continue}if(i&&dE(C)&&(i=!1,c=-1),i&&!m(C)&&!d(C)&&C.length<900&&!/\b(?:PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)\b/i.test(C)){const T=vg(C).filter(G=>!l.test(G)&&!/^serial$/i.test(G));if(T.length){c>=0?n[c].serials.push(...T):a.push(...T);continue}}let R,I="",_=[];for(let J=0;J<w.cells.length;J++){if(w.cells[J].x<520)continue;const G=w.cells[J].text.replace(/\u00a0/g," ").trim().split(/\s+/);let z=-1;for(let fe=0;fe<G.length;fe++)l.test(G[fe].replace(/[,:;]+$/,""))&&(z=fe);if(z<0)continue;const H=w.cells.slice(0,J).map(fe=>fe.text).join(" ").trim(),K=G.slice(0,z).join(" ").trim(),L=`${H} ${K}`.replace(/\s+/g," ").trim(),D=f();I=D&&L?`${D} ${L}`:L||D;const M=G.slice(z+1).join(" "),Z=w.cells.slice(J+1).map(fe=>fe.text).join(" ");if(_=u(`${M} ${Z}`),R=y(I,_),R)break}if(!R&&!m(C)&&!d(C)){const J=[...C.matchAll(/\b(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)\b/gi)],T=J[J.length-1];if(T&&T.index!==void 0){const G=C.slice(0,T.index).trim(),z=C.slice(T.index+T[0].length),H=f();I=H&&G?`${H} ${G}`:G||H,_=u(z),R=y(I,_)}}if(R){a.length&&(R.serials.push(...a),a=[]),R.serials=[...new Set(R.serials)],n.push(R),p(),i=!1,c=-1;continue}!m(C)&&!d(C)&&!/^Serial\b/i.test(C)&&!/^[-\d,.à§³\s]+$/.test(C)&&C.length>=4&&C.length<=900&&g(C),(m(C)||d(C))&&(i=!1,c=-1,p(),d(C)&&(a=[]))}
3720const b=/^(?:NO MODEL|OTHER|CHINA|LOCAL|TV CARD|ADAPTER|BATTERY|CABLE|PRODUCT)$/i,N=new Map;for(const w of n){const C=w.sourceName.replace(/\s+/g," ").trim(),R=Ds(C);if(!R||b.test(R))continue;const I=N.get(R);if(!I){N.set(R,{...w,sourceName:C,serials:[...new Set(w.serials)]});continue}const _=w.qty===I.qty&&w.costPerUnit===I.costPerUnit?I:w;N.set(R,{..._,sourceName:C,serials:[...new Set([...I.serials,...w.serials])]})}return[...N.values()]}function l8(t){const n=t.filter(l=>String(l.str||"").trim()).map(l=>{var m,d;return{text:String(l.str||"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),x:Number(((m=l.transform)==null?void 0:m[4])||0),y:Number(((d=l.transform)==null?void 0:d[5])||0)}}),a=/^(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)$/i,s=l=>/^[-à§³â¹$â¬Â£]?[\d,]+(?:\.\d+)?$/.test(l.trim()),i=[];for(let l=0;l<n.length;l++){const m=n[l];if(m.x<520||!a.test(m.text.replace(/[,:;]+$/,"")))continue;const d=6.5,u=n.filter(w=>Math.abs(w.y-m.y)<=d).sort((w,C)=>w.x-C.x),f=u.filter(w=>w.x<m.x-4&&w.x<535).map(w=>w.text).join(" ").replace(/\s+/g," ").trim(),p=u.filter(w=>w.x>m.x+4).map(w=>w.text).filter(s).map(i2).filter(Number.isFinite);if(!f||p.length<3)continue;const y=p[p.length-3],b=p[p.length-2],N=p[p.length-1];!Number.isFinite(y)||y<0||!Number.isFinite(b)||b<0||i.push({sourceName:f,qty:y,costPerUnit:b,totalCost:Number.isFinite(N)?N:y*b,serials:[]})}const c=new Map;for(const l of i){const m=Ds(l.sourceName);if(!m)continue;const d=c.get(m);(!d||l.qty>d.qty||l.totalCost>d.totalCost)&&c.set(m,l)}return[...c.values()]}function d8(t,n){const a=new Map;for(const s of[...n,...t]){const i=Ds(s.sourceName);if(!i)continue;const c=a.get(i);if(!c){a.set(i,{...s,serials:[...new Set(s.serials)]});continue}a.set(i,{...s,serials:[...new Set([...c.serials||[],...s.serials||[]])]})}return[...a.values()]}function u8(t,n){const a=new Map(n.map(y=>[Ds(y.sourceName),{...y,serials:[...new Set(y.serials||[])]}])),s=/^(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)$/i,i=y=>/(product|item|description).*(qty|quantity)|(qty|quantity).*(cost|rate|value)|cost\s*\/?\s*unit|unit\s*cost|current\s+stock|location\s+wise\s+stock|stock\s+with\s+cost/i.test(y),c=y=>s2(y)||/^(page\s+\d+|print(?:ed)?\s+date|as\s+on\b|unit\s+level\s*:|location\s*:|branch\s*:|warehouse\s*:|grand\s+total|total\s*:)/i.test(y.trim())||/Oner\s+ERP\s+Suite/i.test(y),l=y=>(y.match(/-?[\d,]+(?:\.\d+)?/g)||[]).map(i2).filter(Number.isFinite);let m=[],d="",u=!1;const f=()=>m.join(" ").replace(/\s+/g," ").trim(),g=()=>{m=[]},p=y=>{if(!d)return;const b=a.get(d);if(!b)return;const N=vg(y).filter(w=>!s.test(w)&&!/^serial$/i.test(w)&&!/^no\.?$/i.test(w));N.length&&(b.serials=[...new Set([...b.serials||[],...N])])};for(const y of t)for(const b of y){const N=b.text.replace(/\u00a0/g," ").replace(/\s+/g," ").trim();if(!N)continue;if(/Serial\s*(?:No\.?|Number)?(?:\(s\))?\s*[:#-]?/i.test(N)){u=!0,g(),p(N);continue}let w="",C=!1;for(let R=0;R<b.cells.length;R++){if(b.cells[R].x<520)continue;const _=b.cells[R].text.replace(/\u00a0/g," ").trim().split(/\s+/);let J=-1;for(let M=0;M<_.length;M++)s.test(_[M].replace(/[,:;]+$/,""))&&(J=M);if(J<0)continue;const T=b.cells.slice(0,R).map(M=>M.text).join(" ").trim(),G=_.slice(0,J).join(" ").trim(),z=`${T} ${G}`.replace(/\s+/g," ").trim(),H=f(),K=H&&z?`${H} ${z}`:z||H,L=_.slice(J+1).join(" "),D=b.cells.slice(R+1).map(M=>M.text).join(" ");if(K&&l(`${L} ${D}`).length>=3){w=K,C=!0;break}}if(!C&&!i(N)&&!c(N)){const R=[...N.matchAll(/\b(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)\b/gi)],I=R[R.length-1];if(I&&I.index!==void 0){const _=N.slice(0,I.index).trim(),J=N.slice(I.index+I[0].length),T=f(),G=T&&_?`${T} ${_}`:_||T;G&&l(J).length>=3&&(w=G,C=!0)}}if(C){const R=Ds(w);a.has(R)?d=R:d=[...a.keys()].find(_=>_===R||_.includes(R)||R.includes(_))||"",u=!1,g();continue}if(u&&!i(N)&&!c(N)&&N.length<900){p(N);continue}if(!i(N)&&!c(N)&&!/^Serial\b/i.test(N)&&!/^[-\d,.à§³\s]+$/.test(N)&&N.length>=4&&N.length<=900){const R=N.replace(/\s+/g," ").trim();R&&m[m.length-1]!==R&&m.push(R)}(i(N)||c(N))&&(u=!1,g())}return[...a.values()]}function h8(t,n){const a=new Map(n.map(u=>
3720[Ds(u.sourceName),{...u,serials:[...new Set(u.serials||[])]}])),s=[...a.keys()],i=/^(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)$/i,c=u=>/(product|item|description).*(qty|quantity)|(qty|quantity).*(cost|rate|value)|cost\s*\/?\s*unit|unit\s+type|current\s+stock|location\s+wise\s+stock|stock\s+with\s+cost/i.test(u),l=u=>s2(u)||/^(page\s+\d+|print(?:ed)?\s+date|as\s+on\b|unit\s+level\s*:|location\s*:|branch\s*:|warehouse\s*:|grand\s+total|total\s*:)/i.test(u.trim())||/Oner\s+ERP\s+Suite/i.test(u),m=u=>{const f=Ds(u);if(a.has(f))return f;const g=Oc(u),p=s.find(b=>{var N;return Oc(((N=a.get(b))==null?void 0:N.sourceName)||b)===g});if(p)return p;const y=s.filter(b=>b.includes(f)||f.includes(b));return y.length===1?y[0]:""},d=(u,f)=>{if(!u)return;const g=a.get(u);if(!g)return;const p=vg(f).map(y=>y.replace(/^[,;|]+|[,;|]+$/g,"")).filter(y=>y.length>=3&&!i.test(y)&&!/^serial$/i.test(y)&&!/^no\.?$/i.test(y)&&!/^s$/i.test(y));p.length&&(g.serials=[...new Set([...g.serials||[],...p])])};for(const u of t){const f=u.filter(b=>String(b.str||"").trim()).map(b=>{var N,w;return{text:String(b.str||"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),x:Number(((N=b.transform)==null?void 0:N[4])||0),y:Number(((w=b.transform)==null?void 0:w[5])||0)}}),g=[];for(const b of f.sort((N,w)=>w.y-N.y||N.x-w.x)){let N=g.find(w=>Math.abs(w.y-b.y)<=6.5);N||(N={y:b.y,cells:[]},g.push(N)),N.cells.push({x:b.x,text:b.text})}g.sort((b,N)=>N.y-b.y);let p="",y=!1;for(const b of g){const N=b.cells.sort((R,I)=>R.x-I.x),w=N.map(R=>R.text).join(" ").replace(/\s+/g," ").trim();if(!w)continue;const C=N.findIndex(R=>R.x>=520&&i.test(R.text.replace(/[,:;]+$/,"")));if(C>=0){const R=N[C],I=N.filter(J=>J.x<R.x-4&&J.x<535).map(J=>J.text).join(" ").replace(/\s+/g," ").trim(),_=I?m(I):"";_&&(p=_),y=!1;continue}if(/Serial\s*(?:No\.?|Number)?(?:\(s\))?\s*[:#-]?/i.test(w)){y=!0,d(p,w);continue}if(y){if(dE(w)){y=!1;continue}if(c(w)||l(w)){y=!1;continue}d(p,w)}}}return[...a.values()]}function m8(t,n){const a=new Map(n.map(m=>[Ds(m.sourceName),{...m,serials:[...new Set(m.serials||[])]}])),s=[...a.keys()],i=/^(PCS?|PC|PIECE|PIECES|NOS?|UNIT|UNITS|SET|BOX|PAIR)$/i,c=m=>{const d=Ds(m);if(a.has(d))return d;const u=Oc(m),f=s.find(p=>{var y;return Oc(((y=a.get(p))==null?void 0:y.sourceName)||p)===u});if(f)return f;const g=s.filter(p=>p.includes(d)||d.includes(p));return g.length===1?g[0]:""},l=(m,d)=>{if(!m)return;const u=a.get(m);if(!u)return;const f=vg(d).map(g=>g.replace(/^[,;|]+|[,;|]+$/g,"")).filter(g=>g.length>=3&&!i.test(g)&&!/^serial$/i.test(g)&&!/^no\.?$/i.test(g)&&!/^s$/i.test(g)&&!/^sn[:#-]?$/i.test(g));f.length&&(u.serials=[...new Set([...u.serials||[],...f])])};for(const m of t){const d=m.filter(p=>String(p.str||"").trim()).map(p=>{var y,b;return{text:String(p.str||"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),x:Number(((y=p.transform)==null?void 0:y[4])||0),y:Number(((b=p.transform)==null?void 0:b[5])||0)}}),u=d.filter(p=>p.x>=520&&i.test(p.text.replace(/[,:;]+$/,""))),f=[];for(const p of u){const b=d.filter(w=>Math.abs(w.y-p.y)<=7.5).sort((w,C)=>w.x-C.x).filter(w=>w.x<p.x-4&&w.x<535).map(w=>w.text).join(" ").replace(/\s+/g," ").trim(),N=b?c(b):"";N&&f.push({y:p.y,key:N})}f.sort((p,y)=>y.y-p.y);const g=d.filter(p=>/Serial\s*(?:No\.?|Number)?(?:\(s\))?\s*[:#-]?/i.test(p.text)).sort((p,y)=>y.y-p.y);for(const p of g){const y=f.filter(R=>R.y>p.y+.5).sort((R,I)=>R.y-p.y-(I.y-p.y))[0];if(!y||y.y-p.y>95)continue;const b=f.filter(R=>R.y<p.y-.5).sort((R,I)=>I.y-R.y)[0],N=b?b.y+.5:p.y-80,w=d.filter(R=>R.y<p.y-.5&&R.y>N&&R.x<545).sort((R,I)=>I.y-R.y||R.x-I.x),C=[];for(const R of w){let I=C.find(_=>Math.abs(_.y-R.y)<=3.5);I||(I={y:R.y,texts:[]},C.push(I)),I.texts.push({x:R.x,text:R.text})}l(y.key,p.text);for(const R of C.sort((I,_)=>_.y-I.y)){const I=R.texts.sort((_,J)=>_.x-J.x).map(_=>_.text).join(" ").replace(/\s+/g," ").trim();I&&l(y.key,I)}}}return[...a.values()]}function p8(t,n){const a=Ds(t);let s=0;return/STOCK/.test(a)&&s++,/COST|RATE|VALUE/.test(a)&&s++,/QTY|QUANTITY/.test(a)&&s++,/UNIT|PCS|PIECE/.test(a)&&s++,/SERIAL/.test(a)&&s++,/LOCATION|BRANCH|WAREHOUSE/.test(a)&&s++,n.length&&(s+=3),s}
3720const f8=new Set(["PCS","PC","PIECE","PIECES","UNIT","UNITS","NOS","NO","MODEL","OTHER","CURRENT","STOCK","TOTAL"]);function uE(t){return Ds(t).split(" ").filter(n=>n.length>1&&!f8.has(n))}function Np(t){return new Set(uE(t))}function ij(t,n){const a=Np(t),s=Np(n);if(!a.size||!s.size)return 0;let i=0;for(const m of a)s.has(m)&&i++;const c=i/Math.max(1,s.size),l=i/Math.max(1,a.size);return c*.45+l*.55}function Oc(t){return Ds(t).replace(/\b(?:PCS?|PIECES?|UNITS?|NOS?)\b/g," ").replace(/\s+/g," ").trim()}function Nh(t){return Oc(t).replace(/\b(\d+)\s*(?:TB)\b/g,(n,a)=>`${Number(a)*1e3}GB`).replace(/\b(\d+)\s*(?:GB)\b/g,"$1GB").replace(/\b(\d+)\s*(?:MHZ)\b/g,"$1MHZ").replace(/\b(\d+)(?:ST|ND|RD|TH)\s*(?:GENERATION|GEN)\b/g,"$1GEN").replace(/\bGENERATION\b/g,"GEN").replace(/\b(?:SERIES|SER)\b/g," ").replace(/\bWI[ -]?FI\b/g,"WIFI").replace(/\bUSB[ -]?C\b/g,"USBC").replace(/\s+/g," ").trim()}function Vu(t){const n=Nh(t);return[...new Set(n.split(" ").map(a=>a.replace(/[^A-Z0-9]/g,"")).filter(a=>!(a.length<4||!/[A-Z]/.test(a)||!/[0-9]/.test(a)||/^(?:DDR[345]|USB[23]|WIFI[4567]|CORE[3579])$/.test(a))))]}function o2(t,n){const a=Nh(`${t.sourceName} ${t.category} ${t.model}`),s=Nh(n.sourceName),i=Vu(`${t.model} ${t.sourceName}`),c=new Set(Vu(n.sourceName)),l=i.filter(N=>c.has(N)),m=new Set(hE(`${t.sourceName} ${t.category}`)),d=Np(s),u=[...m].filter(N=>d.has(N)),f=a===s||Nh(`${t.sourceName} ${t.model}`)===s||Nh(t.sourceName)===s,g=Nh(t.model||""),p=g.length>=4&&(s.includes(g)||g.includes(s)),y=l.some(N=>N.length>=5),b=u.length>=1;return{exactCanonical:f,modelContained:p,sharedKeys:l,lexical:u,uniqueKey:y,supported:b}}function Hu(t){return uE(t).filter(n=>n.length<3||/^(?:OTHER|GENERAL|ACCESSORIES|ACCESSORY|ELECTRONICS|PRODUCT|ITEM|DEVICE|BRAND)$/i.test(n)?!1:/\d/.test(n)||n.length>=5)}function g8(t){return[...new Set(Hu(t).filter(n=>/\d/.test(n)&&n.length>=3))]}function hE(t){return[...new Set(Hu(t).filter(n=>!/^\d+$/.test(n)))]}function y8(t,n){const a=Oc(t.model||""),s=Oc(n.sourceName),i=g8(a||`${t.sourceName} ${t.model}`),c=Np(s),l=i.filter(f=>c.has(f)),m=a.length>=3&&(s.includes(a)||a.includes(s)),u=hE(`${t.sourceName} ${t.category}`).filter(f=>c.has(f));return{openingModel:a,modelTokens:i,exactModelTokenMatches:l,modelContainment:m,lexicalMatches:u}}function AI(t){var s;const n=Ds(t);return((s=[["MAINBOARD",/\b(?:MAINBOARD|MOTHERBOARD)\b/],["PROCESSOR",/\b(?:PROCESSOR|CPU)\b/],["RAM",/\b(?:RAM|MEMORY)\b/],["SSD",/\b(?:SSD|NVME|SOLID STATE)\b/],["HDD",/\b(?:HDD|HARD DISK|HARD DRIVE)\b/],["NOTEBOOK",/\b(?:NOTEBOOK|LAPTOP)\b/],["PRINTER",/\b(?:PRINTER|PIXMA|DESKJET|LASERJET)\b/],["ROUTER",/\b(?:ROUTER|ACCESS POINT)\b/],["SWITCH",/\bSWITCH\b/],["POWER_SUPPLY",/\b(?:POWER SUPPLY|PSU)\b/],["GRAPHICS",/\b(?:GRAPHICS CARD|GPU|VGA CARD)\b/],["MONITOR",/\bMONITOR\b/],["KEYBOARD",/\bKEYBOARD\b/],["MOUSE",/\bMOUSE\b/],["TONER",/\bTONER\b/]].find(([,i])=>i.test(n)))==null?void 0:s[0])||""}function v8(t,n){const a=AI(`${t.category} ${t.sourceName}`),s=AI(n.sourceName);return{openingFamily:a,currentFamily:s,compatible:!a||!s||a===s}}function Ob(t){return String(t||"").trim().toUpperCase().replace(/\s+/g,"")}function b8(t){const n=new Map;for(const s of t){const i=vr(s);for(const c of new Set(s.serials||[])){const l=Ob(c);l&&(n.has(l)||n.set(l,new Set),n.get(l).add(i))}}const a=new Set([...n.entries()].filter(([,s])=>s.size>1).map(([s])=>s));return t.map(s=>({...s,serials:[...new Set(s.serials||[])].filter(i=>!a.has(Ob(i)))}))}function x8(t){var l;const n=new Map;let a=0,s=0;for(const m of t){const d=vr(m),u=new Set;for(const f of new Set(m.serials||[])){a++;const g=Ob(f);if(g){if(u.has(g)){s++;continue}u.add(g),n.has(g)||n.set(g,new Set),n.get(g).add(d)}}}const i=new Map;let c=0;for(const m of t){const d=vr(m),u=[],f=new Set;for(const g of new Set(m.serials||[])){const p=Ob(g);!p||f.has(p)||(f.add(p),(((l=n.get(p))==null?void 0:l.size)||0)===1?u.push(g):c++)}i.set(d,u)}return{uniqueByRef:i,duplicateCrossRow:c,duplicateWithinRow:s,uniqueTotal:[...n.values()].filter(m=>m.size===1).length,rawOccurrences:a}}function Ph(t,n){const a=Oc(`${t.sourceName} ${t.category} ${t.model}`),s=Oc(`${t.sourceName} ${t.model}`),i=Oc(t.sourceName),c=new Set(["CABLE","ADAPTER","BATTERY","CASING","GAMING","KEYBOARD","MOUSE","SPEAKER","SERVICE","USB","WIRELESS","LED","CHINA","LAPTOP","NOTEBOOK","MONITOR","PRINTER","SSD","RAM","ROUTER","TV","BOX","HEAD","PHONE","POWER","SUPPLY","MAINBOARD","PROCESSOR","TONER"]),l=Np(s),m=new Set([...l].filter(d=>!c.has(d)&&(/\d/.test(d)||d.length>=5)));return n.map(d=>{const u=Oc(d.sourceName),f=Np(u),g=u===a||u===s||u===i;let p=g?1:Math.max(ij(a,u),ij(s,u),ij(i,u));const y=[];g&&y.push("exact normalized identity"),!g&&i.length>=8&&(u.includes(i)||i.includes(u))&&(p=Math.max(p,.93),y.push("name containment")),!g&&s.length>=10&&(u.includes(s)||s.includes(u))&&(p=Math.max(p,.96),y.push("name+model containment"));const b=o2(t,d);!g&&b.exactCanonical&&(p=Math.max(p,.995),y.push("exact canonical product identity")),!g&&b.modelContained&&b.supported&&(p=Math.max(p,.992),y.push("canonical model containment + lexical support")),!g&&b.uniqueKey&&b.supported&&(p=Math.max(p,b.sharedKeys.length>=2?.995:.985),y.push(`${b.sharedKeys.length} deterministic model/SKU anchor${b.sharedKeys.length===1?"":"s"} + lexical support`));const N=y8(t,d);if(!g&&N.modelContainment&&(p=Math.max(p,.985),y.push("explicit model containment")),!g&&N.exactModelTokenMatches.length){const _=N.exactModelTokenMatches.some(T=>T.length>=5||/[A-Z]/.test(T)&&/\d/.test(T)),J=N.lexicalMatches.length>0;_&&J?(p=Math.max(p,.97),y.push(`${N.exactModelTokenMatches.length} exact model anchor + lexical support`)):N.exactModelTokenMatches.length>=2?(p=Math.max(p,.955),y.push(`${N.exactModelTokenMatches.length} exact model anchors`)):J&&(p=Math.max(p,.91),y.push("model anchor + lexical support"))}let w=0;for(const _ of l)f.has(_)&&w++;let C=0;for(const _ of m)f.has(_)&&C++;w&&y.push(`${w} shared token${w===1?"":"s"}`),C&&y.push(`${C} anchor token${C===1?"":"s"}`),f.size<=2&&l.size>2&&(p=Math.min(p,.55),y.push("generic Current-PDF fragment penalty"));const R=N.modelContainment||N.exactModelTokenMatches.length>=1&&N.lexicalMatches.length>=1||N.exactModelTokenMatches.length>=2;p<.999&&C===0&&w<3&&!R&&(p=Math.min(p,.69),y.push("insufficient specific-token evidence"));const I=v8(t,d);return I.compatible?I.openingFamily&&I.currentFamily&&y.push(`product-family ${I.openingFamily}`):(p=Math.min(p,.35),y.push(`product-family mismatch ${I.openingFamily} â ${I.currentFamily}`)),{ref:d,score:p,reason:y.join(" · ")||"token similarity only"}}).sort((d,u)=>u.score-d.score)}function k1(t,n){if(n.length<=140)return n;const a=new Set([...Hu(`${t.sourceName} ${t.category} ${t.model}`),...Vu(`${t.model} ${t.sourceName}`)]);return a.size?n.map(i=>{const c=Nh(i.sourceName),l=new Set([...Hu(c),...Vu(c)]);let m=0;for(const d of a)l.has(d)&&m++;return{ref:i,hits:m}}).filter(i=>i.hits>0).sort((i,c)=>c.hits-i.hits).slice(0,120).map(i=>i.ref):n.slice(0,80)}function j8(t,n){const a=Ph(t,k1(t,n)),s=a[0],i=a[1];return!s||s.score<.72?{ref:void 0,score:(s==null?void 0:s.score)??null,note:s?`Rejected best candidate at ${Math.round(s.score*100)}%: ${s.reason}`:"No Current Stock candidate",ambiguous:!1,candidates:a.slice(0,3)}:(i?s.score-i.score:1)<.06&&s.score<.95?{ref:void 0,score:s.score,note:`Ambiguous Current Stock match (${s.score.toFixed(2)} vs ${i==null?void 0:i.score.toFixed(2)}); no automatic link`,ambiguous:!0,candidates:a.slice(0,3)}:{ref:s.ref,score:s.score,note:`${s.score===1?"Exact normalized match":`Normalized product match ${Math.round(s.score*100)}%`} · ${s.reason}`,ambiguous:!1,candidates:a.slice(0,3)}}function vr(t){return Oc(t.sourceName)}const Bl=()=>new Promise(t=>setTimeout(t,0));async function oj(t,n,a){const s=await import(t8);s.GlobalWorkerOptions.workerSrc=n8;const i=await s.getDocument({data:new Uint8Array(await t.arrayBuffer())}).promise,c=[],l=[],m=[];for(let d=1;d<=i.numPages;d++){if(a!=null&&a())throw new Error("Preview cancelled");const g=(await(await i.getPage(d)).getTextContent()).items.filter(y=>String(y.str||"").trim()),p=r8(g);c.push(p),l.push(g),m.push(g.map(y=>String(y.str||"")).join(" ")+` 3721`+p.map(y=>y.text).join(` 3722`)),n==null||n(d,i.numPages),await Bl()}if(a!=null&&a())throw new Error("Preview cancelled");return{pages:c,itemPages:l,raw:m.join(` 3723`)}}async function w8(t,n,a){const s=Math.max(1,t.pages.length),i=[],c=[];for(let m=0;m<t.pages.length;m++){if(a!=null&&a())throw new Error("Preview cancelled");i.push(...c8(t.pages[m])),c.push(...l8(t.itemPages[m]||[])),n==null||n("Extracting products",m+1,s),await Bl()}let l=d8(i,c);for(let m=0;m<t.pages.length;m++){if(a!=null&&a())throw new Error("Preview cancelled");l=u8([t.pages[m]],l),n==null||n("Reading serial blocks",m+1,s),await Bl()}for(let m=0;m<t.itemPages.length;m++){if(a!=null&&a())throw new Error("Preview cancelled");l=h8([t.itemPages[m]],l),n==null||n("Reconciling serial lines",m+1,s),await Bl()}for(let m=0;m<t.itemPages.length;m++){if(a!=null&&a())throw new Error("Preview cancelled");l=m8([t.itemPages[m]],l),n==null||n("Verifying serial anchors",m+1,s),await Bl()}return{items:l,primaryCount:i.length,fallbackCount:c.length}}function mE(t){return t.map(n=>({...n,currentRef:void 0,serialMatched:0,serialPending:n.qty,quantityDifference:null,matchStatus:"reference_missing",matchScore:null,matchNote:"Current reference preview not generated yet",diagnosticCandidates:[]}))}function D1(t){const n=new Map;for(const a of t){const s=new Set([...Hu(`${a.sourceName} ${a.category} ${a.model}`),...Vu(`${a.model} ${a.sourceName}`)]);for(const i of s){const c=n.get(i)||[];c.push(a),n.set(i,c)}}return n}function E1(t,n,a,s=100){const i=new Set([...Hu(t.sourceName),...Vu(t.sourceName)]),c=new Map;for(const m of i){for(const d of n.get(m)||[])c.set(d.id,d);if(c.size>=s*2)break}const l=[...c.values()];return(l.length?l:a.slice(0,Math.min(s,a.length))).slice(0,s)}async function N8(t,n,a,s,i){var u;const c=t.filter(f=>f.qty<=0),l=new Set;if(!c.length||!n.length)return l;const m=D1(c),d=D1(a);for(let f=0;f<n.length;f++){if(i!=null&&i())throw new Error("Preview cancelled");const g=n[f],y=E1(g,m,c,90).map(w=>{const C=Ph(w,[g])[0],R=o2(w,g);return{score:(C==null?void 0:C.score)||0,evidence:R}}).filter(w=>w.score>=.9&&(w.evidence.exactCanonical||w.evidence.modelContained&&w.evidence.supported||w.evidence.uniqueKey&&w.evidence.supported)).sort((w,C)=>C.score-w.score),b=y[0],N=y[1];if(b&&b.score>=.93&&(!N||b.score-N.score>=.05)){const w=E1(g,d,a,90);let C=0;for(const R of w){const I=((u=Ph(R,[g])[0])==null?void 0:u.score)||0;I>C&&(C=I)}C<b.score-.03&&l.add(vr(g))}((f+1)%8===0||f===n.length-1)&&(s==null||s(f+1,n.length),await Bl())}return l}async function Av(t,n,a,s,i,c){var N;if(!n.length)return mE(t);const l=n.filter(w=>!s.has(vr(w))),m=new Map(l.map(w=>[vr(w),w])),d=[];for(let w=0;w<t.length;w++){if(c!=null&&c())throw new Error("Preview cancelled");const C=t[w],R=a[C.id],I=R?m.get(R):void 0,_=I?{ref:I,score:1,note:"Manual Serial Product Mapping Review confirmation",ambiguous:!1,candidates:Ph(C,k1(C,l)).slice(0,3)}:j8(C,l);d.push({item:C,match:_}),((w+1)%8===0||w===t.length-1)&&(i==null||i("Matching opening products",w+1,t.length),await Bl())}const u=new Set(d.filter(w=>w.match.ref).map(w=>vr(w.match.ref))),f=d.map((w,C)=>w.match.ref?null:C).filter(w=>w!==null),g=l.filter(w=>!u.has(vr(w)));if(f.length&&g.length){const w=new Map(t.map((C,R)=>
3723[C.id,R]));for(let C=0;C<g.length;C++){if(c!=null&&c())throw new Error("Preview cancelled");const R=g[C],I=new Set([...Hu(R.sourceName),...Vu(R.sourceName)]);if(I.size){const _=f.map(J=>d[J].item).filter(J=>[...Hu(`${J.sourceName} ${J.category} ${J.model}`),...Vu(`${J.model} ${J.sourceName}`)].some(G=>I.has(G))).slice(0,120);if(_.length){const J=_.map(z=>{const H=Ph(z,[R])[0];return{item:z,score:(H==null?void 0:H.score)||0,reason:(H==null?void 0:H.reason)||"No evidence"}}).sort((z,H)=>H.score-z.score),T=J[0],G=J[1];if(T&&T.score>=.91&&(!G||T.score-G.score>=.08)){const z=o2(T.item,R),H=z.exactCanonical||z.modelContained&&z.supported||z.uniqueKey&&z.supported,K=w.get(T.item.id);if(H&&K!==void 0&&!d[K].match.ref){const L=Ph(T.item,k1(T.item,g)),D=L[0],M=L[1];D&&vr(D.ref)===vr(R)&&D.score>=.91&&(!M||D.score-M.score>=.08)&&(d[K].match={ref:R,score:Math.min(.999,D.score),note:`Mutual-best deterministic recovery · ${D.reason}`,ambiguous:!1,candidates:L.slice(0,3)},u.add(vr(R)))}}}}((C+1)%8===0||C===g.length-1)&&(i==null||i("Verifying unmatched identities",C+1,g.length),await Bl())}}const p=new Map;d.forEach((w,C)=>{if(!w.match.ref)return;const R=vr(w.match.ref);if(!R)return;const I=p.get(R)||[];I.push(C),p.set(R,I)});const y=new Map;for(const[w,C]of p){if(C.length<=1)continue;const R=[...C].sort((G,z)=>(d[z].match.score||0)-(d[G].match.score||0)),I=R[0],_=R[1],J=d[I].match.score||0,T=d[_].match.score||0;J>=.95&&(J-T>=.02||J===1&&T<1)&&y.set(w,I)}const b=[];for(let w=0;w<d.length;w++){if(c!=null&&c())throw new Error("Preview cancelled");const{item:C,match:R}=d[w],I=R.ref?vr(R.ref):"",_=I?p.get(I)||[]:[],J=_.length>1&&y.get(I)!==w,T=_.length>1&&!y.has(I),G=J||T?void 0:R.ref,z=G?Math.min(C.qty,Math.max(0,G.qty),((N=G.serials)==null?void 0:N.length)||0):0,H=Math.max(0,C.qty-z),K=G?G.qty-C.qty:null,D=R.ambiguous||!!J||!!T?"ambiguous":G?K!==0?"qty_mismatch":H>0?"serial_pending":"matched":"reference_missing",M=J||T?"Reference collision: the same Current Stock row matched more than one opening item; only a clearly stronger exact/high-confidence winner may use it.":R.note;b.push({...C,currentRef:G,serialMatched:z,serialPending:H,quantityDifference:K,matchStatus:D,matchScore:R.score,matchNote:M,diagnosticCandidates:R.candidates}),((w+1)%20===0||w===d.length-1)&&(i==null||i("Finalizing audit",w+1,d.length),await Bl())}return b}function S8({profile:t,branches:n}){const a=x.useRef(null),s=x.useRef(null),i=x.useRef(null),[c,l]=x.useState(""),[m,d]=x.useState(null),[u,f]=x.useState(""),[g,p]=x.useState(null),[y,b]=x.useState([]),[N,w]=x.useState([]),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState(""),[G,z]=x.useState(!1),[H,K]=x.useState(!1),[L,D]=x.useState(!1),[M,Z]=x.useState([]),[fe,q]=x.useState(!1),[ne,ae]=x.useState(!1),[Y,je]=x.useState(""),[V,$]=x.useState([]),[F,P]=x.useState(!1),[ue,me]=x.useState({}),[ge,de]=x.useState(null),[Pe,Re]=x.useState(!1),[Ee,Be]=x.useState(null),[We,it]=x.useState(null),[_e,ee]=x.useState(null),[qe,se]=x.useState(null),[pe,Se]=x.useState(!1),[Me,ot]=x.useState(new Set),[wt,ct]=x.useState([]),Ce=x.useRef(0),De=x.useMemo(()=>{const we=Ds(I);return wt.filter(rt=>!we||Ds(`${rt.sourceName} ${rt.category} ${rt.model}`).includes(we))},[wt,I]),Te=x.useMemo(()=>({products:y.length,qty:y.reduce((we,rt)=>we+rt.qty,0),currentMatched:wt.filter(we=>we.currentRef).length,serialMatched:wt.reduce((we,rt)=>we+rt.serialMatched,0),serialPending:wt.reduce((we,rt)=>we+rt.serialPending,0),warnings:wt.filter(we=>we.matchStatus==="ambiguous").length,quantityChanges:wt.filter(we=>we.matchStatus==="qty_mismatch").length,ambiguous:wt.filter(we=>we.matchStatus==="ambiguous").length,referenceMissing:wt.filter(we=>we.matchStatus==="reference_missing").length}),[y,wt]),ce=H&&(_e==null?void 0:_e.exact)===!0&&y.length>0&&wt.length===y.length,Ye=ce&&L&&N.length>0,Je=x.useMemo(()=>new Map(wt.map(we=>[we.id,we])),[wt]),le=x.useMemo(()=>x8(N),[N]),nt=x.useMemo(()=>{var Xt;const we=le.uniqueTotal,rt=new Set(wt.filter(Wt=>Wt.currentRef).map(Wt=>vr(Wt.currentRef)));let St=0,Qt=0,gn=0;for(const Wt of wt){const Gt=Wt.currentRef;if(!Gt)continue;const $t=((Xt=le.uniqueByRef.get(vr(Gt)))==null?void 0:Xt.length)||0;St+=$t;const Vt=Math.min($t,Math.max(0,Math.floor(Gt.qty)));Qt+=Math.max(0,$t-Vt),gn+=Math.max(0,Vt-Math.max(0,Math.floor(Wt.qty)))}const An=N.filter(Wt=>!rt.has(vr(Wt))).reduce((Wt,Gt)=>{var $t;return Wt+((($t=le.uniqueByRef.get(vr(Gt)))==null?void 0:$t.length)||0)},0),Sn=wt.reduce((Wt,Gt)=>Wt+Gt.serialMatched,0);return{totalExtracted:we,matchedReferenceSerials:St,unmatchedReferenceSerials:An,currentQtyCapRejected:Qt,openingQtyCapRejected:gn,linked:Sn,duplicateCrossRow:le.duplicateCrossRow,duplicateWithinRow:le.duplicateWithinRow,rawOccurrences:le.rawOccurrences}},[N,wt,le]),xt=x.useMemo(()=>{var Vt,sn;const we=new Set(wt.filter(on=>on.currentRef).map(on=>vr(on.currentRef)));let rt=0,St=0,Qt=0,gn=0;
3723for(const on of N){if(!((Vt=on.serials)!=null&&Vt.length)||we.has(vr(on)))continue;const ke=((sn=le.uniqueByRef.get(vr(on)))==null?void 0:sn.length)||0;Me.has(vr(on))?(rt+=ke,St++):(Qt+=ke,gn++)}const An=nt.currentQtyCapRejected,Sn=nt.openingQtyCapRejected,Xt=nt.linked+rt+Qt+An+Sn,Wt=nt.totalExtracted-Xt,Gt=Math.max(0,Wt),$t=Math.max(0,-Wt);return{raw:nt.totalExtracted,safeOpening:nt.linked,currentOnlyExcluded:rt,currentOnlyRows:St,ambiguousSerials:Qt,ambiguousRows:gn,currentQtyCapExcluded:An,openingQtyCapExcluded:Sn,crossRowDuplicateExcluded:nt.duplicateCrossRow,withinRowDuplicateExcluded:nt.duplicateWithinRow,accounted:Xt,unaccounted:Gt,overaccounted:$t,balanceDifference:Wt,balanced:Xt===nt.totalExtracted}},[N,wt,Me,nt,le]),te=x.useMemo(()=>{if(!L||!N.length)return[];const we=new Set(wt.filter(St=>St.currentRef).map(St=>vr(St.currentRef))),rt=D1(y);return N.filter(St=>{var Qt;return(((Qt=St.serials)==null?void 0:Qt.length)||0)>0&&!we.has(vr(St))&&!Me.has(vr(St))}).map(St=>{var Sn;const gn=E1(St,rt,y,100).map(Xt=>{const Wt=Ph(Xt,[St])[0];return{item:Xt,score:(Wt==null?void 0:Wt.score)||0,reason:(Wt==null?void 0:Wt.reason)||"No evidence"}}).sort((Xt,Wt)=>Wt.score-Xt.score).slice(0,5),An=((Sn=Object.entries(ue).find(([,Xt])=>Xt===vr(St)))==null?void 0:Sn[0])||"";return{ref:St,key:vr(St),candidates:gn,assignedOpeningId:An}}).sort((St,Qt)=>{var gn,An;return(((gn=Qt.ref.serials)==null?void 0:gn.length)||0)-(((An=St.ref.serials)==null?void 0:An.length)||0)})},[N,y,wt,ue,Me,L]),Ge=async(we,rt)=>{const St={...ue};for(const[An,Sn]of Object.entries(St))(Sn===we||An===rt)&&delete St[An];if(rt&&(St[rt]=we),me(St),ae(!1),!L||!N.length)return;const Qt=++Ce.current,gn=()=>Ce.current!==Qt;z(!0);try{const An=await Av(y,N,St,Me,(Sn,Xt,Wt)=>T(`${Sn}... ${Xt}/${Wt}`),gn);gn()||(ct(An),T(`Manual mapping review updated. ${Object.keys(St).length} manual mapping(s) active.`))}catch(An){gn()||T(`Manual mapping recalculation failed: ${An instanceof Error?An.message:"Unknown error"}`)}finally{gn()||z(!1)}},pt=async()=>{if(me({}),ae(!1),!L||!N.length)return;const we=++Ce.current,rt=()=>Ce.current!==we;z(!0);try{const St=await Av(y,N,{},Me,(Qt,gn,An)=>T(`${Qt}... ${gn}/${An}`),rt);rt()||(ct(St),T("Manual mappings cleared; automatic safe reconciliation restored."))}catch(St){rt()||T(`Manual mapping reset failed: ${St instanceof Error?St.message:"Unknown error"}`)}finally{rt()||z(!1)}};async function $e(we){var St;const rt=(St=we.target.files)==null?void 0:St[0];if(rt){z(!0),T(""),l(rt.name),d(rt),K(!1),D(!1),q(!1),ae(!1),$([]),P(!1),me({}),de(null),Re(!1),Be(null),ee(null),se(null),Se(!1),Z([]),ot(new Set),ct([]);try{const Qt=await oj(rt,(ke,Ct)=>T(`Reading opening PDF... ${ke}/${Ct} page(s)`));s.current={file:rt,pdf:Qt};const{pages:gn,raw:An}=Qt,Sn=SI(An,gn);if(!Sn.valid)throw new Error(`Please choose a valid Date Wise Stock PDF with a detectable snapshot date. Detection: Date Wise ${Sn.hasDateWise?"OK":"missing"}, Back Dated ${Sn.hasBackDated?"OK":"not exposed by PDF text layer"}, report date ${Sn.hasReportDate?"OK":"missing"}. No specific calendar date is required.`);je(Sn.reportDate);const Xt=CI(gn,Sn.reportDate,!0),Wt=Xt.filter(ke=>ke.qty>0);if(Z(Xt),!Wt.length)throw new Error("No positive-quantity stock rows could be parsed.");b(Wt);const Gt=i8(gn,Sn.reportDate),$t=Gt.reduce((ke,Ct)=>ke+Ct.qty,0),Vt=Wt.reduce((ke,Ct)=>ke+Ct.qty,0),sn=o8(gn),on=Gt.length===Wt.length&&Math.abs($t-Vt)<1e-6;ee({physicalRows:Gt.length,physicalQty:$t,parsedRows:Wt.length,parsedQty:Vt,negativeRows:sn.rows,negativeQty:sn.qty,exact:on}),T(on?`${Wt.length} opening-stock products read successfully. Independent source row-count + quantity control is EXACT. ${sn.rows} negative-stock source row(s) were correctly excluded from positive opening.`:`SOURCE CONTROL FAIL: physical PDF positive rows/qty ${Gt.length} / ${$t.toLocaleString("en-BD")} do not equal parsed products/qty ${Wt.length} / ${Vt.toLocaleString("en-BD")}. Import is blocked until both controls are exact.`)}catch(Qt){b([]),Z([]),je(""),T(`Opening stock PDF read failed: ${Qt instanceof Error?Qt.message:"Unknown error"}`)}finally{z(!1),we.target.value=""}}}async function st(we){var St;const rt=(St=we.target.files)==null?void 0:St[0];rt&&(f(rt.name),p(rt),w([]),K(!1),D(!1),q(!1),ae(!1),$([]),P(!1),me({}),ot(new Set),ct([]),i.current=null,z(!1),T(`Current PDF selected: ${rt.name}. Parsing is deferred until Preview Current Reference, so file selection stays instant and responsive.`),we.target.value="")}function Nt(){Ce.current++,z(!1),T("Preview cancelled. No stock data was written.")}async function be(){var St;if(!m){T("Choose a Back Dated Date Wise Stock PDF first.");return}z(!0),K(!1),D(!1),q(!1),ae(!1),me({}),de(null),Re(!1),Be(null),ot(new Set),ct([]);const we=++Ce.current,rt=()=>Ce.current!==we;T(g?"Re-reading both PDFs for a safe two-phase preview...":"Re-reading the back-dated PDF for an authoritative opening-quantity preview...");try{let Qt;((St=s.current)==null?void 0:St.file)===m?Qt=s.current.pdf:(Qt=await oj(m,(Xt,Wt)=>T(`Reading opening PDF... ${Xt}/${Wt} page(s)`),rt),s.current={file:m,pdf:Qt});const gn=SI(Qt.raw,Qt.pages);if(!gn.valid)throw new Error(`The selected opening PDF was read, but Date Wise Stock identity/date detection failed: Date Wise ${gn.hasDateWise?"OK":"missing"}, Back Dated ${gn.hasBackDated?"OK":"not exposed by PDF text layer"}, report date ${gn.hasReportDate?"OK":"missing"}. The PDF detected As On date is used as the authoritative opening snapshot date.`);const An=CI(Qt.pages,gn.reportDate,!0),Sn=An.filter(Xt=>Xt.qty>0);if(Z(An),!Sn.length)throw new Error(`The ${ou(gn.reportDate)} opening PDF was selected, but no positive-quantity opening rows could be parsed.`);if(je(gn.reportDate),b(Sn),ct(mE(Sn)),K(!0),!g){w([]),T(`Opening preview ready: ${Sn.length} authoritative product(s). You can import Phase 1 now. The Current Stock PDF is optional and can be reconciled later without changing opening quantity.`);return}try{let Xt,Wt,Gt=0,$t=0;const Vt=i.current;if((Vt==null?void 0:Vt.file)===g)Xt=Vt.pdf,Wt=Vt.items,Gt=Vt.primaryCount,$t=Vt.fallbackCount,T(`Using cached Current PDF parse (${Xt.pages.length} pages). Preparing reconciliation preview...`),await Bl();else{Xt=await oj(g,(Et,Rt)=>T(`Reading Current PDF... ${Et}/${Rt} page(s)`),rt);const Ct=await w8(Xt,(Et,Rt,xn)=>T(`${Et}... ${Rt}/${xn} page(s)`),rt);Wt=Ct.items,Gt=Ct.primaryCount,$t=Ct.fallbackCount,i.current={file:g,pdf:Xt,items:Wt,primaryCount:Gt,fallbackCount:$t}}Wt=b8(Wt),i.current={file:g,pdf:Xt,items:Wt,primaryCount:Gt,fallbackCount:$t};const sn=p8(Xt.raw,Wt);if(!Wt.length||sn<6)throw new Error(`no safe Current Stock rows recognized (row ${Gt}, coordinate ${$t}, confidence ${sn})`);if(rt())throw new Error("Preview cancelled");T("Auditing opening-zero/current-only identities...");const on=await N8(An,Wt,Sn,(Ct,Et)=>T(`Auditing opening-zero/current-only identities... ${Ct}/${Et}`),rt);if(rt())throw new Error("Preview cancelled");ot(on),T("Building safe serial reconciliation...");const ke=await Av(Sn,Wt,{},on,(Ct,Et,Rt)=>T(`${Ct}... ${Et}/${Rt}`),rt);if(rt())throw new Error("Preview cancelled");if(w(Wt),ct(ke),C)try{const Ct=`opening_${gn.reportDate}_${C}`,Et=await mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${Ct}/manualReferenceMappings`)),Rt=Et.exists()?Et.val()||{}:{},xn=new Set(Wt.map(vr)),dn=new Set(Sn.map(wa=>wa.id)),Ln={};for(const[wa,Ca]of Object.entries(Rt))dn.has(wa)&&xn.has(String(Ca))&&(Ln[wa]=String(Ca));
3723if(me(Ln),Object.keys(Ln).length){T("Applying saved manual serial mappings...");const wa=await Av(Sn,Wt,Ln,on,(Ca,In,Sa)=>T(`${Ca}... ${In}/${Sa}`),rt);if(rt())throw new Error("Preview cancelled");ct(wa)}}catch(Ct){console.warn("Opening stock manual mapping restore warning",Ct)}D(!0),T(`Two-phase preview ready: ${Sn.length} authoritative opening product(s) + ${Wt.length} Current Stock reference row(s) + ${Wt.reduce((Ct,Et)=>Ct+new Set(Et.serials||[]).size,0)} serial evidence token(s). Phase 1 can be posted independently; Phase 2 never changes quantity.`)}catch(Xt){w([]),D(!1),T(`Opening preview is READY and safe to import. Current reference preview failed (${Xt instanceof Error?Xt.message:"Unknown error"}). Phase 1 is unaffected; nothing was written.`)}}catch(Qt){K(!1),D(!1),T(`Opening preview failed: ${Qt instanceof Error?Qt.message:"Unknown error"} Nothing was written to Firebase.`)}finally{z(!1),setTimeout(()=>{var Qt;return(Qt=a.current)==null?void 0:Qt.scrollIntoView({behavior:"smooth",block:"start"})},40)}}async function jt(){if(!C||!Y||!ce){T("Select the branch and generate the corrected opening preview first.");return}z(!0),T(""),de(null),Re(!1);try{const we=`opening_${Y}_${C}`,[rt,St]=await Promise.all([mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${we}`)),mn(re(ie,`inventoryOpeningItems/${t.companyId}/${we}`))]);if(!rt.exists())throw new Error("No existing Phase 1 opening batch exists for this branch/date. Use normal Phase 1 import instead.");const Qt=(St.exists()?St.val():{})||{},gn=y.filter(Wt=>!Qt[Wt.id]),An=y.filter(Wt=>{var Gt;return Qt[Wt.id]&&Math.abs(Number(((Gt=Qt[Wt.id])==null?void 0:Gt.qty)||0)-Wt.qty)>1e-6}).map(Wt=>{var Gt;return{item:Wt,savedQty:Number(((Gt=Qt[Wt.id])==null?void 0:Gt.qty)||0)}}),Sn=Object.values(Qt),Xt=Sn.reduce((Wt,Gt)=>Wt+Number((Gt==null?void 0:Gt.qty)||0),0);de({missing:gn,qtyMismatches:An,savedCount:Sn.length,savedTotal:Xt}),T(!gn.length&&!An.length?`OPENING COMPLETENESS EXACT: ${y.length} products / ${Te.qty.toLocaleString("en-BD")} units match the existing opening batch.`:`OPENING COMPLETENESS AUDIT: ${gn.length} source product row(s) were omitted by the old page-boundary parser; ${An.length} existing quantity mismatch(es). Review before repair.`)}catch(we){T(`Opening completeness audit failed: ${we instanceof Error?we.message:"Unknown error"}`)}finally{z(!1)}}async function bt(){if(!C||!Y||!ce){T("Select the branch and generate the opening preview first.");return}z(!0),T(""),Be(null);try{const we=`opening_${Y}_${C}`,[rt,St,Qt]=await Promise.all([mn(re(ie,`inventoryOpeningItems/${t.companyId}/${we}`)),mn(re(ie,`inventoryProducts/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}/${C}`))]),gn=(rt.exists()?rt.val():{})||{},An=(St.exists()?St.val():{})||{},Sn=(Qt.exists()?Qt.val():{})||{},Xt=(sn,on)=>Ds(String(sn??""))===Ds(String(on??"")),Wt=y.map(sn=>{const on=[],ke=gn[sn.id],Ct=An[sn.id],Et=Sn[sn.id];ke?(Xt(ke.sourceName,sn.sourceName)||on.push(`Opening item name mismatch: ${String(ke.sourceName||"(blank)")}`),Xt(ke.category,sn.category)||on.push("Opening item category mismatch"),Xt(ke.model,sn.model)||on.push("Opening item model mismatch"),Xt(ke.unit,sn.unit)||on.push("Opening item unit mismatch"),Math.abs(Number(ke.qty||0)-sn.qty)>1e-6&&on.push(`Opening item qty mismatch: ${Number(ke.qty||0)}`),String(ke.id||sn.id)!==sn.id&&on.push(`Opening item embedded ID mismatch: ${String(ke.id||"(blank)")}`)):on.push("Opening item missing by generated ID"),Ct?(Xt(Ct.name,sn.sourceName)||on.push(`Product master name mismatch: ${String(Ct.name||"(blank)")}`),Xt(Ct.category,sn.category)||on.push("Product master category mismatch"),Xt(Ct.model,sn.model)||on.push("Product master model mismatch"),Xt(Ct.unit,sn.unit)||on.push("Product master unit mismatch"),String(Ct.id||sn.id)!==sn.id&&on.push(`Product master embedded ID mismatch: ${String(Ct.id||"(blank)")}`)):on.push("Inventory product master missing"),Et?(String(Et.productId||sn.id)!==sn.id&&on.push(`Stock productId mismatch: ${String(Et.productId||"(blank)")}`),Math.abs(Number(Et.openingQty||0)-sn.qty)>1e-6&&on.push(`Stock openingQty mismatch: ${Number(Et.openingQty||0)}`),String(Et.openingDate||"")!==Y&&on.push(`Stock openingDate mismatch: ${String(Et.openingDate||"(blank)")}`)):on.push("Branch inventory stock row missing");const Rt=Object.entries(gn).filter(([dn,Ln])=>dn!==sn.id&&Xt(Ln==null?void 0:Ln.sourceName,sn.sourceName)&&Xt(Ln==null?void 0:Ln.category,sn.category)&&Xt(Ln==null?void 0:Ln.model,sn.model)&&Xt(Ln==null?void 0:Ln.unit,sn.unit)).map(([dn])=>dn);Rt.length&&on.push(`Duplicate opening identity under other ID: ${Rt.slice(0,2).join(", ")}`);const xn=Object.entries(An).filter(([dn,Ln])=>dn!==sn.id&&Xt(Ln==null?void 0:Ln.name,sn.sourceName)&&Xt(Ln==null?void 0:Ln.category,sn.category)&&Xt(Ln==null?void 0:Ln.model,sn.model)&&Xt(Ln==null?void 0:Ln.unit,sn.unit)).map(([dn])=>dn);return xn.length&&on.push(`Duplicate product master identity under other ID: ${xn.slice(0,2).join(", ")}`),{item:sn,issues:on,savedItemName:String((ke==null?void 0:ke.sourceName)||""),productName:String((Ct==null?void 0:Ct.name)||""),stockOpeningQty:Et?Number(Et.openingQty||0):null,
3723stockQty:Et?Number(Et.qty||0):null}}),Gt=Wt.filter(sn=>sn.issues.length);Be({rows:Gt,healthy:Wt.length-Gt.length,issues:Gt.length});const $t=Wt.find(sn=>Ds(sn.item.sourceName)===Ds("Toner Power Print 85A // 78A")),Vt=$t?` Target trace: ${$t.item.sourceName} [${$t.item.id}] -> ${$t.issues.length?$t.issues.join(" | "):`identity chain exact; openingQty ${$t.stockOpeningQty}, liveQty ${$t.stockQty}`}.`:" Target product was not present in the corrected positive-opening source rows.";T(`OPENING IDENTITY CHAIN AUDIT: ${Wt.length} source product(s) checked across Opening Items â Product Master â Branch Stock. ${Gt.length} issue row(s), ${Wt.length-Gt.length} exact chain(s).${Vt}`)}catch(we){T(`Opening identity-chain audit failed: ${we instanceof Error?we.message:"Unknown error"}`)}finally{z(!1)}}async function tn(){const we="Toner Power Print 85A // 78A";if(!C||!Y||!ce){T("Select the branch and generate the opening preview first.");return}z(!0),T(""),it(null);try{const rt=`opening_${Y}_${C}`,[St,Qt,gn]=await Promise.all([mn(re(ie,`inventoryOpeningItems/${t.companyId}/${rt}`)),mn(re(ie,`inventoryProducts/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}/${C}`))]),An=(St.exists()?St.val():{})||{},Sn=(Qt.exists()?Qt.val():{})||{},Xt=(gn.exists()?gn.val():{})||{},Wt=Ds(we),Gt=xn=>Ds(String(xn??""))===Wt,$t=y.filter(xn=>Gt(xn.sourceName)),Vt=$t.map(xn=>xn.id),sn=Object.entries(An).filter(([xn,dn])=>Vt.includes(xn)||Gt(dn==null?void 0:dn.sourceName)).map(([xn,dn])=>({id:xn,sourceName:String((dn==null?void 0:dn.sourceName)||""),qty:Number((dn==null?void 0:dn.qty)||0),category:String((dn==null?void 0:dn.category)||""),model:String((dn==null?void 0:dn.model)||""),unit:String((dn==null?void 0:dn.unit)||"")})),on=new Set(sn.map(xn=>xn.id)),ke=Object.entries(Sn).filter(([xn,dn])=>Vt.includes(xn)||on.has(xn)||Gt(dn==null?void 0:dn.name)).map(([xn,dn])=>({id:xn,name:String((dn==null?void 0:dn.name)||""),category:String((dn==null?void 0:dn.category)||""),model:String((dn==null?void 0:dn.model)||""),unit:String((dn==null?void 0:dn.unit)||"")})),Ct=new Set([...Vt,...sn.map(xn=>xn.id),...ke.map(xn=>xn.id)]),Et=Object.entries(Xt).filter(([xn,dn])=>Ct.has(xn)||Ct.has(String((dn==null?void 0:dn.productId)||""))).map(([xn,dn])=>({id:xn,productId:String((dn==null?void 0:dn.productId)||""),qty:Number((dn==null?void 0:dn.qty)||0),openingQty:Number((dn==null?void 0:dn.openingQty)||0),openingDate:String((dn==null?void 0:dn.openingDate)||""),source:String((dn==null?void 0:dn.source)||"")}));let Rt="";$t.length?$t.some(xn=>Math.abs(xn.qty-269)<1e-6)?sn.length?ke.length?Et.length?Et.some(xn=>Math.abs(xn.openingQty-269)<1e-6)?Rt=`TRACE EXACT THROUGH FIREBASE: source 269 PCS â Opening Item â Product Master â branch stock openingQty 269. Live qty: ${Et.map(xn=>xn.qty).join(", ")}. If Stock Report still hides it, the defect is strictly in Stock Report row construction/join.`:Rt=`RED FAIL: branch stock exists, but openingQty is ${Et.map(xn=>xn.openingQty).join(", ")} instead of 269.`:Rt="RED FAIL: Product Master exists, but selected-branch inventoryStock row is missing.":Rt="RED FAIL: Opening Item exists, but Product Master identity is missing.":Rt="RED FAIL: source parser emitted 269 PCS, but no Opening Item exists for its generated identity.":Rt=`RED FAIL: exact source product exists, but parsed opening quantity is ${$t.map(xn=>xn.qty).join(", ")} instead of 269.`:Rt="RED FAIL: corrected PDF parser did not emit the exact 269 PCS source product.",it({target:we,sourceMatches:$t,sourceGeneratedIds:Vt,openingItems:sn,productMasters:ke,branchStock:Et,verdict:Rt}),T(`TARGET FORENSIC TRACE COMPLETE: ${Rt}`)}catch(rt){T(`Target forensic trace failed: ${rt instanceof Error?rt.message:"Unknown error"}`)}finally{z(!1)}}async function B(){if(!C||!Y||!ce||(_e==null?void 0:_e.exact)!==!0){T("Generate a ROW + QTY EXACT source preview and select the branch first.");return}z(!0),T(""),se(null),Se(!1);try{const we=`opening_${Y}_${C}`,[rt,St,Qt]=await Promise.all([mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${we}`)),mn(re(ie,`inventoryOpeningItems/${t.companyId}/${we}`)),mn(re(ie,`inventoryStock/${t.companyId}/${C}`))]);if(!rt.exists())throw new Error("No existing opening batch exists for this branch/date. Delta repair is only for an already-posted opening.");const gn=(St.exists()?St.val():{})||{},An=(Qt.exists()?Qt.val():{})||{},Sn=new Set(y.map(Ct=>Ct.id)),Xt=y.flatMap(Ct=>{var dn,Ln,wa;const Et=Number(((dn=gn[Ct.id])==null?void 0:dn.qty)??((Ln=An[Ct.id])==null?void 0:Ln.openingQty)??0),Rt=Number(((wa=An[Ct.id])==null?void 0:wa.qty)||0),xn=Ct.qty-Et;return Math.abs(xn)<=1e-6?[]:[{item:Ct,savedOpeningQty:Et,liveQty:Rt,delta:xn,kind:!gn[Ct.id]&&Math.abs(Et)<=1e-6?"missing":"qty_mismatch"}]}),Wt=M.filter(Ct=>
3723Ct.qty<0),Gt=Object.entries(gn).filter(([Ct,Et])=>!Sn.has(Ct)&&Number((Et==null?void 0:Et.qty)||0)>1e-6).map(([Ct,Et])=>{var In,Sa,aa,$a;const Rt=Number((Et==null?void 0:Et.qty)||0),xn=String((Et==null?void 0:Et.sourceName)||(Et==null?void 0:Et.name)||Ct),dn=String((Et==null?void 0:Et.category)||""),Ln=String((Et==null?void 0:Et.model)||""),wa=String((Et==null?void 0:Et.unit)||"PCS"),Ca=Wt.find(jn=>jn.id===Ct&&Ds(jn.sourceName)===Ds(xn)&&Ds(jn.category)===Ds(dn)&&Ds(jn.model)===Ds(Ln)&&Ds(jn.unit||"PCS")===Ds(wa||"PCS")&&Math.abs(Math.abs(jn.qty)-Rt)<=1e-6)||null;return{id:Ct,name:xn,category:dn,model:Ln,unit:wa,qty:Rt,liveQty:Number(((In=An[Ct])==null?void 0:In.qty)||0),stockOpeningQty:Number(((Sa=An[Ct])==null?void 0:Sa.openingQty)??(Et==null?void 0:Et.qty)??0),sourceBatchId:String(((aa=An[Ct])==null?void 0:aa.sourceBatchId)||""),stockSource:String((($a=An[Ct])==null?void 0:$a.source)||""),negativeMatch:Ca,forensicStatus:Ca?"exact_negative_mirror":"unresolved"}}),$t=Object.values(gn),Vt=$t.reduce((Ct,Et)=>Ct+Number((Et==null?void 0:Et.qty)||0),0),sn=Xt.reduce((Ct,Et)=>Ct+Et.delta,0);se({rows:Xt,unexpected:Gt,savedCount:$t.length,savedTotal:Vt,targetCount:y.length,targetTotal:Te.qty,deltaQty:sn});const on=Gt.filter(Ct=>Ct.forensicStatus==="unresolved"),ke=Gt.filter(Ct=>Ct.forensicStatus==="exact_negative_mirror");T(on.length?`SAFE DELTA AUDIT BLOCKED: ${on.length} unexpected existing positive opening row(s) do not have exact excluded-negative identity evidence.`:`SAFE DELTA AUDIT READY: ${Xt.length} positive-source correction(s), net +${sn.toLocaleString("en-BD")} units${ke.length?`, plus ${ke.length} exact signed-negative mirror reversal(s)`:""}. Post-cutover movement will be preserved.`)}catch(we){T(`Safe opening delta audit failed: ${we instanceof Error?we.message:"Unknown error"}`)}finally{z(!1)}}async function xe(){if(!qe||!qe.rows.length&&!qe.unexpected.length){T("Run Safe Opening Delta Audit first; there is no queued delta to repair.");return}if(qe.unexpected.filter(rt=>rt.forensicStatus==="unresolved").length){T("REPAIR BLOCKED: an unexpected positive opening row still lacks an exact excluded-negative identity + mirrored-quantity match.");return}if(!pe){T("Confirm the Safe Opening Delta Repair first.");return}if(!C||!Y||(_e==null?void 0:_e.exact)!==!0){T("Branch/source exactness is missing; repair stopped.");return}z(!0),T("");try{const rt=`opening_${Y}_${C}`,[St,Qt,gn]=await Promise.all([mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${rt}`)),mn(re(ie,`inventoryOpeningItems/${t.companyId}/${rt}`)),mn(re(ie,`inventoryStock/${t.companyId}/${C}`))]);if(!St.exists())throw new Error("Opening batch disappeared; repair stopped.");const An=(Qt.exists()?Qt.val():{})||{},Sn=(gn.exists()?gn.val():{})||{},Xt=new Set(y.map(Vt=>Vt.id)),Wt=Date.now(),Gt={};let $t=0;for(const Vt of qe.rows){const sn=Vt.item,on=Sn[sn.id]||{},ke=An[sn.id]||{},Ct=Number((ke==null?void 0:ke.qty)??(on==null?void 0:on.openingQty)??0),Et=sn.qty-Ct;if(Math.abs(Et-Vt.delta)>1e-6)throw new Error(`Safety block: ${sn.sourceName} changed after audit. Re-run the delta audit.`);const Rt=Number((on==null?void 0:on.qty)||0);Gt[`inventoryProducts/${t.companyId}/${sn.id}`]={id:sn.id,name:sn.sourceName,category:sn.category,model:sn.model,unit:sn.unit,sourceSystem:"Oner ERP / Takeplus",active:!0,updatedAt:Wt},Gt[`inventoryOpeningItems/${t.companyId}/${rt}/${sn.id}`]={...ke,...sn,branchId:C,sourceSystem:"Oner ERP / Takeplus",serialStatus:(ke==null?void 0:ke.serialStatus)||"reference_pending",currentReferenceQty:(ke==null?void 0:ke.currentReferenceQty)??null,currentReferenceCostPerUnit:(ke==null?void 0:ke.currentReferenceCostPerUnit)??null,currentReferenceSerialCount:Number((ke==null?void 0:ke.currentReferenceSerialCount)||0),reliableCurrentReferenceSerials:Array.isArray(ke==null?void 0:ke.reliableCurrentReferenceSerials)?ke.reliableCurrentReferenceSerials:[],serialLinkedQty:Number((ke==null?void 0:ke.serialLinkedQty)||0),serialPendingQty:Math.max(0,sn.qty-Number((ke==null?void 0:ke.serialLinkedQty)||0)),referenceMatchScore:(ke==null?void 0:ke.referenceMatchScore)??null,referenceMatchNote:(ke==null?void 0:ke.referenceMatchNote)||"Opening authority corrected by v5.4.352 Safe Opening Delta Repair",openingDeltaRepair:{version:"5.4.352",beforeQty:Ct,afterQty:sn.qty,delta:Et,repairedAt:Wt}},Gt[`inventoryStock/${t.companyId}/${C}/${sn.id}`]={...on,productId:sn.id,branchId:C,qty:Rt+Et,openingQty:sn.qty,openingDate:Y,source:(on==null?void 0:on.source)||"opening_migration_delta_repair",s
3723ourceBatchId:rt,openingCostStatus:(on==null?void 0:on.openingCostStatus)||"pending_historical_cost_reconciliation",serialStatus:(on==null?void 0:on.serialStatus)||"pending_reference_reconciliation",referenceSerialLinkedQty:Number((on==null?void 0:on.referenceSerialLinkedQty)||0),referenceSerialPendingQty:Math.max(0,sn.qty-Number((on==null?void 0:on.referenceSerialLinkedQty)||0)),openingDeltaRepair:{version:"5.4.352",beforeOpeningQty:Ct,afterOpeningQty:sn.qty,delta:Et,liveQtyBefore:Rt,liveQtyAfter:Rt+Et,repairedAt:Wt},updatedAt:Wt},$t+=Et}for(const Vt of qe.unexpected){const sn=An[Vt.id],on=Sn[Vt.id]||{},ke=M.find(Rt=>Rt.qty<0&&Rt.id===Vt.id&&Ds(Rt.sourceName)===Ds(Vt.name)&&Ds(Rt.category)===Ds(Vt.category)&&Ds(Rt.model)===Ds(Vt.model)&&Ds(Rt.unit||"PCS")===Ds(Vt.unit||"PCS")&&Math.abs(Math.abs(Rt.qty)-Vt.qty)<=1e-6),Ct=Number((sn==null?void 0:sn.qty)||0);if(!ke||Xt.has(Vt.id)||Math.abs(Ct-Vt.qty)>1e-6)throw new Error(`Forensic safety block: ${Vt.name} identity/quantity changed after audit. Re-run the audit.`);const Et=Number((on==null?void 0:on.qty)||0);Gt[`inventoryOpeningItems/${t.companyId}/${rt}/${Vt.id}`]=null,Gt[`inventoryStock/${t.companyId}/${C}/${Vt.id}`]={...on,productId:Vt.id,branchId:C,qty:Et-Ct,openingQty:0,openingDate:Y,source:(on==null?void 0:on.source)||"opening_migration_delta_repair",sourceBatchId:rt,openingDeltaRepair:{version:"5.4.360",forensicReason:"exact_signed_negative_mirror",excludedSourceQty:ke.qty,beforeOpeningQty:Ct,afterOpeningQty:0,delta:-Ct,liveQtyBefore:Et,liveQtyAfter:Et-Ct,repairedAt:Wt},updatedAt:Wt},$t-=Ct}Gt[`inventoryOpeningBatches/${t.companyId}/${rt}/productCount`]=y.length,Gt[`inventoryOpeningBatches/${t.companyId}/${rt}/totalQty`]=Te.qty,Gt[`inventoryOpeningBatches/${t.companyId}/${rt}/safeDeltaRepair`]={version:"5.4.360",sourceControl:"independent_row_qty_exact",correctedRowCount:qe.rows.length,forensicNegativeMirrorReversals:qe.unexpected.length,netOpeningDelta:$t,targetProductCount:y.length,targetOpeningQty:Te.qty,repairedAt:Wt,repairedByUid:t.uid,repairedByName:t.name||t.email||"User"},await yn(re(ie),Gt);try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.opening_balances_updated",entityType:"accounting",entityId:rt,summary:`Safe Opening Delta Repair corrected ${qe.rows.length} row(s), reversed ${qe.unexpected.length} exact signed-negative mirror row(s), net ${$t} opening units; post-cutover movement preserved.`,branchId:C,metadata:{phase:"safe_opening_delta_repair",version:"5.4.360",correctedRows:qe.rows.length,forensicNegativeMirrorReversals:qe.unexpected.length,netOpeningDelta:$t,targetProductCount:y.length,targetOpeningQty:Te.qty}})}catch(Vt){console.error("Safe Opening Delta Repair audit warning",Vt)}Se(!1),se(null),T(`SAFE OPENING DELTA REPAIR SUCCESS: ${y.length} authoritative products / ${Te.qty.toLocaleString("en-BD")} opening units are now the batch target. Net live-stock delta ${$t.toLocaleString("en-BD")} was applied without erasing post-cutover movement. Run the delta audit again; it must return 0 corrections.`)}catch(rt){T(`Safe Opening Delta Repair failed: ${rt instanceof Error?rt.message:"Unknown error"}`)}finally{z(!1)}}async function tt(){if(!ge||!ge.missing.length){T("Run the opening completeness audit first; no missing rows are currently queued for repair.");return}if(ge.qtyMismatches.length){T("REPAIR BLOCKED: existing opening quantity mismatches were found. Missing-row repair will not overwrite existing authoritative quantities.");return}if(!Pe){T("Confirm the missing-row completeness repair first.");return}if(!C||!Y){T("Branch/opening date is missing.");return}z(!0),T("");try{const we=`opening_${Y}_${C}`;if(!(await mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${we}`))).exists())throw new Error("Opening batch disappeared; repair was stopped.");const St=await mn(re(ie,`inventoryStock/${t.companyId}/${C}`)),Qt=(St.exists()?St.val():{})||{},gn=Date.now(),An={};let Sn=0;for(const Wt of ge.missing){const Gt=Qt[Wt.id],$t=Gt==null?void 0:Gt.openingQty;if($t!=null&&Math.abs(Number($t))>
37231e-6)throw new Error(`Safety block: ${Wt.sourceName} already has a non-zero openingQty in live stock but is missing from the opening-item ledger.`);const Vt=Number((Gt==null?void 0:Gt.qty)||0);An[`inventoryProducts/${t.companyId}/${Wt.id}`]={id:Wt.id,name:Wt.sourceName,category:Wt.category,model:Wt.model,unit:Wt.unit,sourceSystem:"Oner ERP / Takeplus",active:!0,updatedAt:gn},An[`inventoryOpeningItems/${t.companyId}/${we}/${Wt.id}`]={...Wt,branchId:C,sourceSystem:"Oner ERP / Takeplus",serialStatus:"reference_pending",currentReferenceQty:null,currentReferenceCostPerUnit:null,currentReferenceSerialCount:0,reliableCurrentReferenceSerials:[],serialLinkedQty:0,serialPendingQty:Wt.qty,referenceMatchScore:null,referenceMatchNote:"Recovered by v5.4.346 page-boundary completeness repair; Phase 2 reference can be re-applied safely"},An[`inventoryStock/${t.companyId}/${C}/${Wt.id}`]={...Gt||{},productId:Wt.id,branchId:C,qty:Vt+Wt.qty,openingQty:Wt.qty,openingDate:Y,source:(Gt==null?void 0:Gt.source)||"opening_migration_repair",sourceBatchId:we,openingCostStatus:(Gt==null?void 0:Gt.openingCostStatus)||"pending_historical_cost_reconciliation",serialStatus:(Gt==null?void 0:Gt.serialStatus)||"pending_reference_reconciliation",referenceSerialLinkedQty:Number((Gt==null?void 0:Gt.referenceSerialLinkedQty)||0),referenceSerialPendingQty:Math.max(0,Wt.qty-Number((Gt==null?void 0:Gt.referenceSerialLinkedQty)||0)),updatedAt:gn},Sn+=Wt.qty}An[`inventoryOpeningBatches/${t.companyId}/${we}/productCount`]=y.length,An[`inventoryOpeningBatches/${t.companyId}/${we}/totalQty`]=Te.qty,An[`inventoryOpeningBatches/${t.companyId}/${we}/completenessRepair`]={version:"5.4.346",reason:"cross_page_header_continuation_parser_recovery",recoveredProductCount:ge.missing.length,recoveredOpeningQty:Sn,repairedAt:gn,repairedByUid:t.uid,repairedByName:t.name||t.email||"User"},await yn(re(ie),An);try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.opening_balances_updated",entityType:"accounting",entityId:we,summary:`Opening completeness repair recovered ${ge.missing.length} omitted product row(s) / ${Sn} opening units.`,branchId:C,metadata:{phase:"opening_completeness_repair",version:"5.4.346",recoveredProductCount:ge.missing.length,recoveredOpeningQty:Sn}})}catch(Wt){console.error("Opening completeness repair audit warning",Wt)}const Xt=ge.missing.length;de({missing:[],qtyMismatches:[],savedCount:y.length,savedTotal:Te.qty}),Re(!1),T(`OPENING COMPLETENESS REPAIR SUCCESS: ${Xt} omitted product row(s) / ${Sn.toLocaleString("en-BD")} opening units restored. Existing post-cutover stock movement was preserved additively; existing opening quantities were not overwritten.`)}catch(we){T(`Opening completeness repair failed: ${we instanceof Error?we.message:"Unknown error"}`)}finally{z(!1)}}async function ht(){if(!y.length||!ce||!Y){T("Generate a valid opening preview first.");return}if(!C){T("Select the VERIXO branch before Phase 1 import.");return}if(!fe){T("Confirm the live-stock acknowledgement before Phase 1 import.");return}z(!0),T("");try{const we=`opening_${Y}_${C}`;if((await mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${we}`))).exists())throw new Error(`This branch already has an opening-stock batch for ${ou(Y)}. Phase 1 will not run twice.`);const St=await mn(re(ie,`inventoryStock/${t.companyId}/${C}`));let Qt=[];if(St.exists()){const Xt=St.val()||{},Wt=new Map(y.map($t=>[$t.id,$t]));Qt=Object.entries(Xt).filter(([,$t])=>$t&&Math.abs(Number($t.qty||0))>0).map(([$t,Vt])=>{const sn=String((Vt==null?void 0:Vt.productId)||$t),on=Wt.get(sn);return{productId:sn,productName:(on==null?void 0:on.sourceName)||String((Vt==null?void 0:Vt.name)||(Vt==null?void 0:Vt.productName)||sn),currentQty:Number((Vt==null?void 0:Vt.qty)||0),openingQty:on?on.qty:null,source:String((Vt==null?void 0:Vt.source)||(Vt==null?void 0:Vt.sourceType)||"existing live stock")}}),$(Qt);const Gt=Qt.filter($t=>$t.openingQty===null);if(Gt.length)throw new Error(`LIVE STOCK SAFETY BLOCK: ${Gt.length} existing non-zero stock record(s) are not present in the authoritative opening snapshot. They cannot be removed or over
3723written automatically.`);if(Qt.length&&!F)throw new Error(`CONFLICT REVIEW REQUIRED: ${Qt.length} existing non-zero stock record(s) overlap the opening snapshot. Review the conflict panel, explicitly confirm replacement with the authoritative snapshot, then run Phase 1 again.`)}else $([]),P(!1);const gn=y.filter(Xt=>!Xt.id||!Number.isFinite(Xt.qty)||Xt.qty<=0);if(gn.length)throw new Error(`SAFETY BLOCK: ${gn.length} invalid opening row(s) detected. Nothing was written.`);if(new Set(y.map(Xt=>Xt.id)).size!==y.length)throw new Error("SAFETY BLOCK: duplicate opening product identities detected. Nothing was written.");const An=Date.now(),Sn={};Sn[`inventoryOpeningBatches/${t.companyId}/${we}`]={id:we,branchId:C,openingDate:Y,cutoverDate:a8(Y),sourceSystem:"Oner ERP / Takeplus",sourceFile:c,status:"opening_posted_reference_pending",productCount:y.length,totalQty:Te.qty,openingQuantityAuthority:`${ou(Y)} Back Dated Date Wise Stock PDF`,detectedReportDate:Y,currentReferenceMode:"phase2_reference_only_never_changes_quantity",historicalImportPolicy:"pre_cutover_purchase_sales_must_reconcile_without_reapplying_opening_quantity",existingStockConflictResolution:Qt.length?{mode:"explicit_authoritative_snapshot_replace",count:Qt.length,items:Qt.map(Xt=>({productId:Xt.productId,previousQty:Xt.currentQty,openingQty:Xt.openingQty,previousSource:Xt.source}))}:null,createdAt:An,createdByUid:t.uid,createdByName:t.name||t.email||"User"};for(const Xt of y)Sn[`inventoryProducts/${t.companyId}/${Xt.id}`]={id:Xt.id,name:Xt.sourceName,category:Xt.category,model:Xt.model,unit:Xt.unit,sourceSystem:"Oner ERP / Takeplus",active:!0,updatedAt:An},Sn[`inventoryOpeningItems/${t.companyId}/${we}/${Xt.id}`]={...Xt,branchId:C,sourceSystem:"Oner ERP / Takeplus",serialStatus:"reference_pending",currentReferenceQty:null,currentReferenceCostPerUnit:null,currentReferenceSerialCount:0,reliableCurrentReferenceSerials:[],serialLinkedQty:0,serialPendingQty:Xt.qty,referenceMatchScore:null,referenceMatchNote:"Phase 2 Current Stock reference not applied yet"},Sn[`inventoryStock/${t.companyId}/${C}/${Xt.id}`]={productId:Xt.id,branchId:C,qty:Xt.qty,openingQty:Xt.qty,openingDate:Y,source:"opening_migration",sourceBatchId:we,openingCostStatus:"pending_historical_cost_reconciliation",serialStatus:"pending_reference_reconciliation",referenceSerialLinkedQty:0,referenceSerialPendingQty:Xt.qty,updatedAt:An};await yn(re(ie),Sn);try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.opening_balances_updated",entityType:"accounting",entityId:we,summary:`Opening stock Phase 1 posted for ${ou(Y)}: ${y.length} products / ${Te.qty} units.`,branchId:C,metadata:{sourceFile:c,productCount:y.length,totalQty:Te.qty,phase:"opening_quantity"}})}catch(Xt){console.error("Opening stock audit warning",Xt)}T(`PHASE 1 SUCCESS: ${y.length} products / ${Te.qty.toLocaleString("en-BD")} units posted from ${ou(Y)}. Quantity is now frozen as the opening authority. Any explicitly reviewed overlapping stock was replaced by this authoritative snapshot. Current cost/serial reference can be applied separately.`)}catch(we){T(`Opening stock Phase 1 failed: ${we instanceof Error?we.message:"Unknown error"}`)}finally{z(!1)}}async function dt(){var we,rt;if(!Ye){T("Generate a preview with both PDFs before applying Phase 2 reference data.");return}if(!C){T("Select the VERIXO branch before Phase 2.");return}if(!ne){T("Confirm that Phase 2 is reference-only before applying it.");return}if(!xt.balanced){T(`Phase 2 blocked: serial evidence audit is not exact (${xt.accounted}/${xt.raw}; unaccounted ${xt.unaccounted}, over-accounted ${xt.overaccounted}). Regenerate preview before applying.`);return}z(!0),T("");try{if(!Y)throw new Error("Opening report date is not available. Re-generate the opening preview.");const St=`opening_${Y}_${C}`,Qt=await mn(re(ie,`inventoryOpeningBatches/${t.companyId}/${St}`));if(!Qt.exists())throw new Error("Phase 1 opening quantity has not been posted for this branch yet.");const gn=Qt.val()||{};if(gn.openingDate!==Y)throw new Error("Opening batch date mismatch. Reference enrichment was blocked.");
3723if(Number(gn.productCount||0)!==y.length||Math.abs(Number(gn.totalQty||0)-Te.qty)>1e-6)throw new Error(`The selected ${ou(Y)} PDF does not match the already-posted opening batch. Use the same authoritative opening PDF.`);const An=wt.filter(Wt=>Wt.currentRef).map(Wt=>vr(Wt.currentRef));if(new Set(An).size!==An.length)throw new Error("SAFETY BLOCK: a Current Stock reference is linked to multiple opening products.");if(wt.some(Wt=>{var Gt;return Math.abs(Wt.qty-(((Gt=y.find($t=>$t.id===Wt.id))==null?void 0:Gt.qty)||0))>1e-6}))throw new Error("SAFETY BLOCK: reconciliation attempted to change an authoritative opening quantity.");const Sn=Date.now(),Xt={};Xt[`inventoryOpeningBatches/${t.companyId}/${St}/currentReferenceFile`]=u,Xt[`inventoryOpeningBatches/${t.companyId}/${St}/referenceStatus`]="reconciled_reference_only",Xt[`inventoryOpeningBatches/${t.companyId}/${St}/status`]="opening_posted_reference_reconciled",Xt[`inventoryOpeningBatches/${t.companyId}/${St}/referenceAppliedAt`]=Sn,Xt[`inventoryOpeningBatches/${t.companyId}/${St}/referenceAppliedByUid`]=t.uid,Xt[`inventoryOpeningBatches/${t.companyId}/${St}/manualReferenceMappings`]=ue,Xt[`inventoryOpeningBatches/${t.companyId}/${St}/manualReferenceMappingCount`]=Object.keys(ue).length,Xt[`inventoryOpeningBatches/${t.companyId}/${St}/reconciliation`]={matched:Te.currentMatched,ambiguous:Te.ambiguous,referenceMissing:Te.referenceMissing,quantityDifferences:Te.quantityChanges,serialMatched:Te.serialMatched,serialPending:Te.serialPending};for(const Wt of y){const Gt=Je.get(Wt.id),$t=Gt==null?void 0:Gt.currentRef,Vt=[...new Set(($t==null?void 0:$t.serials)||[])].slice(0,Math.max(0,Math.floor(Math.min(Wt.qty,($t==null?void 0:$t.qty)??0)))),sn=`inventoryOpeningItems/${t.companyId}/${St}/${Wt.id}`;Xt[`${sn}/serialStatus`]=Vt.length?"current_reference_available":"not_verified",Xt[`${sn}/currentReferenceQty`]=($t==null?void 0:$t.qty)??null,Xt[`${sn}/currentReferenceCostPerUnit`]=($t==null?void 0:$t.costPerUnit)??null,Xt[`${sn}/currentReferenceSerialCount`]=((we=$t==null?void 0:$t.serials)==null?void 0:we.length)??0,Xt[`${sn}/reliableCurrentReferenceSerials`]=Vt,Xt[`${sn}/serialLinkedQty`]=(Gt==null?void 0:Gt.serialMatched)||0,Xt[`${sn}/serialPendingQty`]=(Gt==null?void 0:Gt.serialPending)??Wt.qty,Xt[`${sn}/referenceMatchScore`]=(Gt==null?void 0:Gt.matchScore)??null,Xt[`${sn}/referenceMatchNote`]=(Gt==null?void 0:Gt.matchNote)||"Current reference not linked",Xt[`${sn}/referenceMappingMode`]=ue[Wt.id]?"manual_serial_product_review":"automatic_safe_match",Xt[`${sn}/manualCurrentReferenceKey`]=ue[Wt.id]||null,Xt[`${sn}/referenceAppliedAt`]=Sn;const on=`inventoryStock/${t.companyId}/${C}/${Wt.id}`;Xt[`${on}/currentReferenceQty`]=($t==null?void 0:$t.qty)??null,Xt[`${on}/currentReferenceCostPerUnit`]=($t==null?void 0:$t.costPerUnit)??null,Xt[`${on}/currentReferenceSerialCount`]=((rt=$t==null?void 0:$t.serials)==null?void 0:rt.length)??0,Xt[`${on}/referenceSerialLinkedQty`]=(Gt==null?void 0:Gt.serialMatched)||0,Xt[`${on}/referenceSerialPendingQty`]=(Gt==null?void 0:Gt.serialPending)??Wt.qty,Xt[`${on}/referenceReconciledAt`]=Sn}await yn(re(ie),Xt);try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.opening_balances_updated",entityType:"accounting",entityId:St,summary:`Opening stock Phase 2 reference reconciliation applied: ${Te.currentMatched} matched, ${Te.serialMatched} serial evidence linked.`,branchId:C,metadata:{sourceFile:u,phase:"current_reference",matched:Te.currentMatched,serialMatched:Te.serialMatched}})}catch(Wt){console.error("Opening stock reference audit warning",Wt)}T(`PHASE 2 SUCCESS: Current reference applied to ${Te.currentMatched} product(s). Opening quantity was not changed.`)}catch(St){T(`Current reference Phase 2 failed: ${St instanceof Error?St.message:"Unknown error"}`)}finally{z(!1)}}return e.jsxs("section",{className:"stock-migration-panel",children:[e.jsxs("div",{className:"stock-migration-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"INVENTORY MIGRATION"}),e.jsx("h2",{children:"Opening Stock Migration Center"}),e.jsx("p",{children:"Build VERIXO opening quantity from any valid Back Dated Date Wise Stock report. The PDF's detected As On date becomes the authoritative opening snapshot; Current Stock remains reference-only."}),e.jsx("small",{className:"opening-runtime-marker",children:"Runtime v5.4.347 · product-by-product opening identity chain audit"})]}),e.jsxs("div",{className:"safe-badge",children:[e.jsx(gs,{size:18})," Preview First"]})]}),e.jsxs("div",{className:"stock-migration-notice",children:[e.jsx(jp,{size:20}),e.jsxs("div",{children:[e.jsxs("strong",{children:["Detected opening date: ",Y?ou(Y):"Waiting for PDF"]}),e.jsx("p",{children:"Opening quantity is authoritative from the back-dated report. Current cost/serial data never changes that opening quantity automatically."})]})]}),e.jsxs("div",{className:"stock-upload-grid",children:[e.jsxs("label",{className:"stock-upload-card",children:[e.jsx(wp,{size:24}),e.jsx("strong",{children:"1. Choose Back Dated Date Wise Stock PDF"}),e.jsx("span",{children:c||"Back Dated Stock report"}),e.jsx("input",{type:"file",accept:"application/pdf",onChange:$e})]}),e.jsxs("label",{className:"stock-upload-card",children:[e.jsx(wp,{size:24}),e.jsx("strong",{children:"2. Choose Current Stock With Cost PDF"}),e.jsx("span",{children:u||"Qty + current cost + current serial reference"}),e.jsx("input",{type:"file",accept:"application/pdf",onChange:st})]})]}),e.jsxs("div",{className:"stock-workflow-actions stock-workflow-two-phase",children:[e.jsxs("div",{className:"stock-workflow-copy",children:[e.jsx("strong",{children:"3. Two-phase live-stock migration"}),e.jsx("span",{children:m?H?L?"Opening + Current reference preview ready. Post Phase 1 quantity first, then apply Phase 2 reference.":"Opening preview ready. Phase 1 can be posted now; Current cost/serial can be reconciled later.":"Generate a safe preview. The Current Stock PDF is optional for Phase 1.":"Choose a Back Dated Date Wise Stock PDF first."})]}),e.jsxs("div",{className:"stock-workflow-buttons stock-workflow-buttons-grid",children:[e.jsx("button",{className:"stock-preview-button",disabled:G||!m,onClick:be,children:G?"Working...":"Generate Safe Preview"}),e.jsx("button",{className:"stock-import-button",disabled:G||!C||!ce||!fe,onClick:ht,children:G?"Working...":"Phase 1 · Import Detected-Date Quantity"}),e.jsx("button",{className:"stock-preview-button",disabled:G||!m||!g,onClick:be,children:G?"Working...":"Preview Current Reference"}),e.jsx("button",{className:"stock-import-button stock-reference-button",disabled:G||!C||!Ye||!ne||!xt.balanced,onClick:dt,children:G?"Working...":"Phase 2 · Apply Cost / Serial Reference"}),G&&e.jsx("button",{type:"button",className:"stock-preview-button",onClick:Nt,children:"Cancel Preview"})]})]}),e.jsxs("div",{ref:a,className:`stock-result-panel ${H?"ready":J.toLowerCase().includes("fail")||J.toLowerCase().includes("error")?"error":"info"}`,children:[e.jsx("strong",{children:H?"Preview status: READY":J?"Preview status":"Preview status: waiting"}),e.jsx("span",{children:J||"Choose a Back Dated Date Wise Stock PDF and click Generate Safe Preview. The report As On date is detected automatically; no Firebase write happens during preview."}),e.jsx("small",{children:H?`Parsed ${y.length} authoritative opening product(s). To enable Phase 1 import: select a branch and tick the confirmation below.`:"Phase 1 import stays disabled until a valid preview, branch selection and confirmation are complete."})]}),!!y.length&&H&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"stock-summary-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Opening Date"}),e.jsx("strong",{children:ou(Y)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Opening Products"}),e.jsx("strong",{children:Te.products})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Opening Quantity"}
3723),e.jsx("strong",{children:Te.qty.toLocaleString("en-BD")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Current Reference Matched"}),e.jsx("strong",{children:Te.currentMatched})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Serial Matched / Pending"}),e.jsxs("strong",{children:[Te.serialMatched," / ",Te.serialPending]}),e.jsxs("small",{children:[Te.quantityChanges," qty difference(s) · ",Te.ambiguous," ambiguous/collision match(es)"]})]})]}),_e&&e.jsxs("div",{className:`stock-diagnostic-banner ${_e.exact?"":"stock-conflict-review"}`,children:[e.jsx("strong",{children:"Independent PDF Source Control · v5.4.351"}),e.jsxs("span",{children:["Physical positive rows: ",e.jsx("b",{children:_e.physicalRows})," · Physical positive Qty: ",e.jsx("b",{children:_e.physicalQty.toLocaleString("en-BD")})," · Parsed products: ",e.jsx("b",{children:_e.parsedRows})," · Parsed Qty: ",e.jsx("b",{children:_e.parsedQty.toLocaleString("en-BD")})," · Excluded negative rows: ",e.jsx("b",{children:_e.negativeRows})," (",_e.negativeQty.toLocaleString("en-BD"),") · ",e.jsx("b",{children:_e.exact?"ROW + QTY EXACT":"RED FAIL"}),". Phase 1 is allowed only when both physical positive-row count and positive quantity exactly equal the parser result. Signed negative stock is never converted into positive opening stock."]})]}),C&&(_e==null?void 0:_e.exact)&&e.jsxs("div",{className:"stock-diagnostic-banner stock-conflict-review",children:[e.jsx("strong",{children:"Safe Opening Delta Repair · v5.4.360"}),e.jsx("span",{children:"Uses the independently verified source as authority. Unexpected positive rows remain blocked unless Firebase ID, complete source identity and mirrored signed quantity exactly match an excluded negative source row."}),e.jsx("div",{style:{marginTop:10},children:e.jsx("button",{type:"button",className:"stock-preview-button",disabled:G,onClick:B,children:"Audit Safe Opening Delta"})}),qe&&e.jsxs("div",{style:{marginTop:10},children:[e.jsxs("span",{children:["Saved: ",e.jsx("b",{children:qe.savedCount})," products / ",e.jsx("b",{children:qe.savedTotal.toLocaleString("en-BD")})," units · Verified target: ",e.jsx("b",{children:qe.targetCount})," / ",e.jsx("b",{children:qe.targetTotal.toLocaleString("en-BD")})," · Corrections: ",e.jsx("b",{children:qe.rows.length})," · Positive-row delta: ",e.jsxs("b",{children:[qe.deltaQty>0?"+":"",qe.deltaQty.toLocaleString("en-BD")]})," · Unexpected existing rows: ",e.jsx("b",{children:qe.unexpected.length})]}),qe.rows.length>0&&e.jsx("div",{style:{overflowX:"auto",marginTop:8},children:e.jsxs("table",{className:"stock-preview-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Source Product"}),e.jsx("th",{children:"Saved Opening"}),e.jsx("th",{children:"Verified Opening"}),e.jsx("th",{children:"Delta"}),e.jsx("th",{children:"Current Live"}),e.jsx("th",{children:"Live After Repair"}),e.jsx("th",{children:"Type"})]})}),e.jsx("tbody",{children:qe.rows.slice(0,200).map(we=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:we.item.sourceName}),e.jsx("br",{}),e.jsxs("small",{children:[we.item.category," · ",we.item.model||"No model"]})]}),e.jsx("td",{children:we.savedOpeningQty}),e.jsx("td",{children:e.jsx("strong",{children:we.item.qty})}),e.jsx("td",{children:e.jsxs("strong",{children:[we.delta>0?"+":"",we.delta]})}),e.jsx("td",{children:we.liveQty}),e.jsx("td",{children:we.liveQty+we.delta}),e.jsx("td",{children:we.kind==="missing"?"Missing opening row":"Qty correction"})]},`delta-${we.item.id}`))})]})}),qe.unexpected.length>0&&e.jsxs("div",{style:{marginTop:8},children:[e.jsx("strong",{children:qe.unexpected.some(we=>we.forensicStatus==="unresolved")?"HARD BLOCK â unresolved identity evidence":"FORENSIC MATCH EXACT â eligible for confirmed reversal"}),e.jsx("div",{style:{overflowX:"auto",marginTop:8},children:e.jsxs("table",{className:"stock-preview-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Unexpected Existing Product"}),e.jsx("th",{children:"Firebase ID"}),e.jsx("th",{children:"Saved / Stock Opening"}),e.jsx("th",{children:"Current Live"}),e.jsx("th",{children:"Excluded Negative Source"}),e.jsx("th",{children:"Identity Evidence"}),e.jsx("th",{children:"Repair Effect"})]})}),e.jsx("tbody",{children:qe.unexpected.map(we=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:we.name}),e.jsx("br",{}),e.jsxs("small",{children:[we.category," · ",we.model||"No model"," · ",we.unit]})]}),e.jsx("td",{children:e.jsx("code",{children:we.id})}),e.jsxs("td",{children:[e.jsx("strong",{children:we.qty})," / ",we.stockOpeningQty]}),e.jsx("td",{children:we.liveQty}),e.jsx("td",{children:we.negativeMatch?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:we.negativeMatch.sourceName}),e.jsx("br",{}),e.jsxs("small",{children:["Signed Qty ",we.negativeMatch.qty]})]}):"No exact match"}),e.jsx("td",{children:we.forensicStatus==="exact_negative_mirror"?"EXACT: ID + name + category + model + unit + mirrored quantity":"UNRESOLVED: no exact excluded-negative identity"}),e.jsx("td",{children:we.forensicStatus==="exact_negative_mirror"?`Opening ${we.qty} â 0; live ${we.liveQty} â ${we.liveQty-we.qty}`:"No repair allowed"})]},`unexpected-${we.id}`))})]})}),e.jsx("div",{style:{marginTop:6},children:e.jsx("small",{children:"Product Master is never deleted. Only an exactly proven phantom Opening Item is removed; live Qty changes by the same opening delta so post-cutover movement remains intact."})})]}),(qe.rows.length>0||qe.unexpected.length>0)&&!qe.unexpected.some(we=>we.forensicStatus==="unresolved")&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"stock-live-confirm",style:{marginTop:10},children:[e.jsx("input",{type:"checkbox",checked:pe,onChange:we=>Se(we.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Confirm Safe Opening Delta Repair:"})," apply verified positive-source corrections and reverse only exact signed-negative mirror opening rows. Product Masters and post-cutover movement are preserved."]})]}),e.jsx("button",{type:"button",className:"stock-import-button",disabled:G||!pe,onClick:xe,children:"Apply Forensically Verified Safe Repair"})]})]})]}),C&&e.jsxs("div",{className:"stock-diagnostic-banner stock-conflict-review",children:[e.jsx("strong",{children:"Opening Source Completeness Audit · v5.4.346"}),e.jsx("span",{children:"The corrected parser carries the Date Wise Stock table header across PDF page boundaries. Use this on an already-posted opening batch to detect rows the old page-by-page parser could omit."}),e.jsx("div",{style:{marginTop:10},children:e.jsx("button",{type:"button",className:"stock-preview-button",disabled:G,onClick:jt,children:"Audit Existing Opening Batch"})}),ge&&e.jsxs("div",{style:{marginTop:10},children:[e.jsxs("span",{children:["Saved batch: ",e.jsx("b",{children:ge.savedCount}
3723)," products / ",e.jsx("b",{children:ge.savedTotal.toLocaleString("en-BD")})," units · Corrected source: ",e.jsx("b",{children:y.length})," products / ",e.jsx("b",{children:Te.qty.toLocaleString("en-BD")})," units · Missing: ",e.jsx("b",{children:ge.missing.length})," · Qty mismatches: ",e.jsx("b",{children:ge.qtyMismatches.length})]}),ge.missing.length>0&&e.jsx("div",{style:{overflowX:"auto",marginTop:8},children:e.jsxs("table",{className:"stock-preview-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Recovered source product"}),e.jsx("th",{children:"Opening Qty"}),e.jsx("th",{children:"Category / Model"})]})}),e.jsx("tbody",{children:ge.missing.slice(0,100).map(we=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:we.sourceName})}),e.jsx("td",{children:e.jsx("strong",{children:we.qty})}),e.jsxs("td",{children:[we.category," · ",we.model||"No model"]})]},`repair-${we.id}`))})]})}),ge.qtyMismatches.length>0&&e.jsx("small",{children:"Existing quantity mismatches are hard-blocked from automatic repair; they require separate reconciliation."}),ge.missing.length>0&&!ge.qtyMismatches.length&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"stock-live-confirm",style:{marginTop:10},children:[e.jsx("input",{type:"checkbox",checked:Pe,onChange:we=>Re(we.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Confirm completeness repair:"})," add only source rows missing from the existing opening-item ledger. Existing openingQty values are never overwritten. If a recovered product already has post-cutover movement, its opening quantity is added to the current live quantity so that movement is preserved."]})]}),e.jsx("button",{type:"button",className:"stock-import-button",disabled:G||!Pe,onClick:tt,children:"Repair Missing Opening Rows"})]})]})]}),C&&e.jsxs("div",{className:"stock-diagnostic-banner stock-conflict-review",children:[e.jsx("strong",{children:"Opening Identity Chain Audit · v5.4.347"}),e.jsx("span",{children:"Compares every corrected source row by generated ID and exact identity across Opening Items â Product Master â selected-branch Stock. This catches silent overwrite, missing product-master rows, stock-row loss, quantity drift, and duplicate identities even when batch totals still match."}),e.jsx("div",{style:{marginTop:10},children:e.jsx("button",{type:"button",className:"stock-preview-button",disabled:G,onClick:bt,children:"Audit Product-by-Product Identity"})}),Ee&&e.jsxs("div",{style:{marginTop:10},children:[e.jsxs("span",{children:["Exact identity chains: ",e.jsx("b",{children:Ee.healthy})," · Issue rows: ",e.jsx("b",{children:Ee.issues})]}),Ee.rows.length>0?e.jsx("div",{style:{overflowX:"auto",marginTop:8},children:e.jsxs("table",{className:"stock-preview-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Source Product"}),e.jsx("th",{children:"Generated ID"}),e.jsx("th",{children:"Opening Qty"}),e.jsx("th",{children:"Live Qty"}),e.jsx("th",{children:"Identity / Stock Issue"})]})}),e.jsx("tbody",{children:Ee.rows.slice(0,150).map(we=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:we.item.sourceName}),e.jsx("br",{}),e.jsxs("small",{children:[we.item.category," · ",we.item.model||"No model"]})]}),e.jsx("td",{children:e.jsx("code",{children:we.item.id})}),e.jsx("td",{children:we.item.qty}),e.jsx("td",{children:we.stockQty===null?"â":we.stockQty}),e.jsx("td",{children:we.issues.join(" · ")})]},`identity-${we.item.id}`))})]})}):e.jsx("small",{children:"All corrected source identities are exact across the three persisted inventory layers."})]})]}),C&&e.jsxs("div",{className:"stock-diagnostic-banner stock-conflict-review",children:[e.jsx("strong",{children:"Target Product Forensic Trace · v5.4.349"}),e.jsxs("span",{children:["Read-only trace for ",e.jsx("b",{children:"Toner Power Print 85A // 78A"}),". It does not trust batch totals; it shows the exact PDF parser row, generated Firebase ID, persisted Opening Item, Product Master, and selected-branch stock row."]}),e.jsx("div",{style:{marginTop:10},children:e.jsx("button",{type:"button",className:"stock-preview-button",disabled:G,onClick:tn,children:"Trace Exact 269 PCS Product"})}),We&&e.jsxs("div",{style:{marginTop:10},children:[e.jsx("strong",{children:We.verdict}),e.jsx("div",{style:{overflowX:"auto",marginTop:8},children:e.jsxs("table",{className:"stock-preview-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Layer"}),e.jsx("th",{children:"Firebase / Generated ID"}),e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Qty / Opening Qty"}),e.jsx("th",{children:"Details"})]})}),e.jsxs("tbody",{children:[We.sourceMatches.length?We.sourceMatches.map(we=>e.jsxs("tr",{children:[e.jsx("td",{children:"PDF parser source"}),e.jsx("td",{children:e.jsx("code",{children:we.id})}),e.jsx("td",{children:e.jsx("strong",{children:we.sourceName})}),e.jsx("td",{children:we.qty}),e.jsxs("td",{children:[we.category," · ",we.model||"No model"," · ",we.unit]})]},`trace-source-${we.id}`)):e.jsxs("tr",{children:[e.jsx("td",{children:"PDF parser source"}),e.jsx("td",{children:"â"}),e.jsx("td",{children:We.target}),e.jsx("td",{children:"NOT FOUND"}),e.jsx("td",{children:"Parser did not emit this exact positive-stock identity."})]}),We.openingItems.map(we=>e.jsxs("tr",{children:[e.jsx("td",{children:"Opening Item"}),e.jsx("td",{children:e.jsx("code",{children:we.id})}),e.jsx("td",{children:we.sourceName}),e.jsx("td",{children:we.qty}),e.jsxs("td",{children:[we.category," · ",we.model||"No model"," · ",we.unit]})]},`trace-opening-${we.id}`)),We.productMasters.map(we=>e.jsxs("tr",{children:[e.jsx("td",{children:"Product Master"}),e.jsx("td",{children:e.jsx("code",{children:we.id})}),e.jsx("td",{children:we.name}),e.jsx("td",{children:"â"}),e.jsxs("td",{children:[we.category," · ",we.model||"No model"," · ",we.unit]})]},`trace-product-${we.id}`)),We.branchStock.map(we=>e.jsxs("tr",{children:[e.jsx("td",{children:"Branch Stock"}),e.jsxs("td",{children:[e.jsx("code",{children:we.id}),e.jsx("br",{}),e.jsxs("small",{children:["productId: ",we.productId||"(blank)"]})]}),e.jsx("td",{children:"Selected branch stock"}),e.jsxs("td",{children:["Live ",we.qty," / Opening ",we.openingQty]}),e.jsxs("td",{children:[we.openingDate||"No opening date"," · ",we.source||"No source"]})]},`trace-stock-${we.id}`))]})]})})]})]}),L&&e.jsxs("div",{className:"stock-diagnostic-banner",children:[e.jsx("strong",{children:"Serial Evidence Diagnostic"}),e.jsxs("span",{children:["PDF extracted ",e.jsx("b",{children:nt.rawOccurrences})," row-level serial occurrence(s); after global cross-row de-duplication ",e.jsx("b",{children:nt.totalExtracted})," unique safe evidence token(s) remain. Within-row normalized duplicates excluded: ",e.jsx("b",{children:nt.duplicateWithinRow}),";
3723 cross-row duplicate/ambiguous occurrences excluded: ",e.jsx("b",{children:nt.duplicateCrossRow}),". ",e.jsx("b",{children:nt.matchedReferenceSerials})," belong to Current Stock rows matched to the opening snapshot; ",e.jsx("b",{children:nt.unmatchedReferenceSerials})," remain on unmatched/current-only rows. Safe opening-linked serial quantity is ",e.jsx("b",{children:nt.linked}),". Current-qty cap rejected ",e.jsx("b",{children:nt.currentQtyCapRejected}),"; opening-qty cap rejected ",e.jsx("b",{children:nt.openingQtyCapRejected}),". These are diagnostics only and do not write stock."]})]}),L&&e.jsxs("div",{className:"stock-diagnostic-banner stock-audited-serial-banner",children:[e.jsx("strong",{children:"Audited Serial Classification"}),e.jsxs("span",{children:["Unique serial evidence ",e.jsx("b",{children:xt.raw})," = Safe Opening Linked ",e.jsx("b",{children:xt.safeOpening})," + Opening Qty Zero / Current-only Excluded ",e.jsx("b",{children:xt.currentOnlyExcluded})," across ",e.jsx("b",{children:xt.currentOnlyRows})," row(s) + Ambiguous / Review Required ",e.jsx("b",{children:xt.ambiguousSerials})," across ",e.jsx("b",{children:xt.ambiguousRows})," row(s) + Current Qty Cap Excluded ",e.jsx("b",{children:xt.currentQtyCapExcluded})," + Opening Qty Cap Excluded ",e.jsx("b",{children:xt.openingQtyCapExcluded}),". Accounted ",e.jsx("b",{children:xt.accounted})," / ",e.jsx("b",{children:xt.raw})," · Unaccounted Evidence ",e.jsx("b",{children:xt.unaccounted})," · Over-accounted Evidence ",e.jsx("b",{children:xt.overaccounted}),". ",xt.balanced?"AUDIT EXACT â Phase 2 evidence gate passed.":"AUDIT NOT EXACT â Phase 2 is blocked."," Within-row normalized duplicates excluded before unique classification: ",e.jsx("b",{children:xt.withinRowDuplicateExcluded}),"; cross-row duplicate/ambiguous occurrences excluded: ",e.jsx("b",{children:xt.crossRowDuplicateExcluded}),"."]})]}),L&&te.length>0&&e.jsxs("div",{className:"stock-mapping-review",children:[e.jsxs("div",{className:"stock-mapping-review-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Serial Product Mapping Review"}),e.jsxs("span",{children:[te.length," unmatched Current Stock product row(s) still contain serial evidence. Select an Opening product only when the identity is clearly the same. A selection is a manual confirmation, not fuzzy auto-linking."]})]}),e.jsxs("div",{children:[e.jsx("b",{children:Object.keys(ue).length}),e.jsx("small",{children:"manual mapping(s)"})]})]}),e.jsxs("div",{className:"stock-mapping-review-table-wrap",children:[e.jsxs("table",{className:"stock-preview-table stock-mapping-review-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Current Stock Product"}),e.jsx("th",{children:"Serial Evidence"}),e.jsx("th",{children:"Top Opening Candidates"}),e.jsx("th",{children:"Manual Mapping"})]})}),e.jsx("tbody",{children:te.slice(0,150).map(we=>{var rt,St;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:we.ref.sourceName}),e.jsxs("small",{children:["Qty ",we.ref.qty," · Cost ",rj(we.ref.costPerUnit)]})]}),e.jsxs("td",{children:[e.jsx("strong",{children:((rt=we.ref.serials)==null?void 0:rt.length)||0}),e.jsxs("small",{children:[(we.ref.serials||[]).slice(0,4).join(", "),(((St=we.ref.serials)==null?void 0:St.length)||0)>4?" â¦":""]})]}),e.jsx("td",{children:we.candidates.map((Qt,gn)=>e.jsxs("small",{className:"stock-mapping-candidate",children:[e.jsxs("b",{children:[gn===0?"Best":"Alt"," ",Math.round(Qt.score*100),"%"]})," â ",Qt.item.sourceName," · ",Qt.item.model||"No model"]},`${we.key}-opening-${Qt.item.id}`))}),e.jsxs("td",{children:[e.jsxs("select",{value:we.assignedOpeningId,onChange:Qt=>Ge(we.key,Qt.target.value),children:[e.jsx("option",{value:"",children:"Leave unmatched"}),we.candidates.map(Qt=>e.jsxs("option",{value:Qt.item.id,children:[Math.round(Qt.score*100),"% · ",Qt.item.sourceName," · ",Qt.item.model||"No model"]},`${we.key}-choice-${Qt.item.id}`))]}),we.assignedOpeningId&&e.jsx("small",{className:"stock-manual-confirmed",children:"Manual confirmation active"})]})]},we.key)})})]}),te.length>150&&e.jsx("div",{className:"stock-table-note",children:"Showing first 150 unmatched serial-bearing Current Stock rows. Highe
3723st serial-count rows are shown first."})]}),Object.keys(ue).length>0&&e.jsxs("div",{className:"stock-mapping-review-foot",children:[e.jsx("span",{children:"Manual selections immediately recalculate the read-only reconciliation preview. They are persisted with the opening batch only when Phase 2 is applied."}),e.jsx("button",{type:"button",className:"stock-preview-button",onClick:pt,children:"Clear Manual Mappings"})]})]}),e.jsxs("div",{className:"stock-controls",children:[e.jsxs("select",{value:C,onChange:we=>{R(we.target.value),$([]),P(!1)},children:[e.jsx("option",{value:"",children:"Select VERIXO branch..."}),n.filter(we=>we.active!==!1).map(we=>e.jsx("option",{value:we.id,children:we.name},we.id))]}),e.jsxs("div",{className:"stock-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:I,onChange:we=>_(we.target.value),placeholder:"Search product, category or model"})]})]}),e.jsxs("div",{className:"stock-phase1-gate",children:[e.jsxs("label",{className:"stock-live-confirm",children:[e.jsx("input",{type:"checkbox",checked:fe,onChange:we=>q(we.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Phase 1 confirmation: make the detected report-date snapshot the live opening quantity for the selected branch."})," Existing non-zero live stock is blocked. Current Stock is not required and can never change this quantity."]})]}),e.jsxs("div",{className:"stock-gate-state",children:[e.jsx("strong",{children:"Phase 1 import gate"}),e.jsx("span",{children:C?fe?ce?"READY â Phase 1 import button is enabled above.":"Generate a valid preview first.":"Tick the live-stock confirmation.":"Select a VERIXO branch."})]})]}),!!V.length&&e.jsxs("div",{className:"stock-diagnostic-banner stock-conflict-review",children:[e.jsx("strong",{children:"Existing Live Stock Conflict Review"}),e.jsx("span",{children:V.every(we=>we.openingQty!==null)?`${V.length} existing non-zero record(s) overlap this opening snapshot. Nothing has been changed yet.`:"Safety block: some existing stock is not present in this opening snapshot."}),e.jsx("div",{style:{overflowX:"auto",marginTop:8},children:e.jsxs("table",{className:"stock-preview-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Existing Qty"}),e.jsx("th",{children:"Opening Qty"}),e.jsx("th",{children:"Existing Source"}),e.jsx("th",{children:"Resolution"})]})}),e.jsx("tbody",{children:V.slice(0,100).map(we=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:we.productName}),e.jsx("small",{children:we.productId})]}),e.jsx("td",{children:we.currentQty}),e.jsx("td",{children:we.openingQty===null?"Not in snapshot":we.openingQty}),e.jsx("td",{children:we.source}),e.jsx("td",{children:we.openingQty===null?e.jsx("span",{className:"stock-status pending",children:"HARD BLOCK"}):e.jsx("span",{className:"stock-status pending",children:"Needs explicit replace confirmation"})})]},we.productId))})]})}),V.every(we=>we.openingQty!==null)?e.jsxs("label",{className:"stock-live-confirm",children:[e.jsx("input",{type:"checkbox",checked:F,onChange:we=>P(we.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Conflict replacement confirmation:"})," replace only these overlapping existing quantities with the authoritative detected-date opening snapshot. This is not additive and prevents double stock."]})]}):e.jsx("small",{children:"Resolve/remove the out-of-snapshot live stock through its original transaction or controlled adjustment before migration. VERIXO will not auto-delete it."})]}),L?e.jsxs("div",{className:"stock-diagnostic-banner",children:[e.jsx("strong",{children:"Current PDF Candidate Diagnostic"}),e.jsx("span",{children:"Match Diagnostic Mode â every opening row shows the top Current PDF candidates, confidence, Qty/Cost/Serial evidence and acceptance/rejection reason. This preview remains read-only. Phase 2 is reference-only and cannot change the authoritative opening quantity."})]}):e.jsxs("div",{className:"stock-diagnostic-banner",children:[e.jsx("strong",{children:"Opening Quantity Preview"}),e.jsx("span",{children:"Current Stock reference has not been previewed yet. That is O
3723K for Phase 1; all Current Qty/Cost/Serial columns remain informational and blank until Phase 2 preview."})]}),e.jsxs("div",{className:"stock-preview-table-wrap",children:[e.jsxs("table",{className:"stock-preview-table stock-preview-table-diagnostic",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Product / Item"}),e.jsx("th",{children:"Opening Qty (Report Date)"}),e.jsx("th",{children:"Current Qty"}),e.jsx("th",{children:"Serials Found / Matched"}),e.jsx("th",{children:"Serial Pending / Missing Qty"}),e.jsx("th",{children:"Current / Ref Cost"}),e.jsx("th",{children:"Qty Difference"}),e.jsx("th",{children:"Match Status / Warning"})]})}),e.jsx("tbody",{children:De.slice(0,500).map(we=>{var Qt;const rt=we.currentRef,St=we.matchStatus==="matched"?"Matched":we.matchStatus==="qty_mismatch"?"Quantity changed since opening date":we.matchStatus==="serial_pending"?"Serial pending":we.matchStatus==="ambiguous"?"Ambiguous â not auto-matched (collision safe)":"Not found in later Current Stock";return e.jsxs(x.Fragment,{children:[e.jsxs("tr",{className:we.matchStatus!=="matched"?"stock-row-warning":"",children:[e.jsxs("td",{children:[e.jsx("strong",{children:we.sourceName}),e.jsxs("small",{children:[we.category," · ",we.model||"No model"," · ",we.unit]})]}),e.jsxs("td",{children:[e.jsx("strong",{children:we.qty}),e.jsx("small",{children:"Authoritative"})]}),e.jsxs("td",{children:[rt?rt.qty:"â",e.jsx("small",{children:"Reference only"})]}),e.jsxs("td",{children:[((Qt=rt==null?void 0:rt.serials)==null?void 0:Qt.length)||0," / ",e.jsx("strong",{children:we.serialMatched})]}),e.jsxs("td",{children:[e.jsx("strong",{children:we.serialPending}),e.jsx("small",{children:we.serialPending?"No fake serials will be created":"Complete"})]}),e.jsx("td",{children:rt?rj(rt.costPerUnit):"â"}),e.jsx("td",{children:we.quantityDifference===null?"â":we.quantityDifference>0?`+${we.quantityDifference}`:we.quantityDifference}),e.jsxs("td",{children:[e.jsx("span",{className:`stock-status ${we.matchStatus==="matched"?"matched":"pending"}`,children:St}),e.jsx("small",{children:we.matchNote})]})]}),L&&e.jsx("tr",{className:"stock-diagnostic-row",children:e.jsx("td",{colSpan:8,children:e.jsxs("div",{className:"stock-diagnostic-inline",children:[e.jsx("strong",{children:"Current PDF candidates"}),e.jsx("div",{children:we.diagnosticCandidates.length?we.diagnosticCandidates.map((gn,An)=>{var Sn;return e.jsxs("div",{className:`stock-diagnostic-candidate ${An===0?"best":""}`,children:[e.jsxs("strong",{children:[An===0?"Best":"Alt"," ",Math.round(gn.score*100),"% â ",gn.ref.sourceName]}),e.jsxs("small",{children:["Qty ",gn.ref.qty," · ",rj(gn.ref.costPerUnit)," · ",((Sn=gn.ref.serials)==null?void 0:Sn.length)||0," serial(s)"]}),e.jsx("small",{children:gn.reason})]},`${we.id}-candidate-${An}`)}):e.jsx("small",{children:"No Current PDF candidate extracted."})})]})})})]},we.id)})})]}),De.length>500&&e.jsxs("div",{className:"stock-table-note",children:["Showing first 500 of ",De.length," matched search rows."]})]}),L&&e.jsxs("label",{className:"stock-live-confirm stock-reference-confirm",children:[e.jsx("input",{type:"checkbox",checked:ne,onChange:we=>ae(we.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Phase 2 confirmation: apply Current Stock only as cost/serial/reference evidence."})," This update does not write qty, openingQty or openingDate, never creates fake serials, excludes confirmed opening-zero/current-only evidence, and leaves ambiguous evidence unlinked."]})]}),e.jsx("div",{className:"stock-import-footer",children:e.jsxs("div",{children:[e.jsx(Tu,{size:20}),e.jsx("span",{children:"Safe cutover: Phase 1 freezes the authoritative detected-date quantity. Phase 2 can be run immediately or later and only enriches Current Qty/Cost/Serial evidence. Historical Purchase/Sales import must reconcile pre-cutover activity without re-applying opening quantity."})]})})]})]})}const Rh=t=>String(t||"").replace(/\s+/g," ").trim();function C8(t){let n=Rh(t);for(let a=0;a<3;a+=1){const s=n;
3723if(n=n.replace(/\b([A-Z])\s+([a-z])\s+([a-z]{2,})\b/g,"$1$2$3").replace(/\b([B-HJ-Z])\s+([a-z]+)\b/g,"$1$2").replace(/\b([A-Z][A-Za-z]{1,})\s+([a-z]{1,3})\b/g,"$1$2").replace(/\b(\d+[A-Z]+)\s+([A-Z])\b/g,"$1$2"),n===s)break}return Rh(n)}function A8(t){const n=[];for(const a of t){const s=Rh(a.text);n.some(c=>Rh(c.text)===s&&Math.abs(c.x-a.x)<=.75&&Math.abs(Number(c.width||0)-Number(a.width||0))<=.75)||n.push(a)}return n}function I8(t){const n=Number(t.width);return Number.isFinite(n)&&n>=0?t.x+n:null}function Vg(t){const n=A8(t).filter(i=>Rh(i.text)).sort((i,c)=>i.x-c.x);if(!n.length)return"";let a=Rh(n[0].text),s=n[0];for(let i=1;i<n.length;i+=1){const c=n[i],l=Rh(c.text),m=I8(s),d=Math.max(1,Number(s.fontSize)||Number(c.fontSize)||10),u=/\s$/.test(s.text)||/^\s/.test(c.text),f=m===null?null:c.x-m,g=Math.max(1,Math.min(3.2,d*.22)),p=u||f===null||f>g?" ":"";a+=`${p}${l}`,s=c}return C8(a)}const bg=t=>String(t||"").replace(/\s+/g," ").trim();function c2(t){const n=bg(t).replace(/(?:^|[\s,;]+)(?:S\/?N|S\.N\.|SERIAL(?:\s+(?:NO|NUMBER))?)(?=\s|[:#]|$)\s*[:#]?\s*/gi," ").trim();if(!/^[A-Za-z0-9_-]+(?:[\s,;]+[A-Za-z0-9_-]+)*$/.test(n))return[];const a=n.split(/[\s,;]+/).filter(Boolean);return a.length?a.some(s=>/^\d+(?:\.\d+)?(?:mm|cm|m|gb|tb|mhz|ghz|w|v|a|hz|rpm)$/i.test(s))?[]:a.some(s=>s.length<4||s.length>32||!/\d/.test(s)||!/^\d+$/.test(s)&&!/[A-Za-z]/.test(s))?[]:[...new Set(a
3723)]:[]}function _8(t){const n=c2(t);if(n.length)return n;const a=bg(t).replace(/(?:^|[\s,;]+)(?:S\/?N|S\.N\.|SERIAL(?:\s+(?:NO|NUMBER))?)(?=\s|[:#]|$)\s*[:#]?\s*/gi," ").trim();if(!a||a.length>80)return[];const s=a.split(/\s+/).filter(Boolean);if(s.length<2||s.length>5)return[];const i=s[0];return/^\d{4,32}$/.test(i)?/^\d+(?:\.\d+)?(?:mm|cm|m|gb|tb|mhz|ghz|w|v|a|hz|rpm)$/i.test(i)?[]:s.slice(1).every(c=>/^[A-Za-z][A-Za-z._-]{1,19}$/.test(c))?[a]:[]:[]}function pE(t){const n=_8(t);if(n.length)return n;const a=bg(t);if(!a||a.length>160)return[];const s=a.split(/[\s,;]+/).filter(Boolean);return s.length<2||s.length>20?[]:s.every(i=>/^[A-Z0-9_-]{4,32}$/.test(i))?s.some(i=>/\d/.test(i))?[...new Set(s)]:[]:[]}function k8(t){const n=[];for(let a=0;a<t.length;a++){const s=bg(t[a]);if(s){if(s.endsWith("-")&&a+1<t.length){const i=bg(t[a+1]);if(/^[A-Za-z0-9_-]{4,32}$/.test(i)&&/\d/.test(i)){n.push(`${s}${i}`),a++;continue}}n.push(s)}}return[...new Set(n)]}const D8="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.min.mjs",E8="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.mjs",cj=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,_d=t=>Number(String(t||"").replace(/[à§³,\s]/g,""))||0,Qr=t=>String(t||"").replace(/\s+/g," ").trim(),Iv=t=>Qr(t).toLowerCase().replace(/[^a-z0-9]+/g," ").trim(),II=t=>Qr(t).replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120),P8={jan:"01",feb:"02",mar:"03",apr:"04",may:"05",jun:"06",jul:"07",aug:"08",sep:"09",oct:"10",nov:"11",dec:"12"};function R8(t){let n=t.match(/(\d{1,2})[-\/]([A-Za-z]{3})[-\/](\d{4})/);return n?`${n[3]}-${P8[n[2].toLowerCase()]||"01"}-${n[1].padStart(2,"0")}`:(n=t.match(/(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})/),n?`${n[3]}-${n[2].padStart(2,"0")}-${n[1].padStart(2,"0")}`:(n=t.match(/(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})/),n?`${n[1]}-${n[2].padStart(2,"0")}-${n[3].padStart(2,"0")}`:""))}function T8(t){const n=t.filter(s=>Qr(s.str||"")).map(s=>{var i,c,l,m;return{text:String(s.str||""),x:Number(((i=s.transform)==null?void 0:i[4])||0),y:Number(((c=s.transform)==null?void 0:c[5])||0),width:Number(s.width),fontSize:Math.abs(Number(((l=s.transform)==null?void 0:l[3])||0))||Math.abs(Number(((m=s.transform)==null?void 0:m[0])||0))||10}}),a=[];for(const s of n){let i=a.find(c=>Math.abs(c.y-s.y)<=3);i||(i={y:s.y,cells:[]},a.push(i)),i.cells.push({x:s.x,text:s.text,width:s.width,fontSize:s.fontSize})}return a.sort((s,i)=>i.y-s.y).map(s=>{const i=s.cells.sort((c,l)=>c.x-l.x);return{y:s.y,cells:i,text:Vg(i)}}).filter(s=>s.text)}function _v(t,n,a){return Vg(t.cells.filter(s=>s.x>=n&&s.x<a))}function M8(t){return t.find(n=>/(product|item|description|particular)/i.test(n.text)&&/qty|quantity/i.test(n.text)&&/(rate|cost|price)/i.test(n.text)&&/amount|total/i.test(n.text))}function $8(t){const n=M8(t);if(!n)return[];const a=_=>{var J;return(J=n.cells.find(T=>_.test(T.text)))==null?void 0:J.x},s=a(/product|item|description|particular/i),i=a(/qty|quantity/i),c=a(/rate|cost|price/i),l=a(/amount|total/i);if([s,i,c,l].some(_=>_===void 0))return[];const m=s,d=i,u=c,f=l,g=Math.max(0,m-25),p=(m+d)/2,y=(d+u)/2,b=(u+f)/2,N=f+140,w=[];let C=null,R=0,I=[];for(const _ of t.slice(t.indexOf(n)+1)){if(/^(grand\s+)?total\b|net\s+total|in\s+word/i.test(_.text))break;const J=pE(_.text);if(J.length){C?C.serials.push(...J):I.push(...J);continue}const T=_v(_,g,p),G=_d(_v(_,p,y)),z=_d(_v(_,y,b)),H=_d(_v(_,b,N));if(T&&G>0&&(z>0||H>0)){C={id:`line_${++R}`,product:T,qty:G,rate:z||H/G,amount:H||G*z,serials:[...I]},I=[],w.push(C);continue}C&&T&&!G&&!z&&!H&&!/page\s+\d+/i.test(T)&&(C.product=Qr(`${C.product} ${T}`))}return w}function O8(t){const n=[];let a=0,s=null,i=[];const c=/^(?:total\s+qty|grand\s+total|net\s+total|in\s+word|discount|remarks|supplier\s+signature|print\s+date)/i,l=/^\s*(\d+)\s+(.+?)\s+(\d+(?:\.\d+)?)\s+(PCS|PC|NOS|NO|UNIT|SET|BOX|PKT|PAIR|KG|GM|LTR|MTR)\s+(.*?)\s*([\d,]+(?:\.\d{1,2})?)\s+([\d,]+(?:\.\d{1,2})?)\s+([\d,]+(?:\.\d{1,2})?)\s*$/i;for(const m of t){const d=Qr(m);if(!d)continue;if(c.test(d)){if(n.length)break;continue}if(/^#\s+Product\s+Name\s+Quantity\s+Unit/i.test(d))continue;const u=d.match(l);if(u){const f=Qr(u[2]),g=_d(u[3]),p=_d(u[6]),y=_d(u[8]);f&&g>0&&(s={id:`line_${++a}`,product:f,qty:g,rate:p||y/g,amount:y||g*p,serials:[...i]},i=[],n.push(s));continue}{const f=pE(d);if(f.length){s?s.serials.push(...f):i.push(...f);continue}}if(s&&/serial\s*(?:no|number)/i.test(d)){const f=d.replace(/^.*?serial\s*(?:no\.?\(s\)?|number\(s\)?)\s*:?/i,"").split(/[\s,;]+/).map(Qr).filter(g=>g.length>=4);s.serials.push(...f);continue}s&&!/^(?:supplier\s+info|code\s*:|cont\.?\s*:|address\s*:|payment\s+mode|entry\s+by)/i.test(d)&&(s.product=Qr(`${s.product} ${d.replace(/^\d+\s+/,"")}`))}return n}function L8(t){const n=[];let a=0;for(const s of t){if(/^(grand\s+)?total\b|net\s+total/i.test(s))continue;const i=s.match(/^(.+?)\s+(\d+(?:\.\d+)?)\s+([\d,]+(?:\.\d{1,2})?)\s+([\d,]+(?:\.\d{1,2})?)$/);if(!i)continue;const c=Qr(i[1]),l=_d(i[2]),m=_d(i[3]),d=_d(i[4]);c.length>=3&&l>0&&(m>0||d>0)&&n.push({id:`line_${++a}`,product:c,qty:l,rate:m||d/l,amount:d||l*m,serials:[]})}return n}function _I(t){const n=Qr(t).replace(/\s+/g,"").replace(/[^A-Za-z0-9_\-/]/g,"").replace(/-{2,}/g,"-"),a=n.match(/GR-[A-Z0-9]+-\d{4}-\d{2}-\d{4,}/i);if(a)return a[0].slice(0,120);const s=n.match(/[A-Z]{2,}(?:-[A-Z0-9]+){2,}/i);return((s==null?void 0:s[0])||n).slice(0,120)}function kI(t){let n=Qr(t).replace(/\s+/g,"").replace(/[^A-Za-z0-9_\-/]/g,"").replace(/-{2,}/g,"-");n=n.replace(/^(?:Supplier|Vendor)?(?:Invoice|Bill|Ref(?:erence)?)(?:No)?/i,"");const a=n.match(/(?:INV|BILL|REF|CH|DC|PO)-[A-Z0-9]+(?:-[A-Z0-9]+)+/i)||n.match(/[A-Z0-9]+(?:-[A-Z0-9]+){2,}/i);return((a==null?void 0:a[0])||n).slice(0,120)}
3723function B8(t){const n=t.map(Qr).filter(Boolean),a=n.join(` 3724`),s=[...a.matchAll(/(?:^|\n)\s*(?:Date|Purchase\s*Date|Invoice\s*Date|Bill\s*Date)\s*:?\s*([^\n]{6,32})/ig)].map(m=>R8(m[1])).filter(Boolean);let i="";for(const m of n){const d=m.match(/Purchas\s*e?\s+No\s*\.?\s*:\s*(.+)$/i)||m.match(/(?:Purchase\s+Invoice|Invoice|Bill|Voucher)\s*(?:No\.?|#)?\s*:?\s*(.+)$/i);if(d){const u=_I(d[1]);if(u.length>=6){i=u;break}}}if(!i){const m=a.match(/\bGR\s*-\s*[A-Z0-9]+(?:\s*-\s*[A-Z0-9]+){2,}/i);m&&(i=_I(m[0]))}let c="";for(const m of n){const d=m.match(/R\s*ef\s*\.\s*No\s*\.?:?\s*(.+)$/i)||m.match(/(?:Supplier|Vendor)\s*(?:Invoice|Bill|Ref(?:erence)?)\s*(?:No\.?|#)?\s*:?\s*(.+)$/i);if(d){const u=kI(d[1]);if(u.length>=1){c=u;break}}}if(!c){const m=a.match(/\bINV(?:\s*-\s*[A-Z0-9]+){2,}/i);m&&(c=kI(m[0]))}let l="";for(const m of n){const d=m.match(/\bCode\s*:\s*[A-Za-z0-9_-]+.*?\bNam\s*e\s*:\s*(.+)$/i)||m.match(/\b(?:Supplier|Vendor|Party)\s+Nam\s*e\s*:?\s*(.+)$/i);if(d&&(l=Qr(d[1]).slice(0,160),l))break}if(!l){const m=a.match(/\bCode\s*:\s*[A-Za-z0-9_-]+[^\n]*?\bNam\s*e\s*:\s*([^\n]+)/i);l=Qr((m==null?void 0:m[1])||"").slice(0,160)}return{purchaseDate:s[0]||"",sourceInvoiceNo:i,supplierInvoiceRefNo:c,supplier:l}}const F8=new Set(["PCS","PC","PIECE","PIECES","UNIT","UNITS","NOS","NO","MODEL","OTHER","CURRENT","STOCK","TOTAL","WITH","THE","AND"]);function l2(t){return Qr(t).toUpperCase().replace(/[^A-Z0-9]+/g," ").replace(/\s+/g," ").trim()}function DI(t){return l2(t).split(" ").filter(n=>n.length>1&&!F8.has(n))}function Kf(t){return l2(t).replace(/\b(\d+)\s*GB\b/g,"$1GB").replace(/\b(\d+)\s*TB\b/g,(n,a)=>`${Number(a)*1e3}GB`).replace(/\b(\d+)(?:ST|ND|RD|TH)\s*(?:GENERATION|GEN)\b/g,"$1GEN").replace(/\bGENERATION\b/g,"GEN").replace(/\bUSB\s*C\b/g,"USBC").replace(/\bWI\s*FI\b/g,"WIFI").replace(/\s+/g," ").trim()}function EI(t){return[...new Set(Kf(t).split(" ").map(n=>n.replace(/[^A-Z0-9]/g,"")).filter(n=>n.length>=4&&/[A-Z]/.test(n)&&/\d/.test(n)&&!/^(?:DDR[345]|USB[23]|CORE[3579])$/.test(n)))]}function PI(t){var s;const n=l2(t);return((s=[["NOTEBOOK",/\b(?:NOTEBOOK|LAPTOP)\b/],["MAINBOARD",/\b(?:MAINBOARD|MOTHERBOARD)\b/],["PROCESSOR",/\b(?:PROCESSOR|CPU)\b/],["RAM",/\b(?:RAM|MEMORY)\b/],["SSD",/\b(?:SSD|NVME|SOLID STATE)\b/],["HDD",/\b(?:HDD|HARD DISK|HARD DRIVE)\b/],["PRINTER",/\b(?:PRINTER|PIXMA|DESKJET|LASERJET)\b/],["ROUTER",/\b(?:ROUTER|ACCESS POINT)\b/],["SWITCH",/\bSWITCH\b/],["POWER_SUPPLY",/\b(?:POWER SUPPLY|PSU)\b/],["GRAPHICS",/\b(?:GRAPHICS CARD|GPU|VGA CARD)\b/],["MONITOR",/\bMONITOR\b/],["KEYBOARD",/\bKEYBOARD\b/],["MOUSE",/\bMOUSE\b/],["BATTERY",/\bBATTERY\b/]].find(([,i])=>i.test(n)))==null?void 0:s[0])||"GENERAL"}function U8(t,n){const a=new Set(DI(t)),s=new Set(DI(n));if(!a.size||!s.size)return 0;let i=0;for(const c of a)s.has(c)&&i++;return i/Math.max(a.size,s.size)}function z8(t){let n=2166136261;for(let a=0;a<t.length;a++)n^=t.charCodeAt(a),n=Math.imul(n,16777619);return(n>>>0).toString(36)}function q8(t){return`histpur_${z8(Kf(t))}`}function RI(t,n){const a=Kf(t.product),s=PI(t.product),i=EI(t.product),c=Object.entries(n).map(([u,f])=>{const g=`${f.name||""} ${f.category||""} ${f.model||""}`,p=Kf(g),y=PI(g),b=new Set(EI(g)),N=i.filter(C=>b.has(C));let w=U8(a,p)*.72;return a===Kf(f.name||"")&&(w=1),N.some(C=>C.length>=5)&&(w=Math.max(w,.94)),(p.includes(a)||a.includes(p))&&Math.min(p.length,a.length)>=8&&(w=Math.max(w,.96)),s!=="GENERAL"&&y!=="GENERAL"&&s!==y&&(w=Math.min(w,.35)),{id:u,p:f,score:w,shared:N}}).sort((u,f)=>f.score-u.score),l=c[0],m=c[1];if(l&&l.score>=.9&&(!m||l.score-m.score>=.05||l.score>=.98))return{productId:l.id,product:l.p,isNew:!1,score:l.score};const d=q8(t.product);return{productId:d,product:{id:d,name:t.product,category:s==="GENERAL"?"Historical Purchase":s,model:i.slice(0,3).join(" "),unit:"PCS",active:!0},isNew:!n[d],score:0}}function TI(t,n){return Object.values(t||{}).filter(a=>a&&a.branchId===n&&a.openingDate).sort((a,s)=>String(s.openingDate).localeCompare(String(a.openingDate))||Number(s.createdAt||0)-Number(a.createdAt||0))[0]}function V8({profile:t,branches:n}){const[a,s]=x.useState(t.branchId||""),[i,c]=x.useState(null),[l,m]=x.useState(null),[d,u]=x.useState(!1),[f,g]=x.use
3724State(""),[p,y]=x.useState(!1),[b,N]=x.useState({openingDate:"",batchId:"",stockImpact:!1,ready:!1}),[w,C]=x.useState(null),[R,I]=x.useState(null),_=n.find(L=>L.id===a),J=(l==null?void 0:l.items.length)||0,T=!!l&&!!a&&p&&!d&&!w&&J>0&&!!l.purchaseDate&&!!l.sourceInvoiceNo&&!!l.supplier&&b.ready,G=x.useMemo(()=>l?`${l.items.length} line(s) · ${l.totalQty.toLocaleString("en-BD")} qty · ${cj(l.totalAmount)}`:"No preview yet",[l]);async function z(L){var M;const D=((M=L.target.files)==null?void 0:M[0])||null;c(D),m(null),C(null),I(null),g(D?`${D.name} selected. Generate preview before import.`:""),y(!1),N({openingDate:"",batchId:"",stockImpact:!1,ready:!1})}async function H(){if(i){u(!0),g("Reading Purchase PDFâ¦");try{const L=await import(D8);L.GlobalWorkerOptions.workerSrc=E8;const D=await L.getDocument({data:new Uint8Array(await i.arrayBuffer())}).promise,M=[],Z=[];for(let $=1;$<=D.numPages;$++){const P=await(await D.getPage($)).getTextContent(),ue=T8(P.items);M.push(...ue),Z.push(...ue.map(me=>me.text)),await new Promise(me=>
3724setTimeout(me,0))}const fe=B8(Z);let q=O8(Z);q.length||(q=$8(M)),q.length||(q=L8(Z));const ne=new Map;for(const $ of q){const F=`${Qr($.product).toLowerCase()}|${$.qty}|${$.rate}|${$.amount}`;ne.has(F)||ne.set(F,{...$,serials:k8($.serials)})}q=[...ne.values()];const ae={sourceFile:i.name,purchaseDate:fe.purchaseDate,sourceInvoiceNo:fe.sourceInvoiceNo,supplierInvoiceRefNo:fe.supplierInvoiceRefNo,supplier:fe.supplier,items:q,totalQty:q.reduce(($,F)=>$+F.qty,0),totalAmount:q.reduce(($,F)=>$+F.amount,0),rawLines:Z};m(ae);let Y={openingDate:"",batchId:"",stockImpact:!1,ready:!1};if(a&&fe.purchaseDate){const $=await mn(re(ie,`inventoryOpeningBatches/${t.companyId}`)),F=TI($.val()||{},a);F&&(Y={openingDate:String(F.openingDate),batchId:String(F.id||""),stockImpact:fe.purchaseDate>String(F.openingDate),ready:!0})}N(Y);let je=null,V=null;if(a&&fe.sourceInvoiceNo){const $=await mn(re(ie,`historicalPurchaseImports/${t.companyId}`)),F=Qr(fe.supplierInvoiceRefNo).toLowerCase(),P=Iv(fe.supplier),ue=Qr(fe.sourceInvoiceNo).toLowerCase();for(const[me,ge]of Object.entries($.val()||{})){const de={id:me,purchaseDate:ge==null?void 0:ge.purchaseDate,sourceInvoiceNo:ge==null?void 0:ge.sourceInvoiceNo,supplierInvoiceRefNo:ge==null?void 0:ge.supplierInvoiceRefNo,supplier:ge==null?void 0:ge.supplier,branchName:ge==null?void 0:ge.branchName,status:ge==null?void 0:ge.status,stockImpact:ge==null?void 0:ge.stockImpact,createdAt:ge==null?void 0:ge.createdAt,createdByName:ge==null?void 0:ge.createdByName};if(Qr((ge==null?void 0:ge.sourceInvoiceNo)||"").toLowerCase()===ue){je=de;break}!V&&F&&P&&Qr((ge==null?void 0:ge.supplierInvoiceRefNo)||"").toLowerCase()===F&&Iv((ge==null?void 0:ge.supplier)||"")===P&&(V=de)}}C(je),I(je?null:V),je?g(`Duplicate blocked: Source Purchase ${fe.sourceInvoiceNo} is already imported. Existing record details are shown below.`):V?g(`SAFE PREVIEW READY: Supplier Ref ${fe.supplierInvoiceRefNo} also appears on another Source Purchase (${V.sourceInvoiceNo||"unknown"}). This split/related purchase is allowed because the Source Purchase No. is different.`):q.length?fe.purchaseDate?fe.sourceInvoiceNo?fe.supplier?a?Y.ready?g(`SAFE PREVIEW READY: ${q.length} purchase line(s). ${fe.purchaseDate>Y.openingDate?`POST-CUTOVER (${Y.openingDate}) â stock impact is YES.`:`PRE/ON-CUTOVER (${Y.openingDate}) â stock impact is NO.`}`):g("Import blocked: no Opening Stock cutover batch was found for this branch. Post/pre-cutover stock impact cannot be classified safely."):g("SAFE PREVIEW READY. Select a branch to resolve the opening cutover and stock-impact mode."):g("Preview found items, but Supplier could not be detected. Import stays blocked for supplier-history safety."):g("Preview found items, but Purchase No could not be detected. Import stays blocked for duplicate-safety."):g("Preview found items, but Purchase Date could not be detected. Import stays blocked."):g("Preview blocked: no reliable Purchase item table was detected. This PDF format needs a parser profile before import.")}catch(L){g(`Purchase PDF preview failed: ${(L==null?void 0:L.message)||String(L)}`)}finally{u(!1)}}}async function K(){if(!(!T||!l)){u(!0);try{const L=await mn(re(ie,`inventoryOpeningBatches/${t.companyId}`)),D=TI(L.val()||{},a);if(!D)throw new Error("No Opening Stock cutover batch found for the selected branch.");const M=String(D.openingDate||""),Z=l.purchaseDate>M,fe=l.sourceInvoiceNo||II(l.sourceFile.replace(/\.pdf$/i,"")),q=II(`${l.purchaseDate}_${a}_${fe}`),ae=(await mn(re(ie,`historicalPurchaseImports/${t.companyId}/${q}`))).val(),Y=!!(ae&&Z&&ae.stockImpact!==!0);if(ae&&!Y){g("Duplicate blocked: this Purchase document was already imported for the selected branch."),u(!1);return}{const Be=await mn(re(ie,`historicalPurchaseImports/${t.companyId}`)),We=Qr(l.sourceInvoiceNo).toLowerCase();if(Object.entries(Be.val()||{}).some(([_e,ee])=>_e!==q&&Qr((ee==null?void 0:ee.sourceInvoiceNo)||"").toLowerCase()===We)){g("Duplicate blocked: this Source Purchase No. was already imported. Same Supplier Ref on a different Source Purchase is allowed, but the same Source Purchase is never applied twice."),u(!1);return}}const[je,V]=await Promise.all([mn(re(ie,`supplierPromotions/${t.companyId}`)),mn(re(ie,`inventoryProducts/${t.companyId}`))]),$=Iv(l.supplier),F=Object.entries(je.val()||{}).filter(([,Be])=>
3724Be.status==="active"&&(Be.supplierKey||Iv(Be.supplierName||""))===$&&l.purchaseDate>=String(Be.startDate||"")&&l.purchaseDate<=String(Be.endDate||"")),P=V.val()||{},ue={};for(const Be of l.items){const We=RI(Be,P),it=Number(Be.qty||0);ue[We.productId]=Number(ue[We.productId]||0)+it;const _e=`name:${Qr(Be.product).toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}`;_e!=="name:"&&(ue[_e]=Number(ue[_e]||0)+it)}const me=Date.now(),ge={};let de=0,Pe=0;if(Z){const[Be,We]=await Promise.all([mn(re(ie,`inventoryProducts/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}/${a}`))]),it=Be.val()||{},_e=We.val()||{},ee=new Map;for(const qe of l.items){const se=RI(qe,it);se.isNew?(Pe++,it[se.productId]=se.product):de++;const pe=ee.get(se.productId)||{match:se,qty:0,serials:[],lastRate:0,lines:[]};pe.qty+=qe.qty,pe.serials.push(...qe.serials),pe.lastRate=qe.rate||pe.lastRate,pe.lines.push(qe),ee.set(se.productId,pe)}for(const[qe,se]of ee){const pe=_e[qe]||{},Se=(pe.postCutoverPurchaseSerials||[]).map(String),Me=[...new Set([...Se,...se.serials.map(String)])],wt=Number(pe.postCutoverPurchaseQty||0)+se.qty,ct=Number(pe.openingQty||0),Ce=Number(pe.qty||0);(se.match.isNew||!Be.child(qe).exists())&&(ge[`inventoryProducts/${t.companyId}/${qe}`]={...se.match.product,id:qe,sourceSystem:"historical_purchase_migration",active:!0,updatedAt:me}),ge[`inventoryStock/${t.companyId}/${a}/${qe}`]={...pe,productId:qe,branchId:a,qty:Ce+se.qty,openingQty:ct,openingDate:pe.openingDate||M,source:pe.source||"post_cutover_historical_purchase",postCutoverPurchaseQty:wt,postCutoverPurchaseSerials:Me,postCutoverPurchaseUnserializedQty:Math.max(0,wt-Me.length),lastPurchaseCostPerUnit:se.lastRate||null,lastHistoricalPurchaseAt:me,lastHistoricalPurchaseNo:l.sourceInvoiceNo,updatedAt:me}}}const Re={id:q,companyId:t.companyId,branchId:a,branchName:(_==null?void 0:_.name)||"",purchaseDate:l.purchaseDate,sourceInvoiceNo:l.sourceInvoiceNo||"",supplierInvoiceRefNo:l.supplierInvoiceRefNo||"",supplier:l.supplier||"",sourceFile:l.sourceFile,sourceSystem:"takeplus_oner_legacy",migrationMode:Z?"post_cutover_stock_impacting":"pre_cutover_history_only",stockImpact:Z,openingStockProtected:!0,openingDate:M,cutoverBatchId:String(D.id||""),itemCount:l.items.length,totalQty:l.totalQty,totalAmount:l.totalAmount,serialEvidenceCount:l.items.reduce((Be,We)=>Be+We.serials.length,0),items:l.items.map(({id:Be,...We})=>We),matchedProducts:de,newProducts:Pe,upgradedFromHistoryOnly:Y,createdAt:(ae==null?void 0:ae.createdAt)||me,updatedAt:me,createdByUid:(ae==null?void 0:ae.createdByUid)||t.uid,createdByName:(ae==null?void 0:ae.createdByName)||t.name};if(!ae)for(const[Be,We]of F)ge[`supplierPromotionApplications/${t.companyId}/${Be}/${q}`]={promotionId:Be,purchaseImportKey:q,purchaseDate:l.purchaseDate,supplierName:l.supplier,supplierKey:$,sourceInvoiceNo:l.sourceInvoiceNo,contributionAmount:l.totalAmount,contributionQty:l.totalQty,productContributions:ue,targetType:We.targetType||"amount",appliedAt:me,appliedByUid:t.uid,appliedByName:t.name||t.email||"User",sourceType:"historical_purchase"};ge[`historicalPurchaseImports/${t.companyId}/${q}`]={...Re,status:Y?"stock_impact_upgraded":"imported"},ge[`historicalPurchases/${t.companyId}/${q}`]=Re,ge[`migrationHistory/${t.companyId}/purchase_${q}`]={id:`purchase_${q}`,type:"historical_purchase",batchId:q,branchId:a,purchaseDate:l.purchaseDate,sourceInvoiceNo:l.sourceInvoiceNo||"",supplierInvoiceRefNo:l.supplierInvoiceRefNo||"",supplier:l.supplier||"",sourceFile:l.sourceFile,status:Y?"stock_impact_upgraded":"imported",stockImpact:Z,openingDate:M,itemCount:l.items.length,totalQty:l.totalQty,totalAmount:l.totalAmount,createdAt:(ae==null?void 0:ae.createdAt)||me,updatedAt:me,createdByUid:t.uid,createdByName:t.name},await yn(re(ie),ge),N({openingDate:M,batchId:String(D.id||""),stockImpact:Z,ready:!0});const Ee=F.length?` ${F.length} exact-supplier promotion target(s) updated.`:" No approved promotion matched this supplier and purchase date.";
3724g((Z?`POST-CUTOVER PURCHASE SUCCESS: ${l.items.length} line(s) stored and ${l.totalQty.toLocaleString("en-BD")} unit(s) added to live stock. Opening Qty was not changed.${Y?" Previous history-only import was safely upgraded; stock was applied once.":""}`:`HISTORICAL PURCHASE IMPORT SUCCESS: ${l.items.length} line(s) stored. Stock impact: NO because Purchase Date is on/before ${M}. Opening stock was not changed.`)+Ee)}catch(L){g(`Historical Purchase import failed: ${(L==null?void 0:L.message)||String(L)}`)}finally{u(!1)}}}return e.jsxs("div",{className:"pdf-import-panel purchase-history-panel",children:[e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(Kw,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Purchase Migration · cutover-aware"}),e.jsx("p",{children:"PDF â Preview â Validate â Branch â Import. Purchases on/before the opening date remain history-only; post-cutover purchases update live stock without changing Opening Qty."})]})]}),e.jsxs("div",{className:"pdf-cutover-notice",children:[e.jsx(gs,{size:18}),e.jsxs("strong",{children:["Stock impact: ",b.ready?b.stockImpact?"YES · post-cutover":"NO · pre/on-cutover":"Pending cutover check"]}),e.jsx("span",{children:b.ready?`Opening authority: ${b.openingDate}. ${b.stockImpact?"This Purchase will add to live stock; Opening Qty remains unchanged.":"This Purchase is history-only and will not change live stock."}`:"Generate preview after selecting a branch to resolve stock impact safely."})]}),e.jsxs("div",{className:"pdf-import-grid",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Branch"}),e.jsxs("select",{value:a,onChange:L=>{s(L.target.value),y(!1),C(null),I(null),N({openingDate:"",batchId:"",stockImpact:!1,ready:!1})},children:[e.jsx("option",{value:"",children:"Select branch"}),n.map(L=>e.jsx("option",{value:L.id,children:L.name},L.id))]})]}),e.jsxs("label",{className:"pdf-file-picker",children:[e.jsx(wp,{size:18}),e.jsx("span",{children:i?i.name:"Choose Purchase PDF"}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf",onChange:z})]}),e.jsx("button",{className:"primary-button",disabled:!i||d,onClick:H,children:d?"Processingâ¦":"Generate Purchase Preview"})]}),f&&e.jsx("div",{className:"pdf-import-message",children:f}),R&&e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(gs,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"RELATED SUPPLIER REF FOUND · IMPORT ALLOWED"}),e.jsxs("p",{children:["Same Supplier Ref ",e.jsx("b",{children:(l==null?void 0:l.supplierInvoiceRefNo)||"â"})," exists on Source Purchase ",e.jsx("b",{children:R.sourceInvoiceNo||"â"}),". Current Source Purchase ",e.jsx("b",{children:(l==null?void 0:l.sourceInvoiceNo)||"â"})," is different, so it may be imported as a separate purchase."]})]})]}),w&&e.jsxs("div",{className:"sales-duplicate-warning",children:[e.jsx(gs,{size:22}),e.jsxs("div",{children:[e.jsx("strong",{children:"EXISTING PURCHASE IMPORT FOUND · RE-IMPORT BLOCKED"}),e.jsxs("span",{children:["Source Purchase ",e.jsx("b",{children:w.sourceInvoiceNo||"â"})," · Supplier Ref ",e.jsx("b",{children:w.supplierInvoiceRefNo||"â"})," · ",w.supplier||"Supplier not recorded"]}),e.jsxs("small",{children:["Date ",w.purchaseDate||"â"," · Branch ",w.branchName||"â"," · Status ",w.status||"Imported",w.createdByName?` · By ${w.createdByName}`:"",w.createdAt?` · ${new Date(w.createdAt).toLocaleString("en-BD")}`:""]})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"purchase-summary-grid",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Purchase Date"}),e.jsx("strong",{children:l.purchaseDate||"Not detected"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Source Purchase No."}),e.jsx("strong",{children:l.sourceInvoiceNo||"Not detected"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Supplier Invoice / Ref No."}),e.jsx("strong",{children:l.supplierInvoiceRefNo||"Not provided"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Supplier"}),e.jsx("strong",{children:l.supplier||"Not detected"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Preview"}),e.jsx("strong",{children:G})]})]}),e.jsx("div",{className:"purchase-history-table-wrap",children:e.jsxs("table",{className:"purchase-history-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Rate"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Serial Evidence"})]})}),e.jsx("tbody",{children:l.items.slice(0,250).map((L,D)=>e.jsxs("tr",{children:[e.jsx("td",{children:D+1}),e.jsx("td",{children:L.product}),e.jsx("td",{children:L.qty}),e.jsx("td",{children:cj(L.rate)}),e.jsx("td",{children:cj(L.amount)}),e.jsx("td",{children:L.serials.length?L.serials.join(", "):"â"})]},L.id))})]})}),e.jsxs("label",{className:"migration-confirm",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:L=>y(L.target.checked)}),e.jsxs("span",{children:["I confirm this Purchase data for ",e.jsx("strong",{children:(_==null?void 0:_.name)||"the selected branch"}),". Stock Impact is ",e.jsx("strong",{children:b.ready?b.stockImpact?"YES (post-cutover)":"NO (pre/on-cutover)":"pending"}),"; Opening Qty will remain unchanged."]})]}),e.jsxs("button",{className:"primary-button",disabled:!T,onClick:K,children:[e.jsx(jp,{size:18})," ",b.stockImpact?"Import & Apply Live Stock":"Import Historical Purchase"]})]})]})}const kc=t=>Number(Number(t||0).toFixed(2));async function MI(t){var z;const n=`historical_sale_${t.saleKey}`;if((await mn(re(ie,`accountingVouchers/${t.companyId}/${n}`))).exists())return{};const[a,s]=await Promise.all([mn(re(ie,`accountingAccounts/${t.companyId}`)),mn(re(ie,`accountingSettings/${t.companyId}`))]),i=a.exists()?Object.entries(a.val()).map(([H,K])=>({id:H,...K})):[],c=(H,K)=>i.find(L=>L.active!==!1&&!L.isGroup&&(L.systemKey===H||L.code===K)),l=c("cash","1110"),m=c("bank","1120"),d=c("accounts_receivable","1200"),u=c("sales_revenue","4100");if(!l)throw new Error("Cash in Hand (1110) account is missing.");if(!m)throw new Error("Bank Account (1120) is missing.");if(!d)throw new Error("Accounts Receivable (1200) is missing.");if(!u)throw new Error("Sales Revenue (4100) is missing.");const f=String(((z=s.val())==null?void 0:z.lockedThrough)||"");if(f&&t.saleDate.slice(0,7)<=f)throw new Error(`Accounting period ${t.saleDate.slice(0,7)} is locked.`);const g=kc(t.grandTotal),p=kc(t.collected),y=kc(t.due),b=kc(t.payments.reduce((H,K)=>H+kc(K.amount),0)),N=y===0&&g>=p?kc(g-p):y;if(g<=0||p<0||N<0||Math.abs(g-p-N)>=.01)throw new Error("Sales total, collected and due do not balance.");if(Math.abs(b-p)>=.01)throw new Error("PDF payment-mode total does not match Total Collected; accounting was not guessed.");const R=[...t.payments.map(H=>{if(/^cash$/i.test(H.method))return{account:l,debit:kc(H.amount),credit:0,narration:`Historical Sales cash collected · ${t.invoiceNumber}`};const K=H.accountId?i.find(D=>D.id===H.accountId&&D.active!==!1&&!D.isGroup):void 0;if(H.accountId&&!K)throw new Error("Selected Bank/MFS ledger is missing or inactive.");return{account:K||m,debit:kc(H.amount),credit:0,narration:`Historical Sales ${H.method} collected · ${t.invoiceNumber}`}}),...N>0?[{account:d,debit:N,credit:0,narration:`Historical Sales receivable · ${t.invoiceNumber}`}]:[],{account:u,debit:0,credit:g,narration:`Historical Sales revenue · ${t.invoiceNumber}`}].map((H,K)=>({id:`line_${String(K+1).padStart(3,"0")}`,accountId:H.account.id,accountCode:H.account.code,accountName:H.account.name,debit:kc(H.debit),credit:kc(H.credit),narration:H.narration})),I=kc(R.reduce((H,K)=>
3724H+K.debit,0)),_=kc(R.reduce((H,K)=>H+K.credit,0));if(Math.abs(I-_)>=.005)throw new Error("Historical Sales accounting entry is not balanced.");const J=`AUTO-HS-${t.invoiceNumber}`,T=t.saleKey,G={};return G[`accountingVouchers/${t.companyId}/${n}`]={voucherNo:J,type:"receipt",status:"posted",voucherDate:t.saleDate,branchId:t.branchId,reference:t.invoiceNumber,narration:`Historical Sales imported · ${t.invoiceNumber} · ${t.customer||"Customer"}`,lines:R,totalDebit:I,totalCredit:_,createdAt:t.timestamp,createdByUid:t.actorUid,createdByName:t.actorName,updatedAt:t.timestamp,postedAt:t.timestamp,postedByUid:t.actorUid,postedByName:t.actorName,sourceType:"historical_sales_import",sourceId:T,autoPosted:!0},R.forEach((H,K)=>{const L=`${n}_${String(K+1).padStart(3,"0")}`;G[`accountingLedgerEntries/${t.companyId}/${L}`]={id:L,voucherId:n,voucherNo:J,voucherType:"receipt",voucherDate:t.saleDate,branchId:t.branchId,reference:t.invoiceNumber,narration:H.narration,accountId:H.accountId,accountCode:H.accountCode,accountName:H.accountName,debit:H.debit,credit:H.credit,status:"posted",createdAt:t.timestamp,postedByUid:t.actorUid,postedByName:t.actorName,sourceType:"historical_sales_import",sourceId:T,autoPosted:!0}}),G}const H8="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.min.mjs",W8="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38/pdf.worker.min.mjs",dr=t=>String(t||"").replace(/\s+/g," ").trim(),Lc=t=>Number(String(t||"").replace(/[৳,\s]/g,""))||0,Qm=t=>dr(t).replace(/[^A-Za-z0-9_-]/g,"_").slice(0,120),Fm=t=>`৳${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,G8={jan:"01",feb:"02",mar:"03",apr:"04",may:"05",jun:"06",jul:"07",aug:"08",sep:"09",oct:"10",nov:"11",dec:"12"};function P1(t){let n=t.match(/(\d{1,2})[-\/]([A-Za-z]{3})[-\/](\d{4})/);return n?`${n[3]}-${G8[n[2].toLowerCase()]||"01"}-${n[1].padStart(2,"0")}`:(n=t.match(/(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})/),n?`${n[3]}-${n[2].padStart(2,"0")}-${n[1].padStart(2,"0")}`:"")}function fE(t){return[...new Set(dr(t).split(/[\s,;]+/).map(n=>n.replace(/[^A-Za-z0-9_-]/g,"")).filter(n=>n.length>=4&&n.length<=32&&/\d/.test(n)))]}function Y8(t){const n=t.filter(s=>dr(s.str||"")).map(s=>{var i,c,l,m;return{text:String(s.str||""),x:Number(((i=s.transform)==null?void 0:i[4])||0),y:Number(((c=s.transform)==null?void 0:c[5])||0),width:Number(s.width),fontSize:Math.abs(Number(((l=s.transform)==null?void 0:l[3])||0))||Math.abs(Number(((m=s.transform)==null?void 0:m[0])||0))||10}}),a=[];for(const s of n){let i=a.find(c=>Math.abs(c.y-s.y)<=3);i||(i={y:s.y,cells:[]},a.push(i)),i.cells.push({x:s.x,text:s.text,width:s.width,fontSize:s.fontSize})}return a.sort((s,i)=>i.y-s.y).map(s=>{const i=s.cells.sort((c,l)=>c.x-l.x);return{y:s.y,cells:i,text:Vg(i)}}).filter(s=>s.text)}function Ah(t,n,a){return Vg(t.cells.filter(s=>s.x>=n&&s.x<a))}function R1(t){const n=dr(t).replace(/\s+/g,"").replace(/[^A-Za-z0-9_\-/]/g,"").replace(/-{2,}/g,"-"),a=n.match(/INV-[A-Z0-9]+-\d{4}-\d{2}-\d{4,}/i);return((a==null?void 0:a[0])||n).slice(0,120)}function gE(t){let n=dr(t).replace(/^\d+\s+/,"");for(let s=0;s<2;s+=1){const i=n;if(n=n.replace(/\b([B-HJ-Z])\s+([A-Z]{3,})\b/g,"$1$2").replace(/\b([A-Z])\s+(\d[A-Z0-9_-]{1,})\b/g,"$1$2"),n===i)break}const a=n.split(/\s+/);if(a.length>=4&&a.length%2===0){const s=a.length/2,i=a.slice(0,s).join(" "),c=a.slice(s).join(" ");if(i.toLowerCase()===c.toLowerCase())return i}return n}function Q8(t){return dr(t).replace(/[^0-9+]/g,"").replace(/^\+?88(?=01)/,"")}function J8(t){let n=dr(t).replace(/(?:\+?88)?01[\d-]{9,13}/g," ").replace(/^[\s:.,-]+|[\s:.,-]+$/g,"");const a=n.split(/\s+/).filter(Boolean);if(a.length>=2&&a.length%2===0){const l=a.length/2,m=a.slice(0,l).join(" "),d=a.slice(l).join(" ");m.toLowerCase()===d.toLowerCase()&&(n=m)}const s=new Set(["and","of","the","de","van","von"]);let i=n.split(/\s+/).filter(Boolean),c=[];for(const l of i)c.length&&/^[a-z]/.test(l)&&!s.has(l.toLowerCase())?c[c.length-1]+=l:c.push(l);if(c.length>=2){const l=c[c.length-1],m=c[c.length-2];/^[A-Z]{1,2}$/.test(l)&&/^[A-Z]{6,}$/.test(m)&&c.splice(c.length-2,2,m+l)}return dr(c.join(" "))}function yE(t,n){return{name:J8(t),phone:Q8(n)}}function lj(t){return Qm(dr(t).toLowerCase().replace(/[^a-z0-9]+/g,"_"))}function kv(t,n){return dr(t.replace(n,"").replace(/^\s*[:.-]\s*/,""))}function K8(t){const n=/(?:\+?88)?01[\d-]{9,13}/,a=c=>Vg(c.cells.filter(l=>l.x>=132&&l.x<330)),s=c=>{var d;const l=c.match(n),m=dr((l?c.replace(l[0],""):c).replace(/^[:.\-\s]+/,""));return/[A-Za-z]{2,}
3724/.test(m)?{name:m,phone:((d=l==null?void 0:l[0])==null?void 0:d.replace(/[^0-9+]/g,""))||""}:null};for(const c of t){const l=Ah(c,330,1/0);if(/INV\s*-/i.test(l)){const m=s(a(c));if(m)return m}}const i=t.findIndex(c=>/Contact\s*No\.?/i.test(c.text));if(i>0)for(let c=i-1;c>=Math.max(0,i-2);c--){const l=s(a(t[c]));if(l)return l}return null}function X8(t,n){var C,R;const a=I=>Ah(I,-1/0,330),s=I=>Ah(I,330,1/0),i=I=>t.find(_=>I.test(_.text));let c="",l="",m="",d="",u="";const f=i(/Customer\s*Name/i);if(f){const I=kv(a(f),/.*Customer\s*Name\s*/i),_=I.match(/(?:\+?88)?01[\d-]{9,13}/);m=((C=_==null?void 0:_[0])==null?void 0:C.replace(/[^0-9+]/g,""))||"",l=dr(_?I.replace(_[0],""):I)}const g=i(/Contact\s*No\.?/i);if(g&&!m){const I=a(g).match(/(?:\+?88)?01[\d-]{9,13}/);m=((R=I==null?void 0:I[0])==null?void 0:R.replace(/[^0-9+]/g,""))||""}if(!l){const I=K8(t);I&&(l=I.name,m||(m=I.phone))}const p=i(/Invoice\s*No\.?/i);if(p){let I=kv(s(p),/.*Invoice\s*No\.?\s*/i);const _=t.indexOf(p);if((/-$/.test(I)||!/[0-9]{4,}$/.test(I))&&_>=0&&_+1<t.length){const J=s(t[_+1]).match(/(?:^|\s)(\d{4,})(?:\s|$)/);J&&(I=`${I}${J[1]}`)}c=R1(I)}const y=i(/Sales\s*Person/i);y&&(d=kv(a(y),/.*Sales\s*Person\s*/i).replace(/\s+(?:Status|Date|Order\s+By|Billed\s+By)\b.*$/i,""));const b=i(/(?:^|\s)Date\s*:/i);b&&(u=P1(kv(s(b),/.*Date\s*/i)));const N=Z8(n),w=yE(l||N.customer,m||N.customerContact);return{...N,saleDate:u||N.saleDate,invoiceNo:c||N.invoiceNo,customer:w.name,customerContact:w.phone,salesman:dr(d||N.salesman).replace(/\s+Status\s*$/i,"")}}function Z8(t){var w,C;const n=t.map(dr).filter(Boolean),a=n.join(` 3725`),s=n.join(" ");let i="";const c=s.match(/INV\s*-\s*[A-Z0-9]+\s*-\s*\d{4}\s*-\s*\d{2}\s*-\s*\d{4,}/i);if(c&&(i=R1(c[0])),!i)for(let R=0;R<n.length;R++){const I=n[R].match(/Invoice\s*No\.?\s*:\s*(.*)$/i);if(I){let _=dr(I[1]);if((/-$/.test(_)||!/[0-9]{4,}$/.test(_))&&R+1<n.length){const J=n[R+1].match(/(?:^|\s)(\d{4,})(?:\s|$)/);J&&(_=`${_}${J[1]}`)}if(i=R1(_),i)break}}let l="",m="";const d=s.match(/Customer\s*Name\s*:\s*(.*?)(?=\s+Invoice\s*No\.?\s*:|\s+Contact\s*No\.?\s*:|$)/i);if(d){let R=dr(d[1]);const I=R.match(/(?:\+?88)?01[\d-]{9,13}/);m=((w=I==null?void 0:I[0])==null?void 0:w.replace(/[^0-9+]/g,""))||"",l=dr(I?R.replace(I[0],""):R)}if(!l)for(const R of n){const I=R.match(/Customer\s*Name\s*:\s*(.+)$/i);if(I){let _=dr(I[1]).replace(/\s+Invoice\s*No\.?\s*:.*$/i,"");const J=_.match(/(?:\+?88)?01[\d-]{9,13}/);m=((C=J==null?void 0:J[0])==null?void 0:C.replace(/[^0-9+]/g,""))||"",l=dr(J?_.replace(J[0],""):_);break}}for(const R of n){const I=R.match(/Contact\s*No\.?\s*:\s*([^\s]+)/i);I&&!m&&(m=dr(I[1]).replace(/[^0-9+]/g,""))}let u="";const f=s.match(/Sales\s*Person\s*:\s*(.*?)(?=\s+Invoice\s*No\.?\s*:|\s+Date\s*:|\s+Status\s*:|\s+Order\s+By\s*:|$)/i);if(f&&(u=dr(f[1])),!u)for(const R of n){const I=R.match(/Sales\s*Person\s*:\s*(.+)$/i);if(I){u=dr(I[1]).replace(/\s+(?:Invoice|Date|Status|Order\s+By|Billed\s+By)\b.*$/i,"");break}}const g=P1((a.match(/(?:^|\n)\s*Date\s*:\s*([^\n]+)/i)||[])[1]||"")||P1(a),p=Lc((a.match(/Grand\s*Total\s*([\d,.]+)/i)||[])[1]||""),y=Lc((a.match(/Total\s*Collected\s*([\d,.]+)/i)||[])[1]||""),b=Lc((a.match(/(?:^|\n)\s*Due\s*([\d,.]+)/im)||[])[1]||""),N=yE(l,m);return{saleDate:g,invoiceNo:i,customer:N.name,customerContact:N.phone,salesman:u,grandTotal:p,collected:y,due:b}}function eF(t){const n=t.find(K=>/product\s*name/i.test(K.text)&&/qty/i.test(K.text)&&/(price|rate)/i.test(K.text)&&/amount/i.test(K.text));if(!n)return[];const a=K=>{var L;return(L=n.cells.find(D=>K.test(D.text)))==null?void 0:L.x},s=a(/index|#/i)??0,i=a(/product/i),c=a(/qty/i),l=a(/unit$/i),m=a(/price|rate/i),d=a(/disc/i),u=a(/amount/i);if([i,c,m,u].some(K=>K===void 0))return[];const f=i,g=c,p=l??g+35,y=m,b=d??(y+u)/2,N=u,w=(s+f)/2,C=(f+g)/2,R=(g+p)/2,I=(p+y)/2,_=(y+b)/2,J=(b+N)/2,T=N+130,G=[];let z=null,H=0;for(const K of t.slice(t.indexOf(n)+1)){if(/^(?:total\s*qty|collection\s*detail|grand\s*total|in\s*word)/i.test(K.text))break;if(/warranty\s*:/i.test(K.text))continue;const L=Ah(K,w,C),D=Lc(Ah(K,C,R)),M=Lc(Ah(K,I,_)),Z=Lc(Ah(K,J,T));if(L&&D>0&&(M>0||Z>0)){z={id:`line_${++H}`,product:gE(L),qty:D,rate:M||Z/D,amount:Z||D*M,serials:[]},G.push(z);continue}if(z){const fe=/serial\s*(?:no|number)/i.test(K.text)?fE(K.text):c2(K.text);fe.length&&z.serials.push(...fe)}}return G}function tF(t){const n=[];let a=0,s=null;const i=/^\s*(\d+)\s+(.+?)\s+(\d+(?:\.\d+)?)\s+(PCS|PC|NOS|NO|UNIT|SET|BOX|PKT|PAIR|KG|GM|LTR|MTR)\s+([\d,]+(?:\.\d+)?)\s+([\d,]+(?:\.\d+)?)\s+([\d,]+(?:\.\d+)?)\s*$/i;for(const c of t){if(/^(?:total\s*qty|collection\s*detail|grand\s*total|in\s*word)/i.test(c)&&n.length)break;const l=c.match(i);if(l){const m=Lc(l[3]),d=Lc(l[5]),u=Lc(l[7]);s={id:`line_${++a}`,product:gE(l[2]),qty:m,rate:d||u/m,amount:u||m*d,serials:[]},n.push(s);continue}if(s){if(/warranty\s*:/i.test(c))continue;const m=/serial\s*(?:no|number)/i.test(c)?fE(c):c2(c);m.length&&s.serials.push(...m)}}return n}function T1(t,n){if(n<=0)return[];const a=t.findIndex(c=>/collection\s*detail/i.test(c));if(a<0)return[];const s=/^(Cash|TT|B[ -]?Kash|Nagad|Rocket|Card|Bank(?:\s+Transfer)?|Cheque|Mobile\s+Banking)\b\s*[:.-]?\s*([\d,]+(?:\.\d+)?)/i,i=[];
3725for(const c of t.slice(a+1,a+12)){if(/^\s*In\s*Word\b/i.test(c))break;const l=dr(c).match(s);if(l){const m=dr(l[1]).replace(/\s+/g,""),d=Lc(l[2]);d>0&&i.push({method:/^cash$/i.test(m)?"cash":m.toLowerCase(),amount:d})}}return i}function nF(t,n){var a;return((a=T1(t,n)[0])==null?void 0:a.method)||(n>0?"unknown":"")}const aF=new Set(["PCS","PC","NOS","NO","UNIT","SET","BOX","PKT","PAIR","THE","AND","WITH","FOR","CORE","INTEL","AMD"]);function kd(t){return dr(t).toUpperCase().replace(/[^A-Z0-9]+/g," ").split(" ").filter(n=>n.length>1&&!aF.has(n)).join(" ")}function $I(t){const n=kd(t);for(const a of["NOTEBOOK","LAPTOP","DESKTOP","TONER","PRINTER","BATTERY","MONITOR","SSD","HDD","RAM","ROUTER","UPS"])if(n.includes(a))return a;return"GENERAL"}function sF(t,n){const a=new Set(kd(t).split(" ").filter(Boolean)),s=new Set(kd(n).split(" ").filter(Boolean));if(!a.size||!s.size)return 0;let i=0;return a.forEach(c=>{s.has(c)&&i++}),2*i/(a.size+s.size)}function dj(t,n){const a=kd(t.product),s=$I(t.product),i=Object.entries(n).map(([m,d])=>{const u=`${d.name||""} ${d.category||""} ${d.model||""}`,f=kd(u),g=$I(u);let p=sF(a,f);return a===kd(d.name||"")&&(p=1),(f.includes(a)||a.includes(f))&&Math.min(a.length,f.length)>=8&&(p=Math.max(p,.96)),s!=="GENERAL"&&g!=="GENERAL"&&s!==g&&(p=Math.min(p,.35)),{id:m,p:d,score:p}}).sort((m,d)=>d.score-m.score),c=i[0],l=i[1];return c&&c.score>=.9&&(!l||c.score-l.score>=.05||c.score>=.98)?c:null}function rF({profile:t,branches:n}){const[a,s]=x.useState([]),[i,c]=x.useState(""),[l,m]=x.useState(""),[d,u]=x.useState([]),[f,g]=x.useState("");x.useEffect(()=>{if(t.companyId)return qt(re(ie,`historicalSalesImports/${t.companyId}`),_e=>{const ee=Object.entries(_e.val()||{}).map(([qe,se])=>({id:qe,...se}));u(ee.sort((qe,se)=>Number(se.createdAt||0)-Number(qe.createdAt||0)))})},[t.companyId]),x.useEffect(()=>{const _e=t.companyId;_e&&mn(re(ie,`accountingBankAccounts/${_e}`)).then(ee=>{const qe=ee.val()||{};s(Object.entries(qe).map(([se,pe])=>({id:se,...pe})).filter(se=>se.active!==!1&&!!se.ledgerAccountId))}).catch(()=>s([]))},[t.companyId]);const[p,y]=x.useState(null),[b,N]=x.useState(t.branchId||""),[w,C]=x.useState(null),[R,I]=x.useState([]),[_,J]=x.useState(""),[T,G]=x.useState(""),[z,H]=x.useState(""),[K,L]=x.useState(null),[D,M]=x.useState(!1),[Z,fe]=x.useState(!1),[q,ne]=x.useState({}),[ae,Y]=x.useState({}),je=n.find(_e=>_e.id===b),V=R.find(_e=>_e.id===_),$=!!w&&!!T&&w.saleDate>T,F=x.useMemo(()=>w?`${w.items.length} line(s) · ${w.totalQty} qty · ${Fm(w.totalAmount)}`:"",[w]);function P(_e){var ee;y(((ee=_e.target.files)==null?void 0:ee[0])||null),C(null),L(null),M(!1),Y({}),c(""),m(""),H("")}async function ue(){var _e;if(!(!p||!b)){c(""),m(""),fe(!0);try{const ee=await import(H8);ee.GlobalWorkerOptions.workerSrc=W8;const qe=await ee.getDocument({data:new Uint8Array(await p.arrayBuffer())}).promise,se=[],pe=[];for(let jt=1;jt<=qe.numPages;jt++){const tn=await(await qe.getPage(jt)).getTextContent(),B=Y8(tn.items);se.push(...B),pe.push(...B.map(xe=>xe.text)),await new Promise(xe=>setTimeout(xe,0))}const Se=X8(se,pe);let Me=eF(se);Me.length||(Me=tF(pe));const ot={sourceFile:p.name,...Se,items:Me,totalQty:Me.reduce((jt,bt)=>jt+bt.qty,0),totalAmount:Me.reduce((jt,bt)=>jt+bt.amount,0),rawLines:pe},wt=ot.saleDate&&ot.invoiceNo?Qm(`${ot.saleDate}_${b}_${ot.invoiceNo}`):"",[ct,Ce,De,Te,ce,Ye]=await Promise.all([mn(re(ie,`employees/${t.companyId}`)),mn(re(ie,`inventoryOpeningBatches/${t.companyId}`)),mn(re(ie,`historicalSalespersonMappings/${t.companyId}`)),wt?mn(re(ie,`historicalSalesImports/${t.companyId}/${wt}`)):Promise.resolve(null),mn(re(ie,`inventoryProducts/${t.companyId}`)),mn(re(ie,`historicalProductMappings/${t.companyId}`))]),Je=ce.val()||{};ne(Je);const le=Ye.val()||{},nt={};ot.items.forEach(jt=>{var B;const bt=Qm(kd(jt.product)),tn=String(((B=le[bt])==null?void 0:B.productId)||"");if(tn&&Je[tn])nt[jt.id]=tn;else{const xe=dj(jt,Je);xe&&(nt[jt.id]=xe.id)}}),Y(nt);const xt=Object.entries(ct.val()||{}).map(([jt,bt])=>({id:jt,...bt})).filter(jt=>jt.active!==!1);I(xt);const te=Object.values(Ce.val()||{}).filter(jt=>jt.branchId===b&&jt.openingDate).sort((jt,bt)=>String(bt.openingDate).localeCompare(String(jt.openingDate)));G(String(((_e=te[0])==null?void 0:_e.openingDate)||""));const Ge=dr(ot.salesman.replace(/^\d+\s*#\s*/,"")),pt=(De.val()||{})[lj(ot.salesman)],$e=xt.find(jt=>jt.id===(pt==null?void 0:pt.salespersonEmployeeId))||xt.find(jt=>{const bt=dr(jt.name||"").toLowerCase();return bt===Ge.toLowerCase()||bt===dr(ot.salesman).toLowerCase()}),st=!$e&&Ge.length>=3?xt.filter(jt=>
3725dr(jt.name||"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).includes(Ge.toLowerCase())):[],Nt=$e||(st.length===1?st[0]:void 0);J((Nt==null?void 0:Nt.id)||"");const be=Te!=null&&Te.exists()?Te.val():null;L(be!=null&&be.accountingPosted&&!(be!=null&&be.cancelled)?be:null),M(!1),C(ot),H(be!=null&&be.cancelled?`REVERSED IMPORT â Invoice ${ot.invoiceNo} was previously cancelled/reversed. The same import key remains protected from accidental re-import.`:be!=null&&be.accountingPosted?`ALREADY IMPORTED â Invoice ${ot.invoiceNo} and its accounting are already posted.`:be?`ACCOUNTING REPAIR READY â Invoice ${ot.invoiceNo} is already imported. Confirm to post only its missing accounting; stock, serial and KPI will not change.`:ot.items.length?`SAFE SALES PREVIEW READY. Invoice ${ot.invoiceNo||"not detected"}; ${ot.salesman?"salesperson detected â confirm employee mapping.":"select the VERIXO salesperson before import."}`:"Preview blocked: no reliable Sales item table was detected.")}catch(ee){H(`Sales PDF preview failed: ${(ee==null?void 0:ee.message)||ee}`)}finally{fe(!1)}}}async function me(_e){if(J(_e),!(w!=null&&w.salesman)||!_e)return;const ee=R.find(pe=>pe.id===_e);if(!ee)return;const qe=Date.now(),se=lj(w.salesman);try{await yn(re(ie),{[`historicalSalespersonMappings/${t.companyId}/${se}`]:{sourceSalesmanName:w.salesman,salespersonEmployeeId:_e,salespersonEmployeeCode:ee.employeeId||"",salespersonName:ee.name||"",confirmedAt:qe,confirmedByUid:t.uid}})}catch(pe){console.warn("Could not remember salesperson mapping",pe)}}async function ge(){var _e;if(!(!w||!b||!_||!D||!T||!w.saleDate||!w.invoiceNo)){fe(!0);try{const ee=Qm(`${w.saleDate}_${b}_${w.invoiceNo}`),qe=Date.now(),se=await mn(re(ie,`historicalSalesImports/${t.companyId}/${ee}`));if(se.exists()){const Me=se.val();if(Me.cancelled){L(Me),M(!1),H("Re-import blocked: this Historical Sales invoice was already safely reversed. Audit/provenance has been retained.");return}if(!$){L(Me),M(!1),H("Duplicate blocked: pre/on-cutover Sales is history-only and has no live accounting impact.");return}const ot=T1(w.rawLines,w.collected),ct=(ot.length?ot:w.collected>0?[{method:"unknown",amount:w.collected}]:[]).map((De,Te)=>{if(Te>0)return De;const ce=i||De.method;if(ce!=="cash"&&!l)throw new Error("Select the destination Bank/MFS account for this collected payment.");const Ye=ce==="cash"?void 0:a.find(Je=>Je.id===l);return{...De,method:ce,sourceMethod:De.method,...Ye!=null&&Ye.ledgerAccountId?{accountId:Ye.ledgerAccountId}:{},...Ye!=null&&Ye.ledgerCode?{accountCode:Ye.ledgerCode}:{},...Ye!=null&&Ye.ledgerName?{accountName:Ye.ledgerName}:{},...Ye!=null&&Ye.id?{paymentAccountId:Ye.id}:{}}}),Ce=await MI({companyId:t.companyId,branchId:b,saleKey:ee,saleDate:w.saleDate,invoiceNumber:w.invoiceNo,customer:w.customer,grandTotal:w.grandTotal||w.totalAmount,collected:w.collected,due:w.due,payments:ct,actorUid:t.uid,actorName:t.name||t.email||"User",timestamp:qe});if(!Object.keys(Ce).length){L({...Me,accountingPosted:!0}),M(!1),H("Already imported and accounting is already posted. No stock or accounting data was duplicated.");return}Ce[`historicalSalesImports/${t.companyId}/${ee}/accountingPosted`]=!0,Ce[`historicalSalesImports/${t.companyId}/${ee}/accountingVoucherId`]=`historical_sale_${ee}`,Ce[`historicalSalesImports/${t.companyId}/${ee}/accountingPostedAt`]=qe,Ce[`historicalSales/${t.companyId}/${ee}/accountingPosted`]=!0,Ce[`historicalSales/${t.companyId}/${ee}/accountingVoucherId`]=`historical_sale_${ee}`,Ce[`historicalSales/${t.companyId}/${ee}/accountingPostedAt`]=qe,Ce[`migrationHistory/${t.companyId}/sales_${ee}/accountingPosted`]=!0,Ce[`migrationHistory/${t.companyId}/sales_${ee}/accountingVoucherId`]=`historical_sale_${ee}`,await yn(re(ie),Ce),L({...Me,accountingPosted:!0}),M(!1),H(`ACCOUNTING REPAIR SUCCESS: ${Fm(w.collected)} collected posted from the PDF payment mode; stock, serial and KPI data were not changed.`);return}const pe={id:ee,companyId:t.companyId,branchId:b,branchName:(je==null?void 0:je.name)||"",saleDate:w.saleDate,sourceInvoiceNo:w.invoiceNo,customer:w.customer,customerContact:w.customerContact,sourceSalesmanName:w.salesman,salespersonEmployeeId:_,salespersonEmployeeCode:(V==null?void 0:V.employeeId)||"",salespersonName:(V==null?void 0:V.name)||"",salespersonMapping:"confirmed",targetAttributionEligible:!0,sourceFile:w.sourceFile,sourceSystem:"takeplus_oner_legacy",migrationMode:$?"post_cutover_stock_impacting":"pre_cutover_history_only",stockImpact:$,openingDate:T,itemCount:w.items.length,totalQty:w.totalQty,totalAmount:w.totalAmount,grandTotal:w.grandTotal||w.totalAmount,collected:w.collected,due:w.due,serialEvidenceCount:w.items.reduce((Me,ot)=>Me+ot.serials.length,0),items:w.items.map(({id:Me,...ot})=>ot),createdAt:qe,createdByUid:t.uid,createdByName:t.name},Se={};if($){const[Me,ot]=await Promise.all([mn(re(ie,`inventoryProducts/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}/${b}`))]),wt=Me.val()||{},ct=ot.val()||{},Ce=[...new Set(Object.values(ct).map(Je=>
3725String((Je==null?void 0:Je.sourceBatchId)||"")).filter(Boolean))],De=await Promise.all(Ce.map(Je=>mn(re(ie,`inventoryOpeningItems/${t.companyId}/${Je}`)))),Te={};Ce.forEach((Je,le)=>{var nt;return Te[Je]=((nt=De[le])==null?void 0:nt.val())||{}});const ce=w.items.map(Je=>{const le=ae[Je.id],nt=le&&wt[le]?{id:le,p:wt[le],score:1}:null;return{line:Je,match:nt||dj(Je,wt)}}),Ye=ce.filter(Je=>!Je.match);if(Ye.length){H(`Import blocked: ${Ye.length} post-cutover Sales line(s) could not be mapped safely to existing VERIXO products. First unmatched: ${Ye[0].line.product}`);return}for(const{line:Je,match:le}of ce){const nt=le.id,xt=ct[nt]||{},te=Lc(String(xt.qty||0));if(te+1e-9<Je.qty){H(`Import blocked: insufficient live stock for ${Je.product}. Live ${te}, Sales ${Je.qty}. Opening Qty was not changed.`);return}const Ge=xt.sourceBatchId?(_e=Te[xt.sourceBatchId])==null?void 0:_e[nt]:void 0,pt=new Set((xt.postCutoverSoldSerials||[]).map(bt=>String(bt).trim()).filter(Boolean)),$e=[...new Set([...(Ge==null?void 0:Ge.reliableCurrentReferenceSerials)||[],...xt.postCutoverPurchaseSerials||[],...xt.manualReconciledSerials||[]].map(bt=>String(bt).trim()).filter(Boolean))].filter(bt=>!pt.has(bt)),st=new Set($e),Nt=[...new Set((Je.serials||[]).map(bt=>String(bt).trim()).filter(Boolean))];if($e.length>0||Number(xt.referenceSerialLinkedQty||0)>0||Nt.length>0){if(Nt.length!==Math.round(Number(Je.qty||0))){H(`Import blocked: serial-controlled item ${Je.product} requires ${Je.qty} in-stock serial(s), but the PDF contains ${Nt.length}. No quantity-only bypass is allowed.`);return}const bt=Nt.filter(tn=>!st.has(tn));if(bt.length){H(`Import blocked: serial ${bt[0]} is not currently available in stock for mapped product ${Je.product}. Historical Sales requires exact in-stock serial matching.`);return}}const jt=[...new Set([...xt.postCutoverSoldSerials||[],...Nt])];Se[`inventoryStock/${t.companyId}/${b}/${nt}/qty`]=te-Je.qty,Se[`inventoryStock/${t.companyId}/${b}/${nt}/postCutoverSalesQty`]=Lc(String(xt.postCutoverSalesQty||0))+Je.qty,Se[`inventoryStock/${t.companyId}/${b}/${nt}/postCutoverSoldSerials`]=jt,Se[`inventoryStock/${t.companyId}/${b}/${nt}/lastHistoricalSaleAt`]=qe,Se[`inventoryStock/${t.companyId}/${b}/${nt}/lastHistoricalSaleNo`]=w.invoiceNo,Se[`inventoryStock/${t.companyId}/${b}/${nt}/updatedAt`]=qe}}if($){const Me=T1(w.rawLines,w.collected),wt=(Me.length?Me:w.collected>0?[{method:"unknown",amount:w.collected}]:[]).map((Ce,De)=>{if(De>0)return Ce;const Te=i||Ce.method;if(Te!=="cash"&&!l)throw new Error("Select the destination Bank/MFS account for this collected payment.");const ce=Te==="cash"?void 0:a.find(Ye=>Ye.id===l);return{...Ce,method:Te,sourceMethod:Ce.method,...ce!=null&&ce.ledgerAccountId?{accountId:ce.ledgerAccountId}:{},...ce!=null&&ce.ledgerCode?{accountCode:ce.ledgerCode}:{},...ce!=null&&ce.ledgerName?{accountName:ce.ledgerName}:{},...ce!=null&&ce.id?{paymentAccountId:ce.id}:{}}}),ct=await MI({companyId:t.companyId,branchId:b,saleKey:ee,saleDate:w.saleDate,invoiceNumber:w.invoiceNo,customer:w.customer,grandTotal:w.grandTotal||w.totalAmount,collected:w.collected,due:w.due,payments:wt,actorUid:t.uid,actorName:t.name||t.email||"User",timestamp:qe});Object.assign(Se,ct),pe.paymentBreakdown=wt,pe.accountingPosted=!0,pe.accountingVoucherId=`historical_sale_${ee}`,pe.accountingPostedAt=qe,w.collected>0&&wt.forEach((Ce,De)=>{const Te=`historical_${ee}_${String(De+1).padStart(2,"0")}`,ce=w.invoiceNo.replace(/[^A-Za-z0-9]/g,"").slice(-8),Ye=`HS-COL-${ce}-${String(De+1).padStart(2,"0")}`,Je=`HS-MR-${ce}-${String(De+1).padStart(2,"0")}`;Se[`collections/${t.companyId}/${Te}`]={id:Te,companyId:t.companyId,branchId:b,customerId:"",customerName:w.customer,customerPhone:w.customerContact,serviceJobId:"",invoiceId:`historical_${ee}`,invoiceNumber:w.invoiceNo,collectionNumber:Ye,moneyReceiptNumber:Je,amount:Ce.amount,method:/^cash$/i.test(Ce.method)?"cash":Ce.method,reference:"Historical Sales PDF",notes:"Auto-created from Historical Sales import",collectedAt:new Date(`${w.saleDate}T12:00:00`).getTime(),createdAt:qe,createdBy:t.name||t.email||"User",accountingPosted:!0,sourceType:"historical_sales_import",sourceId:ee},Se[`moneyReceipts/${t.companyId}/${Te}`]={id:Te,collectionId:Te,companyId:t.companyId,branchId:b,customerId:"",customerName:w.customer,customerPhone:w.customerContact,invoiceId:`historical_${ee}`,invoiceNumber:w.invoiceNo,collectionNumber:Ye,moneyReceiptNumber:Je,amount:Ce.amount,method:/^cash$/i.test(Ce.method)?"cash":Ce.method,collectedAt:new Date(`${w.saleDate}T12:00:00`).getTime(),createdAt:qe,createdBy:t.name||t.email||"User",accountingPosted:!0,sourceType:"historical_sales_import",sourceId:ee}})}if($)for(const Me of w.items){const ot=ae[Me.id];if(ot&&q[ot]){const wt=Qm(kd(Me.product));Se[`historicalProductMappings/${t.companyId}/${wt}`]={sourceProductName:Me.product,productId:ot,productName:q[ot].name||"",confirmedAt:qe,confirmedByUid:t.uid,source:"historical_sales_pdf"}}}if(w.salesman){const Me=lj(w.salesman);Se[`historicalSalespersonMappings/${t.companyId}/${Me}`]={sourceSalesmanName:w.salesman,salespersonEmployeeId:_,salespersonEmployeeCode:(V==null?void 0:V.employeeId)||"",salespersonName:(V==null?void 0:V.name)||"",confirmedAt:qe,confirmedByUid:t.uid}}Se[`historicalSalesImports/${t.companyId}/${ee}`]=pe,Se[`historicalSales/${t.companyId}/${ee}`]=pe,Se[`migrationHistory/${t.companyId}/sales_${ee}`]={...pe,type:"historical_sales",items:null},await yn(re(ie),Se),H(`HISTORICAL SALES IMPORT SUCCESS: ${w.items.length} line(s) stored under ${(V==null?void 0:V.name)||"mapped salesperson"}. ${$?`${w.totalQty} unit(s) deducted from live stock. Opening Qty was not changed.`:"Pre/on-cutover sale is history-only; opening stock remains unchanged."}`)}catch(ee){H(`Historical Sales import failed: ${(ee==null?void 0:ee.message)||ee}`)}finally{fe(!1)}}}async function de(_e){var se,pe,Se;const ee=String(_e.id||"");if(!ee||_e.cancelled)return;const qe=(se=window.prompt(`Reason for reversing Historical Sales invoice ${_e.sourceInvoiceNo||ee}:`,"Wrong / duplicate historical import"))==null?void 0:se.trim();if(qe&&window.confirm(`Reverse Historical Sales ${_e.sourceInvoiceNo||ee}? 3726 3727This keeps the import/audit record, removes it from active Historical Sales, reverses its posted accounting/collection evidence, and restores post-cutover stock
3727impact only when applicable.`)){g(ee);try{const Me=Date.now(),ot=t.companyId,[wt,ct,Ce,De,Te,ce,Ye]=await Promise.all([mn(re(ie,`historicalSales/${ot}/${ee}`)),mn(re(ie,`inventoryStock/${ot}/${_e.branchId||""}`)),mn(re(ie,`historicalProductMappings/${ot}`)),mn(re(ie,`historicalSales/${ot}`)),mn(re(ie,`accountingVouchers/${ot}/historical_sale_${ee}`)),mn(re(ie,`collections/${ot}`)),mn(re(ie,`accountingSettings/${ot}`))]);if(!wt.exists())throw new Error("Active Historical Sales record is missing; nothing was changed.");const Je=wt.val(),le={};if(Je.stockImpact){const te=ct.val()||{},Ge=Ce.val()||{},pt=De.val()||{};for(const $e of Je.items||[]){const st=Qm(kd(String($e.product||""))),Nt=String(((pe=Ge[st])==null?void 0:pe.productId)||"");if(!Nt)throw new Error(`Stock reversal blocked: product mapping is missing for ${$e.product||"an imported item"}. No data was changed.`);const be=te[Nt]||{},jt=Number($e.qty||0);le[`inventoryStock/${ot}/${Je.branchId}/${Nt}/qty`]=Number(be.qty||0)+jt,le[`inventoryStock/${ot}/${Je.branchId}/${Nt}/postCutoverSalesQty`]=Math.max(0,Number(be.postCutoverSalesQty||0)-jt);const bt=new Set;Object.entries(pt).forEach(([B,xe])=>{B===ee||xe!=null&&xe.cancelled||((xe==null?void 0:xe.items)||[]).forEach(tt=>(tt.serials||[]).forEach(ht=>bt.add(String(ht))))});const tn=new Set(($e.serials||[]).map(String).filter(B=>!bt.has(B)));le[`inventoryStock/${ot}/${Je.branchId}/${Nt}/postCutoverSoldSerials`]=(be.postCutoverSoldSerials||[]).filter(B=>!tn.has(String(B))),le[`inventoryStock/${ot}/${Je.branchId}/${Nt}/lastHistoricalSaleAt`]=Me,le[`inventoryStock/${ot}/${Je.branchId}/${Nt}/lastHistoricalSaleNo`]=`REVERSED ${Je.sourceInvoiceNo||ee}`,le[`inventoryStock/${ot}/${Je.branchId}/${Nt}/updatedAt`]=Me}}if(Te.exists()){const te=Te.val(),Ge=String(((Se=Ye.val())==null?void 0:Se.lockedThrough)||""),pt=String(te.voucherDate||Je.saleDate||"").slice(0,7);if(Ge&&pt&&pt<=Ge)throw new Error(`Accounting period ${pt} is locked. Unlock/reopen the period before reversing this imported sale.`);const $e=`historical_sale_reverse_${ee}`;if(!(await mn(re(ie,`accountingVouchers/${ot}/${$e}`))).exists()){const Nt=(te.lines||[]).map((be,jt)=>({...be,id:`line_${String(jt+1).padStart(3,"0")}`,debit:Number(be.credit||0),credit:Number(be.debit||0),narration:`Reversal · ${be.narration||Je.sourceInvoiceNo||ee}`}));le[`accountingVouchers/${ot}/${$e}`]={...te,voucherNo:`REV-${te.voucherNo||Je.sourceInvoiceNo||ee}`,type:"journal",reference:Je.sourceInvoiceNo||ee,narration:`Historical Sales import reversed · ${Je.sourceInvoiceNo||ee} · ${qe}`,lines:Nt,totalDebit:Number(te.totalCredit||0),totalCredit:Number(te.totalDebit||0),createdAt:Me,updatedAt:Me,postedAt:Me,createdByUid:t.uid,createdByName:t.name||t.email||"User",postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"historical_sales_import_reversal",sourceId:ee,reversesVoucherId:`historical_sale_${ee}`},Nt.forEach((be,jt)=>{const bt=`${$e}_${String(jt+1).padStart(3,"0")}`;le[`accountingLedgerEntries/${ot}/${bt}`]={id:bt,voucherId:$e,voucherNo:`REV-${te.voucherNo||Je.sourceInvoiceNo||ee}`,voucherType:"journal",voucherDate:te.voucherDate||Je.saleDate,branchId:Je.branchId||"",reference:Je.sourceInvoiceNo||ee,narration:be.narration,accountId:be.accountId,accountCode:be.accountCode,accountName:be.accountName,debit:be.debit,credit:be.credit,status:"posted",createdAt:Me,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"historical_sales_import_reversal",sourceId:ee,autoPosted:!0}}),le[`accountingVouchers/${ot}/historical_sale_${ee}/reversedByVoucherId`]=$e,le[`accountingVouchers/${ot}/historical_sale_${ee}/reversedAt`]=Me}}const nt=ce.val()||{};Object.entries(nt).forEach(([te,Ge])=>{(Ge==null?void 0:Ge.sourceType)==="historical_sales_import"&&String((Ge==null?void 0:Ge.sourceId)||"")===ee&&(le[`collections/${ot}/${te}/originalAmount`]=Number(Ge.amount||0),le[`collections/${ot}/${te}/amount`]=0,le[`collections/${ot}/${te}/status`]="cancelled",le[`collections/${ot}/${te}/cancelledAt`]=Me,le[`collections/${ot}/${te}/cancelReason`]=qe,le[`moneyReceipts/${ot}/${te}/originalAmount`]=Number(Ge.amount||0),le[`moneyReceipts/${ot}/${te}/amount`]=0,le[`moneyReceipts/${ot}/${te}/status`]="cancelled",le[`moneyReceipts/${ot}/${te}/cancelledAt`]=Me)}),le[`historicalSales/${ot}/${ee}`]=null,le[`historicalSalesImports/${ot}/${ee}/cancelled`]=!0,le[`historicalSalesImports/${ot}/${ee}/cancelledAt`]=Me,le[`historicalSalesImports/${ot}/${ee}/cancelledByUid`]=t.uid,le[`historicalSalesImports/${ot}/${ee}/cancelledByName`]=t.name||t.email||"User",le[`historicalSalesImports/${ot}/${ee}/cancelReason`]=qe,le[`historicalSalesImports/${ot}/${ee}/reversalVoucherId`]=Te.exists()?`historical_sale_reverse_${ee}`:"",le[`migrationHistory/${ot}/sales_${ee}/cancelled`]=!0,le[`migrationHistory/${ot}/sales_${ee}/cancelledAt`]=Me,le[`migrationHistory/${ot}/sales_${ee}/cancelReason`]=qe;const xt=`historical_sales_reverse_${ee}_${Me}`;le[`auditLogs/${ot}/${xt}`]={id:xt,action:"migration.historical_sales_reversed",entityType:"historical_sales",entityId:ee,description:`Historical Sales ${Je.sourceInvoiceNo||ee} safely reversed`,metadata:{sourceInvoiceNo:Je.sourceInvoiceNo||"",saleDate:Je.saleDate||"",stockImpact:!!Je.stockImpact,grandTotal:Number(Je.grandTotal||Je.totalAmount||0),reason:qe},createdAt:Me,createdByUid:t.uid,createdByName:t.name||t.email||"User"},await yn(re(ie),le),H(`HISTORICAL SALES REVERSED: ${Je.sourceInvoiceNo||ee}. Import/audit history retained; active KPI/report contribution removed${Je.stockImpact?", stock
3727impact restored and accounting reversed":""}.`)}catch(Me){H(`Historical Sales reversal failed: ${(Me==null?void 0:Me.message)||Me}`)}finally{g("")}}}const Pe=!$||!!w&&w.items.every(_e=>!!ae[_e.id]),Re=w?nF(w.rawLines,w.collected):"",Ee=!!w&&w.collected>0&&(!Re||/^(tt|unknown)$/i.test(Re)),Be=i||(Ee?"":Re),We=!$||!w||w.collected<=0||!!Be&&(Be==="cash"||!!l),it=!!w&&!!b&&!!_&&D&&!!T&&!!w.saleDate&&!!w.invoiceNo&&w.items.length>0&&!K&&Pe&&We;return e.jsxs("div",{className:"pdf-import-panel purchase-history-panel",children:[e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(Iu,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Sales Migration · salesperson-aware"}),e.jsx("p",{children:"PDF â Preview â Salesperson Mapping â Validate â Import. Historical salesperson attribution is preserved for future Sales Target, Achievement and KPI analysis."})]})]}),e.jsxs("div",{className:"pdf-cutover-notice",children:[e.jsx(gs,{size:18}),e.jsxs("strong",{children:["Stock impact: ",w&&T?$?"YES · post-cutover":"NO · pre/on-cutover":"Pending preview"]}),e.jsx("span",{children:T?`Opening authority: ${T}. Opening Qty is never rewritten by Sales import.`:"Select branch and generate preview to resolve the cutover."})]}),e.jsxs("div",{className:"pdf-import-grid",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Branch"}),e.jsxs("select",{value:b,onChange:_e=>{N(_e.target.value),C(null),L(null),M(!1)},children:[e.jsx("option",{value:"",children:"Select branch"}),n.map(_e=>e.jsx("option",{value:_e.id,children:_e.name},_e.id))]})]}),e.jsxs("label",{className:"pdf-file-picker",children:[e.jsx(wp,{size:18}),e.jsx("span",{children:(p==null?void 0:p.name)||"Choose Sales PDF"}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf",onChange:P})]}),e.jsx("button",{className:"primary-button",disabled:!p||!b||Z,onClick:ue,children:Z?"Processingâ¦":"Generate Sales Preview"})]}),z&&e.jsx("div",{className:`pdf-import-message${K?" duplicate":""}`,children:z}),K&&e.jsxs("div",{className:"sales-duplicate-warning",children:[e.jsx(gs,{size:22}),e.jsxs("div",{children:[e.jsx("strong",{children:"ALREADY IMPORTED · RE-IMPORT BLOCKED"}),e.jsxs("span",{children:["Invoice ",e.jsx("b",{children:K.sourceInvoiceNo||(w==null?void 0:w.invoiceNo)})," was already imported for ",e.jsx("b",{children:K.branchName||(je==null?void 0:je.name)}),". No stock, serial, opening quantity or Sales KPI data will be written again."]}),e.jsxs("small",{children:["Previous import: ",K.createdAt?new Date(K.createdAt).toLocaleString("en-BD"):"Recorded",K.createdByName?` · By ${K.createdByName}`:"",K.salespersonName?` · Salesperson ${K.salespersonName}`:"",Number.isFinite(Number(K.totalQty))?` · Qty ${K.totalQty}`:""]})]})]}),w&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"purchase-summary-grid",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Sales Date"}),e.jsx("strong",{children:w.saleDate||"Not detected"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Invoice No."}),e.jsx("strong",{children:w.invoiceNo||"Not detected"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Customer"}),e.jsxs("strong",{children:[w.customer||"Not detected",w.customerContact?` · ${w.customerContact}`:""]})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Source Salesman"}),e.jsx("strong",{children:w.salesman||"Not detected"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Preview"}),e.jsx("strong",{children:F})]})]}),e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(Mc,{size:18}),e.jsxs("div",{style:{width:"100%"},children:[e.jsx("strong",{children:"Salesperson Mapping · required for Target/KPI"}),e.jsxs("p",{children:["Source: ",e.jsx("b",{children:w.salesman||"Not detected"})," · confirmed mappings are remembered for future Sales PDFs."]}),e.jsxs("select",{value:_,onChange:_e=>void me(_e.target.value),style:{width:"100%",padding:10},children:[e.jsx("option",{value:"",children:"Select VERIXO employee / salesperson"}),R.map(_e=>e.jsxs("option",{value:_e.id,children:[_e.name||_e.employeeId||_e.id,_e.employeeId?` · ${_e.employeeId}`:"",_e.designation?` · ${_e.designation}`:""]},_e.id))]})]})]}),e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(Nd,{size:18}),e.jsxs("div",{style:{width:"100%"},children:[e.jsx("strong",{children:"Collection / Payment Mapping"}),e.jsxs("p",{children:["Source: ",e.jsx("b",{children:Re||"Not detected"}),w.collected>0?` · ${Fm(w.collected)}`:"",". TT/unknown modes require confirmation; VERIXO never guesses Cash or Bank."]}),w.collected>0&&e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(220px,.8fr) minmax(320px,1.2fr)",gap:10},children:[e.jsxs("select",{value:Be,onChange:_e=>{c(_e.target.value),_e.target.value==="cash"&&m("")},children:[e.jsx("option",{value:"",children:"Select imported payment method..."}),e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bank_transfer",children:"Bank Account"}),e.jsx("option",{value:"bkash",children:"bKash / MFS"}),e.jsx("option",{value:"nagad",children:"Nagad / MFS"}),e.jsx("option",{value:"card",children:"Card"}),e.jsx("option",{value:"cheque",children:"Cheque"})]}
3727),Be&&Be!=="cash"?e.jsxs("select",{value:l,onChange:_e=>m(_e.target.value),children:[e.jsx("option",{value:"",children:"Select destination Bank/MFS account..."}),a.map(_e=>e.jsxs("option",{value:_e.id,children:[_e.bankName||_e.name||"Payment Account",_e.accountName?` · ${_e.accountName}`:"",_e.accountNumber?` · ${_e.accountNumber}`:"",_e.ledgerCode?` · Ledger ${_e.ledgerCode}`:""]},_e.id))]}):e.jsx("div",{className:"muted",style:{padding:10},children:"Cash â Cash in Hand (1110)"})]}),Ee&&e.jsx("small",{style:{display:"block",marginTop:8},children:"Review Required: source mode is ambiguous. Select the real payment destination before import."})]})]}),e.jsxs("div",{className:"pdf-import-notice",children:[e.jsx(gs,{size:18}),e.jsxs("div",{style:{width:"100%"},children:[e.jsx("strong",{children:"Product Mapping · safe stock matching"}),e.jsx("p",{children:"Each Sales PDF product must map to an existing VERIXO product. Confirmed mappings are remembered for future PDFs; no fuzzy match is written unless you confirm it."}),w.items.map(_e=>{const ee=ae[_e.id]||"",qe=dj(_e,q);return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(260px,1fr) minmax(320px,1.4fr)",gap:10,alignItems:"center",marginTop:8},children:[e.jsxs("span",{children:[e.jsx("b",{children:_e.product}),_e.serials.length?e.jsxs("small",{style:{display:"block"},children:["Serial: ",_e.serials.join(", ")]}):null]}),e.jsxs("select",{value:ee,onChange:se=>Y(pe=>({...pe,[_e.id]:se.target.value})),style:{width:"100%",padding:10},children:[e.jsx("option",{value:"",children:"Select VERIXO product"}),Object.entries(q).filter(([,se])=>se.active!==!1).sort((se,pe)=>String(se[1].name||"").localeCompare(String(pe[1].name||""))).map(([se,pe])=>e.jsxs("option",{value:se,children:[pe.name||se,pe.model?` · ${pe.model}`:"",(qe==null?void 0:qe.id)===se?" · Suggested":""]},se))]})]},`map-${_e.id}`)})]})]}),e.jsx("div",{className:"purchase-history-table-wrap",children:e.jsxs("table",{className:"purchase-history-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Rate"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Serial Evidence"})]})}),e.jsx("tbody",{children:w.items.slice(0,250).map((_e,ee)=>e.jsxs("tr",{children:[e.jsx("td",{children:ee+1}),e.jsx("td",{children:_e.product}),e.jsx("td",{children:_e.qty}),e.jsx("td",{children:Fm(_e.rate)}),e.jsx("td",{children:Fm(_e.amount)}),e.jsx("td",{children:_e.serials.length?_e.serials.join(", "):"â"})]},_e.id))})]})}),e.jsxs("label",{className:"migration-confirm",children:[e.jsx("input",{type:"checkbox",checked:D,disabled:!!K,onChange:_e=>M(_e.target.checked)}),e.jsxs("span",{children:["I confirm this Sales data for ",e.jsx("strong",{children:(je==null?void 0:je.name)||"the selected branch"})," and salesperson ",e.jsx("strong",{children:(V==null?void 0:V.name)||"not mapped"}),". This attribution will be retained for future Sales Target/KPI."]})]}),e.jsxs("button",{className:"primary-button",disabled:!it||Z,onClick:ge,children:[e.jsx(jp,{size:18}),K?" Already Imported · Import Blocked":" Import Historical Sales"]})]}),e.jsxs("div",{style:{marginTop:18},children:[e.jsx("h4",{style:{margin:"0 0 8px"},children:"Imported Sales History"}),e.jsx("div",{className:"purchase-history-table-wrap",children:e.jsxs("table",{className:"purchase-history-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Invoice"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Salesperson"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:d.slice(0,100).map(_e=>e.jsxs("tr",{children:[e.jsx("td",{children:_e.saleDate||"â"}),e.jsx("td",{children:e.jsx("b",{children:_e.sourceInvoiceNo||_e.id})}),e.jsx("td",{children:_e.customer||"â"}),e.jsx("td",{children:_e.salespersonName||"â"}),e.jsx("td",{children:Fm(Number(_e.grandTotal||_e.totalAmount||0))}),e.jsx("td",{children:_e.cancelled?"Reversed":_e.accountingPosted?"Imported · Posted":"Imported"}),e.jsx("td",{children:_e.cancelled?e.jsx("small",{children:_e.cancelReason||"Reversed safely"}):e.jsxs("button",{type:"button",className:"secondary-button",disabled:!!f,onClick:()=>void de(_e),title:"Safely reverse this Historical Sales import",children:[e.jsx(Id,{size:15})," ",f===_e.id?"Reversing...":"Reverse Import"]})})]},_e.id))})]})}
3727),e.jsx("small",{className:"muted",children:"Reverse Import never hard-deletes the migration evidence. Pre/on-cutover rows only leave active Historical Sales; post-cutover rows also reverse their own stock/accounting/collection impact."})]})]})}function iF({profile:t,branches:n}){const[a,s]=x.useState("openingStock");return e.jsxs("section",{className:"data-migration-page",children:[e.jsxs("div",{className:"data-migration-hero",children:[e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"VERIXO DATA MIGRATION CENTER"}),e.jsx("h1",{children:"Data Migration"}),e.jsx("p",{children:"Import legacy ERP data safely with Preview â Validate â Map â Import â Reconcile. Original PDFs are parsed in the browser and are not stored in Firebase."})]}),e.jsx("span",{className:"migration-mode",children:"Operational start · Aug 2026"})]}),e.jsxs("div",{className:"migration-type-tabs",children:[e.jsxs("button",{className:a==="openingStock"?"active":"",onClick:()=>s("openingStock"),children:[e.jsx(Tu,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Opening Stock"}),e.jsx("small",{children:"Snapshot quantity + current reference"})]})]}),e.jsxs("button",{className:a==="accountingVoucher"?"active":"",onClick:()=>s("accountingVoucher"),children:[e.jsx(Zs,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Accounting Voucher"}),e.jsx("small",{children:"Debit Voucher PDF"})]})]}),e.jsxs("button",{className:a==="purchase"?"active":"",onClick:()=>s("purchase"),children:[e.jsx(Kw,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Purchase"}),e.jsx("small",{children:"Historical PDF import"})]})]}),e.jsxs("button",{className:a==="sales"?"active":"",onClick:()=>s("sales"),children:[e.jsx(Iu,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Sales"}),e.jsx("small",{children:"Historical PDF import"})]})]}),e.jsxs("button",{className:a==="balances"?"active":"",onClick:()=>s("balances"),children:[e.jsx(t2,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Opening Balances"}),e.jsx("small",{children:"Receivable / Payable"})]})]}),e.jsxs("button",{className:a==="history"?"active":"",onClick:()=>s("history"),children:[e.jsx(Rb,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Import History"}),e.jsx("small",{children:"Batch & reconciliation"})]})]})]}),a==="openingStock"&&e.jsx(S8,{profile:t,branches:n})," ",a==="accountingVoucher"&&e.jsx(JB,{profile:t,branches:n})," ",a==="purchase"&&e.jsx(V8,{profile:t,branches:n})," ",a==="sales"&&e.jsx(rF,{profile:t,branches:n})," ",["balances","history"].includes(a)&&e.jsxs("div",{className:"migration-placeholder",children:[e.jsx(Rb,{size:28}),e.jsx("h2",{children:a==="balances"?"Opening Receivable / Payable":"Import History & Reconciliation"}),e.jsx("p",{children:"This area is reserved so future migration types stay together instead of being scattered across operational modules."}),e.jsx("span",{children:"Not active in this release"})]})]})}const oF="modulepreload",cF=function(t){return"/"+t},OI={},M1=function(n,a,s){let i=Promise.resolve();if(a&&a.length>0){let l=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const m=document.querySelector("meta[property=csp-nonce]"),d=(m==null?void 0:m.nonce)||(m==null?void 0:m.getAttribute("nonce"));i=l(a.map(u=>{if(u=cF(u),u in OI)return;OI[u]=!0;const f=u.endsWith(".css"),g=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${g}`))return;const p=document.createElement("link");if(p.rel=f?"stylesheet":oF,f||(p.as="script"),p.crossOrigin="",p.href=u,d&&p.setAttribute("nonce",d),document.head.appendChild(p),f)return new Promise((y,b)=>{p.addEventListener("load",y),p.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${u}`)))})}))}function c(l){const m=new Event("vite:preloadError",{cancelable:!0});if(m.payload=l,window.dispatchEvent(m),!m.defaultPrevented)throw l}return i.then(l=>{for(const m of l||[])m.status==="rejected"&&c(m.reason);return n().catch(c)})};function ur(t){"@babel/helpers - typeof";return ur=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},ur(t)}var mo=Uint8Array,gc=Uint16Array,d2=Int32Array,mx=new mo([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),px=new mo([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),$1=new mo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),vE=function(t,n){for(var a=new gc(31),s=0;s<31;++s)a[s]=n+=1<<t[s-1];for(var i=new d2(a[30]),s=1;s<30;++s)for(var c=a[s];c<a[s+1];++c)i[c]=c-a[s]<<5|s;return{b:a,r:i}},bE=vE(mx,2),xE=bE.b,O1=bE.r;xE[28]=258,O1[258]=28;var jE=vE(px,0),lF=jE.b,LI=jE.r,L1=new gc(32768);for(var $r=0;$r<32768;++$r){var cu=($r&43690)>>1|($r&21845)<<1;cu=(cu&52428)>>2|(cu&13107)<<2,cu=(cu&61680)>>4|(cu&3855)<<4,L1[$r]=((cu&65280)>>8|(cu&255)<<8)>>1}var Hl=(function(t,n,a){for(var s=t.length,i=0,c=new gc(n);i<s;++i)t[i]&&++c[t[i]-1];var l=new gc(n);for(i=1;i<n;++i)l[i]=l[i-1]+c[i-1]<<1;var m;if(a){m=new gc(1<<n);var d=15-n;for(i=0;i<s;++i)if(t[i])for(var u=i<<4|t[i],f=n-t[i],g=l[t[i]-1]++<<f,p=g|(1<<f)-1;g<=p;++g)m[L1[g]>>d]=u}else for(m=new gc(s),i=0;i<s;++i)t[i]&&(m[i]=L1[l[t[i]-1]++]>>15-t[i]);return m}),Wu=new mo(288);for(var $r=0;$r<144;++$r)Wu[$r]=8;for(var $r=144;$r<256;++$r)Wu[$r]=9;for(var $r=256;$r<280;++$r)Wu[$r]=7;for(var $r=280;$r<288;++$r)Wu[$r]=8;var xg=new mo(32);for(var $r=0;$r<32;++$r)xg[$r]=5;var dF=Hl(Wu,9,0),uF=Hl(Wu,9,1),hF=Hl(xg,5,0),mF=Hl(xg,5,1),uj=function(t){for(var n=t[0],a=1;a<t.length;++a)t[a]>n&&(n=t[a]);return n},nl=function(t,n,a){var s=n/8|0;return(t[s]|t[s+1]<<8)>>(n&7)&a},hj=function(t,n){var a=n/8|0;return(t[a]|t[a+1]<<8|t[a+2]<<16)>>(n&7)},u2=function(t){return(t+7)/8|0},wE=function(t,n,a){return(a==null||a>t.length)&&(a=t.length),new mo(t.subarray(n,a))}
vendor: 6,093 bytes, line 3727
3727,pF=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],il=function(t,n,a){var s=new Error(n||pF[t]);if(s.code=t,Error.captureStackTrace&&Error.captureStackTrace(s,il),!a)throw s;return s},fF=function(t,n,a,s){var i=t.length,c=0;if(!i||n.f&&!n.l)return a||new mo(0);var l=!a,m=l||n.i!=2,d=n.i;l&&(a=new mo(i*3));var u=function(Ee){var Be=a.length;if(Ee>Be){var We=new mo(Math.max(Be*2,Ee));We.set(a),a=We}},f=n.f||0,g=n.p||0,p=n.b||0,y=n.l,b=n.d,N=n.m,w=n.n,C=i*8;do{if(!y){f=nl(t,g,1);var R=nl(t,g+1,3);if(g+=3,R)if(R==1)y=uF,b=mF,N=9,w=5;else if(R==2){var T=nl(t,g,31)+257,G=nl(t,g+10,15)+4,z=T+nl(t,g+5,31)+1;g+=14;for(var H=new mo(z),K=new mo(19),L=0;L<G;++L)K[$1[L]]=nl(t,g+L*3,7);g+=G*3;for(var D=uj(K),M=(1<<D)-1,Z=Hl(K,D,1),L=0;L<z;){var fe=Z[nl(t,g,M)];g+=fe&15;var I=fe>>4;if(I<16)H[L++]=I;else{var q=0,ne=0;for(I==16?(ne=3+nl(t,g,3),g+=2,q=H[L-1]):I==17?(ne=3+nl(t,g,7),g+=3):I==18&&(ne=11+nl(t,g,127),g+=7);ne--;)H[L++]=q}}var ae=H.subarray(0,T),Y=H.subarray(T);N=uj(ae),w=uj(Y),y=Hl(ae,N,1),b=Hl(Y,w,1)}else il(1);else{var I=u2(g)+4,_=t[I-4]|t[I-3]<<8,J=I+_;if(J>i){d&&il(0);break}m&&u(p+_),a.set(t.subarray(I,J),p),n.b=p+=_,n.p=g=J*8,n.f=f;continue}if(g>C){d&&il(0);break}}m&&u(p+131072);for(var je=(1<<N)-1,V=(1<<w)-1,$=g;;$=g){var q=y[hj(t,g)&je],F=q>>4;if(g+=q&15,g>C){d&&il(0);break}if(q||il(2),F<256)a[p++]=F;else if(F==256){$=g,y=null;break}else{var P=F-254;if(F>264){var L=F-257,ue=mx[L];P=nl(t,g,(1<<ue)-1)+xE[L],g+=ue}var me=b[hj(t,g)&V],ge=me>>4;me||il(3),g+=me&15;var Y=lF[ge];if(ge>3){var ue=px[ge];Y+=hj(t,g)&(1<<ue)-1,g+=ue}if(g>C){d&&il(0);break}m&&u(p+131072);var de=p+P;if(p<Y){var Pe=c-Y,Re=Math.min(Y,de);for(Pe+p<0&&il(3);p<Re;++p)a[p]=s[Pe+p]}for(;p<de;++p)a[p]=a[p-Y]}}n.l=y,n.p=$,n.b=p,n.f=f,y&&(f=1,n.m=N,n.d=b,n.n=w)}while(!f);return p!=a.length&&l?wE(a,0,p):a.subarray(0,p)},pd=function(t,n,a){a<<=n&7;var s=n/8|0;t[s]|=a,t[s+1]|=a>>8},Cf=function(t,n,a){a<<=n&7;var s=n/8|0;t[s]|=a,t[s+1]|=a>>8,t[s+2]|=a>>16},mj=function(t,n){for(var a=[],s=0;s<t.length;++s)t[s]&&a.push({s,f:t[s]});var i=a.length,c=a.slice();if(!i)return{t:SE,l:0};if(i==1){var l=new mo(a[0].s+1);return l[a[0].s]=1,{t:l,l:1}}a.sort(function(J,T){return J.f-T.f}),a.push({s:-1,f:25001});var m=a[0],d=a[1],u=0,f=1,g=2;for(a[0]={s:-1,f:m.f+d.f,l:m,r:d};f!=i-1;)m=a[a[u].f<a[g].f?u++:g++],d=a[u!=f&&a[u].f<a[g].f?u++:g++],a[f++]={s:-1,f:m.f+d.f,l:m,r:d};for(var p=c[0].s,s=1;s<i;++s)c[s].s>p&&(p=c[s].s);var y=new gc(p+1),b=B1(a[f-1],y,0);if(b>n){var s=0,N=0,w=b-n,C=1<<w;for(c.sort(function(T,G){return y[G.s]-y[T.s]||T.f-G.f});s<i;++s){var R=c[s].s;if(y[R]>n)N+=C-(1<<b-y[R]),y[R]=n;else break}for(N>>=w;N>0;){var I=c[s].s;y[I]<n?N-=1<<n-y[I]++-1:++s}for(;s>=0&&N;--s){var _=c[s].s;y[_]==n&&(--y[_],++N)}b=n}return{t:new mo(y),l:b}},B1=function(t,n,a){return t.s==-1?Math.max(B1(t.l,n,a+1),B1(t.r,n,a+1)):n[t.s]=a},BI=function(t){for(var n=t.length;n&&!t[--n];);for(var a=new gc(++n),s=0,i=t[0],c=1,l=function(d){a[s++]=d},m=1;m<=n;++m)if(t[m]==i&&m!=n)++c;else{if(!i&&c>2){for(;c>138;c-=138)l(32754);c>2&&(l(c>10?c-11<<5|28690:c-3<<5|12305),c=0)}else if(c>3){for(l(i),--c;c>6;c-=6)l(8304);c>2&&(l(c-3<<5|8208),c=0)}for(;c--;)l(i);c=1,i=t[m]}return{c:a.subarray(0,s),n}},Af=function(t,n){for(var a=0,s=0;s<n.length;++s)a+=t[s]*n[s];return a},NE=function(t,n,a){var s=a.length,i=u2(n+2);t[i]=s&255,t[i+1]=s>>8,t[i+2]=t[i]^255,t[i+3]=t[i+1]^255;for(var c=0;c<s;++c)t[i+c+4]=a[c];return(i+4+s)*8},FI=function(t,n,a,s,i,c,l,m,d,u,f){pd(n,f++,a),++i[256];for(var g=mj(i,15),p=g.t,y=g.l,b=mj(c,15),N=b.t,w=b.l,C=BI(p),R=C.c,I=C.n,_=BI(N),J=_.c,T=_.n,G=new gc(19),z=0;z<R.length;++z)++G[R[z]&31];for(var z=0;z<J.length;++z)++G[J[z]&31];for(var H=mj(G,7),K=H.t,L=H.l,D=19;D>4&&!K[$1[D-1]];--D);var M=u+5<<3,Z=Af(i,Wu)+Af(c,xg)+l,fe=Af(i,p)+Af(c,N)+l+14+3*D+Af(G,K)+2*G[16]+3*G[17]+7*G[18];if(d>=0&&M<=Z&&M<=fe)return NE(n,f,t.subarray(d,d+u));var q,ne,ae,Y;if(pd(n,f,1+(fe<Z)),f+=2,fe<Z){q=Hl(p,y,0),ne=p,ae=Hl(N,w,0),Y=N;var je=Hl(K,L,0);pd(n,f,I-257),pd(n,f+5,T-1),pd(n,f+10,D-4),f+=14;for(var z=0;z<D;++z)pd(n,f+3*z,K[$1[z]]);f+=3*D;for(var V=[R,J],$=0;$<2;++$)for(var F=V[$],z=0;z<F.length;++z){var P=F[z]&31;pd(n,f,je[P]),f+=K[P],P>15&&(pd(n,f,F[z]>>5&127),f+=F[z]>>12)}}else q=dF,ne=Wu,ae=hF,Y=xg;for(var z=0;z<m;++z){var ue=s[z];if(ue>255){var P=ue>>18&31;Cf(n,f,q[P+257]),f+=ne[P+257],P>7&&(pd(n,f,ue>>23&31),f+=mx[P]);var me=ue&31;Cf(n,f,ae[me]),f+=Y[me],me>3&&(Cf(n,f,ue>>5&8191),f+=px[me])}else Cf(n,f,q[ue]),f+=ne[ue]}return Cf(n,f,q[256]),f+ne[256]},gF=new d2([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),SE=new mo(0),yF=function(t,n,a,s,i,c){var l=c.z||t.length,m=new mo(s+l+5*(1+Math.ceil(l/7e3))+i),d=m.subarray(s,m.length-i),u=c.l,f=(c.r||0)&7;if(n){f&&(d[0]=c.r>>3);for(var g=gF[n-1],p=g>>13,y=g&8191,b=(1<<a)-1,N=c.p||new gc(32768),w=c.h||new gc(b+1),C=Math.ceil(a/3),R=2*C,I=function(it){return(t[it]^t[it+1]<<C^t[it+2]<<R)&b},_=new d2(25e3),J=new gc(288),T=new gc(32),G=0,z=0,H=c.i||0,K=0,L=c.w||0,D=0;H+2<l;++H){var M=I(H),Z=H&32767,fe=w[M];if(N[Z]=fe,w[M]=Z,L<=H){var q=l-H;if((G>7e3||K>24576)&&(q>423||!u)){f=FI(t,d,0,_,J,T,z,K,D,H-D,f),K=G=z=0,D=H;for(var ne=0;ne<286;++ne)J[ne]=0;for(var ne=0;ne<30;++ne)T[ne]=0}var ae=2,Y=0,je=y,V=Z-fe&32767;if(q>2&&M==I(H-V))for(var $=Math.min(p,q)-1,F=Math.min(32767,H),P=Math.min(258,q);V<=F&&--je&&Z!=fe;){if(t[H+ae]==t[H+ae-V]){for(var ue=0;ue<P&&t[H+ue]==t[H+ue-V];++ue);if(ue>ae){if(ae=ue,Y=V,ue>$)break;for(var me=Math.min(V,ue-2),ge=0,ne=0;ne<me;++ne){var de=H-V+ne&32767,Pe=N[de],Re=de-Pe&32767;Re>ge&&(ge=Re,fe=de)}}}Z=fe,fe=N[Z],V+=Z-fe&32767}if(Y){_[K++]=268435456|O1[ae]<<18|LI[Y];var Ee=O1[ae]&31,Be=LI[Y]&31;z+=mx[Ee]+px[Be],++J[257+Ee],++T[Be],L=H+ae,++G}else _[K++]=t[H],++J[t[H]]}}for(H=Math.max(H,L);H<l;++H)_[K++]=t[H],++J[t[H]];f=FI(t,d,u,_,J,T,z,K,D,H-D,f),u||(c.r=f&7|d[f/8|0]<<3,f-=7,c.h=w,c.p=N,c.i=H,c.w=L)}else{for(var H=c.w||0;H<l+u;H+=65535){var We=H+65535;We>
3727=l&&(d[f/8|0]=u,We=l),f=NE(d,f+1,t.subarray(H,We))}c.i=l}return wE(m,0,s+u2(f)+i)},CE=function(){var t=1,n=0;return{p:function(a){for(var s=t,i=n,c=a.length|0,l=0;l!=c;){for(var m=Math.min(l+2655,c);l<m;++l)i+=s+=a[l];s=(s&65535)+15*(s>>16),i=(i&65535)+15*(i>>16)}t=s,n=i},d:function(){return t%=65521,n%=65521,(t&255)<<24|(t&65280)<<8|(n&255)<<8|n>>8}}},vF=function(t,n,a,s,i){if(!i&&(i={l:1},n.dictionary)){var c=n.dictionary.subarray(-32768),l=new mo(c.length+t.length);l.set(c),l.set(t,c.length),t=l,i.w=c.length}return yF(t,n.level==null?6:n.level,n.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(t.length)))*1.5):20:12+n.mem,a,s,i)},AE=function(t,n,a){for(;a;++n)t[n]=a,a>>>=8},bF=function(t,n){var a=n.level,s=a==0?0:a<6?1:a==9?3:2;if(t[0]=120,t[1]=s<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=CE();i.p(n.dictionary),AE(t,2,i.d())}},xF=function(t,n){return((t[0]&15)!=8||t[0]>>4>7||(t[0]<<8|t[1])%31)&&il(6,"invalid zlib data"),(t[1]>>5&1)==1&&il(6,"invalid zlib data: "+(t[1]&32?"need":"unexpected")+" dictionary"),(t[1]>>3&4)+2};function F1(t,n){n||(n={});var a=CE();a.p(t);var s=vF(t,n,n.dictionary?6:2,4);return bF(s,n),AE(s,s.length-4,a.d()),s}function jF(t,n){return fF(t.subarray(xF(t),-4),{i:2},n,n)}var wF=typeof TextDecoder<"u"&&new TextDecoder,NF=0;try{wF.decode(SE,{stream:!0}),NF=1}catch{}var ns=(function(){return typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this})();function pj(){ns.console&&typeof ns.console.log=="function"&&ns.console.log.apply(ns.console,arguments)}var Ar={log:pj,warn:function(t){ns.console&&(typeof ns.console.warn=="function"?ns.console.warn.apply(ns.console,arguments):pj.call(null,arguments))},error:function(t){ns.console&&(typeof ns.console.error=="function"?ns.console.error.apply(ns.console,arguments):pj(t))}};function fj(t,n,a){var s=new XMLHttpRequest;s.open("GET",t),s.responseType="blob",s.onload=function(){wh(s.response,n,a)},s.onerror=function(){Ar.error("could not download file")},s.send()}function UI(t){var n=new XMLHttpRequest;n.open("HEAD",t,!1);try{n.send()}catch{}return n.status>=200&&n.status<=299}function Dv(t){try{t.dispatchEvent(new MouseEvent("click"))}catch{var n=document.createEvent("MouseEvents");
3727n.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),t.dispatchEvent(n)}}var Xf,U1,wh=ns.saveAs||((typeof window>"u"?"undefined":ur(window))!=="object"||window!==ns?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(t,n,a){var s=ns.URL||ns.webkitURL,i=document.createElement("a");n=n||t.name||"download",i.download=n,i.rel="noopener",typeof t=="string"?(i.href=t,i.origin!==location.origin?UI(i.href)?fj(t,n,a):Dv(i,i.target="_blank"):Dv(i)):(i.href=s.createObjectURL(t),setTimeout((function(){s.revokeObjectURL(i.href)}),4e4),setTimeout((function(){Dv(i)}),0))}:"msSaveOrOpenBlob"in navigator?function(t,n,a){if(n=n||t.name||"download",typeof t=="string")if(UI(t))fj(t,n,a);else{var s=document.createElement("a");s.href=t,s.target="_blank",setTimeout((function(){Dv(s)}))}else navigator.msSaveOrOpenBlob((function(i,c){return c===void 0?c={autoBom:!1}:ur(c)!=="object"&&(Ar.warn("Deprecated: Expected third argument to be a object"),c={autoBom:!c}),c.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(i.type)?new Blob(["\uFEFF",i],{type:i.type}):i})(t,a),n)}:function(t,n,a,s){if((s=s||open("","_blank"))&&(s.document.title=s.document.body.innerText="downloading..."),typeof t=="string")return fj(t,n,a);var i=t.type==="application/octet-stream",c=/constructor/i.test(ns.HTMLElement)||ns.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||i&&c)&&(typeof FileReader>"u"?"undefined":ur(FileReader))==="object"){var m=new FileReader;m.onloadend=function(){var f=m.result;f=l?f:f.replace(/^data:[^;]*;/,"data:attachment/file;"),s?s.location.href=f:location=f,s=null},m.readAsDataURL(t)}else{var d=ns.URL||ns.webkitURL,u=d.createObjectURL(t);
3727s?s.location=u:location.href=u,s=null,setTimeout((function(){d.revokeObjectURL(u)}),4e4)}});/** 3728 * A class to parse color values 3729 * @author Stoyan Stefanov <[email protected]> 3730 * {@link http://www.phpied.com/rgb-color-parser-in-javascript/} 3731 * @license Use it if you like it 3732 */function IE(t){var n;t=t||"",this.ok=!1,t.charAt(0)=="#"&&(t=t.substr(1,6)),t={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee9
37320",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"}[t=(t=t.replace(/ /g,"")).toLowerCase()]||t;for(var a=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(m){return[parseInt(m[1]),parseInt(m[2]),parseInt(m[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(m){return[parseInt(m[1],16),parseInt(m[2],16),parseInt(m[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(m){return[parseInt(m[1]+m[1],16),parseInt(m[2]+m[2],16),parseInt(m[3]+m[3],16)]}}],s=0;s<a.length;s++){var i=a[s].re,c=a[s].process,l=i.exec(t);l&&(n=c(l),this.r=n[0],this.g=n[1],this.b=n[2],this.ok=!0)}this.r=this.r<0||isNaN(this.r)?0:this.r>255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var m=this.r.toString(16),d=this.g.toString(16),u=this.b.toString(16);return m.length==1&&(m="0"+m),d.length==1&&(d="0"+d),u.length==1&&(u="0"+u),"#"+m+d+u}}/** 3733 * @license 3734 * Joseph Myers does not specify a particular license for his work. 3735 * 3736 * Author: Joseph Myers 3737 * Accessed from: http://www.myersdaily.org/joseph/javascript/md5.js 3738 * 3739 * Modified by: Owen Leong 3740 */function gj(t,n){var a=t[0],s=t[1],i=t[2],c=t[3];a=oo(a,s,i,c,n[0],7,-680876936),c=oo(c,a,s,i,n[1],12,-389564586),i=oo(i,c,a,s,n[2],17,606105819),s=oo(s,i,c,a,n[3],22,-1044525330),a=oo(a,s,i,c,n[4],7,-176418897),c=oo(c,a,s,i,n[5],12,1200080426),i=oo(i,c,a,s,n[6],17,-1473231341),s=oo(s,i,c,a,n[7],22,-45705983),a=oo(a,s,i,c,n[8],7,1770035416),c=oo(c,a,s,i,n[9],12,-1958414417),i=oo(i,c,a,s,n[10],17,-42063),s=oo(s,i,c,a,n[11],22,-1990404162),a=oo(a,s,i,c,n[12],7,1804603682),c=oo(c,a,s,i,n[13],12,-40341101),i=oo(i,c,a,s,n[14],17,-1502002290),a=co(a,s=oo(s,i,c,a,n[15],22,1236535329),i,c,n[1],5,-165796510),c=co(c,a,s,i,n[6],9,-1069501632),i=co(i,c,a,s,n[11],14,643717713),s=co(s,i,c,a,n[0],20,-373897302),a=co(a,s,i,c,n[5],5,-701558691),c=co(c,a,s,i,n[10],9,38016083),i=co(i,c,a,s,n[15],14,-660478335),s=co(s,i,c,a,n[4],20,-405537848),a=co(a,s,i,c,n[9],5,568446438),c=co(c,a,s,i,n[14],9,-1019803690),i=co(i,c,a,s,n[3],14,-187363961),s=co(s,i,c,a,n[8],20,1163531501),a=co(a,s,i,c,n[13],5,-1444681467),c=co(c,a,s,i,n[2],9,-51403784),i=co(i,c,a,s,n[7],14,1735328473),a=lo(a,s=co(s,i,c,a,n[12],20,-1926607734),i,c,n[5],4,-378558),c=lo(c,a,s,i,n[8],11,-2022574463),i=lo(i,c,a,s,n[11],16,1839030562),s=lo(s,i,c,a,n[14],23,-35309556),a=lo(a,s,i,c,n[1],4,-1530992060),c=lo(c,a,s,i,n[4],11,1272893353),i=lo(i,c,a,s,n[7],16,-155497632),s=lo(s,i,c,a,n[10],23,-1094730640),a=lo(a,s,i,c,n[13],4,681279174),c=lo(c,a,s,i,n[0],11,-358537222),i=lo(i,c,a,s,n[3],16,-722521979),s=lo(s,i,c,a,n[6],23,76029189),a=lo(a,s,i,c,n[9],4,-640364487),c=lo(c,a,s,i,n[12],11,-421815835),i=lo(i,c,a,s,n[15],16,530742520),a=uo(a,s=lo(s,i,c,a,n[2],23,-995338651),i,c,n[0],6,-198630844),c=uo(c,a,s,i,n[7],10,1126891415),i=uo(i,c,a,s,n[14],15,-1416354905),s=uo(s,i,c,a,n[5],21,-57434055),a=uo(a,s,i,c,n[12],6,1700485571),c=uo(c,a,s,i,n[3],10,-1894986606),i=uo(i,c,a,s,n[10],15,-1051523),s=uo(s,i,c,a,n[1],21,-2054922799),a=uo(a,s,i,c,n[8],6,1873313359),c=uo(c,a,s,i,n[15],10,-30611744),i=uo(i,c,a,s,n[6],15,-1560198380),s=uo(s,i,c,a,n[13],21,1309151649),a=uo(a,s,i,c,n[4],6,-145523070),c=uo(c,a,s,i,n[11],10,-1120210379),i=uo(i,c,a,s,n[2],
vendor: 5,375 bytes, lines 3740-3757
374015,718787259),s=uo(s,i,c,a,n[9],21,-343485551),t[0]=_u(a,t[0]),t[1]=_u(s,t[1]),t[2]=_u(i,t[2]),t[3]=_u(c,t[3])}function fx(t,n,a,s,i,c){return n=_u(_u(n,t),_u(s,c)),_u(n<<i|n>>>32-i,a)}function oo(t,n,a,s,i,c,l){return fx(n&a|~n&s,t,n,i,c,l)}function co(t,n,a,s,i,c,l){return fx(n&s|a&~s,t,n,i,c,l)}function lo(t,n,a,s,i,c,l){return fx(n^a^s,t,n,i,c,l)}function uo(t,n,a,s,i,c,l){return fx(a^(n|~s),t,n,i,c,l)}function _E(t){var n,a=t.length,s=[1732584193,-271733879,-1732584194,271733878];for(n=64;n<=t.length;n+=64)gj(s,SF(t.substring(n-64,n)));t=t.substring(n-64);var i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(n=0;n<t.length;n++)i[n>>2]|=t.charCodeAt(n)<<(n%4<<3);if(i[n>>2]|=128<<(n%4<<3),n>55)for(gj(s,i),n=0;n<16;n++)i[n]=0;return i[14]=8*a,gj(s,i),s}function SF(t){var n,a=[];for(n=0;n<64;n+=4)a[n>>2]=t.charCodeAt(n)+(t.charCodeAt(n+1)<<8)+(t.charCodeAt(n+2)<<16)+(t.charCodeAt(n+3)<<24);return a}Xf=ns.atob.bind(ns),U1=ns.btoa.bind(ns);var zI="0123456789abcdef".split("");function CF(t){for(var n="",a=0;a<4;a++)n+=zI[t>>8*a+4&15]+zI[t>>8*a&15];return n}function AF(t){return String.fromCharCode((255&t)>>0,(65280&t)>>8,(16711680&t)>>16,(4278190080&t)>>24)}function z1(t){return _E(t).map(AF).join("")}var IF=(function(t){for(var n=0;n<t.length;n++)t[n]=CF(t[n]);return t.join("")})(_E("hello"))!="5d41402abc4b2a76b9719d911017c592";function _u(t,n){if(IF){var a=(65535&t)+(65535&n);return(t>>16)+(n>>16)+(a>>16)<<16|65535&a}return t+n&4294967295}/** 3741 * @license 3742 * FPDF is released under a permissive license: there is no usage restriction. 3743 * You may embed it freely in your application (commercial or not), with or 3744 * without modifications. 3745 * 3746 * Reference: http://www.fpdf.org/en/script/script37.php 3747 */function q1(t,n){var a,s,i,c;if(t!==a){for(var l=(i=t,c=1+(256/t.length>>0),new Array(c+1).join(i)),m=[],d=0;d<256;d++)m[d]=d;var u=0;for(d=0;d<256;d++){var f=m[d];u=(u+f+l.charCodeAt(d))%256,m[d]=m[u],m[u]=f}a=t,s=m}else m=s;var g=n.length,p=0,y=0,b="";for(d=0;d<g;d++)y=(y+(f=m[p=(p+1)%256]))%256,m[p]=m[y],m[y]=f,l=m[(m[p]+m[y])%256],b+=String.fromCharCode(n.charCodeAt(d)^l);return b}/** 3748 * @license 3749 * Licensed under the MIT License. 3750 * http://opensource.org/licenses/mit-license 3751 * Author: Owen Leong (@owenl131) 3752 * Date: 15 Oct 2020 3753 * References: 3754 * https://www.cs.cmu.edu/~dst/Adobe/Gallery/anon21jul01-pdf-encryption.txt 3755 * https://github.com/foliojs/pdfkit/blob/master/lib/security.js 3756 * http://www.fpdf.org/en/script/script37.php 3757 */var qI={print:4,modify:8,copy:16,"annot-forms":32};function Jm(t,n,a,s){this.v=1,this.r=2;var i=192;t.forEach((function(m){if(qI.perm!==void 0)throw new Error("Invalid permission: "+m);i+=qI[m]})),this.padding="(¿N^NuÂAd\0NVÿú�\b..\0¶Ãh>Â/\f©þdSiz";var c=(n+this.padding).substr(0,32),l=(a+this.padding).substr(0,32);this.O=this.processOwnerPassword(c,l),this.P=-(1+(255^i)),this.encryptionKey=z1(c+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(s)).substr(0,5),this.U=q1(this.encryptionKey,this.padding)}function Km(t){if(/[^\u0000-\u00ff]/.test(t))throw new Error("Invalid PDF Name Object: "+t+", Only accept ASCII characters.");for(var n="",a=t.length,s=0;s<a;s++){var i=t.charCodeAt(s);i<33||i===35||i===37||i===40||i===41||i===47||i===60||i===62||i===91||i===93||i===123||i===125||i>126?n+="#"+("0"+i.toString(16)).slice(-2):n+=t[s]}return n}function VI(t){if(ur(t)!=="object")throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)");var n={};this.subscribe=function(a,s,i){if(i=i||!1,typeof a!="string"||typeof s!="function"||typeof i!="boolean")throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)");n.hasOwnProperty(a)||(n[a]={});var c=Math.random().toString(35);return n[a][c]=[s,!!i],c},this.unsubscribe=function(a){for(var s in n)if(n[s][a])return delete n[s][a],Object.keys(n[s]).length===0&&delete n[s],!0;return!1},this.publish=function(a){if(n.hasOwnProperty(a)){var s=Array.prototype.slice.call(arguments,1),i=[];for(var c in n[a]){var l=n[a][c];try{l[0].apply(t,s)}catch(m){ns.console&&Ar.error("jsPDF PubSub Error",m.message,m)}l[1]&&i.push(c)}i.length&&i.forEach(this.unsubscribe)}},this.getTopics=function(){return n}}function jg(t){if(!(this instanceof jg))return new jg(t);var n="opacity,stroke-opacity".split(",");for(var a in t)t.hasOwnProperty(a)&&n.indexOf(a)>=0&&(this[a]=t[a]);this.id="",this.objectNumber=-1}function kE(t,n){this.gState=t,this.matrix=n,this.id="",this.objectNumber=-1}function Cu(t,n,a,s,i){if(!(this instanceof Cu))return new Cu(t,n,a,s,i);this.type=t==="axial"?2:3,this.coords=n,this.colors=a,kE.call(this,s,i)}function Ih(t,n,a,s,i){if(!(this instanceof Ih))return new Ih(t,n,a,s,i);this.boundingBox=t,this.xStep=n,this.yStep=a,this.stream="",this.cloneIndex=0,kE.call(this,s,i)}function Ra(t){var n,a=typeof arguments[0]=="string"?arguments[0]:"p",s=arguments[1],i=arguments[2],c=arguments[3],l=[],m=1,d=16,u="S",f=null;ur(t=t||{})==="object"&&(a=t.orientation,s=t.unit||s,i=t.format||i,c=t.compress||t.compressPdf||c,(f=t.encryption||null)!==null&&(f.userPassword=f.userPassword||"",f.ownerPassword=f.ownerPassword||"",f.userPermissions=f.userPermissions||[]),m=typeof t.userUnit=="number"?Math.abs(t.userUnit):1,t.precision!==void 0&&(n=t.precision),t.floatPrecision!==void 0&&(d=t.floatPrecision),u=t.defaultPathOperation||"S"),l=t.filters||(c===!0?["FlateEncode"]:l),s=s||"mm",a=(""+(a||"P")).toLowerCase();
vendor: 1,069 bytes, line 3757
3757var g=t.putOnlyUsedFonts||!1,p={},y={internal:{},__private__:{}};y.__private__.PubSub=VI;var b="1.3",N=y.__private__.getPdfVersion=function(){return b};y.__private__.setPdfVersion=function(U){b=U};var w={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};y.__private__.getPageFormats=function(){return w};
vendor: 12,994 bytes, lines 3757-3758
3757var C=y.__private__.getPageFormat=function(U){return w[U]};i=i||"a4";var R={COMPAT:"compat",ADVANCED:"advanced"},I=R.COMPAT;function _(){this.saveGraphicsState(),ee(new rt(le,0,0,-le,0,_o()*le).toString()+" cm"),this.setFontSize(this.getFontSize()/le),u="n",I=R.ADVANCED}function J(){this.restoreGraphicsState(),u="S",I=R.COMPAT}var T=y.__private__.combineFontStyleAndFontWeight=function(U,Ue){if(U=="bold"&&Ue=="normal"||U=="bold"&&Ue==400||U=="normal"&&Ue=="italic"||U=="bold"&&Ue=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Ue&&(U=Ue==400||Ue==="normal"?U==="italic"?"italic":"normal":Ue!=700&&Ue!=="bold"||U!=="normal"?(Ue==700?"bold":Ue)+""+U:"bold"),U};y.advancedAPI=function(U){var Ue=I===R.COMPAT;return Ue&&_.call(this),typeof U!="function"||(U(this),Ue&&J.call(this)),this},y.compatAPI=function(U){var Ue=I===R.ADVANCED;return Ue&&J.call(this),typeof U!="function"||(U(this),Ue&&_.call(this)),this},y.isAdvancedAPI=function(){return I===R.ADVANCED};var G,z=function(U){if(I!==R.ADVANCED)throw new Error(U+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},H=y.roundToPrecision=y.__private__.roundToPrecision=function(U,Ue){var yt=n||Ue;if(isNaN(U)||isNaN(yt))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return U.toFixed(yt).replace(/0+$/,"")};G=y.hpf=y.__private__.hpf=typeof d=="number"?function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.hpf");return H(U,d)}:d==="smart"?function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.hpf");return H(U,U>-1&&U<1?16:5)}:function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.hpf");return H(U,16)};var K=y.f2=y.__private__.f2=function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.f2");return H(U,2)},L=y.__private__.f3=function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.f3");return H(U,3)},D=y.scale=y.__private__.scale=function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.scale");return I===R.COMPAT?U*le:I===R.ADVANCED?U:void 0},M=function(U){return I===R.COMPAT?_o()-U:I===R.ADVANCED?U:void 0},Z=function(U){return D(M(U))};y.__private__.setPrecision=y.setPrecision=function(U){typeof parseInt(U,10)=="number"&&(n=parseInt(U,10))};var fe,q="00000000000000000000000000000000",ne=y.__private__.getFileId=function(){return q},ae=y.__private__.setFileId=function(U){return q=U!==void 0&&/^[a-fA-F0-9]{32}$/.test(U)?U.toUpperCase():q.split("").map((function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))})).join(""),f!==null&&(Ma=new Jm(f.userPermissions,f.userPassword,f.ownerPassword,q)),q};y.setFileId=function(U){return ae(U),this},y.getFileId=function(){return ne()};var Y=y.__private__.convertDateToPDFDate=function(U){var Ue=U.getTimezoneOffset(),yt=Ue<0?"+":"-",kt=Math.floor(Math.abs(Ue/60)),an=Math.abs(Ue%60),Cn=[yt,P(kt),"'",P(an),"'"].join("");return["D:",U.getFullYear(),P(U.getMonth()+1),P(U.getDate()),P(U.getHours()),P(U.getMinutes()),P(U.getSeconds()),Cn].join("")},je=y.__private__.convertPDFDateToDate=function(U){var Ue=parseInt(U.substr(2,4),10),yt=parseInt(U.substr(6,2),10)-1,kt=parseInt(U.substr(8,2),10),an=parseInt(U.substr(10,2),10),Cn=parseInt(U.substr(12,2),10),Qn=parseInt(U.substr(14,2),10);return new Date(Ue,yt,kt,an,Cn,Qn,0)},V=y.__private__.setCreationDate=function(U){var Ue;if(U===void 0&&(U=new Date),U instanceof Date)Ue=Y(U);else{if(!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(U))throw new Error("Invalid argument passed to jsPDF.setCreationDate");Ue=U}return fe=Ue},$=y.__private__.getCreationDate=function(U){var Ue=fe;return U==="jsDate"&&(Ue=je(fe)),Ue};y.setCreationDate=function(U){return V(U),this},y.getCreationDate=function(U){return $(U)};var F,P=y.__private__.padd2=function(U){return("0"+parseInt(U)).slice(-2)},ue=y.__private__.padd2Hex=function(U){return("00"+(U=U.toString())).substr(U.length)},me=0,ge=[],de=[],Pe=0,Re=[],Ee=[],Be=!1,We=de,it=function(){me=0,Pe=0,de=[],ge=[],Re=[],Gt=Sn(),$t=Sn()};y.__private__.setCustomOutputDestination=function(U){Be=!0,We=U};var _e=function(U){Be||(We=U)};y.__private__.resetCustomOutputDestination=function(){Be=!1,We=de};var ee=y.__private__.out=function(U){return U=U.toString(),Pe+=U.length+1,We.push(U),We},qe=y.__private__.write=function(U){return ee(arguments.length===1?U.toString():Array.prototype.join.call(arguments," "))},se=y.__private__.getArrayBuffer=function(U){for(var Ue=U.length,yt=new ArrayBuffer(Ue),kt=new Uint8Array(yt);Ue--;)kt[Ue]=U.charCodeAt(Ue);return yt},pe=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];y.__private__.getStandardFonts=function(){return pe};var Se=t.fontSize||16;y.__private__.setFontSize=y.setFontSize=function(U){return Se=I===R.ADVANCED?U/le:U,this};var Me,ot=y.__private__.getFontSize=y.getFontSize=function(){return I===R.COMPAT?Se:Se*le},wt=t.R2L||!1;y.__private__.setR2L=y.setR2L=function(U){return wt=U,this},y.__private__.getR2L=y.getR2L=function(){return wt};var ct,Ce=y.__private__.setZoomMode=function(U){var Ue=[void 0,null,"fullwidth","fullheight","fullpage","original"];if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(U))Me=U;else if(isNaN(U)){if(Ue.indexOf(U)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+U+'" is not recognized.');Me=U}else Me=parseInt(U,10)};y.__private__.getZoomMode=function(){return Me};var De,Te=y.__private__.setPageMode=function(U){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(U)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+U+'" is not recognized.');ct=U};y.__private__.getPageMode=function(){return ct};var ce=y.__private__.setLayoutMode=function(U){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(U)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+U+'" is not recognized.');De=U};y.__private__.getLayoutMode=function(){return De},y.__private__.setDisplayMode=y.setDisplayMode=function(U,Ue,yt){return Ce(U),ce(Ue),Te(yt),this};var Ye={title:"",subject:"",author:"",keywords:"",creator:""};y.__private__.getDocumentProperty=function(U){if(Object.keys(Ye).indexOf(U)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return Ye[U]},y.__private__.getDocumentProperties=function(){return Ye},y.__private__.setDocumentProperties=y.setProperties=y.setDocumentProperties=function(U){for(var Ue in Ye)Ye.hasOwnProperty(Ue)&&U[Ue]&&(Ye[Ue]=U[Ue]);return this},y.__private__.setDocumentProperty=function(U,Ue){if(Object.keys(Ye).indexOf(U)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return Ye[U]=Ue};var Je,le,nt,xt,te,Ge={},pt={},$e=[],st={},Nt={},be={},jt={},bt=null,tn=0,B=[],xe=new VI(y),tt=t.hotfixes||[],ht={},dt={},we=[],rt=function U(Ue,yt,kt,an,Cn,Qn){if(!(this instanceof U))return new U(Ue,yt,kt,an,Cn,Qn);isNaN(Ue)&&(Ue=1),isNaN(yt)&&(yt=0),isNaN(kt)&&(kt=0),isNaN(an)&&(an=1),isNaN(Cn)&&(Cn=0),isNaN(Qn)&&(Qn=0),this._matrix=[Ue,yt,kt,an,Cn,Qn]};Object.defineProperty(rt.prototype,"sx",{get:function(){return this._matrix[0]},set:function(U){this._matrix[0]=U}}),Object.defineProperty(rt.prototype,"shy",{get:function(){return this._matrix[1]},set:function(U){this._matrix[1]=U}}),Object.defineProperty(rt.prototype,"shx",{get:function(){return this._matrix[2]},set:function(U){this._matrix[2]=U}}),Object.defineProperty(rt.prototype,"sy",{get:function(){return this._matrix[3]},set:function(U){this._matrix[3]=U}}),Object.defineProperty(rt.prototype,"tx",{get:function(){return this._matrix[4]},set:function(U){this._matrix[4]=U}}),Object.defineProperty(rt.prototype,"ty",{get:function(){return this._matrix[5]},set:function(U){this._matrix[5]=U}}),Object.defineProperty(rt.prototype,"a",{get:function(){return this._matrix[0]},set:function(U){this._matrix[0]=U}}),Object.defineProperty(rt.prototype,"b",{get:function(){return this._matrix[1]},set:function(U){this._matrix[1]=U}}),Object.defineProperty(rt.prototype,"c",{get:function(){return this._matrix[2]},set:function(U){this._matrix[2]=U}}),Object.defineProperty(rt.prototype,"d",{get:function(){return this._matrix[3]},set:function(U){this._matrix[3]=U}}),Object.defineProperty(rt.prototype,"e",{get:function(){return this._matrix[4]},set:function(U){this._matrix[4]=U}}),Object.defineProperty(rt.prototype,"f",{get:function(){return this._matrix[5]},set:function(U){this._matrix[5]=U}}),Object.defineProperty(rt.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(rt.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(rt.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(rt.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),rt.prototype.join=function(U){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(G).join(U)},rt.prototype.multiply=function(U){var Ue=U.sx*this.sx+U.shy*this.shx,yt=U.sx*this.shy+U.shy*this.sy,kt=U.shx*this.sx+U.sy*this.shx,an=U.shx*this.shy+U.sy*this.sy,Cn=U.tx*this.sx+U.ty*this.shx+this.tx,Qn=U.tx*this.shy+U.ty*this.sy+this.ty;return new rt(Ue,yt,kt,an,Cn,Qn)},rt.prototype.decompose=function(){var U=this.sx,Ue=this.shy,yt=this.shx,kt=this.sy,an=this.tx,Cn=this.ty,Qn=Math.sqrt(U*U+Ue*Ue),E=(U/=Qn)*yt+(Ue/=Qn)*kt;yt-=U*E,kt-=Ue*E;var Q=Math.sqrt(yt*yt+kt*kt);return E/=Q,U*(kt/=Q)<Ue*(yt/=Q)&&(U=-U,Ue=-Ue,E=-E,Qn=-Qn),{scale:new rt(Qn,0,0,Q,0,0),translate:new rt(1,0,0,1,an,Cn),rotate:new rt(U,Ue,-Ue,U,0,0),skew:new rt(1,0,E,1,0,0)}},rt.prototype.toString=function(U){return this.join(" ")},rt.prototype.inversed=function(){var U=this.sx,Ue=this.shy,yt=this.shx,kt=this.sy,an=this.tx,Cn=this.ty,Qn=1/(U*kt-Ue*yt),E=kt*Qn,Q=-Ue*Qn,Ie=-yt*Qn,Le=U*Qn;return new rt(E,Q,Ie,Le,-E*an-Ie*Cn,-Q*an-Le*Cn)},rt.prototype.applyToPoint=function(U){var Ue=U.x*this.sx+U.y*this.shx+this.tx,yt=U.x*this.shy+U.y*this.sy+this.ty;return new Zo(Ue,yt)},rt.prototype.applyToRectangle=function(U){var Ue=this.applyToPoint(U),yt=this.applyToPoint(new Zo(U.x+U.w,U.y+U.h));return new qc(Ue.x,Ue.y,yt.x-Ue.x,yt.y-Ue.y)},rt.prototype.clone=function(){var U=this.sx,Ue=this.shy,yt=this.shx,kt=this.sy,an=this.tx,Cn=this.ty;return new rt(U,Ue,yt,kt,an,Cn)},y.Matrix=rt;var St=y.matrixMult=function(U,Ue){return Ue.multiply(U)},Qt=new rt(1,0,0,1,0,0);y.unitMatrix=y.identityMatrix=Qt;var gn=function(U,Ue){if(!Nt[U]){var yt=(Ue instanceof Cu?"Sh":"P")+(Object.keys(st).length+1).toString(10);Ue.id=yt,Nt[U]=yt,st[yt]=Ue,xe.publish("addPattern",Ue)}};y.ShadingPattern=Cu,y.TilingPattern=Ih,y.addShadingPattern=function(U,Ue){return z("addShadingPattern()"),gn(U,Ue),this},y.beginTilingPattern=function(U){z("beginTilingPattern()"),bc(U.boundingBox[0],U.boundingBox[1],U.boundingBox[2]-U.boundingBox[0],U.boundingBox[3]-U.boundingBox[1],U.matrix)},y.endTilingPattern=function(U,Ue){z("endTilingPattern()"),Ue.stream=Ee[F].join(` 3758`),gn(U,Ue),xe.publish("endTilingPattern",Ue),we.pop().restore()};var An=y.__private__.newObject=function(){var U=Sn();return Xt(U,!0),U},Sn=y.__private__.newObjectDeferred=function(){return me++,ge[me]=function(){return Pe},me},Xt=function(U,Ue){return Ue=typeof Ue=="boolean"&&Ue,ge[U]=Pe,Ue&&ee(U+" 0 obj"),U},Wt=y.__private__.newAdditionalObject=function(){var U={objId:Sn(),content:""};return Re.push(U),U},Gt=Sn(),$t=Sn(),Vt=y.__private__.decodeColorString=function(U){var Ue=U.split(" ");if(Ue.length!==2||Ue[1]!=="g"&&Ue[1]!=="G")Ue.length===5&&(Ue[4]==="k"||Ue[4]==="K")&&(Ue=[(1-Ue[0])*(1-Ue[3]),(1-Ue[1])*(1-Ue[3]),(1-Ue[2])*(1-Ue[3]),"r"]);else{var yt=parseFloat(Ue[0]);Ue=[yt,yt,yt,"r"]}for(var kt="#",an=0;an<3;an++)kt+=("0"+Math.floor(255*parseFloat(Ue[an])).toString(16)).slice(-2);return kt},sn=y.__private__.encodeColorString=function(U){var Ue;typeof U=="string"&&(U={ch1:U});var yt=U.ch1,kt=U.ch2,an=U.ch3,Cn=U.ch4,Qn=U.pdfColorType==="draw"?["G","RG","K"]:["g","rg","k"];if(typeof yt=="string"&&yt.charAt(0)!=="#"){var E=new IE(yt);
vendor: 5,603 bytes, lines 3758-3761
3758if(E.ok)yt=E.toHex();else if(!/^\d*\.?\d*$/.test(yt))throw new Error('Invalid color "'+yt+'" passed to jsPDF.encodeColorString.')}if(typeof yt=="string"&&/^#[0-9A-Fa-f]{3}$/.test(yt)&&(yt="#"+yt[1]+yt[1]+yt[2]+yt[2]+yt[3]+yt[3]),typeof yt=="string"&&/^#[0-9A-Fa-f]{6}$/.test(yt)){var Q=parseInt(yt.substr(1),16);yt=Q>>16&255,kt=Q>>8&255,an=255&Q}if(kt===void 0||Cn===void 0&&yt===kt&&kt===an)if(typeof yt=="string")Ue=yt+" "+Qn[0];else switch(U.precision){case 2:Ue=K(yt/255)+" "+Qn[0];break;case 3:default:Ue=L(yt/255)+" "+Qn[0]}else if(Cn===void 0||ur(Cn)==="object"){if(Cn&&!isNaN(Cn.a)&&Cn.a===0)return Ue=["1.","1.","1.",Qn[1]].join(" ");if(typeof yt=="string")Ue=[yt,kt,an,Qn[1]].join(" ");else switch(U.precision){case 2:Ue=[K(yt/255),K(kt/255),K(an/255),Qn[1]].join(" ");break;default:case 3:Ue=[L(yt/255),L(kt/255),L(an/255),Qn[1]].join(" ")}}else if(typeof yt=="string")Ue=[yt,kt,an,Cn,Qn[2]].join(" ");else switch(U.precision){case 2:Ue=[K(yt),K(kt),K(an),K(Cn),Qn[2]].join(" ");break;case 3:default:Ue=[L(yt),L(kt),L(an),L(Cn),Qn[2]].join(" ")}return Ue},on=y.__private__.getFilters=function(){return l},ke=y.__private__.putStream=function(U){var Ue=(U=U||{}).data||"",yt=U.filters||on(),kt=U.alreadyAppliedFilters||[],an=U.addLength1||!1,Cn=Ue.length,Qn=U.objectId,E=function(vn){return vn};if(f!==null&&Qn===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");f!==null&&(E=Ma.encryptor(Qn,0));var Q={};yt===!0&&(yt=["FlateEncode"]);var Ie=U.additionalKeyValues||[],Le=(Q=Ra.API.processDataByFilters!==void 0?Ra.API.processDataByFilters(Ue,yt):{data:Ue,reverseChain:[]}).reverseChain+(Array.isArray(kt)?kt.join(" "):kt.toString());if(Q.data.length!==0&&(Ie.push({key:"Length",value:Q.data.length}),an===!0&&Ie.push({key:"Length1",value:Cn})),Le.length!=0)if(Le.split("/").length-1==1)Ie.push({key:"Filter",value:Le});else{Ie.push({key:"Filter",value:"["+Le+"]"});for(var He=0;He<Ie.length;He+=1)if(Ie[He].key==="DecodeParms"){for(var gt=[],Dt=0;Dt<Q.reverseChain.split("/").length-1;Dt+=1)gt.push("null");gt.push(Ie[He].value),Ie[He].value="["+gt.join(" ")+"]"}}ee("<<");for(var Yt=0;Yt<Ie.length;Yt++)ee("/"+Ie[Yt].key+" "+Ie[Yt].value);ee(">>"),Q.data.length!==0&&(ee("stream"),ee(E(Q.data)),ee("endstream"))},Ct=y.__private__.putPage=function(U){var Ue=U.number,yt=U.data,kt=U.objId,an=U.contentsObjId;Xt(kt,!0),ee("<</Type /Page"),ee("/Parent "+U.rootDictionaryObjId+" 0 R"),ee("/Resources "+U.resourceDictionaryObjId+" 0 R"),ee("/MediaBox ["+parseFloat(G(U.mediaBox.bottomLeftX))+" "+parseFloat(G(U.mediaBox.bottomLeftY))+" "+G(U.mediaBox.topRightX)+" "+G(U.mediaBox.topRightY)+"]"),U.cropBox!==null&&ee("/CropBox ["+G(U.cropBox.bottomLeftX)+" "+G(U.cropBox.bottomLeftY)+" "+G(U.cropBox.topRightX)+" "+G(U.cropBox.topRightY)+"]"),U.bleedBox!==null&&ee("/BleedBox ["+G(U.bleedBox.bottomLeftX)+" "+G(U.bleedBox.bottomLeftY)+" "+G(U.bleedBox.topRightX)+" "+G(U.bleedBox.topRightY)+"]"),U.trimBox!==null&&ee("/TrimBox ["+G(U.trimBox.bottomLeftX)+" "+G(U.trimBox.bottomLeftY)+" "+G(U.trimBox.topRightX)+" "+G(U.trimBox.topRightY)+"]"),U.artBox!==null&&ee("/ArtBox ["+G(U.artBox.bottomLeftX)+" "+G(U.artBox.bottomLeftY)+" "+G(U.artBox.topRightX)+" "+G(U.artBox.topRightY)+"]"),typeof U.userUnit=="number"&&U.userUnit!==1&&ee("/UserUnit "+U.userUnit),xe.publish("putPage",{objId:kt,pageContext:B[Ue],pageNumber:Ue,page:yt}),ee("/Contents "+an+" 0 R"),ee(">>"),ee("endobj");var Cn=yt.join(` 3759`);return I===R.ADVANCED&&(Cn+=` 3760Q`),Xt(an,!0),ke({data:Cn,filters:on(),objectId:an}),ee("endobj"),kt},Et=y.__private__.putPages=function(){var U,Ue,yt=[];for(U=1;U<=tn;U++)B[U].objId=Sn(),B[U].contentsObjId=Sn();for(U=1;U<=tn;U++)yt.push(Ct({number:U,data:Ee[U],objId:B[U].objId,contentsObjId:B[U].contentsObjId,mediaBox:B[U].mediaBox,cropBox:B[U].cropBox,bleedBox:B[U].bleedBox,trimBox:B[U].trimBox,artBox:B[U].artBox,userUnit:B[U].userUnit,rootDictionaryObjId:Gt,resourceDictionaryObjId:$t}));Xt(Gt,!0),ee("<</Type /Pages");var kt="/Kids [";for(Ue=0;Ue<tn;Ue++)kt+=yt[Ue]+" 0 R ";ee(kt+"]"),ee("/Count "+tn),ee(">>"),ee("endobj"),xe.publish("postPutPages")},Rt=function(U){xe.publish("putFont",{font:U,out:ee,newObject:An,putStream:ke}),U.isAlreadyPutted!==!0&&(U.objectNumber=An(),ee("<<"),ee("/Type /Font"),ee("/BaseFont /"+Km(U.postScriptName)),ee("/Subtype /Type1"),typeof U.encoding=="string"&&ee("/Encoding /"+U.encoding),ee("/FirstChar 32"),ee("/LastChar 255"),ee(">>"),ee("endobj"))},xn=function(){for(var U in Ge)Ge.hasOwnProperty(U)&&(g===!1||g===!0&&p.hasOwnProperty(U))&&Rt(Ge[U])},dn=function(U){U.objectNumber=An();var Ue=[];Ue.push({key:"Type",value:"/XObject"}),Ue.push({key:"Subtype",value:"/Form"}),Ue.push({key:"BBox",value:"["+[G(U.x),G(U.y),G(U.x+U.width),G(U.y+U.height)].join(" ")+"]"}),Ue.push({key:"Matrix",value:"["+U.matrix.toString()+"]"});var yt=U.pages[1].join(` 3761`);ke({data:yt,additionalKeyValues:Ue,objectId:U.objectNumber}),ee("endobj")},Ln=function(){for(var U in ht)ht.hasOwnProperty(U)&&dn(ht[U])},wa=function(U,Ue){var yt,kt=[],an=1/(Ue-1);for(yt=0;yt<1;yt+=an)kt.push(yt);if(kt.push(1),U[0].offset!=0){var Cn={offset:0,color:U[0].color};U.unshift(Cn)}if(U[U.length-1].offset!=1){var Qn={offset:1,color:U[U.length-1].color};U.push(Qn)}for(var E="",Q=0,Ie=0;Ie<kt.length;Ie++){for(yt=kt[Ie];yt>U[Q+1].offset;)Q++;var Le=U[Q].offset,He=(yt-Le)/(U[Q+1].offset-Le),gt=U[Q].color,Dt=U[Q+1].color;E+=ue(Math.round((1-He)*gt[0]+He*Dt[0]).toString(16))+ue(Math.round((1-He)*gt[1]+He*Dt[1]).toString(16))+ue(Math.round((1-He)*gt[2]+He*Dt[2]).toString(16))}return E.trim()},Ca=function(U,Ue){Ue||(Ue=21);var yt=An(),kt=wa(U.colors,Ue),an=[];
vendor: 4,883 bytes, lines 3761-3762
3761an.push({key:"FunctionType",value:"0"}),an.push({key:"Domain",value:"[0.0 1.0]"}),an.push({key:"Size",value:"["+Ue+"]"}),an.push({key:"BitsPerSample",value:"8"}),an.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),an.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),ke({data:kt,additionalKeyValues:an,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:yt}),ee("endobj"),U.objectNumber=An(),ee("<< /ShadingType "+U.type),ee("/ColorSpace /DeviceRGB");var Cn="/Coords ["+G(parseFloat(U.coords[0]))+" "+G(parseFloat(U.coords[1]))+" ";U.type===2?Cn+=G(parseFloat(U.coords[2]))+" "+G(parseFloat(U.coords[3])):Cn+=G(parseFloat(U.coords[2]))+" "+G(parseFloat(U.coords[3]))+" "+G(parseFloat(U.coords[4]))+" "+G(parseFloat(U.coords[5])),ee(Cn+="]"),U.matrix&&ee("/Matrix ["+U.matrix.toString()+"]"),ee("/Function "+yt+" 0 R"),ee("/Extend [true true]"),ee(">>"),ee("endobj")},In=function(U,Ue){var yt=Sn(),kt=An();Ue.push({resourcesOid:yt,objectOid:kt}),U.objectNumber=kt;var an=[];an.push({key:"Type",value:"/Pattern"}),an.push({key:"PatternType",value:"1"}),an.push({key:"PaintType",value:"1"}),an.push({key:"TilingType",value:"1"}),an.push({key:"BBox",value:"["+U.boundingBox.map(G).join(" ")+"]"}),an.push({key:"XStep",value:G(U.xStep)}),an.push({key:"YStep",value:G(U.yStep)}),an.push({key:"Resources",value:yt+" 0 R"}),U.matrix&&an.push({key:"Matrix",value:"["+U.matrix.toString()+"]"}),ke({data:U.stream,additionalKeyValues:an,objectId:U.objectNumber}),ee("endobj")},Sa=function(U){var Ue;for(Ue in st)st.hasOwnProperty(Ue)&&(st[Ue]instanceof Cu?Ca(st[Ue]):st[Ue]instanceof Ih&&In(st[Ue],U))},aa=function(U){for(var Ue in U.objectNumber=An(),ee("<<"),U)switch(Ue){case"opacity":ee("/ca "+K(U[Ue]));break;case"stroke-opacity":ee("/CA "+K(U[Ue]))}ee(">>"),ee("endobj")},$a=function(){var U;for(U in be)be.hasOwnProperty(U)&&aa(be[U])},jn=function(){for(var U in ee("/XObject <<"),ht)ht.hasOwnProperty(U)&&ht[U].objectNumber>=0&&ee("/"+U+" "+ht[U].objectNumber+" 0 R");xe.publish("putXobjectDict"),ee(">>")},vs=function(){Ma.oid=An(),ee("<<"),ee("/Filter /Standard"),ee("/V "+Ma.v),ee("/R "+Ma.r),ee("/U <"+Ma.toHexString(Ma.U)+">"),ee("/O <"+Ma.toHexString(Ma.O)+">"),ee("/P "+Ma.P),ee(">>"),ee("endobj")},ka=function(){for(var U in ee("/Font <<"),Ge)Ge.hasOwnProperty(U)&&(g===!1||g===!0&&p.hasOwnProperty(U))&&ee("/"+U+" "+Ge[U].objectNumber+" 0 R");ee(">>")},Ja=function(){if(Object.keys(st).length>0){for(var U in ee("/Shading <<"),st)st.hasOwnProperty(U)&&st[U]instanceof Cu&&st[U].objectNumber>=0&&ee("/"+U+" "+st[U].objectNumber+" 0 R");xe.publish("putShadingPatternDict"),ee(">>")}},_n=function(U){if(Object.keys(st).length>0){for(var Ue in ee("/Pattern <<"),st)st.hasOwnProperty(Ue)&&st[Ue]instanceof y.TilingPattern&&st[Ue].objectNumber>=0&&st[Ue].objectNumber<U&&ee("/"+Ue+" "+st[Ue].objectNumber+" 0 R");xe.publish("putTilingPatternDict"),ee(">>")}},ha=function(){if(Object.keys(be).length>0){var U;for(U in ee("/ExtGState <<"),be)be.hasOwnProperty(U)&&be[U].objectNumber>=0&&ee("/"+U+" "+be[U].objectNumber+" 0 R");xe.publish("putGStateDict"),ee(">>")}},ta=function(U){Xt(U.resourcesOid,!0),ee("<<"),ee("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),ka(),Ja(),_n(U.objectOid),ha(),jn(),ee(">>"),ee("endobj")},W=function(){var U=[];xn(),$a(),Ln(),Sa(U),xe.publish("putResources"),U.forEach(ta),ta({resourcesOid:$t,objectOid:Number.MAX_SAFE_INTEGER}),xe.publish("postPutResources")},ft=function(){xe.publish("putAdditionalObjects");for(var U=0;U<Re.length;U++){var Ue=Re[U];Xt(Ue.objId,!0),ee(Ue.content),ee("endobj")}xe.publish("postPutAdditionalObjects")},Zt=function(U){pt[U.fontName]=pt[U.fontName]||{},pt[U.fontName][U.fontStyle]=U.id},vt=function(U,Ue,yt,kt,an){var Cn={id:"F"+(Object.keys(Ge).length+1).toString(10),postScriptName:U,fontName:Ue,fontStyle:yt,encoding:kt,isStandardFont:an||!1,metadata:{}};return xe.publish("addFont",{font:Cn,instance:this}),Ge[Cn.id]=Cn,Zt(Cn),Cn.id},Ae=function(U){for(var Ue=0,yt=pe.length;Ue<yt;Ue++){var kt=vt.call(this,U[Ue][0],U[Ue][1],U[Ue][2],pe[Ue][3],!0);g===!1&&(p[kt]=!0);var an=U[Ue][0].split("-");Zt({id:kt,fontName:an[0],fontStyle:an[1]||""})}xe.publish("addFonts",{fonts:Ge,dictionary:pt})},oe=function(U){return U.foo=function(){try{return U.apply(this,arguments)}catch(kt){var Ue=kt.stack||"";~Ue.indexOf(" at ")&&(Ue=Ue.split(" at ")[1]);var yt="Error in function "+Ue.split(` 3762`)[0].split("<")[0]+": "+kt.message;if(!ns.console)throw new Error(yt);ns.console.error(yt,kt),ns.alert&&alert(yt)}},U.foo.bar=U,U.foo},Ve=function(U,Ue){var yt,kt,an,Cn,Qn,E,Q,Ie,Le;if(an=(Ue=Ue||{}).sourceEncoding||"Unicode",Qn=Ue.outputEncoding,(Ue.autoencode||Qn)&&Ge[Je].metadata&&Ge[Je].metadata[an]&&Ge[Je].metadata[an].encoding&&(Cn=Ge[Je].metadata[an].encoding,!Qn&&Ge[Je].encoding&&(Qn=Ge[Je].encoding),!Qn&&Cn.codePages&&(Qn=Cn.codePages[0]),typeof Qn=="string"&&(Qn=Cn[Qn]),Qn)){for(Q=!1,E=[],yt=0,kt=U.length;yt<kt;
vendor: 9,102 bytes, lines 3762-3763
3762yt++)(Ie=Qn[U.charCodeAt(yt)])?E.push(String.fromCharCode(Ie)):E.push(U[yt]),E[yt].charCodeAt(0)>>8&&(Q=!0);U=E.join("")}for(yt=U.length;Q===void 0&&yt!==0;)U.charCodeAt(yt-1)>>8&&(Q=!0),yt--;if(!Q)return U;for(E=Ue.noBOM?[]:[254,255],yt=0,kt=U.length;yt<kt;yt++){if((Le=(Ie=U.charCodeAt(yt))>>8)>>8)throw new Error("Character at position "+yt+" of string '"+U+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");E.push(Le),E.push(Ie-(Le<<8))}return String.fromCharCode.apply(void 0,E)},he=y.__private__.pdfEscape=y.pdfEscape=function(U,Ue){return Ve(U,Ue).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Oe=y.__private__.beginPage=function(U){Ee[++tn]=[],B[tn]={objId:0,contentsObjId:0,userUnit:Number(m),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(U[0]),topRightY:Number(U[1])}},en(tn),_e(Ee[F])},ut=function(U,Ue){var yt,kt,an;switch(a=Ue||a,typeof U=="string"&&(yt=C(U.toLowerCase()),Array.isArray(yt)&&(kt=yt[0],an=yt[1])),Array.isArray(U)&&(kt=U[0]*le,an=U[1]*le),isNaN(kt)&&(kt=i[0],an=i[1]),(kt>14400||an>14400)&&(Ar.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),kt=Math.min(14400,kt),an=Math.min(14400,an)),i=[kt,an],a.substr(0,1)){case"l":an>kt&&(i=[an,kt]);break;case"p":kt>an&&(i=[an,kt])}Oe(i),Qo(er),ee($i),Uc!==0&&ee(Uc+" J"),Gi!==0&&ee(Gi+" j"),xe.publish("addPage",{pageNumber:tn})},At=function(U){U>0&&U<=tn&&(Ee.splice(U,1),B.splice(U,1),tn--,F>tn&&(F=tn),this.setPage(F))},en=function(U){U>0&&U<=tn&&(F=U)},It=y.__private__.getNumberOfPages=y.getNumberOfPages=function(){return Ee.length-1},Pt=function(U,Ue,yt){var kt,an=void 0;return yt=yt||{},U=U!==void 0?U:Ge[Je].fontName,Ue=Ue!==void 0?Ue:Ge[Je].fontStyle,kt=U.toLowerCase(),pt[kt]!==void 0&&pt[kt][Ue]!==void 0?an=pt[kt][Ue]:pt[U]!==void 0&&pt[U][Ue]!==void 0?an=pt[U][Ue]:yt.disableWarning===!1&&Ar.warn("Unable to look up font label for font '"+U+"', '"+Ue+"'. Refer to getFontList() for available fonts."),an||yt.noFallback||(an=pt.times[Ue])==null&&(an=pt.times.normal),an},Jn=y.__private__.putInfo=function(){var U=An(),Ue=function(kt){return kt};for(var yt in f!==null&&(Ue=Ma.encryptor(U,0)),ee("<<"),ee("/Producer ("+he(Ue("jsPDF "+Ra.version))+")"),Ye)Ye.hasOwnProperty(yt)&&Ye[yt]&&ee("/"+yt.substr(0,1).toUpperCase()+yt.substr(1)+" ("+he(Ue(Ye[yt]))+")");ee("/CreationDate ("+he(Ue(fe))+")"),ee(">>"),ee("endobj")},na=y.__private__.putCatalog=function(U){var Ue=(U=U||{}).rootDictionaryObjId||Gt;switch(An(),ee("<<"),ee("/Type /Catalog"),ee("/Pages "+Ue+" 0 R"),Me||(Me="fullwidth"),Me){case"fullwidth":ee("/OpenAction [3 0 R /FitH null]");break;case"fullheight":ee("/OpenAction [3 0 R /FitV null]");break;case"fullpage":ee("/OpenAction [3 0 R /Fit]");break;case"original":ee("/OpenAction [3 0 R /XYZ null null 1]");break;default:var yt=""+Me;yt.substr(yt.length-1)==="%"&&(Me=parseInt(Me)/100),typeof Me=="number"&&ee("/OpenAction [3 0 R /XYZ null null "+K(Me)+"]")}switch(De||(De="continuous"),De){case"continuous":ee("/PageLayout /OneColumn");break;case"single":ee("/PageLayout /SinglePage");break;case"two":case"twoleft":ee("/PageLayout /TwoColumnLeft");break;case"tworight":ee("/PageLayout /TwoColumnRight")}ct&&ee("/PageMode /"+ct),xe.publish("putCatalog"),ee(">>"),ee("endobj")},Mn=y.__private__.putTrailer=function(){ee("trailer"),ee("<<"),ee("/Size "+(me+1)),ee("/Root "+me+" 0 R"),ee("/Info "+(me-1)+" 0 R"),f!==null&&ee("/Encrypt "+Ma.oid+" 0 R"),ee("/ID [ <"+q+"> <"+q+"> ]"),ee(">>")},Ea=y.__private__.putHeader=function(){ee("%PDF-"+b),ee("%ºÃˆ ")},ga=y.__private__.putXRef=function(){var U="0000000000";ee("xref"),ee("0 "+(me+1)),ee("0000000000 65535 f ");for(var Ue=1;Ue<=me;Ue++)typeof ge[Ue]=="function"?ee((U+ge[Ue]()).slice(-10)+" 00000 n "):ge[Ue]!==void 0?ee((U+ge[Ue]).slice(-10)+" 00000 n "):ee("0000000000 00000 n ")},zn=y.__private__.buildDocument=function(){it(),_e(de),xe.publish("buildDocument"),Ea(),Et(),ft(),W(),f!==null&&vs(),Jn(),na();var U=Pe;return ga(),Mn(),ee("startxref"),ee(""+U),ee("%%EOF"),_e(Ee[F]),de.join(` 3763`)},Xn=y.__private__.getBlob=function(U){return new Blob([se(U)],{type:"application/pdf"})},Vn=y.output=y.__private__.output=oe((function(U,Ue){switch(typeof(Ue=Ue||{})=="string"?Ue={filename:Ue}:Ue.filename=Ue.filename||"generated.pdf",U){case void 0:return zn();case"save":y.save(Ue.filename);break;case"arraybuffer":return se(zn());case"blob":return Xn(zn());case"bloburi":case"bloburl":if(ns.URL!==void 0&&typeof ns.URL.createObjectURL=="function")return ns.URL&&ns.URL.createObjectURL(Xn(zn()))||void 0;Ar.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var yt="",kt=zn();try{yt=U1(kt)}catch{yt=U1(unescape(encodeURIComponent(kt)))}return"data:application/pdf;filename="+Ue.filename+";base64,"+yt;case"pdfobjectnewwindow":if(Object.prototype.toString.call(ns)==="[object Window]"){var an="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Cn=' integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==" crossorigin="anonymous"';Ue.pdfObjectUrl&&(an=Ue.pdfObjectUrl,Cn="");var Qn='<html><style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style><body><script src="'+an+'"'+Cn+'><\/script><script >PDFObject.embed("'+this.output("dataurlstring")+'", '+JSON.stringify(Ue)+");<\/script></body></html>",E=ns.open();return E!==null&&E.document.write(Qn),E}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(ns)==="[object Window]"){var Q='<html><style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style><body><iframe id="pdfViewer" src="'+(Ue.pdfJsUrl||"examples/PDF.js/web/viewer.html")+"?file=&downloadName="+Ue.filename+'" width="500px" height="400px" /></body></html>',Ie=ns.open();if(Ie!==null){Ie.document.write(Q);var Le=this;Ie.document.documentElement.querySelector("#pdfViewer").onload=function(){Ie.document.title=Ue.filename,Ie.document.documentElement.querySelector("#pdfViewer").contentWindow.PDFViewerApplication.open(Le.output("bloburl"))}}return Ie}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(ns)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var He='<html><style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style><body><iframe src="'+this.output("datauristring",Ue)+'"></iframe></body></html>',gt=ns.open();if(gt!==null&&(gt.document.write(He),gt.document.title=Ue.filename),gt||typeof safari>"u")return gt;break;case"datauri":case"dataurl":return ns.document.location.href=this.output("datauristring",Ue);default:return null}})),ua=function(U){return Array.isArray(tt)===!0&&tt.indexOf(U)>-1};switch(s){case"pt":le=1;break;case"mm":le=72/25.4;break;case"cm":le=72/2.54;break;case"in":le=72;break;case"px":le=ua("px_scaling")==1?.75:96/72;break;case"pc":case"em":le=12;break;case"ex":le=6;break;default:if(typeof s!="number")throw new Error("Invalid unit: "+s);le=s}var Ma=null;V(),ae();var Xe=function(U){return f!==null?Ma.encryptor(U,0):function(Ue){return Ue}},Jt=y.__private__.getPageInfo=y.getPageInfo=function(U){if(isNaN(U)||U%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:B[U].objId,pageNumber:U,pageContext:B[U]}},Ht=y.__private__.getPageInfoByObjId=function(U){if(isNaN(U)||U%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Ue in B)if(B[Ue].objId===U)break;return Jt(Ue)},xa=y.__private__.getCurrentPageInfo=y.getCurrentPageInfo=function(){return{objId:B[F].objId,pageNumber:F,pageContext:B[F]}};y.addPage=function(){return ut.apply(this,arguments),this},y.setPage=function(){return en.apply(this,arguments),_e.call(this,Ee[F]),this},y.insertPage=function(U){return this.addPage(),this.movePage(F,U),this},y.movePage=function(U,Ue){var yt,kt;if(U>Ue){yt=Ee[U],kt=B[U];for(var an=U;an>Ue;an--)Ee[an]=Ee[an-1],B[an]=B[an-1];Ee[Ue]=yt,B[Ue]=kt,this.setPage(Ue)}else if(U<Ue){yt=Ee[U],kt=B[U];for(var Cn=U;Cn<Ue;Cn++)Ee[Cn]=Ee[Cn+1],B[Cn]=B[Cn+1];Ee[Ue]=yt,B[Ue]=kt,this.setPage(Ue)}return this},y.deletePage=function(){return At.apply(this,arguments),this},y.__private__.text=y.text=function(U,Ue,yt,kt,an){var Cn,Qn,E,Q,Ie,Le,He,gt,Dt,Yt=(kt=kt||{}).scope||this;if(typeof U=="number"&&typeof Ue=="number"&&(typeof yt=="string"||Array.isArray(yt))){var vn=yt;yt=Ue,Ue=U,U=vn}if(arguments[3]instanceof rt?(z("The transform parameter of text() with a Matrix value"),Dt=an):(E=arguments[4],Q=arguments[5],ur(He=arguments[3])==="object"&&He!==null||(typeof E=="string"&&(Q=E,E=null),typeof He=="string"&&(Q=He,He=null),typeof He=="number"&&(E=He,He=null),kt={flags:He,angle:E,align:Q})),isNaN(Ue)||isNaN(yt)||U==null)throw new Error("Invalid arguments passed to
3763jsPDF.text");if(U.length===0)return Yt;var zt="",Bt=!1,En=typeof kt.lineHeightFactor=="number"?kt.lineHeightFactor:Rr,wn=Yt.internal.scaleFactor;function ma(Ka){return Ka=Ka.split(" ").join(Array(kt.TabLen||9).join(" ")),he(Ka,He)}function ca(Ka){for(var Ss,Es=Ka.concat(),rr=[],ao=Es.length;ao--;)typeof(Ss=Es.shift())=="string"?rr.push(Ss):Array.isArray(Ka)&&(Ss.length===1||Ss[1]===void 0&&Ss[2]===void 0)?rr.push(Ss[0]):rr.push([Ss[0],Ss[1],Ss[2]]);return rr}function Pa(Ka,Ss){var Es;if(typeof Ka=="string")Es=Ss(Ka)[0];else if(Array.isArray(Ka)){for(var rr,ao,xc=Ka.concat(),Do=[],go=xc.length;go--;)typeof(rr=xc.shift())=="string"?Do.push(Ss(rr)[0]):Array.isArray(rr)&&typeof rr[0]=="string"&&(ao=Ss(rr[0],rr[1],rr[2]),Do.push([ao[0],ao[1],ao[2]]));Es=Do}return Es}var kn=!1,Kn=!0;if(typeof U=="string")kn=!0;else if(Array.isArray(U)){var Zn=U.concat();Qn=[];for(var da,Ga=Zn.length;Ga--;)(typeof(da=Zn.shift())!="string"||Array.isArray(da)&&typeof da[0]!="string")&&(Kn=!1);kn=Kn}if(kn===!1)throw new Error('Type of text must be string or Array. "'+U+'" is not recognized.');typeof U=="string"&&(U=U.match(/[\r?\n]/)?U.split(/\r\n|\r|\n/g):[U]);var Da=Se/Yt.internal.scaleFactor,Ia=Da*(En-1);switch(kt.baseline){case"bottom":yt-=Ia;break;case"top":yt+=Da-Ia;break;case"hanging":yt+=Da-2*Ia;break;case"middle":yt+=Da/2-Ia}if((Le=kt.maxWidth||0)>0&&(typeof U=="string"?U=Yt.splitTextToSize(U,Le):Object.prototype.toString.call(U)==="[object Array]"&&(U=U.reduce((function(Ka,Ss){return Ka.concat(Yt.splitTextToSize(Ss,Le))}),[]))),Cn={text:U,x:Ue,y:yt,options:kt,mutex:{pdfEscape:he,activeFontKey:Je,fonts:Ge,activeFontSize:Se}},xe.publish("preProcessText",Cn),U=Cn.text,E=(kt=Cn.options).angle,!(Dt instanceof rt)&&E&&typeof E=="number"){E*=Math.PI/180,kt.rotationDirection===0&&(E=-E),I===R.ADVANCED&&(E=-E);var ls=Math.cos(E),Ua=Math.sin(E);Dt=new rt(ls,Ua,-Ua,ls,0,0)}else E&&E instanceof rt&&(Dt=E);I!==R.ADVANCED||Dt||(Dt=Qt),(Ie=kt.charSpace||Xo)!==void 0&&(zt+=G(D(Ie))+` Tc 3764`,this.setCharSpace(this.getCharSpace()||0)),(gt=kt.horizontalScale)!==void 0&&(zt+=G(100*gt)+` Tz 3765`),kt.lang;var va=-1,_a=kt.renderingMode!==void 0?kt.renderingMode:kt.stroke,Vs=Yt.internal.getCurrentPageInfo().pageContext;switch(_a){case 0:case!1:case"fill":va=0;break;case 1:case!0:case"stroke":va=1;break;case 2:case"fillThenStroke":va=2;break;case 3:case"invisible":va=3;break;case 4:case"fillAndAddForClipping":va=4;break;case 5:case"strokeAndAddPathForClipping":va=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":va=6;break;case 7:case"addToPathForClipping":va=7}var Hn=Vs.usedRenderingMode!==void 0?Vs.usedRenderingMode:-1;va!==-1?zt+=va+` Tr 3766`:Hn!==-1&&(zt+=`0 Tr 3767`),va!==-1&&(Vs.usedRenderingMode=va),Q=kt.align||"left";var Fa,zs=Se*En,Bs=Yt.internal.pageSize.getWidth(),S=Ge[Je];Ie=kt.charSpace||Xo,Le=kt.maxWidth||0,He=Object.assign({autoencode:!0,noBOM:!0},kt.flags);var ye=[],Fe=function(Ka){return Yt.getStringUnitWidth(Ka,{font:S,charSpace:Ie,fontSize:Se,doKerning:!1})*Se/wn};if(Object.prototype.toString.call(U)==="[object Array]"){var lt;Qn=ca(U),Q!=="left"&&(Fa=Qn.map(Fe));var Ot,Ft=0;if(Q==="right"){Ue-=Fa[0],U=[],Ga=Qn.length;for(var rn=0;rn<Ga;rn++)rn===0?(Ot=Or(Ue),lt=Js(yt)):(Ot=D(Ft-Fa[rn]),lt=-zs),U.push([Qn[rn],Ot,lt]),Ft=Fa[rn]}else if(Q==="center"){Ue-=Fa[0]/2,U=[],Ga=Qn.length;for(var Rn=0;Rn<Ga;Rn++)Rn===0?(Ot=Or(Ue),lt=Js(yt)):(Ot=D((Ft-Fa[Rn])/2),lt=-zs),U.push([Qn[Rn],Ot,lt]),Ft=Fa[Rn]}else if(Q==="left"){U=[],Ga=Qn.length;for(var ea=0;ea<Ga;ea++)U.push(Qn[ea])}else if(Q==="justify"&&S.encoding==="Identity-H"){U=[],Ga=Qn.length,Le=Le!==0?Le:Bs;for(var Wn=0,Bn=0;Bn<Ga;Bn++)if(lt=Bn===0?Js(yt):-zs,Ot=Bn===0?Or(Ue):Wn,Bn<Ga-1){var Fn=D((Le-Fa[Bn])/(Qn[Bn].split(" ").length-1)),Na=Qn[Bn].split(" ");U.push([Na[0]+" ",Ot,lt]),Wn=0;for(var ya=1;ya<Na.length;ya++){var Ba=(Fe(Na[ya-1]+" "+Na[ya])-Fe(Na[ya]))*wn+Fn;ya==Na.length-1?U.push([Na[ya],Ba,0]):U.push([Na[ya]+" ",Ba,0]),Wn-=Ba}}else U.push([Qn[Bn],Ot,lt]);U.push(["",Wn,0])}else{if(Q!=="justify")throw new Error('Unrecognized alignment option, use "left", "center", "right" or "justify".');for(U=[],Ga=Qn.length,Le=Le!==0?Le:Bs,Bn=0;Bn<Ga;Bn++)lt=Bn===0?Js(yt):-zs,Ot=Bn===0?Or(Ue):0,Bn<Ga-1?ye.push(G(D((Le-Fa[Bn
vendor: 8,854 bytes, lines 3767-3777
3767])/(Qn[Bn].split(" ").length-1)))):ye.push(0),U.push([Qn[Bn],Ot,lt])}}var Ya=typeof kt.R2L=="boolean"?kt.R2L:wt;Ya===!0&&(U=Pa(U,(function(Ka,Ss,Es){return[Ka.split("").reverse().join(""),Ss,Es]}))),Cn={text:U,x:Ue,y:yt,options:kt,mutex:{pdfEscape:he,activeFontKey:Je,fonts:Ge,activeFontSize:Se}},xe.publish("postProcessText",Cn),U=Cn.text,Bt=Cn.mutex.isHex||!1;var Os=Ge[Je].encoding;Os!=="WinAnsiEncoding"&&Os!=="StandardEncoding"||(U=Pa(U,(function(Ka,Ss,Es){return[ma(Ka),Ss,Es]}))),Qn=ca(U),U=[];for(var ys,_r,tr,wr=0,Ns=1,Wr=Array.isArray(Qn[0])?Ns:wr,nr="",Fs=function(Ka,Ss,Es){var rr="";return Es instanceof rt?(Es=typeof kt.angle=="number"?St(Es,new rt(1,0,0,1,Ka,Ss)):St(new rt(1,0,0,1,Ka,Ss),Es),I===R.ADVANCED&&(Es=St(new rt(1,0,0,-1,0,0),Es)),rr=Es.join(" ")+` Tm 3768`):rr=G(Ka)+" "+G(Ss)+` Td 3769`,rr},Hs=0;Hs<Qn.length;Hs++){switch(nr="",Wr){case Ns:tr=(Bt?"<":"(")+Qn[Hs][0]+(Bt?">":")"),ys=parseFloat(Qn[Hs][1]),_r=parseFloat(Qn[Hs][2]);break;case wr:tr=(Bt?"<":"(")+Qn[Hs]+(Bt?">":")"),ys=Or(Ue),_r=Js(yt)}ye!==void 0&&ye[Hs]!==void 0&&(nr=ye[Hs]+` Tw 3770`),Hs===0?U.push(nr+Fs(ys,_r,Dt)+tr):Wr===wr?U.push(nr+tr):Wr===Ns&&U.push(nr+Fs(ys,_r,Dt)+tr)}U=Wr===wr?U.join(` Tj 3771T* `):U.join(` Tj 3772`),U+=` Tj 3773`;var sr=`BT 3774/`;return sr+=Je+" "+Se+` Tf 3775`,sr+=G(Se*En)+` TL 3776`,sr+=no+` 3777`,sr+=zt,sr+=U,ee(sr+="ET"),p[Je]=!0,Yt};var ra=y.__private__.clip=y.clip=function(U){return ee(U==="evenodd"?"W*":"W"),this};y.clipEvenOdd=function(){return ra("evenodd")},y.__private__.discardPath=y.discardPath=function(){return ee("n"),this};var Ha=y.__private__.isValidStyle=function(U){var Ue=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(U)!==-1&&(Ue=!0),Ue};y.__private__.setDefaultPathOperation=y.setDefaultPathOperation=function(U){return Ha(U)&&(u=U),this};var is=y.__private__.getStyle=y.getStyle=function(U){var Ue=u;switch(U){case"D":case"S":Ue="S";break;case"F":Ue="f";break;case"FD":case"DF":Ue="B";break;case"f":case"f*":case"B":case"B*":Ue=U}return Ue},hs=y.close=function(){return ee("h"),this};y.stroke=function(){return ee("S"),this},y.fill=function(U){return rs("f",U),this},y.fillEvenOdd=function(U){return rs("f*",U),this},y.fillStroke=function(U){return rs("B",U),this},y.fillStrokeEvenOdd=function(U){return rs("B*",U),this};var rs=function(U,Ue){ur(Ue)==="object"?bs(Ue,U):ee(U)},oa=function(U){U===null||I===R.ADVANCED&&U===void 0||(U=is(U),ee(U))};function qa(U,Ue,yt,kt,an){var Cn=new Ih(Ue||this.boundingBox,yt||this.xStep,kt||this.yStep,this.gState,an||this.matrix);Cn.stream=this.stream;var Qn=U+"$$"+this.cloneIndex+++"$$";return gn(Qn,Cn),Cn}var bs=function(U,Ue){var yt=Nt[U.key],kt=st[yt];if(kt instanceof Cu)ee("q"),ee(Wa(Ue)),kt.gState&&y.setGState(kt.gState),ee(U.matrix.toString()+" cm"),ee("/"+yt+" sh"),ee("Q");else if(kt instanceof Ih){var an=new rt(1,0,0,-1,0,_o());U.matrix&&(an=an.multiply(U.matrix||Qt),yt=qa.call(kt,U.key,U.boundingBox,U.xStep,U.yStep,an).id),ee("q"),ee("/Pattern cs"),ee("/"+yt+" scn"),kt.gState&&y.setGState(kt.gState),ee(Ue),ee("Q")}},Wa=function(U){switch(U){case"f":case"F":return"W n";case"f*":return"W* n";case"B":return"W S";case"B*":return"W* S";case"S":return"W S";case"n":return"W n"}},$s=y.moveTo=function(U,Ue){return ee(G(D(U))+" "+G(Z(Ue))+" m"),this},jr=y.lineTo=function(U,Ue){return ee(G(D(U))+" "+G(Z(Ue))+" l"),this},Kr=y.curveTo=function(U,Ue,yt,kt,an,Cn){return ee([G(D(U)),G(Z(Ue)),G(D(yt)),G(Z(kt)),G(D(an)),G(Z(Cn)),"c"].join(" ")),this};y.__private__.line=y.line=function(U,Ue,yt,kt,an){if(isNaN(U)||isNaN(Ue)||isNaN(yt)||isNaN(kt)||!Ha(an))throw new Error("Invalid arguments passed to jsPDF.line");return I===R.COMPAT?this.lines([[yt-U,kt-Ue]],U,Ue,[1,1],an||"S"):this.lines([[yt-U,kt-Ue]],U,Ue,[1,1]).stroke()},y.__private__.lines=y.lines=function(U,Ue,yt,kt,an,Cn){var Qn,E,Q,Ie,Le,He,gt,Dt,Yt,vn,zt,Bt;if(typeof U=="number"&&(Bt=yt,yt=Ue,Ue=U,U=Bt),kt=kt||[1,1],Cn=Cn||!1,isNaN(Ue)||isNaN(yt)||!Array.isArray(U)||!Array.isArray(kt)||!Ha(an)||typeof Cn!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for($s(Ue,yt),Qn=kt[0],E=kt[1],Ie=U.length,vn=Ue,zt=yt,Q=0;Q<Ie;Q++)(Le=U[Q]).length===2?(vn=Le[0]*Qn+vn,zt=Le[1]*E+zt,jr(vn,zt)):(He=Le[0]*Qn+vn,gt=Le[1]*E+zt,Dt=Le[2]*Qn+vn,Yt=Le[3]*E+zt,vn=Le[4]*Qn+vn,zt=Le[5]*E+zt,Kr(He,gt,Dt,Yt,vn,zt));return Cn&&hs(),oa(an),this},y.path=function(U){for(var Ue=0;Ue<U.length;Ue++){var yt=U[Ue],kt=yt.c;switch(yt.op){case"m":$s(kt[0],kt[1]);break;case"l":jr(kt[0],kt[1]);break;case"c":Kr.apply(this,kt);break;case"h":hs()}}return this},y.__private__.rect=y.rect=function(U,Ue,yt,kt,an){if(isNaN(U)||isNaN(Ue)||isNaN(yt)||isNaN(kt)||!Ha(an))throw new Error("Invalid arguments passed to jsPDF.rect");return I===R.COMPAT&&(kt=-kt),ee([G(D(U)),G(Z(Ue)),G(D(yt)),G(D(kt)),"re"].join(" ")),oa(an),this},y.__private__.triangle=y.triangle=function(U,Ue,yt,kt,an,Cn,Qn){if(isNaN(U)||isNaN(Ue)||isNaN(yt)||isNaN(kt)||isNaN(an)||isNaN(Cn)||!Ha(Qn))throw new Error("Invalid arguments passed to jsPDF.triangle");return this.lines([[yt-U,kt-Ue],[an-yt,Cn-kt],[U-an,Ue-Cn]],U,Ue,[1,1],Qn,!0),this},y.__private__.roundedRect=y.roundedRect=function(U,Ue,yt,kt,an,Cn,Qn){if(isNaN(U)||isNaN(Ue)||isNaN(yt)||isNaN(kt)||isNaN(an)||isNaN(Cn)||!Ha(Qn))throw new Error("Invalid arguments passed to jsPDF.roundedRect");var E=4/3*(Math.SQRT2-1);return an=Math.min(an,.5*yt),Cn=Math.min(Cn,.5*kt),this.lines([[yt-2*an,0],[an*E,0,an,Cn-Cn*E,an,Cn],[0,kt-2*Cn],[0,Cn*E,-an*E,Cn,-an,Cn],[2*an-yt,0],[-an*E,0,-an,-Cn*E,-an,-Cn],[0,2*Cn-kt],[0,-Cn*E,an*E,-Cn,an,-Cn]],U+an,Ue,[1,1],Qn,!0),this},y.__private__.ellipse=y.ellipse=function(U,Ue,yt,kt,an){if(isNaN(U)||isNaN(Ue)||isNaN(yt)||isNaN(kt)||!Ha(an))throw new Error("Invalid arguments passed to jsPDF.ellipse");var Cn=4/3*(Math.SQRT2-1)*yt,Qn=4/3*(Math.SQRT2-1)*kt;return $s(U+yt,Ue),Kr(U+yt,Ue-Qn,U+Cn,Ue-kt,U,Ue-kt),Kr(U-Cn,Ue-kt,U-yt,Ue-Qn,U-yt,Ue),Kr(U-yt,Ue+Qn,U-Cn,Ue+kt,U,Ue+kt),Kr(U+Cn,Ue+kt,U+yt,Ue+Qn,U+yt,Ue),oa(an),this},y.__private__.circle=y.circle=function(U,Ue,yt,kt){if(isNaN(U)||isNaN(Ue)||isNaN(yt)||!Ha(kt))throw new Error("Invalid arguments passed to jsPDF.circle");return this.ellipse(U,Ue,yt,yt,kt)},y.setFont=function(U,Ue,yt){return yt&&(Ue=T(Ue,yt)),Je=Pt(U,Ue,{disableWarning:!1}),this};var Xr=y.__private__.getFont=y.getFont=function(){return Ge[Pt.apply(y,arguments)]};y.__private__.getFontList=y.getFontList=function(){var U,Ue,yt={};for(U in pt)if(pt.hasOwnProperty(U))for(Ue in yt[U]=[],pt[U])pt[U].hasOwnProperty(Ue)&&yt[U].push(Ue);return yt},y.addFont=function(U,Ue,yt,kt,an){var Cn=["StandardEncoding","MacRomanEncoding","Identity-H","WinAnsiEncoding"];return arguments[3]&&Cn.indexOf(arguments[3])!==-1?an=arguments[3]:arguments[3]&&Cn.indexOf(arguments[3])==-1&&(yt=T(yt,kt)),an=an||"Identity-H",vt.call(this,U,Ue,yt,an)};var Rr,er=t.lineWidth||.200025,Ir=y.__private__.getLineWidth=y.getLineWidth=function(){return er},Qo=y.__private__.setLineWidth=y.setLineWidth=function(U){return er=U,ee(G(D(U))+" w"),this};y.__private__.setLineDash=Ra.API.setLineDash=Ra.API.setLineDashPattern=function(U,Ue){if(U=U||[],Ue=Ue||0,isNaN(Ue)||!Array.isArray(U))throw new Error("Invalid arguments passed to jsPDF.setLineDash");return U=U.map((function(yt){return G(D(yt))})).join(" "),Ue=G(D(Ue)),ee("["+U+"] "+Ue+" d"),this};var fo=y.__private__.getLineHeight=y.getLineHeight=function(){return Se*Rr};y.__private__.getLineHeight=y.getLineHeight=function(){return Se*Rr};var Jo=y.__private__.setLineHeightFactor=y.setLineHeightFactor=function(U){return typeof(U=U||1.15)=="number"&&(Rr=U),this},pr=y.__private__.getLineHeightFactor=y.getLineHeightFactor=function(){return Rr};Jo(t.lineHeight);var Or=y.__private__.getHorizontalCoordinate=function(U){return D(U)},Js=y.__private__.getVerticalCoordinate=function(U){return I===R.ADVANCED?U:B[F].mediaBox.topRightY-B[F].mediaBox.bottomLeftY-D(U)},Ko=y.__private__.getHorizontalCoordinateString=y.getHorizontalCoordinateString=function(U){return G(Or(U))},to=y.__private__.getVerticalCoordinateString=y.getVerticalCoordinateString=function(U){return G(Js(U))},$i=t.strokeColor||"0 G";y.__private__.getStrokeColor=y.getDrawColor=function(){return Vt($i)},y.__private__.setStrokeColor=y.setDrawColor=function(U,Ue,yt,kt){return $i=sn({ch1:U,ch2:Ue,ch3:yt,ch4:kt,pdfColorType:"draw",precision:2}),ee($i),this};var Bc=t.fillColor||"0 g";y.__private__.getFillColor=y.getFillColor=function(){return Vt(Bc)},y.__private__.setFillColor=y.setFillColor=function(U,Ue,yt,kt){return Bc=sn({ch1:U,ch2:Ue,ch3:yt,ch4:kt,pdfColorType:"fill",precision:2}),ee(Bc),this};var no=t.textColor||"0 g",Fc=y.__private__.getTextColor=y.getTextColor=function(){return Vt(no)};y.__private__.setTextColor=y.setTextColor=function(U,Ue,yt,kt){return no=sn({ch1:U,ch2:Ue,ch3:yt,ch4:kt,pdfColorType:"text",precision:3}),this};var Xo=t.charSpace,Yl=y.__private__.getCharSpace=y.getCharSpace=function(){return parseFloat(Xo||0)};
vendor: 5,944 bytes, line 3777
3777y.__private__.setCharSpace=y.setCharSpace=function(U){if(isNaN(U))throw new Error("Invalid argument passed to jsPDF.setCharSpace");return Xo=U,this};var Uc=0;y.CapJoinStyles={0:0,butt:0,but:0,miter:0,1:1,round:1,rounded:1,circle:1,2:2,projecting:2,project:2,square:2,bevel:2},y.__private__.setLineCap=y.setLineCap=function(U){var Ue=y.CapJoinStyles[U];if(Ue===void 0)throw new Error("Line cap style of '"+U+"' is not recognized. See or extend .CapJoinStyles property for valid styles");return Uc=Ue,ee(Ue+" J"),this};var Gi=0;y.__private__.setLineJoin=y.setLineJoin=function(U){var Ue=y.CapJoinStyles[U];if(Ue===void 0)throw new Error("Line join style of '"+U+"' is not recognized. See or extend .CapJoinStyles property for valid styles");return Gi=Ue,ee(Ue+" j"),this},y.__private__.setLineMiterLimit=y.__private__.setMiterLimit=y.setLineMiterLimit=y.setMiterLimit=function(U){if(U=U||0,isNaN(U))throw new Error("Invalid argument passed to jsPDF.setLineMiterLimit");return ee(G(D(U))+" M"),this},y.GState=jg,y.setGState=function(U){(U=typeof U=="string"?be[jt[U]]:zc(null,U)).equals(bt)||(ee("/"+U.id+" gs"),bt=U)};var zc=function(U,Ue){if(!U||!jt[U]){var yt=!1;for(var kt in be)if(be.hasOwnProperty(kt)&&be[kt].equals(Ue)){yt=!0;break}if(yt)Ue=be[kt];else{var an="GS"+(Object.keys(be).length+1).toString(10);be[an]=Ue,Ue.id=an}return U&&(jt[U]=Ue.id),xe.publish("addGState",Ue),Ue}};y.addGState=function(U,Ue){return zc(U,Ue),this},y.saveGraphicsState=function(){return ee("q"),$e.push({key:Je,size:Se,color:no}),this},y.restoreGraphicsState=function(){ee("Q");var U=$e.pop();return Je=U.key,Se=U.size,no=U.color,bt=null,this},y.setCurrentTransformationMatrix=function(U){return ee(U.toString()+" cm"),this},y.comment=function(U){return ee("#"+U),this};var Zo=function(U,Ue){var yt=U||0;Object.defineProperty(this,"x",{enumerable:!0,get:function(){return yt},set:function(Cn){isNaN(Cn)||(yt=parseFloat(Cn))}});var kt=Ue||0;Object.defineProperty(this,"y",{enumerable:!0,get:function(){return kt},set:function(Cn){isNaN(Cn)||(kt=parseFloat(Cn))}});var an="pt";return Object.defineProperty(this,"type",{enumerable:!0,get:function(){return an},set:function(Cn){an=Cn.toString()}}),this},qc=function(U,Ue,yt,kt){Zo.call(this,U,Ue),this.type="rect";var an=yt||0;Object.defineProperty(this,"w",{enumerable:!0,get:function(){return an},set:function(Qn){isNaN(Qn)||(an=parseFloat(Qn))}});var Cn=kt||0;return Object.defineProperty(this,"h",{enumerable:!0,get:function(){return Cn},set:function(Qn){isNaN(Qn)||(Cn=parseFloat(Qn))}}),this},ec=function(){this.page=tn,this.currentPage=F,this.pages=Ee.slice(0),this.pagesContext=B.slice(0),this.x=nt,this.y=xt,this.matrix=te,this.width=tc(F),this.height=_o(F),this.outputDestination=We,this.id="",this.objectNumber=-1};ec.prototype.restore=function(){tn=this.page,F=this.currentPage,B=this.pagesContext,Ee=this.pages,nt=this.x,xt=this.y,te=this.matrix,Vc(F,this.width),ko(F,this.height),We=this.outputDestination};var bc=function(U,Ue,yt,kt,an){we.push(new ec),tn=F=0,Ee=[],nt=U,xt=Ue,te=an,Oe([yt,kt])},vl=function(U){if(dt[U])we.pop().restore();else{var Ue=new ec,yt="Xo"+(Object.keys(ht).length+1).toString(10);Ue.id=yt,dt[U]=yt,ht[yt]=Ue,xe.publish("addFormObject",Ue),we.pop().restore()}};for(var Oi in y.beginFormObject=function(U,Ue,yt,kt,an){return bc(U,Ue,yt,kt,an),this},y.endFormObject=function(U){return vl(U),this},y.doFormObject=function(U,Ue){var yt=ht[dt[U]];return ee("q"),ee(Ue.toString()+" cm"),ee("/"+yt.id+" Do"),ee("Q"),this},y.getFormObject=function(U){var Ue=ht[dt[U]];return{x:Ue.x,y:Ue.y,width:Ue.width,height:Ue.height,matrix:Ue.matrix}},y.save=function(U,Ue){return U=U||"generated.pdf",(Ue=Ue||{}).returnPromise=Ue.returnPromise||!1,Ue.returnPromise===!1?(wh(Xn(zn()),U),typeof wh.unload=="function"&&ns.setTimeout&&setTimeout(wh.unload,911),this):new Promise((function(yt,kt){try{var an=wh(Xn(zn()),U);typeof wh.unload=="function"&&ns.setTimeout&&setTimeout(wh.unload,911),yt(an)}catch(Cn){kt(Cn.message)}}))},Ra.API)Ra.API.hasOwnProperty(Oi)&&(Oi==="events"&&Ra.API.events.length?(function(U,Ue){var yt,kt,an;for(an=Ue.length-1;an!==-1;an--)yt=Ue[an][0],kt=Ue[an][1],U.subscribe.apply(U,[yt].concat(typeof kt=="function"?[kt]:kt))})(xe,Ra.API.events):y[Oi]=Ra.API[Oi]);var tc=y.getPageWidth=function(U){return(B[U=U||F].mediaBox.topRightX-B[U].mediaBox.bottomLeftX)/le},Vc=y.setPageWidth=function(U,Ue){B[U].mediaBox.topRightX=Ue*le+B[U].mediaBox.bottomLeftX},_o=y.getPageHeight=function(U){return(B[U=U||F].mediaBox.topRightY-B[U].mediaBox.bottomLeftY)/le},ko=y.setPageHeight=function(U,Ue){B[U].mediaBox.topRightY=Ue*le+B[U].mediaBox.bottomLeftY};return y.internal={pdfEscape:he,getStyle:is,getFont:Xr,getFontSize:ot,getCharSpace:Yl,getTextColor:Fc,getLineHeight:fo,getLineHeightFactor:pr,getLineWidth:Ir,write:qe,getHorizontalCoordinate:Or,getVerticalCoordinate:Js,getCoordinateString:Ko,getVerticalCoordinateString:to,collections:{},newObject:An,newAdditionalObject:Wt,newObjectDeferred:Sn,newObjectDeferredBegin:Xt,getFilters:on,putStream:ke,events:xe,scaleFactor:le,pageSize:{getWidth:function(){return tc(F)},setWidth:function(U){Vc(F,U)},getHeight:function(){return _o(F)},setHeight:function(U){ko(F,U)}},encryptionOptions:f,encryption:Ma,getEncryptor:Xe,output:Vn,getNumberOfPages:It,pages:Ee,out:ee,f2:K,f3:L,getPageInfo:Jt,getPageInfoByObjId:Ht,getCurrentPageInfo:xa,getPDFVersion:N,Point:Zo,Rectangle:qc,Matrix:rt,hasHotfix:ua},Object.defineProperty(y.internal.pageSize,"width",{get:function(){return tc(F)},set:function(U){Vc(F,U)},enumerable:!0,configurable:!0}),Object.defineProperty(y.internal.pageSize,"height",{get:function(){return _o(F)},set:function(U){ko(F,U)},enumerable:!0,configurable:!0}),Ae.call(y,pe),Je="F1",ut(i,a),xe.publish("initialized"),y}Jm.prototype.lsbFirstWord=function(t){return String.fromCharCode(t>>0&255,t>>8&255,t>>16&255,t>>24&255)},Jm.prototype.toHexString=function(t){return t.split("").map((function(n){return("0"+(255&n.charCo
vendor: 30,448 bytes, lines 3777-3796
3777deAt(0)).toString(16)).slice(-2)})).join("")},Jm.prototype.hexToBytes=function(t){for(var n=[],a=0;a<t.length;a+=2)n.push(String.fromCharCode(parseInt(t.substr(a,2),16)));return n.join("")},Jm.prototype.processOwnerPassword=function(t,n){return q1(z1(n).substr(0,5),t)},Jm.prototype.encryptor=function(t,n){var a=z1(this.encryptionKey+String.fromCharCode(255&t,t>>8&255,t>>16&255,255&n,n>>8&255)).substr(0,10);return function(s){return q1(a,s)}},jg.prototype.equals=function(t){var n,a="id,objectNumber,equals";if(!t||ur(t)!==ur(this))return!1;var s=0;for(n in this)if(!(a.indexOf(n)>=0)){if(this.hasOwnProperty(n)&&!t.hasOwnProperty(n)||this[n]!==t[n])return!1;s++}for(n in t)t.hasOwnProperty(n)&&a.indexOf(n)<0&&s--;return s===0},Ra.API={events:[]},Ra.version="2.5.2";var ai=Ra.API,h2=1,tm=function(t){return t.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Um=function(t){return t.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},us=function(t){return t.toFixed(2)},lu=function(t){return t.toFixed(5)};ai.__acroform__={};var Yo=function(t,n){t.prototype=Object.create(n.prototype),t.prototype.constructor=t},HI=function(t){return t*h2},$l=function(t){var n=new EE,a=La.internal.getHeight(t)||0,s=La.internal.getWidth(t)||0;return n.BBox=[0,0,Number(us(s)),Number(us(a))],n},_F=ai.__acroform__.setBit=function(t,n){if(t=t||0,n=n||0,isNaN(t)||isNaN(n))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBit");return t|=1<<n},kF=ai.__acroform__.clearBit=function(t,n){if(t=t||0,n=n||0,isNaN(t)||isNaN(n))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.clearBit");return t&=~(1<<n)},DF=ai.__acroform__.getBit=function(t,n){if(isNaN(t)||isNaN(n))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.getBit");return(t&1<<n)==0?0:1},ci=ai.__acroform__.getBitForPdf=function(t,n){if(isNaN(t)||isNaN(n))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.getBitForPdf");return DF(t,n-1)},li=ai.__acroform__.setBitForPdf=function(t,n){if(isNaN(t)||isNaN(n))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBitForPdf");return _F(t,n-1)},di=ai.__acroform__.clearBitForPdf=function(t,n){if(isNaN(t)||isNaN(n))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.clearBitForPdf");return kF(t,n-1)},EF=ai.__acroform__.calculateCoordinates=function(t,n){var a=n.internal.getHorizontalCoordinate,s=n.internal.getVerticalCoordinate,i=t[0],c=t[1],l=t[2],m=t[3],d={};return d.lowerLeft_X=a(i)||0,d.lowerLeft_Y=s(c+m)||0,d.upperRight_X=a(i+l)||0,d.upperRight_Y=s(c)||0,[Number(us(d.lowerLeft_X)),Number(us(d.lowerLeft_Y)),Number(us(d.upperRight_X)),Number(us(d.upperRight_Y))]},PF=function(t){if(t.appearanceStreamContent)return t.appearanceStreamContent;if(t.V||t.DV){var n=[],a=t._V||t.DV,s=V1(t,a),i=t.scope.internal.getFont(t.fontName,t.fontStyle).id;n.push("/Tx BMC"),n.push("q"),n.push("BT"),n.push(t.scope.__private__.encodeColorString(t.color)),n.push("/"+i+" "+us(s.fontSize)+" Tf"),n.push("1 0 0 1 0 0 Tm"),n.push(s.text),n.push("ET"),n.push("Q"),n.push("EMC");var c=$l(t);return c.scope=t.scope,c.stream=n.join(` 3778`),c}},V1=function(t,n){var a=t.fontSize===0?t.maxFontSize:t.fontSize,s={text:"",fontSize:""},i=(n=(n=n.substr(0,1)=="("?n.substr(1):n).substr(n.length-1)==")"?n.substr(0,n.length-1):n).split(" ");i=t.multiline?i.map((function(L){return L.split(` 3779`)})):i.map((function(L){return[L]}));var c=a,l=La.internal.getHeight(t)||0;l=l<0?-l:l;var m=La.internal.getWidth(t)||0;m=m<0?-m:m;var d=function(L,D,M){if(L+1<i.length){var Z=D+" "+i[L+1][0];return Ev(Z,t,M).width<=m-4}return!1};c++;e:for(;c>0;){n="",c--;var u,f,g=Ev("3",t,c).height,p=t.multiline?l-c:(l-g)/2,y=p+=2,b=0,N=0,w=0;if(c<=0){n=`(...) Tj 3780`,n+="% Width of Text: "+Ev(n,t,c=12).width+", FieldWidth:"+m+` 3781`;break}for(var C="",R=0,I=0;I<i.length;I++)if(i.hasOwnProperty(I)){var _=!1;if(i[I].length!==1&&w!==i[I].length-1){if((g+2)*(R+2)+2>l)continue e;C+=i[I][w],_=!0,N=I,I--}else{C=(C+=i[I][w]+" ").substr(C.length-1)==" "?C.substr(0,C.length-1):C;var J=parseInt(I),T=d(J,C,c),G=I>=i.length-1;if(T&&!G){C+=" ",w=0;continue}if(T||G){if(G)N=J;else if(t.multiline&&(g+2)*(R+2)+2>l)continue e}else{if(!t.multiline||(g+2)*(R+2)+2>l)continue e;N=J}}for(var z="",H=b;H<=N;H++){var K=i[H];if(t.multiline){if(H===N){z+=K[w]+" ",w=(w+1)%K.length;continue}if(H===b){z+=K[K.length-1]+" ";continue}}z+=K[0]+" "}switch(z=z.substr(z.length-1)==" "?z.substr(0,z.length-1):z,f=Ev(z,t,c).width,t.textAlign){case"right":u=m-f-2;break;case"center":u=(m-f)/2;break;case"left":default:u=2}n+=us(u)+" "+us(y)+` Td 3782`,n+="("+tm(z)+`) Tj 3783`,n+=-us(u)+` 0 Td 3784`,y=-(c+2),f=0,b=_?N:N+1,R++,C=""}break}return s.text=n,s.fontSize=c,s},Ev=function(t,n,a){var s=n.scope.internal.getFont(n.fontName,n.fontStyle),i=n.scope.getStringUnitWidth(t,{font:s,fontSize:parseFloat(a),charSpace:0})*parseFloat(a);return{height:n.scope.getStringUnitWidth("3",{font:s,fontSize:parseFloat(a),charSpace:0})*parseFloat(a)*1.5,width:i}},RF={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},TF=function(t,n){var a={type:"reference",object:t};n.internal.getPageInfo(t.page).pageContext.annotations.find((function(s){return s.type===a.type&&s.object===a.object}))===void 0&&n.internal.getPageInfo(t.page).pageContext.annotations.push(a)},MF=function(t,n){for(var a in t)if(t.hasOwnProperty(a)){var s=a,i=t[a];n.internal.newObjectDeferredBegin(i.objId,!0),ur(i)==="object"&&typeof i.putStream=="function"&&i.putStream(),delete t[s]}},$F=function(t,n){if(n.scope=t,t.internal!==void 0&&(t.internal.acroformPlugin===void 0||t.internal.acroformPlugin.isInitialized===!1)){if(gl.FieldNum=0,t.internal.acroformPlugin=JSON.parse(JSON.stringify(RF)),t.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");h2=t.internal.scaleFactor,t.internal.acroformPlugin.acroFormDictionaryRoot=new PE,t.internal.acroformPlugin.acroFormDictionaryRoot.scope=t,t.internal.acroformPlugin.acroFormDictionaryRoot._eventID=t.internal.events.subscribe("postPutResources",(function(){(function(a){a.internal.events.unsubscribe(a.internal.acroformPlugin.acroFormDictionaryRoot._eventID),delete a.internal.acroformPlugin.acroFormDictionaryRoot._eventID,a.internal.acroformPlugin.printedOut=!0})(t)})),t.internal.events.subscribe("buildDocument",(function(){(function(a){a.internal.acroformPlugin.acroFormDictionaryRoot.objId=void 0;var s=a.internal.acroformPlugin.acroFormDictionaryRoot.Fields;for(var i in s)if(s.hasOwnProperty(i)){var c=s[i];c.objId=void 0,c.hasAnnotation&&TF(c,a)}})(t)})),t.internal.events.subscribe("putCatalog",(function(){(function(a){if(a.internal.acroformPlugin.acroFormDictionaryRoot===void 0)throw new Error("putCatalogCallback: Root missing.");a.internal.write("/AcroForm "+a.internal.acroformPlugin.acroFormDictionaryRoot.objId+" 0 R")})(t)})),t.internal.events.subscribe("postPutPages",(function(a){(function(s,i){var c=!s;for(var l in s||(i.internal.newObjectDeferredBegin(i.internal.acroformPlugin.acroFormDictionaryRoot.objId,!0),i.internal.acroformPlugin.acroFormDictionaryRoot.putStream()),s=s||i.internal.acroformPlugin.acroFormDictionaryRoot.Kids)if(s.hasOwnProperty(l)){var m=s[l],d=[],u=m.Rect;if(m.Rect&&(m.Rect=EF(m.Rect,i)),i.internal.newObjectDeferredBegin(m.objId,!0),m.DA=La.createDefaultAppearanceStream(m),ur(m)==="object"&&typeof m.getKeyValueListForStream=="function"&&(d=m.getKeyValueListForStream()),m.Rect=u,m.hasAppearanceStream&&!m.appearanceStreamContent){var f=PF(m);d.push({key:"AP",value:"<</N "+f+">>"}),i.internal.acroformPlugin.xForms.push(f)}if(m.appearanceStreamContent){var g="";for(var p in m.appearanceStreamContent)if(m.appearanceStreamContent.hasOwnProperty(p)){var y=m.appearanceStreamContent[p];if(g+="/"+p+" ",g+="<<",Object.keys(y).length>=1||Array.isArray(y)){for(var l in y)if(y.hasOwnProperty(l)){var b=y[l];typeof b=="function"&&(b=b.call(i,m)),g+="/"+l+" "+b+" ",i.internal.acroformPlugin.xForms.indexOf(b)>=0||i.internal.acroformPlugin.xForms.push(b)}}else typeof(b=y)=="function"&&(b=b.call(i,m)),g+="/"+l+" "+b,i.internal.acroformPlugin.xForms.indexOf(b)>=0||i.internal.acroformPlugin.xForms.push(b);g+=">>"}d.push({key:"AP",value:`<< 3785`+g+">>"})}i.internal.putStream({additionalKeyValues:d,objectId:m.objId}),i.internal.out("endobj")}c&&MF(i.internal.acroformPlugin.xForms,i)})(a,t)})),t.internal.acroformPlugin.isInitialized=!0}},DE=ai.__acroform__.arrayToPdfArray=function(t,n,a){var s=function(l){return l};if(Array.isArray(t)){for(var i="[",c=0;c<t.length;c++)switch(c!==0&&(i+=" "),ur(t[c])){case"boolean":case"number":case"object":i+=t[c].toString();break;case"string":t[c].substr(0,1)!=="/"?(n!==void 0&&a&&(s=a.internal.getEncryptor(n)),i+="("+tm(s(t[c].toString()))+")"):i+=t[c].toString()}return i+="]"}throw new Error("Invalid argument passed to jsPDF.__acroform__.arrayToPdfArray")},yj=function(t,n,a){var s=function(i){return i};return n!==void 0&&a&&(s=a.internal.getEncryptor(n)),(t=t||"").toString(),t="("+tm(s(t))+")"},Fl=function(){this._objId=void 0,this._scope=void 0,Object.defineProperty(this,"objId",{get:function(){if(this._objId===void 0){if(this.scope===void 0)return;this._objId=this.scope.internal.newObjectDeferred()}return this._objId},set:function(t){this._objId=t}}),Object.defineProperty(this,"scope",{value:this._scope,writable:!0})};Fl.prototype.toString=function(){return this.objId+" 0 R"},Fl.prototype.putStream=function(){var t=this.getKeyValueListForStream();this.scope.internal.putStream({data:this.stream,additionalKeyValues:t,objectId:this.objId}),this.scope.internal.out("endobj")},Fl.prototype.getKeyValueListForStream=function(){var t=[],n=Object.getOwnPropertyNames(this).filter((function(c){return c!="content"&&c!="appearanceStreamContent"&&c!="scope"&&c!="objId"&&c.substring(0,1)!="_"}));for(var a in n)if(Object.getOwnPropertyDescriptor(this,n[a]).configurable===!1){var s=n[a],i=this[s];i&&(Array.isArray(i)?t.push({key:s,value:DE(i,this.objId,this.scope)}):i instanceof Fl?(i.scope=this.scope,t.push({key:s,value:i.objId+" 0 R"})):typeof i!="function"&&t.push({key:s,value:i}))}return t};var EE=function(){Fl.call(this),Object.defineProperty(this,"Type",{value:"/XObject",configurable:!1,writable:!0}),Object.defineProperty(this,"Subtype",{value:"/Form",configurable:!1,writable:!0}),Object.defineProperty(this,"FormType",{value:1,configurable:!1,writable:!0});var t,n=[];Object.defineProperty(this,"BBox",{configurable:!1,get:function(){return n},set:function(a){n=a}}),Object.defineProperty(this,"Resources",{value:"2 0 R",configurable:!1,writable:!0}),Object.defineProperty(this,"stream",{enumerable:!1,configurable:!0,set:function(a){t=a.trim()},get:function(){return t||null}})};Yo(EE,Fl);var PE=function(){Fl.call(this);var t,n=[];Object.defineProperty(this,"Kids",{enumerable:!1,configurable:!0,get:function(){return n.length>0?n:void 0}}),Object.defineProperty(this,"Fields",{enumerable:!1,configurable:!1,get:function(){return n}}),Object.defineProperty(this,"DA",{enumerable:!1,configurable:!1,get:function(){if(t){var a=function(s){return s};return this.scope&&(a=this.scope.internal.getEncryptor(this.objId)),"("+tm(a(t))+")"}},set:function(a){t=a}})};Yo(PE,Fl);var gl=function t(){Fl.call(this);var n=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return n},set:function(C){if(isNaN(C))throw new Error('Invalid value "'+C+'" for attribute F supplied.');n=C}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!ci(n,3)},set:function(C){C?this.F=li(n,3):this.F=di(n,3)}});var a=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return a},set:function(C){if(isNaN(C))throw new Error('Invalid value "'+C+'" for attribute Ff supplied.');a=C}});var s=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(s.length!==0)return s},set:function(C){s=C!==void 0?C:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!s||isNaN(s[0])?0:s[0]},set:function(C){s[0]=C}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!s||isNaN(s[1])?0:s[1]},set:function(C){s[1]=C}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!s||isNaN(s[2])?0:s[2]},set:function(C){s[2]=C}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!s||isNaN(s[3])?0:s[3]},set:function(C){s[3]=C}});var i="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return i},set:function(C){switch(C){case"/Btn":case"/Tx":case"/Ch":case"/Sig":i=C;break;default:throw new Error('Invalid value "'+C+'" for attribute FT supplied.')}}});var c=null;Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,get:function(){if(!c||c.length<1){if(this instanceof Lb)return;c="FieldObject"+t.FieldNum++}var C=function(R){return R};return this.scope&&(C=this.scope.internal.getEncryptor(this.objId)),"("+tm(C(c))+")"},set:function(C){c=C.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return c},set:function(C){c=C}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(C){l=C}});var m="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return m},set:function(C){m=C}});var d=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return d},set:function(C){d=C}});var u=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return u===void 0?50/h2:u},set:function(C){u=C}});var f="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return f},set:function(C){f=C}});var g="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!g||this instanceof Lb||this instanceof Mu))return yj(g,this.objId,this.scope)},set:function(C){C=C.toString(),g=C}});var p=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof Pi?p:yj(p,this.objId,this.scope)},set:function(C){C=C.toString(),p=this instanceof Pi?C:C.substr(0,1)==="("?Um(C.substr(1,C.length-2)):Um(C)}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof Pi?Um(p.substr(1,p.length-1)):p},set:function(C){C=C.toString(),p=this instanceof Pi?"/"+C:C}});var y=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(y)return y},set:function(C){this.V=C}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(y)return this instanceof Pi?y:yj(y,this.objId,this.scope)},set:function(C){C=C.toString(),y=this instanceof Pi?C:C.substr(0,1)==="("?Um(C.substr(1,C.length-2)):Um(C)}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof Pi?Um(y.substr(1,y.length-1)):y},set:function(C){C=C.toString(),y=this instanceof Pi?"/"+C:C}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var b,N=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return N},set:function(C){C=!!C,N=C}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(b)return b},set:function(C){b=C}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,1)},set:function(C){C?this.Ff=li(this.Ff,1):this.Ff=di(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,2)},set:function(C){C?this.Ff=li(this.Ff,2):this.Ff=di(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,3)},set:function(C){C?this.Ff=li(this.Ff,3):this.Ff=di(this.Ff,3)}});var w=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(w!==null)return w},set:function(C){if([0,1,2].indexOf(C)===-1)throw new Error('Invalid value "'+C+'" for attribute Q supplied.');w=C}}),Object.defineProperty(this,"textAlign",{get:function(){var C;switch(w){case 0:default:C="left";break;case 1:C="center";break;case 2:C="right"}return C},configurable:!0,enumerable:!0,set:function(C){switch(C){case"right":case 2:w=2;break;case"center":case 1:w=1;break;case"left":case 0:default:w=0}}})};Yo(gl,Fl);var Th=function(){gl.call(this),this.FT="/Ch",this.V="()",this.fontName="zapfdingbats";var t=0;Object.defineProperty(this,"TI",{enumerable:!0,configurable:!1,get:function(){return t},set:function(a){t=a}}),Object.defineProperty(this,"topIndex",{enumerable:!0,configurable:!0,get:function(){return t},set:function(a){t=a}});var n=[];Object.defineProperty(this,"Opt",{enumerable:!0,configurable:!1,get:function(){return DE(n,this.objId,this.scope)},set:function(a){var s,i;i=[],typeof(s=a)=="string"&&(i=(function(c,l,m){m||(m=1);for(var d,u=[];d=l.exec(c);)u.push(d[m]);return u})(s,/\((.*?)\)/g)),n=i}}),this.getOptions=function(){return n},this.setOptions=function(a){n=a,this.sort&&n.sort()},this.addOption=function(a){a=(a=a||"").toString(),n.push(a),this.sort&&n.sort()},this.removeOption=function(a,s){for(s=s||!1,a=(a=a||"").toString();n.indexOf(a)!==-1&&(n.splice(n.indexOf(a),1),s!==!1););},Object.defineProperty(this,"combo",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,18)},set:function(a){a?this.Ff=li(this.Ff,18):this.Ff=di(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,19)},set:function(a){this.combo===!0&&(a?this.Ff=li(this.Ff,19):this.Ff=di(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,20)},set:function(a){a?(this.Ff=li(this.Ff,20),n.sort()):this.Ff=di(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,22)},set:function(a){a?this.Ff=li(this.Ff,22):this.Ff=di(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,23)},set:function(a){a?this.Ff=li(this.Ff,23):this.Ff=di(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,27)},set:function(a){a?this.Ff=li(this.Ff,27):this.Ff=di(this.Ff,27)}}),this.hasAppearanceStream=!1};Yo(Th,gl);var Mh=function(){Th.call(this),this.fontName="helvetica",this.combo=!1};Yo(Mh,Th);var $h=function(){Mh.call(this),this.combo=!0};Yo($h,Mh);var Zf=function(){$h.call(this),this.edit=!0};Yo(Zf,$h);var Pi=function(){gl.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,15)},set:function(a){a?this.Ff=li(this.Ff,15):this.Ff=di(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,16)},set:function(a){a?this.Ff=li(this.Ff,16):this.Ff=di(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,17)},set:function(a){a?this.Ff=li(this.Ff,17):this.Ff=di(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,26)},set:function(a){a?this.Ff=li(this.Ff,26):this.Ff=di(this.Ff,26)}});var t,n={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var a=function(c){return c};if(this.scope&&(a=this.scope.internal.getEncryptor(this.objId)),Object.keys(n).length!==0){var s,i=[];for(s in i.push("<<"),n)i.push("/"+s+" ("+tm(a(n[s]))+")");return i.push(">>"),i.join(` 3786`)}},set:function(a){ur(a)==="object"&&(n=a)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return n.CA||""},set:function(a){typeof a=="string"&&(n.CA=a)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return t},set:function(a){t=a}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return t.substr(1,t.length-1)},set:function(a){t="/"+a}})};Yo(Pi,gl);var eg=function(){Pi.call(this),this.pushButton=!0};Yo(eg,Pi);var Oh=function(){Pi.call(this),this.radio=!0,this.pushButton=!1;var t=[];Object.defineProperty(this,"Kids",{enumerable:!0,configurable:!1,get:function(){return t},set:function(n){t=n!==void 0?n:[]}})};Yo(Oh,Pi);var Lb=function(){var t,n;gl.call(this),Object.defineProperty(this,"Parent",{enumerable:!1,configurable:!1,get:function(){return t},set:function(i){t=i}}),Object.defineProperty(this,"optionName",{enumerable:!1,configurable:!0,get:function(){return n},set:function(i){n=i}});var a,s={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var i=function(m){return m};this.scope&&(i=this.scope.internal.getEncryptor(this.objId));var c,l=[];for(c in l.push("<<"),s)l.push("/"+c+" ("+tm(i(s[c]))+")");return l.push(">>"),l.join(` 3787`)},set:function(i){ur(i)==="object"&&(s=i)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return s.CA||""},set:function(i){typeof i=="string"&&(s.CA=i)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return a},set:function(i){a=i}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return a.substr(1,a.length-1)},set:function(i){a="/"+i}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=La.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};Yo(Lb,gl),Oh.prototype.setAppearance=function(t){if(!("createAppearanceStream"in t)||!("getCA"in t))throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");for(var n in this.Kids)if(this.Kids.hasOwnProperty(n)){var a=this.Kids[n];a.appearanceStreamContent=t.createAppearanceStream(a.optionName),a.caption=t.getCA()}},Oh.prototype.createOption=function(t){var n=new Lb;return n.Parent=this,n.optionName=t,this.Kids.push(n),OF.call(this.scope,n),n};var tg=function(){Pi.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=La.CheckBox.createAppearanceStream()};Yo(tg,Pi);var Mu=function(){gl.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,13)},set:function(n){n?this.Ff=li(this.Ff,13):this.Ff=di(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,21)},set:function(n){n?this.Ff=li(this.Ff,21):this.Ff=di(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,23)},set:function(n){n?this.Ff=li(this.Ff,23):this.Ff=di(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,24)},set:function(n){n?this.Ff=li(this.Ff,24):this.Ff=di(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,25)},set:function(n){n?this.Ff=li(this.Ff,25):this.Ff=di(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,26)},set:function(n){n?this.Ff=li(this.Ff,26):this.Ff=di(this.Ff,26)}});var t=null;Object.defineProperty(this,"MaxLen",{enumerable:!0,configurable:!1,get:function(){return t},set:function(n){t=n}}),Object.defineProperty(this,"maxLength",{enumerable:!0,configurable:!0,get:function(){return t},set:function(n){Number.isInteger(n)&&(t=n)}}),Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return this.V||this.DV}})};Yo(Mu,gl);var ng=function(){Mu.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!ci(this.Ff,14)},set:function(t){t?this.Ff=li(this.Ff,14):this.Ff=di(this.Ff,14)}}),this.password=!0};Yo(ng,Mu);var La={CheckBox:{createAppearanceStream:function(){return{N:{On:La.CheckBox.YesNormal},D:{On:La.CheckBox.YesPushDown,Off:La.CheckBox.OffPushDown}}},YesPushDown:function(t){var n=$l(t);n.scope=t.scope;var a=[],s=t.scope.internal.getFont(t.fontName,t.fontStyle).id,i=t.scope.__private__.encodeColorString(t.color),c=V1(t,t.caption);return a.push("0.749023 g"),a.push("0 0 "+us(La.internal.getWidth(t))+" "+us(La.internal.getHeight(t))+" re"),a.push("f"),a.push("BMC"),a.push("q"),a.push("0 0 1 rg"),a.push("/"+s+" "+us(c.fontSize)+" Tf "+i),a.push("BT"),a.push(c.text),a.push("ET"),a.push("Q"),a.push("EMC"),n.stream=a.join(` 3788`),n},YesNormal:function(t){var n=$l(t);n.scope=t.scope;var a=t.scope.internal.getFont(t.fontName,t.fontStyle).id,s=t.scope.__private__.encodeColorString(t.color),i=[],c=La.internal.getHeight(t),l=La.internal.getWidth(t),m=V1(t,t.caption);return i.push("1 g"),i.push("0 0 "+us(l)+" "+us(c)+" re"),i.push("f"),i.push("q"),i.push("0 0 1 rg"),i.push("0 0 "+us(l-1)+" "+us(c-1)+" re"),i.push("W"),i.push("n"),i.push("0 g"),i.push("BT"),i.push("/"+a+" "+us(m.fontSize)+" Tf "+s),i.push(m.text),i.push("ET"),i.push("Q"),n.stream=i.join(` 3789`),n},OffPushDown:function(t){var n=$l(t);n.scope=t.scope;var a=[];return a.push("0.749023 g"),a.push("0 0 "+us(La.internal.getWidth(t))+" "+us(La.internal.getHeight(t))+" re"),a.push("f"),n.stream=a.join(` 3790`),n}},RadioButton:{Circle:{createAppearanceStream:function(t){var n={D:{Off:La.RadioButton.Circle.OffPushDown},N:{}};return n.N[t]=La.RadioButton.Circle.YesNormal,n.D[t]=La.RadioButton.Circle.YesPushDown,n},getCA:function(){return"l"},YesNormal:function(t){var n=$l(t);n.scope=t.scope;var a=[],s=La.internal.getWidth(t)<=La.internal.getHeight(t)?La.internal.getWidth(t)/4:La.internal.getHeight(t)/4;s=Number((.9*s).toFixed(5));var i=La.internal.Bezier_C,c=Number((s*i).toFixed(5));return a.push("q"),a.push("1 0 0 1 "+lu(La.internal.getWidth(t)/2)+" "+lu(La.internal.getHeight(t)/2)+" cm"),a.push(s+" 0 m"),a.push(s+" "+c+" "+c+" "+s+" 0 "+s+" c"),a.push("-"+c+" "+s+" -"+s+" "+c+" -"+s+" 0 c"),a.push("-"+s+" -"+c+" -"+c+" -"+s+" 0 -"+s+" c"),a.push(c+" -"+s+" "+s+" -"+c+" "+s+" 0 c"),a.push("f"),a.push("Q"),n.stream=a.join(` 3791`),n},YesPushDown:function(t){var n=$l(t);n.scope=t.scope;var a=[],s=La.internal.getWidth(t)<=La.internal.getHeight(t)?La.internal.getWidth(t)/4:La.internal.getHeight(t)/4;s=Number((.9*s).toFixed(5));var i=Number((2*s).toFixed(5)),c=Number((i*La.internal.Bezier_C).toFixed(5)),l=Number((s*La.internal.Bezier_C).toFixed(5));return a.push("0.749023 g"),a.push("q"),a.push("1 0 0 1 "+lu(La.internal.getWidth(t)/2)+" "+lu(La.internal.getHeight(t)/2)+" cm"),a.push(i+" 0 m"),a.push(i+" "+c+" "+c+" "+i+" 0 "+i+" c"),a.push("-"+c+" "+i+" -"+i+" "+c+" -"+i+" 0 c"),a.push("-"+i+" -"+c+" -"+c+" -"+i+" 0 -"+i+" c"),a.push(c+" -"+i+" "+i+" -"+c+" "+i+" 0 c"),a.push("f"),a.push("Q"),a.push("0 g"),a.push("q"),a.push("1 0 0 1 "+lu(La.internal.getWidth(t)/2)+" "+lu(La.internal.getHeight(t)/2)+" cm"),a.push(s+" 0 m"),a.push(s+" "+l+" "+l+" "+s+" 0 "+s+" c"),a.push("-"+l+" "+s+" -"+s+" "+l+" -"+s+" 0 c"),a.push("-"+s+" -"+l+" -"+l+" -"+s+" 0 -"+s+" c"),a.push(l+" -"+s+" "+s+" -"+l+" "+s+" 0 c"),a.push("f"),a.push("Q"),n.stream=a.join(` 3792`),n},OffPushDown:function(t){var n=$l(t);n.scope=t.scope;var a=[],s=La.internal.getWidth(t)<=La.internal.getHeight(t)?La.internal.getWidth(t)/4:La.internal.getHeight(t)/4;s=Number((.9*s).toFixed(5));var i=Number((2*s).toFixed(5)),c=Number((i*La.internal.Bezier_C).toFixed(5));return a.push("0.749023 g"),a.push("q"),a.push("1 0 0 1 "+lu(La.internal.getWidth(t)/2)+" "+lu(La.internal.getHeight(t)/2)+" cm"),a.push(i+" 0 m"),a.push(i+" "+c+" "+c+" "+i+" 0 "+i+" c"),a.push("-"+c+" "+i+" -"+i+" "+c+" -"+i+" 0 c"),a.push("-"+i+" -"+c+" -"+c+" -"+i+" 0 -"+i+" c"),a.push(c+" -"+i+" "+i+" -"+c+" "+i+" 0 c"),a.push("f"),a.push("Q"),n.stream=a.join(` 3793`),n}},Cross:{createAppearanceStream:function(t){var n={D:{Off:La.RadioButton.Cross.OffPushDown},N:{}};return n.N[t]=La.RadioButton.Cross.YesNormal,n.D[t]=La.RadioButton.Cross.YesPushDown,n},getCA:function(){return"8"},YesNormal:function(t){var n=$l(t);n.scope=t.scope;var a=[],s=La.internal.calculateCross(t);return a.push("q"),a.push("1 1 "+us(La.internal.getWidth(t)-2)+" "+us(La.internal.getHeight(t)-2)+" re"),a.push("W"),a.push("n"),a.push(us(s.x1.x)+" "+us(s.x1.y)+" m"),a.push(us(s.x2.x)+" "+us(s.x2.y)+" l"),a.push(us(s.x4.x)+" "+us(s.x4.y)+" m"),a.push(us(s.x3.x)+" "+us(s.x3.y)+" l"),a.push("s"),a.push("Q"),n.stream=a.join(` 3794`),n},YesPushDown:function(t){var n=$l(t);n.scope=t.scope;var a=La.internal.calculateCross(t),s=[];return s.push("0.749023 g"),s.push("0 0 "+us(La.internal.getWidth(t))+" "+us(La.internal.getHeight(t))+" re"),s.push("f"),s.push("q"),s.push("1 1 "+us(La.internal.getWidth(t)-2)+" "+us(La.internal.getHeight(t)-2)+" re"),s.push("W"),s.push("n"),s.push(us(a.x1.x)+" "+us(a.x1.y)+" m"),s.push(us(a.x2.x)+" "+us(a.x2.y)+" l"),s.push(us(a.x4.x)+" "+us(a.x4.y)+" m"),s.push(us(a.x3.x)+" "+us(a.x3.y)+" l"),s.push("s"),s.push("Q"),n.stream=s.join(` 3795`),n},OffPushDown:function(t){var n=$l(t);n.scope=t.scope;var a=[];return a.push("0.749023 g"),a.push("0 0 "+us(La.internal.getWidth(t))+" "+us(La.internal.getHeight(t))+" re"),a.push("f"),n.stream=a.join(` 3796`),n}}},createDefaultAppearanceStream:function(t){var n=t.scope.internal.getFont(t.fontName,t.fontStyle).id,a=t.scope.__private__.encodeColorString(t.color);return"/"+n+" "+t.fontSize+" Tf "+a}};La.internal={Bezier_C:.551915024494,calculateCross:function(t){var n=La.internal.getWidth(t),a=La.internal.getHeight(t),s=Math.min(n,a);return{x1:{x:(n-s)/2,y:(a-s)/2+s},x2:{x:(n-s)/2+s,y:(a-s)/2},x3:{x:(n-s)/2,y:(a-s)/2},x4:{x:(n-s)/2+s,y:(a-s)/2+s}}}},La.internal.getWidth=function(t){var n=0;return ur(t)==="object"&&(n=HI(t.Rect[2])),n},La.internal.getHeight=function(t){var n=0;return ur(t)==="object"&&(n=HI(t.Rect[3])),n};var OF=ai.addField=function(t){if($F(this,t),!(t instanceof gl))throw new Error("Invalid argument passed to
3796jsPDF.addField.");var n;return(n=t).scope.internal.acroformPlugin.printedOut&&(n.scope.internal.acroformPlugin.printedOut=!1,n.scope.internal.acroformPlugin.acroFormDictionaryRoot=null),n.scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(n),t.page=t.scope.internal.getCurrentPageInfo().pageNumber,this};ai.AcroFormChoiceField=Th,ai.AcroFormListBox=Mh,ai.AcroFormComboBox=$h,ai.AcroFormEditBox=Zf,ai.AcroFormButton=Pi,ai.AcroFormPushButton=eg,ai.AcroFormRadioButton=Oh,ai.AcroFormCheckBox=tg,ai.AcroFormTextField=Mu,ai.AcroFormPasswordField=ng,ai.AcroFormAppearance=La,ai.AcroForm={ChoiceField:Th,ListBox:Mh,ComboBox:$h,EditBox:Zf,Button:Pi,PushButton:eg,RadioButton:Oh,CheckBox:tg,TextField:Mu,PasswordField:ng,Appearance:La},Ra.AcroForm={ChoiceField:Th,ListBox:Mh,ComboBox:$h,EditBox:Zf,Button:Pi,PushButton:eg,RadioButton:Oh,CheckBox:tg,TextField:Mu,PasswordField:ng,Appearance:La};var LF=Ra.AcroForm;function RE(t){return t.reduce((function(n,a,s){return n[a]=s,n}),{})}(function(t){t.__addimage__={};var n="UNKNOWN",a={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0],[255,216,255,219],[255,216,255,238]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],WEBP:[[82,73,70,70,void 0,void 0,void 0,void 0,87,69,66,80]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]},s=t.__addimage__.getImageFileTypeByImageData=function(L,D){var M,Z,fe,q,ne,ae=n;if((D=D||n)==="RGBA"||L.data!==void 0&&L.data instanceof Uint8ClampedArray&&"height"in L&&"width"in L)return"RGBA";if(T(L))for(ne in a)for(fe=a[ne],M=0;M<fe.length;M+=1){for(q=!0,Z=0;Z<fe[M].length;Z+=1)if(fe[M][Z]!==void 0&&fe[M][Z]!==L[Z]){q=!1;break}if(q===!0){ae=ne;break}}else for(ne in a)for(fe=a[ne],M=0;M<fe.length;M+=1){for(q=!0,Z=0;Z<fe[M].length;Z+=1)if(fe[M][Z]!==void 0&&fe[M][Z]!==L.charCodeAt(Z)){q=!1;break}if(q===!0){ae=ne;break}}return ae===n&&D!==n&&(ae=D),ae},i=function L(D){for(var M=this.internal.write,Z=this.internal.putStream,fe=(0,this.internal.getFilters)();fe.indexOf("FlateEncode")!==-1;)fe.splice(fe.indexOf("FlateEncode"),1);D.objectId=this.internal.newObject();var q=[];if(q.push({key:"Type",value:"/XObject"}),q.push({key:"Subtype",value:"/Image"}),q.push({key:"Width",value:D.width}),q.push({key:"Height",value:D.height}),D.colorSpace===w.INDEXED?q.push({key:"ColorSpace",value:"[/Indexed /DeviceRGB "+(D.palette.length/3-1)+" "+("sMask"in D&&D.sMask!==void 0?D.objectId+2:D.objectId+1)+" 0 R]"}):(q.push({key:"ColorSpace",value:"/"+D.colorSpace}),D.colorSpace===w.DEVICE_CMYK&&q.push({key:"Decode",value:"[1 0 1 0 1 0 1 0]"})),q.push({key:"BitsPerComponent",value:D.bitsPerComponent}),"decodeParameters"in D&&D.decodeParameters!==void 0&&q.push({key:"DecodeParms",value:"<<"+D.decodeParameters+">>"}),"transparency"in D&&Array.isArray(D.transparency)){for(var ne="",ae=0,Y=D.transparency.length;ae<Y;ae++)ne+=D.transparency[ae]+" "+D.transparency[ae]+" ";q.push({key:"Mask",value:"["+ne+"]"})}D.sMask!==void 0&&q.push({key:"SMask",value:D.objectId+1+" 0 R"});var je=D.filter!==void 0?["/"+D.filter]:void 0;if(Z({data:D.data,additionalKeyValues:q,alreadyAppliedFilters:je,objectId:D.objectId}),M("endobj"),"sMask"in D&&D.sMask!==void 0){var V="/Predictor "+D.predictor+" /Colors 1 /BitsPerComponent "+D.bitsPerComponent+" /Columns "+D.width,$={width:D.width,height:D.height,colorSpace:"DeviceGray",bitsPerComponent:D.bitsPerComponent,decodeParameters:V,data:D.sMask};"filter"in D&&($.filter=D.filter),L.call(this,$)}
vendor: 20,330 bytes, line 3796
3796if(D.colorSpace===w.INDEXED){var F=this.internal.newObject();Z({data:z(new Uint8Array(D.palette)),objectId:F}),M("endobj")}},c=function(){var L=this.internal.collections.addImage_images;for(var D in L)i.call(this,L[D])},l=function(){var L,D=this.internal.collections.addImage_images,M=this.internal.write;for(var Z in D)M("/I"+(L=D[Z]).index,L.objectId,"0","R")},m=function(){this.internal.collections.addImage_images||(this.internal.collections.addImage_images={},this.internal.events.subscribe("putResources",c),this.internal.events.subscribe("putXobjectDict",l))},d=function(){var L=this.internal.collections.addImage_images;return m.call(this),L},u=function(){return Object.keys(this.internal.collections.addImage_images).length},f=function(L){return typeof t["process"+L.toUpperCase()]=="function"},g=function(L){return ur(L)==="object"&&L.nodeType===1},p=function(L,D){if(L.nodeName==="IMG"&&L.hasAttribute("src")){var M=""+L.getAttribute("src");if(M.indexOf("data:image/")===0)return Xf(unescape(M).split("base64,").pop());var Z=t.loadFile(M,!0);if(Z!==void 0)return Z}if(L.nodeName==="CANVAS"){if(L.width===0||L.height===0)throw new Error("Given canvas must have data. Canvas width: "+L.width+", height: "+L.height);var fe;switch(D){case"PNG":fe="image/png";break;case"WEBP":fe="image/webp";break;case"JPEG":case"JPG":default:fe="image/jpeg"}return Xf(L.toDataURL(fe,1).split("base64,").pop())}},y=function(L){var D=this.internal.collections.addImage_images;if(D){for(var M in D)if(L===D[M].alias)return D[M]}},b=function(L,D,M){return L||D||(L=-96,D=-96),L<0&&(L=-1*M.width*72/L/this.internal.scaleFactor),D<0&&(D=-1*M.height*72/D/this.internal.scaleFactor),L===0&&(L=D*M.width/M.height),D===0&&(D=L*M.height/M.width),[L,D]},N=function(L,D,M,Z,fe,q){var ne=b.call(this,M,Z,fe),ae=this.internal.getCoordinateString,Y=this.internal.getVerticalCoordinateString,je=d.call(this);if(M=ne[0],Z=ne[1],je[fe.index]=fe,q){q*=Math.PI/180;var V=Math.cos(q),$=Math.sin(q),F=function(ue){return ue.toFixed(4)},P=[F(V),F($),F(-1*$),F(V),0,0,"cm"]}this.internal.write("q"),q?(this.internal.write([1,"0","0",1,ae(L),Y(D+Z),"cm"].join(" ")),this.internal.write(P.join(" ")),this.internal.write([ae(M),"0","0",ae(Z),"0","0","cm"].join(" "))):this.internal.write([ae(M),"0","0",ae(Z),ae(L),Y(D+Z),"cm"].join(" ")),this.isAdvancedAPI()&&this.internal.write([1,0,0,-1,0,0,"cm"].join(" ")),this.internal.write("/I"+fe.index+" Do"),this.internal.write("Q")},w=t.color_spaces={DEVICE_RGB:"DeviceRGB",DEVICE_GRAY:"DeviceGray",DEVICE_CMYK:"DeviceCMYK",CAL_GREY:"CalGray",CAL_RGB:"CalRGB",LAB:"Lab",ICC_BASED:"ICCBased",INDEXED:"Indexed",PATTERN:"Pattern",SEPARATION:"Separation",DEVICE_N:"DeviceN"};t.decode={DCT_DECODE:"DCTDecode",FLATE_DECODE:"FlateDecode",LZW_DECODE:"LZWDecode",JPX_DECODE:"JPXDecode",JBIG2_DECODE:"JBIG2Decode",ASCII85_DECODE:"ASCII85Decode",ASCII_HEX_DECODE:"ASCIIHexDecode",RUN_LENGTH_DECODE:"RunLengthDecode",CCITT_FAX_DECODE:"CCITTFaxDecode"};var C=t.image_compression={NONE:"NONE",FAST:"FAST",MEDIUM:"MEDIUM",SLOW:"SLOW"},R=t.__addimage__.sHashCode=function(L){var D,M,Z=0;if(typeof L=="string")for(M=L.length,D=0;D<M;D++)Z=(Z<<5)-Z+L.charCodeAt(D),Z|=0;else if(T(L))for(M=L.byteLength/2,D=0;D<M;D++)Z=(Z<<5)-Z+L[D],Z|=0;return Z},I=t.__addimage__.validateStringAsBase64=function(L){(L=L||"").toString().trim();var D=!0;return L.length===0&&(D=!1),L.length%4!=0&&(D=!1),/^[A-Za-z0-9+/]+$/.test(L.substr(0,L.length-2))===!1&&(D=!1),/^[A-Za-z0-9/][A-Za-z0-9+/]|[A-Za-z0-9+/]=|==$/.test(L.substr(-2))===!1&&(D=!1),D},_=t.__addimage__.extractImageFromDataUrl=function(L){var D=(L=L||"").split("base64,"),M=null;if(D.length===2){var Z=/^data:(\w*\/\w*);*(charset=(?!charset=)[\w=-]*)*;*$/.exec(D[0]);Array.isArray(Z)&&(M={mimeType:Z[1],charset:Z[2],data:D[1]})}return M},J=t.__addimage__.supportsArrayBuffer=function(){return typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"};t.__addimage__.isArrayBuffer=function(L){return J()&&L instanceof ArrayBuffer};var T=t.__addimage__.isArrayBufferView=function(L){return J()&&typeof Uint32Array<"u"&&(L instanceof Int8Array||L instanceof Uint8Array||typeof Uint8ClampedArray<"u"&&L instanceof Uint8ClampedArray||L instanceof Int16Array||L instanceof Uint16Array||L instanceof Int32Array||L instanceof Uint32Array||L instanceof Float32Array||L instanceof Float64Array)},G=t.__addimage__.binaryStringToUint8Array=function(L){for(var D=L.length,M=new Uint8Array(D),Z=0;Z<D;Z++)M[Z]=L.charCodeAt(Z);return M},z=t.__addimage__.arrayBufferToBinaryString=function(L){for(var D="",M=T(L)?L:new Uint8Array(L),Z=0;Z<M.length;Z+=8192)D+=String.fromCharCode.apply(null,M.subarray(Z,Z+8192));return D};t.addImage=function(){var L,D,M,Z,fe,q,ne,ae,Y;if(typeof arguments[1]=="number"?(D=n,M=arguments[1],Z=arguments[2],fe=arguments[3],q=arguments[4],ne=arguments[5],ae=arguments[6],Y=arguments[7]):(D=arguments[1],M=arguments[2],Z=arguments[3],fe=arguments[4],q=arguments[5],ne=arguments[6],ae=arguments[7],Y=arguments[8]),ur(L=arguments[0])==="object"&&!g(L)&&"imageData"in L){var je=L;L=je.imageData,D=je.format||D||n,M=je.x||M||0,Z=je.y||Z||0,fe=je.w||je.width||fe,q=je.h||je.height||q,ne=je.alias||ne,ae=je.compression||ae,Y=je.rotation||je.angle||Y}var V=this.internal.getFilters();if(ae===void 0&&V.indexOf("FlateEncode")!==-1&&(ae="SLOW"),isNaN(M)||isNaN(Z))throw new Error("Invalid coordinates passed to jsPDF.addImage");m.call(this);var $=H.call(this,L,D,ne,ae);return N.call(this,M,Z,fe,q,$,Y),this};var H=function(L,D,M,Z){var fe,q,ne;if(typeof L=="string"&&s(L)===n){L=unescape(L);var ae=K(L,!1);(ae!==""||(ae=t.loadFile(L,!0))!==void 0)&&(L=ae)}if(g(L)&&(L=p(L,D)),D=s(L,D),!f(D))throw new Error("addImage does not support files of type '"+D+"', please ensure that a plugin for '"+D+"' support is added.");if(((ne=M)==null||ne.length===0)&&(M=(function(Y){return typeof Y=="string"||T(Y)?R(Y):T(Y.data)?R(Y.data):null})(L)),(fe=y.call(this,M))||(J()&&(L instanceof Uint8Array||D==="RGBA"||(q=L,L=G(L))),fe=this["process"+D.toUpperCase()](L,u.call(this),M,(function(Y){return Y&&typeof Y=="string"&&(Y=Y.toUpperCase()),Y in t.image_compression?Y:C.NONE})(Z),q)),!fe)throw new Error("An unknown error occurred whilst processing the image.");return fe},K=t.__addimage__.convertBase64ToBinaryString=function(L,D){var M;D=typeof D!="boolean"||D;var Z,fe="";if(typeof L=="string"){Z=(M=_(L))!==null?M.data:L;try{fe=Xf(Z)}catch(q){if(D)throw I(Z)?new Error("atob-Error in jsPDF.convertBase64ToBinaryString "+q.message):new Error("Supplied Data is not a valid base64-String jsPDF.convertBase64ToBinaryString ")}}return fe};t.getImageProperties=function(L){var D,M,Z="";if(g(L)&&(L=p(L)),typeof L=="string"&&s(L)===n&&((Z=K(L,!1))===""&&(Z=t.loadFile(L)||""),L=Z),M=s(L),!f(M))throw new Error("addImage does not support files of type '"+M+"', please ensure that a plugin for '"+M+"' support is added.");if(!J()||L instanceof Uint8Array||(L=G(L)),!(D=this["process"+M.toUpperCase()](L)))throw new Error("An unknown error occurred whilst processing the image");return D.fileType=M,D}})(Ra.API),(function(t){var n=function(a){if(a!==void 0&&a!="")return!0};Ra.API.events.push(["addPage",function(a){this.internal.getPageInfo(a.pageNumber).pageContext.annotations=[]}]),t.events.push(["putPage",function(a){for(var s,i,c,l=this.internal.getCoordinateString,m=this.internal.getVerticalCoordinateString,d=this.internal.getPageInfoByObjId(a.objId),u=a.pageContext.annotations,f=!1,g=0;g<u.length&&!f;g++)switch((s=u[g]).type){case"link":(n(s.options.url)||n(s.options.pageNumber))&&(f=!0);break;case"reference":case"text":case"freetext":f=!0}if(f!=0){this.internal.write("/Annots [");for(var p=0;p<u.length;p++){s=u[p];var y=this.internal.pdfEscape,b=this.internal.getEncryptor(a.objId);switch(s.type){case"reference":this.internal.write(" "+s.object.objId+" 0 R ");break;case"text":var N=this.internal.newAdditionalObject(),w=this.internal.newAdditionalObject(),C=this.internal.getEncryptor(N.objId),R=s.title||"Note";c="<</Type /Annot /Subtype /Text "+(i="/Rect ["+l(s.bounds.x)+" "+m(s.bounds.y+s.bounds.h)+" "+l(s.bounds.x+s.bounds.w)+" "+m(s.bounds.y)+"] ")+"/Contents ("+y(C(s.contents))+")",c+=" /Popup "+w.objId+" 0 R",c+=" /P "+d.objId+" 0 R",c+=" /T ("+y(C(R))+") >>",N.content=c;var I=N.objId+" 0 R";c="<</Type /Annot /Subtype /Popup "+(i="/Rect ["+l(s.bounds.x+30)+" "+m(s.bounds.y+s.bounds.h)+" "+l(s.bounds.x+s.bounds.w+30)+" "+m(s.bounds.y)+"] ")+" /Parent "+I,s.open&&(c+=" /Open true"),c+=" >>",w.content=c,this.internal.write(N.objId,"0 R",w.objId,"0 R");break;case"freetext":i="/Rect ["+l(s.bounds.x)+" "+m(s.bounds.y)+" "+l(s.bounds.x+s.bounds.w)+" "+m(s.bounds.y+s.bounds.h)+"] ";var _=s.color||"#000000";c="<</Type /Annot /Subtype /FreeText "+i+"/Contents ("+y(b(s.contents))+")",c+=" /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#"+_+")",c+=" /Border [0 0 0]",c+=" >>",this.internal.write(c);break;case"link":if(s.options.name){var J=this.annotations._nameMap[s.options.name];s.options.pageNumber=J.page,s.options.top=J.y}else s.options.top||(s.options.top=0);if(i="/Rect ["+s.finalBounds.x+" "+s.finalBounds.y+" "+s.finalBounds.w+" "+s.finalBounds.h+"] ",c="",s.options.url)c="<</Type /Annot /Subtype /Link "+i+"/Border [0 0 0] /A <</S /URI /URI ("+y(b(s.options.url))+") >>";else if(s.options.pageNumber)switch(c="<</Type /Annot /Subtype /Link "+i+"/Border [0 0 0] /Dest ["+this.internal.getPageInfo(s.options.pageNumber).objId+" 0 R",s.options.magFactor=s.options.magFactor||"XYZ",s.options.magFactor){case"Fit":c+=" /Fit]";break;case"FitH":c+=" /FitH "+s.options.top+"]";break;case"FitV":s.options.left=s.options.left||0,c+=" /FitV "+s.options.left+"]";break;case"XYZ":default:var T=m(s.options.top);s.options.left=s.options.left||0,s.options.zoom===void 0&&(s.options.zoom=0),c+=" /XYZ "+s.options.left+" "+T+" "+s.options.zoom+"]"}c!=""&&(c+=" >>",this.internal.write(c))}}this.internal.write("]")}}]),t.createAnnotation=function(a){var s=this.internal.getCurrentPageInfo();switch(a.type){case"link":this.link(a.bounds.x,a.bounds.y,a.bounds.w,a.bounds.h,a);break;case"text":case"freetext":s.pageContext.annotations.push(a)}},t.link=function(a,s,i,c,l){var m=this.internal.getCurrentPageInfo(),d=this.internal.getCoordinateString,u=this.internal.getVerticalCoordinateString;m.pageContext.annotations.push({finalBounds:{x:d(a),y:u(s),w:d(a+i),h:u(s+c)},options:l,type:"link"})},t.textWithLink=function(a,s,i,c){var l,m,d=this.getTextWidth(a),u=this.internal.getLineHeight()/this.internal.scaleFactor;if(c.maxWidth!==void 0){m=c.maxWidth;var f=this.splitTextToSize(a,m).length;l=Math.ceil(u*f)}else m=d,l=u;return this.text(a,s,i,c),i+=.2*u,c.align==="center"&&(s-=d/2),c.align==="right"&&(s-=d),this.link(s,i-u,m,l,c),d},t.getTextWidth=function(a){var s=this.internal.getFontSize();return this.getStringUnitWidth(a)*s/this.internal.scaleFactor}})(Ra.API),(function(t){var n={1569:[65152],1570:[65153,65154],1571:[65155,65156],1572:[65157,65158],1573:[65159,65160],1574:[65161,65162,65163,65164],1575:[65165,65166],1576:[65167,65168,65169,65170],1577:[65171,65172],1578:[65173,65174,65175,65176],1579:[65177,65178,65179,65180],1580:[65181,65182,65183,65184],1581:[65185,65186,65187,65188],1582:[65189,65190,65191,65192],1583:[65193,65194],1584:[65195,65196],1585:[65197,65198],1586:[65199,65200],1587:[65201,65202,65203,65204],1588:[65205,65206,65207,65208],1589:[65209,65210,65211,65212],1590:[65213,65214,65215,65216],1591:[65217,65218,65219,65220],1592:[65221,65222,65223,65224],1593:[65225,65226,65227,65228],1594:[65229,65230,65231,65232],1601:[65233,65234,65235,65236],1602:[65237,65238,65239,65240],1603:[65241,65242,65243,65244],1604:[65245,65246,65247,65248],1605:[65249,65250,65251,65252],1606:[65253,65254,65255,65256],1607:[65257,65258,65259,65260],1608:[65261,65262],1609:[65263,65264,64488,64489],1610:[65265,65266,65267,65268],1649:[64336,64337],1655:[64477],1657:[64358,64359,64360,64361],1658:[64350,64351,64352,64353],1659:[64338,64339,64340,64341],1662:[64342,64343,64344,64345],1663:[64354,64355,64356,64357],1664:[64346,64347,64348,64349],1667:[64374,64375,64376,64377],1668:[64370,64371,64372,64373],1670:[64378,64379,64380,64381],1671:[64382,64383,64384,64385],1672:[64392,64393],1676:[64388,64389],1677:[64386,64387],1678:[64390,64391],1681:[64396,64397],1688:[64394,64395],1700:[64362,64363,64364,64365],1702:[64366,64367,64368,64369],1705:[64398,64399,64400,64401],1709:[64467,64468,64469,64470],1711:[64402,64403,64404,64405],1713:[64410,64411,64412,64413],1715:[64406,64407,64408,64409],1722:[64414,64415],1723:[64416,64417,64418,64419],1726:[64426,64427,64428,64429],1728:[64420,64421],1729:[64422,64423,64424,64425],1733:[64480,64481],1734:[64473,64474],1735:[64471,64472],1736:[64475,64476],1737:[64482,64483],1739:[64478,64479],1740:[64508,64509,64510,64511],1744:[64484,64485,64486,64487],1746:[64430,64431],1747:[64432,64433]},a={65247:{65154:65269,65156:65271,65160:65273,65166:65275},65248:{65154:65270,65156:65272,65160:65274,65166:65276},65165:{65247:{65248:{65258:65010}}},1617:{1612:64606,1613:64607,1614:64608,1615:64609,1616:64610}},s={1612:64606,1613:64607,1614:64608,1615:64609,1616:64610},i=[1570,1571,1573,1575];t.__arabicParser__={};var c=t.__arabicParser__.isInArabicSubstitutionA=function(N){return n[N.charCodeAt(0)]!==void 0},l=t.__arabicParser__.isArabicLetter=function(N){return typeof N=="string"&&/^[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]+$/.test(N)},m=t.__arabicParser__.isArabicEndLetter=function(N){return l(N)&&c(N)&&n[N.charCodeAt(0)].length<=2},d=t.__arabicParser__.isArabicAlfLetter=function(N){return l(N)&&i.indexOf(N.charCodeAt(0))>=0};t.__arabicParser__.arabicLetterHasIsolatedForm=function(N){return l(N)&&c(N)&&n[N.charCodeAt(0)].length>=1};var u=t.__arabicParser__.arabicLetterHasFinalForm=function(N){return l(N)&&c(N)&&n[N.charCodeAt(0)].length>=2};t.__arabicParser__.arabicLetterHasInitialForm=function(N){return l(N)&&c(N)&&n[N.charCodeAt(0)].length>=3};var f=t.__arabicParser__.arabicLetterHasMedialForm=function(N){return l(N)&&c(N)&&n[N.charCodeAt(0)].length==4},g=t.__arabicParser__.resolveLigatures=function(N){var w=0,C=a,R="",I=0;for(w=0;w<N.length;w+=1)C[N.charCodeAt(w)]!==void 0?(I++,typeof(C=C[N.charCodeAt(w)])=="number"&&(R+=String.fromCharCode(C),C=a,I=0),w===N.length-1&&(C=a,R+=N.charAt(w-(I-1)),w-=I-1,I=0)):(C=a,R+=N.charAt(w-I),w-=I,I=0);return R};t.__arabicParser__.isArabicDiacritic=function(N){return N!==void 0&&s[N.charCodeAt(0)]!==void 0};var p=t.__arabicParser__.getCorrectForm=function(N,w,C){return l(N)?c(N)===!1?-1:!u(N)||!l(w)&&!l(C)||!l(C)&&m(w)||m(N)&&!l(w)||m(N)&&d(w)||m(N)&&m(w)?0:f(N)&&l(w)&&!m(w)&&l(C)&&u(C)?3:m(N)||!l(C)?1:2:-1},y=function(N){var w=0,C=0,R=0,I="",_="",J="",T=(N=N||"").split("\\s+"),G=[];for(w=0;w<T.length;w+=1){for(G.push(""),C=0;C<T[w].length;C+=1)I=T[w][C],_=T[w][C-1],J=T[w][C+1],l(I)?(R=p(I,_,J),G[w]+=R!==-1?String.fromCharCode(n[I.charCodeAt(0)][R]):I):G[w]+=I;G[w]=g(G[w])}return G.join(" ")},b=t.__arabicParser__.processArabic=t.processArabic=function(){var N,w=typeof arguments[0]=="string"?arguments[0]:arguments[0].text,C=[];if(Array.isArray(w)){var R=0;for(C=[],R=0;R<w.length;R+=1)Array.isArray(w[R])?C.push([y(w[R][0]),w[R][1],w[R][2]]):C.push([y(w[R])]);N=C}else N=y(w);return typeof arguments[0]=="string"?N:(arguments[0].text=N,arguments[0])};t.events.push(["preProcessText",b])})(Ra.API),Ra.API.autoPrint=function(t){var n;switch((t=t||{}).variant=t.variant||"non-conform",t.variant){case"javascript":this.addJS("print({});");break;case"non-conform":default:this.internal.events.subscribe("postPutResources",(function(){n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /Named"),this.internal.out("/Type /Action"),this.internal.out("/N /Print"),this.internal.out(">>"),this.internal.out("endobj")})),this.internal.events.subscribe("putCatalog",(function(){this.internal.out("/OpenAction "+n+" 0 R")}))}return this},(function(t){var n=function(){var a=void 0;Object.defineProperty(this,"pdf",{get:function(){return a},set:function(m){a=m}});var s=150;Object.defineProperty(this,"width",{get:function(){return s},set:function(m){s=isNaN(m)||Number.isInteger(m)===!1||m<0?150:m,this.getContext("2d").pageWrapXEnabled&&(this.getContext("2d").pageWrapX=s+1)}});var i=300;Object.defineProperty(this,"height",{get:function(){return i},set:function(m){i=isNaN(m)||Number.isInteger(m)===!1||m<0?300:m,this.getContext("2d").pageWrapYEnabled&&(this.getContext("2d").pageWrapY=i+1)}});var c=[];Object.defineProperty(this,"childNodes",{get:function(){return c},set:function(m){c=m}});var l={};Object.defineProperty(this,"style",{get:function(){return l},set:function(m){l=m}}),Object.defineProperty(this,"parentNode",{})};n.prototype.getContext=function(a,s){var i;if((a=a||"2d")!=="2d")return null;for(i in s)this.pdf.context2d.hasOwnProperty(i)&&(this.pdf.context2d[i]=s[i]);return this.pdf.context2d._canvas=this,this.pdf.context2d},n.prototype.toDataURL=function(){throw new Error("toDataURL is not implemented.")},t.events.push(["initialized",function(){this.canvas=new n,this.canvas.pdf=this}])})(Ra.API),(function(t){var n={left:0,top:0,bottom:0,right:0},a=!1,s=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},n),this.internal.__cell__.margins.width=this.getPageWidth(),i.call(this))},i=function(){this.internal.__cell__.lastCell=new c,this.internal.__cell__.pages=1},c=function(){var d=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return d},set:function(N){d=N}});var u=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return u},set:function(N){u=N}});var f=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return f},set:function(N){f=N}});var g=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return g},set:function(N){g=N}});var p=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return p},set:function(N){p=N}});var y=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return y},set:function(N){y=N}});var b=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return b},set:function(N){b=N}}),this};c.prototype.clone=function(){return new c(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},c.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},t.setHeaderFunction=function(d){return s.call(this),this.internal.__cell__.headerFunction=typeof d=="function"?d:void 0,this},t.getTextDimensions=function(d,u){s.call(this);var f=(u=u||{}).fontSize||this.getFontSize(),g=u.font||this.getFont(),p=u.scaleFactor||this.internal.scaleFactor,y=0,b=0,N=0,w=this;if(!Array.isArray(d)&&typeof d!="string"){if(typeof d!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");d=String(d)}var C=u.maxWidth;C>0?typeof d=="string"?d=this.splitTextToSize(d,C):Object.prototype.toString.call(d)==="[object Array]"&&(d=d.reduce((function(I,_){return I.concat(w.splitTextToSize(_,C))}),[])):d=Array.isArray(d)?d:[d];for(var R=0;R<d.length;R++)y<(N=this.getStringUnitWidth(d[R],{font:g})*f)&&(y=N);return y!==0&&(b=d.length),{w:y/=p,h:Math.max((b*f*this.getLineHeightFactor()-f*(this.getLineHeightFactor()-1))/p,0)}},t.cellAddPage=function(){s.call(this),this.addPage();var d=this.internal.__cell__.margins||n;return this.internal.__cell__.lastCell=new c(d.left,d.top,void 0,void 0),this.internal.__cell__.pages+=1,this};var l=t.cell=function(){var d;d=arguments[0]instanceof c?arguments[0]:new c(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]),s.call(this);var u=this.internal.__cell__.lastCell,f=this.internal.__cell__.padding,g=this.internal.__cell__.margins||n,p=this.internal.__cell__.tableHeaderRow,y=this.internal.__cell__.printHeaders;return u.lineNumber!==void 0&&(u.lineNumber===d.lineNumber?(d.x=(u.x||0)+(u.width||0),d.y=u.y||0):u.y+u.height+d.height+g.bottom>this.getPageHeight()?(this.cellAddPage(),d.y=g.top,y&&p&&(this.printHeaderRow(d.lineNumber,!0),d.y+=p[0].height)):d.y=u.y+u.height||d.y),d.text[0]!==void 0&&(this.rect(
3796d.x,d.y,d.width,d.height,a===!0?"FD":void 0),d.align==="right"?this.text(d.text,d.x+d.width-f,d.y+f,{align:"right",baseline:"top"}):d.align==="center"?this.text(d.text,d.x+d.width/2,d.y+f,{align:"center",baseline:"top",maxWidth:d.width-f-f}):this.text(d.text,d.x+f,d.y+f,{align:"left",baseline:"top",maxWidth:d.width-f-f})),this.internal.__cell__.lastCell=d,this};t.table=function(d,u,f,g,p){if(s.call(this),!f)throw new Error("No data for PDF table.");var y,b,N,w,C=[],R=[],I=[],_={},J={},T=[],G=[],z=(p=p||{}).autoSize||!1,H=p.printHeaders!==!1,K=p.css&&p.css["font-size"]!==void 0?16*p.css["font-size"]:p.fontSize||12,L=p.margins||Object.assign({width:this.getPageWidth()},n),D=typeof p.padding=="number"?p.padding:3,M=p.headerBackgroundColor||"#c8c8c8",Z=p.headerTextColor||"#000";if(i.call(this),this.internal.__cell__.printHeaders=H,this.internal.__cell__.margins=L,this.internal.__cell__.table_font_size=K,this.internal.__cell__.padding=D,this.internal.__cell__.headerBackgroundColor=M,this.internal.__cell__.headerTextColor=Z,this.setFontSize(K),g==null)R=C=Object.keys(f[0]),I=C.map((function(){return"left"}));else if(Array.isArray(g)&&ur(g[0])==="object")for(C=g.map((function(je){return je.name})),R=g.map((function(je){return je.prompt||je.name||""})),I=g.map((function(je){return je.align||"left"})),y=0;y<g.length;y+=1)J[g[y].name]=g[y].width*(19.049976/25.4);else Array.isArray(g)&&typeof g[0]=="string"&&(R=C=g,I=C.map((function(){return"left"})));if(z||Array.isArray(g)&&typeof g[0]=="string")for(y=0;y<C.length;y+=1){for(_[w=C[y]]=f.map((function(je){return je[w]})),this.setFont(void 0,"bold"),T.push(this.getTextDimensions(R[y],{fontSize:this.internal.__cell__.table_font_size,scaleFactor:this.internal.scaleFactor}).w),b=_[w],this.setFont(void 0,"normal"),N=0;N<b.length;N+=1)T.push(this.getTextDimensions(b[N],{fontSize:this.internal.__cell__.table_font_size,scaleFactor:this.internal.scaleFactor}).w);J[w]=Math.max.apply(null,T)+D+D,T=[]}if(H){var fe={};for(y=0;y<C.length;y+=1)fe[C[y]]={},fe[C[y]].text=R[y],fe[C[y]].align=I[y];var q=m.call(this,fe,J);G=C.map((function(je){return new c(d,u,J[je],q,fe[je].text,void 0,fe[je].align)})),this.setTableHeaderRow(G),this.printHeaderRow(1,!1)}var ne=g.reduce((function(je,V){return je[V.name]=V.align,je}),{});for(y=0;y<f.length;
3796y+=1){"rowStart"in p&&p.rowStart instanceof Function&&p.rowStart({row:y,data:f[y]},this);var ae=m.call(this,f[y],J);for(N=0;N<C.length;N+=1){var Y=f[y][C[N]];"cellStart"in p&&p.cellStart instanceof Function&&p.cellStart({row:y,col:N,data:Y},this),l.call(this,new c(d,u,J[C[N]],ae,Y,y+2,ne[C[N]]))}}return this.internal.__cell__.table_x=d,this.internal.__cell__.table_y=u,this};var m=function(d,u){var f=this.internal.__cell__.padding,g=this.internal.__cell__.table_font_size,p=this.internal.scaleFactor;return Object.keys(d).map((function(y){var b=d[y];return this.splitTextToSize(b.hasOwnProperty("text")?b.text:b,u[y]-f-f)}),this).map((function(y){return this.getLineHeightFactor()*y.length*g/p+f+f}),this).reduce((function(y,b){return Math.max(y,b)}),0)};t.setTableHeaderRow=function(d){s.call(this),this.internal.__cell__.tableHeaderRow=d},t.printHeaderRow=function(d,u){if(s.call(this),!this.internal.__cell__.tableHeaderRow)throw new Error("Property tableHeaderRow does not exist.");var f;if(a=!0,typeof this.internal.__cell__.headerFunction=="function"){var g=this.internal.__cell__.headerFunction(this,this.internal.__cell__.pages);this.internal.__cell__.lastCell=new c(g[0],g[1],g[2],g[3],void 0,-1)}this.setFont(void 0,"bold");for(var p=[],y=0;y<this.internal.__cell__.tableHeaderRow.length;y+=1){f=this.internal.__cell__.tableHeaderRow[y].clone(),u&&(f.y=this.internal.__cell__.margins.top||0,p.push(f)),f.lineNumber=d;var b=this.getTextColor();this.setTextColor(this.internal.__cell__.headerTextColor),this.setFillColor(this.internal.__cell__.headerBackgroundColor),l.call(this,f),this.setTextColor(b)}p.length>0&&this.setTableHeaderRow(p),this.setFont(void 0,"normal"),a=!1}})(Ra.API);var TE={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},ME=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],H1=RE(ME),$E=[100,200,300,400,500,600,700,800,900],BF=RE($E);function W1(t){var n=t.family.replace(/"|'/g,"").toLowerCase(),a=(function(c){return TE[c=c||"normal"]?c:"normal"})(t.style),s=(function(c){if(!c)return 400;if(typeof c=="number")return c>=100&&c<=900&&c%100==0?c:400;if(/^\d00$/.test(c))return parseInt(c);switch(c){case"bold":return 700;case"normal":default:return 400}})(t.weight),i=(function(c){return typeof H1[c=c||"normal"]=="number"?c:"normal"})(t.stretch);return{family:n,style:a,weight:s,stretch:i,src:t.src||[],ref:t.ref||{name:n,style:[i,a,s].join(" ")}}}function WI(t,n,a,s){var i;for(i=a;i>=0&&i<n.length;i+=s)if(t[n[i]])return t[n[i]];for(i=a;i>=0&&i<n.length;i-=s)if(t[n[i]])return t[n[i]]}var FF={"sans-serif":"helvetica",fixed:"courier",monospace:"courier",terminal:"courier",cursive:"times",fantasy:"times",serif:"times"},GI={caption:"times",icon:"times",menu:"times","message-box":"times","small-caption":"times","status-bar":"times"};function YI(t){return[t.stretch,t.style,t.weight,t.family].join(" ")}function UF(t,n,a){for(var s=(a=a||{}).defaultFontFamily||"times",i=Object.assign({},FF,a.genericFontFamilies||{}),c=null,l=null,m=0;m<n.length;++m)if(i[(c=W1(n[m])).family]&&(c.family=i[c.family]),t.hasOwnProperty(c.family)){l=t[c.family];break}if(!(l=l||t[s]))throw new Error("Could not find a font-family for the rule '"+YI(c)+"' and default family '"+s+"'.");if(l=(function(d,u){if(u[d])return u[d];var f=H1[d],g=f<=H1.normal?-1:1,p=WI(u,ME,f,g);if(!p)throw new Error("Could not find a matching font-stretch value for "+d);return p})(c.stretch,l),l=(function(d,u){if(u[d])return u[d];for(var f=TE[d],g=0;g<f.length;++g)if(u[f[g]])return u[f[g]];throw new Error("Could not find a matching font-style for "+d)})(c.style,l),!(l=(function(d,u){if(u[d])return u[d];if(d===400&&u[500])return u[500];if(d===500&&u[400])return u[400];var f=BF[d],g=WI(u,$E,f,d<400?-1:1);if(!g)throw new Error("Could not find a matching font-weight for value "+d);return g})(c.weight,l)))throw new Error("Failed to resolve a font for the rule '"+YI(c)+"'.");return l}function QI(t){return t.trimLeft()}function zF(t,n){for(var a=0;a<t.length;){if(t.charAt(a)===n)return[t.substring(0,a),t.substring(a+1)];a+=1}return null}function qF(t){var n=t.match(/^(-[a-z_]|[a-z_])[a-z0-9_-]*/i);return n===null?null:[n[0],t.substring(n[0].length)]}
vendor: 9,902 bytes, line 3796
3796var Pv,JI,KI,vj=["times"];(function(t){var n,a,s,i,c,l,m,d,u,f=function($){return $=$||{},this.isStrokeTransparent=$.isStrokeTransparent||!1,this.strokeOpacity=$.strokeOpacity||1,this.strokeStyle=$.strokeStyle||"#000000",this.fillStyle=$.fillStyle||"#000000",this.isFillTransparent=$.isFillTransparent||!1,this.fillOpacity=$.fillOpacity||1,this.font=$.font||"10px sans-serif",this.textBaseline=$.textBaseline||"alphabetic",this.textAlign=$.textAlign||"left",this.lineWidth=$.lineWidth||1,this.lineJoin=$.lineJoin||"miter",this.lineCap=$.lineCap||"butt",this.path=$.path||[],this.transform=$.transform!==void 0?$.transform.clone():new d,this.globalCompositeOperation=$.globalCompositeOperation||"normal",this.globalAlpha=$.globalAlpha||1,this.clip_path=$.clip_path||[],this.currentPoint=$.currentPoint||new l,this.miterLimit=$.miterLimit||10,this.lastPoint=$.lastPoint||new l,this.lineDashOffset=$.lineDashOffset||0,this.lineDash=$.lineDash||[],this.margin=$.margin||[0,0,0,0],this.prevPageLastElemOffset=$.prevPageLastElemOffset||0,this.ignoreClearRect=typeof $.ignoreClearRect!="boolean"||$.ignoreClearRect,this};t.events.push(["initialized",function(){this.context2d=new g(this),n=this.internal.f2,a=this.internal.getCoordinateString,s=this.internal.getVerticalCoordinateString,i=this.internal.getHorizontalCoordinate,c=this.internal.getVerticalCoordinate,l=this.internal.Point,m=this.internal.Rectangle,d=this.internal.Matrix,u=new f}]);var g=function($){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var F=$;Object.defineProperty(this,"pdf",{get:function(){return F}});var P=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return P},set:function(_e){P=!!_e}});var ue=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return ue},set:function(_e){ue=!!_e}});var me=0;Object.defineProperty(this,"posX",{get:function(){return me},set:function(_e){isNaN(_e)||(me=_e)}});var ge=0;Object.defineProperty(this,"posY",{get:function(){return ge},set:function(_e){isNaN(_e)||(ge=_e)}}),Object.defineProperty(this,"margin",{get:function(){return u.margin},set:function(_e){var ee;typeof _e=="number"?ee=[_e,_e,_e,_e]:((ee=new Array(4))[0]=_e[0],ee[1]=_e.length>=2?_e[1]:ee[0],ee[2]=_e.length>=3?_e[2]:ee[0],ee[3]=_e.length>=4?_e[3]:ee[1]),u.margin=ee}});var de=!1;Object.defineProperty(this,"autoPaging",{get:function(){return de},set:function(_e){de=_e}});var Pe=0;Object.defineProperty(this,"lastBreak",{get:function(){return Pe},set:function(_e){Pe=_e}});var Re=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Re},set:function(_e){Re=_e}}),Object.defineProperty(this,"ctx",{get:function(){return u},set:function(_e){_e instanceof f&&(u=_e)}}),Object.defineProperty(this,"path",{get:function(){return u.path},set:function(_e){u.path=_e}});var Ee=[];Object.defineProperty(this,"ctxStack",{get:function(){return Ee},set:function(_e){Ee=_e}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(_e){var ee;ee=p(_e),this.ctx.fillStyle=ee.style,this.ctx.isFillTransparent=ee.a===0,this.ctx.fillOpacity=ee.a,this.pdf.setFillColor(ee.r,ee.g,ee.b,{a:ee.a}),this.pdf.setTextColor(ee.r,ee.g,ee.b,{a:ee.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(_e){var ee=p(_e);this.ctx.strokeStyle=ee.style,this.ctx.isStrokeTransparent=ee.a===0,this.ctx.strokeOpacity=ee.a,ee.a===0?this.pdf.setDrawColor(255,255,255):(ee.a,this.pdf.setDrawColor(ee.r,ee.g,ee.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(_e){["butt","round","square"].indexOf(_e)!==-1&&(this.ctx.lineCap=_e,this.pdf.setLineCap(_e))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(_e){isNaN(_e)||(this.ctx.lineWidth=_e,this.pdf.setLineWidth(_e))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(_e){["bevel","round","miter"].indexOf(_e)!==-1&&(this.ctx.lineJoin=_e,this.pdf.setLineJoin(_e))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(_e){isNaN(_e)||(this.ctx.miterLimit=_e,this.pdf.setMiterLimit(_e))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(_e){this.ctx.textBaseline=_e}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(_e){["right","end","center","left","start"].indexOf(_e)!==-1&&(this.ctx.textAlign=_e)}});var Be=null;function We(_e,ee){if(Be===null){var qe=(function(se){var pe=[];return Object.keys(se).forEach((function(Se){se[Se].forEach((function(Me){var ot=null;switch(Me){case"bold":ot={family:Se,weight:"bold"};break;case"italic":ot={family:Se,style:"italic"};break;case"bolditalic":ot={family:Se,weight:"bold",style:"italic"};break;case"":case"normal":ot={family:Se}}ot!==null&&(ot.ref={name:Se,style:Me},pe.push(ot))}))})),pe})(_e.getFontList());Be=(function(se){for(var pe={},Se=0;Se<se.length;++Se){var Me=W1(se[Se]),ot=Me.family,wt=Me.stretch,ct=Me.style,Ce=Me.weight;pe[ot]=pe[ot]||{},pe[ot][wt]=pe[ot][wt]||{},pe[ot][wt][ct]=pe[ot][wt][ct]||{},pe[ot][wt][ct][Ce]=Me}return pe})(qe.concat(ee))}return Be}var it=null;Object.defineProperty(this,"fontFaces",{get:function(){return it},set:function(_e){Be=null,it=_e}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(_e){var ee;if(this.ctx.font=_e,(ee=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i.exec(_e))!==null){var qe=ee[1],se=(ee[2],ee[3]),pe=ee[4],Se=(ee[5],ee[6]),Me=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(pe)[2];pe=Math.floor(Me==="px"?parseFloat(pe)*this.pdf.internal.scaleFactor:Me==="em"?parseFloat(pe)*this.pdf.getFontSize():parseFloat(pe)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(pe);var ot=(function(Ye){var Je,le,nt=[],xt=Ye.trim();if(xt==="")return vj;if(xt in GI)return[GI[xt]];for(;xt!=="";){switch(le=null,Je=(xt=QI(xt)).charAt(0)){case'"':case"'":le=zF(xt.substring(1),Je);break;default:le=qF(xt)}if(le===null||(nt.push(le[0]),(xt=QI(le[1]))!==""&&xt.charAt(0)!==","))return vj;xt=xt.replace(/^,/,"")}return nt})(Se);if(this.fontFaces){var wt=UF(We(this.pdf,this.fontFaces),ot.map((function(Ye){return{family:Ye,stretch:"normal",weight:se,style:qe}})));this.pdf.setFont(wt.ref.name,wt.ref.style)}else{var ct="";(se==="bold"||parseInt(se,10)>=700||qe==="bold")&&(ct="bold"),qe==="italic"&&(ct+="italic"),ct.length===0&&(ct="normal");for(var Ce="",De={arial:"Helvetica",Arial:"Helvetica",verdana:"Helvetica",Verdana:"Helvetica",helvetica:"Helvetica",Helvetica:"Helvetica","sans-serif":"Helvetica",fixed:"Courier",monospace:"Courier",terminal:"Courier",cursive:"Times",fantasy:"Times",serif:"Times"},Te=0;Te<ot.length;Te++){if(this.pdf.internal.getFont(ot[Te],ct,{noFallback:!0,disableWarning:!0})!==void 0){Ce=ot[Te];break}if(ct==="bolditalic"&&this.pdf.internal.getFont(ot[Te],"bold",{noFallback:!0,disableWarning:!0})!==void 0)Ce=ot[Te],ct="bold";else if(this.pdf.internal.getFont(ot[Te],"normal",{noFallback:!0,disableWarning:!0})!==void 0){Ce=ot[Te],ct="normal";break}}if(Ce===""){for(var ce=0;ce<ot.length;ce++)if(De[ot[ce]]){Ce=De[ot[ce]];break}}Ce=Ce===""?"Times":Ce,this.pdf.setFont(Ce,ct)}}}}),Object.defineProperty(this,"globalCompositeOperation",{get:function(){return this.ctx.globalCompositeOperation},set:function(_e){this.ctx.globalCompositeOperation=_e}}),Object.defineProperty(this,"globalAlpha",{get:function(){return this.ctx.globalAlpha},set:function(_e){this.ctx.globalAlpha=_e}}),Object.defineProperty(this,"lineDashOffset",{get:function(){return this.ctx.lineDashOffset},set:function(_e){this.ctx.lineDashOffset=_e,V.call(this)}}),Object.defineProperty(this,"lineDash",{get:function(){return this.ctx.lineDash},set:function(_e){this.ctx.lineDash=_e,V.call(this)}}),Object.defineProperty(this,"ignoreClearRect",{get:function(){return this.ctx.ignoreClearRect},set:function(_e){this.ctx.ignoreClearRect=!!_e}})};g.prototype.setLineDash=function($){this.lineDash=$},g.prototype.getLineDash=function(){return this.lineDash.length%2?this.lineDash.concat(this.lineDash):this.lineDash.slice()},g.prototype.fill=function(){_.call(this,"fill",!1)},g.prototype.stroke=function(){_.call(this,"stroke",!1)},g.prototype.beginPath=function(){this.path=[{type:"begin"}]},g.prototype.moveTo=function($,F){if(isNaN($)||isNaN(F))throw Ar.error("jsPDF.context2d.moveTo: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.moveTo");var P=this.ctx.transform.applyToPoint(new l($,F));this.path.push({type:"mt",x:P.x,y:P.y}),this.ctx.lastPoint=new l($,F)},g.prototype.closePath=function(){var $=new l(0,0),F=0;for(F=this.path.length-1;F!==-1;F--)if(this.path[F].type==="begin"&&ur(this.path[F+1])==="object"&&typeof this.path[F+1].x=="number"){$=new l(this.path[F+1].x,this.path[F+1].y);break}this.path.push({type:"close"}),this.ctx.lastPoint=new l($.x,$.y)},g.prototype.lineTo=function($,F){if(isNaN($)||isNaN(F))throw Ar.error("jsPDF.context2d.lineTo: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.lineTo");var P=this.ctx.transform.applyToPoint(new l($,F));this.path.push({type:"lt",x:P.x,y:P.y}),this.ctx.lastPoint=new l(P.x,P.y)},g.prototype.clip=function(){this.ctx.clip_path=JSON.parse(JSON.stringify(this.path)),_.call(this,null,!0)},g.prototype.quadraticCurveTo=function($,F,P,ue){if(isNaN(P)||isNaN(ue)||isNaN($)||isNaN(F))throw Ar.error("jsPDF.context2d.quadraticCurveTo: Invalid arguments",arguments),new Error("Invalid arguments passed to
3796jsPDF.context2d.quadraticCurveTo");var me=this.ctx.transform.applyToPoint(new l(P,ue)),ge=this.ctx.transform.applyToPoint(new l($,F));this.path.push({type:"qct",x1:ge.x,y1:ge.y,x:me.x,y:me.y}),this.ctx.lastPoint=new l(me.x,me.y)},g.prototype.bezierCurveTo=function($,F,P,ue,me,ge){if(isNaN(me)||isNaN(ge)||isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue))throw Ar.error("jsPDF.context2d.bezierCurveTo: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.bezierCurveTo");var de=this.ctx.transform.applyToPoint(new l(me,ge)),Pe=this.ctx.transform.applyToPoint(new l($,F)),Re=this.ctx.transform.applyToPoint(new l(P,ue));this.path.push({type:"bct",x1:Pe.x,y1:Pe.y,x2:Re.x,y2:Re.y,x:de.x,y:de.y}),this.ctx.lastPoint=new l(de.x,de.y)},g.prototype.arc=function($,F,P,ue,me,ge){if(isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue)||isNaN(me))throw Ar.error("jsPDF.context2d.arc: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.arc");if(ge=!!ge,!this.ctx.transform.isIdentity){var de=this.ctx.transform.applyToPoint(new l($,F));$=de.x,F=de.y;var Pe=this.ctx.transform.applyToPoint(new l(0,P)),Re=this.ctx.transform.applyToPoint(new l(0,0));P=Math.sqrt(Math.pow(Pe.x-Re.x,2)+Math.pow(Pe.y-Re.y,2))}Math.abs(me-ue)>=2*Math.PI&&(ue=0,me=2*Math.PI),this.path.push({type:"arc",x:$,y:F,radius:P,startAngle:ue,endAngle:me,counterclockwise:ge})},g.prototype.arcTo=function($,F,P,ue,me){throw new Error("arcTo not implemented.")},g.prototype.rect=function($,F,P,ue){if(isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue))throw Ar.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo($,F),this.lineTo($+P,F),this.lineTo($+P,F+ue),this.lineTo($,F+ue),this.lineTo($,F),this.lineTo($+P,F),this.lineTo($,F)},g.prototype.fillRect=function($,F,P,ue){if(isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue))throw Ar.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!y.call(this)){var me={};this.lineCap!=="butt"&&(me.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(me.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect($,F,P,ue),this.fill(),me.hasOwnProperty("lineCap")&&(this.lineCap=me.lineCap),me.hasOwnProperty("lineJoin")&&(this.lineJoin=me.lineJoin)}},g.prototype.strokeRect=function($,F,P,ue){if(isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue))throw Ar.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");b.call(this)||(this.beginPath(),this.rect($,F,P,ue),this.stroke())},g.prototype.clearRect=function($,F,P,ue){if(isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue))throw Ar.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect($,F,P,ue))},g.prototype.save=function($){$=typeof $!="boolean"||$;for(var F=this.pdf.internal.getCurrentPageInfo().pageNumber,P=0;P<this.pdf.internal.getNumberOfPages();P++)this.pdf.setPage(P+1),this.pdf.internal.out("q");if(this.pdf.setPage(F),$){this.ctx.fontSize=this.pdf.internal.getFontSize();var ue=new f(this.ctx);this.ctxStack.push(this.ctx),this.ctx=ue}},g.prototype.restore=function($){$=typeof $!="boolean"||$;for(var F=this.pdf.internal.getCurrentPageInfo().pageNumber,P=0;P<this.pdf.internal.getNumberOfPages();P++)this.pdf.setPage(P+1),this.pdf.internal.out("Q");this.pdf.setPage(F),$&&this.ctxStack.length!==0&&(this.ctx=this.ctxStack.pop(),this.fillStyle=this.ctx.fillStyle,this.strokeStyle=this.ctx.strokeStyle,this.font=this.ctx.font,this.lineCap=this.ctx.lineCap,this.lineWidth=this.ctx.lineWidth,this.lineJoin=this.ctx.lineJoin,this.lineDash=this.ctx.lineDash,this.lineDashOffset=this.ctx.lineDashOffset)},g.prototype.toDataURL=function(){throw new Error("toDataUrl not implemented.")};var p=function($){var F,P,ue,me;if($.isCanvasGradient===!0&&($=$.getColor()),!$)return{r:0,g:0,b:0,a:0,style:$};if(/transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/.test($))F=0,P=0,ue=0,me=0;else{var ge=/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec($);if(ge!==null)F=parseInt(ge[1]),P=parseInt(ge[2]),ue=parseInt(ge[3]),me=1;else if((ge=/rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)/.exec($))!==null)F=parseInt(ge[1]),P=parseInt(ge[2]),ue=parseInt(ge[3]),me=parseFloat(ge[4]);else{if(me=1,typeof $=="string"&&$.charAt(0)!=="#"){var de=new IE($);$=de.ok?de.toHex():"#000000"}$.length===4?(F=$.substring(1,2),F+=F,P=$.substring(2,3),P+=P,ue=$.substring(3,4),ue
vendor: 15,856 bytes, line 3796
3796+=ue):(F=$.substring(1,3),P=$.substring(3,5),ue=$.substring(5,7)),F=parseInt(F,16),P=parseInt(P,16),ue=parseInt(ue,16)}}return{r:F,g:P,b:ue,a:me,style:$}},y=function(){return this.ctx.isFillTransparent||this.globalAlpha==0},b=function(){return!!(this.ctx.isStrokeTransparent||this.globalAlpha==0)};g.prototype.fillText=function($,F,P,ue){if(isNaN(F)||isNaN(P)||typeof $!="string")throw Ar.error("jsPDF.context2d.fillText: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillText");if(ue=isNaN(ue)?void 0:ue,!y.call(this)){var me=ae(this.ctx.transform.rotation),ge=this.ctx.transform.scaleX;D.call(this,{text:$,x:F,y:P,scale:ge,angle:me,align:this.textAlign,maxWidth:ue})}},g.prototype.strokeText=function($,F,P,ue){if(isNaN(F)||isNaN(P)||typeof $!="string")throw Ar.error("jsPDF.context2d.strokeText: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeText");if(!b.call(this)){ue=isNaN(ue)?void 0:ue;var me=ae(this.ctx.transform.rotation),ge=this.ctx.transform.scaleX;D.call(this,{text:$,x:F,y:P,scale:ge,renderingMode:"stroke",angle:me,align:this.textAlign,maxWidth:ue})}},g.prototype.measureText=function($){if(typeof $!="string")throw Ar.error("jsPDF.context2d.measureText: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.measureText");var F=this.pdf,P=this.pdf.internal.scaleFactor,ue=F.internal.getFontSize(),me=F.getStringUnitWidth($)*ue/F.internal.scaleFactor,ge=function(de){var Pe=(de=de||{}).width||0;return Object.defineProperty(this,"width",{get:function(){return Pe}}),this};return new ge({width:me*=Math.round(96*P/72*1e4)/1e4})},g.prototype.scale=function($,F){if(isNaN($)||isNaN(F))throw Ar.error("jsPDF.context2d.scale: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.scale");var P=new d($,0,0,F,0,0);this.ctx.transform=this.ctx.transform.multiply(P)},g.prototype.rotate=function($){if(isNaN($))throw Ar.error("jsPDF.context2d.rotate: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rotate");var F=new d(Math.cos($),Math.sin($),-Math.sin($),Math.cos($),0,0);this.ctx.transform=this.ctx.transform.multiply(F)},g.prototype.translate=function($,F){if(isNaN($)||isNaN(F))throw Ar.error("jsPDF.context2d.translate: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.translate");var P=new d(1,0,0,1,$,F);this.ctx.transform=this.ctx.transform.multiply(P)},g.prototype.transform=function($,F,P,ue,me,ge){if(isNaN($)||isNaN(F)||isNaN(P)||isNaN(ue)||isNaN(me)||isNaN(ge))throw Ar.error("jsPDF.context2d.transform: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.transform");var de=new d($,F,P,ue,me,ge);this.ctx.transform=this.ctx.transform.multiply(de)},g.prototype.setTransform=function($,F,P,ue,me,ge){$=isNaN($)?1:$,F=isNaN(F)?0:F,P=isNaN(P)?0:P,ue=isNaN(ue)?1:ue,me=isNaN(me)?0:me,ge=isNaN(ge)?0:ge,this.ctx.transform=new d($,F,P,ue,me,ge)};var N=function(){return this.margin[0]>0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};g.prototype.drawImage=function($,F,P,ue,me,ge,de,Pe,Re){var Ee=this.pdf.getImageProperties($),Be=1,We=1,it=1,_e=1;ue!==void 0&&Pe!==void 0&&(it=Pe/ue,_e=Re/me,Be=Ee.width/ue*Pe/ue,We=Ee.height/me*Re/me),ge===void 0&&(ge=F,de=P,F=0,P=0),ue!==void 0&&Pe===void 0&&(Pe=ue,Re=me),ue===void 0&&Pe===void 0&&(Pe=Ee.width,Re=Ee.height);for(var ee,qe=this.ctx.transform.decompose(),se=ae(qe.rotate.shx),pe=new d,Se=(pe=(pe=(pe=pe.multiply(qe.translate)).multiply(qe.skew)).multiply(qe.scale)).applyToRectangle(new m(ge-F*it,de-P*_e,ue*Be,me*We)),Me=w.call(this,Se),ot=[],wt=0;wt<Me.length;wt+=1)ot.indexOf(Me[wt])===-1&&ot.push(Me[wt]);if(I(ot),this.autoPaging)for(var ct=ot[0],Ce=ot[ot.length-1],De=ct;De<Ce+1;De++){this.pdf.setPage(De);var Te=this.pdf.internal.pageSize.width-this.margin[3]-this.margin[1],ce=De===1?this.posY+this.margin[0]:this.margin[0],Ye=this.pdf.internal.pageSize.height-this.posY-this.margin[0]-this.margin[2],Je=this.pdf.internal.pageSize.height-this.margin[0]-this.margin[2],le=De===1?0:Ye+(De-2)*Je;if(this.ctx.clip_path.length!==0){var nt=this.path;ee=JSON.parse(JSON.stringify(this.ctx.clip_path)),this.path=R(ee,this.posX+this.margin[3],-le+ce+this.ctx.prevPageLastElemOffset),J.call(this,"fill",!0),this.path=nt}var xt=JSON.parse(JSON.stringify(Se));xt=R([xt],this.posX+this.margin[3],-le+ce+this.ctx.prevPageLastElemOffset)[0];var te=(De>ct||De<Ce)&&N.call(this);te&&(this.pdf.saveGraphicsState(),this.pdf.rect(this.margin[3],this.margin[0],Te,Je,null).clip().discardPath()),this.pdf.addImage($,"JPEG",xt.x,xt.y,xt.w,xt.h,null,null,se),te&&this.pdf.restoreGraphicsState()}else this.pdf.addImage($,"JPEG",Se.x,Se.y,Se.w,Se.h,null,null,se)};var w=function($,F,P){var ue=[];F=F||this.pdf.internal.pageSize.width,P=P||this.pdf.internal.pageSize.height-this.margin[0]-this.margin[2];var me=this.posY+this.ctx.prevPageLastElemOffset;switch($.type){default:case"mt":case"lt":ue.push(Math.floor(($.y+me)/P)+1);break;case"arc":ue.push(Math.floor(($.y+me-$.radius)/P)+1),ue.push(Math.floor(($.y+me+$.radius)/P)+1);break;case"qct":var ge=Y(this.ctx.lastPoint.x,this.ctx.lastPoint.y,$.x1,$.y1,$.x,$.y);ue.push(Math.floor((ge.y+me)/P)+1),ue.push(Math.floor((ge.y+ge.h+me)/P)+1);break;case"bct":var de=je(this.ctx.lastPoint.x,this.ctx.lastPoint.y,$.x1,$.y1,$.x2,$.y2,$.x,$.y);ue.push(Math.floor((de.y+me)/P)+1),ue.push(Math.floor((de.y+de.h+me)/P)+1);break;case"rect":ue.push(Math.floor(($.y+me)/P)+1),ue.push(Math.floor(($.y+$.h+me)/P)+1)}for(var Pe=0;Pe<ue.length;Pe+=1)for(;this.pdf.internal.getNumberOfPages()<ue[Pe];)C.call(this);return ue},C=function(){var $=this.fillStyle,F=this.strokeStyle,P=this.font,ue=this.lineCap,me=this.lineWidth,ge=this.lineJoin;this.pdf.addPage(),this.fillStyle=$,this.strokeStyle=F,this.font=P,this.lineCap=ue,this.lineWidth=me,this.lineJoin=ge},R=function($,F,P){for(var ue=0;ue<$.length;ue++)switch($[ue].type){case"bct":$[ue].x2+=F,$[ue].y2+=P;case"qct":$[ue].x1+=F,$[ue].y1+=P;case"mt":case"lt":case"arc":default:$[ue].x+=F,$[ue].y+=P}return $},I=function($){return $.sort((function(F,P){return F-P}))},_=function($,F){for(var P,ue,me=this.fillStyle,ge=this.strokeStyle,de=this.lineCap,Pe=this.lineWidth,Re=Math.abs(Pe*this.ctx.transform.scaleX),Ee=this.lineJoin,Be=JSON.parse(JSON.stringify(this.path)),We=JSON.parse(JSON.stringify(this.path)),it=[],_e=0;_e<We.length;_e++)if(We[_e].x!==void 0)for(var ee=w.call(this,We[_e]),qe=0;qe<ee.length;qe+=1)it.indexOf(ee[qe])===-1&&it.push(ee[qe]);for(var se=0;se<it.length;se++)for(;this.pdf.internal.getNumberOfPages()<it[se];)C.call(this);if(I(it),this.autoPaging)for(var pe=it[0],Se=it[it.length-1],Me=pe;Me<Se+1;Me++){this.pdf.setPage(Me),this.fillStyle=me,this.strokeStyle=ge,this.lineCap=de,this.lineWidth=Re,this.lineJoin=Ee;var ot=this.pdf.internal.pageSize.width-this.margin[3]-this.margin[1],wt=Me===1?this.posY+this.margin[0]:this.margin[0],ct=this.pdf.internal.pageSize.height-this.posY-this.margin[0]-this.margin[2],Ce=this.pdf.internal.pageSize.height-this.margin[0]-this.margin[2],De=Me===1?0:ct+(Me-2)*Ce;if(this.ctx.clip_path.length!==0){var Te=this.path;P=JSON.parse(JSON.stringify(this.ctx.clip_path)),this.path=R(P,this.posX+this.margin[3],-De+wt+this.ctx.prevPageLastElemOffset),J.call(this,$,!0),this.path=Te}if(ue=JSON.parse(JSON.stringify(Be)),this.path=R(ue,this.posX+this.margin[3],-De+wt+this.ctx.prevPageLastElemOffset),F===!1||Me===0){var ce=(Me>pe||Me<Se)&&N.call(this);ce&&(this.pdf.saveGraphicsState(),this.pdf.rect(this.margin[3],this.margin[0],ot,Ce,null).clip().discardPath()),J.call(this,$,F),ce&&this.pdf.restoreGraphicsState()}this.lineWidth=Pe}else this.lineWidth=Re,J.call(this,$,F),this.lineWidth=Pe;this.path=Be},J=function($,F){if(($!=="stroke"||F||!b.call(this))&&($==="stroke"||F||!y.call(this))){for(var P,ue,me=[],ge=this.path,de=0;de<ge.length;de++){var Pe=ge[de];switch(Pe.type){case"begin":me.push({begin:!0});break;case"close":me.push({close:!0});break;case"mt":me.push({start:Pe,deltas:[],abs:[]});break;case"lt":var Re=me.length;if(ge[de-1]&&!isNaN(ge[de-1].x)&&(P=[Pe.x-ge[de-1].x,Pe.y-ge[de-1].y],Re>0)){for(;Re>=0;Re--)if(me[Re-1].close!==!0&&me[Re-1].begin!==!0){me[Re-1].deltas.push(P),me[Re-1].abs.push(Pe);break}}break;case"bct":P=[Pe.x1-ge[de-1].x,Pe.y1-ge[de-1].y,Pe.x2-ge[de-1].x,Pe.y2-ge[de-1].y,Pe.x-ge[de-1].x,Pe.y-ge[de-1].y],me[me.length-1].deltas.push(P);break;case"qct":var Ee=ge[de-1].x+2/3*(Pe.x1-ge[de-1].x),Be=ge[de-1].y+2/3*(Pe.y1-ge[de-1].y),We=Pe.x+2/3*(Pe.x1-Pe.x),it=Pe.y+2/3*(Pe.y1-Pe.y),_e=Pe.x,ee=Pe.y;P=[Ee-ge[de-1].x,Be-ge[de-1].y,We-ge[de-1].x,it-ge[de-1].y,_e-ge[de-1].x,ee-ge[de-1].y],me[me.length-1].deltas.push(P);break;case"arc":me.push({deltas:[],abs:[],arc:!0}),Array.isArray(me[me.length-1].abs)&&me[me.length-1].abs.push(Pe)}}ue=F?null:$==="stroke"?"stroke":"fill";for(var qe=!1,se=0;se<me.length;se++)if(me[se].arc)for(var pe=me[se].abs,Se=0;Se<pe.length;Se++){var Me=pe[Se];Me.type==="arc"?z.call(this,Me.x,Me.y,Me.radius,Me.startAngle,Me.endAngle,Me.counterclockwise,void 0,F,!qe):M.call(this,Me.x,Me.y),qe=!0}else if(me[se].close===!0)this.pdf.internal.out("h"),qe=!1;else if(me[se].begin!==!0){var ot=me[se].start.x,wt=me[se].start.y;Z.call(this,me[se].deltas,ot,wt),qe=!0}ue&&H.call(this,ue),F&&K.call(this)}},T=function($){var F=this.pdf.internal.getFontSize()/this.pdf.internal.scaleFactor,P=F*(this.pdf.internal.getLineHeightFactor()-1);switch(this.ctx.textBaseline){case"bottom":return $-P;case"top":return $+F-P;case"hanging":return $+F-2*P;case"middle":return $+F/2-P;case"ideographic":return $;case"alphabetic":default:return $}},G=function($){return $+this.pdf.internal.getFontSize()/this.pdf.internal.scaleFactor*(this.pdf.internal.getLineHeightFactor()-1)};g.prototype.createLinearGradient=function(){var $=function(){};return $.colorStops=[],$.addColorStop=function(F,P){this.colorStops.push([F,P])},$.getColor=function(){return this.colorStops.length===0?"#000000":this.colorStops[0][1]},$.isCanvasGradient=!0,$},g.prototype.createPattern=function(){return this.createLinearGradient()},g.prototype.createRadialGradient=function(){return this.createLinearGradient()};var z=function($,F,P,ue,me,ge,de,Pe,Re){for(var Ee=q.call(this,P,ue,me,ge),Be=0;Be<Ee.length;Be++){var We=Ee[Be];Be===0&&(Re?L.call(this,We.x1+$,We.y1+F):M.call(this,We.x1+$,We.y1+F)),fe.call(this,$,F,We.x2,We.y2,We.x3,We.y3,We.x4,We.y4)}Pe?K.call(this):H.call(this,de)},H=function($){switch($){case"stroke":this.pdf.internal.out("S");break;case"fill":this.pdf.internal.out("f")}},K=function(){this.pdf.clip(),this.pdf.discardPath()},L=function($,F){this.pdf.internal.out(a($)+" "+s(F)+" m")},D=function($){var F;switch($.align){case"right":case"end":F="right";break;case"center":F="center";break;case"left":case"start":default:F="left"}var P=this.pdf.getTextDimensions($.text),ue=T.call(this,$.y),me=G.call(this,ue)-P.h,ge=this.ctx.transform.applyToPoint(new l($.x,ue)),de=this.ctx.transform.decompose(),Pe=new d;Pe=(Pe=(Pe=Pe.multiply(de.translate)).multiply(de.skew)).multiply(de.scale);for(var Re,Ee,Be,We=this.ctx.transform.applyToRectangle(new m($.x,ue,P.w,P.h)),it=Pe.applyToRectangle(new m($.x,me,P.w,P.h)),_e=w.call(this,it),ee=[],qe=0;qe<_e.length;qe+=1)ee.indexOf(_e[qe])===-1&&ee.push(_e[qe]);if(I(ee),this.autoPaging)for(var se=ee[0],pe=ee[ee.length-1],Se=se;Se<pe+1;Se++){this.pdf.setPage(Se);var Me=Se===1?this.posY+this.margin[0]:this.margin[0],ot=this.pdf.internal.pageSize.height-this.posY-this.margin[0]-this.margin[2],wt=this.pdf.internal.pageSize.height-this.margin[2],ct=wt-this.margin[0],Ce=this.pdf.internal.pageSize.width-this.margin[1],De=Ce-this.margin[3],Te=Se===1?0:ot+(Se-2)*ct;if(this.ctx.clip_path.length!==0){var ce=this.path;Re=JSON.parse(JSON.stringify(this.ctx.clip_path)),this.path=R(Re,this.posX+this.margin[3],-1*Te+Me),J.call(this,"fill",!0),this.path=ce}var Ye=R([JSON.parse(JSON.stringify(it))],this.posX+this.margin[3],-Te+Me+this.ctx.prevPageLastElemOffset)[0];$.scale>=.01&&(Ee=this.pdf.internal.getFontSize(),this.pdf.setFontSize(Ee*$.scale),Be=this.lineWidth,this.lineWidth=Be*$.scale);var Je=this.autoPaging!=="text";if(Je||Ye.y+Ye.h<=wt){if(Je||Ye.y>=Me&&Ye.x<=Ce){var le=Je?$.text:this.pdf.splitTextToSize($.text,$.maxWidth||Ce-Ye.x)[0],nt=R([JSON.parse(JSON.stringify(We))],this.posX+this.margin[3],-Te+Me+this.ctx.prevPageLastElemOffset)[0],xt=Je&&(Se>se||Se<pe)&&N.call(this);xt&&(this.pdf.saveGraphicsState(),this.pdf.rect(this.margin[3],this.margin[0],De,ct,null).clip().discardPath()),this.pdf.text(le,nt.x,nt.y,{angle:$.angle,align:F,renderingMode:$.renderingMode}),xt&&this.pdf.restoreGraphicsState()}}else Ye.y<wt&&(this.ctx.prevPageLastElemOffset+=wt-Ye.y);$.scale>=.01&&(this.pdf.setFontSize(Ee),this.lineWidth=Be)}else $.scale>=.01&&(Ee=this.pdf.internal.getFontSize(),this.pdf.setFontSize(Ee*$.scale),Be=this.lineWidth,this.lineWidth=Be*$.scale),this.pdf.text($.text,ge.x+this.posX,ge.y+this.posY,{angle:$.angle,align:F,renderingMode:$.renderingMode,maxWidth:$.maxWidth}),$.scale>=.01&&(this.pdf.setFontSize(Ee),this.lineWidth=Be)},M=function($,F,P,ue){P=P||0,ue=ue||0,this.pdf.internal.out(a($+P)+" "+s(F+ue)+" l")},Z=function($,F,P){return this.pdf.lines($,F,P,null,null)},fe=function($,F,P,ue,me,ge,de,Pe){this.pdf.internal.out([n(i(P+$)),n(c(ue+F)),n(i(me+$)),n(c(ge+F)),n(i(de+$)),n(c(Pe+F)),"c"].join(" "))},q=function($,F,P,ue){for(var me=2*Math.PI,ge=Math.PI/2;F>P;)F-=me;var de=Math.abs(P-F);de<me&&ue&&(de=me-de);for(var Pe=[],Re=ue?-1:1,Ee=F;de>1e-5;){var Be=Ee+Re*Math.min(de,ge);Pe.push(ne.call(this,$,Ee,Be)),de-=Math.abs(Be-Ee),Ee=Be}return Pe},ne=function($,F,P){var ue=(P-F)/2,me=$*Math.cos(ue),ge=$*Math.sin(ue),de=me,Pe=-ge,Re=de*de+Pe*Pe,Ee=Re+de*me+Pe*ge,Be=4/3*(Math.sqrt(2*Re*Ee)-Ee)/(de*ge-Pe*me),We=de-Be*Pe,it=Pe+Be*de,_e=We,ee=-it,qe=ue+F,se=Math.cos(qe),pe=Math.sin(qe);return{x1:$*Math.cos(F),y1:$*Math.sin(F),x2:We*se-it*pe,y2:We*pe+it*se,x3:_e*se-ee*pe,y3:_e*pe+ee*se,x4:$*Math.cos(P),y4:$*Math.sin(P)}},ae=function($){return 180*$/Math.PI},Y=function($,F,P,ue,me,ge){var de=$+.5*(P-$),Pe=F+.5*(ue-F),Re=me+.5*(P-me),Ee=ge+.5*(ue-ge),Be=Math.min($,me,de,Re),We=Math.max($,me,de,Re),it=Math.min(F,ge,Pe,Ee),_e=Math.max(F,ge,Pe,Ee);return new m(Be,it,We-Be,_e-it)},je=function($,F,P,ue,me,ge,de,Pe){var Re,Ee,Be,We,it,_e,ee,qe,se,pe,Se,Me,ot,wt,ct=P-$,Ce=ue-F,De=me-P,Te=ge-ue,ce=de-me,Ye=Pe-ge;for(Ee=0;Ee<41;Ee++)se=(ee=(Be=$+(Re=Ee/40)*ct)+Re*((it=P+Re*De)-Be))+Re*(it+Re*(me+Re*ce-it)-ee),pe=(qe=(We=F+Re*Ce)+Re*((_e=ue+Re*Te)-We))+Re*(_e+Re*(ge+Re*Ye-_e)-qe),Ee==0?(Se=se,Me=pe,ot=se,wt=pe):(Se=Math.min(Se,se),Me=Math.min(Me,pe),ot=Math.max(ot,se),wt=Math.max(wt,pe));return new m(Math.round(Se),Math.round(Me),Math.round(ot-Se),Math.round(wt-Me))},V=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var $,F,P=($=this.ctx.lineDash,F=this.ctx.lineDashOffset,JSON.stringify({lineDash:$,lineDashOffset:F}));this.prevLineDash!==P&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=P)}}})(Ra.API),(function(t){var n=function(c){var l,m,d,u,f,g,p,y,b,N;for(m=[],d=0,u=(c+=l="\0\0\0\0".slice(c.length%4||4)).length;u>d;d+=4)(f=(c.charCodeAt(d)<<24)+(c.charCodeAt(d+1)<<16)+(c.charCodeAt(d+2)<<8)+c.charCodeAt(d+3))!==0?(g=(f=((f=((f=((f=(f-(N=f%85))/85)-(b=f%85))/85)-(y=f%85))/85)-(p=f%85))/85)%85,m.push(g+33,p+33,y+33,b+33,N+33)):m.push(122);return(function(w,C){for(var R=C;R>0;R--)w.pop()})(m,l.length),String.fromCharCode.apply(String,m)+"~>"},a=function(c){var l,m,d,u,f,g=String,p="length",y=255,b="charCodeAt",N="slice",w="replace";for(c[N](-2),c=c[N](0,-2)[w](/\s/g,"")[w]("z","!!!!!"),d=[],u=0,f=(c+=l="uuuuu"[N](c[p]%5||5))[p];f>u;u+=5)m=52200625*(c[b](u)-33)+614125*(c[b](u+1)-33)+7225*(c[b](u+2)-33)+85*(c[b](u+3)-33)+(c[b](u+4)-33),d.push(y&m>>24,y&m>>16,y&m>>8,y&m);return(function(C,R){for(var I=R;I>
37960;I--)C.pop()})(d,l[p]),g.fromCharCode.apply(g,d)},s=function(c){var l=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((c=c.replace(/\s/g,"")).indexOf(">")!==-1&&(c=c.substr(0,c.indexOf(">"))),c.length%2&&(c+="0"),l.test(c)===!1)return"";for(var m="",d=0;d<c.length;d+=2)m+=String.fromCharCode("0x"+(c[d]+c[d+1]));return m},i=function(c){for(var l=new Uint8Array(c.length),m=c.length;m--;)l[m]=c.charCodeAt(m);return c=(l=F1(l)).reduce((function(d,u){return d+String.fromCharCode(u)}),"")};t.processDataByFilters=function(c,l){var m=0,d=c||"",u=[];for(typeof(l=l||[])=="string"&&(l=[l]),m=0;m<l.length;m+=1)switch(l[m]){case"ASCII85Decode":case"/ASCII85Decode":d=a(d),u.push("/ASCII85Encode");break;case"ASCII85Encode":case"/ASCII85Encode":d=n(d),u.push("/ASCII85Decode");break;case"ASCIIHexDecode":case"/ASCIIHexDecode":d=s(d),u.push("/ASCIIHexEncode");break;case"ASCIIHexEncode":case"/ASCIIHexEncode":d=d.split("").map((function(f){return("0"+f.charCodeAt().toString(16)).slice(-2)})).join("")+">",u.push("/ASCIIHexDecode");break;case"FlateEncode":case"/FlateEncode":d=i(d),u.push("/FlateDecode");break;default:throw new Error('The filter: "'+l[m]+'" is not implemented')}return{data:d,reverseChain:u.reverse().join(" ")}}})(Ra.API),(function(t){t.loadFile=function(n,a,s){return(function(i,c,l){c=c!==!1,l=typeof l=="function"?l:function(){};var m=void 0;try{m=(function(d,u,f){var g=new XMLHttpRequest,p=0,y=function(b){var N=b.length,w=[],C=String.fromCharCode;for(p=0;p<N;p+=1)w.push(C(255&b.charCodeAt(p)));return w.join("")};if(g.open("GET",d,!u),g.overrideMimeType("text/plain; charset=x-user-defined"),u===!1&&(g.onload=function(){g.status===200?f(y(this.responseText)):f(void 0)}),g.send(null),u&&g.status===200)return y(g.responseText)})(i,c,l)}catch{}return m})(n,a,s)},t.loadImageFile=t.loadFile})(Ra.API),(function(t){function n(){return(ns.html2canvas?Promise.resolve(ns.html2canvas):M1(()=>import("./html2canvas.esm-QH1iLAAe.js"),[])).catch((function(l){return Promise.reject(new Error("Could not load html2canvas: "+l))})).then((function(l){return l.default?l.default:l}))}function a(){return(ns.DOMPurify?Promise.resolve(ns.DOMPurify):M1(()=>import("./purify.es-BwoZCkIS.js"),[])).catch((function(l){return Promise.reject(new Error("Could not load dompurify: "+l))})).then((function(l){return l.default?l.default:l}))}var s=function(l){var m=ur(l);return m==="undefined"?"undefined":m==="string"||l instanceof String?"string":m==="number"||l instanceof Number?"number":m==="function"||l instanceof Function?"function":l&&l.constructor===Array?"array":l&&l.nodeType===1?"element":m==="object"?"object":"unknown"},i=function(l,m){var d=document.createElement(l);for(var u in m.className&&(d.className=m.className),m.innerHTML&&m.dompurify&&(d.innerHTML=m.dompurify.sanitize(m.innerHTML)),m.style)d.style[u]=m.style[u];return d},c=function l(m){var d=Object.assign(l.convert(Promise.resolve()),JSON.parse(JSON.stringify(l.template))),u=l.convert(Promise.resolve(),d);return u=(u=u.setProgress(1,l,1,[l])).set(m)};(c.prototype=Object.create(Promise.prototype)).constructor=c,c.convert=function(l,m){return l.__proto__=m||c.prototype,l},c.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:!0,x:0,y:0,html2canvas:{},jsPDF:{},backgroundColor:"transparent"}},c.prototype.from=function(l,m){return this.then((function(){switch(m=m||(function(d){switch(s(d)){case"string":return"string";case"element":return d.nodeName.toLowerCase()==="canvas"?"canvas":"element";default:return"unknown"}})(l)){case"string":return this.then(a).then((function(d){return this.set({src:i("div",{innerHTML:l,dompurify:d})})}));case"element":return this.set({src:l});case"canvas":return this.set({canvas:l});case"img":return this.set({img:l});default:return this.error("Unknown source type.")}}))},c.prototype.to=function(l){switch(l){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();
3796case"pdf":return this.toPdf();default:return this.error("Invalid target.")}},c.prototype.toContainer=function(){return this.thenList([function(){return this.prop.src||this.error("Cannot duplicate - no source HTML.")},function(){return this.prop.pageSize||this.setPageSize()}]).then((function(){var l={position:"relative",display:"inline-block",width:(typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth):this.opt.windowWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:this.opt.backgroundColor},m=(function d(u,f){for(var g=u.nodeType===3?document.createTextNode(u.nodeValue):u.cloneNode(!1),p=u.firstChild;p;p=p.nextSibling)f!==!0&&p.nodeType===1&&p.nodeName==="SCRIPT"||g.appendChild(d(p,f));return u.nodeType===1&&(u.nodeName==="CANVAS"?(g.width=u.width,g.height=u.height,g.getContext("2d").drawImage(u,0,0)):u.nodeName!=="TEXTAREA"&&u.nodeName!=="SELECT"||(g.value=u.value),g.addEventListener("load",(function(){g.scrollTop=u.scrollTop,g.scrollLeft=u.scrollLeft}),!0)),g})(this.prop.src,this.opt.html2canvas.javascriptEnabled);m.tagName==="BODY"&&(l.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px"),this.prop.overlay=i("div",{className:"html2pdf__overlay",style:{position:"fixed",overflow:"hidden",zIndex:1e3,left:"-100000px",right:0,bottom:0,top:0}}),this.prop.container=i("div",{className:"html2pdf__container",style:l}),this.prop.container.appendChild(m),this.prop.container.firstChild.appendChild(i("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}})),this.prop.container.style.float="none",this.prop.overlay.appendChild(this.prop.container),document.body.appendChild(this.prop.overlay),this.prop.container.firstChild.style.position="relative",this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px"}))},c.prototype.toCanvas=function(){var l=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(l).then(n).then((function(m){var d=Object.assign({},this.opt.html2canvas);return delete d.onrendered,m(this.prop.container,d)})).then((function(m){(this.opt.html2canvas.onrendered||function(){})(m),this.prop.canvas=m,document.body.removeChild(this.prop.overlay)}))},c.prototype.toContext2d=function(){var l=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(l).then(n).then((function(m){var d=this.opt.jsPDF,u=this.opt.fontFaces,f=typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?1:this.opt.width/this.opt.windowWidth,g=Object.assign({async:!0,allowTaint:!0,scale:f,scrollX:this.opt.scrollX||0,scrollY:this.opt.scrollY||0,backgroundColor:"#ffffff",imageTimeout:15e3,logging:!0,proxy:null,removeContainer:!0,foreignObjectRendering:!1,useCORS:!1},this.opt.html2canvas);if(delete g.onrendered,d.context2d.autoPaging=this.opt.autoPaging===void 0||this.opt.autoPaging,d.context2d.posX=this.opt.x,d.context2d.posY=this.opt.y,d.context2d.margin=this.opt.margin,d.context2d.fontFaces=u,u)for(var p=0;p<u.length;++p){var y=u[p],b=y.src.find((function(N){return N.format==="truetype"}));b&&d.addFont(b.url,y.ref.name,y.ref.style)}
vendor: 4,712 bytes, line 3796
3796return g.windowHeight=g.windowHeight||0,g.windowHeight=g.windowHeight==0?Math.max(this.prop.container.clientHeight,this.prop.container.scrollHeight,this.prop.container.offsetHeight):g.windowHeight,d.context2d.save(!0),m(this.prop.container,g)})).then((function(m){this.opt.jsPDF.context2d.restore(!0),(this.opt.html2canvas.onrendered||function(){})(m),this.prop.canvas=m,document.body.removeChild(this.prop.overlay)}))},c.prototype.toImg=function(){return this.thenList([function(){return this.prop.canvas||this.toCanvas()}]).then((function(){var l=this.prop.canvas.toDataURL("image/"+this.opt.image.type,this.opt.image.quality);this.prop.img=document.createElement("img"),this.prop.img.src=l}))},c.prototype.toPdf=function(){return this.thenList([function(){return this.toContext2d()}]).then((function(){this.prop.pdf=this.prop.pdf||this.opt.jsPDF}))},c.prototype.output=function(l,m,d){return(d=d||"pdf").toLowerCase()==="img"||d.toLowerCase()==="image"?this.outputImg(l,m):this.outputPdf(l,m)},c.prototype.outputPdf=function(l,m){return this.thenList([function(){return this.prop.pdf||this.toPdf()}]).then((function(){return this.prop.pdf.output(l,m)}))},c.prototype.outputImg=function(l){return this.thenList([function(){return this.prop.img||this.toImg()}]).then((function(){switch(l){case void 0:case"img":return this.prop.img;case"datauristring":case"dataurlstring":return this.prop.img.src;case"datauri":case"dataurl":return document.location.href=this.prop.img.src;default:throw'Image output type "'+l+'" is not supported.'}}))},c.prototype.save=function(l){return this.thenList([function(){return this.prop.pdf||this.toPdf()}]).set(l?{filename:l}:null).then((function(){this.prop.pdf.save(this.opt.filename)}))},c.prototype.doCallback=function(){return this.thenList([function(){return this.prop.pdf||this.toPdf()}]).then((function(){this.prop.callback(this.prop.pdf)}))},c.prototype.set=function(l){if(s(l)!=="object")return this;var m=Object.keys(l||{}).map((function(d){if(d in c.template.prop)return function(){this.prop[d]=l[d]};switch(d){case"margin":return this.setMargin.bind(this,l.margin);case"jsPDF":return function(){return this.opt.jsPDF=l.jsPDF,this.setPageSize()};case"pageSize":return this.setPageSize.bind(this,l.pageSize);default:return function(){this.opt[d]=l[d]}}}),this);return this.then((function(){return this.thenList(m)}))},c.prototype.get=function(l,m){return this.then((function(){var d=l in c.template.prop?this.prop[l]:this.opt[l];return m?m(d):d}))},c.prototype.setMargin=function(l){return this.then((function(){switch(s(l)){case"number":l=[l,l,l,l];case"array":if(l.length===2&&(l=[l[0],l[1],l[0],l[1]]),l.length===4)break;default:return this.error("Invalid margin array.")}this.opt.margin=l})).then(this.setPageSize)},c.prototype.setPageSize=function(l){function m(d,u){return Math.floor(d*u/72*96)}return this.then((function(){(l=l||Ra.getPageSize(this.opt.jsPDF)).hasOwnProperty("inner")||(l.inner={width:l.width-this.opt.margin[1]-this.opt.margin[3],height:l.height-this.opt.margin[0]-this.opt.margin[2]},l.inner.px={width:m(l.inner.width,l.k),height:m(l.inner.height,l.k)},l.inner.ratio=l.inner.height/l.inner.width),this.prop.pageSize=l}))},c.prototype.setProgress=function(l,m,d,u){return l!=null&&(this.progress.val=l),m!=null&&(this.progress.state=m),d!=null&&(this.progress.n=d),u!=null&&(this.progress.stack=u),this.progress.ratio=this.progress.val/this.progress.state,this},c.prototype.updateProgress=function(l,m,d,u){return this.setProgress(l?this.progress.val+l:null,m||null,d?this.progress.n+d:null,u?this.progress.stack.concat(u):null)},c.prototype.then=function(l,m){var d=this;return this.thenCore(l,m,(function(u,f){return d.updateProgress(null,null,1,[u]),Promise.prototype.then.call(this,(function(g){return d.updateProgress(null,u),g})).then(u,f).then((function(g){return d.updateProgress(1),g}))}))},c.prototype.thenCore=function(l,m,d){d=d||Promise.prototype.then,l&&(l=l.bind(this)),m&&(m=m.bind(this));var u=Promise.toString().indexOf("[native code]")!==-1&&Promise.name==="Promise"?this:c.convert(Object.assign({},this),Promise.prototype),f=d.call(u,l,m);return c.convert(f,this.__proto__)},c.prototype.thenExternal=function(l,m){return Promise.prototype.then.call(this,l,m)},c.prototype.thenList=function(l){var m=this;return l.forEach((function(d){m=m.thenCore(d)})),m},c.prototype.catch=function(l){l&&(l=l.bind(this));var m=Promise.prototype.catch.call(this,l);return c.convert(m,this)},c.prototype.catchExternal=function(l){return Promise.prototype.catch.call(this,l)},c.prototype.error=function(l){return this.then((function(){throw new Error(l)}))},c.prototype.using=c.prototype.set,c.prototype.saveAs=c.prototype.save,c.prototype.exp
vendor: 5,685 bytes, lines 3796-3802
3796ort=c.prototype.output,c.prototype.run=c.prototype.then,Ra.getPageSize=function(l,m,d){if(ur(l)==="object"){var u=l;l=u.orientation,m=u.unit||m,d=u.format||d}m=m||"mm",d=d||"a4",l=(""+(l||"P")).toLowerCase();var f,g=(""+d).toLowerCase(),p={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};switch(m){case"pt":f=1;break;case"mm":f=72/25.4;break;case"cm":f=72/2.54;break;case"in":f=72;break;case"px":f=.75;break;case"pc":case"em":f=12;break;case"ex":f=6;break;default:throw"Invalid unit: "+m}var y,b=0,N=0;if(p.hasOwnProperty(g))b=p[g][1]/f,N=p[g][0]/f;else try{b=d[1],N=d[0]}catch{throw new Error("Invalid format: "+d)}if(l==="p"||l==="portrait")l="p",N>b&&(y=N,N=b,b=y);else{if(l!=="l"&&l!=="landscape")throw"Invalid orientation: "+l;l="l",b>N&&(y=N,N=b,b=y)}return{width:N,height:b,unit:m,k:f,orientation:l}},t.html=function(l,m){(m=m||{}).callback=m.callback||function(){},m.html2canvas=m.html2canvas||{},m.html2canvas.canvas=m.html2canvas.canvas||this.canvas,m.jsPDF=m.jsPDF||this,m.fontFaces=m.fontFaces?m.fontFaces.map(W1):null;var d=new c(m);return m.worker?d:d.from(l).doCallback()}})(Ra.API),Ra.API.addJS=function(t){return KI=t,this.internal.events.subscribe("postPutResources",(function(){Pv=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(Pv+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),JI=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+KI+")"),this.internal.out(">>"),this.internal.out("endobj")})),this.internal.events.subscribe("putCatalog",(function(){Pv!==void 0&&JI!==void 0&&this.internal.out("/Names <</JavaScript "+Pv+" 0 R>>")})),this},(function(t){var n;t.events.push(["postPutResources",function(){var a=this,s=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var i=a.outline.render().split(/\r\n/),c=0;c<i.length;c++){var l=i[c],m=s.exec(l);if(m!=null){var d=m[1];a.internal.newObjectDeferredBegin(d,!1)}a.internal.write(l)}if(this.outline.createNamedDestinations){var u=this.internal.pages.length,f=[];for(c=0;c<u;c++){var g=a.internal.newObject();f.push(g);var p=a.internal.getPageInfo(c+1);a.internal.write("<< /D["+p.objId+" 0 R /XYZ null null null]>> endobj")}var y=a.internal.newObject();for(a.internal.write("<< /Names [ "),c=0;c<f.length;c++)a.internal.write("(page_"+(c+1)+")"+f[c]+" 0 R");a.internal.write(" ] >>","endobj"),n=a.internal.newObject(),a.internal.write("<< /Dests "+y+" 0 R"),a.internal.write(">>","endobj")}}]),t.events.push(["putCatalog",function(){this.outline.root.children.length>0&&(this.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&this.internal.write("/Names "+n+" 0 R"))}]),t.events.push(["initialized",function(){var a=this;a.outline={createNamedDestinations:!1,root:{children:[]}},a.outline.add=function(s,i,c){var l={title:i,options:c,children:[]};return s==null&&(s=this.root),s.children.push(l),l},a.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=a,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},a.outline.genIds_r=function(s){s.id=a.internal.newObjectDeferred();for(var i=0;i<s.children.length;i++)this.genIds_r(s.children[i])},a.outline.renderRoot=function(s){this.objStart(s),this.line("/Type /Outlines"),s.children.length>0&&(this.line("/First "+this.makeRef(s.children[0])),this.line("/Last "+this.makeRef(s.children[s.children.length-1]))),this.line("/Count "+this.count_r({count:0},s)),this.objEnd()},a.outline.renderItems=function(s){for(var i=this.ctx.pdf.internal.getVerticalCoordinateString,c=0;c<s.children.length;c++){var l=s.children[c];this.objStart(l),this.line("/Title "+this.makeString(l.title)),this.line("/Parent "+this.makeRef(s)),c>0&&this.line("/Prev "+this.makeRef(s.children[c-1])),c<s.children.length-1&&this.line("/Next "+this.makeRef(s.children[c+1])),l.children.length>0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var m=this.count=this.count_r({count:0},l);if(m>0&&this.line("/Count "+m),l.options&&l.options.pageNumber){var d=a.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+d.objId+" 0 R /XYZ 0 "+i(0)+" 0]")}this.objEnd()}for(var u=0;u<s.children.length;u++)this.renderItems(s.children[u])},a.outline.line=function(s){this.ctx.val+=s+`\r 3797`},a.outline.makeRef=function(s){return s.id+" 0 R"},a.outline.makeString=function(s){return"("+a.internal.pdfEscape(s)+")"},a.outline.objStart=function(s){this.ctx.val+=`\r 3798`+s.id+` 0 obj\r 3799<<\r 3800`},a.outline.objEnd=function(){this.ctx.val+=`>> \r 3801endobj\r 3802`},a.outline.count_r=function(s,i){for(var c=0;c<i.children.length;c++)s.count++,this.count_r(s,i.children[c]);return s.count}}])})(Ra.API),(function(t){var n=[192,193,194,195,196,197,198,199];t.processJPEG=function(a,s,i,c,l,m){var d,u=this.decode.DCT_DECODE,f=null;
vendor: 10,725 bytes, lines 3802-3853
3802if(typeof a=="string"||this.__addimage__.isArrayBuffer(a)||this.__addimage__.isArrayBufferView(a)){switch(a=l||a,a=this.__addimage__.isArrayBuffer(a)?new Uint8Array(a):a,(d=(function(g){for(var p,y=256*g.charCodeAt(4)+g.charCodeAt(5),b=g.length,N={width:0,height:0,numcomponents:1},w=4;w<b;w+=2){if(w+=y,n.indexOf(g.charCodeAt(w+1))!==-1){p=256*g.charCodeAt(w+5)+g.charCodeAt(w+6),N={width:256*g.charCodeAt(w+7)+g.charCodeAt(w+8),height:p,numcomponents:g.charCodeAt(w+9)};break}y=256*g.charCodeAt(w+2)+g.charCodeAt(w+3)}return N})(a=this.__addimage__.isArrayBufferView(a)?this.__addimage__.arrayBufferToBinaryString(a):a)).numcomponents){case 1:m=this.color_spaces.DEVICE_GRAY;break;case 4:m=this.color_spaces.DEVICE_CMYK;break;case 3:m=this.color_spaces.DEVICE_RGB}f={data:a,width:d.width,height:d.height,colorSpace:m,bitsPerComponent:8,filter:u,index:s,alias:i}}return f}})(Ra.API);var zm,Rv,XI,ZI,e_,VF=(function(){var t,n,a;function s(c){var l,m,d,u,f,g,p,y,b,N,w,C,R,I;for(this.data=c,this.pos=8,this.palette=[],this.imgData=[],this.transparency={},this.animation=null,this.text={},g=null;;){switch(l=this.readUInt32(),b=(function(){var _,J;for(J=[],_=0;_<4;++_)J.push(String.fromCharCode(this.data[this.pos++]));return J}).call(this).join("")){case"IHDR":this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(l);break;case"fcTL":g&&this.animation.frames.push(g),this.pos+=4,g={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()},f=this.readUInt16(),u=this.readUInt16()||100,g.delay=1e3*f/u,g.disposeOp=this.data[this.pos++],g.blendOp=this.data[this.pos++],g.data=[];break;case"IDAT":case"fdAT":for(b==="fdAT"&&(this.pos+=4,l-=4),c=(g!=null?g.data:void 0)||this.imgData,C=0;0<=l?C<l:C>l;0<=l?++C:--C)c.push(this.data[this.pos++]);break;case"tRNS":switch(this.transparency={},this.colorType){case 3:if(d=this.palette.length/3,this.transparency.indexed=this.read(l),this.transparency.indexed.length>d)throw new Error("More transparent colors than palette size");if((N=d-this.transparency.indexed.length)>0)for(R=0;0<=N?R<N:R>N;0<=N?++R:--R)this.transparency.indexed.push(255);break;case 0:this.transparency.grayscale=this.read(l)[0];break;case 2:this.transparency.rgb=this.read(l)}break;case"tEXt":p=(w=this.read(l)).indexOf(0),y=String.fromCharCode.apply(String,w.slice(0,p)),this.text[y]=String.fromCharCode.apply(String,w.slice(p+1));break;case"IEND":return g&&this.animation.frames.push(g),this.colors=(function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3}}).call(this),this.hasAlphaChannel=(I=this.colorType)===4||I===6,m=this.colors+(this.hasAlphaChannel?1:0),this.pixelBitlength=this.bits*m,this.colorSpace=(function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB"}}).call(this),void(this.imgData=new Uint8Array(this.imgData));default:this.pos+=l}if(this.pos+=4,this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}s.prototype.read=function(c){var l,m;for(m=[],l=0;0<=c?l<c:l>c;0<=c?++l:--l)m.push(this.data[this.pos++]);return m},s.prototype.readUInt32=function(){return this.data[this.pos++]<<24|this.data[this.pos++]<<16|this.data[this.pos++]<<8|this.data[this.pos++]},s.prototype.readUInt16=function(){return this.data[this.pos++]<<8|this.data[this.pos++]},s.prototype.decodePixels=function(c){var l=this.pixelBitlength/8,m=new Uint8Array(this.width*this.height*l),d=0,u=this;if(c==null&&(c=this.imgData),c.length===0)return new Uint8Array(0);function f(g,p,y,b){var N,w,C,R,I,_,J,T,G,z,H,K,L,D,M,Z,fe,q,ne,ae,Y,je=Math.ceil((u.width-g)/y),V=Math.ceil((u.height-p)/b),$=u.width==je&&u.height==V;for(D=l*je,K=$?m:new Uint8Array(D*V),_=c.length,L=0,w=0;L<V&&d<_;){switch(c[d++]){case 0:for(R=fe=0;fe<D;R=fe+=1)K[w++]=c[d++];break;case 1:for(R=q=0;q<D;R=q+=1)N=c[d++],I=R<l?0:K[w-l],K[w++]=(N+I)%256;break;case 2:for(R=ne=0;ne<D;R=ne+=1)N=c[d++],C=(R-R%l)/l,M=L&&K[(L-1)*D+C*l+R%l],K[w++]=(M+N)%256;break;case 3:for(R=ae=0;ae<D;R=ae+=1)N=c[d++],C=(R-R%l)/l,I=R<l?0:K[w-l],M=L&&K[(L-1)*D+C*l+R%l],K[w++]=(N+Math.floor((I+M)/2))%256;break;case 4:for(R=Y=0;Y<D;R=Y+=1)N=c[d++],C=(R-R%l)/l,I=R<l?0:K[w-l],L===0?M=Z=0:(M=K[(L-1)*D+C*l+R%l],Z=C&&K[(L-1)*D+(C-1)*l+R%l]),J=I+M-Z,T=Math.abs(J-I),z=Math.abs(J-M),H=Math.abs(J-Z),G=T<=z&&T<=H?I:z<=H?M:Z,K[w++]=(N+G)%256;break;default:throw new Error("Invalid filter algorithm: "+c[d-1])}if(!$){var F=((p+L*b)*u.width+g)*l,P=L*D;for(R=0;R<je;R+=1){for(var ue=0;ue<l;ue+=1)m[F++]=K[P++];F+=(y-1)*l}}L++}}return c=jF(c),u.interlaceMethod==1?(f(0,0,8,8),f(4,0,8,8),f(0,4,4,8),f(2,0,4,4),f(0,2,2,4),f(1,0,2,2),f(0,1,1,2)):f(0,0,1,1),m},s.prototype.decodePalette=function(){var c,l,m,d,u,f,g,p,y;for(m=this.palette,f=this.transparency.indexed||[],u=new Uint8Array((f.length||0)+m.length),d=0,c=0,l=g=0,p=m.length;g<p;l=g+=3)u[d++]=m[l],u[d++]=m[l+1],u[d++]=m[l+2],u[d++]=(y=f[c++])!=null?y:255;return u},s.prototype.copyToImageData=function(c,l){var m,d,u,f,g,p,y,b,N,w,C;if(d=this.colors,N=null,m=this.hasAlphaChannel,this.palette.length&&(N=(C=this._decodedPalette)!=null?C:this._decodedPalette=this.decodePalette(),d=4,m=!0),b=(u=c.data||c).length,g=N||l,f=p=0,d===1)for(;f<b;)y=N?4*l[f/4]:p,w=g[y++],u[f++]=w,u[f++]=w,u[f++]=w,u[f++]=m?g[y++]:255,p=y;else for(;f<b;)y=N?4*l[f/4]:p,u[f++]=g[y++],u[f++]=g[y++],u[f++]=g[y++],u[f++]=m?g[y++]:255,p=y},s.prototype.decode=function(){var c;return c=new Uint8Array(this.width*this.height*4),this.copyToImageData(c,this.decodePixels()),c};var i=function(){if(Object.prototype.toString.call(ns)==="[object Window]"){try{n=ns.document.createElement("canvas"),a=n.getContext("2d")}catch{return!1}return!0}return!1};return i(),t=function(c){var l;if(i()===!0)return a.width=c.width,a.height=c.height,a.clearRect(0,0,c.width,c.height),a.putImageData(c,0,0),(l=new Image).src=n.toDataURL(),l;throw new Error("This method requires a Browser with Canvas-capability.")},s.prototype.decodeFrames=function(c){var l,m,d,u,f,g,p,y;if(this.animation){for(y=[],m=f=0,g=(p=this.animation.frames).length;f<g;m=++f)l=p[m],d=c.createImageData(l.width,l.height),u=this.decodePixels(new Uint8Array(l.data)),this.copyToImageData(d,u),l.imageData=d,y.push(l.image=t(d));return y}},s.prototype.renderFrame=function(c,l){var m,d,u;return m=(d=this.animation.frames)[l],u=d[l-1],l===0&&c.clearRect(0,0,this.width,this.height),(u!=null?u.disposeOp:void 0)===1?c.clearRect(u.xOffset,u.yOffset,u.width,u.height):(u!=null?u.disposeOp:void 0)===2&&c.putImageData(u.imageData,u.xOffset,u.yOffset),m.blendOp===0&&c.clearRect(m.xOffset,m.yOffset,m.width,m.height),c.drawImage(m.image,m.xOffset,m.yOffset)},s.prototype.animate=function(c){var l,m,d,u,f,g,p=this;return m=0,g=this.animation,u=g.numFrames,d=g.frames,f=g.numPlays,(l=function(){var y,b;if(y=m++%u,b=d[y],p.renderFrame(c,y),u>1&&m/u<f)return p.animation._timeout=setTimeout(l,b.delay)})()},s.prototype.stopAnimation=function(){var c;return clearTimeout((c=this.animation)!=null?c._timeout:void 0)},s.prototype.render=function(c){var l,m;return c._png&&c._png.stopAnimation(),c._png=this,c.width=this.width,c.height=this.height,l=c.getContext("2d"),this.animation?(this.decodeFrames(l),this.animate(l)):(m=l.createImageData(this.width,this.height),this.copyToImageData(m,this.decodePixels()),l.putImageData(m,0,0))},s})();/** 3803 * @license 3804 * 3805 * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb 3806 * 3807 * Permission is hereby granted, free of charge, to any person obtaining 3808 * a copy of this software and associated documentation files (the 3809 * "Software"), to deal in the Software without restriction, including 3810 * without limitation the rights to use, copy, modify, merge, publish, 3811 * distribute, sublicense, and/or sell copies of the Software, and to 3812 * permit persons to whom the Software is furnished to do so, subject to 3813 * the following conditions: 3814 * 3815 * The above copyright notice and this permission notice shall be 3816 * included in all copies or substantial portions of the Software. 3817 * 3818 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 3819 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3820 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 3821 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 3822 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 3823 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 3824 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 3825 * ==================================================================== 3826 *//** 3827 * @license 3828 * (c) Dean McNamee <[email protected]>, 2013. 3829 * 3830 * https://github.com/deanm/omggif 3831 * 3832 * Permission is hereby granted, free of charge, to any person obtaining a copy 3833 * of this software and associated documentation files (the "Software"), to 3834 * deal in the Software without restriction, including without limitation the 3835 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 3836 * sell copies of the Software, and to permit persons to whom the Software is 3837 * furnished to do so, subject to the following conditions: 3838 * 3839 * The above copyright notice and this permission notice shall be included in 3840 * all copies or substantial portions of the Software. 3841 * 3842 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 3843 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 3844 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 3845 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 3846 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 3847 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 3848 * IN THE SOFTWARE. 3849 * 3850 * omggif is a JavaScript implementation of a GIF 89a encoder and decoder, 3851 * including animation and compression. It does not rely on any specific 3852 * underlying system, so should run in the browser, Node, or Plask. 3853 */function HF(t){var n=0;if(t[n++]!==71||t[n++]!==73||t[n++]!==70||t[n++]!==56||(t[n++]+1&253)!=56||t[n++]!==97)throw new Error("Invalid GIF 87a/89a header.");var a=t[n++]|t[n++]<<8,s=t[n++]|t[n++]<<8,i=t[n++],c=i>>7,l=1<<(7&i)+1;t[n++],t[n++];var m=null,d=null;c&&(m=n,d=l,n+=3*l);var u=!0,f=[],g=0,p=null,y=0,b=null;for(this.width=a,this.height=s;u&&n<t.length;)switch(t[n++]){case 33:switch(t[n++]){case 255:if(t[n]!==11||t[n+1]==78&&t[n+2]==69&&t[n+3]==84&&t[n+4]==83&&t[
vendor: 63,349 bytes, lines 3853-3890
3853n+5]==67&&t[n+6]==65&&t[n+7]==80&&t[n+8]==69&&t[n+9]==50&&t[n+10]==46&&t[n+11]==48&&t[n+12]==3&&t[n+13]==1&&t[n+16]==0)n+=14,b=t[n++]|t[n++]<<8,n++;else for(n+=12;;){if(!((L=t[n++])>=0))throw Error("Invalid block size");if(L===0)break;n+=L}break;case 249:if(t[n++]!==4||t[n+4]!==0)throw new Error("Invalid graphics extension block.");var N=t[n++];g=t[n++]|t[n++]<<8,p=t[n++],(1&N)==0&&(p=null),y=N>>2&7,n++;break;case 254:for(;;){if(!((L=t[n++])>=0))throw Error("Invalid block size");if(L===0)break;n+=L}break;default:throw new Error("Unknown graphic control label: 0x"+t[n-1].toString(16))}break;case 44:var w=t[n++]|t[n++]<<8,C=t[n++]|t[n++]<<8,R=t[n++]|t[n++]<<8,I=t[n++]|t[n++]<<8,_=t[n++],J=_>>6&1,T=1<<(7&_)+1,G=m,z=d,H=!1;_>>7&&(H=!0,G=n,z=T,n+=3*T);var K=n;for(n++;;){var L;if(!((L=t[n++])>=0))throw Error("Invalid block size");if(L===0)break;n+=L}f.push({x:w,y:C,width:R,height:I,has_local_palette:H,palette_offset:G,palette_size:z,data_offset:K,data_length:n-K,transparent_index:p,interlaced:!!J,delay:g,disposal:y});break;case 59:u=!1;break;default:throw new Error("Unknown gif block: 0x"+t[n-1].toString(16))}this.numFrames=function(){return f.length},this.loopCount=function(){return b},this.frameInfo=function(D){if(D<0||D>=f.length)throw new Error("Frame index out of range.");return f[D]},this.decodeAndBlitFrameBGRA=function(D,M){var Z=this.frameInfo(D),fe=Z.width*Z.height,q=new Uint8Array(fe);t_(t,Z.data_offset,q,fe);var ne=Z.palette_offset,ae=Z.transparent_index;ae===null&&(ae=256);var Y=Z.width,je=a-Y,V=Y,$=4*(Z.y*a+Z.x),F=4*((Z.y+Z.height)*a+Z.x),P=$,ue=4*je;Z.interlaced===!0&&(ue+=4*a*7);for(var me=8,ge=0,de=q.length;ge<de;++ge){var Pe=q[ge];if(V===0&&(V=Y,(P+=ue)>=F&&(ue=4*je+4*a*(me-1),P=$+(Y+je)*(me<<1),me>>=1)),Pe===ae)P+=4;else{var Re=t[ne+3*Pe],Ee=t[ne+3*Pe+1],Be=t[ne+3*Pe+2];M[P++]=Be,M[P++]=Ee,M[P++]=Re,M[P++]=255}--V}},this.decodeAndBlitFrameRGBA=function(D,M){var Z=this.frameInfo(D),fe=Z.width*Z.height,q=new Uint8Array(fe);t_(t,Z.data_offset,q,fe);var ne=Z.palette_offset,ae=Z.transparent_index;ae===null&&(ae=256);var Y=Z.width,je=a-Y,V=Y,$=4*(Z.y*a+Z.x),F=4*((Z.y+Z.height)*a+Z.x),P=$,ue=4*je;Z.interlaced===!0&&(ue+=4*a*7);for(var me=8,ge=0,de=q.length;ge<de;++ge){var Pe=q[ge];if(V===0&&(V=Y,(P+=ue)>=F&&(ue=4*je+4*a*(me-1),P=$+(Y+je)*(me<<1),me>>=1)),Pe===ae)P+=4;else{var Re=t[ne+3*Pe],Ee=t[ne+3*Pe+1],Be=t[ne+3*Pe+2];M[P++]=Re,M[P++]=Ee,M[P++]=Be,M[P++]=255}--V}}}function t_(t,n,a,s){for(var i=t[n++],c=1<<i,l=c+1,m=l+1,d=i+1,u=(1<<d)-1,f=0,g=0,p=0,y=t[n++],b=new Int32Array(4096),N=null;;){for(;f<16&&y!==0;)g|=t[n++]<<f,f+=8,y===1?y=t[n++]:--y;if(f<d)break;var w=g&u;if(g>>=d,f-=d,w!==c){if(w===l)break;for(var C=w<m?w:N,R=0,I=C;I>c;)I=b[I]>>8,++R;var _=I;if(p+R+(C!==w?1:0)>s)return void Ar.log("Warning, gif stream longer than expected.");a[p++]=_;var J=p+=R;for(C!==w&&(a[p++]=_),I=C;R--;)I=b[I],a[--J]=255&I,I>>=8;N!==null&&m<4096&&(b[m++]=N<<8|_,m>=u+1&&d<12&&(++d,u=u<<1|1)),N=w}else m=l+1,u=(1<<(d=i+1))-1,N=null}return p!==s&&Ar.log("Warning, gif stream shorter than expected."),a}/** 3854 * @license 3855 Copyright (c) 2008, Adobe Systems Incorporated 3856 All rights reserved. 3857 3858 Redistribution and use in source and binary forms, with or without 3859 modification, are permitted provided that the following conditions are 3860 met: 3861 3862 * Redistributions of source code must retain the above copyright notice, 3863 this list of conditions and the following disclaimer. 3864 3865 * Redistributions in binary form must reproduce the above copyright 3866 notice, this list of conditions and the following disclaimer in the 3867 documentation and/or other materials provided with the distribution. 3868 3869 * Neither the name of Adobe Systems Incorporated nor the names of its 3870 contributors may be used to endorse or promote products derived from 3871 this software without specific prior written permission. 3872 3873 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 3874 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 3875 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 3876 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 3877 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 3878 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 3879 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 3880 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 3881 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 3882 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 3883 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 3884*/function bj(t){var n,a,s,i,c,l=Math.floor,m=new Array(64),d=new Array(64),u=new Array(64),f=new Array(64),g=new Array(65535),p=new Array(65535),y=new Array(64),b=new Array(64),N=[],w=0,C=7,R=new Array(64),I=new Array(64),_=new Array(64),J=new Array(256),T=new Array(2048),G=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],z=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],H=[0,1,2,3,4,5,6,7,8,9,10,11],K=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],L=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],D=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],M=[0,1,2,3,4,5,6,7,8,9,10,11],Z=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],fe=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function q($,F){for(var P=0,ue=0,me=new Array,ge=1;ge<=16;ge++){for(var de=1;de<=$[ge];de++)me[F[ue]]=[],me[F[ue]][0]=P,me[F[ue]][1]=ge,ue++,P++;P*=2}return me}function ne($){for(var F=$[0],P=$[1]-1;P>=0;)F&1<<P&&(w|=1<<C),P--,--C<0&&(w==255?(ae(255),ae(0)):ae(w),C=7,w=0)}function ae($){N.push($)}function Y($){ae($>>8&255),ae(255&$)}function je($,F,P,ue,me){for(var ge,de=me[0],Pe=me[240],Re=(function(pe,Se){var Me,ot,wt,ct,Ce,De,Te,ce,Ye,Je,le=0;for(Ye=0;Ye<8;++Ye){Me=pe[le],ot=pe[le+1],wt=pe[le+2],ct=pe[le+3],Ce=pe[le+4],De=pe[le+5],Te=pe[le+6];var nt=Me+(ce=pe[le+7]),xt=Me-ce,te=ot+Te,Ge=ot-Te,pt=wt+De,$e=wt-De,st=ct+Ce,Nt=ct-Ce,be=nt+st,jt=nt-st,bt=te+pt,tn=te-pt;pe[le]=be+bt,pe[le+4]=be-bt;var B=.707106781*(tn+jt);pe[le+2]=jt+B,pe[le+6]=jt-B;var xe=.382683433*((be=Nt+$e)-(tn=Ge+xt)),tt=.5411961*be+xe,ht=1.306562965*tn+xe,dt=.707106781*(bt=$e+Ge),we=xt+dt,rt=xt-dt;pe[le+5]=rt+tt,pe[le+3]=rt-tt,pe[le+1]=we+ht,pe[le+7]=we-ht,le+=8}for(le=0,Ye=0;Ye<8;++Ye){Me=pe[le],ot=pe[le+8],wt=pe[le+16],ct=pe[le+24],Ce=pe[le+32],De=pe[le+40],Te=pe[le+48];var St=Me+(ce=pe[le+56]),Qt=Me-ce,gn=ot+Te,An=ot-Te,Sn=wt+De,Xt=wt-De,Wt=ct+Ce,Gt=ct-Ce,$t=St+Wt,Vt=St-Wt,sn=gn+Sn,on=gn-Sn;pe[le]=$t+sn,pe[le+32]=$t-sn;var ke=.707106781*(on+Vt);pe[le+16]=Vt+ke,pe[le+48]=Vt-ke;var Ct=.382683433*(($t=Gt+Xt)-(on=An+Qt)),Et=.5411961*$t+Ct,Rt=1.306562965*on+Ct,xn=.707106781*(sn=Xt+An),dn=Qt+xn,Ln=Qt-xn;pe[le+40]=Ln+Et,pe[le+24]=Ln-Et,pe[le+8]=dn+Rt,pe[le+56]=dn-Rt,le++}for(Ye=0;Ye<64;++Ye)Je=pe[Ye]*Se[Ye],y[Ye]=Je>0?Je+.5|0:Je-.5|0;return y})($,F),Ee=0;Ee<64;++Ee)b[G[Ee]]=Re[Ee];var Be=b[0]-P;P=b[0],Be==0?ne(ue[0]):(ne(ue[p[ge=32767+Be]]),ne(g[ge]));for(var We=63;We>0&&b[We]==0;)We--;if(We==0)return ne(de),P;for(var it,_e=1;_e<=We;){for(var ee=_e;b[_e]==0&&_e<=We;)++_e;var qe=_e-ee;if(qe>=16){it=qe>>4;for(var se=1;se<=it;++se)ne(Pe);qe&=15}ge=32767+b[_e],ne(me[(qe<<4)+p[ge]]),ne(g[ge]),_e++}return We!=63&&ne(de),P}function V($){$=Math.min(Math.max($,1),100),c!=$&&((function(F){for(var P=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],ue=0;ue<64;ue++){var me=l((P[ue]*F+50)/100);me=Math.min(Math.max(me,1),255),m[G[ue]]=me}for(var ge=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],de=0;de<64;de++){var Pe=l((ge[de]*F+50)/100);Pe=Math.min(Math.max(Pe,1),255),d[G[de]]=Pe}for(var Re=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Ee=0,Be=0;Be<8;Be++)for(var We=0;We<8;We++)u[Ee]=1/(m[G[Ee]]*Re[Be]*Re[We]*8),f[Ee]=1/(d[G[Ee]]*Re[Be]*Re[We]*8),Ee++})($<50?Math.floor(5e3/$):Math.floor(200-2*$)),c=$)}this.encode=function($,F){F&&V(F),N=new Array,w=0,C=7,Y(65496),Y(65504),Y(16),ae(74),ae(70),ae(73),ae(70),ae(0),ae(1),ae(1),ae(0),Y(1),Y(1),ae(0),ae(0),(function(){Y(65499),Y(132),ae(0);for(var ot=0;ot<64;ot++)ae(m[ot]);ae(1);for(var wt=0;wt<64;wt++)ae(d[wt])})(),(function(ot,wt){Y(65472),Y(17),ae(8),Y(wt),Y(ot),ae(3),ae(1),ae(17),ae(0),ae(2),ae(17),ae(1),ae(3),ae(17),ae(1)})($.width,$.height),(function(){Y(65476),Y(418),ae(0);for(var ot=0;ot<16;ot++)ae(z[ot+1]);for(var wt=0;wt<=11;wt++)ae(H[wt]);ae(16);for(var ct=0;ct<16;ct++)ae(K[ct+1]);for(var Ce=0;Ce<=161;Ce++)ae(L[Ce]);ae(1);for(var De=0;De<16;De++)ae(D[De+1]);for(var Te=0;Te<=11;Te++)ae(M[Te]);ae(17);for(var ce=0;ce<16;ce++)ae(Z[ce+1]);for(var Ye=0;Ye<=161;Ye++)ae(fe[Ye])})(),Y(65498),Y(12),ae(3),ae(1),ae(0),ae(2),ae(17),ae(3),ae(17),ae(0),ae(63),ae(0);var P=0,ue=0,me=0;w=0,C=7,this.encode.displayName="_encode_";for(var ge,de,Pe,Re,Ee,Be,We,it,_e,ee=$.data,qe=$.width,se=$.height,pe=4*qe,Se=0;Se<se;){for(ge=0;ge<pe;){for(Ee=pe*Se+ge,We=-1,it=0,_e=0;_e<64;_e++)Be=Ee+(it=_e>>3)*pe+(We=4*(7&_e)),Se+it>=se&&(Be-=pe*(Se+1+it-se)),ge+We>=pe&&(Be-=ge+We-pe+4),de=ee[Be++],Pe=ee[Be++],Re=ee[Be++],R[_e]=(T[de]+T[Pe+256>>0]+T[Re+512>>0]>>16)-128,I[_e]=(T[de+768>>0]+T[Pe+1024>>0]+T[Re+1280>>0]>>16)-128,_[_e]=(T[de+1280>>0]+T[Pe+1536>>0]+T[Re+1792>>0]>>16)-128;P=je(R,u,P,n,s),ue=je(I,f,ue,a,i),me=je(_,f,me,a,i),ge+=32}Se+=8}if(C>=0){var Me=[];Me[1]=C+1,Me[0]=(1<<C+1)-1,ne(Me)}return Y(65497),new Uint8Array(N)},t=t||50,(function(){for(var $=String.fromCharCode,F=0;F<256;F++)J[F]=$(F)})(),n=q(z,H),a=q(D,M),s=q(K,L),i=q(Z,fe),(function(){for(var $=1,F=2,P=1;P<=15;P++){for(var ue=$;ue<F;ue++)p[32767+ue]=P,g[32767+ue]=[],g[32767+ue][1]=P,g[32767+ue][0]=ue;for(var me=-(F-1);me<=-$;me++)p[32767+me]=P,g[32767+me]=[],g[32767+me][1]=P,g[32767+me][0]=F-1+me;$<<=1,F<<=1}})(),(function(){for(var $=0;$<256;$++)T[$]=19595*$,T[$+256>>0]=38470*$,T[$+512>>0]=7471*$+32768,T[$+768>>0]=-11059*$,T[$+1024>>0]=-21709*$,T[$+1280>>0]=32768*$+8421375,T[$+1536>>0]=-27439*$,T[$+1792>>0]=-5329*$})(),V(t)}/** 3885 * @license 3886 * Copyright (c) 2017 Aras Abbasi 3887 * 3888 * Licensed under the MIT License. 3889 * http://opensource.org/licenses/mit-license 3890 */function al(t,n){if(this.pos=0,this.buffer=t,this.datav=new DataView(t.buffer),this.is_with_alpha=!!n,this.bottom_up=!0,this.flag=String.fromCharCode(this.buffer[0])+String.fromCharCode(this.buffer[1]),this.pos+=2,["BM","BA","CI","CP","IC","PT"].indexOf(this.flag)===-1)throw new Error("Invalid BMP File");this.parseHeader(),this.parseBGR()}function n_(t){function n(z){if(!z)throw Error("assert :P")}function a(z,H,K){for(var L=0;4>L;L++)if(z[H+L]!=K.charCodeAt(L))return!0;return!1}function s(z,H,K,L,D){for(var M=0;M<D;M++)z[H+M]=K[L+M]}function i(z,H,K,L){for(var D=0;D<L;D++)z[H+D]=K}function c(z){return new Int32Array(z)}function l(z,H){for(var K=[],L=0;L<z;L++)K.push(new H);return K}function m(z,H){var K=[];return(function L(D,M,Z){for(var fe=Z[M],q=0;q<fe&&(D.push(Z.length>M+1?[]:new H),!(Z.length<M+1));q++)L(D[q],M+1,Z)})(K,0,z),K}var d=function(){var z=this;function H(j,k){for(var X=1<<k-1>>>0;j&X;)X>>>=1;return X?(j&X-1)+X:j}function K(j,k,X,ve,ze){n(!(ve%X));do j[k+(ve-=X)]=ze;while(0<ve)}function L(j,k,X,ve,ze){if(n(2328>=ze),512>=ze)var Qe=c(512);else if((Qe=c(ze))==null)return 0;return(function(Ke,Ze,at,mt,Tt,ln){var cn,Kt,Un=Ze,Nn=1<<at,Mt=c(16),Ut=c(16);for(n(Tt!=0),n(mt!=null),n(Ke!=null),n(0<at),Kt=0;Kt<Tt;++Kt){if(15<mt[Kt])return 0;++Mt[mt[Kt]]}if(Mt[0]==Tt)return 0;for(Ut[1]=0,cn=1;15>cn;++cn){if(Mt[cn]>1<<cn)return 0;Ut[cn+1]=Ut[cn]+Mt[cn]}for(Kt=0;Kt<Tt;++Kt)cn=mt[Kt],0<mt[Kt]&&(ln[Ut[cn]++]=Kt);if(Ut[15]==1)return(mt=new D).g=0,mt.value=ln[0],K(Ke,Un,1,Nn,mt),Nn;var $n,Yn=-1,Tn=Nn-1,Aa=0,fa=1,Va=1,ba=1<<at;for(Kt=0,cn=1,Tt=2;cn<=at;++cn,Tt<<=1){if(fa+=Va<<=1,0>(Va-=Mt[cn]))return 0;for(;0<Mt[cn];--Mt[cn])(mt=new D).g=cn,mt.value=ln[Kt++],K(Ke,Un+Aa,Tt,ba,mt),Aa=H(Aa,cn)}for(cn=at+1,Tt=2;15>=cn;++cn,Tt<<=1){if(fa+=Va<<=1,0>(Va-=Mt[cn]))return 0;for(;0<Mt[cn];--Mt[cn]){if(mt=new D,(Aa&Tn)!=Yn){for(Un+=ba,$n=1<<(Yn=cn)-at;15>Yn&&!(0>=($n-=Mt[Yn]));)++Yn,$n<<=1;Nn+=ba=1<<($n=Yn-at),Ke[Ze+(Yn=Aa&Tn)].g=$n+at,Ke[Ze+Yn].value=Un-Ze-Yn}mt.g=cn-at,mt.value=ln[Kt++],K(Ke,Un+(Aa>>at),Tt,ba,mt),Aa=H(Aa,cn)}}return fa!=2*Ut[15]-1?0:Nn})(j,k,X,ve,ze,Qe)}function D(){this.value=this.g=0}function M(){this.value=this.g=0}function Z(){this.G=l(5,D),this.H=c(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(Ga,M)}function fe(j,k,X,ve){n(j!=null),n(k!=null),n(2147483648>ve),j.Ca=254,j.I=0,j.b=-8,j.Ka=0,j.oa=k,j.pa=X,j.Jd=k,j.Yc=X+ve,j.Zc=4<=ve?X+ve-4+1:X,ge(j)}function q(j,k){for(var X=0;0<k--;)X|=Pe(j,128)<<k;return X}function ne(j,k){var X=q(j,k);return de(j)?-X:X}function ae(j,k,X,ve){var ze,Qe=0;for(n(j!=null),n(k!=null),n(4294967288>ve),j.Sb=ve,j.Ra=0,j.u=0,j.h=0,4<ve&&(ve=4),ze=0;ze<ve;++ze)Qe+=k[X+ze]<<8*ze;j.Ra=Qe,j.bb=ve,j.oa=k,j.pa=X}function Y(j){for(;8<=j.u&&j.bb<j.Sb;)j.Ra>>>=8,j.Ra+=j.oa[j.pa+j.bb]<<ls-8>>>0,++j.bb,j.u-=8;P(j)&&(j.h=1,j.u=0)}function je(j,k){if(n(0<=k),!j.h&&k<=Ia){var X=F(j)&Da[k];return j.u+=k,Y(j),X}return j.h=1,j.u=0}function V(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function $(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function F(j){return j.Ra>>>(j.u&ls-1)>>>0}function P(j){return n(j.bb<=j.Sb),j.h||j.bb==j.Sb&&j.u>ls}function ue(j,k){j.u=k,j.h=P(j)}function me(j){j.u>=Ua&&(n(j.u>=Ua),Y(j))}function ge(j){n(j!=null&&j.oa!=null),j.pa<j.Zc?(j.I=(j.oa[j.pa++]|j.I<<8)>>>0,j.b+=8):(n(j!=null&&j.oa!=null),j.pa<j.Yc?(j.b+=8,j.I=j.oa[j.pa++]|j.I<<8):j.Ka?j.b=0:(j.I<<=8,j.b+=8,j.Ka=1))}function de(j){return q(j,1)}function Pe(j,k){var X=j.Ca;0>j.b&&ge(j);var ve=j.b,ze=X*k>>>8,Qe=(j.I>>>ve>ze)+0;for(Qe?(X-=ze,j.I-=ze+1<<ve>>>0):X=ze+1,ve=X,ze=0;256<=ve;)ze+=8,ve>>=8;return ve=7^ze+va[ve],j.b-=ve,j.Ca=(X<<ve)-1,Qe}function Re(j,k,X){j[k+0]=X>>24&255,j[k+1]=X>>16&255,j[k+2]=X>>8&255,j[k+3]=X>>0&255}function Ee(j,k){return j[k+0]<<0|j[k+1]<<8}function Be(j,k){return Ee(j,k)|j[k+2]<<16}function We(j,k){return Ee(j,k)|Ee(j,k+2)<<16}function it(j,k){var X=1<<k;return n(j!=null),n(0<k),j.X=c(X),j.X==null?0:(j.Mb=32-k,j.Xa=k,1)}function _e(j,k){n(j!=null),n(k!=null),n(j.Xa==k.Xa),s(k.X,0,j.X,0,1<<k.Xa)}function ee(){this.X=[],this.Xa=this.Mb=0}function qe(j,k,X,ve){n(X!=null),n(ve!=null);var ze=X[0],Qe=ve[0];return ze==0&&(ze=(j*Qe+k/2)/k),Qe==0&&(Qe=(k*ze+j/2)/j),0>=ze||0>=Qe?0:(X[0]=ze,ve[0]=Qe,1)}function se(j,k){return j+(1<<k)-1>>>k}function pe(j,k){return((4278255360&j)+(4278255360&k)>>>0&4278255360)+((16711935&j)+(16711935&k)>>>0&16711935)>>>0}function Se(j,k){z[k]=function(X,ve,ze,Qe,Ke,Ze,at){var mt;for(mt=0;mt<Ke;++mt){var Tt=z[j](Ze[at+mt-1],ze,Qe+mt);Ze[at+mt]=pe(X[ve+mt],Tt)}}}function Me(){this.ud=this.hd=this.jd=0}function ot(j,k){return((4278124286&(j^k))>>>1)+(j&k)>>>0}function wt(j){return 0<=j&&256>j?j:0>j?0:255<j?255:void 0}function ct(j,k){return wt(j+(j-k+.5>>1))}function Ce(j,k,X){return Math.abs(k-X)-Math.abs(j-X)}function De(j,k,X,ve,ze,Qe,Ke){for(ve=Qe[Ke-1],X=0;X<ze;++X)Qe[Ke+X]=ve=pe(j[k+X],ve)}function Te(j,k,X,ve,ze){var Qe;for(Qe=0;Qe<X;++Qe){var Ke=j[k+Qe],Ze=Ke>>8&255,at=16711935&(at=(at=16711935&Ke)+((Ze<<16)+Ze));ve[ze+Qe]=(4278255360&Ke)+at>>>0}}function ce(j,k){k.jd=j>>0&255,k.hd=j>>8&255,k.ud=j>>16&255}function Ye(j,k,X,ve,ze,Qe){var Ke;for(Ke=0;Ke<ve;++Ke){var Ze=k[X+Ke],at=Ze>>>8,mt=Ze,Tt=255&(Tt=(Tt=Ze>>>16)+((j.jd<<24>>24)*(at<<24>>24)>>>5));mt=255&(mt=(mt=mt+((j.hd<<24>>24)*(at<<24>>24)>>>5))+((j.ud<<24>>24)*(Tt<<24>>24)>>>5)),ze[Qe+Ke]=(4278255360&Ze)+(Tt<<16)+mt}}function Je(j,k,X,ve,ze){z[k]=function(Qe,Ke,Ze,at,mt,Tt,ln,cn,Kt){for(at=ln;at<cn;++at)for(ln=0;ln<Kt;++ln)mt[Tt++]=ze(Ze[ve(Qe[Ke++])])},z[j]=function(Qe,Ke,Ze,at,mt,Tt,ln){var cn=8>>Qe.b,Kt=Qe.Ea,Un=Qe.K[0],Nn=Qe.w;if(8>cn)for(Qe=(1<<Qe.b)-1,Nn=(1<<cn)-1;Ke<Ze;++Ke){var Mt,Ut=0;for(Mt=0;Mt<Kt;++Mt)Mt&Qe||(Ut=ve(at[mt++])),Tt[ln++]=ze(Un[Ut&Nn]),Ut>>=cn}else z["VP8LMapColor"+X](at,mt,Un,Nn,Tt,ln,Ke,Ze,Kt)}}function le(j,k,X,ve,ze){for(X=k+X;k<X;){var Qe=j[k++];ve[ze++]=Qe>>16&255,ve[ze++]=Qe>>8&255,ve[ze++]=Qe>>0&255}}function nt(j,k,X,ve,ze){for(X=k+X;k<X;){var Qe=j[k++];ve[ze++]=Qe>>16&255,ve[ze++]=Qe>>8&255,ve[ze++]=Qe>>0&255,ve[ze++]=Qe>>24&255}}function xt(j,k,X,ve,ze){for(X=k+X;k<X;){var Qe=(Ke=j[k++])>>16&240|Ke>>12&15,Ke=Ke>>0&240|Ke>>28&15;ve[ze++]=Qe,ve[ze++]=Ke}}function te(j,k,X,ve,ze){for(X=k+X;k<X;){var Qe=(Ke=j[k++])>>16&248|Ke>>13&7,Ke=Ke>>5&224|Ke>>3&31;ve[ze++]=Qe,ve[ze++]=Ke}}function Ge(j,k,X,ve,ze){for(X=k+X;k<X;){var Qe=j[k++];ve[ze++]=Qe>>0&255,ve[ze++]=Qe>>8&255,ve[ze++]=Qe>>16&255}}function pt(j,k,X,ve,ze,Qe){if(Qe==0)for(X=k+X;k<X;)Re(ve,((Qe=j[k++])[0]>>24|Qe[1]>>8&65280|Qe[2]<<8&16711680|Qe[3]<<24)>>>0),ze+=32;else s(ve,ze,j,k,X)}function $e(j,k){z[k][0]=z[j+"0"],z[k][1]=z[j+"1"],z[k][2]=z[j+"2"],z[k][3]=z[j+"3"],z[k][4]=z[j+"4"],z[k][5]=z[j+"5"],z[k][6]=z[j+"6"],z[k][7]=z[j+"7"],z[k][8]=z[j+"8"],z[k][9]=z[j+"9"],z[k][10]=z[j+"10"],z[k][11]=z[j+"11"],z[k][12]=z[j+"12"],z[k][13]=z[j+"13"],z[k][14]=z[j+"0"],z[k][15]=z[j+"0"]}function st(j){return j==Xu||j==sm||j==$d||j==rm}function Nt(){this.eb=[],this.size=this.A=this.fb=0}function be(){this.y=[],this.f=[],this.ea=[],this.F=[],this.Tc=this.Ed=this.Cd=this.Fd=this.lb=this.Db=this.Ab=this.fa=this.J=this.W=this.N=this.O=0}function jt(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Nt,this.f.kb=new be,this.sd=null}function bt(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function tn(){this.Id=this.fd=this.Md=this.hb=this.ib=this.da=this.bd=this.cd=this.j=this.v=this.Da=this.Sd=this.ob=0}function B(j){return alert("todo:WebPSamplerProcessPlane"),j.T}function xe(j,k){var X=j.T,ve=k.ba.f.RGBA,ze=ve.eb,Qe=ve.fb+j.ka*ve.A,Ke=Ci[k.ba.S],Ze=j.y,at=j.O,mt=j.f,Tt=j.N,ln=j.ea,cn=j.W,Kt=k.cc,Un=k.dc,Nn=k.Mc,Mt=k.Nc,Ut=j.ka,$n=j.ka+j.T,Yn=j.U,Tn=Yn+1>>1;for(Ut==0?Ke(Ze,at,null,null,mt,Tt,ln,cn,mt,Tt,ln,cn,ze,Qe,null,null,Yn):(Ke(k.ec,k.fc,Ze,at,Kt,Un,Nn,Mt,mt,Tt,ln,cn,ze,Qe-ve.A,ze,Qe,Yn),++X);Ut+2<$n;Ut+=2)Kt=mt,Un=Tt,Nn=ln,Mt=cn,Tt+=j.Rc,cn+=j.Rc,Qe+=2*ve.A,Ke(Ze,(at+=2*j.fa)-j.fa,Ze,at,Kt,Un,Nn,Mt,mt,Tt,ln,cn,ze,Qe-ve.A,ze,Qe,Yn);return at+=j.fa,j.j+$n<j.o?(s(k.ec,k.fc,Ze,at,Yn),s(k.cc,k.dc,mt,Tt,Tn),s(k.Mc,k.Nc,ln,cn,Tn),X--):1&$n||Ke(Ze,at,null,null,mt,Tt,ln,cn,mt,Tt,ln,cn,ze,Qe+ve.A,null,null,Yn),X}function tt(j,k,X){var ve=j.F,ze=[j.J];if(ve!=null){var Qe=j.U,Ke=k.ba.S,Ze=Ke==Ku||Ke==$d;k=k.ba.f.RGBA;var at=[0],mt=j.ka;at[0]=j.T,j.Kb&&(mt==0?--at[0]:(--mt,ze[0]-=j.width),j.j+j.ka+j.T==j.o&&(at[0]=j.o-j.j-mt));var Tt=k.eb;mt=k.fb+mt*k.A,j=Ss(ve,ze[0],j.width,Qe,at,Tt,mt+(Ze?0:3),k.A),n(X==at),j&&st(Ke)&&sr(Tt,mt,Ze,Qe,at,k.A)}return 0}function ht(j){var k=j.ma,X=k.ba.S,ve=11>X,ze=X==Bi||X==Eo||X==Ku||X==Md||X==12||st(X);if(k.memory=null,k.Ib=null,k.Jb=null,k.Nd=null,!Kn(k.Oa,j,ze?11:12))return 0;if(ze&&st(X)&&Qn(),j.da)alert("todo:use_scaling");else{if(ve){if(k.Ib=B,j.Kb){if(X=j.U+1>>1,k.memory=c(j.U+2*X),k.memory==null)return 0;k.ec=k.memory,k.fc=0,k.cc=k.ec,k.dc=k.fc+j.U,k.Mc=k.cc,k.Nc=k.dc+X,k.Ib=xe,Qn()}}else alert("todo:EmitYUV");ze&&(k.Jb=tt,ve&&an())}if(ve&&!Cl){for(j=0;256>j;++j)Ai[j]=89858*(j-128)+Bd>>Oo,gx[j]=-22014*(j-128)+Bd,Gg[j]=-45773*(j-128),dm[j]=113618*(j-128)+Bd>>Oo;for(j=Kl;j<Sl;++j)k=76283*(j-16)+Bd>>Oo,yx[j-Kl]=En(k,255),vx[j-Kl]=En(k+8>>4,15);Cl=1}return 1}function dt(j){var k=j.ma,X=j.U,ve=j.T;return n(!(1&j.ka)),0>=X||0>=ve?0:(X=k.Ib(j,k),k.Jb!=null&&k.Jb(j,k,X),k.Dc+=X,1)}function we(j){j.ma.memory=null}function rt(j,k,X,ve){return je(j,8)!=47?0:(k[0]=je(j,14)+1,X[0]=je(j,14)+1,ve[0]=je(j,1),je(j,3)!=0?0:!j.h)}function St(j,k){if(4>j)return j+1;var X=j-2>>1;return(2+(1&j)<<X)+je(k,X)+1}function Qt(j,k){return 120<k?k-120:1<=(X=((X=Ro[k-1])>>4)*j+(8-(15&X)))?X:1;var X}function gn(j,k,X){var ve=F(X),ze=j[k+=255&ve].g-8;return 0<ze&&(ue(X,X.u+8),ve=F(X),k+=j[k].value,k+=ve&(1<<ze)-1),ue(X,X.u+j[k].g),j[k].value}function An(j,k,X){return X.g+=j.g,X.value+=j.value<<k>>>0,n(8>=X.g),j.g}function Sn(j,k,X){var ve=j.xc;return n((k=ve==0?0:j.vc[j.md*(X>>ve)+(k>>ve)])<j.Wb),j.Ya[k]}function Xt(j,k,X,ve){var ze=j.ab,Qe=j.c*k,Ke=j.C;k=Ke+k;var Ze=X,at=ve;for(ve=j.Ta,X=j.Ua;0<ze--;){var mt=j.gc[ze],Tt=Ke,ln=k,cn=Ze,Kt=at,Un=(at=ve,Ze=X,mt.Ea);switch(n(Tt<ln),n(ln<=mt.nc),mt.hc){case 2:Hn(cn,Kt,(ln-Tt)*Un,at,Ze);break;case 0:var Nn=Tt,Mt=ln,Ut=at,$n=Ze,Yn=(ba=mt).Ea;Nn==0&&(_a(cn,Kt,null,null,1,Ut,$n),De(cn,Kt+1,0,0,Yn-1,Ut,$n+1),Kt+=Yn,$n+=Yn,++Nn);for(var Tn=1<<ba.b,Aa=Tn-1,fa=se(Yn,ba.b),Va=ba.K,ba=ba.w+(Nn>>ba.b)*fa;Nn<Mt;){var Us=Va,As=ba,Ps=1;for(Vs(cn,Kt,Ut,$n-Yn,1,Ut,$n);Ps<Yn;){var cs=(Ps&~Aa)+Tn;cs>Yn&&(cs=Yn),(0,ye[Us[As++]>>8&15])(cn,Kt+ +Ps,Ut,$n+Ps-Yn,cs-Ps,Ut,$n+Ps),Ps=cs}Kt+=Yn,$n+=Yn,++Nn&Aa||(ba+=fa)}ln!=mt.nc&&s(at,Ze-Un,at,Ze+(ln-Tt-1)*Un,Un);break;case 1:for(Un=cn,Mt=Kt,Yn=(cn=mt.Ea)-($n=cn&~(Ut=(Kt=1<<mt.b)-1)),Nn=se(cn,mt.b),Tn=mt.K,mt=mt.w+(Tt>>mt.b)*Nn;Tt<ln;){for(Aa=Tn,fa=mt,Va=new Me,ba=Mt+$n,Us=Mt+cn;Mt<ba;)ce(Aa[fa++],Va),Fe(Va,Un,Mt,Kt,at,Ze),Mt+=Kt,Ze+=Kt;Mt<Us&&(ce(Aa[fa++],Va),Fe(Va,Un,Mt,Yn,at,Ze),Mt+=Yn,Ze+=Yn),++Tt&Ut||(mt+=Nn)}break;case 3:if(cn==at&&Kt==Ze&&0<mt.b){for(Mt=at,cn=Un=Ze+(ln-Tt)*Un-($n=(ln-Tt)*se(mt.Ea,mt.b)),Kt=at,Ut=Ze,Nn=[],$n=(Yn=$n)-1;0<=$n;--$n)Nn[$n]=Kt[Ut+$n];for($n=Yn-1;0<=$n;--$n)Mt[cn+$n]=Nn[$n];Fa(mt,Tt,ln,at,Un,at,Ze)}else Fa(mt,Tt,ln,cn,Kt,at,Ze)}Ze=ve,at=X}at!=X&&s(ve,X,Ze,at,Qe)}function Wt(j,k){var X=j.V,ve=j.Ba+j.c*j.C,ze=k-j.C;if(n(k<=j.l.o),n(16>=ze),0<ze){var Qe=j.l,Ke=j.Ta,Ze=j.Ua,at=Qe.width;if(Xt(j,ze,X,ve),ze=Ze=[Ze],n((X=j.C)<(ve=k)),n(Qe.v<Qe.va),ve>Qe.o&&(ve=Qe.o),X<Qe.j){var mt=Qe.j-X;X=Qe.j,ze[0]+=mt*at}if(X>=ve?X=0:(ze[0]+=4*Qe.v,Qe.ka=X-Qe.j,Qe.U=Qe.va-Qe.v,Qe.T=ve-X,X=1),X){if(Ze=Ze[0],11>(X=j.ca).S){var Tt=X.f.RGBA,ln=(ve=X.S,ze=Qe.U,Qe=Qe.T,mt=Tt.eb,Tt.A),cn=Qe;for(Tt=Tt.fb+j.Ma*Tt.A;0<cn--;){var Kt=Ke,Un=Ze,Nn=ze,Mt=mt,Ut=Tt;switch(ve){case nm:lt(Kt,Un,Nn,Mt,Ut);break;case Bi:Ot(Kt,Un,Nn,Mt,Ut);break;case Xu:Ot(Kt,Un,Nn,Mt,Ut),sr(Mt,Ut,0,Nn,1,0);break;case am:Rn(Kt,Un,Nn,Mt,Ut);break;case Eo:pt(Kt,Un,Nn,Mt,Ut,1);break;case sm:pt(Kt,Un,Nn,Mt,Ut,1),sr(Mt,Ut,0,Nn,1,0);break;case Ku:pt(Kt,Un,Nn,Mt,Ut,0);break;case $d:pt(Kt,Un,Nn,Mt,Ut,0),sr(Mt,Ut,1,Nn,1,0);break;case Md:Ft(Kt,Un,Nn,Mt,Ut);break;case rm:Ft(Kt,Un,Nn,Mt,Ut),Ka(Mt,Ut,Nn,1,0);break;case bl:rn(Kt,Un,Nn,Mt,Ut);break;default:n(0)}Ze+=at,Tt+=ln}j.Ma+=Qe}else alert("todo:EmitRescaledRowsYUVA");n(j.Ma<=X.height)}}j.C=k,n(j.C<=j.i)}function Gt(j){var k;if(0<j.ua)return 0;for(k=0;k<j.Wb;++k){var X=j.Ya[k].G,ve=j.Ya[k].H;if(0<X[1][ve[1]+0].g||0<X[2][ve[2]+0].g||0<X[3][ve[3]+0].g)return 0}return 1}function $t(j,k,X,ve,ze,Qe){if(j.Z!=0){var Ke=j.qd,Ze=j.rd;for(n(Wc[j.Z]!=null);k<X;++k)Wc[j.Z](Ke,Ze,ve,ze,ve,ze,Qe),Ke=ve,Ze=ze,ze+=Qe;j.qd=Ke,j.rd=Ze}}function Vt(j,k){var X=j.l.ma,ve=X.Z==0||X.Z==1?j.l.j:j.C;if(ve=j.C<ve?ve:j.C,n(k<=j.l.o),k>ve){var ze=j.l.width,Qe=X.ca,Ke=X.tb+ze*ve,Ze=j.V,at=j.Ba+j.c*ve,mt=j.gc;n(j.ab==1),n(mt[0].hc==3),Bs(mt[0],ve,k,Ze,at,Qe,Ke),$t(X,ve,k,Qe,Ke,ze)}j.C=j.Ma=k}function sn(j,k,X,ve,ze,Qe,Ke){var Ze=j.$/ve,at=j.$%ve,mt=j.m,Tt=j.s,ln=X+j.$,cn=ln;ze=X+ve*ze;var Kt=X+ve*Qe,Un=280+Tt.ua,Nn=j.Pb?Ze:16777216,Mt=0<Tt.ua?Tt.Wa:null,Ut=Tt.wc,$n=ln<Kt?Sn(Tt,at,Ze):null;n(j.C<Qe),n(Kt<=ze);var Yn=!1;e:for(;;){for(;Yn||ln<Kt;){var Tn=0;if(Ze>=Nn){var Aa=ln-X;n((Nn=j).Pb),Nn.wd=Nn.m,Nn.xd=Aa,0<Nn.s.ua&&_e(Nn.s.Wa,Nn.s.vb),Nn=Ze+xl}if(at&Ut||($n=Sn(Tt,at,Ze)),n($n!=null),$n.Qb&&(k[ln]=$n.qb,Yn=!0),!Yn)if(me(mt),$n.jc){Tn=mt,Aa=k;var fa=ln,Va=$n.pd[F(Tn)&Ga-1];n($n.jc),256>Va.g?(ue(Tn,Tn.u+Va.g),Aa[fa]=Va.value,Tn=0):(ue(Tn,Tn.u+Va.g-256),n(256<=Va.value),Tn=Va.value),Tn==0&&(Yn=!0)}else Tn=gn($n.G[0],$n.H[0],mt);if(mt.h)break;if(Yn||256>Tn){if(!Yn)if($n.nd)k[ln]=($n.qb|Tn<<8)>>>0;else{if(me(mt),Yn=gn($n.G[1],$n.H[1],mt),me(mt),Aa=gn($n.G[2],$n.H[2],mt),fa=gn($n.G[3],$n.H[3],mt),mt.h)break;k[ln]=(fa<<24|Yn<<16|Tn<<8|Aa)>>>0}if(Yn=!1,++ln,++at>=ve&&(at=0,++Ze,Ke!=null&&Ze<=Qe&&!(Ze%16)&&Ke(j,Ze),Mt!=null))for(;cn<ln;)Tn=k[cn++],Mt.X[(506832829*Tn&4294967295)>>>Mt.Mb]=Tn}else if(280>Tn){if(Tn=St(Tn-256,mt),Aa=gn($n.G[4],$n.H[4],mt),me(mt),Aa=Qt(ve,Aa=St(Aa,mt)),mt.h)break;if(ln-X<Aa||ze-ln<Tn)break e;for(fa=0;fa<Tn;++fa)k[ln+fa]=k[ln+fa-Aa];for(ln+=Tn,at+=Tn;at>=ve;)at-=ve,++Ze,Ke!=null&&Ze<=Qe&&!(Ze%16)&&Ke(j,Ze);if(n(ln<=ze),at&Ut&&($n=Sn(Tt,at,Ze)),Mt!=null)for(;cn<ln;)Tn=k[cn++],Mt.X[(506832829*Tn&4294967295)>>>Mt.Mb]=Tn}else{if(!(Tn<Un))break e;for(Yn=Tn-280,n(Mt!=null);cn<ln;)Tn=k[cn++],Mt.X[(506832829*Tn&4294967295)>>>Mt.Mb]=Tn;Tn=ln,n(!(Yn>>>(Aa=Mt).Xa)),k[Tn]=Aa.X[Yn],Yn=!0}Yn||n(mt.h==P(mt))}if(j.Pb&&mt.h&&ln<ze)n(j.m.h),j.a=5,j.m=j.wd,j.$=j.xd,0<j.s.ua&&_e(j.s.vb,j.s.Wa);else{if(mt.h)break e;Ke!=null&&Ke(j,Ze>Qe?Qe:Ze),j.a=0,j.$=ln-X}return 1}return j.a=3,0}function on(j){n(j!=null),j.vc=null,j.yc=null,j.Ya=null;var k=j.Wa;k!=null&&(k.X=null),j.vb=null,n(j!=null)}function ke(){var j=new vl;return j==null?null:(j.a=0,j.xb=Tp,$e("Predictor","VP8LPredictors"),$e("Predictor","VP8LPredictors_C"),$e("PredictorAdd","VP8LPredictorsAdd"),$e("PredictorAdd","VP8LPredictorsAdd_C"),Hn=Te,Fe=Ye,lt=le,Ot=nt,Ft=xt,rn=te,Rn=Ge,z.VP8LMapColor32b=zs,z.VP8LMapColor8b=S,j)}function Ct(j,k,X,ve,ze){var Qe=1,Ke=[j],Ze=[k],at=ve.m,mt=ve.s,Tt=null,ln=0;e:for(;;){if(X)for(;Qe&&je(at,1);){var cn=Ke,Kt=Ze,Un=ve,Nn=1,Mt=Un.m,Ut=Un.gc[Un.ab],$n=je(Mt,2);if(Un.Oc&1<<$n)Qe=0;else{switch(Un.Oc|=1<<$n,Ut.hc=$n,Ut.Ea=cn[0],Ut.nc=Kt[0],Ut.K=[null],++Un.ab,n(4>=Un.ab),$n){case 0:case 1:Ut.b=je(Mt,3)+2,Nn=Ct(se(Ut.Ea,Ut.b),se(Ut.nc,Ut.b),0,Un,Ut.K),Ut.K=Ut.K[0];break;case 3:var Yn,Tn=je(Mt,8)+1,Aa=16<Tn?0:4<Tn?1:2<Tn?2:3;if(cn[0]=se(Ut.Ea,Aa),Ut.b=Aa,Yn=Nn=Ct(Tn,1,0,Un,Ut.K)){var fa,Va=Tn,ba=Ut,Us=1<<(8>>ba.b),As=c(Us);if(As==null)Yn=0;else{var Ps=ba.K[0],cs=ba.w;for(As[0]=ba.K[0][0],fa=1;fa<1*Va;++fa)As[fa]=pe(Ps[cs+fa],As[fa-1]);for(;fa<4*Us;++fa)As[fa]=0;ba.K[0]=null,ba.K[0]=As,Yn=1}}Nn=Yn;break;case 2:break;default:n(0)}Qe=Nn}}if(Ke=Ke[0],Ze=Ze[0],Qe&&je(at,1)&&!(Qe=1<=(ln=je(at,4))&&11>=ln)){ve.a=3;break e}var Ks;if(Ks=Qe)t:{var Ws,Za,ir,hi=ve,Br=Ke,Fi=Ze,Ls=ln,Ii=X,so=hi.m,ri=hi.s,Fr=[null],mi=1,vo=0,Lo=To[Ls];n:for(;;){if(Ii&&je(so,1)){var Zr=je(so,3)+2,Yr=se(Br,Zr),pi=se(Fi,Zr),bo=Yr*pi;if(!Ct(Yr,pi,0,hi,Fr))break n;for(Fr=Fr[0],ri.xc=Zr,Ws=0;Ws<bo;++Ws){var wc=Fr[Ws]>>8&65535;Fr[Ws]=wc,wc>=mi&&(mi=wc+1)}}if(so.h)break n;for(Za=0;5>Za;++Za){var Tr=Ql[Za];!Za&&0<Ls&&(Tr+=1<<Ls),vo<Tr&&(vo=Tr)}var Nc=l(mi*Lo,D),ro=mi,Ur=l(ro,Z);if(Ur==null)var Xl=null;else n(65536>=ro),Xl=Ur;var xo=c(vo);if(Xl==null||xo==null||Nc==null){hi.a=1;break n}var os=Nc;for(Ws=ir=0;Ws<mi;++Ws){var ps=Xl[Ws],Sr=ps.G,Gc=ps.H,Zl=0,Sc=1,nh=0;for(Za=0;5>Za;++Za){Tr=Ql[Za],Sr[Za]=os,Gc[Za]=ir,!Za&&0<Ls&&(Tr+=1<<Ls);s:{var Al,Il=Tr,hm=hi,fr=xo,$p=os,Op=ir,mm=0,Yc=hm.m,bx=je(Yc,1);if(i(fr,0,0,Il),bx){var Lp=je(Yc,1)+1,Bp=je(Yc,1),pm=je(Yc,Bp==0?1:8);fr[pm]=1,Lp==2&&(fr[pm=je(Yc,8)]=1);var fi=1}else{var zr=c(19),ah=je(Yc,4)+4;if(19<ah){hm.a=3;var _l=0;break s}for(Al=0;Al<ah;++Al)zr[Zu[Al]]=je(Yc,3);var Ud=void 0,ed=void 0,Cc=hm,fm=zr,zd=Il,gm=fr,ym=0,Qc=Cc.m,Fp=8,Up=l(128,D);a:for(;L(Up,0,7,fm,19);){if(je(Qc,1)){var Yg=2+2*je(Qc,3);if((Ud=2+je(Qc,Yg))>zd)break a}else Ud=zd;for(ed=0;ed<zd&&Ud--;){me(Qc);var zp=Up[0+(127&F(Qc))];ue(Qc,Qc.u+zp.g);var kl=zp.value;if(16>kl)gm[ed++]=kl,kl!=0&&(Fp=kl);else{var Qg=kl==16,Jg=kl-16,Kg=Od[Jg],qp=je(Qc,Po[Jg])+Kg;if(ed+qp>zd)break a;for(var Xg=Qg?Fp:0;0<qp--;)gm[ed++]=Xg}}ym=1;break a}ym||(Cc.a=3),fi=ym}(fi=fi&&!Yc.h)&&(mm=L($p,Op,8,fr,Il)),fi&&mm!=0?_l=mm:(hm.a=3,_l=0)}if(_l==0)break n;if(Sc&&im[Za]==1&&(Sc=os[ir].g==0),Zl+=os[ir].g,ir+=_l,3>=Za){var td,vm=xo[0];for(td=1;td<Tr;++td)xo[td]>vm&&(vm=xo[td]);nh+=vm}}if(ps.nd=Sc,ps.Qb=0,Sc&&(ps.qb=(Sr[3][Gc[3]+0].value<<24|Sr[1][Gc[1]+0].value<<16|Sr[2][Gc[2]+0].value)>>>0,Zl==0&&256>Sr[0][Gc[0]+0].value&&(ps.Qb=1,ps.qb+=Sr[0][Gc[0]+0].value<<8)),ps.jc=!ps.Qb&&6>nh,ps.jc){var sh,Ac=ps;for(sh=0;sh<Ga;++sh){var Jc=sh,Kc=Ac.pd[Jc],bm=Ac.G[0][Ac.H[0]+Jc];256<=bm.value?(Kc.g=bm.g+256,Kc.value=bm.value):(Kc.g=0,Kc.value=0,Jc>>=An(bm,8,Kc),Jc>>=An(Ac.G[1][Ac.H[1]+Jc],16,Kc),Jc>>=An(Ac.G[2][Ac.H[2]+Jc],0,Kc),An(Ac.G[3][Ac.H[3]+Jc],24,Kc))}}}ri.vc=Fr,ri.Wb=mi,ri.Ya=Xl,ri.yc=Nc,Ks=1;break t}Ks=0}if(!(Qe=Ks)){ve.a=3;break e}if(0<ln){if(mt.ua=1<<ln,!it(mt.Wa,ln)){ve.a=1,Qe=0;break e}}else mt.ua=0;var xm=ve,nd=Ke,Zg=Ze,qd=xm.s,Vd=qd.xc;if(xm.c=nd,xm.i=Zg,qd.md=se(nd,Vd),qd.wc=Vd==0?-1:(1<<Vd)-1,X){ve.xb=jl;break e}if((Tt=c(Ke*Ze))==null){ve.a=1,Qe=0;break e}Qe=(Qe=sn(ve,Tt,0,Ke,Ze,Ze,null))&&!at.h;break e}return Qe?(ze!=null?ze[0]=Tt:(n(Tt==null),n(X)),ve.$=0,X||on(mt)):on(mt),Qe}function Et(j,k){var X=j.c*j.i,ve=X+k+16*k;return n(j.c<=k),j.V=c(ve),j.V==null?(j.Ta=null,j.Ua=0,j.a=1,0):(j.Ta=j.V,j.Ua=j.Ba+X+k,1)}function Rt(j,k){var X=j.C,ve=k-X,ze=j.V,Qe=j.Ba+j.c*X;for(n(k<=j.l.o);0<ve;){var Ke=16<ve?16:ve,Ze=j.l.ma,at=j.l.width,mt=at*Ke,Tt=Ze.ca,ln=Ze.tb+at*X,cn=j.Ta,Kt=j.Ua;Xt(j,Ke,ze,Qe),Es(cn,Kt,Tt,ln,mt),$t(Ze,X,X+Ke,Tt,ln,at),ve-=Ke,ze+=Ke*j.c,X+=Ke}n(X==k),j.C=j.Ma=k}function xn(){this.ub=this.yd=this.td=this.Rb=0}function dn(){this.Kd=this.Ld=this.Ud=this.Td=this.i=this.c=0}function Ln(){this.Fb=this.Bb=this.Cb=0,this.Zb=c(4),this.Lb=c(4)}function wa(){this.Yb=(function(){var j=[];return(function k(X,ve,ze){for(var Qe=ze[ve],Ke=0;Ke<Qe&&(X.push(ze.length>ve+1?[]:0),!(ze.length<ve+1));Ke++)k(X[Ke],ve+1,ze)})(j,0,[3,11]),j})()}function Ca(){this.jb=c(3),this.Wc=m([4,8],wa),this.Xc=m([4,17],wa)}function In(){this.Pc=this.wb=this.Tb=this.zd=0,this.vd=new c(4),this.od=new c(4)}function Sa(){this.ld=this.La=this.dd=this.tc=0}function aa(){this.Na=this.la=0}function $a(){this.Sc=[0,0],this.Eb=[0,0],this.Qc=[0,0],this.ia=this.lc=0}function jn(){this.ad=c(384),this.Za=0,this.Ob=c(16),this.$b=this.Ad=this.ia=this.Gc=this.Hc=this.Dd=0}function vs(){this.uc=this.M=this.Nb=0,this.wa=Array(new Sa),this.Y=0,this.ya=Array(new jn),this.aa=0,this.l=new _n}function ka(){this.y=c(16),this.f=c(8),this.ea=c(8)}function Ja(){this.cb=this.a=0,this.sc="",this.m=new V,this.Od=new xn,this.Kc=new dn,this.ed=new In,this.Qa=new Ln,this.Ic=this.$c=this.Aa=0,this.D=new vs,this.Xb=this.Va=this.Hb=this.zb=this.yb=this.Ub=this.za=0,this.Jc=l(8,V),this.ia=0,this.pb=l(4,$a),this.Pa=new Ca,this.Bd=this.kc=0,this.Ac=[],this.Bc=0,this.zc=[0,0,0,0],this.Gd=Array(new ka),this.Hd=0,this.rb=Array(new aa),this.sb=0,this.wa=Array(new Sa),this.Y=0,this.oc=[],this.pc=0,this.sa=[],this.ta=0,this.qa=[],this.ra=0,this.Ha=[],this.B=this.R=this.Ia=0,this.Ec=[],this.M=this.ja=this.Vb=this.Fc=0,this.ya=Array(new jn),this.L=this.aa=0,this.gd=m([4,2],Sa),this.ga=null,this.Fa=[],this.Cc=this.qc=this.P=0,this.Gb=[],this.Uc=0,this.mb=[],this.nb=0,this.rc=[],this.Ga=this.Vc=0}function _n(){this.T=this.U=this.ka=this.height=this.width=0,this.y=[],this.f=[],this.ea=[],this.Rc=this.fa=this.W=this.N=this.O=0,this.ma="void",this.put="VP8IoPutHook",this.ac="VP8IoSetupHook",this.bc="VP8IoTeardownHook",this.ha=this.Kb=0,this.data=[],this.hb=this.ib=this.da=this.o=this.j=this.va=this.v=this.Da=this.ob=this.w=0,this.F=[],this.J=0}function ha(){var j=new Ja;return j!=null&&(j.a=0,j.sc="OK",j.cb=0,j.Xb=0,yo||(yo=Zt)),j}function ta(j,k,X){return j.a==0&&(j.a=k,j.sc=X,j.cb=0),0}function W(j,k,X){return 3<=X&&j[k+0]==157&&j[k+1]==1&&j[k+2]==42}function ft(j,k){if(j==null)return 0;if(j.a=0,j.sc="OK",k==null)return ta(j,2,"null VP8Io passed to VP8GetHeaders()");var X=k.data,ve=k.w,ze=k.ha;if(4>ze)return ta(j,7,"Truncated header.");var Qe=X[ve+0]|X[ve+1]<<8|X[ve+2]<<16,Ke=j.Od;if(Ke.Rb=!(1&Qe),Ke.td=Qe>>1&7,Ke.yd=Qe>>4&1,Ke.ub=Qe>>5,3<Ke.td)return ta(j,3,"Incorrect keyframe parameters.");if(!Ke.yd)return ta(j,4,"Frame not displayable.");ve+=3,ze-=3;var Ze=j.Kc;if(Ke.Rb){if(7>ze)return ta(j,7,"cannot parse picture header");if(!W(X,ve,ze))return ta(j,3,"Bad code word");Ze.c=16383&(X[ve+4]<<8|X[ve+3]),Ze.Td=X[ve+4]>>6,Ze.i=16383&(X[ve+6]<<8|X[ve+5]),Ze.Ud=X[ve+6]>>6,ve+=7,ze-=7,j.za=Ze.c+15>>4,j.Ub=Ze.i+15>>4,k.width=Ze.c,k.height=Ze.i,k.Da=0,k.j=0,k.v=0,k.va=k.width,k.o=k.height,k.da=0,k.ib=k.width,k.hb=k.height,k.U=k.width,k.T=k.height,i((Qe=j.Pa).jb,0,255,Qe.jb.length),n((Qe=j.Qa)!=null),Qe.Cb=0,Qe.Bb=0,Qe.Fb=1,i(Qe.Zb,0,0,Qe.Zb.length),i(Qe.Lb,0,0,Qe.Lb)}if(Ke.ub>ze)return ta(j,7,"bad partition length");fe(Qe=j.m,X,ve,Ke.ub),ve+=Ke.ub,ze-=Ke.ub,Ke.Rb&&(Ze.Ld=de(Qe),Ze.Kd=de(Qe)),Ze=j.Qa;var at,mt=j.Pa;if(n(Qe!=null),n(Ze!=null),Ze.Cb=de(Qe),Ze.Cb){if(Ze.Bb=de(Qe),de(Qe)){for(Ze.Fb=de(Qe),at=0;4>at;++at)Ze.Zb[at]=de(Qe)?ne(Qe,7):0;for(at=0;4>at;++at)Ze.Lb[at]=de(Qe)?ne(Qe,6):0}if(Ze.Bb)for(at=0;3>at;++at)mt.jb[at]=de(Qe)?q(Qe,8):255}else Ze.Bb=0;if(Qe.Ka)return ta(j,3,"cannot parse segment header");if((Ze=j.ed).zd=de(Qe),Ze.Tb=q(Qe,6),Ze.wb=q(Qe,3),Ze.Pc=de(Qe),Ze.Pc&&de(Qe)){for(mt=0;4>mt;++mt)de(Qe)&&(Ze.vd[mt]=ne(Qe,6));for(mt=0;4>mt;++mt)de(Qe)&&(Ze.od[mt]=ne(Qe,6))}if(j.L=Ze.Tb==0?0:Ze.zd?1:2,Qe.Ka)return ta(j,3,"cannot parse filter header");var Tt=ze;if(ze=at=ve,ve=at+Tt,Ze=Tt,j.Xb=(1<<q(j.m,2))-1,Tt<3*(mt=j.Xb))X=7;else{for(at+=3*mt,Ze-=3*mt,Tt=0;Tt<mt;++Tt){var ln=X[ze+0]|X[ze+1]<<8|X[ze+2]<<16;ln>Ze&&(ln=Ze),fe(j.Jc[+Tt],X,at,ln),at+=ln,Ze-=ln,ze+=3}fe(j.Jc[+mt],X,at,Ze),X=at<ve?0:5}if(X!=0)return ta(j,X,"cannot parse partitions");for(X=q(at=j.m,7),ze=de(at)?ne(at,4):0,ve=de(at)?ne(at,4):0,Ze=de(at)?ne(at,4):0,mt=de(at)?ne(at,4):0,at=de(at)?ne(at,4):0,Tt=j.Qa,ln=0;4>ln;++ln){if(Tt.Cb){var cn=Tt.Zb[ln];Tt.Fb||(cn+=X)}else{if(0<ln){j.pb[ln]=j.pb[0];continue}cn=X}var Kt=j.pb[ln];Kt.Sc[0]=Mo[En(cn+ze,127)],Kt.Sc[1]=$o[En(cn+0,127)],Kt.Eb[0]=2*Mo[En(cn+ve,127)],Kt.Eb[1]=101581*$o[En(cn+Ze,127)]>>16,8>Kt.Eb[1]&&(Kt.Eb[1]=8),Kt.Qc[0]=Mo[En(cn+mt,117)],Kt.Qc[1]=$o[En(cn+at,127)],Kt.lc=cn+at}if(!Ke.Rb)return ta(j,4,"Not a key frame.");for(de(Qe),Ke=j.Pa,X=0;4>X;++X){for(ze=0;8>ze;++ze)for(ve=0;3>ve;++ve)for(Ze=0;11>Ze;++Ze)mt=Pe(Qe,Nr[X][ze][ve][Ze])?q(Qe,8):Wg[X][ze][ve][Ze],Ke.Wc[X][ze].Yb[ve][Ze]=mt;for(ze=0;17>ze;++ze)Ke.Xc[X][ze]=Ke.Wc[X][Cs[ze]]}return j.kc=de(Qe),j.kc&&(j.Bd=q(Qe,8)),j.cb=1}function Zt(j,k,X,ve,ze,Qe,Ke){var Ze=k[ze].Yb[X];for(X=0;16>ze;++ze){if(!Pe(j,Ze[X+0]))return ze;for(;!Pe(j,Ze[X+1]);)if(Ze=k[++ze].Yb[0],X=0,ze==16)return 16;var at=k[ze+1].Yb;if(Pe(j,Ze[X+2])){var mt=j,Tt=0;if(Pe(mt,(cn=Ze)[(ln=X)+3]))if(Pe(mt,cn[ln+6])){for(Ze=0,ln=2*(Tt=Pe(mt,cn[ln+8]))+(cn=Pe(mt,cn[ln+9+Tt])),Tt=0,cn=Hg[ln];cn[Ze];++Ze)Tt+=Tt+Pe(mt,cn[Ze]);Tt+=3+(8<<ln)}else Pe(mt,cn[ln+7])?(Tt=7+2*Pe(mt,165),Tt+=Pe(mt,145)):Tt=5+Pe(mt,159);else Tt=Pe(mt,cn[ln+4])?3+Pe(mt,cn[ln+5]):2;Ze=at[2]}else Tt=1,Ze=at[1];at=Ke+Rp[ze],0>(mt=j).b&&ge(mt);var ln,cn=mt.b,Kt=(ln=mt.Ca>>1)-(mt.I>>cn)>>31;--mt.b,mt.Ca+=Kt,mt.Ca|=1,mt.I-=(ln+1&Kt)<<cn,Qe[at]=((Tt^Kt)-Kt)*ve[(0<ze)+0]}return 16}function vt(j){var k=j.rb[j.sb-1];k.la=0,k.Na=0,i(j.zc,0,0,j.zc.length),j.ja=0}function Ae(j,k){if(j==null)return 0;if(k==null)return ta(j,2,"NULL VP8Io parameter in VP8Decode().");if(!j.cb&&!ft(j,k))return 0;if(n(j.cb),k.ac==null||k.ac(k)){k.ob&&(j.L=0);var X=Fd[j.L];if(j.L==2?(j.yb=0,j.zb=0):(j.yb=k.v-X>>4,j.zb=k.j-X>>4,0>j.yb&&(j.yb=0),0>j.zb&&(j.zb=0)),j.Va=k.o+15+X>>4,j.Hb=k.va+15+X>>4,j.Hb>j.za&&(j.Hb=j.za),j.Va>j.Ub&&(j.Va=j.Ub),0<j.L){var ve=j.ed;for(X=0;4>X;++X){var ze;if(j.Qa.Cb){var Qe=j.Qa.Lb[X];j.Qa.Fb||(Qe+=ve.Tb)}else Qe=ve.Tb;for(ze=0;1>=ze;++ze){var Ke=j.gd[X][ze],Ze=Qe;if(ve.Pc&&(Ze+=ve.vd[0],ze&&(Ze+=ve.od[0])),0<(Ze=0>Ze?0:63<Ze?63:Ze)){var at=Ze;0<ve.wb&&(at=4<ve.wb?at>>2:at>>1)>9-ve.wb&&(at=9-ve.wb),1>at&&(at=1),Ke.dd=at,Ke.tc=2*Ze+at,Ke.ld=40<=Ze?2:15<=Ze?1:0}else Ke.tc=0;Ke.La=ze}}}X=0}else ta(j,6,"Frame setup failed"),X=j.a;if(X=X==0){if(X){j.$c=0,0<j.Aa||(j.Ic=th);e:{X=j.Ic,ve=4*(at=j.za);var mt=32*at,Tt=at+1,ln=0<j.L?at*(0<j.Aa?2:1):0,cn=(j.Aa==2?2:1)*at;if((Ke=ve+832+(ze=3*(16*X+Fd[j.L])/2*mt)+(Qe=j.Fa!=null&&0<j.Fa.length?j.Kc.c*j.Kc.i:0))!=Ke)X=0;else{if(Ke>j.Vb){if(j.Vb=0,j.Ec=c(Ke),j.Fc=0,j.Ec==null){X=ta(j,1,"no memory during frame initialization.");break e}j.Vb=Ke}Ke=j.Ec,Ze=j.Fc,j.Ac=Ke,j.Bc=Ze,Ze+=ve,j.Gd=l(mt,ka),j.Hd=0,j.rb=l(Tt+1,aa),j.sb=1,j.wa=ln?l(ln,Sa):null,j.Y=0,j.D.Nb=0,j.D.wa=j.wa,j.D.Y=j.Y,0<j.Aa&&(j.D.Y+=at),n(!0),j.oc=Ke,j.pc=Ze,Ze+=832,j.ya=l(cn,jn),j.aa=0,j.D.ya=j.ya,j.D.aa=j.aa,j.Aa==2&&(j.D.aa+=at),j.R=16*at,j.B=8*at,at=(mt=Fd[j.L])*j.R,mt=mt/2*j.B,j.sa=Ke,j.ta=Ze+at,j.qa=j.sa,j.ra=j.ta+16*X*j.R+mt,j.Ha=j.qa,j.Ia=j.ra+8*X*j.B+mt,j.$c=0,Ze+=ze,j.mb=Qe?Ke:null,j.nb=Qe?Ze:null,n(Ze+Qe<=j.Fc+j.Vb),vt(j),i(j.Ac,j.Bc,0,ve),X=1}}if(X){if(k.ka=0,k.y=j.sa,k.O=j.ta,k.f=j.qa,k.N=j.ra,k.ea=j.Ha,k.Vd=j.Ia,k.fa=j.R,k.Rc=j.B,k.F=null,k.J=0,!go){for(X=-255;255>=X;++X)rr[255+X]=0>X?-X:X;for(X=-1020;1020>=X;++X)ao[1020+X]=-128>X?-128:127<X?127:X;for(X=-112;112>=X;++X)xc[112+X]=-16>X?-16:15<X?15:X;for(X=-255;510>=X;++X)Do[255+X]=0>X?0:255<X?255:X;go=1}ea=Jn,Wn=At,Fn=en,Na=It,ya=Pt,Bn=ut,Ba=Bc,Ya=no,Os=Yl,ys=Uc,_r=Fc,tr=Xo,wr=Gi,Ns=zc,Wr=pr,nr=Or,Fs=Js,Hs=Ko,Lr[0]=Ha,Lr[1]=Mn,Lr[2]=xa,Lr[3]=ra,Lr[4]=is,Lr[5]=rs,Lr[6]=hs,Lr[7]=oa,Lr[8]=bs,Lr[9]=qa,Yi[0]=ua,Yi[1]=ga,Yi[2]=zn,Yi[3]=Xn,Yi[4]=Ma,Yi[5]=Xe,Yi[6]=Jt,nc[0]=Kr,nc[1]=Ea,nc[2]=Wa,nc[3]=$s,nc[4]=Rr,nc[5]=Xr,nc[6]=er,X=1}else X=0}X&&(X=(function(Kt,Un){for(Kt.M=0;Kt.M<Kt.Va;++Kt.M){var Nn,Mt=Kt.Jc[Kt.M&Kt.Xb],Ut=Kt.m,$n=Kt;for(Nn=0;Nn<$n.za;++Nn){var Yn=Ut,Tn=$n,Aa=Tn.Ac,fa=Tn.Bc+4*Nn,Va=Tn.zc,ba=Tn.ya[Tn.aa+Nn];if(Tn.Qa.Bb?ba.$b=Pe(Yn,Tn.Pa.jb[0])?2+Pe(Yn,Tn.Pa.jb[2]):Pe(Yn,Tn.Pa.jb[1]):ba.$b=0,Tn.kc&&(ba.Ad=Pe(Yn,Tn.Bd)),ba.Za=!Pe(Yn,145)+0,ba.Za){var Us=ba.Ob,As=0;for(Tn=0;4>Tn;++Tn){var Ps,cs=Va[0+Tn];for(Ps=0;4>Ps;++Ps){cs=Si[Aa[fa+Ps]][cs];for(var Ks=om[Pe(Yn,cs[0])];0<Ks;)Ks=om[2*Ks+Pe(Yn,cs[Ks])];cs=-Ks,Aa[fa+Ps]=cs}s(Us,As,Aa,fa,4),As+=4,Va[0+Tn]=cs}}else cs=Pe(Yn,156)?Pe(Yn,128)?1:3:Pe(Yn,163)?2:0,ba.Ob[0]=cs,i(Aa,fa,cs,4),i(Va,0,cs,4);ba.Dd=Pe(Yn,142)?Pe(Yn,114)?Pe(Yn,183)?1:3:2:0}if($n.m.Ka)return ta(Kt,7,"Premature end-of-partition0 encountered.");for(;Kt.ja<Kt.za;++Kt.ja){if($n=Mt,Yn=(Ut=Kt).rb[Ut.sb-1],Aa=Ut.rb[Ut.sb+Ut.ja],Nn=Ut.ya[Ut.aa+Ut.ja],fa=Ut.kc?Nn.Ad:0)Yn.la=Aa.la=0,Nn.Za||(Yn.Na=Aa.Na=0),Nn.Hc=0,Nn.Gc=0,Nn.ia=0;else{var Ws,Za;if(Yn=Aa,Aa=$n,fa=Ut.Pa.Xc,Va=Ut.ya[Ut.aa+Ut.ja],ba=Ut.pb[Va.$b],Tn=Va.ad,Us=0,As=Ut.rb[Ut.sb-1],cs=Ps=0,i(Tn,Us,0,384),Va.Za)var ir=0,hi=fa[3];else{Ks=c(16);var Br=Yn.Na+As.Na;if(Br=yo(Aa,fa[1],Br,ba.Eb,0,Ks,0),Yn.Na=As.Na=(0<Br)+0,1<Br)ea(Ks,0,Tn,Us);else{var Fi=Ks[0]+3>>3;for(Ks=0;256>Ks;Ks+=16)Tn[Us+Ks]=Fi}ir=1,hi=fa[0]}var Ls=15&Yn.la,Ii=15&As.la;for(Ks=0;4>Ks;++Ks){var so=1&Ii;for(Fi=Za=0;4>Fi;++Fi)Ls=Ls>>1|(so=(Br=yo(Aa,hi,Br=so+(1&Ls),ba.Sc,ir,Tn,Us))>ir)<<7,Za=Za<<2|(3<Br?3:1<Br?2:Tn[Us+0]!=0),Us+=16;Ls>>=4,Ii=Ii>>1|so<<7,Ps=(Ps<<8|Za)>>>0}for(hi=Ls,ir=Ii>>4,Ws=0;4>Ws;Ws+=2){for(Za=0,Ls=Yn.la>>4+Ws,Ii=As.la>>4+Ws,Ks=0;2>Ks;++Ks){for(so=1&Ii,Fi=0;2>Fi;++Fi)Br=so+(1&Ls),Ls=Ls>>1|(so=0<(Br=yo(Aa,fa[2],Br,ba.Qc,0,Tn,Us)))<<3,Za=Za<<2|(3<Br?3:1<Br?2:Tn[Us+0]!=0),Us+=16;Ls>>=2,Ii=Ii>>1|so<<5}cs|=Za<<4*Ws,hi|=Ls<<4<<Ws,ir|=(240&Ii)<<Ws}Yn.la=hi,As.la=ir,Va.Hc=Ps,Va.Gc=cs,Va.ia=43690&cs?0:ba.ia,fa=!(Ps|cs)}if(0<Ut.L&&(Ut.wa[Ut.Y+Ut.ja]=Ut.gd[Nn.$b][Nn.Za],Ut.wa[Ut.Y+Ut.ja].La|=!fa),$n.Ka)return ta(Kt,7,"Premature end-of-file encountered.")}if(vt(Kt),Ut=Un,$n=1,Nn=(Mt=Kt).D,Yn=0<Mt.L&&Mt.M>=Mt.zb&&Mt.M<=Mt.Va,Mt.Aa==0)e:{if(Nn.M=Mt.M,Nn.uc=Yn,Pa(Mt,Nn),$n=1,Nn=(Za=Mt.D).Nb,Yn=(cs=Fd[Mt.L])*Mt.R,Aa=cs/2*Mt.B,Ks=16*Nn*Mt.R,Fi=8*Nn*Mt.B,fa=Mt.sa,Va=Mt.ta-Yn+Ks,ba=Mt.qa,Tn=Mt.ra-Aa+Fi,Us=Mt.Ha,As=Mt.Ia-Aa+Fi,Ii=(Ls=Za.M)==0,Ps=Ls>=Mt.Va-1,Mt.Aa==2&&Pa(Mt,Za),Za.uc)for(so=(Br=Mt).D.M,n(Br.D.uc),Za=Br.yb;Za<Br.Hb;++Za){ir=Za,hi=so;var ri=(Fr=(Tr=Br).D).Nb;Ws=Tr.R;var Fr=Fr.wa[Fr.Y+ir],mi=Tr.sa,vo=Tr.ta+16*ri*Ws+16*ir,Lo=Fr.dd,Zr=Fr.tc;if(Zr!=0)if(n(3<=Zr),Tr.L==1)0<ir&&nr(mi,vo,Ws,Zr+4),Fr.La&&Hs(mi,vo,Ws,Zr),0<hi&&Wr(mi,vo,Ws,Zr+4),Fr.La&&Fs(mi,vo,Ws,Zr);else{var Yr=Tr.B,pi=Tr.qa,bo=Tr.ra+8*ri*Yr+8*ir,wc=Tr.Ha,Tr=Tr.Ia+8*ri*Yr+8*ir;ri=Fr.ld,0<ir&&(Ya(mi,vo,Ws,Zr+4,Lo,ri),ys(pi,bo,wc,Tr,Yr,Zr+4,Lo,ri)),Fr.La&&(tr(mi,vo,Ws,Zr,Lo,ri),Ns(pi,bo,wc,Tr,Yr,Zr,Lo,ri)),0<hi&&(Ba(mi,vo,Ws,Zr+4,Lo,ri),Os(pi,bo,wc,Tr,Yr,Zr+4,Lo,ri)),Fr.La&&(_r(mi,vo,Ws,Zr,Lo,ri),wr(pi,bo,wc,Tr,Yr,Zr,Lo,ri))}}if(Mt.ia&&alert("todo:DitherRow"),Ut.put!=null){if(Za=16*Ls,Ls=16*(Ls+1),Ii?(Ut.y=Mt.sa,Ut.O=Mt.ta+Ks,Ut.f=Mt.qa,Ut.N=Mt.ra+Fi,Ut.ea=Mt.Ha,Ut.W=Mt.Ia+Fi):(Za-=cs,Ut.y=fa,Ut.O=Va,Ut.f=ba,Ut.N=Tn,Ut.ea=Us,Ut.W=As),Ps||(Ls-=cs),Ls>Ut.o&&(Ls=Ut.o),Ut.F=null,Ut.J=null,Mt.Fa!=null&&0<Mt.Fa.length&&Za<Ls&&(Ut.J=ko(Mt,Ut,Za,Ls-Za),Ut.F=Mt.mb,Ut.F==null&&Ut.F.length==0)){$n=ta(Mt,3,"Could not decode alpha data.");break e}Za<Ut.j&&(cs=Ut.j-Za,Za=Ut.j,n(!(1&cs)),Ut.O+=Mt.R*cs,Ut.N+=Mt.B*(cs>>1),Ut.W+=Mt.B*(cs>>1),Ut.F!=null&&(Ut.J+=Ut.width*cs)),Za<Ls&&(Ut.O+=Ut.v,Ut.N+=Ut.v>>1,Ut.W+=Ut.v>>1,Ut.F!=null&&(Ut.J+=Ut.v),Ut.ka=Za-Ut.j,Ut.U=Ut.va-Ut.v,Ut.T=Ls-Za,$n=Ut.put(Ut))}Nn+1!=Mt.Ic||Ps||(s(Mt.sa,Mt.ta-Yn,fa,Va+16*Mt.R,Yn),s(Mt.qa,Mt.ra-Aa,ba,Tn+8*Mt.B,Aa),s(Mt.Ha,Mt.Ia-Aa,Us,As+8*Mt.B,Aa))}if(!$n)return ta(Kt,6,"Output aborted.")}return 1})(j,k)),k.bc!=null&&k.bc(k),X&=1}return X?(j.cb=0,X):0}function oe(j,k,X,ve,ze){ze=j[k+X+32*ve]+(ze>>3),j[k+X+32*ve]=-256&ze?0>ze?0:255:ze}function Ve(j,k,X,ve,ze,Qe){oe(j,k,0,X,ve+ze),oe(j,k,1,X,ve+Qe),oe(j,k,2,X,ve-Qe),oe(j,k,3,X,ve-ze)}function he(j){return(20091*j>>16)+j}function Oe(j,k,X,ve){var ze,Qe=0,Ke=c(16);for(ze=0;4>ze;++ze){var Ze=j[k+0]+j[k+8],at=j[k+0]-j[k+8],mt=(35468*j[k+4]>>16)-he(j[k+12]),Tt=he(j[k+4])+(35468*j[k+12]>>16);Ke[Qe+0]=Ze+Tt,Ke[Qe+1]=at+mt,Ke[Qe+2]=at-mt,Ke[Qe+3]=Ze-Tt,Qe+=4,k++}for(ze=Qe=0;4>ze;++ze)Ze=(j=Ke[Qe+0]+4)+Ke[Qe+8],at=j-Ke[Qe+8],mt=(35468*Ke[Qe+4]>>16)-he(Ke[Qe+12]),oe(X,ve,0,0,Ze+(Tt=he(Ke[Qe+4])+(35468*Ke[Qe+12]>>16))),oe(X,ve,1,0,at+mt),oe(X,ve,2,0,at-mt),oe(X,ve,3,0,Ze-Tt),Qe++,ve+=32}function ut(j,k,X,ve){var ze=j[k+0]+4,Qe=35468*j[k+4]>>16,Ke=he(j[k+4]),Ze=35468*j[k+1]>>16;Ve(X,ve,0,ze+Ke,j=he(j[k+1]),Ze),Ve(X,ve,1,ze+Qe,j,Ze),Ve(X,ve,2,ze-Qe,j,Ze),Ve(X,ve,3,ze-Ke,j,Ze)}function At(j,k,X,ve,ze){Oe(j,k,X,ve),ze&&Oe(j,k+16,X,ve+4)}function en(j,k,X,ve){Wn(j,k+0,X,ve,1),Wn(j,k+32,X,ve+128,1)}function It(j,k,X,ve){var ze;for(j=j[k+0]+4,ze=0;4>ze;++ze)for(k=0;4>k;++k)oe(X,ve,k,ze,j)}function Pt(j,k,X,ve){j[k+0]&&Na(j,k+0,X,ve),j[k+16]&&Na(j,k+16,X,ve+4),j[k+32]&&Na(j,k+32,X,ve+128),j[k+48]&&Na(j,k+48,X,ve+128+4)}function Jn(j,k,X,ve){var ze,Qe=c(16);for(ze=0;4>ze;++ze){var Ke=j[k+0+ze]+j[k+12+ze],Ze=j[k+4+ze]+j[k+8+ze],at=j[k+4+ze]-j[k+8+ze],mt=j[k+0+ze]-j[k+12+ze];Qe[0+ze]=Ke+Ze,Qe[8+ze]=Ke-Ze,Qe[4+ze]=mt+at,Qe[12+ze]=mt-at}for(ze=0;4>ze;++ze)Ke=(j=Qe[0+4*ze]+3)+Qe[3+4*ze],Ze=Qe[1+4*ze]+Qe[2+4*ze],at=Qe[1+4*ze]-Qe[2+4*ze],mt=j-Qe[3+4*ze],X[ve+0]=Ke+Ze>>3,X[ve+16]=mt+at>>3,X[ve+32]=Ke-Ze>>3,X[ve+48]=mt-at>>3,ve+=64}function na(j,k,X){var ve,ze=k-32,Qe=Li,Ke=255-j[ze-1];for(ve=0;ve<X;++ve){var Ze,at=Qe,mt=Ke+j[k-1];for(Ze=0;Ze<X;++Ze)j[k+Ze]=at[mt+j[ze+Ze]];k+=32}}function Mn(j,k){na(j,k,4)}function Ea(j,k){na(j,k,8)}function ga(j,k){na(j,k,16)}function zn(j,k){var X;for(X=0;16>X;++X)s(j,k+32*X,j,k-32,16)}function Xn(j,k){var X;for(X=16;0<X;--X)i(j,k,j[k-1],16),k+=32}function Vn(j,k,X){var ve;for(ve=0;16>ve;++ve)i(k,X+32*ve,j,16)}function ua(j,k){var X,ve=16;for(X=0;16>X;++X)ve+=j[k-1+32*X]+j[k+X-32];Vn(ve>>5,j,k)}function Ma(j,k){var X,ve=8;for(X=0;16>X;++X)ve+=j[k-1+32*X];Vn(ve>>4,j,k)}function Xe(j,k){var X,ve=8;for(X=0;16>X;++X)ve+=j[k+X-32];Vn(ve>>4,j,k)}function Jt(j,k){Vn(128,j,k)}function Ht(j,k,X){return j+2*k+X+2>>2}function xa(j,k){var X,ve=k-32;for(ve=new Uint8Array([Ht(j[ve-1],j[ve+0],j[ve+1]),Ht(j[ve+0],j[ve+1],j[ve+2]),Ht(j[ve+1],j[ve+2],j[ve+3]),Ht(j[ve+2],j[ve+3],j[ve+4])]),X=0;4>X;++X)s(j,k+32*X,ve,0,ve.length)}function ra(j,k){var X=j[k-1],ve=j[k-1+32],ze=j[k-1+64],Qe=j[k-1+96];Re(j,k+0,16843009*Ht(j[k-1-32],X,ve)),Re(j,k+32,16843009*Ht(X,ve,ze)),Re(j,k+64,16843009*Ht(ve,ze,Qe)),Re(j,k+96,16843009*Ht(ze,Qe,Qe))}function Ha(j,k){var X,ve=4;for(X=0;4>X;++X)ve+=j[k+X-32]+j[k-1+32*X];for(ve>>=3,X=0;4>X;++X)i(j,k+32*X,ve,4)}function is(j,k){var X=j[k-1+0],ve=j[k-1+32],ze=j[k-1+64],Qe=j[k-1-32],Ke=j[k+0-32],Ze=j[k+1-32],at=j[k+2-32],mt=j[k+3-32];j[k+0+96]=Ht(ve,ze,j[k-1+96]),j[k+1+96]=j[k+0+64]=Ht(X,ve,ze),j[k+2+96]=j[k+1+64]=j[k+0+32]=Ht(Qe,X,ve),j[k+3+96]=j[k+2+64]=j[k+1+32]=j[k+0+0]=Ht(Ke,Qe,X),j[k+3+64]=j[k+2+32]=j[k+1+0]=Ht(Ze,Ke,Qe),j[k+3+32]=j[k+2+0]=Ht(at,Ze,Ke),j[k+3+0]=Ht(mt,at,Ze)}function hs(j,k){var X=j[k+1-32],ve=j[k+2-32],ze=j[k+3-32],Qe=j[k+4-32],Ke=j[k+5-32],Ze=j[k+6-32],at=j[k+7-32];j[k+0+0]=Ht(j[k+0-32],X,ve),j[k+1+0]=j[k+0+32]=Ht(X,ve,ze),j[k+2+0]=j[k+1+32]=j[k+0+64]=Ht(ve,ze,Qe),j[k+3+0]=j[k+2+32]=j[k+1+64]=j[k+0+96]=Ht(ze,Qe,Ke),j[k+3+32]=j[k+2+64]=j[k+1+96]=Ht(Qe,Ke,Ze),j[k+3+64]=j[k+2+96]=Ht(Ke,Ze,at),j[k+3+96]=Ht(Ze,at,at)}function rs(j,k){var X=j[k-1+0],ve=j[k-1+32],ze=j[k-1+64],Qe=j[k-1-32],Ke=j[k+0-32],Ze=j[k+1-32],at=j[k+2-32],mt=j[k+3-32];j[k+0+0]=j[k+1+64]=Qe+Ke+1>>1,j[k+1+0]=j[k+2+64]=Ke+Ze+1>>1,j[k+2+0]=j[k+3+64]=Ze+at+1>>1,j[k+3+0]=at+mt+1>>1,j[k+0+96]=Ht(ze,ve,X),j[k+0+64]=Ht(ve,X,Qe),j[k+0+32]=j[k+1+96]=Ht(X,Qe,Ke),j[k+1+32]=j[k+2+96]=Ht(Qe,Ke,Ze),j[k+2+32]=j[k+3+96]=Ht(Ke,Ze,at),j[k+3+32]=Ht(Ze,at,mt)}function oa(j,k){var X=j[k+0-32],ve=j[k+1-32],ze=j[k+2-32],Qe=j[k+3-32],Ke=j[k+4-32],Ze=j[k+5-32],at=j[k+6-32],mt=j[k+7-32];j[k+0+0]=X+ve+1>>1,j[k+1+0]=j[k+0+64]=ve+ze+1>>1,j[k+2+0]=j[k+1+64]=ze+Qe+1>>1,j[k+3+0]=j[k+2+64]=Qe+Ke+1>>1,j[k+0+32]=Ht(X,ve,ze),j[k+1+32]=j[k+0+96]=Ht(ve,ze,Qe),j[k+2+32]=j[k+1+96]=Ht(ze,Qe,Ke),j[k+3+32]=j[k+2+96]=Ht(Qe,Ke,Ze),j[k+3+64]=Ht(Ke,Ze,at),j[k+3+96]=Ht(Ze,at,mt)}function qa(j,k){var X=j[k-1+0],ve=j[k-1+32],ze=j[k-1+64],Qe=j[k-1+96];j[k+0+0]=X+ve+1>>1,j[k+2+0]=j[k+0+32]=ve+ze+1>>1,j[k+2+32]=j[k+0+64]=ze+Qe+1>>1,j[k+1+0]=Ht(X,ve,ze),j[k+3+0]=j[k+1+32]=Ht(ve,ze,Qe),j[k+3+32]=j[k+1+64]=Ht(ze,Qe,Qe),j[k+3+64]=j[k+2+64]=j[k+0+96]=j[k+1+96]=j[k+2+96]=j[k+3+96]=Qe}function bs(j,k){var X=j[k-1+0],ve=j[k-1+32],ze=j[k-1+64],Qe=j[k-1+96],Ke=j[k-1-32],Ze=j[k+0-32],at=j[k+1-32],mt=j[k+2-32];j[k+0+0]=j[k+2+32]=X+Ke+1>>1,j[k+0+32]=j[k+2+64]=ve+X+1>>1,j[k+0+64]=j[k+2+96]=ze+ve+1>>1,j[k+0+96]=Qe+ze+1>>1,j[k+3+0]=Ht(Ze,at,mt),j[k+2+0]=Ht(Ke,Ze,at),j[k+1+0]=j[k+3+32]=Ht(X,Ke,Ze),j[k+1+32]=j[k+3+64]=Ht(ve,X,Ke),j[k+1+64]=j[k+3+96]=Ht(ze,ve,X),j[k+1+96]=Ht(Qe,ze,ve)}function Wa(j,k){var X;for(X=0;8>X;++X)s(j,k+32*X,j,k-32,8)}function $s(j,k){var X;for(X=0;8>X;++X)i(j,k,j[k-1],8),k+=32}function jr(j,k,X){var ve;for(ve=0;8>ve;++ve)i(k,X+32*ve,j,8)}function Kr(j,k){var X,ve=8;for(X=0;8>X;++X)ve+=j[k+X-32]+j[k-1+32*X];jr(ve>>4,j,k)}function Xr(j,k){var X,ve=4;for(X=0;8>X;++X)ve+=j[k+X-32];jr(ve>>3,j,k)}function Rr(j,k){var X,ve=4;for(X=0;8>X;++X)ve+=j[k-1+32*X];jr(ve>>3,j,k)}function er(j,k){jr(128,j,k)}function Ir(j,k,X){var ve=j[k-X],ze=j[k+0],Qe=3*(ze-ve)+Hc[1020+j[k-2*X]-j[k+X]],Ke=Ju[112+(Qe+4>>3)];j[k-X]=Li[255+ve+Ju[112+(Qe+3>>3)]],j[k+0]=Li[255+ze-Ke]}function Qo(j,k,X,ve){var ze=j[k+0],Qe=j[k+X];return Ni[255+j[k-2*X]-j[k-X]]>ve||Ni[255+Qe-ze]>ve}function fo(j,k,X,ve){return 4*Ni[255+j[k-X]-j[k+0]]+Ni[255+j[k-2*X]-j[k+X]]<=ve}function Jo(j,k,X,ve,ze){var Qe=j[k-3*X],Ke=j[k-2*X],Ze=j[k-X],at=j[k+0],mt=j[k+X],Tt=j[k+2*X],ln=j[k+3*X];return 4*Ni[255+Ze-at]+Ni[255+Ke-mt]>ve?0:Ni[255+j[k-4*X]-Qe]<=ze&&Ni[255+Qe-Ke]<=ze&&Ni[255+Ke-Ze]<=ze&&Ni[255+ln-Tt]<=ze&&Ni[255+Tt-mt]<=ze&&Ni[255+mt-at]<=ze}function pr(j,k,X,ve){var ze=2*ve+1;for(ve=0;16>ve;++ve)fo(j,k+ve,X,ze)&&Ir(j,k+ve,X)}function Or(j,k,X,ve){var ze=2*ve+1;for(ve=0;16>ve;++ve)fo(j,k+ve*X,1,ze)&&Ir(j,k+ve*X,1)}function Js(j,k,X,ve){var ze;for(ze=3;0<ze;--ze)pr(j,k+=4*X,X,ve)}function Ko(j,k,X,ve){var ze;for(ze=3;0<ze;--ze)Or(j,k+=4,X,ve)}function to(j,k,X,ve,ze,Qe,Ke,Ze){for(Qe=2*Qe+1;0<ze--;){if(Jo(j,k,X,Qe,Ke))if(Qo(j,k,X,Ze))Ir(j,k,X);else{var at=j,mt=k,Tt=X,ln=at[mt-2*Tt],cn=at[mt-Tt],Kt=at[mt+0],Un=at[mt+Tt],Nn=at[mt+2*Tt],Mt=27*($n=Hc[1020+3*(Kt-cn)+Hc[1020+ln-Un]])+63>>7,Ut=18*$n+63>>7,$n=9*$n+63>>7;at[mt-3*Tt]=Li[255+at[mt-3*Tt]+$n],at[mt-2*Tt]=Li[255+ln+Ut],at[mt-Tt]=Li[255+cn+Mt],at[mt+0]=Li[255+Kt-Mt],at[mt+Tt]=Li[255+Un-Ut],at[mt+2*Tt]=Li[255+Nn-$n]}k+=ve}}function $i(j,k,X,ve,ze,Qe,Ke,Ze){for(Qe=2*Qe+1;0<ze--;){if(Jo(j,k,X,Qe,Ke))if(Qo(j,k,X,Ze))Ir(j,k,X);else{var at=j,mt=k,Tt=X,ln=at[mt-Tt],cn=at[mt+0],Kt=at[mt+Tt],Un=Ju[112+((Nn=3*(cn-ln))+4>>3)],Nn=Ju[112+(Nn+3>>3)],Mt=Un+1>>1;at[mt-2*Tt]=Li[255+at[mt-2*Tt]+Mt],at[mt-Tt]=Li[255+ln+Nn],at[mt+0]=Li[255+cn-Un],at[mt+Tt]=Li[255+Kt-Mt]}k+=ve}}function Bc(j,k,X,ve,ze,Qe){to(j,k,X,1,16,ve,ze,Qe)}function no(j,k,X,ve,ze,Qe){to(j,k,1,X,16,ve,ze,Qe)}function Fc(j,k,X,ve,ze,Qe){var Ke;for(Ke=3;0<Ke;--Ke)$i(j,k+=4*X,X,1,16,ve,ze,Qe)}function Xo(j,k,X,ve,ze,Qe){var Ke;for(Ke=3;0<Ke;--Ke)$i(j,k+=4,1,X,16,ve,ze,Qe)}function Yl(j,k,X,ve,ze,Qe,Ke,Ze){to(j,k,ze,1,8,Qe,Ke,Ze),to(X,ve,ze,1,8,Qe,Ke,Ze)}function Uc(j,k,X,ve,ze,Qe,Ke,Ze){to(j,k,1,ze,8,Qe,Ke,Ze),to(X,ve,1,ze,8,Qe,Ke,Ze)}function Gi(j,k,X,ve,ze,Qe,Ke,Ze){$i(j,k+4*ze,ze,1,8,Qe,Ke,Ze),$i(X,ve+4*ze,ze,1,8,Qe,Ke,Ze)}function zc(j,k,X,ve,ze,Qe,Ke,Ze){$i(j,k+4,1,ze,8,Qe,Ke,Ze),$i(X,ve+4,1,ze,8,Qe,Ke,Ze)}function Zo(){this.ba=new jt,this.ec=[],this.cc=[],this.Mc=[],this.Dc=this.Nc=this.dc=this.fc=0,this.Oa=new tn,this.memory=0,this.Ib="OutputFunc",this.Jb="OutputAlphaFunc",this.Nd="OutputRowFunc"}function qc(){this.data=[],this.offset=this.kd=this.ha=this.w=0,this.na=[],this.xa=this.gb=this.Ja=this.Sa=this.P=0}function ec(){this.nc=this.Ea=this.b=this.hc=0,this.K=[],this.w=0}function bc(){this.ua=0,this.Wa=new ee,this.vb=new ee,this.md=this.xc=this.wc=0,this.vc=[],this.Wb=0,this.Ya=new Z,this.yc=new D}function vl(){this.xb=this.a=0,this.l=new _n,this.ca=new jt,this.V=[],this.Ba=0,this.Ta=[],this.Ua=0,this.m=new $,this.Pb=0,this.wd=new $,this.Ma=this.$=this.C=this.i=this.c=this.xd=0,this.s=new bc,this.ab=0,this.gc=l(4,ec),this.Oc=0}function Oi(){this.Lc=this.Z=this.$a=this.i=this.c=0,this.l=new _n,this.ic=0,this.ca=[],this.tb=0,this.qd=null,this.rd=0}function tc(j,k,X,ve,ze,Qe,Ke){for(j=j==null?0:j[k+0],k=0;k<Ke;++k)ze[Qe+k]=j+X[ve+k]&255,j=ze[Qe+k]}function Vc(j,k,X,ve,ze,Qe,Ke){var Ze;if(j==null)tc(null,null,X,ve,ze,Qe,Ke);else for(Ze=0;Ze<Ke;++Ze)ze[Qe+Ze]=j[k+Ze]+X[ve+Ze]&255}function _o(j,k,X,ve,ze,Qe,Ke){if(j==null)tc(null,null,X,ve,ze,Qe,Ke);else{var Ze,at=j[k+0],mt=at,Tt=at;for(Ze=0;Ze<Ke;++Ze)mt=Tt+(at=j[k+Ze])-mt,Tt=X[ve+Ze]+(-256&mt?0>mt?0:255:mt)&255,mt=at,ze[Qe+Ze]=Tt}}function ko(j,k,X,ve){var ze=k.width,Qe=k.o;if(n(j!=null&&k!=null),0>X||0>=ve||X+ve>Qe)return null;if(!j.Cc){if(j.ga==null){var Ke;if(j.ga=new Oi,(Ke=j.ga==null)||(Ke=k.width*k.o,n(j.Gb.length==0),j.Gb=c(Ke),j.Uc=0,j.Gb==null?Ke=0:(j.mb=j.Gb,j.nb=j.Uc,j.rc=null,Ke=1),Ke=!Ke),!Ke){Ke=j.ga;var Ze=j.Fa,at=j.P,mt=j.qc,Tt=j.mb,ln=j.nb,cn=at+1,Kt=mt-1,Un=Ke.l;if(n(Ze!=null&&Tt!=null&&k!=null),Wc[0]=null,Wc[1]=tc,Wc[2]=Vc,Wc[3]=_o,Ke.ca=Tt,Ke.tb=ln,Ke.c=k.width,Ke.i=k.height,n(0<Ke.c&&0<Ke.i),1>=mt)k=0;else if(Ke.$a=Ze[at+0]>>0&3,Ke.Z=Ze[at+0]>>2&3,Ke.Lc=Ze[at+0]>>4&3,at=Ze[at+0]>>6&3,0>Ke.$a||1<Ke.$a||4<=Ke.Z||1<Ke.Lc||at)k=0;else if(Un.put=dt,Un.ac=ht,Un.bc=we,Un.ma=Ke,Un.width=k.width,Un.height=k.height,Un.Da=k.Da,Un.v=k.v,Un.va=k.va,Un.j=k.j,Un.o=k.o,Ke.$a)e:{n(Ke.$a==1),k=ke();t:for(;;){if(k==null){k=0;break e}if(n(Ke!=null),Ke.mc=k,k.c=Ke.c,k.i=Ke.i,k.l=Ke.l,k.l.ma=Ke,k.l.width=Ke.c,k.l.height=Ke.i,k.a=0,ae(k.m,Ze,cn,Kt),!Ct(Ke.c,Ke.i,1,k,null)||(k.ab==1&&k.gc[0].hc==3&&Gt(k.s)?(Ke.ic=1,Ze=k.c*k.i,k.Ta=null,k.Ua=0,k.V=c(Ze),k.Ba=0,k.V==null?(k.a=1,k=0):k=1):(Ke.ic=0,k=Et(k,Ke.c)),!k))break t;k=1;break e}Ke.mc=null,k=0}else k=Kt>=Ke.c*Ke.i;Ke=!k}if(Ke)return null;j.ga.Lc!=1?j.Ga=0:ve=Qe-X}n(j.ga!=null),n(X+ve<=Qe);e:{if(k=(Ze=j.ga).c,Qe=Ze.l.o,Ze.$a==0){if(cn=j.rc,Kt=j.Vc,Un=j.Fa,at=j.P+1+X*k,mt=j.mb,Tt=j.nb+X*k,n(at<=j.P+j.qc),Ze.Z!=0)for(n(Wc[Ze.Z]!=null),Ke=0;Ke<ve;++Ke)Wc[Ze.Z](cn,Kt,Un,at,mt,Tt,k),cn=mt,Kt=Tt,Tt+=k,at+=k;else for(Ke=0;Ke<ve;++Ke)s(mt,Tt,Un,at,k),cn=mt,Kt=Tt,Tt+=k,at+=k;j.rc=cn,j.Vc=Kt}else{if(n(Ze.mc!=null),k=X+ve,n((Ke=Ze.mc)!=null),n(k<=Ke.i),Ke.C>=k)k=1;else if(Ze.ic||an(),Ze.ic){Ze=Ke.V,cn=Ke.Ba,Kt=Ke.c;var Nn=Ke.i,Mt=(Un=1,at=Ke.$/Kt,mt=Ke.$%Kt,Tt=Ke.m,ln=Ke.s,Ke.$),Ut=Kt*Nn,$n=Kt*k,Yn=ln.wc,Tn=Mt<$n?Sn(ln,mt,at):null;n(Mt<=Ut),n(k<=Nn),n(Gt(ln));t:for(;;){for(;!Tt.h&&Mt<$n;){if(mt&Yn||(Tn=Sn(ln,mt,at)),n(Tn!=null),me(Tt),256>(Nn=gn(Tn.G[0],Tn.H[0],Tt)))Ze[cn+Mt]=Nn,++Mt,++mt>=Kt&&(mt=0,++at<=k&&!(at%16)&&Vt(Ke,at));else{if(!(280>Nn)){Un=0;break t}Nn=St(Nn-256,Tt);var Aa,fa=gn(Tn.G[4],Tn.H[4],Tt);if(me(Tt),!(Mt>=(fa=Qt(Kt,fa=St(fa,Tt)))&&Ut-Mt>=Nn)){Un=0;break t}for(Aa=0;Aa<Nn;++Aa)Ze[cn+Mt+Aa]=Ze[cn+Mt+Aa-fa];for(Mt+=Nn,mt+=Nn;mt>=Kt;)mt-=Kt,++at<=k&&!(at%16)&&Vt(Ke,at);Mt<$n&&mt&Yn&&(Tn=Sn(ln,mt,at))}n(Tt.h==P(Tt))}Vt(Ke,at>k?k:at);break t}!Un||Tt.h&&Mt<Ut?(Un=0,Ke.a=Tt.h?5:3):Ke.$=Mt,k=Un}else k=sn(Ke,Ke.V,Ke.Ba,Ke.c,Ke.i,k,Rt);if(!k){ve=0;break e}}X+ve>=Qe&&(j.Cc=1),ve=1}if(!ve)return null;if(j.Cc&&((ve=j.ga)!=null&&(ve.mc=null),j.ga=null,0<j.Ga))return alert("todo:WebPDequantizeLevels"),null}return j.nb+X*ze}function U(j,k,X,ve,ze,Qe){for(;0<ze--;){var Ke,Ze=j,at=k+(X?1:0),mt=j,Tt=k+(X?0:3);for(Ke=0;Ke<ve;++Ke){var ln=mt[Tt+4*Ke];ln!=255&&(ln*=32897,Ze[at+4*Ke+0]=Ze[at+4*Ke+0]*ln>>23,Ze[at+4*Ke+1]=Ze[at+4*Ke+1]*ln>>23,Ze[at+4*Ke+2]=Ze[at+4*Ke+2]*ln>>23)}k+=Qe}}function Ue(j,k,X,ve,ze){for(;0<ve--;){var Qe;for(Qe=0;Qe<X;++Qe){var Ke=j[k+2*Qe+0],Ze=15&(mt=j[k+2*Qe+1]),at=4369*Ze,mt=(240&mt|mt>>4)*at>>16;j[k+2*Qe+0]=(240&Ke|Ke>>4)*at>>16&240|(15&Ke|Ke<<4)*at>>16>>4&15,j[k+2*Qe+1]=240&mt|Ze}k+=ze}}function yt(j,k,X,ve,ze,Qe,Ke,Ze){var at,mt,Tt=255;for(mt=0;mt<ze;++mt){for(at=0;at<ve;++at){var ln=j[k+at];Qe[Ke+4*at]=ln,Tt&=ln}k+=X,Ke+=Ze}return Tt!=255}function kt(j,k,X,ve,ze){var Qe;for(Qe=0;Qe<ze;++Qe)X[ve+Qe]=j[k+Qe]>>8}function an(){sr=U,Ka=Ue,Ss=yt,Es=kt}function Cn(j,k,X){z[j]=function(ve,ze,Qe,Ke,Ze,at,mt,Tt,ln,cn,Kt,Un,Nn,Mt,Ut,$n,Yn){var Tn,Aa=Yn-1>>1,fa=Ze[at+0]|mt[Tt+0]<<16,Va=ln[cn+0]|Kt[Un+0]<<16;n(ve!=null);var ba=3*fa+Va+131074>>2;for(k(ve[ze+0],255&ba,ba>>16,Nn,Mt),Qe!=null&&(ba=3*Va+fa+131074>>2,k(Qe[Ke+0],255&ba,ba>>16,Ut,$n)),Tn=1;Tn<=Aa;++Tn){var Us=Ze[at+Tn]|mt[Tt+Tn]<<16,As=ln[cn+Tn]|Kt[Un+Tn]<<16,Ps=fa+Us+Va+As+524296,cs=Ps+2*(Us+Va)>>3;ba=cs+fa>>1,fa=(Ps=Ps+2*(fa+As)>>3)+Us>>1,k(ve[ze+2*Tn-1],255&ba,ba>>16,Nn,Mt+(2*Tn-1)*X),k(ve[ze+2*Tn-0],255&fa,fa>>16,Nn,Mt+(2*Tn-0)*X),Qe!=null&&(ba=Ps+Va>>1,fa=cs+As>>1,k(Qe[Ke+2*Tn-1],255&ba,ba>>16,Ut,$n+(2*Tn-1)*X),k(Qe[Ke+2*Tn+0],255&fa,fa>>16,Ut,$n+(2*Tn+0)*X)),fa=Us,Va=As}1&Yn||(ba=3*fa+Va+131074>>2,k(ve[ze+Yn-1],255&ba,ba>>16,Nn,Mt+(Yn-1)*X),Qe!=null&&(ba=3*Va+fa+131074>>2,k(Qe[Ke+Yn-1],255&ba,ba>>16,Ut,$n+(Yn-1)*X)))}}function Qn(){Ci[nm]=Jl,Ci[Bi]=Ld,Ci[am]=Mp,Ci[Eo]=cm,Ci[Ku]=wl,Ci[Md]=jc,Ci[bl]=Nl,Ci[Xu]=Ld,Ci[sm]=cm,Ci[$d]=wl,Ci[rm]=jc}function E(j){return j&-16384?0>j?0:255:j>>lm}function Q(j,k){return E((19077*j>>8)+(26149*k>>8)-14234)}function Ie(j,k,X){return E((19077*j>>8)-(6419*k>>8)-(13320*X>>8)+8708)}function Le(j,k){return E((19077*j>>8)+(33050*k>>8)-17685)}function He(j,k,X,ve,ze){ve[ze+0]=Q(j,X),ve[ze+1]=Ie(j,k,X),ve[ze+2]=Le(j,k)}function gt(j,k,X,ve,ze){ve[ze+0]=Le(j,k),ve[ze+1]=Ie(j,k,X),ve[ze+2]=Q(j,X)}function Dt(j,k,X,ve,ze){var Qe=Ie(j,k,X);k=Qe<<3&224|Le(j,k)>>3,ve[ze+0]=248&Q(j,X)|Qe>>5,ve[ze+1]=k}function Yt(j,k,X,ve,ze){var Qe=240&Le(j,k)|15;ve[ze+0]=240&Q(j,X)|Ie(j,k,X)>>4,ve[ze+1]=Qe}function vn(j,k,X,ve,ze){ve[ze+0]=255,He(j,k,X,ve,ze+1)}function zt(j,k,X,ve,ze){gt(j,k,X,ve,ze),ve[ze+3]=255}function Bt(j,k,X,ve,ze){He(j,k,X,ve,ze),ve[ze+3]=255}function En(j,k){return 0>j?0:j>k?k:j}function wn(j,k,X){z[j]=function(ve,ze,Qe,Ke,Ze,at,mt,Tt,ln){for(var cn=Tt+(-2&ln)*X;Tt!=cn;)k(ve[ze+0],Qe[Ke+0],Ze[at+0],mt,Tt),k(ve[ze+1],Qe[Ke+0],Ze[at+0],mt,Tt+X),ze+=2,++Ke,++at,Tt+=2*X;1&ln&&k(ve[ze+0],Qe[Ke+0],Ze[at+0],mt,Tt)}}function ma(j,k,X){return X==0?j==0?k==0?6:5:k==0?4:0:X}function ca(j,k,X,ve,ze){switch(j>>>30){case 3:Wn(k,X,ve,ze,0);break;case 2:Bn(k,X,ve,ze);break;case 1:Na(k,X,ve,ze)}}function Pa(j,k){var X,ve,ze=k.M,Qe=k.Nb,Ke=j.oc,Ze=j.pc+40,at=j.oc,mt=j.pc+584,Tt=j.oc,ln=j.pc+600;for(X=0;16>X;++X)Ke[Ze+32*X-1]=129;for(X=0;8>X;++X)at[mt+32*X-1]=129,Tt[ln+32*X-1]=129;for(0<ze?Ke[Ze-1-32]=at[mt-1-32]=Tt[ln-1-32]=129:(i(Ke,Ze-32-1,127,21),i(at,mt-32-1,127,9),i(Tt,ln-32-1,127,9)),ve=0;ve<j.za;++ve){var cn=k.ya[k.aa+ve];if(0<ve){for(X=-1;16>X;++X)s(Ke,Ze+32*X-4,Ke,Ze+32*X+12,4);for(X=-1;8>X;++X)s(at,mt+32*X-4,at,mt+32*X+4,4),s(Tt,ln+32*X-4,Tt,ln+32*X+4,4)}var Kt=j.Gd,Un=j.Hd+ve,Nn=cn.ad,Mt=cn.Hc;if(0<ze&&(s(Ke,Ze-32,Kt[Un].y,0,16),s(at,mt-32,Kt[Un].f,0,8),s(Tt,ln-32,Kt[Un].ea,0,8)),cn.Za){var Ut=Ke,$n=Ze-32+16;for(0<ze&&(ve>=j.za-1?i(Ut,$n,Kt[Un].y[15],4):s(Ut,$n,Kt[Un+1].y,0,4)),X=0;4>X;X++)Ut[$n+128+X]=Ut[$n+256+X]=Ut[$n+384+X]=Ut[$n+0+X];for(X=0;16>X;++X,Mt<<=2)Ut=Ke,$n=Ze+Gr[X],Lr[cn.Ob[X]](Ut,$n),ca(Mt,Nn,16*+X,Ut,$n)}else if(Ut=ma(ve,ze,cn.Ob[0]),Yi[Ut](Ke,Ze),Mt!=0)for(X=0;16>X;++X,Mt<<=2)ca(Mt,Nn,16*+X,Ke,Ze+Gr[X]);for(X=cn.Gc,Ut=ma(ve,ze,cn.Dd),nc[Ut](at,mt),nc[Ut](Tt,ln),Mt=Nn,Ut=at,$n=mt,255&(cn=X>>0)&&(170&cn?Fn(Mt,256,Ut,$n):ya(Mt,256,Ut,$n)),cn=Tt,Mt=ln,255&(X>>=8)&&(170&X?Fn(Nn,320,cn,Mt):ya(Nn,320,cn,Mt)),ze<j.Ub-1&&(s(Kt[Un].y,0,Ke,Ze+480,16),s(Kt[Un].f,0,at,mt+224,8),s(Kt[Un].ea,0,Tt,ln+224,8)),X=8*Qe*j.B,Kt=j.sa,Un=j.ta+16*ve+16*Qe*j.R,Nn=j.qa,cn=j.ra+8*ve+X,Mt=j.Ha,Ut=j.Ia+8*ve+X,X=0;16>X;++X)s(Kt,Un+X*j.R,Ke,Ze+32*X,16);for(X=0;8>X;++X)s(Nn,cn+X*j.B,at,mt+32*X,8),s(Mt,Ut+X*j.B,Tt,ln+32*X,8)}}function kn(j,k,X,ve,ze,Qe,Ke,Ze,at){var mt=[0],Tt=[0],ln=0,cn=at!=null?at.kd:0,Kt=at??new qc;if(j==null||12>X)return 7;Kt.data=j,Kt.w=k,Kt.ha=X,k=[k],X=[X],Kt.gb=[Kt.gb];e:{var Un=k,Nn=X,Mt=Kt.gb;if(n(j!=null),n(Nn!=null),n(Mt!=null),Mt[0]=0,12<=Nn[0]&&!a(j,Un[0],"RIFF")){if(a(j,Un[0]+8,"WEBP")){Mt=3;break e}var Ut=We(j,Un[0]+4);if(12>Ut||4294967286<Ut){Mt=3;break e}if(cn&&Ut>Nn[0]-8){Mt=7;break e}Mt[0]=Ut,Un[0]+=12,Nn[0]-=12}Mt=0}if(Mt!=0)return Mt;for(Ut=0<Kt.gb[0],X=X[0];;){e:{var $n=j;Nn=k,Mt=X;var Yn=mt,Tn=Tt,Aa=Un=[0];if((ba=ln=[ln])[0]=0,8>Mt[0])Mt=7;else{if(!a($n,Nn[0],"VP8X")){if(We($n,Nn[0]+4)!=10){Mt=3;break e}if(18>Mt[0]){Mt=7;break e}var fa=We($n,Nn[0]+8),Va=1+Be($n,Nn[0]+12);if(2147483648<=Va*($n=1+Be($n,Nn[0]+15))){Mt=3;break e}Aa!=null&&(Aa[0]=fa),Yn!=null&&(Yn[0]=Va),Tn!=null&&(Tn[0]=$n),Nn[0]+=18,Mt[0]-=18,ba[0]=1}Mt=0}}if(ln=ln[0],Un=Un[0],Mt!=0)return Mt;if(Nn=!!(2&Un),!Ut&&ln)return 3;if(Qe!=null&&(Qe[0]=!!(16&Un)),Ke!=null&&(Ke[0]=Nn),Ze!=null&&(Ze[0]=0),Ke=mt[0],Un=Tt[0],ln&&Nn&&at==null){Mt=0;break}if(4>X){Mt=7;break}if(Ut&&ln||!Ut&&!ln&&!a(j,k[0],"ALPH")){X=[X],Kt.na=[Kt.na],Kt.P=[Kt.P],Kt.Sa=[Kt.Sa];e:{fa=j,Mt=k,Ut=X;var ba=Kt.gb;Yn=Kt.na,Tn=Kt.P,Aa=Kt.Sa,Va=22,n(fa!=null),n(Ut!=null),$n=Mt[0];var Us=Ut[0];for(n(Yn!=null),n(Aa!=null),Yn[0]=null,Tn[0]=null,Aa[0]=0;;){if(Mt[0]=$n,Ut[0]=Us,8>Us){Mt=7;break e}var As=We(fa,$n+4);if(4294967286<As){Mt=3;break e}var Ps=8+As+1&-2;if(Va+=Ps,0<ba&&Va>ba){Mt=3;break e}if(!a(fa,$n,"VP8 ")||!a(fa,$n,"VP8L")){Mt=0;break e}if(Us[0]<Ps){Mt=7;break e}a(fa,$n,"ALPH")||(Yn[0]=fa,Tn[0]=$n+8,Aa[0]=As),$n+=Ps,Us-=Ps}}if(X=X[0],Kt.na=Kt.na[0],Kt.P=Kt.P[0],Kt.Sa=Kt.Sa[0],Mt!=0)break}X=[X],Kt.Ja=[Kt.Ja],Kt.xa=[Kt.xa];e:if(ba=j,Mt=k,Ut=X,Yn=Kt.gb[0],Tn=Kt.Ja,Aa=Kt.xa,fa=Mt[0],$n=!a(ba,fa,"VP8 "),Va=!a(ba,fa,"VP8L"),n(ba!=null),n(Ut!=null),n(Tn!=null),n(Aa!=null),8>Ut[0])Mt=7;else{if($n||Va){if(ba=We(ba,fa+4),12<=Yn&&ba>Yn-12){Mt=3;break e}if(cn&&ba>Ut[0]-8){Mt=7;break e}Tn[0]=ba,Mt[0]+=8,Ut[0]-=8,Aa[0]=Va}else Aa[0]=5<=Ut[0]&&ba[fa+0]==47&&!(ba[fa+4]>>5),Tn[0]=Ut[0];Mt=0}if(X=X[0],Kt.Ja=Kt.Ja[0],Kt.xa=Kt.xa[0],k=k[0],Mt!=0)break;if(4294967286<Kt.Ja)return 3;if(Ze==null||Nn||(Ze[0]=Kt.xa?2:1),Ke=[Ke],Un=[Un],Kt.xa){if(5>X){Mt=7;break}Ze=Ke,cn=Un,Nn=Qe,j==null||5>X?j=0:5<=X&&j[k+0]==47&&!(j[k+4]>>5)?(Ut=[0],ba=[0],Yn=[0],ae(Tn=new $,j,k,X),rt(Tn,Ut,ba,Yn)?(Ze!=null&&(Ze[0]=Ut[0]),cn!=null&&(cn[0]=ba[0]),Nn!=null&&(Nn[0]=Yn[0]),j=1):j=0):j=0}else{if(10>X){Mt=7;break}Ze=Un,j==null||10>X||!W(j,k+3,X-3)?j=0:(cn=j[k+0]|j[k+1]<<8|j[k+2]<<16,Nn=16383&(j[k+7]<<8|j[k+6]),j=16383&(j[k+9]<<8|j[k+8]),1&cn||3<(cn>>1&7)||!(cn>>4&1)||cn>>5>=Kt.Ja||!Nn||!j?j=0:(Ke&&(Ke[0]=Nn),Ze&&(Ze[0]=j),j=1))}if(!j||(Ke=Ke[0],Un=Un[0],ln&&(mt[0]!=Ke||Tt[0]!=Un)))return 3;at!=null&&(at[0]=Kt,at.offset=k-at.w,n(4294967286>k-at.w),n(at.offset==at.ha-X));break}return Mt==0||Mt==7&&ln&&at==null?(Qe!=null&&(Qe[0]|=Kt.na!=null&&0<Kt.na.length),ve!=null&&(ve[0]=Ke),ze!=null&&(ze[0]=Un),0):Mt}function Kn(j,k,X){var ve=k.width,ze=k.height,Qe=0,Ke=0,Ze=ve,at=ze;if(k.Da=j!=null&&0<j.Da,k.Da&&(Ze=j.cd,at=j.bd,Qe=j.v,Ke=j.j,11>X||(Qe&=-2,Ke&=-2),0>Qe||0>Ke||0>=Ze||0>=at||Qe+Ze>ve||Ke+at>ze))return 0;if(k.v=Qe,k.j=Ke,k.va=Qe+Ze,k.o=Ke+at,k.U=Ze,k.T=at,k.da=j!=null&&0<j.da,k.da){if(!qe(Ze,at,X=[j.ib],Qe=[j.hb]))return 0;k.ib=X[0],k.hb=Qe[0]}return k.ob=j!=null&&j.ob,k.Kb=j==null||!j.Sd,k.da&&(k.ob=k.ib<3*ve/4&&k.hb<3*ze/4,k.Kb=0),1}function Zn(j){if(j==null)return 2;if(11>j.S){var k=j.f.RGBA;k.fb+=(j.height-1)*k.A,k.A=-k.A}else k=j.f.kb,j=j.height,k.O+=(j-1)*k.fa,k.fa=-k.fa,k.N+=(j-1>>1)*k.Ab,k.Ab=-k.Ab,k.W+=(j-1>>1)*k.Db,k.Db=-k.Db,k.F!=null&&(k.J+=(j-1)*k.lb,k.lb=-k.lb);return 0}function da(j,k,X,ve){if(ve==null||0>=j||0>=k)return 2;if(X!=null){if(X.Da){var ze=X.cd,Qe=X.bd,Ke=-2&X.v,Ze=-2&X.j;if(0>Ke||0>Ze||0>=ze||0>=Qe||Ke+ze>j||Ze+Qe>k)return 2;j=ze,k=Qe}if(X.da){if(!qe(j,k,ze=[X.ib],Qe=[X.hb]))return 2;j=ze[0],k=Qe[0]}}ve.width=j,ve.height=k;e:{var at=ve.width,mt=ve.height;if(j=ve.S,0>=at||0>=mt||!(j>=nm&&13>j))j=2;else{if(0>=ve.Rd&&ve.sd==null){Ke=Qe=ze=k=0;var Tt=(Ze=at*um[j])*mt;if(11>j||(Qe=(mt+1)/2*(k=(at+1)/2),j==12&&(Ke=(ze=at)*mt)),(mt=c(Tt+2*Qe+Ke))==null){j=1;break e}ve.sd=mt,11>j?((at=ve.f.RGBA).eb=mt,at.fb=0,at.A=Ze,at.size=Tt):((at=ve.f.kb).y=mt,at.O=0,at.fa=Ze,at.Fd=Tt,at.f=mt,at.N=0+Tt,at.Ab=k,at.Cd=Qe,at.ea=mt,at.W=0+Tt+Qe,at.Db=k,at.Ed=Qe,j==12&&(at.F=mt,at.J=0+Tt+2*Qe),at.Tc=Ke,at.lb=ze)}if(k=1,ze=ve.S,Qe=ve.width,Ke=ve.height,ze>=nm&&13>ze)if(11>ze)j=ve.f.RGBA,k&=(Ze=Math.abs(j.A))*(Ke-1)+Qe<=j.size,k&=Ze>=Qe*um[ze],k&=j.eb!=null;else{j=ve.f.kb,Ze=(Qe+1)/2,Tt=(Ke+1)/2,at=Math.abs(j.fa),mt=Math.abs(j.Ab);var ln=Math.abs(j.Db),cn=Math.abs(j.lb),Kt=cn*(Ke-1)+Qe;k&=at*(Ke-1)+Qe<=j.Fd,k&=mt*(Tt-1)+Ze<=j.Cd,k=(k&=ln*(Tt-1)+Ze<=j.Ed)&at>=Qe&mt>=Ze&ln>=Ze,k&=j.y!=null,k&=j.f!=null,k&=j.ea!=null,ze==12&&(k&=cn>=Qe,k&=Kt<=j.Tc,k&=j.F!=null)}else k=0;j=k?0:2}}return j!=0||X!=null&&X.fd&&(j=Zn(ve)),j}var Ga=64,Da=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215],Ia=24,ls=32,Ua=8,va=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
vendor: 4,784 bytes, line 3890
38906,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];Se("Predictor0","PredictorAdd0"),z.Predictor0=function(){return 4278190080},z.Predictor1=function(j){return j},z.Predictor2=function(j,k,X){return k[X+0]},z.Predictor3=function(j,k,X){return k[X+1]},z.Predictor4=function(j,k,X){return k[X-1]},z.Predictor5=function(j,k,X){return ot(ot(j,k[X+1]),k[X+0])},z.Predictor6=function(j,k,X){return ot(j,k[X-1])},z.Predictor7=function(j,k,X){return ot(j,k[X+0])},z.Predictor8=function(j,k,X){return ot(k[X-1],k[X+0])},z.Predictor9=function(j,k,X){return ot(k[X+0],k[X+1])},z.Predictor10=function(j,k,X){return ot(ot(j,k[X-1]),ot(k[X+0],k[X+1]))},z.Predictor11=function(j,k,X){var ve=k[X+0];return 0>=Ce(ve>>24&255,j>>24&255,(k=k[X-1])>>24&255)+Ce(ve>>16&255,j>>16&255,k>>16&255)+Ce(ve>>8&255,j>>8&255,k>>8&255)+Ce(255&ve,255&j,255&k)?ve:j},z.Predictor12=function(j,k,X){var ve=k[X+0];return(wt((j>>24&255)+(ve>>24&255)-((k=k[X-1])>>24&255))<<24|wt((j>>16&255)+(ve>>16&255)-(k>>16&255))<<16|wt((j>>8&255)+(ve>>8&255)-(k>>8&255))<<8|wt((255&j)+(255&ve)-(255&k)))>>>0},z.Predictor13=function(j,k,X){var ve=k[X-1];return(ct((j=ot(j,k[X+0]))>>24&255,ve>>24&255)<<24|ct(j>>16&255,ve>>16&255)<<16|ct(j>>8&255,ve>>8&255)<<8|ct(j>>0&255,ve>>0&255))>>>0};var _a=z.PredictorAdd0;z.PredictorAdd1=De,Se("Predictor2","PredictorAdd2"),Se("Predictor3","PredictorAdd3"),Se("Predictor4","PredictorAdd4"),Se("Predictor5","PredictorAdd5"),Se("Predictor6","PredictorAdd6"),Se("Predictor7","PredictorAdd7"),Se("Predictor8","PredictorAdd8"),Se("Predictor9","PredictorAdd9"),Se("Predictor10","PredictorAdd10"),Se("Predictor11","PredictorAdd11"),Se("Predictor12","PredictorAdd12"),Se("Predictor13","PredictorAdd13");var Vs=z.PredictorAdd2;Je("ColorIndexInverseTransform","MapARGB","32b",(function(j){return j>>8&255}),(function(j){return j})),Je("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",(function(j){return j}),(function(j){return j>>8&255}));var Hn,Fa=z.ColorIndexInverseTransform,zs=z.MapARGB,Bs=z.VP8LColorIndexInverseTransformAlpha,S=z.MapAlpha,ye=z.VP8LPredictorsAdd=[];ye.length=16,(z.VP8LPredictors=[]).length=16,(z.VP8LPredictorsAdd_C=[]).length=16,(z.VP8LPredictors_C=[]).length=16;var Fe,lt,Ot,Ft,rn,Rn,ea,Wn,Bn,Fn,Na,ya,Ba,Ya,Os,ys,_r,tr,wr,Ns,Wr,nr,Fs,Hs,sr,Ka,Ss,Es,rr=c(511),ao=c(2041),xc=c(225),Do=c(767),go=0,Hc=ao,Ju=xc,Li=Do,Ni=rr,nm=0,Bi=1,am=2,Eo=3,Ku=4,Md=5,bl=6,Xu=7,sm=8,$d=9,rm=10,Po=[2,3,7],Od=[3,3,11],Ql=[280,256,256,256,40],im=[0,1,1,1,0],Zu=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],Ro=[24,7,23,25,40,6,39,41,22,26,38,42,56,5,55,57,21,27,54,58,37,43,72,4,71,73,20,28,53,59,70,74,36,44,88,69,75,52,60,3,87,89,19,29,86,90,35,45,68,76,85,91,51,61,104,2,103,105,18,30,102,106,34,46,84,92,67,77,101,107,50,62,120,1,119,121,83,93,17,31,100,108,66,78,118,122,33,47,117,123,49,63,99,109,82,94,0,116,124,65,79,16,32,98,110,48,115,125,81,95,64,114,126,97,111,80,113,127,96,112],To=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],xl=8,Mo=[4,5,6,7,8,9,10,10,11,12,13,14,15,16,17,17,18,19,20,20,21,21,22,22,23,23,24,25,25,26,27,28,29,30,31,32,33,34,35,36,37,37,38,39,40,41,42,43,44,45,46,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91,93,95,96,98,100,101,102,104,106,108,110,112,114,116,118,122,124,126,128,130,132,134,136,138,140,143,145,148,151,154,157],$o=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,119,122,125,128,131,134,137,140,143,146,149,152,155,158,161,164,167,170,173,177,181,185,189,193,197,201,205,209,213,217,221,225,229,234,239,245,249,254,259,264,269,274,279,284],yo=null,Hg=[[173,148,140,0],[176,155,140,135,0],[180,157,141,134,130,0],[254,254,243,230,196,177,153,140,133,130,129,0]],Rp=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],om=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],Wg=[[[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]],[[253,136,254,255,228,219,128,128,128,128,128],[189,129,242,255,227,213,255,219,128,128,128],[106,126,227,252,214,209,255,255,128,128,128]],[[1,98,248,255,236,226,255,255,128,128,128],[181,133,238,254,221,234,255,154,128,128,128],[78,134,202,247,198,180,255,219,128,128,128]],[[1,185,249,25
38905,243,255,128,128,128,128,128],[184,150,247,255,236,224,128,128,128,128,128],[77,110,216,255,236,230,128,128,128,128,128]],[[1,101,251,255,241,255,128,128,128,128,128],[170,139,241,252,236,209,255,255,128,128,128],[37,116,196,243,228,255,255,255,128,128,128]],[[1,204,254,255,245,255,128,128,128,128,128],[207,160,250,255,238,128,128,128,128,128,128],[102,103,231,255,211,171,128,128,128,128,128]],[[1,152,252,255,240,255,128,128,128,128,128],[177,135,243,255,234,225,128,128,128,128,128],[80,129,211,255,194,224,128,128,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[246,1,255,128,128,128,128,128,128,128,128],[255,128,128,128,128,128,128,128,128,128,128]]],[[[198,35,237,223,193,187,162,160,145,155,62],[131,45,198,221,172,176,220,157,252,221,1],[68,47,146,208,149,167,221,162,255,223,128]],[[1,149,241,255,221,224,255,255,128,128,128],[184,141,234,253,222,220,255,199,128,128,128],[81,99,181,242,176,190,249,202,255,255,128]],[[1,129,232,253,214,197,242,196,255,255,128],[99,121,210,250,201,198,255,202,128,128,128],[23,91,163,242,170,187,247,210,255,255,128]],[[1,200,246,255,234,255,128,128,128,128,128],[109,178,241,255,231,245,255,255,128,128,128],[44,130,201,253,205,192,255,255,128,128,128]],[[1,132,239,251,219,209,255,165,128,128,128],[94,136,225,251,218,190,255,255,128,128,128],[22,100,174,245,186,161,255,199,128,128,128]],[[1,182,249,255,232,235,128,128,128,128,128],[124,143,241,255,227,234,128,128,128,128,128],[35,77,181,251,193,211,255,205,128,128,128]],[[1,157,247,255,236,231,255,255,128,128,128],[121,141,235,255,225,227,255,255,128,128,128],[45,99,188,251,195,217,255,224,128,128,128]],[[1,1,251,255,213,255,128,128,128,128,128],[203,1,248,255,255,128,128,128,128,128,128],[137,1,177,255,224,255,128,128,128,128,128]]],[[[253,9,248,251,207,208,255,192,128,128,128],[175,13,224,243,193,185,249,198,255,255,128],[73,17,171,221,161,179,236,167,255,234,128]],[[1,95,247,253,212,183,255,255,128,128,128],[239,90,244,250,211,209,255,255,128,128,128],[155,77,195,248,188,195,255,255,128,128,128]],[[1,24,239,251,218,219,255,205,128,128,128],[201,51,219,255,196,186,128,128,128,128,128],[69,46,190,239,201,218,255,228,128,128,128]],[[1,191,251,255,255,128,128,128,128,128,128],[223,165,249,255,213,255,128,128,128,128,128],[141,124,248,255,255,128,128,128,128,128,128]],[[1,16,248,255,255,128,128,128,128,128,128],[190,36,230,255,236,255,128,128,128,128,128],[149,1,255,128,128,128,128,128,128,128,128]],[[1,226,255,128,128,128,128,128,128,128,128],[247,192,255,128,128,128,128,128,128,128,128],[240,128,255,128,128,128,128,128,128,128,128]],[[1,134,252,255,255,128,128,128,128,128,128],[213,62,250,255,255,128,128,128,128,128,128],[55,93,255,128,128,128,128,128,128,128,128]],[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]]],[[[202,24,213,235,186,191,220,160,240,175,255],[126,38,182,232,169,184,228,174,255,187,128],[61,46,138,219,151,178,240,170,255,216,128]],[[1,112,230,250,199,191,247,159,255,255,128],[166,109,228,252,211,215,255,174,128,128,128],[39,77,162,232,172,180,245,178,255,255,128]],[[1,52,220,246,198,199,249,220,255,255,128],[124,74,191,243,183,193,250,221,255,255,128],[24,71,130,219,154,170,243,182,255,255,128]],[[1,182,225,249,219,240,255,224,128,128,128],[149,150,226,252,216,205,255,171,128,128,128],[28,108,170,242,183,194,254,223,255,255,128]],[[1,81,230,252,204,203,255,192,128,128,128],[123,102,209,247,188,196,255,233,128,128,128],[20,95,153,243,164,173,255,203,128,128,128]],[[1,222,248,255,216,213,128,128,128,128,128],[168,175,246,252,235,205,255,255,128,128,128],[47,116,215,255,211,212,255,255,128,128,128]],[[1,121,236,253,212,214,255,255,128,128,128],[141,84,213,252,201,202,255,219,128,128,128],[42,80,160,240,162,185,255,205,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[244,1,255,128,128,128,128,128,128,128,128],[238,1,255,128,128,128,128,128,128,128,128]]]],Si=[[[231,120,48,89,115,113,120,152,112],[152,179,64,126,170,118,46,70,95],[175,69,143,80,85,82,72,155,103],[56,58,10,171,218,189,17,13,152],[114,26,17,163,44,195,21,10,173],[121,24,80,195,26,62,44,64,85],[144,71,10,38,171,213,144,34,26],[170,46,55,19,136,160,33,206,71],[63,20,8,114,114,208,12,9,226],[81,40,11,96,182,84,29,16,36]],[[134,183,89,137,98,101,106,165,148],[72,187,100,130,157,111,32,75,80],[66,102,167,99,74,62,40,234,128],[41,53,9,178,241,141,26,8,107],[74,43,26,146,73,166,49,23,157],[65,38,105,160,51,52,31,115,128],[104,79,12,27,217,255,87,17,7],[87,68,71,44,114,51,15,186,23],[47,41,14,110,182,183,21,17,194],[66,45,25,102,197,189,23,18,22]],[[88,88,147,150,42,46,45,196,205],[43,97,183,117,85,38,35,179,61],[39,53,200,87,26,21,43,232,171],[56,34,51,104,114,102,29,93,77],[39,28,85,171,58,165,90,98,64],[34,22,116,206,23,34,43,166,73],[107,54,32,26,51,1,81,43,31],[68,25,106,22,64,171,36,225,114],[34,19,21,102,132,188,16,76,124],[62,18,78,95,85,57,50,48,51]],[[193,101,35,159,215,111,89,46,111],[60,148,31,172,219,228,21,18,111],[112,113,77,85,179,255,38,120,114],[40,42,1,196,245,209,10,25,109],[88,43,29,140,166,213,37,43,154],[61,63,30,155,67,45,68,1,209],[100,80,8,43,154,1,51,26,71],[142,78,78,16,255,128,34,197,171],[41,40,5,102,211,183,4,1,221],[51,50,17,168,209,192,23,25,82]],[[138,31,36,171,27,166,38,44,229],[67,87,58,169,82,115,26,59,179],[63,59,90,180,59,166,93,73,154],[40,40,21,116,143,209,34,39,175],[47,15,16,183,34,223,49,45,183],[46,17,33,183,6,98,15,32,183],[57,46,22,24,128,1,54,17,37],[65,32,73,115,28,128,23,128,205],[40,3,9,115,51,192,18,6,223],[87,37,9,115,59,77,64,21,47]],[[104,55,44,218,9,54,53,130,226],[64,90,70,205,40,41,23,26,57],[54,57,112,184,5,41,38,166,213],[30,34,26,133,152,116,10,32,134],[39,19,53,221,26,114,32,73,255],[31,9,65,234,2,15,1,118,73],[75,32,12,51,192,255,160,43,51],[88,31,35,67,102,85,55,186,85],[56,21,23,111,59,205,45,37,192],[55,38,70,124,73,102,1,34,98]],[[125,98,42,88,104,85,117,175,82],[95,84,53,89,128,100,113,101,45],[75,79,123,47,51,128,81,171,1],[57,17,5,71,102,57,53,41,49],[38,33,13,121,57,73,26,1,85],[41,10,67,138,77,110,90,47,114],[115,21,2,10,102,255,166,23,6],[101,29,16,10,85,128,101,196,26],[57,18,10,102,102,213,34,20,43],[117,20,15,36,163,128,68,1,26]],[[102,61,71,37,34,53,31,243,192],[69,60,71,38,73,119,28,222,37],[68,45,128,34,1,47,11,245,171],[62,17,19,70,146,85,55,62,70],[37,43,37,154,100,163,85,160,1],[63,9,92,136,28,64,32,201,85],[75,15,9,9,64,255,184,119,16],[86,6,28,5,64,25
38905,25,248,1],[56,8,17,132,137,255,55,116,128],[58,15,20,82,135,57,26,121,40]],[[164,50,31,137,154,133,25,35,218],[51,103,44,131,131,123,31,6,158],[86,40,64,135,148,224,45,183,128],[22,26,17,131,240,154,14,1,209],[45,16,21,91,64,222,7,1,197],[56,21,39,155,60,138,23,102,213],[83,12,13,54,192,255,68,47,28],[85,26,85,85,128,128,32,146,171],[18,11,7,63,144,171,4,4,246],[35,27,10,146,174,171,12,26,128]],[[190,80,35,99,180,80,126,54,45],[85,126,47,87,176,51,41,20,32],[101,75,128,139,118,146,116,128,85],[56,41,15,176,236,85,37,9,62],[71,30,17,119,118,255,17,18,138],[101,38,60,138,55,70,43,26,142],[146,36,19,30,171,255,97,27,20],[138,45,61,62,219,1,81,188,64],[32,41,20,117,151,142,20,21,163],[112,19,12,61,195,128,48,4,24]]],Nr=[[[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[176,246,255,255,255,255,255,255,255,255,255],[223,241,252,255,255,255,255,255,255,255,255],[249,253,253,255,255,255,255,255,255,255,255]],[[255,244,252,255,255,255,255,255,255,255,255],[234,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255]],[[255,246,254,255,255,255,255,255,255,255,255],[239,253,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[251,255,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[251,254,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,254,253,255,254,255,255,255,255,255,255],[250,255,254,255,254,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[217,255,255,255,255,255,255,255,255,255,255],[225,252,241,253,255,255,254,255,255,255,255],[234,250,241,250,253,255,253,254,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[223,254,254,255,255,255,255,255,255,255,255],[238,253,254,254,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[249,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,255,255,255,255,255,255,255,255,255],[247,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[252,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[186,251,250,255,255,255,255,255,255,255,255],[234,251,244,254,255,255,255,255,255,255,255],[251,251,243,253,254,255,254,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[236,253,254,255,255,255,255,255,255,255,255],[251,253,253,254,254,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[254,254,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[254,254,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[248,255,255,255,255,255,255,255,255,255,255],[250,254,252,254,255,255,255,255,255,255,255],[248,254,249,253,255,255,255,255,255,255,255]],[[255,253,253,255,255,255,255,255,255,255,255],[246,253,253,255,255,255,255,255,255,255,255],[252,254,251,254,254,255,255,255,255,255,255]],[[255,254,252,25
vendor: 4,397 bytes, line 3890
38905,255,255,255,255,255,255,255],[248,254,253,255,255,255,255,255,255,255,255],[253,255,254,254,255,255,255,255,255,255,255]],[[255,251,254,255,255,255,255,255,255,255,255],[245,251,254,255,255,255,255,255,255,255,255],[253,253,254,255,255,255,255,255,255,255,255]],[[255,251,253,255,255,255,255,255,255,255,255],[252,253,254,255,255,255,255,255,255,255,255],[255,254,255,255,255,255,255,255,255,255,255]],[[255,252,255,255,255,255,255,255,255,255,255],[249,255,254,255,255,255,255,255,255,255,255],[255,255,254,255,255,255,255,255,255,255,255]],[[255,255,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]]],Cs=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Yi=[],Lr=[],nc=[],jl=1,Tp=2,Wc=[],Ci=[];Cn("UpsampleRgbLinePair",He,3),Cn("UpsampleBgrLinePair",gt,3),Cn("UpsampleRgbaLinePair",Bt,4),Cn("UpsampleBgraLinePair",zt,4),Cn("UpsampleArgbLinePair",vn,4),Cn("UpsampleRgba4444LinePair",Yt,2),Cn("UpsampleRgb565LinePair",Dt,2);var Jl=z.UpsampleRgbLinePair,Mp=z.UpsampleBgrLinePair,Ld=z.UpsampleRgbaLinePair,cm=z.UpsampleBgraLinePair,wl=z.UpsampleArgbLinePair,jc=z.UpsampleRgba4444LinePair,Nl=z.UpsampleRgb565LinePair,Oo=16,Bd=1<<Oo-1,Kl=-227,Sl=482,lm=6,Cl=0,Ai=c(256),dm=c(256),Gg=c(256),gx=c(256),yx=c(Sl-Kl),vx=c(Sl-Kl);wn("YuvToRgbRow",He,3),wn("YuvToBgrRow",gt,3),wn("YuvToRgbaRow",Bt,4),wn("YuvToBgraRow",zt,4),wn("YuvToArgbRow",vn,4),wn("YuvToRgba4444Row",Yt,2),wn("YuvToRgb565Row",Dt,2);var Gr=[0,4,8,12,128,132,136,140,256,260,264,268,384,388,392,396],Fd=[0,2,8],eh=[8,7,6,4,4,2,2,2,1,1,1,1],th=1;this.WebPDecodeRGBA=function(j,k,X,ve,ze){var Qe=Bi,Ke=new Zo,Ze=new jt;Ke.ba=Ze,Ze.S=Qe,Ze.width=[Ze.width],Ze.height=[Ze.height];var at=Ze.width,mt=Ze.height,Tt=new bt;if(Tt==null||j==null)var ln=2;else n(Tt!=null),ln=kn(j,k,X,Tt.width,Tt.height,Tt.Pd,Tt.Qd,Tt.format,null);if(ln!=0?at=0:(at!=null&&(at[0]=Tt.width[0]),mt!=null&&(mt[0]=Tt.height[0]),at=1),at){Ze.width=Ze.width[0],Ze.height=Ze.height[0],ve!=null&&(ve[0]=Ze.width),ze!=null&&(ze[0]=Ze.height);e:{if(ve=new _n,(ze=new qc).data=j,ze.w=k,ze.ha=X,ze.kd=1,k=[0],n(ze!=null),((j=kn(ze.data,ze.w,ze.ha,null,null,null,k,null,ze))==0||j==7)&&k[0]&&(j=4),(k=j)==0){if(n(Ke!=null),ve.data=ze.data,ve.w=ze.w+ze.offset,ve.ha=ze.ha-ze.offset,ve.put=dt,ve.ac=ht,ve.bc=we,ve.ma=Ke,ze.xa){if((j=ke())==null){Ke=1;break e}if((function(cn,Kt){var Un=[0],Nn=[0],Mt=[0];t:for(;;){if(cn==null)return 0;if(Kt==null)return cn.a=2,0;if(cn.l=Kt,cn.a=0,ae(cn.m,Kt.data,Kt.w,Kt.ha),!rt(cn.m,Un,Nn,Mt)){cn.a=3;break t}if(cn.xb=Tp,Kt.width=Un[0],Kt.height=Nn[0],!Ct(Un[0],Nn[0],1,cn,null))break t;return 1}return n(cn.a!=0),0})(j,ve)){if(ve=(k=da(ve.width,ve.height,Ke.Oa,Ke.ba))==0){t:{ve=j;n:for(;;){if(ve==null){ve=0;break t}if(n(ve.s.yc!=null),n(ve.s.Ya!=null),n(0<ve.s.Wb),n((X=ve.l)!=null),n((ze=X.ma)!=null),ve.xb!=0){if(ve.ca=ze.ba,ve.tb=ze.tb,n(ve.ca!=null),!Kn(ze.Oa,X,Eo)){ve.a=2;break n}if(!Et(ve,X.width)||X.da)break n;if((X.da||st(ve.ca.S))&&an(),11>ve.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),ve.ca.f.kb.F!=null&&an()),ve.Pb&&0<ve.s.ua&&ve.s.vb.X==null&&!it(ve.s.vb,ve.s.Wa.Xa)){ve.a=1;break n}ve.xb=0}if(!sn(ve,ve.V,ve.Ba,ve.c,ve.i,X.o,Wt))break n;ze.Dc=ve.Ma,ve=1;break t}n(ve.a!=0),ve=0}ve=!ve}ve&&(k=j.a)}else k=j.a}else{if((j=new ha)==null){Ke=1;break e}if(j.Fa=ze.na,j.P=ze.P,j.qc=ze.Sa,ft(j,ve)){if((k=da(ve.width,ve.height,Ke.Oa,Ke.ba))==0){if(j.Aa=0,X=Ke.Oa,n((ze=j)!=null),X!=null){if(0<(at=0>(at=X.Md)?0:100<at?255:255*at/100)){for(mt=Tt=0;4>mt;++mt)12>(ln=ze.pb[mt]).lc&&(ln.ia=at*eh[0>ln.lc?0:ln.lc]>>3),Tt|=ln.ia;Tt&&(alert("todo:VP8InitRandom"),ze.ia=1)}ze.Ga=X.Id,100<ze.Ga?ze.Ga=100:0>ze.Ga&&(ze.Ga=0)}Ae(j,ve)||(k=j.a)}}else k=j.a}k==0&&Ke.Oa!=null&&Ke.Oa.fd&&(k=Zn(Ke.ba))}Ke=k}Qe=Ke!=0?null:11>Qe?Ze.f.RGBA.eb:Ze.f.kb.y}else Qe=null;return Qe};var um=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function u(z,H){for(var K="",L=0;L<4;L++)K+=String.fromCharCode(z[H++]);return K}function f(z,H){return(z[H+0]<<0|z[H+1]<<8|z[H+2]<<16)>>>0}function g(z,H){return(z[H+0]<<0|z[H+1]<<8|z[H+2]<<16|z[H+3]<<24)>>>0}new d;var p=[0],y=[0],b=[],N=new d,w=t,C=(function(z,H){var K={},L=0,D=!1,M=0,Z=0;if(K.frames=[],!(function(F,P,ue,me){for(var ge=0;ge<me;ge++)if(F[P+ge]!=ue.charCodeAt(ge))return!0;return!1})(z,H,"RIFF",4)){var fe,q;
vendor: 6,720 bytes, line 3890
3890for(g(z,H+=4),H+=8;H<z.length;){var ne=u(z,H),ae=g(z,H+=4);H+=4;var Y=ae+(1&ae);switch(ne){case"VP8 ":case"VP8L":K.frames[L]===void 0&&(K.frames[L]={}),($=K.frames[L]).src_off=D?Z:H-8,$.src_size=M+ae+8,L++,D&&(D=!1,M=0,Z=0);break;case"VP8X":($=K.header={}).feature_flags=z[H];var je=H+4;$.canvas_width=1+f(z,je),je+=3,$.canvas_height=1+f(z,je),je+=3;break;case"ALPH":D=!0,M=Y+8,Z=H-8;break;case"ANIM":($=K.header).bgcolor=g(z,H),je=H+4,$.loop_count=(fe=z)[(q=je)+0]<<0|fe[q+1]<<8,je+=2;break;case"ANMF":var V,$;($=K.frames[L]={}).offset_x=2*f(z,H),H+=3,$.offset_y=2*f(z,H),H+=3,$.width=1+f(z,H),H+=3,$.height=1+f(z,H),H+=3,$.duration=f(z,H),H+=3,V=z[H++],$.dispose=1&V,$.blend=V>>1&1}ne!="ANMF"&&(H+=Y)}return K}})(w,0);C.response=w,C.rgbaoutput=!0,C.dataurl=!1;var R=C.header?C.header:null,I=C.frames?C.frames:null;if(R){R.loop_counter=R.loop_count,p=[R.canvas_height],y=[R.canvas_width];for(var _=0;_<I.length&&I[_].blend!=0;_++);}var J=I[0],T=N.WebPDecodeRGBA(w,J.src_off,J.src_size,y,p);J.rgba=T,J.imgwidth=y[0],J.imgheight=p[0];for(var G=0;G<y[0]*p[0]*4;G++)b[G]=T[G];return this.width=y,this.height=p,this.data=b,this}(function(t){var n=function(){return typeof F1=="function"},a=function(p,y,b,N){var w=4,C=l;switch(N){case t.image_compression.FAST:w=1,C=c;break;case t.image_compression.MEDIUM:w=6,C=m;break;case t.image_compression.SLOW:w=9,C=d}p=s(p,y,b,C);var R=F1(p,{level:w});return t.__addimage__.arrayBufferToBinaryString(R)},s=function(p,y,b,N){for(var w,C,R,I=p.length/y,_=new Uint8Array(p.length+I),J=f(),T=0;T<I;T+=1){if(R=T*y,w=p.subarray(R,R+y),N)_.set(N(w,b,C),R+T);else{for(var G,z=J.length,H=[];G<z;G+=1)H[G]=J[G](w,b,C);var K=g(H.concat());_.set(H[K],R+T)}C=w}return _},i=function(p){var y=Array.apply([],p);return y.unshift(0),y},c=function(p,y){var b,N=[],w=p.length;N[0]=1;for(var C=0;C<w;C+=1)b=p[C-y]||0,N[C+1]=p[C]-b+256&255;return N},l=function(p,y,b){var N,w=[],C=p.length;w[0]=2;for(var R=0;R<C;R+=1)N=b&&b[R]||0,w[R+1]=p[R]-N+256&255;return w},m=function(p,y,b){var N,w,C=[],R=p.length;C[0]=3;for(var I=0;I<R;I+=1)N=p[I-y]||0,w=b&&b[I]||0,C[I+1]=p[I]+256-(N+w>>>1)&255;return C},d=function(p,y,b){var N,w,C,R,I=[],_=p.length;I[0]=4;for(var J=0;J<_;J+=1)N=p[J-y]||0,w=b&&b[J]||0,C=b&&b[J-y]||0,R=u(N,w,C),I[J+1]=p[J]-R+256&255;return I},u=function(p,y,b){if(p===y&&y===b)return p;var N=Math.abs(y-b),w=Math.abs(p-b),C=Math.abs(p+y-b-b);return N<=w&&N<=C?p:w<=C?y:b},f=function(){return[i,c,l,m,d]},g=function(p){var y=p.map((function(b){return b.reduce((function(N,w){return N+Math.abs(w)}),0)}));return y.indexOf(Math.min.apply(null,y))};t.processPNG=function(p,y,b,N){var w,C,R,I,_,J,T,G,z,H,K,L,D,M,Z,fe=this.decode.FLATE_DECODE,q="";if(this.__addimage__.isArrayBuffer(p)&&(p=new Uint8Array(p)),this.__addimage__.isArrayBufferView(p)){if(p=(R=new VF(p)).imgData,C=R.bits,w=R.colorSpace,_=R.colors,[4,6].indexOf(R.colorType)!==-1){if(R.bits===8){z=(G=R.pixelBitlength==32?new Uint32Array(R.decodePixels().buffer):R.pixelBitlength==16?new Uint16Array(R.decodePixels().buffer):new Uint8Array(R.decodePixels().buffer)).length,K=new Uint8Array(z*R.colors),H=new Uint8Array(z);var ne,ae=R.pixelBitlength-R.bits;for(M=0,Z=0;M<z;M++){for(D=G[M],ne=0;ne<ae;)K[Z++]=D>>>ne&255,ne+=R.bits;H[M]=D>>>ne&255}}if(R.bits===16){z=(G=new Uint32Array(R.decodePixels().buffer)).length,K=new Uint8Array(z*(32/R.pixelBitlength)*R.colors),H=new Uint8Array(z*(32/R.pixelBitlength)),L=R.colors>1,M=0,Z=0;for(var Y=0;M<z;)D=G[M++],K[Z++]=D>>>0&255,L&&(K[Z++]=D>>>16&255,D=G[M++],K[Z++]=D>>>0&255),H[Y++]=D>>>16&255;C=8}N!==t.image_compression.NONE&&n()?(p=a(K,R.width*R.colors,R.colors,N),T=a(H,R.width,1,N)):(p=K,T=H,fe=void 0)}if(R.colorType===3&&(w=this.color_spaces.INDEXED,J=R.palette,R.transparency.indexed)){var je=R.transparency.indexed,V=0;for(M=0,z=je.length;M<z;++M)V+=je[M];if((V/=255)===z-1&&je.indexOf(0)!==-1)I=[je.indexOf(0)];else if(V!==z){for(G=R.decodePixels(),H=new Uint8Array(G.length),M=0,z=G.length;M<z;M++)H[M]=je[G[M]];T=a(H,R.width,1)}}var $=(function(F){var P;switch(F){case t.image_compression.FAST:P=11;break;case t.image_compression.MEDIUM:P=13;break;case t.image_compression.SLOW:P=14;break;default:P=12}return P})(N);return fe===this.decode.FLATE_DECODE&&(q="/Predictor "+$+" "),q+="/Colors "+_+" /BitsPerComponent "+C+" /Columns "+R.width,(this.__addimage__.isArrayBuffer(p)||this.__addimage__.isArrayBufferView(p))&&(p=this.__addimage__.arrayBufferToBinaryString(p)),(T&&this.__addimage__.isArrayBuffer(T)||this.__addimage__.isArrayBufferView(T))&&(T=this.__addimage__.arrayBufferToBinaryString(T)),{alias:b,data:p,index:y,filter:fe,decodeParameters:q,transparency:I,palette:J,sMask:T,predictor:$,width:R.width,height:R.height,bitsPerComponent:C,colorSpace:w}}}})(Ra.API),(function(t){t.processGIF89A=function(n,a,s,i){var c=new HF(n),l=c.width,m=c.height,d=[];c.decodeAndBlitFrameRGBA(0,d);var u={data:d,width:l,height:m},f=new bj(100).encode(u,100);return t.processJPEG.call(this,f,a,s,i)},t.processGIF87A=t.processGIF89A})(Ra.API),al.prototype.parseHeader=function(){if(this.fileSize=this.datav.getUint32(this.pos,!0),this.pos+=4,this.reserved=this.datav.getUint32(this.pos,!0),this.pos+=4,this.offset=this.datav.getUint32(this.pos,!0),this.pos+=4,this.headerSize=this.datav.getUint32(this.pos,!0),this.pos+=4,this.width=this.datav.getUint32(this.pos,!0),this.pos+=4,this.height=this.datav.getInt32(this.pos,!0),this.pos+=4,this.planes=this.datav.getUint16(this.pos,!0),this.pos+=2,this.bitPP=this.datav.getUint16(this.pos,!0),this.pos+=2,this.compress=this.datav.getUint32(this.pos,!0),this.pos+=4,this.rawSize=this.datav.getUint32(this.pos,!0),this.pos+=4,this.hr=this.datav.getUint32(this.pos,!0),this.pos+=4,this.vr=this.datav.getUint32(this.pos,!0),this.pos+=4,this.colors=this.datav.getUint32(this.pos,!0),this.pos+=4,this.importantColors=this.datav.getUint32(this.pos,!0),this.pos+=4,this.bitPP===16&&this.is_with_alpha&&(this.bitPP=15),this.bitPP<15){var t=this.colors===0?1<<this.bitPP:this.colors;this.palette=new Array(t);for(var n=0;n<t;n++){var a=this.datav.getUint8(this.pos++,!0),s=this.datav.getUint8(this.pos++,!0),i=this.datav.getUint8(this.pos++,!0),c=this.datav.getUint8(this.pos++,!0);this.palette[n]={red:i,green:s,blue:a,quad:c}}}this.height<0&&(this.height*=-1,this.bottom_up=!1)},al.prototype.parseBGR=function(){this.pos=this.offset;try{var t="bit"+this.bitPP,n=this.width*this.height*4;this.data=new Uint8Array(n),this[t]()}catch(a){Ar.log("bit decode error:"+a)}},al.prototype.bit1=function(){var t,n=Math.ceil(this.width/8),a=n%4;for(t=this.height-1;t>=0;t--){for(var s=this.bottom_up?t:this.height-1-t,i=0;i<n;i++)for(var c=this.datav.getUint8(this.pos++,!0),l=s*this.width*4+8*i*4,m=0;m<8&&8*i+m<this.width;m++){var d=this.palette[c>>7-m&1];
vendor: 4,671 bytes, line 3890
3890this.data[l+4*m]=d.blue,this.data[l+4*m+1]=d.green,this.data[l+4*m+2]=d.red,this.data[l+4*m+3]=255}a!==0&&(this.pos+=4-a)}},al.prototype.bit4=function(){for(var t=Math.ceil(this.width/2),n=t%4,a=this.height-1;a>=0;a--){for(var s=this.bottom_up?a:this.height-1-a,i=0;i<t;i++){var c=this.datav.getUint8(this.pos++,!0),l=s*this.width*4+2*i*4,m=c>>4,d=15&c,u=this.palette[m];if(this.data[l]=u.blue,this.data[l+1]=u.green,this.data[l+2]=u.red,this.data[l+3]=255,2*i+1>=this.width)break;u=this.palette[d],this.data[l+4]=u.blue,this.data[l+4+1]=u.green,this.data[l+4+2]=u.red,this.data[l+4+3]=255}n!==0&&(this.pos+=4-n)}},al.prototype.bit8=function(){for(var t=this.width%4,n=this.height-1;n>=0;n--){for(var a=this.bottom_up?n:this.height-1-n,s=0;s<this.width;s++){var i=this.datav.getUint8(this.pos++,!0),c=a*this.width*4+4*s;if(i<this.palette.length){var l=this.palette[i];this.data[c]=l.red,this.data[c+1]=l.green,this.data[c+2]=l.blue,this.data[c+3]=255}else this.data[c]=255,this.data[c+1]=255,this.data[c+2]=255,this.data[c+3]=255}t!==0&&(this.pos+=4-t)}},al.prototype.bit15=function(){for(var t=this.width%3,n=parseInt("11111",2),a=this.height-1;a>=0;a--){for(var s=this.bottom_up?a:this.height-1-a,i=0;i<this.width;i++){var c=this.datav.getUint16(this.pos,!0);this.pos+=2;var l=(c&n)/n*255|0,m=(c>>5&n)/n*255|0,d=(c>>10&n)/n*255|0,u=c>>15?255:0,f=s*this.width*4+4*i;this.data[f]=d,this.data[f+1]=m,this.data[f+2]=l,this.data[f+3]=u}this.pos+=t}},al.prototype.bit16=function(){for(var t=this.width%3,n=parseInt("11111",2),a=parseInt("111111",2),s=this.height-1;s>=0;s--){for(var i=this.bottom_up?s:this.height-1-s,c=0;c<this.width;c++){var l=this.datav.getUint16(this.pos,!0);this.pos+=2;var m=(l&n)/n*255|0,d=(l>>5&a)/a*255|0,u=(l>>11)/n*255|0,f=i*this.width*4+4*c;this.data[f]=u,this.data[f+1]=d,this.data[f+2]=m,this.data[f+3]=255}this.pos+=t}},al.prototype.bit24=function(){for(var t=this.height-1;t>=0;t--){for(var n=this.bottom_up?t:this.height-1-t,a=0;a<this.width;a++){var s=this.datav.getUint8(this.pos++,!0),i=this.datav.getUint8(this.pos++,!0),c=this.datav.getUint8(this.pos++,!0),l=n*this.width*4+4*a;this.data[l]=c,this.data[l+1]=i,this.data[l+2]=s,this.data[l+3]=255}this.pos+=this.width%4}},al.prototype.bit32=function(){for(var t=this.height-1;t>=0;t--)for(var n=this.bottom_up?t:this.height-1-t,a=0;a<this.width;a++){var s=this.datav.getUint8(this.pos++,!0),i=this.datav.getUint8(this.pos++,!0),c=this.datav.getUint8(this.pos++,!0),l=this.datav.getUint8(this.pos++,!0),m=n*this.width*4+4*a;this.data[m]=c,this.data[m+1]=i,this.data[m+2]=s,this.data[m+3]=l}},al.prototype.getData=function(){return this.data},(function(t){t.processBMP=function(n,a,s,i){var c=new al(n,!1),l=c.width,m=c.height,d={data:c.getData(),width:l,height:m},u=new bj(100).encode(d,100);return t.processJPEG.call(this,u,a,s,i)}})(Ra.API),n_.prototype.getData=function(){return this.data},(function(t){t.processWEBP=function(n,a,s,i){var c=new n_(n),l=c.width,m=c.height,d={data:c.getData(),width:l,height:m},u=new bj(100).encode(d,100);return t.processJPEG.call(this,u,a,s,i)}})(Ra.API),Ra.API.processRGBA=function(t,n,a){for(var s=t.data,i=s.length,c=new Uint8Array(i/4*3),l=new Uint8Array(i/4),m=0,d=0,u=0;u<i;u+=4){var f=s[u],g=s[u+1],p=s[u+2],y=s[u+3];c[m++]=f,c[m++]=g,c[m++]=p,l[d++]=y}var b=this.__addimage__.arrayBufferToBinaryString(c);return{alpha:this.__addimage__.arrayBufferToBinaryString(l),data:b,index:n,alias:a,colorSpace:"DeviceRGB",bitsPerComponent:8,width:t.width,height:t.height}},Ra.API.setLanguage=function(t){return this.internal.languageSettings===void 0&&(this.internal.languageSettings={},this.internal.languageSettings.isSubscribed=!1),{af:"Afrikaans",sq:"Albanian",ar:"Arabic (Standard)","ar-DZ":"Arabic (Algeria)","ar-BH":"Arabic (Bahrain)","ar-EG":"Arabic (Egypt)","ar-IQ":"Arabic (Iraq)","ar-JO":"Arabic (Jordan)","ar-KW":"Arabic (Kuwait)","ar-LB":"Arabic (Lebanon)","ar-LY":"Arabic (Libya)","ar-MA":"Arabic (Morocco)","ar-OM":"Arabic (Oman)","ar-QA":"Arabic (Qatar)","ar-SA":"Arabic (Saudi Arabia)","ar-SY":"Arabic (Syria)","ar-TN":"Arabic (Tunisia)","ar-AE":"Arabic (U.A.E.)","ar-YE":"Arabic (Yemen)",an:"Aragonese",hy:"Armenian",as:"Assamese",ast:"Asturian",az:"Azerbaijani",eu:"Basque",be:"Belarusian",bn:"Bengali",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",zh:"Chinese","zh-HK":"Chinese (Hong Kong)","zh-CN":"Chinese (PRC)","zh-SG":"Chinese (Singapore)","zh-TW":"Chinese (Taiwan)",cv:"Chuvash",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",nl:"Dutch (Standard)","nl-BE":"Dutch (Belgian)",en:"English","en-AU":"English (Australia)","en-BZ":"English (Belize)","en-CA":"English (Canad
3890a)","en-IE":"English (Ireland)","en-JM":"English (Jamaica)","en-NZ":"English (New Zealand)","en-PH":"English (Philippines)","en-ZA":"English (South Africa)","en-TT":"English (Trinidad & Tobago)","en-GB":"English (United Kingdom)","en-US":"English (United States)","en-ZW":"English (Zimbabwe)",eo:"Esperanto",et:"Estonian",fo:"Faeroese",fj:"Fijian",fi:"Finnish",fr:"French (Standard)","fr-BE":"French (Belgium)","fr-CA":"French (Canada)","fr-FR":"French (France)","fr-LU":"French (Luxembourg)","fr-MC":"French (Monaco)","fr-CH":"French (Switzerland)",fy:"Frisian",fur:"Friulian",gd:"Gaelic (Scots)","gd-IE":"Gaelic (Irish)",gl:"Galacian",ka:"Georgian",de:"German (Standard)","de-AT":"German (Austria)","de-DE":"German (Germany)","de-LI":"German (Liechtenstein)","de-LU":"German (Luxembourg)","de-CH":"German (Switzerland)",el:"Greek",gu:"Gujurati",ht:"Haitian",he:"Hebrew",hi:"Hindi",hu:"Hungarian",is:"Icelandic",id:"Indonesian",iu:"Inuktitut",ga:"Irish",it:"Italian (Standard)","it-CH":"Italian (Switzerland)",ja:"Japanese",kn:"Kannada",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ky:"Kirghiz",tlh:"Klingon",ko:"Korean","ko-KP":"Korean (North Korea)","ko-KR":"Korean (South Korea)",la:"Latin",lv:"Latvian",lt:"Lithuanian",lb:"Luxembourgish",mk:"North Macedonia",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mo:"Moldavian",nv:"Navajo",ng:"Ndonga",ne:"Nepali",no:"Norwegian",nb:"Norwegian (Bokmal)",nn:"Norwegian (Nynorsk)",oc:"Occitan",or:"Oriya",om:"Oromo",fa:"Persian","fa-IR":"Persian/Iran",pl:"Polish",pt:"Portuguese","pt-BR":"Portuguese (Brazil)",pa:"Punjabi","pa-IN":"Punjabi (India)","pa-PK":"Punjabi (Pakistan)",qu:"Quechua",rm:"Rhaeto-Romanic",ro:"Romanian","ro-MO":"Romanian (Moldavia)",ru:"Russian","ru-MO":"Russian (Moldavia)",sz:"Sami (Lappish)",sg:"Sango",sa:"Sanskrit",sc:"Sardinian",sd:"Sindhi",si:"Singhalese",sr:"Serbian",sk:"Slovak",sl:"Slovenian",so:"Somani",sb:"Sorbian",es:"Spanish","es-AR":"Spanish (Argentina)","es-BO":"Spanish (Bolivia)","es-CL":"Spanish (Chile)","es-CO":"Spanish (Colombia)","es-CR":"Spanish (Costa Rica)","es-DO":"Spanish (Dominican Republic)","es-EC":"Spanish (Ecuador)","es-SV":"Spanish (El Salvador)","es-GT":"Spanish (Guatemala)","es-HN":"Spanish (Honduras)","es-MX":"Spanish (Mexico)","es-NI":"Spanish (Nicaragua)","es-PA":"Spanish (Panama)","es-PY":"Spanish (Paraguay)","es-PE":"Spanish (Peru)","es-PR":"Spanish (Puerto Rico)","es-ES":"Spanish (Spain)","es-UY":"Spanish (Uruguay)","es-VE":"Spanish (Venezuela)",sx:"Sutu",sw:"Swahili",sv:"Swedish","sv-FI":"Swedish (Finland)","sv-SV":"Swedish (Sweden)",ta:"Tamil",tt:"Tatar",te:"Teluga",th:"Thai",tig:"Tigre",ts:"Tsonga",tn:"Tswana",tr:"Turkish",tk:"Turkmen",uk:"Ukrainian",hsb:"Upper Sorbian",ur:"Urdu",ve:"Venda",vi:"Vietnamese",vo:"Volapuk",wa:"Walloon",cy:"Welsh",xh:"Xhosa",ji:"Yiddish",zu:"Zulu"}[t]!==void 0&&(this.internal.languageSettings.languageCode=t,this.internal.languageSettings.isSubscribed===!1&&(this.internal.events.subscribe("putCatalog",(function(){this.internal.write("/Lang ("+this.internal.languageSettings.languageCode+")")})),this.internal.languageSettings.isSubscribed=!0)),this},zm=Ra.API,Rv=zm.getCharWidthsArray=function(t,n){var a,s,i=(n=n||{}).font||this.internal.getFont(),c=n.fontSize||this.internal.getFontSize(),l=n.charSpace||this.internal.getCharSpace(),m=n.widths?n.widths:i.metadata.Unicode.widths,d=m.fof?m.fof:1,u=n.kerning?n.kerning:i.metadata.Unicode.kerning,f=u.fof?u.fof:1,g=n.doKerning!==!1,p=0,y=t.length,b=0,N=m[0]||d,w=[];for(a=0;a<y;a++)s=t.charCodeAt(a),typeof i.metadata.widthOfString=="function"?w.push((i.metadata.widthOfGlyph(i.metadata.characterToGlyph(s))+l*(1e3/c)||0)/1e3):(p=g&&ur(u[s])==="object"&&!isNaN(parseInt(u[s][b],10))?u[s][b]/f:0,w.push((m[s]||N)/d+p)),b=s;return w},XI=zm.getStringUnitWidth=function(t,n){var a=(n=n||{}).fontSize||this.internal.getFontSize(),s=n.font||this.internal.getFont(),i=n.charSpace||this.internal.getCharSpace();return zm.processArabic&&(t=zm.processArabic(t)),typeof s.metadata.widthOfString=="function"?s.metadata.widthOfString(t,a,i)/a:Rv.apply(this,arguments).reduce((function(c,l){return c+l}),0)},ZI=function(t,n,a,s){for(var i=[],c=0,l=t.length,m=0;c!==l&&m+n[c]<a;)m+=n[c],c++;i.push(t.slice(0,c));var d=c;for(m=0;c!==l;)m+n[c]>s&&(i.push(t.slice(d,c)),m=0,d=c),m+=n[c],c++;return d!==c&&i.push(t.slice(d,c)),i},e_=function(t,n,a){a||(a={});var s,i,c,l,m,d,u,f=[],g=[f],p=a.textIndent||0,y=0,b=0,N=t.split(" "),w=Rv.apply(this,[" ",a])[0];if(d=a.lineIndent===-1?N[0].length+2:a.lineIndent||0){var C=Array(d).join(" "),R=[];N.map((function(_){(_=_.split(/\s*\n/)).length>1?R=R.concat(_.map((function(J,T){return(T&&J.length?` 3891`:"")+J}))):R.push(_[0])})),N=R,d=XI.apply(this,[C,a])}for(c=0,l=N.length;c<l;c++){var I=0;if(s=N[c],d&&s[0]==` 3892`&&(s=s.substr(1),I=1),p+y+(b=(i=Rv.apply(this,[s,a])).reduce((function(_,J){return _+J}),0))>n||I){if(b>n){for(m=ZI.apply(this,[s,i,n-(p+y),n]),f.push(m.shift()),f=[m.pop()];m.length;)g.push([m.shift()]);b=i.slice(s.length-(f[0]?f[0].length:0)).reduce((function(_,J){return _+J}),0)}else f=[s];g.push(f),p=b+d,y=w}else f.push(s),p+=y+b,y=w}return u=d?function(_,J){return(J?C:"")+_.join(" ")}:function(_){return _.join(" ")},g.map(u)},zm.splitTextToSize=function(t,n,a){var s,i=(a=a||{}).fontSize||this.internal.getFontSize(),c=(function(f){if(f.widths&&f.kerning)return{widths:f.widths,kerning:f.kerning};var g=this.internal.getFont(f.fontName,f.fontStyle);return g.metadata.Unicode?{widths:g.metadata.Unicode.widths||{0:1},kerning:g.metadata.Unicode.kerning||{}}:{font:g.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}).call(this,a);s=Array.isArray(t)?t:String(t).split(/\r?\n/);var l=1*this.internal.scaleFactor*n/i;c.textIndent=a.textIndent?1*a.textIndent*this.internal.scaleFactor/i:0,c.lineIndent=a.lineIndent;var m,d,u=[];for(m=0,d=s.length;m<d;m++)u=u.concat(e_.apply(this,[s[m],l,c]));return u},(function(t){t.__fontmetrics__=t.__fontmetrics__||{};for(var n="klmnopqrstuvwxyz",a={},s={},i=0;i<n.length;i++)a[n[i]]="0123456789abcdef"[i],s["0123456789abcdef"[i]]=n[i];var c=function(g){return"0x"+parseInt(g,10).toString(16)},l=t.__fontmetrics__.compress=function(g){var p,y,b,N,w=["{"];for(var C in g){if(p=g[C],isNaN(parseInt(C,10))?y="'"+C+"'":(C=parseInt(C,10),y=(y=c(C).slice(2)).slice(0,-1)+s[y.slice(-1)]),typeof p=="number")p<0?(b=c(p).slice(3),N="-"):(b=c(p).slice(2),N=""),b=N+b.slice(0,-1)+s[b.slice(-1)];
vendor: 3,660 bytes, line 3892
3892else{if(ur(p)!=="object")throw new Error("Don't know what to do with value type "+ur(p)+".");b=l(p)}w.push(y+b)}return w.push("}"),w.join("")},m=t.__fontmetrics__.uncompress=function(g){if(typeof g!="string")throw new Error("Invalid argument passed to uncompress.");for(var p,y,b,N,w={},C=1,R=w,I=[],_="",J="",T=g.length-1,G=1;G<T;G+=1)(N=g[G])=="'"?p?(b=p.join(""),p=void 0):p=[]:p?p.push(N):N=="{"?(I.push([R,b]),R={},b=void 0):N=="}"?((y=I.pop())[0][y[1]]=R,b=void 0,R=y[0]):N=="-"?C=-1:b===void 0?a.hasOwnProperty(N)?(_+=a[N],b=parseInt(_,16)*C,C=1,_=""):_+=N:a.hasOwnProperty(N)?(J+=a[N],R[b]=parseInt(J,16)*C,C=1,b=void 0,J=""):J+=N;return w},d={codePages:["WinAnsiEncoding"],WinAnsiEncoding:m("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")},u={Unicode:{Courier:d,"Courier-Bold":d,"Courier-BoldOblique":d,"Courier-Oblique":d,Helvetica:d,"Helvetica-Bold":d,"Helvetica-BoldOblique":d,"Helvetica-Oblique":d,"Times-Roman":d,"Times-Bold":d,"Times-BoldItalic":d,"Times-Italic":d}},f={Unicode:{"Courier-Oblique":m("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-BoldItalic":m("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"),"Helvetica-Bold":m("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
3892dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),Courier:m("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Courier-BoldOblique":m("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-Bold":m("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"),Symbol:m("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"),Helvetica:m("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
3892dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"),"Helvetica-BoldOblique":m("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4y
3892dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),ZapfDingbats:m("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"),"Courier-Bold":m("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),"Times-Italic":m("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}
3892fv{17su5tu5qs}fw{17su5tu5qs}}}"),"Times-Roman":m("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"),"Helvetica-Oblique":m("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4y
3892dn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}")}};t.events.push(["addFont",function(g){var p=g.font,y=f.Unicode[p.postScriptName];y&&(p.metadata.Unicode={},p.metadata.Unicode.widths=y.widths,p.metadata.Unicode.kerning=y.kerning);var b=u.Unicode[p.postScriptName];b&&(p.metadata.Unicode.encoding=b,p.encoding=b.codePages[0])}])})(Ra.API),(function(t){var n=function(a){for(var s=a.length,i=new Uint8Array(s),c=0;c<s;c++)i[c]=a.charCodeAt(c);return i};t.API.events.push(["addFont",function(a){var s=void 0,i=a.font,c=a.instance;if(!i.isStandardFont){if(c===void 0)throw new Error("Font does not exist in vFS, import fonts or remove declaration doc.addFont('"+i.postScriptName+"').");if(typeof(s=c.existsFileInVFS(i.postScriptName)===!1?c.loadFile(i.postScriptName):c.getFileFromVFS(i.postScriptName))!="string")throw new Error("Font is not stored as string-data in vFS, import fonts or remove declaration doc.addFont('"+i.postScriptName+"').");(function(l,m){m=/^\x00\x01\x00\x00/.test(m)?n(m):n(Xf(m)),l.metadata=t.API.TTFFont.open(m),l.metadata.Unicode=l.metadata.Unicode||{encoding:{},kerning:{},widths:[]},l.metadata.glyIdsUsed=[0]})(i,s)}}])})(Ra),(function(t){function n(){return(ns.canvg?Promise.resolve(ns.canvg):M1(()=>import("./index.es-C6cWECBE.js"),[])).catch((function(a){return Promise.reject(new Error("Could not load canvg: "+a))})).then((function(a){return a.default?a.default:a}))}Ra.API.addSvgAsImage=function(a,s,i,c,l,m,d,u){if(isNaN(s)||isNaN(i))throw Ar.error("jsPDF.addSvgAsImage: Invalid coordinates",arguments),new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");if(isNaN(c)||isNaN(l))throw Ar.error("jsPDF.addSvgAsImage: Invalid measurements",arguments),new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage");var f=document.createElement("canvas");f.width=c,f.height=l;var g=f.getContext("2d");g.fillStyle="#fff",g.fillRect(0,0,f.width,f.height);var p={ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0},y=this;return n().then((function(b){return b.fromString(g,a,p)}),(function(){return Promise.reject(new Error("Could not load canvg."))})).then((function(b){return b.render(p)})).then((function(){y.addImage(f.toDataURL("image/jpeg",1),s,i,c,l,d,u)}))}})(),Ra.API.putTotalPages=function(t){var n,a=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(n=new RegExp(t,"g"),a=this.internal.getNumberOfPages()):(n=new RegExp(this.pdfEscape16(t,this.internal.getFont()),"g"),a=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var s=1;s<=this.internal.getNumberOfPages();s++)for(var i=0;i<this.internal.pages[s].length;i++)this.internal.pages[s][i]=this.internal.pages[s][i].replace(n,a);return this},Ra.API.viewerPreferences=function(t,n){var a;t=t||{},n=n||!1;var s,i,c,l={HideToolbar:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},HideMenubar:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},HideWindowUI:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},FitWindow:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},CenterWindow:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.3},DisplayDocTitle:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.4},NonFullScreenPageMode:{defaultValue:"UseNone",value:"UseNone",type:"name",explicitSet:!1,valueSet:["UseNone","UseOutlines","UseThumbs","UseOC"],pdfVersion:1.3},Direction:{defaultValue:"L2R",value:"L2R",type:"name",explicitSet:!1,valueSet:["L2R","R2L"],pdfVersion:1.3},ViewArea:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},ViewClip:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintArea:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintClip:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:!1,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintScaling:{defaultValue:"AppDefault",value:"AppDefault",type:"name",explicitSet:!1,valueSet:["AppDefault","None"],pdfVersion:1.6},Duplex:{defaultValue:"",value:"none",type:"name",explicitSet:!1,valueSet:["Simplex","DuplexFlipShortEdge","DuplexFlipLongEdge","none"],pdfVersion:1.7},PickTrayByPDFSize:{defaultValue:!1,value:!1,type:"boolean",explicitSet:!1,valueSet:[!0,!1],pdfVersion:1.7},PrintPageRange:{defaultValue:"",value:"",type:"array",explicitSet:!1,valueSet:null,pdfVersion:1.7},NumCopies:{defaultValue:1,value:1,type:"integer",explicitSet:!1,valueSet:null,pdfVersion:1.7}},m=Object.keys(l),d=[],u=0,f=0,g=0;function p(b,N){var w,C=!1;for(w=0;w<b.length;w+=1)b[w]===N&&(C=!0);return C}if(this.internal.viewerpreferences===void 0&&(this.internal.viewerpreferences={},this.internal.viewerpreferences.configuration=JSON.parse(JSON.stringify(l)),this.internal.viewerpreferences.isSubscribed=!1),a=this.internal.viewerpreferences.configuration,t==="reset"||n===!0){var y=m.length;for(g=0;g<y;g+=1)a[m[g]].value=a[m[g]].defaultValue,a[m[g]].explicitSet=!1}if(ur(t)==="object"){for(i in t)if(c=t[i],p(m,i)&&c!==void 0){if(a[i].type==="boolean"&&typeof c=="boolean")a[i].value=c;else if(a[i].type==="name"&&p(a[i].valueSet,c))a[i].value=c;else if(a[i].type==="integer"&&Number.isInteger(c))a[i].value=c;else if(a[i].type==="array"){for(u=0;
vendor: 4,556 bytes, lines 3892-3920
3892u<c.length;u+=1)if(s=!0,c[u].length===1&&typeof c[u][0]=="number")d.push(String(c[u]-1));else if(c[u].length>1){for(f=0;f<c[u].length;f+=1)typeof c[u][f]!="number"&&(s=!1);s===!0&&d.push([c[u][0]-1,c[u][1]-1].join(" "))}a[i].value="["+d.join(" ")+"]"}else a[i].value=a[i].defaultValue;a[i].explicitSet=!0}}return this.internal.viewerpreferences.isSubscribed===!1&&(this.internal.events.subscribe("putCatalog",(function(){var b,N=[];for(b in a)a[b].explicitSet===!0&&(a[b].type==="name"?N.push("/"+b+" /"+a[b].value):N.push("/"+b+" "+a[b].value));N.length!==0&&this.internal.write(`/ViewerPreferences 3893<< 3894`+N.join(` 3895`)+` 3896>>`)})),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=a,this},(function(t){var n=function(){var s='<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="'+this.internal.__metadata__.namespaceuri+'"><jspdf:metadata>',i=unescape(encodeURIComponent('<x:xmpmeta xmlns:x="adobe:ns:meta/">')),c=unescape(encodeURIComponent(s)),l=unescape(encodeURIComponent(this.internal.__metadata__.metadata)),m=unescape(encodeURIComponent("</jspdf:metadata></rdf:Description></rdf:RDF>")),d=unescape(encodeURIComponent("</x:xmpmeta>")),u=c.length+l.length+m.length+i.length+d.length;this.internal.__metadata__.metadata_object_number=this.internal.newObject(),this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+u+" >>"),this.internal.write("stream"),this.internal.write(i+c+l+m+d),this.internal.write("endstream"),this.internal.write("endobj")},a=function(){this.internal.__metadata__.metadata_object_number&&this.internal.write("/Metadata "+this.internal.__metadata__.metadata_object_number+" 0 R")};t.addMetadata=function(s,i){return this.internal.__metadata__===void 0&&(this.internal.__metadata__={metadata:s,namespaceuri:i||"http://jspdf.default.namespaceuri/"},this.internal.events.subscribe("putCatalog",a),this.internal.events.subscribe("postPutResources",n)),this}})(Ra.API),(function(t){var n=t.API,a=n.pdfEscape16=function(c,l){for(var m,d=l.metadata.Unicode.widths,u=["","0","00","000","0000"],f=[""],g=0,p=c.length;g<p;++g){if(m=l.metadata.characterToGlyph(c.charCodeAt(g)),l.metadata.glyIdsUsed.push(m),l.metadata.toUnicode[m]=c.charCodeAt(g),d.indexOf(m)==-1&&(d.push(m),d.push([parseInt(l.metadata.widthOfGlyph(m),10)])),m=="0")return f.join("");m=m.toString(16),f.push(u[4-m.length],m)}return f.join("")},s=function(c){var l,m,d,u,f,g,p;for(f=`/CIDInit /ProcSet findresource begin 389712 dict begin 3898begincmap 3899/CIDSystemInfo << 3900 /Registry (Adobe) 3901 /Ordering (UCS) 3902 /Supplement 0 3903>> def 3904/CMapName /Adobe-Identity-UCS def 3905/CMapType 2 def 39061 begincodespacerange 3907<0000><ffff> 3908endcodespacerange`,d=[],g=0,p=(m=Object.keys(c).sort((function(y,b){return y-b}))).length;g<p;g++)l=m[g],d.length>=100&&(f+=` 3909`+d.length+` beginbfchar 3910`+d.join(` 3911`)+` 3912endbfchar`,d=[]),c[l]!==void 0&&c[l]!==null&&typeof c[l].toString=="function"&&(u=("0000"+c[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),d.push("<"+l+"><"+u+">"));return d.length&&(f+=` 3913`+d.length+` beginbfchar 3914`+d.join(` 3915`)+` 3916endbfchar 3917`),f+=`endcmap 3918CMapName currentdict /CMap defineresource pop 3919end 3920end`};n.events.push(["putFont",function(c){(function(l){var m=l.font,d=l.out,u=l.newObject,f=l.putStream;if(m.metadata instanceof t.API.TTFFont&&m.encoding==="Identity-H"){for(var g=m.metadata.Unicode.widths,p=m.metadata.subset.encode(m.metadata.glyIdsUsed,1),y="",b=0;b<p.length;b++)y+=String.fromCharCode(p[b]);var N=u();f({data:y,addLength1:!0,objectId:N}),d("endobj");var w=u();f({data:s(m.metadata.toUnicode),addLength1:!0,objectId:w}),d("endobj");var C=u();d("<<"),d("/Type /FontDescriptor"),d("/FontName /"+Km(m.fontName)),d("/FontFile2 "+N+" 0 R"),d("/FontBBox "+t.API.PDFObject.convert(m.metadata.bbox)),d("/Flags "+m.metadata.flags),d("/StemV "+m.metadata.stemV),d("/ItalicAngle "+m.metadata.italicAngle),d("/Ascent "+m.metadata.ascender),d("/Descent "+m.metadata.decender),d("/CapHeight "+m.metadata.capHeight),d(">>"),d("endobj");var R=u();d("<<"),d("/Type /Font"),d("/BaseFont /"+Km(m.fontName)),d("/FontDescriptor "+C+" 0 R"),d("/W "+t.API.PDFObject.convert(g)),d("/CIDToGIDMap /Identity"),d("/DW 1000"),d("/Subtype /CIDFontType2"),d("/CIDSystemInfo"),d("<<"),d("/Supplement 0"),d("/Registry (Adobe)"),d("/Ordering ("+m.encoding+")"),d(">>"),d(">>"),d("endobj"),m.objectNumber=u(),d("<<"),d("/Type /Font"),d("/Subtype /Type0"),d("/ToUnicode "+w+" 0 R"),d("/BaseFont /"+Km(m.fontName)),d("/Encoding /"+m.encoding),d("/DescendantFonts ["+R+" 0 R]"),d(">>
3920"),d("endobj"),m.isAlreadyPutted=!0}})(c)}]),n.events.push(["putFont",function(c){(function(l){var m=l.font,d=l.out,u=l.newObject,f=l.putStream;if(m.metadata instanceof t.API.TTFFont&&m.encoding==="WinAnsiEncoding"){for(var g=m.metadata.rawData,p="",y=0;y<g.length;y++)p+=String.fromCharCode(g[y]);var b=u();f({data:p,addLength1:!0,objectId:b}),d("endobj");var N=u();f({data:s(m.metadata.toUnicode),addLength1:!0,objectId:N}),d("endobj");var w=u();d("<<"),d("/Descent "+m.metadata.decender),d("/CapHeight "+m.metadata.capHeight),d("/StemV "+m.metadata.stemV),d("/Type /FontDescriptor"),d("/FontFile2 "+b+" 0 R"),d("/Flags 96"),d("/FontBBox "+t.API.PDFObject.convert(m.metadata.bbox)),d("/FontName /"+Km(m.fontName)),d("/ItalicAngle "+m.metadata.italicAngle),d("/Ascent "+m.metadata.ascender),d(">>"),d("endobj"),m.objectNumber=u();for(var C=0;C<m.metadata.hmtx.widths.length;C++)m.metadata.hmtx.widths[C]=parseInt(m.metadata.hmtx.widths[C]*(1e3/m.metadata.head.unitsPerEm));d("<</Subtype/TrueType/Type/Font/ToUnicode "+N+" 0 R/BaseFont/"+Km(m.fontName)+"/FontDescriptor "+w+" 0 R/Encoding/"+m.encoding+" /FirstChar 29 /LastChar 255 /Widths "+t.API.PDFObject.convert(m.metadata.hmtx.widths)+">>"),d("endobj"),m.isAlreadyPutted=!0}})(c)}]);var i=function(c){var l,m=c.text||"",d=c.x,u=c.y,f=c.options||{},g=c.mutex||{},p=g.pdfEscape,y=g.activeFontKey,b=g.fonts,N=y,w="",C=0,R="",I=b[N].encoding;if(b[N].encoding!=="Identity-H")return{text:m,x:d,y:u,options:f,mutex:g};for(R=m,N=y,Array.isArray(m)&&(R=m[0]),C=0;C<R.length;C+=1)b[N].metadata.hasOwnProperty("cmap")&&(l=b[N].metadata.cmap.unicode.codeMap[R[C].charCodeAt(0)]),l||R[C].charCodeAt(0)<256&&b[N].metadata.hasOwnProperty("Unicode")?w+=R[C]:w+="";var _="";return parseInt(N.slice(1))<14||I==="WinAnsiEncoding"?_=p(w,N).split("").map((function(J){return J.charCodeAt(0).toString(16)})).join(""):I==="Identity-H"&&(_=a(w,b[N])),g.isHex=!0,{text:_,x:d,y:u,options:f,mutex:g}};n.events.push(["postProcessText",function(c){var l=c.text||"",m=[],d={text:l,x:c.x,y:c.y,options:c.options,mutex:c.mutex};if(Array.isArray(l)){var u=0;for(u=0;u<l.length;u+=1)Array.isArray(l[u])&&l[u].length===3?m.push([i(Object.assign({},d,{text:l[u][0]})).text,l[u][1],l[u][2]]):m.push(i(Object.assign({},d,{text:l[u]})).text);c.text=m}else c.text=i(Object.assign({},d,{text:l})).text}])})(Ra),(function(t){var n=function(){return this.internal.vFS===void 0&&(this.internal.vFS={}),!0};t.existsFileInVFS=function(a){return n.call(this),this.internal.vFS[a]!==void 0},t.addFileToVFS=function(a,s){return n.call(this),this.internal.vFS[a]=s,this},t.getFileFromVFS=function(a){return n.call(this),this.internal.vFS[a]!==void 0?this.internal.vFS[a]:null}})(Ra.API),(function(t){t.__bidiEngine__=t.prototype.__bidiEngine__=function(s){var i,c,l,m,d,u,f,g=n,p=[[0,3,0,1,0,0,0],[0,3,0,1,2,2,0],[0,3,0,17,2,0,1],[0,3,5,5,4,1,0],[0,3,21,21,4,0,1],[0,3,5,5,4,2,0]],y=[[2,0,1,1,0,1,0],[2,0,1,1,0,2,0],[2,0,2,1,3,2,0],[2,0,2,33,3,1,1]],b={L:0,R:1,EN:2,AN:3,N:4,B:5,S:6},N={0:0,5:1,6:2,7:3,32:4,251:5,254:6,255:7},w=["(",")","(","<",">","<","[","]","[","{","}","{","«","»","«","â¹","âº","â¹","â
","â","â
","â½","â¾","â½","â","â","â","â¤","â¥","â¤","â©","âª","â©","ï¹","ï¹","ï¹","ï¹","ï¹","ï¹","ï¹","ï¹","ï¹","﹤","ï¹¥","﹤"],C=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),R=!1,I=0;this.__bidiEngine__={};var _=function(L){var D=L.charCodeAt(),M=D>>8,Z=N[M];return Z!==void 0?g[256*Z+(255&D)]:M===252||M===253?"AL":C.test(M)?"L":M===8?"R":"N"},J=function(L){for(var D,M=0;M<L.length;M++){if((D=_(L.charAt(M)))==="L")return!1;if(D==="R")return!0}return!1},T=function(L,D,M,Z){var fe,q,ne,ae,Y=D[Z];switch(Y){case"L":case"R":R=!1;break;case"N":case"AN":break;case"EN":R&&(Y="AN");break;case"AL":R=!0,Y="R";break;case"WS":Y="N";break;case"CS":Z<1||Z+1>=D.length||(fe=M[Z-1])!=="EN"&&fe!=="AN"||(q=D[Z+1])!=="EN"&&q!=="AN"?Y="N":R&&(q="AN"),Y=q===fe?q:"N";break;case"ES":Y=(fe=Z>0?M[Z-1]:"B")==="EN"&&Z+1<D.length&&D[Z+1]==="EN"?"EN":"N";break;case"ET":if(Z>0&&M[Z-1]==="EN"){Y="EN";break}if(R){Y="N";break}for(ne=Z+1,ae=D.length;ne<ae&&D[ne]==="ET";)ne++;Y=ne<ae&&D[ne]==="EN"?"EN":"N";break;case"NSM":if(l&&!m){for(ae=D.length,ne=Z+1;ne<ae&&D[ne]==="NSM";)ne++;if(ne<ae){var je=L[Z],V=je>=1425&&je<=2303||je===64286;if(fe=D[ne],V&&(fe==="R"||fe==="AL")){Y="R";break}}}Y=Z<1||(fe=D[Z-1])==="B"?"N":M[Z-1];break;case"B":R=!1,i=!0,Y=I;break;case"S":c=!0,Y="N";break;case"LRE":case"RLE":case"LRO":case"RLO":case"PDF":R=!1;break;case"BN":Y="N"}return Y},G=function(L,D,M){var Z=L.split("");return M&&z(Z,M,{hiLevel:I}),Z.reverse(),D&&D.reverse(),Z.join("")},z=function(L,D,M){var Z,fe,q,ne,ae,Y=-1,je=L.length,V=0,$=[],F=I?y:p,P=[];for(R=!1,i=!1,c=!1,fe=0;fe<je;fe++)P[fe]=_(L[fe]);for(q=0;q<je;q++){if(ae=V,$[q]=T(L,P,$,q),Z=240&(V=F[ae][b[$[q]]]),V&=15,D[q]=ne=F[V][5],Z>0)if(Z===16){for(fe=Y;fe<q;fe++)D[fe]=1;Y=-1}else Y=-1;if(F[V][6])Y===-1&&(Y=q);else if(Y>-1){for(fe=Y;fe<q;fe++)D[fe]=ne;Y=-1}P[q]==="B"&&(D[q]=0),M.hiLevel|=ne}c&&(function(ue,me,ge){for(var de=0;de<ge;de++)if(ue[de]==="S"){me[de]=I;for(var Pe=de-1;Pe>=0&&ue[Pe]==="WS";Pe--)me[Pe]=I}})(P,D,je)}
vendor: 17,316 bytes, line 3920
3920,H=function(L,D,M,Z,fe){if(!(fe.hiLevel<L)){if(L===1&&I===1&&!i)return D.reverse(),void(M&&M.reverse());for(var q,ne,ae,Y,je=D.length,V=0;V<je;){if(Z[V]>=L){for(ae=V+1;ae<je&&Z[ae]>=L;)ae++;for(Y=V,ne=ae-1;Y<ne;Y++,ne--)q=D[Y],D[Y]=D[ne],D[ne]=q,M&&(q=M[Y],M[Y]=M[ne],M[ne]=q);V=ae}V++}}},K=function(L,D,M){var Z=L.split(""),fe={hiLevel:I};return M||(M=[]),z(Z,M,fe),(function(q,ne,ae){if(ae.hiLevel!==0&&f)for(var Y,je=0;je<q.length;je++)ne[je]===1&&(Y=w.indexOf(q[je]))>=0&&(q[je]=w[Y+1])})(Z,M,fe),H(2,Z,D,M,fe),H(1,Z,D,M,fe),Z.join("")};return this.__bidiEngine__.doBidiReorder=function(L,D,M){if((function(fe,q){if(q)for(var ne=0;ne<fe.length;ne++)q[ne]=ne;m===void 0&&(m=J(fe)),u===void 0&&(u=J(fe))})(L,D),l||!d||u)if(l&&d&&m^u)I=m?1:0,L=G(L,D,M);else if(!l&&d&&u)I=m?1:0,L=K(L,D,M),L=G(L,D);else if(!l||m||d||u){if(l&&!d&&m^u)L=G(L,D),m?(I=0,L=K(L,D,M)):(I=1,L=K(L,D,M),L=G(L,D));else if(l&&m&&!d&&u)I=1,L=K(L,D,M),L=G(L,D);else if(!l&&!d&&m^u){var Z=f;m?(I=1,L=K(L,D,M),I=0,f=!1,L=K(L,D,M),f=Z):(I=0,L=K(L,D,M),L=G(L,D),I=1,f=!1,L=K(L,D,M),f=Z,L=G(L,D))}}else I=0,L=K(L,D,M);else I=m?1:0,L=K(L,D,M);return L},this.__bidiEngine__.setOptions=function(L){L&&(l=L.isInputVisual,d=L.isOutputVisual,m=L.isInputRtl,u=L.isOutputRtl,f=L.isSymmetricSwapping)},this.__bidiEngine__.setOptions(s),this.__bidiEngine__};var n=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","N","N","ET","ET","ET","N","N","N","N","N","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","N","N","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","N","N","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","N","ET","ET","ET","ET","N","N","N","N","L","N","N","BN","N","N","ET","ET","EN","EN","N","L","N","N","N","EN","L","N","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","L","L","L","L","L","L","L","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","L","N","N","N","N","N","ET","N","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","R","NSM","R","NSM","NSM","R","NSM","NSM","R","NSM","N","N","N","N","N","N","N","N","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","N","N","N","N","N","R","R","R","R","R","N","N","N","N","N","N","N","N","N","N","N","AN","AN","AN","AN","AN","AN","N","N","AL","ET","ET","AL","CS","AL","N","N","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AL","AL","N","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AN","AN","AN","AN","AN","AN","AN","AN","AN","AN","ET","AN","AN","AL","AL","AL","NSM","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AN","N","NSM","NSM","NSM","NSM","NSM","NSM","AL","AL","NSM","NSM","N","NSM","NSM","NSM","NSM","AL","AL","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","N","AL","AL","NSM","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","N","N","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","AL","N","N","N","N","N","N","N","N","N","N","N","N","N","N","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","R","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","R","R","N","N","N","N","R","N","N","N","N","N","WS","WS","WS","WS","WS","WS","WS","WS","WS","WS","WS","BN","BN","BN","L","R","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","WS","B","LRE","RLE","PDF","LRO","RLO","CS","ET","ET","ET","ET","ET","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","CS","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","WS","BN","BN","BN","BN","BN","N","LRI","RLI","FSI","PDI","BN","BN","BN","BN","BN","BN","EN","L","N","N","EN","EN","EN","EN","EN","EN","ES","ES","N","N","N","L","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","ES","ES","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","N","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","ET","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","L","L","L","L","L","L","L","N","N","N","N","N","N","N","N","N","N","N","N","L","L","L","L","L","N","N","N","N","N","R","NSM","R","R","R","R","R","R","R","R","R","R","ES","R","R","R","R","R","R","R","R","R","R","R","R","R","N","R","R","R","R","R","N","R","N","R","R","N","R","R","N","R","R","R","R","R","R","R","R","R","R","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","NSM","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","CS","N","CS","N","N","CS","N","N","N","N","N","N","N","N","N","ET","N","N","ES","ES","N","N","N","N","N","ET","ET","N","N","N","N","N","AL","AL","AL","AL","AL","N","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","AL","N","N","BN","N","N","N","ET","ET","ET","N","N","N","N","N","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","N","N","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","N","N","N","N","N","N","N","N","N","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","N","N","N","L","L","L","L","L","L","N","N","L","L","L","L","L","L","N","N","L","L","L","L","L","L","N","N","L","L","L","N","N","N","ET","ET","N","N","N","ET","ET","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N","N"],a=new t.__bidiEngine__({isInputVisual:!0});t.API.events.push(["postProcessText",function(s){var i=s.text,c=(s.x,s.y,s.options||{}),l=(s.mutex,c.lang,[]);if(c.isInputVisual=typeof c.isInputVisual!="boolean"||c.isInputVisual,a.setOptions(c),Object.prototype.toString.call(i)==="[object Array]"){var m=0;for(l=[],m=0;m<i.length;m+=1)Object.prototype.toString.call(i[m])==="[object Array]"?l.push([a.doBidiReorder(i[m][0]),i[m][1],i[m][2]]):l.push([a.doBidiReorder(i[m])]);s.text=l}else s.text=a.doBidiReorder(i);a.setOptions({isInputVisual:!0})}])})(Ra),Ra.API.TTFFont=(function(){function t(n){var a;if(this.rawData=n,a=this.contents=new Gu(n),this.contents.pos=4,a.readString(4)==="ttcf")throw new Error("TTCF not supported.");a.pos=0,this.parse(),this.subset=new i7(this),this.registerTTF()}return t.open=function(n){return new t(n)},t.prototype.parse=function(){return this.directory=new WF(this.contents),this.head=new YF(this),this.name=new ZF(this),this.cmap=new OE(this),this.toUnicode={},this.hhea=new QF(this),this.maxp=new e7(this),this.hmtx=new t7(this),this.post=new KF(this),this.os2=new JF(this),this.loca=new r7(this),this.glyf=new n7(this),this.ascender=this.os2.exists&&this.os2.ascender||this.hhea.ascender,this.decender=this.os2.exists&&this.os2.decender||this.hhea.decender,this.lineGap=this.os2.exists&&this.os2.lineGap||this.hhea.lineGap,this.bbox=[this.head.xMin,this.head.yMin,this.head.xMax,this.head.yMax]},t.prototype.registerTTF=function(){var n,a,s,i,c;if(this.scaleFactor=1e3/this.head.unitsPerEm,this.bbox=(function(){var l,m,d,u;for(u=[],l=0,m=(d=this.bbox).length;l<m;l++)n=d[l],u.push(Math.round(n*this.scaleFactor));return u}).call(this),this.stemV=0,this.post.exists?(s=255&(i=this.post.italic_angle),(32768&(a=i>>16))!=0&&(a=-(1+(65535^a))),this.italicAngle=+(a+"."+s)):this.italicAngle=0,this.ascender=Math.round(this.ascender*this.scaleFactor),this.decender=Math.round(this.decender*this.scaleFactor),this.lineGap=Math.round(this.lineGap*this.scaleFactor),this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender,this.xHeight=this.os2.exists&&this.os2.xHeight||0,this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8,this.isSerif=(c=this.familyClass)===1||c===2||c===3||c===4||c===5||c===7,this.isScript=this.familyClass===10,this.flags=0,this.post.isFixedPitch&&(this.flags|=1),this.isSerif&&(this.flags|=2),this.isScript&&(this.flags|=8),this.italicAngle!==0&&(this.flags|=64),this.flags|=32,!this.cmap.unicode)throw new Error("No unicode cmap for font")},t.prototype.characterToGlyph=function(n){var a;return((a=this.cmap.unicode)!=null?a.codeMap[n]:void 0)||0},t.prototype.widthOfGlyph=function(n){var a;return a=1e3/this.head.unitsPerEm,this.hmtx.forGlyph(n).advance*a},t.prototype.widthOfString=function(n,a,s){var i,c,l,m;for(l=0,c=0,m=(n=""+n).length;0<=m?c<m:c>m;c=0<=m?++c:--c)i=n.charCodeAt(c),l+=this.widthOfGlyph(this.characterToGlyph(i))+s*(1e3/a)||0;return l*(a/1e3)},t.prototype.lineHeight=function(n,a){var s;return a==null&&(a=!1),s=a?this.lineGap:0,(this.ascender+s-this.decender)/1e3*n},t})();var yl,Gu=(function(){function t(n){this.data=n??[],this.pos=0,this.length=this.data.length}return t.prototype.readByte=function(){return this.data[this.pos++]},t.prototype.writeByte=function(n){return this.data[this.pos++]=n},t.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},t.prototype.writeUInt32=function(n){return this.writeByte(n>>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n)},t.prototype.readInt32=function(){var n;return(n=this.readUInt32())>=2147483648?n-4294967296:n},t.prototype.writeInt32=function(n){return n<0&&(n+=4294967296),this.writeUInt32(n)},t.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},t.prototype.writeUInt16=function(n){return this.writeByte(n>>8&255),this.writeByte(255&n)},t.prototype.readInt16=function(){var n;return(n=this.readUInt16())>=32768?n-65536:n},t.prototype.writeInt16=function(n){return n<0&&(n+=65536),this.writeUInt16(n)},t.prototype.readString=function(n){var a,s;for(s=[],a=0;0<=n?a<n:a>n;a=0<=n?++a:--a)s[a]=String.fromCharCode(this.readByte());return s.join("")},t.prototype.writeString=function(n){var a,s,i;for(i=[],a=0,s=n.length;0<=s?a<s:a>s;a=0<=s?++a:--a)i.push(this.writeByte(n.charCodeAt(a)));return i},t.prototype.readShort=function(){return this.readInt16()},t.prototype.writeShort=function(n){return this.writeInt16(n)},t.prototype.readLongLong=function(){var n,a,s,i,c,l,m,d;return n=this.readByte(),a=this.readByte(),s=this.readByte(),i=this.readByte(),c=this.readByte(),l=this.readByte(),m=this.readByte(),d=this.readByte(),128&n?-1*(72057594037927940*(255^n)+281474976710656*(255^a)+1099511627776*(255^s)+4294967296*(255^i)+16777216*(255^c)+65536*(255^l)+256*(255^m)+(255^d)+1):72057594037927940*n+281474976710656*a+1099511627776*s+4294967296*i+16777216*c+65536*l+256*m+d},t.prototype.writeLongLong=function(n){var a,s;return a=Math.floor(n/4294967296),s=4294967295&n,this.writeByte(a>>24&255),this.writeByte(a>>16&255),this.writeByte(a>>8&255),this.writeByte(255&a),this.writeByte(s>>24&255),this.writeByte(s>>16&255),this.writeByte(s>>8&255),this.writeByte(255&s)},t.prototype.readInt=function(){return this.readInt32()},t.prototype.writeInt=function(n){return this.writeInt32(n)},t.prototype.read=function(n){var a,s;for(a=[],s=0;0<=n?s<n:s>n;s=0<=n?++s:--s)a.push(this.readByte());return a},t.prototype.write=function(n){var a,s,i,c;for(c=[],s=0,i=n.length;s<i;s++)a=n[s],c.push(this.writeByte(a));return c},t})(),WF=(function(){var t;function n(a){var s,i,c;for(this.scalarType=a.readInt(),this.tableCount=a.readShort(),this.searchRange=a.readShort(),this.entrySelector=a.readShort(),this.rangeShift=a.readShort(),this.tables={},i=0,c=this.tableCount;0<=c?i<c:i>c;i=0<=c?++i:--i)s={tag:a.readString(4),checksum:a.readInt(),offset:a.readInt(),length:a.readInt()},this.tables[s.tag]=s}return n.prototype.encode=function(a){var s,i,c,l,m,d,u,f,g,p,y,b,N;for(N in y=Object.keys(a).length,d=Math.log(2),g=16*Math.floor(Math.log(y)/d),l=Math.floor(g/d),f=16*y-g,(i=new Gu).writeInt(this.scalarType),i.writeShort(y),i.writeShort(g),i.writeShort(l),i.writeShort(f),c=16*y,u=i.pos+c,m=null,b=[],a)for(p=a[N],i.writeString(N),i.writeInt(t(p)),i.writeInt(u),i.writeInt(p.length),b=b.concat(p),N==="head"&&(m=u),u+=p.length;u%4;)b.push(0),u++;return i.write(b),s=2981146554-t(i.data),i.pos=m+8,i.writeUInt32(s),i.data},t=function(a){var s,i,c,l;
3920for(a=LE.call(a);a.length%4;)a.push(0);for(c=new Gu(a),i=0,s=0,l=a.length;s<l;s=s+=4)i+=c.readUInt32();return 4294967295&i},n})(),GF={}.hasOwnProperty,Gl=function(t,n){for(var a in n)GF.call(n,a)&&(t[a]=n[a]);function s(){this.constructor=t}return s.prototype=n.prototype,t.prototype=new s,t.__super__=n.prototype,t};yl=(function(){function t(n){var a;this.file=n,a=this.file.directory.tables[this.tag],this.exists=!!a,a&&(this.offset=a.offset,this.length=a.length,this.parse(this.file.contents))}return t.prototype.parse=function(){},t.prototype.encode=function(){},t.prototype.raw=function(){return this.exists?(this.file.contents.pos=this.offset,this.file.contents.read(this.length)):null},t})();var YF=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="head",n.prototype.parse=function(a){return a.pos=this.offset,this.version=a.readInt(),this.revision=a.readInt(),this.checkSumAdjustment=a.readInt(),this.magicNumber=a.readInt(),this.flags=a.readShort(),this.unitsPerEm=a.readShort(),this.created=a.readLongLong(),this.modified=a.readLongLong(),this.xMin=a.readShort(),this.yMin=a.readShort(),this.xMax=a.readShort(),this.yMax=a.readShort(),this.macStyle=a.readShort(),this.lowestRecPPEM=a.readShort(),this.fontDirectionHint=a.readShort(),this.indexToLocFormat=a.readShort(),this.glyphDataFormat=a.readShort()},n.prototype.encode=function(a){var s;return(s=new Gu).writeInt(this.version),s.writeInt(this.revision),s.writeInt(this.checkSumAdjustment),s.writeInt(this.magicNumber),s.writeShort(this.flags),s.writeShort(this.unitsPerEm),s.writeLongLong(this.created),s.writeLongLong(this.modified),s.writeShort(this.xMin),s.writeShort(this.yMin),s.writeShort(this.xMax),s.writeShort(this.yMax),s.writeShort(this.macStyle),s.writeShort(this.lowestRecPPEM),s.writeShort(this.fontDirectionHint),s.writeShort(a),s.writeShort(this.glyphDataFormat),s.data},n})(),a_=(function(){function t(n,a){var s,i,c,l,m,d,u,f,g,p,y,b,N,w,C,R,I;switch(this.platformID=n.readUInt16(),this.encodingID=n.readShort(),this.offset=a+n.readInt(),g=n.pos,n.pos=this.offset,this.format=n.readUInt16(),this.length=n.readUInt16(),this.language=n.readUInt16(),this.isUnicode=this.platformID===3&&this.encodingID===1&&this.format===4||this.platformID===0&&this.format===4,this.codeMap={},this.format){case 0:for(d=0;d<256;++d)this.codeMap[d]=n.readByte();break;case 4:for(y=n.readUInt16(),p=y/2,n.pos+=6,c=(function(){var _,J;for(J=[],d=_=0;0<=p?_<p:_>p;d=0<=p?++_:--_)J.push(n.readUInt16());return J})(),n.pos+=2,N=(function(){var _,J;for(J=[],d=_=0;0<=p?_<p:_>p;d=0<=p?++_:--_)J.push(n.readUInt16());return J})(),u=(function(){var _,J;for(J=[],d=_=0;0<=p?_<p:_>p;d=0<=p?++_:--_)J.push(n.readUInt16());return J})(),f=(function(){var _,J;for(J=[],d=_=0;0<=p?_<p:_>p;d=0<=p?++_:--_)J.push(n.readUInt16());return J})(),i=(this.length-n.pos+this.offset)/2,m=(function(){var _,J;for(J=[],d=_=0;0<=i?_<i:_>i;d=0<=i?++_:--_)J.push(n.readUInt16());return J})(),d=C=0,I=c.length;C<I;d=++C)for(w=c[d],s=R=b=N[d];b<=w?R<=w:R>=w;s=b<=w?++R:--R)f[d]===0?l=s+u[d]:(l=m[f[d]/2+(s-b)-(p-d)]||0)!==0&&(l+=u[d]),this.codeMap[s]=65535&l}n.pos=g}return t.encode=function(n,a){var s,i,c,l,m,d,u,f,g,p,y,b,N,w,C,R,I,_,J,T,G,z,H,K,L,D,M,Z,fe,q,ne,ae,Y,je,V,$,F,P,ue,me,ge,de,Pe,Re,Ee,Be;switch(Z=new Gu,l=Object.keys(n).sort((function(We,it){return We-it})),a){case"macroman":for(N=0,w=(function(){var We=[];for(b=0;b<256;++b)We.push(0);return We})(),R={0:0},c={},fe=0,Y=l.length;fe<Y;fe++)R[Pe=n[i=l[fe]]]==null&&(R[Pe]=++N),c[i]={old:n[i],new:R[n[i]]},w[i]=R[n[i]];return Z.writeUInt16(1),Z.writeUInt16(0),Z.writeUInt32(12),Z.writeUInt16(0),Z.writeUInt16(262),Z.writeUInt16(0),Z.write(w),{charMap:c,subtable:Z.data,maxGlyphID:N+1};case"unicode":for(D=[],g=[],I=0,R={},s={},C=u=null,q=0,je=l.length;q<je;q++)R[J=n[i=l[q]]]==null&&(R[J]=++I),s[i]={old:J,new:R[J]},m=R[J]-i,C!=null&&m===u||(C&&g.push(C),D.push(i),u=m),C=i;for(C&&g.push(C),g.push(65535),D.push(65535),K=2*(H=D.length),z=2*Math.pow(Math.log(H)/Math.LN2,2),p=Math.log(z/2)/Math.LN2,G=2*H-z,d=[],T=[],y=[],b=ne=0,V=D.length;ne<V;
vendor: 8,871 bytes, line 3920
3920b=++ne){if(L=D[b],f=g[b],L===65535){d.push(0),T.push(0);break}if(L-(M=s[L].new)>=32768)for(d.push(0),T.push(2*(y.length+H-b)),i=ae=L;L<=f?ae<=f:ae>=f;i=L<=f?++ae:--ae)y.push(s[i].new);else d.push(M-L),T.push(0)}for(Z.writeUInt16(3),Z.writeUInt16(1),Z.writeUInt32(12),Z.writeUInt16(4),Z.writeUInt16(16+8*H+2*y.length),Z.writeUInt16(0),Z.writeUInt16(K),Z.writeUInt16(z),Z.writeUInt16(p),Z.writeUInt16(G),ge=0,$=g.length;ge<$;ge++)i=g[ge],Z.writeUInt16(i);for(Z.writeUInt16(0),de=0,F=D.length;de<F;de++)i=D[de],Z.writeUInt16(i);for(Re=0,P=d.length;Re<P;Re++)m=d[Re],Z.writeUInt16(m);for(Ee=0,ue=T.length;Ee<ue;Ee++)_=T[Ee],Z.writeUInt16(_);for(Be=0,me=y.length;Be<me;Be++)N=y[Be],Z.writeUInt16(N);return{charMap:s,subtable:Z.data,maxGlyphID:I+1}}},t})(),OE=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="cmap",n.prototype.parse=function(a){var s,i,c;for(a.pos=this.offset,this.version=a.readUInt16(),c=a.readUInt16(),this.tables=[],this.unicode=null,i=0;0<=c?i<c:i>c;i=0<=c?++i:--i)s=new a_(a,this.offset),this.tables.push(s),s.isUnicode&&this.unicode==null&&(this.unicode=s);return!0},n.encode=function(a,s){var i,c;return s==null&&(s="macroman"),i=a_.encode(a,s),(c=new Gu).writeUInt16(0),c.writeUInt16(1),i.table=c.data.concat(i.subtable),i},n})(),QF=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="hhea",n.prototype.parse=function(a){return a.pos=this.offset,this.version=a.readInt(),this.ascender=a.readShort(),this.decender=a.readShort(),this.lineGap=a.readShort(),this.advanceWidthMax=a.readShort(),this.minLeftSideBearing=a.readShort(),this.minRightSideBearing=a.readShort(),this.xMaxExtent=a.readShort(),this.caretSlopeRise=a.readShort(),this.caretSlopeRun=a.readShort(),this.caretOffset=a.readShort(),a.pos+=8,this.metricDataFormat=a.readShort(),this.numberOfMetrics=a.readUInt16()},n})(),JF=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="OS/2",n.prototype.parse=function(a){if(a.pos=this.offset,this.version=a.readUInt16(),this.averageCharWidth=a.readShort(),this.weightClass=a.readUInt16(),this.widthClass=a.readUInt16(),this.type=a.readShort(),this.ySubscriptXSize=a.readShort(),this.ySubscriptYSize=a.readShort(),this.ySubscriptXOffset=a.readShort(),this.ySubscriptYOffset=a.readShort(),this.ySuperscriptXSize=a.readShort(),this.ySuperscriptYSize=a.readShort(),this.ySuperscriptXOffset=a.readShort(),this.ySuperscriptYOffset=a.readShort(),this.yStrikeoutSize=a.readShort(),this.yStrikeoutPosition=a.readShort(),this.familyClass=a.readShort(),this.panose=(function(){var s,i;for(i=[],s=0;s<10;++s)i.push(a.readByte());return i})(),this.charRange=(function(){var s,i;for(i=[],s=0;s<4;++s)i.push(a.readInt());return i})(),this.vendorID=a.readString(4),this.selection=a.readShort(),this.firstCharIndex=a.readShort(),this.lastCharIndex=a.readShort(),this.version>0&&(this.ascent=a.readShort(),this.descent=a.readShort(),this.lineGap=a.readShort(),this.winAscent=a.readShort(),this.winDescent=a.readShort(),this.codePageRange=(function(){var s,i;for(i=[],s=0;s<2;s=++s)i.push(a.readInt());return i})(),this.version>1))return this.xHeight=a.readShort(),this.capHeight=a.readShort(),this.defaultChar=a.readShort(),this.breakChar=a.readShort(),this.maxContext=a.readShort()},n})(),KF=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="post",n.prototype.parse=function(a){var s,i,c;switch(a.pos=this.offset,this.format=a.readInt(),this.italicAngle=a.readInt(),this.underlinePosition=a.readShort(),this.underlineThickness=a.readShort(),this.isFixedPitch=a.readInt(),this.minMemType42=a.readInt(),this.maxMemType42=a.readInt(),this.minMemType1=a.readInt(),this.maxMemType1=a.readInt(),this.format){case 65536:break;case 131072:var l;for(i=a.readUInt16(),this.glyphNameIndex=[],l=0;0<=i?l<i:l>i;l=0<=i?++l:--l)this.glyphNameIndex.push(a.readUInt16());for(this.names=[],c=[];a.pos<this.offset+this.length;)s=a.readByte(),c.push(this.names.push(a.readString(s)));return c;case 151552:return i=a.readUInt16(),this.offsets=a.read(i);case 196608:break;case 262144:return this.map=(function(){var m,d,u;for(u=[],l=m=0,d=this.file.maxp.numGlyphs;0<=d?m<d:m>d;l=0<=d?++m:--m)u.push(a.readUInt32());return u}).call(this)}},n})(),XF=function(t,n){this.raw=t,this.length=t.length,this.platformID=n.platformID,this.encodingID=n.encodingID,this.languageID=n.languageID},ZF=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="name",n.prototype.parse=function(a){var s,i,c,l,m,d,u,f,g,p,y;for(a.pos=this.offset,a.readShort(),s=a.readShort(),d=a.readShort(),i=[],l=0;0<=s?l<s:l>s;l=0<=s?++l:--l)i.push({platformID:a.readShort(),encodingID:a.readShort(),languageID:a.readShort(),nameID:a.readShort(),length:a.readShort(),offset:this.offset+d+a.readShort()});for(u={},l=g=0,p=i.length;g<p;l=++g)c=i[l],a.pos=c.offset,f=a.readString(c.length),m=new XF(f,c),u[y=c.nameID]==null&&(u[y]=[]),u[c.nameID].push(m);this.strings=u,this.copyright=u[0],this.fontFamily=u[1],this.fontSubfamily=u[2],this.uniqueSubfamily=u[3],this.fontName=u[4],this.version=u[5];try{this.postscriptName=u[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g,"")}catch{this.postscriptName=u[4][0].raw.replace(/[\x00-\x19\x80-\xff]/g,"")}return this.trademark=u[7],this.manufacturer=u[8],this.designer=u[9],this.description=u[10],this.vendorUrl=u[11],this.designerUrl=u[12],this.license=u[13],this.licenseUrl=u[14],this.preferredFamily=u[15],this.preferredSubfamily=u[17],this.compatibleFull=u[18],this.sampleText=u[19]},n})(),e7=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="maxp",n.prototype.parse=function(a){return a.pos=this.offset,this.version=a.readInt(),this.numGlyphs=a.readUInt16(),this.maxPoints=a.readUInt16(),this.maxContours=a.readUInt16(),this.maxCompositePoints=a.readUInt16(),this.maxComponentContours=a.readUInt16(),this.maxZones=a.readUInt16(),this.maxTwilightPoints=a.readUInt16(),this.maxStorage=a.readUInt16(),this.maxFunctionDefs=a.readUInt16(),this.maxInstructionDefs=a.readUInt16(),this.maxStackElements=a.readUInt16(),this.maxSizeOfInstructions=a.readUInt16(),this.maxComponentElements=a.readUInt16(),this.maxComponentDepth=a.readUInt16()},n})(),t7=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="hmtx",n.prototype.parse=function(a){var s,i,c,l,m,d,u;for(a.pos=this.offset,this.metrics=[],s=0,d=this.file.hhea.numberOfMetrics;0<=d?s<d:s>d;s=0<=d?++s:--s)this.metrics.push({advance:a.readUInt16(),lsb:a.readInt16()});for(c=this.file.maxp.numGlyphs-this.file.hhea.numberOfMetrics,this.leftSideBearings=(function(){var f,g;for(g=[],s=f=0;0<=c?f<c:f>c;s=0<=c?++f:--f)g.push(a.readInt16());return g})(),this.widths=(function(){var f,g,p,y;for(y=[],f=0,g=(p=this.metrics).length;f<g;f++)l=p[f],y.push(l.advance);return y}).call(this),i=this.widths[this.widths.length-1],u=[],s=m=0;0<=c?m<c:m>c;s=0<=c?++m:--m)u.push(this.widths.push(i));return u},n.prototype.forGlyph=function(a){return a in this.metrics?this.metrics[a]:{advance:this.metrics[this.metrics.length-1].advance,lsb:this.leftSideBearings[a-this.metrics.length]}},n})(),LE=[].slice,n7=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return Gl(n,yl),n.prototype.tag="glyf",n.prototype.parse=function(){return this.cache={}},n.prototype.glyphFor=function(a){var s,i,c,l,m,d,u,f,g,p;return a in this.cache?this.cache[a]:(l=this.file.loca,s=this.file.contents,i=l.indexOf(a),(c=l.lengthOf(a))===0?this.cache[a]=null:(s.pos=this.offset+i,m=(d=new Gu(s.read(c))).readShort(),f=d.readShort(),p=d.readShort(),u=d.readShort(),g=d.readShort(),this.cache[a]=m===-1?new s7(d,f,p,u,g):new a7(d,m,f,p,u,g),this.cache[a]))},n.prototype.encode=function(a,s,i){var c,l,m,d,u;for(m=[],l=[],d=0,u=s.length;d<u;d++)c=a[s[d]],l.push(m.length),c&&(m=m.concat(c.encode(i)));return l.push(m.length),{table:m,offsets:l}},n})(),a7=(function(){function t(n,a,s,i,c,l){this.raw=n,this.numberOfContours=a,this.xMin=s,this.yMin=i,this.xMax=c,this.yMax=l,this.compound=!1}return t.prototype.encode=function(){return this.raw.data},t})(),s7=(function(){function t(n,a,s,i,c){var l,m;for(this.raw=n,this.xMin=a,this.yMin=s,this.xMax=i,this.yMax=c,this.compound=!0,this.glyphIDs=[],this.glyphOffsets=[],l=this.raw;m=l.readShort(),this.glyphOffsets.push(l.pos),this.glyphIDs.push(l.readUInt16()),32&m;)l.pos+=1&m?4:2,128&m?l.pos+=8:64&m?l.pos+=4:8&m&&(l.pos+=2)}return t.prototype.encode=function(){var n,a,s;for(a=new Gu(LE.call(this.raw.data)),n=0,s=this.glyphIDs.length;n<s;++n)a.pos=this.glyphOffsets[n];return a.data},t})(),r7=(function(t){function n(){return n.__super__.constructor.apply(this,arguments)}
3920return Gl(n,yl),n.prototype.tag="loca",n.prototype.parse=function(a){var s,i;return a.pos=this.offset,s=this.file.head.indexToLocFormat,this.offsets=s===0?(function(){var c,l;for(l=[],i=0,c=this.length;i<c;i+=2)l.push(2*a.readUInt16());return l}).call(this):(function(){var c,l;for(l=[],i=0,c=this.length;i<c;i+=4)l.push(a.readUInt32());return l}).call(this)},n.prototype.indexOf=function(a){return this.offsets[a]},n.prototype.lengthOf=function(a){return this.offsets[a+1]-this.offsets[a]},n.prototype.encode=function(a,s){for(var i=new Uint32Array(this.offsets.length),c=0,l=0,m=0;m<i.length;++m)if(i[m]=c,l<s.length&&s[l]==m){++l,i[m]=c;var d=this.offsets[m],u=this.offsets[m+1]-d;u>0&&(c+=u)}for(var f=new Array(4*i.length),g=0;g<i.length;++g)f[4*g+3]=255&i[g],f[4*g+2]=(65280&i[g])>>8,f[4*g+1]=(16711680&i[g])>>16,f[4*g]=(4278190080&i[g])>>24;return f},n})(),i7=(function(){function t(n){this.font=n,this.subset={},this.unicodes={},this.next=33}return t.prototype.generateCmap=function(){var n,a,s,i,c;for(a in i=this.font.cmap.tables[0].codeMap,n={},c=this.subset)s=c[a],n[a]=i[s];return n},t.prototype.glyphsFor=function(n){var a,s,i,c,l,m,d;for(i={},l=0,m=n.length;l<m;l++)i[c=n[l]]=this.font.glyf.glyphFor(c);for(c in a=[],i)(s=i[c])!=null&&s.compound&&a.push.apply(a,s.glyphIDs);if(a.length>0)for(c in d=this.glyphsFor(a))s=d[c],i[c]=s;return i},t.prototype.encode=function(n,a){var s,i,c,l,m,d,u,f,g,p,y,b,N,w,C;for(i in s=OE.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(n),y={0:0},C=s.charMap)y[(d=C[i]).old]=d.new;for(b in p=s.maxGlyphID,l)b in y||(y[b]=p++);return f=(function(R){var I,_;for(I in _={},R)_[R[I]]=I;return _})(y),g=Object.keys(f).sort((function(R,I){return R-I})),N=(function(){var R,I,_;for(_=[],R=0,I=g.length;R<I;R++)m=g[R],_.push(f[m]);return _})(),c=this.font.glyf.encode(l,N,y),u=this.font.loca.encode(c.offsets,N),w={cmap:this.font.cmap.raw(),glyf:c.table,loca:u,hmtx:this.font.hmtx.raw(),hhea:this.font.hhea.raw(),maxp:this.font.maxp.raw(),post:this.font.post.raw(),name:this.font.name.raw(),head:this.font.head.encode(a)},this.font.os2.exists&&(w["OS/2"]=this.font.os2.raw()),this.font.directory.encode(w)},t})();Ra.API.PDFObject=(function(){var t;function n(){}return t=function(a,s){return(Array(s+1).join("0")+a).slice(-s)},n.convert=function(a){var s,i,c,l;if(Array.isArray(a))return"["+(function(){var m,d,u;for(u=[],m=0,d=a.length;m<d;m++)s=a[m],u.push(n.convert(s));return u})().join(" ")+"]";if(typeof a=="string")return"/"+a;if(a!=null&&a.isString)return"("+a+")";if(a instanceof Date)return"(D:"+t(a.getUTCFullYear(),4)+t(a.getUTCMonth(),2)+t(a.getUTCDate(),2)+t(a.getUTCHours(),2)+t(a.getUTCMinutes(),2)+t(a.getUTCSeconds(),2)+"Z)";if({}.toString.call(a)==="[object Object]"){for(i in c=["<<"],a)l=a[i],c.push("/"+i+" "+n.convert(l));return c.push(">>"),c.join(` 3921`)}return""+a},n})();const o7=Object.freeze(Object.defineProperty({__proto__:null,AcroForm:LF,AcroFormAppearance:La,AcroFormButton:Pi,AcroFormCheckBox:tg,AcroFormChoiceField:Th,AcroFormComboBox:$h,AcroFormEditBox:Zf,AcroFormListBox:Mh,AcroFormPasswordField:ng,AcroFormPushButton:eg,AcroFormRadioButton:Oh,AcroFormTextField:Mu,GState:jg,ShadingPattern:Cu,TilingPattern:Ih,default:Ra,jsPDF:Ra},Symbol.toStringTag,{value:"Module"}));var sb={exports:{}};const c7=sR(o7);/*! 3922 * 3923 * jsPDF AutoTable plugin v3.8.4 3924 * 3925 * Copyright (c) 2024 Simon Bengtsson, https://github.com/simonbengtsson/jsPDF-AutoTable 3926 * Licensed under the MIT License. 3927 * http://opensource.org/licenses/mit-license 3928 * 3929 */var s_=sb.exports,r_;function l7(){return r_||(r_=1,(function(t,n){(function(s,i){t.exports=i((function(){try{return c7}catch{}})())})(typeof globalThis<"u"?globalThis:typeof s_<"u"?s_:typeof window<"u"?window:typeof self<"u"?self:aR,function(a){return(function(){var s={172:(function(m,d){var u=this&&this.__extends||(function(){var p=function(y,b){return p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(N,w){N.__proto__=w}||function(N,w){for(var C in w)Object.prototype.hasOwnProperty.call(w,C)&&(N[C]=w[C])},p(y,b)};return function(y,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");p(y,b);function N(){this.constructor=y}
3929y.prototype=b===null?Object.create(b):(N.prototype=b.prototype,new N)}})();Object.defineProperty(d,"__esModule",{value:!0}),d.CellHookData=d.HookData=void 0;var f=(function(){function p(y,b,N){this.table=b,this.pageNumber=b.pageNumber,this.pageCount=this.pageNumber,this.settings=b.settings,this.cursor=N,this.doc=y.getDocument()}return p})();d.HookData=f;var g=(function(p){u(y,p);function y(b,N,w,C,R,I){var _=p.call(this,b,N,I)||this;return _.cell=w,_.row=C,_.column=R,_.section=C.section,_}return y})(f);d.CellHookData=g}),340:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0});var f=u(4),g=u(136),p=u(744),y=u(776),b=u(664),N=u(972);function w(C){C.API.autoTable=function(){for(var R=[],I=0;I<arguments.length;I++)R[I]=arguments[I];var _;R.length===1?_=R[0]:(console.error("Use of deprecated autoTable initiation"),_=R[2]||{},_.columns=R[0],_.body=R[1]);var J=(0,y.parseInput)(this,_),T=(0,N.createTable)(this,J);return(0,b.drawTable)(this,T),this},C.API.lastAutoTable=!1,C.API.previousAutoTable=!1,C.API.autoTable.previous=!1,C.API.autoTableText=function(R,I,_,J){(0,g.default)(R,I,_,J,this)},C.API.autoTableSetDefaults=function(R){return p.DocHandler.setDefaults(R,this),this},C.autoTableSetDefaults=function(R,I){p.DocHandler.setDefaults(R,I)},C.API.autoTableHtmlToJson=function(R,I){var _;if(I===void 0&&(I=!1),typeof window>"u")return console.error("Cannot run autoTableHtmlToJson in non browser environment"),null;var J=new p.DocHandler(this),T=(0,f.parseHtml)(J,R,window,I,!1),G=T.head,z=T.body,H=((_=G[0])===null||_===void 0?void 0:_.map(function(K){return K.content}))||[];return{columns:H,rows:z,data:z}},C.API.autoTableEndPosY=function(){console.error("Use of deprecated function: autoTableEndPosY. Use doc.lastAutoTable.finalY instead.");var R=this.lastAutoTable;return R&&R.finalY?R.finalY:0},C.API.autoTableAddPageContent=function(R){return console.error("Use of deprecated function: autoTableAddPageContent. Use jsPDF.autoTableSetDefaults({didDrawPage: () => {}}) instead."),C.API.autoTable.globalDefaults||(C.API.autoTable.globalDefaults={}),C.API.autoTable.globalDefaults.addPageContent=R,this},C.API.autoTableAddPage=function(){return console.error("Use of deprecated function: autoTableAddPage. Use doc.addPage()"),this.addPage(),this}}d.default=w}),136:(function(m,d){Object.defineProperty(d,"__esModule",{value:!0});function u(f,g,p,y,b){y=y||{};var N=1.15,w=b.internal.scaleFactor,C=b.internal.getFontSize()/w,R=b.getLineHeightFactor?b.getLineHeightFactor():N,I=C*R,_=/\r\n|\r|\n/g,J="",T=1;if((y.valign==="middle"||y.valign==="bottom"||y.halign==="center"||y.halign==="right")&&(J=typeof f=="string"?f.split(_):f,T=J.length||1),p+=C*(2-N),y.valign==="middle"?p-=T/2*I:y.valign==="bottom"&&(p-=T*I),y.halign==="center"||y.halign==="right"){var G=C;if(y.halign==="center"&&(G*=.5),J&&T>=1){for(var z=0;z<J.length;z++)b.text(J[z],g-b.getStringUnitWidth(J[z])*G,p),p+=I;return b}g-=b.getStringUnitWidth(f)*G}return y.halign==="justify"?b.text(f,g,p,{maxWidth:y.maxWidth||100,align:"justify"}):b.text(f,g,p),b}d.default=u}),420:(function(m,d){Object.defineProperty(d,"__esModule",{value:!0}),d.getPageAvailableWidth=d.parseSpacing=d.getFillStyle=d.addTableBorder=d.getStringWidth=void 0;function u(b,N,w){w.applyStyles(N,!0);var C=Array.isArray(b)?b:[b],R=C.map(function(I){return w.getTextWidth(I)}).reduce(function(I,_){return Math.max(I,_)},0);return R}d.getStringWidth=u;function f(b,N,w,C){var R=N.settings.tableLineWidth,I=N.settings.tableLineColor;b.applyStyles({lineWidth:R,lineColor:I});var _=g(R,!1);_&&b.rect(w.x,w.y,N.getWidth(b.pageSize().width),C.y-w.y,_)}d.addTableBorder=f;function g(b,N){var w=b>0,C=N||N===0;return w&&C?"DF":w?"S":C?"F":null}d.getFillStyle=g;function p(b,N){var w,C,R,I;if(b=b||N,Array.isArray(b)){if(b.length>=4)return{top:b[0],right:b[1],bottom:b[2],left:b[3]};if(b.length===3)return{top:b[0],right:b[1],bottom:b[2],left:b[1]};if(b.length===2)return{top:b[0],right:b[1],bottom:b[0],left:b[1]};b.length===1?b=b[0]:b=N}return typeof b=="object"?(typeof b.vertical=="number"&&(b.top=b.vertical,b.bottom=b.vertical),typeof b.horizontal=="number"&&(b.right=b.horizontal,b.left=b.horizontal),{left:(w=b.left)!==null&&w!==void 0?w:N,top:(C=b.top)!==null&&C!==void 0?C:N,right:(R=b.right)!==null&&R!==void 0?R:N,bottom:(I=b.bottom)!==null&&I!==void 0?I:N}):(typeof b!="number"&&(b=N),{top:b,right:b,bottom:b,left:b})}d.parseSpacing=p;
3929function y(b,N){var w=p(N.settings.margin,0);return b.pageSize().width-(w.left+w.right)}d.getPageAvailableWidth=y}),796:(function(m,d){var u=this&&this.__extends||(function(){var y=function(b,N){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,C){w.__proto__=C}||function(w,C){for(var R in C)Object.prototype.hasOwnProperty.call(C,R)&&(w[R]=C[R])},y(b,N)};return function(b,N){if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");y(b,N);function w(){this.constructor=b}b.prototype=N===null?Object.create(N):(w.prototype=N.prototype,new w)}})();Object.defineProperty(d,"__esModule",{value:!0}),d.getTheme=d.defaultStyles=d.HtmlRowInput=void 0;var f=(function(y){u(b,y);function b(N){var w=y.call(this)||this;return w._element=N,w}return b})(Array);d.HtmlRowInput=f;function g(y){return{font:"helvetica",fontStyle:"normal",overflow:"linebreak",fillColor:!1,textColor:20,halign:"left",valign:"top",fontSize:10,cellPadding:5/y,lineColor:200,lineWidth:0,cellWidth:"auto",minCellHeight:0,minCellWidth:0}}d.defaultStyles=g;function p(y){var b={striped:{table:{fillColor:255,textColor:80,fontStyle:"normal"},head:{textColor:255,fillColor:[41,128,185],fontStyle:"bold"},body:{},foot:{textColor:255,fillColor:[41,128,185],fontStyle:"bold"},alternateRow:{fillColor:245}},grid:{table:{fillColor:255,textColor:80,fontStyle:"normal",lineWidth:.1},head:{textColor:255,fillColor:[26,188,156],fontStyle:"bold",lineWidth:0},body:{},foot:{textColor:255,fillColor:[26,188,156],fontStyle:"bold",lineWidth:0},alternateRow:{}},plain:{head:{fontStyle:"bold"},foot:{fontStyle:"bold"}}};return b[y]}d.getTheme=p}),903:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.parseCss=void 0;var f=u(420);function g(w,C,R,I,_){var J={},T=1.3333333333333333,G=y(C,function(Y){return _.getComputedStyle(Y).backgroundColor});G!=null&&(J.fillColor=G);var z=y(C,function(Y){return _.getComputedStyle(Y).color});z!=null&&(J.textColor=z);var H=N(I,R);H&&(J.cellPadding=H);var K="borderTopColor",L=T*R,D=I.borderTopWidth;if(I.borderBottomWidth===D&&I.borderRightWidth===D&&I.borderLeftWidth===D){var M=(parseFloat(D)||0)/L;M&&(J.lineWidth=M)}else J.lineWidth={top:(parseFloat(I.borderTopWidth)||0)/L,right:(parseFloat(I.borderRightWidth)||0)/L,bottom:(parseFloat(I.borderBottomWidth)||0)/L,left:(parseFloat(I.borderLeftWidth)||0)/L},J.lineWidth.top||(J.lineWidth.right?K="borderRightColor":J.lineWidth.bottom?K="borderBottomColor":J.lineWidth.left&&(K="borderLeftColor"));var Z=y(C,function(Y){return _.getComputedStyle(Y)[K]});Z!=null&&(J.lineColor=Z);var fe=["left","right","center","justify"];fe.indexOf(I.textAlign)!==-1&&(J.halign=I.textAlign),fe=["middle","bottom","top"],fe.indexOf(I.verticalAlign)!==-1&&(J.valign=I.verticalAlign);var q=parseInt(I.fontSize||"");isNaN(q)||(J.fontSize=q/T);var ne=p(I);ne&&(J.fontStyle=ne);var ae=(I.fontFamily||"").toLowerCase();return w.indexOf(ae)!==-1&&(J.font=ae),J}d.parseCss=g;function p(w){var C="";return(w.fontWeight==="bold"||w.fontWeight==="bolder"||parseInt(w.fontWeight)>=700)&&(C="bold"),(w.fontStyle==="italic"||w.fontStyle==="oblique")&&(C+="italic"),C}function y(w,C){var R=b(w,C);if(!R)return null;var I=R.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d*))?\)$/);if(!I||!Array.isArray(I))return null;var _=[parseInt(I[1]),parseInt(I[2]),parseInt(I[3])],J=parseInt(I[4]);return J===0||isNaN(_[0])||isNaN(_[1])||isNaN(_[2])?null:_}function b(w,C){var R=C(w);return R==="rgba(0, 0, 0, 0)"||R==="transparent"||R==="initial"||R==="inherit"?w.parentElement==null?null:b(w.parentElement,C):R}function N(w,C){var R=[w.paddingTop,w.paddingRight,w.paddingBottom,w.paddingLeft],I=96/(72/C),_=(parseInt(w.lineHeight)-parseInt(w.fontSize))/C/2,J=R.map(function(G){return parseInt(G||"0")/I}),T=(0,f.parseSpacing)(J,0);return _>T.top&&(T.top=_),_>T.bottom&&(T.bottom=_),T}}),744:(function(m,d){Object.defineProperty(d,"__esModule",{value:!0}),d.DocHandler=void 0;var u={},f=(function(){function g(p){this.jsPDFDocument=p,this.userStyles={textColor:p.getTextColor?this.jsPDFDocument.getTextColor():0,fontSize:p.internal.getFontSize(),fontStyle:p.internal.getFont().fontStyle,font:p.internal.getFont().fontName,lineWidth:p.getLineWidth?this.jsPDFDocument.getLineWidth():0,lineColor:p.getDrawColor?this.jsPDFDocument.getDrawColor():0}}return g.setDefaults=function(p,y){y===void 0&&(y=null),y?y.__autoTableDocumentDefaults=p:u=p},g.unifyColor=function(p){return Array.isArray(p)?p:typeof p=="number"?[p,p,p]:typeof p=="string"?[p]:null},g.prototype.applyStyles=function(p,y){var b,N,w;y===void 0&&(y=!1),p.fontStyle&&this.jsPDFDocument.setFontStyle&&this.jsPDFDocument.setFontStyle(p.fontStyle);var C=this.jsPDFDocument.internal.getFont(),R=C.fontStyle,I=C.fontName;if(p.font&&(I=p.font),p.fontStyle){R=p.fontStyle;
3929var _=this.getFontList()[I];_&&_.indexOf(R)===-1&&(this.jsPDFDocument.setFontStyle&&this.jsPDFDocument.setFontStyle(_[0]),R=_[0])}if(this.jsPDFDocument.setFont(I,R),p.fontSize&&this.jsPDFDocument.setFontSize(p.fontSize),!y){var J=g.unifyColor(p.fillColor);J&&(b=this.jsPDFDocument).setFillColor.apply(b,J),J=g.unifyColor(p.textColor),J&&(N=this.jsPDFDocument).setTextColor.apply(N,J),J=g.unifyColor(p.lineColor),J&&(w=this.jsPDFDocument).setDrawColor.apply(w,J),typeof p.lineWidth=="number"&&this.jsPDFDocument.setLineWidth(p.lineWidth)}},g.prototype.splitTextToSize=function(p,y,b){return this.jsPDFDocument.splitTextToSize(p,y,b)},g.prototype.rect=function(p,y,b,N,w){return this.jsPDFDocument.rect(p,y,b,N,w)},g.prototype.getLastAutoTable=function(){return this.jsPDFDocument.lastAutoTable||null},g.prototype.getTextWidth=function(p){return this.jsPDFDocument.getTextWidth(p)},g.prototype.getDocument=function(){return this.jsPDFDocument},g.prototype.setPage=function(p){this.jsPDFDocument.setPage(p)},g.prototype.addPage=function(){return this.jsPDFDocument.addPage()},g.prototype.getFontList=function(){return this.jsPDFDocument.getFontList()},g.prototype.getGlobalOptions=function(){return u||{}},g.prototype.getDocumentOptions=function(){return this.jsPDFDocument.__autoTableDocumentDefaults||{}},g.prototype.pageSize=function(){var p=this.jsPDFDocument.internal.pageSize;return p.width==null&&(p={width:p.getWidth(),height:p.getHeight()}),p},g.prototype.scaleFactor=function(){return this.jsPDFDocument.internal.scaleFactor},g.prototype.getLineHeightFactor=function(){var p=this.jsPDFDocument;return p.getLineHeightFactor?p.getLineHeightFactor():1.15},g.prototype.getLineHeight=function(p){return p/this.scaleFactor()*this.getLineHeightFactor()},g.prototype.pageNumber=function(){var p=this.jsPDFDocument.internal.getCurrentPageInfo();return p?p.pageNumber:this.jsPDFDocument.internal.getNumberOfPages()},g})();d.DocHandler=f}),4:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.parseHtml=void 0;var f=u(903),g=u(796);function p(N,w,C,R,I){var _,J;R===void 0&&(R=!1),I===void 0&&(I=!1);var T;typeof w=="string"?T=C.document.querySelector(w):T=w;var G=Object.keys(N.getFontList()),z=N.scaleFactor(),H=[],K=[],L=[];if(!T)return console.error("Html table could not be found with input: ",w),{head:H,body:K,foot:L};for(var D=0;D<T.rows.length;D++){var M=T.rows[D],Z=(J=(_=M==null?void 0:M.parentElement)===null||_===void 0?void 0:_.tagName)===null||J===void 0?void 0:J.toLowerCase(),fe=y(G,z,C,M,R,I);fe&&(Z==="thead"?H.push(fe):Z==="tfoot"?L.push(fe):K.push(fe))}return{head:H,body:K,foot:L}}d.parseHtml=p;function y(N,w,C,R,I,_){for(var J=new g.HtmlRowInput(R),T=0;T<R.cells.length;T++){var G=R.cells[T],z=C.getComputedStyle(G);if(I||z.display!=="none"){var H=void 0;_&&(H=(0,f.parseCss)(N,G,w,z,C)),J.push({rowSpan:G.rowSpan,colSpan:G.colSpan,styles:H,_element:G,content:b(G)})}}var K=C.getComputedStyle(R);if(J.length>0&&(I||K.display!=="none"))return J}function b(N){var w=N.cloneNode(!0);return w.innerHTML=w.innerHTML.replace(/\n/g,"").replace(/ +/g," "),w.innerHTML=w.innerHTML.split(/<br.*?>/).map(function(C){return C.trim()}).join(` 3930`),w.innerText||w.textContent||""}}),776:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.parseInput=void 0;var f=u(4),g=u(356),p=u(420),y=u(744),b=u(792);function N(T,G){var z=new y.DocHandler(T),H=z.getDocumentOptions(),K=z.getGlobalOptions();(0,b.default)(z,K,H,G);var L=(0,g.assign)({},K,H,G),D;typeof window<"u"&&(D=window);var M=w(K,H,G),Z=C(K,H,G),fe=R(z,L),q=_(z,L,D);return{id:G.tableId,content:q,hooks:Z,styles:M,settings:fe}}d.parseInput=N;function w(T,G,z){for(var H={styles:{},headStyles:{},bodyStyles:{},footStyles:{},alternateRowStyles:{},columnStyles:{}},K=function(Z){if(Z==="columnStyles"){var fe=T[Z],q=G[Z],ne=z[Z];H.columnStyles=(0,g.assign)({},fe,q,ne)}else{var ae=[T,G,z],Y=ae.map(function(je){return je[Z]||{}});H[Z]=(0,g.assign)({},Y[0],Y[1],Y[2])}},L=0,D=Object.keys(H);L<D.length;L++){var M=D[L];K(M)}return H}function C(T,G,z){for(var H=[T,G,z],K={didParseCell:[],willDrawCell:[],didDrawCell:[],willDrawPage:[],didDrawPage:[]},L=0,D=H;L<D.length;L++){var M=D[L];M.didParseCell&&K.didParseCell.push(M.didParseCell),M.willDrawCell&&K.willDrawCell.push(M.willDrawCell),M.didDrawCell&&K.didDrawCell.push(M.didDrawCell),M.willDrawPage&&K.willDrawPage.push(M.willDrawPage),M.didDrawPage&&K.didDrawPage.push(M.didDrawPage)}return K}function R(T,G){var z,H,K,L,D,M,Z,fe,q,ne,ae,Y,je=(0,p.parseSpacing)(G.margin,40/T.scaleFactor()),V=(z=I(T,G.startY))!==null&&z!==void 0?z:je.top,$;G.showFoot===!0?$="everyPage":G.showFoot===!1?$="never":$=(H=G.showFoot)!==null&&H!==void 0?H:"everyPage";var F;
3930G.showHead===!0?F="everyPage":G.showHead===!1?F="never":F=(K=G.showHead)!==null&&K!==void 0?K:"everyPage";var P=(L=G.useCss)!==null&&L!==void 0?L:!1,ue=G.theme||(P?"plain":"striped"),me=!!G.horizontalPageBreak,ge=(D=G.horizontalPageBreakRepeat)!==null&&D!==void 0?D:null;return{includeHiddenHtml:(M=G.includeHiddenHtml)!==null&&M!==void 0?M:!1,useCss:P,theme:ue,startY:V,margin:je,pageBreak:(Z=G.pageBreak)!==null&&Z!==void 0?Z:"auto",rowPageBreak:(fe=G.rowPageBreak)!==null&&fe!==void 0?fe:"auto",tableWidth:(q=G.tableWidth)!==null&&q!==void 0?q:"auto",showHead:F,showFoot:$,tableLineWidth:(ne=G.tableLineWidth)!==null&&ne!==void 0?ne:0,tableLineColor:(ae=G.tableLineColor)!==null&&ae!==void 0?ae:200,horizontalPageBreak:me,horizontalPageBreakRepeat:ge,horizontalPageBreakBehaviour:(Y=G.horizontalPageBreakBehaviour)!==null&&Y!==void 0?Y:"afterAllRows"}}function I(T,G){var z=T.getLastAutoTable(),H=T.scaleFactor(),K=T.pageNumber(),L=!1;if(z&&z.startPageNumber){var D=z.startPageNumber+z.pageNumber-1;L=D===K}return typeof G=="number"?G:(G==null||G===!1)&&L&&(z==null?void 0:z.finalY)!=null?z.finalY+20/H:null}function _(T,G,z){var H=G.head||[],K=G.body||[],L=G.foot||[];if(G.html){var D=G.includeHiddenHtml;if(z){var M=(0,f.parseHtml)(T,G.html,z,D,G.useCss)||{};H=M.head||H,K=M.body||H,L=M.foot||H}else console.error("Cannot parse html in non browser environment")}var Z=G.columns||J(H,K,L);return{columns:Z,head:H,body:K,foot:L}}function J(T,G,z){var H=T[0]||G[0]||z[0]||[],K=[];return Object.keys(H).filter(function(L){return L!=="_element"}).forEach(function(L){var D=1,M;Array.isArray(H)?M=H[parseInt(L)]:M=H[L],typeof M=="object"&&!Array.isArray(M)&&(D=(M==null?void 0:M.colSpan)||1);for(var Z=0;Z<D;Z++){var fe=void 0;Array.isArray(H)?fe=K.length:fe=L+(Z>0?"_".concat(Z):"");var q={dataKey:fe};K.push(q)}}),K}}),792:(function(m,d){Object.defineProperty(d,"__esModule",{value:!0});function u(g,p,y,b){for(var N=function(I){I&&typeof I!="object"&&console.error("The options parameter should be of type object, is: "+typeof I),typeof I.extendWidth<"u"&&(I.tableWidth=I.extendWidth?"auto":"wrap",console.error("Use of deprecated option: extendWidth, use tableWidth instead.")),typeof I.margins<"u"&&(typeof I.margin>"u"&&(I.margin=I.margins),console.error("Use of deprecated option: margins, use margin instead.")),I.startY&&typeof I.startY!="number"&&(console.error("Invalid value for startY option",I.startY),delete I.startY),!I.didDrawPage&&(I.afterPageContent||I.beforePageContent||I.afterPageAdd)&&(console.error("The afterPageContent, beforePageContent and afterPageAdd hooks are deprecated. Use didDrawPage instead"),I.didDrawPage=function(L){g.applyStyles(g.userStyles),I.beforePageContent&&I.beforePageContent(L),g.applyStyles(g.userStyles),I.afterPageContent&&I.afterPageContent(L),g.applyStyles(g.userStyles),I.afterPageAdd&&L.pageNumber>1&&L.afterPageAdd(L),g.applyStyles(g.userStyles)}),["createdHeaderCell","drawHeaderRow","drawRow","drawHeaderCell"].forEach(function(L){I[L]&&console.error('The "'.concat(L,'" hook has changed in version 3.0, check the changelog for how to migrate.'))}),[["showFoot","showFooter"],["showHead","showHeader"],["didDrawPage","addPageContent"],["didParseCell","createdCell"],["headStyles","headerStyles"]].forEach(function(L){var D=L[0],M=L[1];I[M]&&(console.error("Use of deprecated option ".concat(M,". Use ").concat(D," instead")),I[D]=I[M])}),[["padding","cellPadding"],["lineHeight","rowHeight"],"fontSize","overflow"].forEach(function(L){var D=typeof L=="string"?L:L[0],M=typeof L=="string"?L:L[1];typeof I[D]<"u"&&(typeof I.styles[M]>"u"&&(I.styles[M]=I[D]),console.error("Use of deprecated option: "+D+", use the style "+M+" instead."))});for(var _=0,J=["styles","bodyStyles","headStyles","footStyles"];_<J.length;_++){var T=J[_];f(I[T]||{})}for(var G=I.columnStyles||{},z=0,H=Object.keys(G);z<H.length;z++){var K=H[z];f(G[K]||{})}},w=0,C=[p,y,b];w<C.length;w++){var R=C[w];N(R)}}d.default=u;function f(g){g.rowHeight?(console.error("Use of deprecated style rowHeight. It is renamed to minCellHeight."),g.minCellHeight||(g.minCellHeight=g.rowHeight)):g.columnWidth&&(console.error("Use of deprecated style columnWidth. It is renamed to cellWidth."),g.cellWidth||(g.cellWidth=g.columnWidth))}}),260:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.Column=d.Cell=d.Row=d.Table=void 0;var f=u(796),g=u(172),p=u(420),y=(function(){function C(R,I){this.pageNumber=1,this.pageCount=1,this.id=R.id,this.settings=R.settings,this.styles=R.styles,this.hooks=R.hooks,this.columns=I.columns,this.head=I.head,this.body=I.body,this.foot=I.foot}return C.prototype.getHeadHeight=function(R){return this.head.reduce(function(I,_){return I+_.getMaxCellHeight(R)},0)},C.prototype.getFootHeight=function(R){return this.foot.reduce(function(I,_){return I+_.getMaxCellHeight(R)},0)},C.prototype.allRows=function(){return this.head.concat(this.body).concat(this.foot)},C.prototype.callCellHooks=function(R,I,_,J,T,G){for(var z=0,H=I;z<H.length;z++){var K=H[z],L=new g.CellHookData(R,this,_,J,T,G),D=K(L)===!1;if(_.text=Array.isArray(_.text)?_.text:[_.text],D)return!1}return!0},C.prototype.callEndPageHooks=function(R,I){R.applyStyles(R.userStyles);for(var _=0,J=this.hooks.didDrawPage;_<J.length;_++){var T=J[_];T(new g.HookData(R,this,I))}},C.prototype.callWillDrawPageHooks=function(R,I){for(var _=0,J=this.hooks.willDrawPage;_<J.length;_++){var T=J[_];T(new g.HookData(R,this,I))}},C.prototype.getWidth=function(R){if(typeof this.settings.tableWidth=="number")return this.settings.tableWidth;if(this.settings.tableWidth==="wrap"){var I=this.columns.reduce(function(J,T){return J+T.wrappedWidth},0);return I}else{var _=this.settings.margin;return R-_.left-_.right}},C})();d.Table=y;var b=(function(){function C(R,I,_,J,T){T===void 0&&(T=!1),this.height=0,this.raw=R,R instanceof f.HtmlRowInput&&(this.raw=R._element,this.element=R._element),this.index=I,this.section=_,this.cells=J,this.spansMultiplePages=T}return C.prototype.getMaxCellHeight=function(R){var I=this;return R.reduce(function(_,J){var T;return Math.max(_,((T=I.cells[J.index])===null||T===void 0?void 0:T.height)||0)},0)},C.prototype.hasRowSpan=function(R){var I=this;return R.filter(function(_){var J=I.cells[_.index];return J?J.rowSpan>1:!1}).length>0},C.prototype.canEntireRowFit=function(R,I){return this.getMaxCellHeight(I)<=R},C.prototype.getMinimumRowHeight=function(R,I){var _=this;return R.reduce(function(J,T){var G=_.cells[T.index];if(!G)return 0;var z=I.getLineHeight(G.styles.fontSize),H=G.padding("vertical"),K=H+z;return K>J?K:J},0)},C})();d.Row=b;var N=(function(){function C(R,I,_){var J,T;this.contentHeight=0,this.contentWidth=0,this.wrappedWidth=0,this.minReadableWidth=0,this.minWidth=0,this.width=0,this.height=0,this.x=0,this.y=0,this.styles=I,this.section=_,this.raw=R;var G=R;R!=null&&typeof R=="object"&&!Array.isArray(R)?(this.rowSpan=R.rowSpan||1,this.colSpan=R.colSpan||1,G=(T=(J=R.content)!==null&&J!==void 0?J:R.title)!==null&&T!==void 0?T:R,R._element&&(this.raw=R._element)):(this.rowSpan=1,this.colSpan=1);var z=G!=null?""+G:"",H=/\r\n|\r|\n/g;this.text=z.split(H)}return C.prototype.getTextPos=function(){var R;if(this.styles.valign==="top")R=this.y+this.padding("top");else if(this.styles.valign==="bottom")R=this.y+this.height-this.padding("bottom");else{var I=this.height-this.padding("vertical");R=this.y+I/2+this.padding("top")}var _;if(this.styles.halign==="right")_=this.x+this.width-this.padding("right");else if(this.styles.halign==="center"){var J=this.width-this.padding("horizontal");_=this.x+J/2+this.padding("left")}else _=this.x+this.padding("left");return{x:_,y:R}},C.prototype.getContentHeight=function(R,I){I===void 0&&(I=1.15);var _=Array.isArray(this.text)?this.text.length:1,J=this.styles.fontSize/R*I,T=_*J+this.padding("vertical");return Math.max(T,this.styles.minCellHeight)},C.prototype.padding=function(R){var I=(0,p.parseSpacing)(this.styles.cellPadding,0);return R==="vertical"?I.top+I.bottom:R==="horizontal"?I.left+I.right:I[R]},C})();d.Cell=N;var w=(function(){function C(R,I,_){this.wrappedWidth=0,this.minReadableWidth=0,this.minWidth=0,this.width=0,this.dataKey=R,this.raw=I,this.index=_}return C.prototype.getMaxCustomCellWidth=function(R){for(var I=0,_=0,J=R.allRows();_<J.length;_++){var T=J[_],G=T.cells[this.index];G&&typeof G.styles.cellWidth=="number"&&(I=Math.max(I,G.styles.cellWidth))}return I},C})();d.Column=w}),356:(function(m,d){Object.defineProperty(d,"__esModule",{value:!0}),d.assign=void 0;function u(f,g,p,y,b){if(f==null)throw new TypeError("Cannot convert undefined or null to object");for(var N=Object(f),w=1;w<arguments.length;w++){var C=arguments[w];if(C!=null)for(var R in C)Object.prototype.hasOwnProperty.call(C,R)&&(N[R]=C[R])}return N}d.assign=u}),972:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.createTable=void 0;var f=u(744),g=u(260),p=u(324),y=u(796),b=u(356);function N(T,G){var z=new f.DocHandler(T),H=w(G,z.scaleFactor()),K=new g.Table(G,H);return(0,p.calculateWidths)(z,K),z.applyStyles(z.userStyles),K}d.createTable=N;function w(T,G){var z=T.content,H=_(z.columns);
3930if(z.head.length===0){var K=R(H,"head");K&&z.head.push(K)}if(z.foot.length===0){var K=R(H,"foot");K&&z.foot.push(K)}var L=T.settings.theme,D=T.styles;return{columns:H,head:C("head",z.head,H,D,L,G),body:C("body",z.body,H,D,L,G),foot:C("foot",z.foot,H,D,L,G)}}function C(T,G,z,H,K,L){var D={},M=G.map(function(Z,fe){for(var q=0,ne={},ae=0,Y=0,je=0,V=z;je<V.length;je++){var $=V[je];if(D[$.index]==null||D[$.index].left===0)if(Y===0){var F=void 0;Array.isArray(Z)?F=Z[$.index-ae-q]:F=Z[$.dataKey];var P={};typeof F=="object"&&!Array.isArray(F)&&(P=(F==null?void 0:F.styles)||{});var ue=J(T,$,fe,K,H,L,P),me=new g.Cell(F,ue,T);ne[$.dataKey]=me,ne[$.index]=me,Y=me.colSpan-1,D[$.index]={left:me.rowSpan-1,times:Y}}else Y--,ae++;else D[$.index].left--,Y=D[$.index].times,q++}return new g.Row(Z,fe,T,ne)});return M}function R(T,G){var z={};return T.forEach(function(H){if(H.raw!=null){var K=I(G,H.raw);K!=null&&(z[H.dataKey]=K)}}),Object.keys(z).length>0?z:null}function I(T,G){if(T==="head"){if(typeof G=="object")return G.header||G.title||null;if(typeof G=="string"||typeof G=="number")return G}else if(T==="foot"&&typeof G=="object")return G.footer;return null}function _(T){return T.map(function(G,z){var H,K,L;return typeof G=="object"?L=(K=(H=G.dataKey)!==null&&H!==void 0?H:G.key)!==null&&K!==void 0?K:z:L=z,new g.Column(L,G,z)})}function J(T,G,z,H,K,L,D){var M=(0,y.getTheme)(H),Z;T==="head"?Z=K.headStyles:T==="body"?Z=K.bodyStyles:T==="foot"&&(Z=K.footStyles);var fe=(0,b.assign)({},M.table,M[T],K.styles,Z),q=K.columnStyles[G.dataKey]||K.columnStyles[G.index]||{},ne=T==="body"?q:{},ae=T==="body"&&z%2===0?(0,b.assign)({},M.alternateRow,K.alternateRowStyles):{},Y=(0,y.defaultStyles)(L),je=(0,b.assign)({},Y,fe,ae,ne);return(0,b.assign)(je,D)}}),664:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.addPage=d.drawTable=void 0;var f=u(420),g=u(260),p=u(744),y=u(356),b=u(136),N=u(224);function w(q,ne){var ae=ne.settings,Y=ae.startY,je=ae.margin,V={x:je.left,y:Y},$=ne.getHeadHeight(ne.columns)+ne.getFootHeight(ne.columns),F=Y+je.bottom+$;if(ae.pageBreak==="avoid"){var P=ne.body,ue=P.reduce(function(de,Pe){return de+Pe.height},0);F+=ue}var me=new p.DocHandler(q);(ae.pageBreak==="always"||ae.startY!=null&&F>me.pageSize().height)&&(fe(me),V.y=je.top),ne.callWillDrawPageHooks(me,V);var ge=(0,y.assign)({},V);ne.startPageNumber=me.pageNumber(),ae.horizontalPageBreak?C(me,ne,ge,V):(me.applyStyles(me.userStyles),(ae.showHead==="firstPage"||ae.showHead==="everyPage")&&ne.head.forEac
3930h(function(de){return K(me,ne,de,V,ne.columns)}),me.applyStyles(me.userStyles),ne.body.forEach(function(de,Pe){var Re=Pe===ne.body.length-1;H(me,ne,de,Re,ge,V,ne.columns)}),me.applyStyles(me.userStyles),(ae.showFoot==="lastPage"||ae.showFoot==="everyPage")&&ne.foot.forEach(function(de){return K(me,ne,de,V,ne.columns)})),(0,f.addTableBorder)(me,ne,ge,V),ne.callEndPageHooks(me,V),ne.finalY=V.y,q.lastAutoTable=ne,q.previousAutoTable=ne,q.autoTable&&(q.autoTable.previous=ne),me.applyStyles(me.userStyles)}d.drawTable=w;function C(q,ne,ae,Y){var je=(0,N.calculateAllColumnsCanFitInPage)(q,ne),V=ne.settings;if(V.horizontalPageBreakBehaviour==="afterAllRows")je.forEach(function(ue,me){q.applyStyles(q.userStyles),me>0?Z(q,ne,ae,Y,ue.columns,!0):R(q,ne,Y,ue.columns),I(q,ne,ae,Y,ue.columns),J(q,ne,Y,ue.columns)});else for(var $=-1,F=je[0],P=function(){var ue=$;if(F){q.applyStyles(q.userStyles);var me=F.columns;$>=0?Z(q,ne,ae,Y,me,!0):R(q,ne,Y,me),ue=_(q,ne,$+1,Y,me),J(q,ne,Y,me)}var ge=ue-$;je.slice(1).forEach(function(de){q.applyStyles(q.userStyles),Z(q,ne,ae,Y,de.columns,!0),_(q,ne,$+1,Y,de.columns,ge),J(q,ne,Y,de.columns)}),$=ue};$<ne.body.length-1;)P()}function R(q,ne,ae,Y){var je=ne.settings;q.applyStyles(q.userStyles),(je.showHead==="firstPage"||je.showHead==="everyPage")&&ne.head.forEac
3930h(function(V){return K(q,ne,V,ae,Y)})}function I(q,ne,ae,Y,je){q.applyStyles(q.userStyles),ne.body.forEach(function(V,$){var F=$===ne.body.length-1;H(q,ne,V,F,ae,Y,je)})}function _(q,ne,ae,Y,je,V){q.applyStyles(q.userStyles),V=V??ne.body.length;var $=Math.min(ae+V,ne.body.length),F=-1;return ne.body.slice(ae,$).forEach(function(P,ue){var me=ae+ue===ne.body.length-1,ge=M(q,ne,me,Y);P.canEntireRowFit(ge,je)&&(K(q,ne,P,Y,je),F=ae+ue)}),F}function J(q,ne,ae,Y){var je=ne.settings;q.applyStyles(q.userStyles),(je.showFoot==="lastPage"||je.showFoot==="everyPage")&&ne.foot.forEach(function(V){return K(q,ne,V,ae,Y)})}function T(q,ne,ae){var Y=ae.getLineHeight(q.styles.fontSize),je=q.padding("vertical"),V=Math.floor((ne-je)/Y);return Math.max(0,V)}function G(q,ne,ae,Y){var je={};q.spansMultiplePages=!0,q.height=0;for(var V=0,$=0,F=ae.columns;$<F.length;$++){var P=F[$],ue=q.cells[P.index];if(ue){Array.isArray(ue.text)||(ue.text=[ue.text]);var me=new g.Cell(ue.raw,ue.styles,ue.section);me=(0,y.assign)(me,ue),me.text=[];var ge=T(ue,ne,Y);ue.text.length>ge&&(me.text=ue.text.splice(ge,ue.text.length));var de=Y.scaleFactor(),Pe=Y.getLineHeightFactor();ue.contentHeight=ue.getContentHeight(de,Pe),ue.contentHeight>=ne&&(ue.contentHeight=ne,me.styles.minCellHeight-=ne),ue.contentHeight>q.height&&(q.height=ue.contentHeight),me.contentHeight=me.getContentHeight(de,Pe),me.contentHeight>V&&(V=me.contentHeight),je[P.index]=me}}var Re=new g.Row(q.raw,-1,q.section,je,!0);Re.height=V;for(var Ee=0,Be=ae.columns;Ee<Be.length;Ee++){var P=Be[Ee],me=Re.cells[P.index];me&&(me.height=Re.height);var ue=q.cells[P.index];ue&&(ue.height=q.height)}return Re}function z(q,ne,ae,Y){var je=q.pageSize().height,V=Y.settings.margin,$=V.top+V.bottom,F=je-$;ne.section==="body"&&(F-=Y.getHeadHeight(Y.columns)+Y.getFootHeight(Y.columns));var P=ne.getMinimumRowHeight(Y.columns,q),ue=P<ae;if(P>F)return console.error("Will not be able to print row ".concat(ne.index," correctly since it's minimum height is larger than page height")),!0;if(!ue)return!1;var me=ne.hasRowSpan(Y.columns),ge=ne.getMaxCellHeight(Y.columns)>F;return ge?(me&&console.error("The content of row ".concat(ne.index," will not be drawn correctly since drawing rows with a height larger than the page height and has cells with rowspans is not supported.")),!0):!(me||Y.settings.rowPageBreak==="avoid")}function H(q,ne,ae,Y,je,V,$){var F=M(q,ne,Y,V);if(ae.canEntireRowFit(F,$))K(q,ne,ae,V,$);else if(z(q,ae,F,ne)){var P=G(ae,F,ne,q);K(q,ne,ae,V,$),Z(q,ne,je,V,$),H(q,ne,P,Y,je,V,$)}else Z(q,ne,je,V,$),H(q,ne,ae,Y,je,V,$)}function K(q,ne,ae,Y,je){Y.x=ne.settings.margin.left;for(var V=0,$=je;V<$.length;V++){var F=$[V],P=ae.cells[F.index];if(!P){Y.x+=F.width;continue}q.applyStyles(P.styles),P.x=Y.x,P.y=Y.y;var ue=ne.callCellHooks(q,ne.hooks.willDrawCell,P,ae,F,Y);if(ue===!1){Y.x+=F.width;continue}L(q,P,Y);var me=P.getTextPos();(0,b.default)(P.text,me.x,me.y,{halign:P.styles.halign,valign:P.styles.valign,maxWidth:Math.ceil(P.width-P.padding("left")-P.padding("right"))},q.getDocument()),ne.callCellHooks(q,ne.hooks.didDrawCell,P,ae,F,Y),Y.x+=F.width}Y.y+=ae.height}function L(q,ne,ae){var Y=ne.styles;if(q.getDocument().setFillColor(q.getDocument().getFillColor()),typeof Y.lineWidth=="number"){var je=(0,f.getFillStyle)(Y.lineWidth,Y.fillColor);je&&q.rect(ne.x,ae.y,ne.width,ne.height,je)}else typeof Y.lineWidth=="object"&&(Y.fillColor&&q.rect(ne.x,ae.y,ne.width,ne.height,"F"),D(q,ne,ae,Y.lineWidth))}function D(q,ne,ae,Y){var je,V,$,F;Y.top&&(je=ae.x,V=ae.y,$=ae.x+ne.width,F=ae.y,Y.right&&($+=.5*Y.right),Y.left&&(je-=.5*Y.left),P(Y.top,je,V,$,F)),Y.bottom&&(je=ae.x,V=ae.y+ne.height,$=ae.x+ne.width,F=ae.y+ne.height,Y.right&&($+=.5*Y.right),Y.left&&(je-=.5*Y.left),P(Y.bottom,je,V,$,F)),Y.left&&(je=ae.x,V=ae.y,$=ae.x,F=ae.y+ne.height,Y.top&&(V-=.5*Y.top),Y.bottom&&(F+=.5*Y.bottom),P(Y.left,je,V,$,F)),Y.right&&(je=ae.x+ne.width,V=ae.y,$=ae.x+ne.width,F=ae.y+ne.height,Y.top&&(V-=.5*Y.top),Y.bottom&&(F+=.5*Y.bottom),P(Y.right,je,V,$,F));function P(ue,me,ge,de,Pe){q.getDocument().setLineWidth(ue),q.getDocument().line(me,ge,de,Pe,"S")}}function M(q,ne,ae,Y){var je=ne.settings.margin.bottom,V=ne.settings.showFoot;return(V==="everyPage"||V==="lastPage"&&ae)&&(je+=ne.getFootHeight(ne.columns)),q.pageSize().height-Y.y-je}function Z(q,ne,ae,Y,je,V){je===void 0&&(je=[]),V===void 0&&(V=!1),q.applyStyles(q.userStyles),ne.settings.showFoot==="everyPage"&&!V&&ne.foot.forEach(function(F){return K(q,ne,F,Y,je)}),ne.callEndPageHooks(q,Y);var $=ne.settings.margin;
3930(0,f.addTableBorder)(q,ne,ae,Y),fe(q),ne.pageNumber++,ne.pageCount++,Y.x=$.left,Y.y=$.top,ae.y=$.top,ne.callWillDrawPageHooks(q,Y),ne.settings.showHead==="everyPage"&&(ne.head.forEach(function(F){return K(q,ne,F,Y,je)}),q.applyStyles(q.userStyles))}d.addPage=Z;function fe(q){var ne=q.pageNumber();q.setPage(ne+1);var ae=q.pageNumber();return ae===ne?(q.addPage(),!0):!1}}),224:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.calculateAllColumnsCanFitInPage=void 0;var f=u(420);function g(y,b,N){var w;N===void 0&&(N={});var C=(0,f.getPageAvailableWidth)(y,b),R=new Map,I=[],_=[],J=[];b.settings.horizontalPageBreakRepeat,Array.isArray(b.settings.horizontalPageBreakRepeat)?J=b.settings.horizontalPageBreakRepeat:(typeof b.settings.horizontalPageBreakRepeat=="string"||typeof b.settings.horizontalPageBreakRepeat=="number")&&(J=[b.settings.horizontalPageBreakRepeat]),J.forEach(function(H){var K=b.columns.find(function(L){return L.dataKey===H||L.index===H});K&&!R.has(K.index)&&(R.set(K.index,!0),I.push(K.index),_.push(b.columns[K.index]),C-=K.wrappedWidth)});for(var T=!0,G=(w=N==null?void 0:N.start)!==null&&w!==void 0?w:0;G<b.columns.length;){if(R.has(G)){G++;continue}var z=b.columns[G].wrappedWidth;if(T||C>=z)T=!1,I.push(G),_.push(b.columns[G]),C-=z;else break;G++}return{colIndexes:I,columns:_,lastIndex:G-1}}function p(y,b){for(var N=[],w=0;w<b.columns.length;w++){var C=g(y,b,{start:w});C.columns.length&&(N.push(C),w=C.lastIndex)}return N}d.calculateAllColumnsCanFitInPage=p}),324:(function(m,d,u){Object.defineProperty(d,"__esModule",{value:!0}),d.ellipsize=d.resizeColumns=d.calculateWidths=void 0;var f=u(420);function g(I,_){p(I,_);var J=[],T=0;_.columns.forEach(function(z){var H=z.getMaxCustomCellWidth(_);H?z.width=H:(z.width=z.wrappedWidth,J.push(z)),T+=z.width});var G=_.getWidth(I.pageSize().width)-T;G&&(G=y(J,G,function(z){return Math.max(z.minReadableWidth,z.minWidth)})),G&&(G=y(J,G,function(z){return z.minWidth})),G=Math.abs(G),!_.settings.horizontalPageBreak&&G>.1/I.scaleFactor()&&(G=G<1?G:Math.round(G),console.warn("Of the table content, ".concat(G," units width could not fit page"))),N(_),w(_,I),b(_)}d.calculateWidths=g;function p(I,_){var J=I.scaleFactor(),T=_.settings.horizontalPageBreak,G=(0,f.getPageAvailableWidth)(I,_);_.allRows().forEach(function(z){for(var H=0,K=_.columns;H<K.length;H++){var L=K[H],D=z.cells[L.index];if(D){var M=_.hooks.didParseCell;_.callCellHooks(I,M,D,z,L,null);var Z=D.padding("horizontal");D.contentWidth=(0,f.getStringWidth)(D.text,D.styles,I)+Z;var fe=(0,f.getStringWidth)(D.text.join(" ").split(/[^\S\u00A0]+/),D.styles,I);if(D.minReadableWidth=fe+D.padding("horizontal"),typeof D.styles.cellWidth=="number")D.minWidth=D.styles.cellWidth,D.wrappedWidth=D.styles.cellWidth;else if(D.styles.cellWidth==="wrap"||T===!0)D.contentWidth>G?(D.minWidth=G,D.wrappedWidth=G):(D.minWidth=D.contentWidth,D.wrappedWidth=D.contentWidth);else{var q=10/J;D.minWidth=D.styles.minCellWidth||q,D.wrappedWidth=D.contentWidth,D.minWidth>D.wrappedWidth&&(D.wrappedWidth=D.minWidth)}}}}),_.allRows().forEach(function(z){for(var H=0,K=_.columns;H<K.length;H++){var L=K[H],D=z.cells[L.index];if(D&&D.colSpan===1)L.wrappedWidth=Math.max(L.wrappedWidth,D.wrappedWidth),L.minWidth=Math.max(L.minWidth,D.minWidth),L.minReadableWidth=Math.max(L.minReadableWidth,D.minReadableWidth);else{var M=_.styles.columnStyles[L.dataKey]||_.styles.columnStyles[L.index]||{},Z=M.cellWidth||M.minCellWidth;Z&&typeof Z=="number"&&(L.minWidth=Z,L.wrappedWidth=Z)}D&&(D.colSpan>1&&!L.minWidth&&(L.minWidth=D.minWidth),D.colSpan>1&&!L.wrappedWidth&&(L.wrappedWidth=D.minWidth))}})}function y(I,_,J){for(var T=_,G=I.reduce(function(q,ne){return q+ne.wrappedWidth},0),z=0;z<I.length;z++){var H=I[z],K=H.wrappedWidth/G,L=T*K,D=H.width+L,M=J(H),Z=D<M?M:D;_-=Z-H.width,H.width=Z}if(_=Math.round(_*1e10)/1e10,_){var fe=I.filter(function(q){return _<0?q.width>J(q):!0});fe.length&&(_=y(fe,_,J))}return _}d.resizeColumns=y;function b(I){for(var _={},J=1,T=I.allRows(),G=0;G<T.length;G++)for(var z=T[G],H=0,K=I.columns;H<K.length;H++){var L=K[H],D=_[L.index];if(J>1)J--,delete z.cells[L.index];else if(D)D.cell.height+=z.height,J=D.cell.colSpan,delete z.cells[L.index],D.left--,D.left<=1&&delete _[L.index];else{var M=z.cells[L.index];if(!M)continue;if(M.height=z.height,M.rowSpan>1){var Z=T.length-G,fe=M.rowSpan>Z?Z:M.rowSpan;
3930_[L.index]={cell:M,left:fe,row:z}}}}}function N(I){for(var _=I.allRows(),J=0;J<_.length;J++)for(var T=_[J],G=null,z=0,H=0,K=0;K<I.columns.length;K++){var L=I.columns[K];if(H-=1,H>1&&I.columns[K+1])z+=L.width,delete T.cells[L.index];else if(G){var D=G;delete T.cells[L.index],G=null,D.width=L.width+z}else{var D=T.cells[L.index];if(!D)continue;if(H=D.colSpan,z=0,D.colSpan>1){G=D,z+=L.width;continue}D.width=L.width+z}}}function w(I,_){for(var J={count:0,height:0},T=0,G=I.allRows();T<G.length;T++){for(var z=G[T],H=0,K=I.columns;H<K.length;H++){var L=K[H],D=z.cells[L.index];if(D){_.applyStyles(D.styles,!0);var M=D.width-D.padding("horizontal");if(D.styles.overflow==="linebreak")D.text=_.splitTextToSize(D.text,M+1/_.scaleFactor(),{fontSize:D.styles.fontSize});else if(D.styles.overflow==="ellipsize")D.text=C(D.text,M,D.styles,_,"...");else if(D.styles.overflow==="hidden")D.text=C(D.text,M,D.styles,_,"");else if(typeof D.styles.overflow=="function"){var Z=D.styles.overflow(D.text,M);typeof Z=="string"?D.text=[Z]:D.text=Z}D.contentHeight=D.getContentHeight(_.scaleFactor(),_.getLineHeightFactor());var fe=D.contentHeight/D.rowSpan;D.rowSpan>1&&J.count*J.height<fe*D.rowSpan?J={height:fe,count:D.rowSpan}:J&&J.count>0&&J.height>fe&&(fe=J.height),fe>z.height&&(z.height=fe)}}J.count--}}function C(I,_,J,T,G){return I.map(function(z){return R(z,_,J,T,G)})}d.ellipsize=C;function R(I,_,J,T,G){var z=1e4*T.scaleFactor();if(_=Math.ceil(_*z)/z,_>=(0,f.getStringWidth)(I,J,T))return I;for(;_<(0,f.getStringWidth)(I+G,J,T)&&!(I.length<=1);)I=I.substring(0,I.length-1);return I.trim()+G}}),964:(function(m){if(typeof a>"u"){var d=new Error("Cannot find module 'undefined'");throw d.code="MODULE_NOT_FOUND",d}m.exports=a})},i={};function c(m){var d=i[m];if(d!==void 0)return d.exports;var u=i[m]={exports:{}};return s[m].call(u.exports,u,u.exports,c),u.exports}var l={};return(function(){var m=l;Object.defineProperty(m,"__esModule",{value:!0}),m.Cell=m.Column=m.Row=m.Table=m.CellHookData=m.__drawTable=m.__createTable=m.applyPlugin=void 0;var d=c(340),u=c(776),f=c(664),g=c(972),p=c(260);Object.defineProperty(m,"Table",{enumerable:!0,get:function(){return p.Table}});var y=c(172);Object.defineProperty(m,"CellHookData",{enumerable:!0,get:function(){return y.CellHookData}});var b=c(260);Object.defineProperty(m,"Cell",{enumerable:!0,get:function(){return b.Cell}}),Object.defineProperty(m,"Column",{enumerable:!0,get:function(){return b.Column}}),Object.defineProperty(m,"Row",{enumerable:!0,get:function(){return b.Row}});function N(_){(0,d.default)(_)}m.applyPlugin=N;function w(_,J){var T=(0,u.parseInput)(_,J),G=(0,g.createTable)(_,T);(0,f.drawTable)(_,G)}function C(_,J){var T=(0,u.parseInput)(_,J);return(0,g.createTable)(_,T)}m.__createTable=C;function R(_,J){(0,f.drawTable)(_,J)}m.__drawTable=R;try{var I=c(964);I.jsPDF&&(I=I.jsPDF),N(I)}catch{}m.default=w})(),l})()})})(sb)),sb.exports}var d7=l7();const oi=Ub(d7);async function fc(t){const n=await mn(re(ie,`companies/${t}`)),a=n.exists()?n.val():{};let s="",i="";try{const c=await mn(re(ie,"companyDirectory"));c.exists()&&Object.values(c.val()).some(l=>(l==null?void 0:l.id)!==t?!1:(s=String((l==null?void 0:l.name)||""),i=String((l==null?void 0:l.logoUrl)||""),!0))}catch(c){console.warn("Company directory branding fallback unavailable:",c)}return{name:String((a==null?void 0:a.name)||s||""),logoUrl:String((a==null?void 0:a.logoUrl)||i||"")}}async function u7(t,n){await yn(re(ie,`companies/${t}`),{logoUrl:n,updatedAt:Date.now()});try{const a=await mn(re(ie,"companyDirectory"));if(!a.exists())return;const s={};Object.entries(a.val()).forEach(([i,c])=>{(c==null?void 0:c.id)===t&&(s[`companyDirectory/${i}/logoUrl`]=n)}),Object.keys(s).length&&await yn(re(ie),s)}catch(a){console.warn("Company directory logo sync skipped:",a)}}const Dc=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,h7=t=>`BDT ${Number(t||0).toLocaleString("en-US",{maximumFractionDigits:2})}`,rb=()=>{const t=new Date,n=a=>String(a).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`},ar=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g," ").trim(),G1=t=>Array.isArray(t)?t:t&&typeof t=="object"?Object.values(t):[],uc=t=>String(t??""),xj=t=>G1(t.packages).map(n=>({...n,id:uc(n==null?void 0:n.id),name:uc(n==null?void 0:n.name),rewardDescription:uc(n==null?void 0:n.rewardDescription),items:G1(n==null?void 0:n.items)})),gu=t=>
3930t.endDate<rb()?"expired":t.status,jj=(t,n=!1)=>gu(t)==="expired"?"Expired":t.status==="pending"?"Pending Approval":t.status==="rejected"?"Rejected":t.status==="cancelled"?"Cancelled":t.status==="merged"?"Merged to Multi-Package":n?"Achieved":"Active";function m7({profile:t}){const[n,a]=x.useState({}),[s,i]=x.useState([]),[c,l]=x.useState({}),[m,d]=x.useState(""),[u,f]=x.useState(""),[g,p]=x.useState("amount"),[y,b]=x.useState(""),[N,w]=x.useState(""),[C,R]=x.useState([]),[I,_]=x.useState([]),[J,T]=x.useState(""),[G,z]=x.useState(""),[H,K]=x.useState(""),[L,D]=x.useState([]),[M,Z]=x.useState(""),[fe,q]=x.useState(""),[ne,ae]=x.useState(""),[Y,je]=x.useState(""),[V,$]=x.useState(""),[F,P]=x.useState("1"),[ue,me]=x.useState("highest"),[ge,de]=x.useState(""),[Pe,Re]=x.useState(rb()),[Ee,Be]=x.useState(""),[We,it]=x.useState(""),[_e,ee]=x.useState(""),[qe,se]=x.useState(!1),[pe,Se]=x.useState(""),[Me,ot]=x.useState(""),[wt,ct]=x.useState(""),[Ce,De]=x.useState(""),[Te,ce]=x.useState(""),[Ye,Je]=x.useState([]),[le,nt]=x.useState({}),[xt,te]=x.useState({}),[Ge,pt]=x.useState({}),[$e,st]=x.useState(""),[Nt,be]=x.useState(""),[jt,bt]=x.useState(""),[tn,B]=x.useState(""),[xe,tt]=x.useState(""),[ht,dt]=x.useState(""),[we,rt]=x.useState(""),[St,Qt]=x.useState(rb()),[gn,An]=x.useState("ledger_adjustment"),[Sn,Xt]=x.useState(""),[Wt,Gt]=x.useState(""),[$t,Vt]=x.useState(""),sn=["owner","admin","super_admin"].includes(t.role),on=sa(t,"promotion.manage");x.useEffect(()=>qt(re(ie,`inventoryProducts/${t.companyId}`),oe=>a(oe.val()||{})),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierPromotions/${t.companyId}`),oe=>{const Ve=oe.val()||{};i(Object.entries(Ve).map(([he,Oe])=>({id:he,...Oe})).sort((he,Oe)=>Oe.createdAt-he.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierPromotionRevisions/${t.companyId}`),oe=>nt(oe.val()||{})),[t.companyId]);const ke=oe=>Object.values(le).find(Ve=>Ve.promotionId===oe&&Ve.status==="pending");x.useEffect(()=>qt(re(ie,`supplierPromotionApplications/${t.companyId}`),oe=>l(oe.val()||{})),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierPromotionOpeningAchievements/${t.companyId}`),oe=>te(oe.val()||{})),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierPromotionRewardSettlements/${t.companyId}`),oe=>pt(oe.val()||{})),[t.companyId]);const Ct=oe=>Object.values(xt).filter(Ve=>Ve.promotionId===oe&&Ve.status==="approved"),Et=(oe,Ve)=>{const he=Object.values(c[oe.id]||{}),Oe=Ct(oe.id),ut=[];if(Number(Ve.targetAmount||0)>0){const At=he.reduce((en,It)=>en+Number(It.contributionAmount||0),0)+Oe.reduce((en,It)=>en+Number(It.amount||0),0);ut.push(At/Number(Ve.targetAmount))}for(const At of G1(Ve.items)){const en=ar(At.productName||""),It=he.reduce((Pt,Jn)=>{var na,Mn;return Pt+Number(((na=Jn.productContributions)==null?void 0:na[At.productId])||((Mn=Jn.productContributions)==null?void 0:Mn[`name:${en}`])||0)},0)+Oe.reduce((Pt,Jn)=>{var na,Mn;return Pt+Number(((na=Jn.productContributions)==null?void 0:na[At.productId])||((Mn=Jn.productContributions)==null?void 0:Mn[`name:${en}`])||0)},0);ut.push(At.requiredQty>0?It/At.requiredQty:0)}return ut.length?Math.min(...ut):0},Rt=x.useMemo(()=>{const oe={};for(const Ve of s){const he=Object.values(c[Ve.id]||{}),Oe=Ct(Ve.id);if(Ve.targetType==="tiered"){const ut=xj(Ve).map(At=>Et(Ve,At));if(Ve.rewardMode==="repeatable")oe[Ve.id]=ut.reduce((At,en)=>At+Math.floor(Math.max(0,en)),0);else if(Ve.rewardMode==="cumulative")oe[Ve.id]=ut.filter(At=>At>=1).length;else{let At=0;ut.forEach((en,It)=>{en>=1&&(At=It+1)}),oe[Ve.id]=At}}else if(Ve.targetType==="bundle"){const ut=Ve.bundleItems||[];oe[Ve.id]=ut.length?Math.min(...ut.map(At=>{const en=ar(At.productName||""),It=he.reduce((Pt,Jn)=>{var na,Mn;return Pt+Number(((na=Jn.productContributions)==null?void 0:na[At.productId])||((Mn=Jn.productContributions)==null?void 0:Mn[`name:${en}`])||0)},0)+Oe.reduce((Pt,Jn)=>{var na,Mn;return Pt+Number(((na=Jn.productContributions)==null?void 0:na[At.productId])||((Mn=Jn.productContributions)==null?void 0:Mn[`name:${en}`])||0)},0);return At.requiredQty>0?It/At.requiredQty:0})):0}else if(Ve.targetType==="mix"){const ut=new Set;for(const At of Ve.mixProducts||[]){At.productId&&ut.add(At.productId);const en=ar(At.productName||"");en&&ut.add(`name:${en}`)}oe[Ve.id]=he.reduce((At,en)=>
3930At+Object.entries(en.productContributions||{}).reduce((It,[Pt,Jn])=>It+(ut.has(Pt)?Number(Jn||0):0),0),0)+Oe.reduce((At,en)=>At+Object.entries(en.productContributions||{}).reduce((It,[Pt,Jn])=>It+(ut.has(Pt)?Number(Jn||0):0),0),0)}else if(Ve.targetType==="quantity"&&(Ve.productId||Ve.productName)){const ut=ar(Ve.productName||"");oe[Ve.id]=he.reduce((At,en)=>{var It,Pt;return At+Number(((It=en.productContributions)==null?void 0:It[Ve.productId||""])||((Pt=en.productContributions)==null?void 0:Pt[`name:${ut}`])||0)},0)+Oe.reduce((At,en)=>{var It,Pt;return At+Number(((It=en.productContributions)==null?void 0:It[Ve.productId||""])||((Pt=en.productContributions)==null?void 0:Pt[`name:${ut}`])||0)},0)}else oe[Ve.id]=he.reduce((ut,At)=>ut+(Ve.targetType==="amount"?Number(At.contributionAmount||0):Number(At.contributionQty||0)),0)+Oe.reduce((ut,At)=>ut+(Ve.targetType==="amount"?Number(At.amount||0):Number(At.qty||0)),0)}return oe},[s,c,xt]);x.useMemo(()=>Object.entries(n).filter(([,oe])=>(oe==null?void 0:oe.active)!==!1).map(([oe,Ve])=>({id:oe,name:String((Ve==null?void 0:Ve.name)||oe),model:String((Ve==null?void 0:Ve.model)||"")})).sort((oe,Ve)=>oe.name.localeCompare(Ve.name)),[n]);const xn=()=>{const oe=H.trim();if(!oe||C.some(he=>ar(he.productName)===ar(oe)))return;const Ve=`manual_${ar(oe).replace(/ /g,"_")}`;R(he=>[...he,{productId:Ve,productName:oe,requiredQty:1}]),K("")},dn=s.filter(oe=>gu(oe)==="pending"),Ln=s.filter(oe=>gu(oe)==="active");s.filter(oe=>gu(oe)==="expired");const wa=x.useMemo(()=>{const oe=ar(pe);return s.filter(Ve=>Ve.status!=="merged"&&(!oe||ar(uc(Ve.title)).includes(oe)))},[s,pe]),Ca=x.useMemo(()=>{const oe=new Map;for(const Ve of s){if(Ve.status!=="pending"||Ve.targetType!=="amount"||(Rt[Ve.id]||0)!==0)continue;const he=[ar(uc(Ve.title)),Ve.supplierKey||ar(uc(Ve.supplierName)),Ve.startDate,Ve.endDate].join("|");oe.set(he,[...oe.get(he)||[],Ve])}return[...oe.values()].filter(Ve=>Ve.length>=2).map(Ve=>Ve.sort((he,Oe)=>he.targetValue-Oe.targetValue))},[s,Rt]),In=oe=>oe.map((Ve,he)=>({id:`legacy_amount_${Ve.id}`,name:`Package ${he+1} · ${Dc(Ve.targetValue)}`,targetAmount:Ve.targetValue,items:[],rewardDescription:uc(Ve.benefitDescription)})),Sa=oe=>{const Ve=oe[0];ce([ar(uc(Ve.title)),Ve.supplierKey||ar(uc(Ve.supplierName)),Ve.startDate,Ve.endDate].join("|")),Je(In(oe))},aa=(oe,Ve)=>Je(he=>he.map(Oe=>Oe.id===oe?{...Oe,...Ve}:Oe)),$a=(oe,Ve,he)=>{const Oe=Ve.trim(),ut=Number(he||0);aa(oe,{items:Oe||ut>0?[{productId:Oe?`manual_${ar(Oe).replace(/ /g,"_")}`:"",productName:Oe,requiredQty:ut}]:[]})};async function jn(oe,Ve){if(!sn||oe.length<2)return;if(oe.some(Pt=>Pt.status!=="pending"||Pt.targetType!=="amount"||(Rt[Pt.id]||0)!==0))return ee("Only untouched Pending Approval amount promotions can be merged safely.");const he=oe[0],Oe=Date.now(),ut=(Ve||In(oe)).map((Pt,Jn)=>{var Ea;const na=((Ea=Pt.freeProductName)==null?void 0:Ea.trim())||"",Mn=Number(Pt.freeProductQty||0);return{id:Pt.id,name:Pt.name.trim()||`Package ${Jn+1}`,rewardDescription:Pt.rewardDescription.trim(),targetAmount:Number(Pt.targetAmount||0),items:(Pt.items||[]).filter(ga=>ga.productName.trim()&&Number(ga.requiredQty)>0),...na?{freeProductName:na}:{},...Mn>0?{freeProductQty:Mn}:{}}});if(ut.some(Pt=>!(Number(Pt.targetAmount||0)>0)&&!Pt.items.length))return ee("Each package needs an Amount Target or Required Product/Qty.");if(ut.some(Pt=>(Pt.items||[]).some(Jn=>!Jn.productName.trim()||!(Number(Jn.requiredQty)>0))))return ee("Required Product / Model and Required Purchase Qty must be entered together.");if(ut.some(Pt=>!Pt.rewardDescription))return ee("Each package needs a Reward Description before merge.");const en=Ta(re(ie,`supplierPromotions/${t.companyId}`)).key;if(!en)return ee("Could not create merged promotion key.");const It={title:he.title,supplierName:he.supplierName,supplierKey:he.supplierKey||ar(uc(he.supplierName)),targetType:"tiered",targetValue:ut.length,packages:ut,rewardMode:"highest",benefitDescription:`${ut.length} package(s) · ${ut.map(Pt=>Pt.rewardDescription).join(" / ")}`,startDate:he.startDate,endDate:he.endDate,notes:`Converted from ${oe.length} legacy pending amount promotions after Safe Merge Preview/Edit. Original records retained as merged audit history.`,status:"pending",createdAt:Oe,createdByUid:t.uid,createdByName:t.name||t.email||"User"};se(!0);try{const Pt={[`supplierPromotions/${t.companyId}/${en}`]:It};for(const Jn of oe)Pt[`supplierPromotions/${t.companyId}/${Jn.id}/status`]="merged",Pt[`supplierPromotions/${t.companyId}/${Jn.id}/mergedIntoPromotionId`]=en,Pt[`supplierPromotions/${t.companyId}/${Jn.id}/mergedAt`]=Oe,Pt[`supplierPromotions/${t.companyId}/${Jn.id}/mergedByName`]=t.name||t.email||"User";await yn(re(ie),Pt),ce(""),Je([]),ee(`${oe.length}
3930 old pending entries merged into one reviewed Multi-Package promotion. Original rows remain as audit history; approve the new promotion after final review.`)}catch(Pt){ee(`Promotion merge failed: ${(Pt==null?void 0:Pt.message)||Pt}`)}finally{se(!1)}}async function vs(oe){oe.preventDefault();const Ve=g==="bundle"?1:g==="tiered"?L.length:Number(y),he=g==="quantity"?!G.trim():g==="bundle"?!C.length||C.some(Oe=>!Oe.productId||Oe.requiredQty<=0):g==="mix"?!I.length:g==="tiered"?!L.length||L.some(Oe=>!Oe.name.trim()||!Oe.rewardDescription.trim()||!(Number(Oe.targetAmount||0)>0)&&!Oe.items.length||Oe.items.some(ut=>ut.requiredQty<=0)):!1;if(!m.trim()||!u.trim()||!ge.trim()||!Pe||!Ee||!Number.isFinite(Ve)||Ve<=0||he){ee("Complete all required promotion fields with a target greater than zero.");return}if(Ee<Pe){ee("End Date cannot be before Start Date.");return}se(!0);try{const Oe={title:m.trim(),supplierName:u.trim(),supplierKey:ar(u),targetType:g,targetValue:Ve,...g==="quantity"?{productId:`manual_${ar(G.trim()).replace(/ /g,"_")}`,productName:G.trim()}:{},...g==="bundle"?{bundleItems:C}:{},...g==="mix"?{mixProducts:I}:{},...g==="tiered"?{packages:L,rewardMode:ue}:{},benefitDescription:ge.trim(),startDate:Pe,endDate:Ee,notes:We.trim(),status:"pending",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name||t.email||"User"};if(Ce){const ut=s.find(It=>It.id===Ce);if(!ut)throw new Error("Promotion no longer exists.");if(ke(Ce))throw new Error("A revision is already waiting for approval.");const At=Object.values(le).filter(It=>It.promotionId===Ce).length,en=Ta(re(ie,`supplierPromotionRevisions/${t.companyId}`));await Pn(en,{id:en.key,promotionId:Ce,status:"pending",revisionNo:At+1,proposed:{...Oe,status:"active",createdAt:ut.createdAt,createdByUid:ut.createdByUid,createdByName:ut.createdByName},createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name||t.email||"User"}),ee("Promotion revision submitted for re-approval. The currently approved rule remains active until approval.")}else{const ut=Ta(re(ie,`supplierPromotions/${t.companyId}`));await Pn(ut,Oe),ee("Promotion submitted for Owner/Admin/Super Admin approval.")}De(""),d(""),f(""),b(""),w(""),z(""),K(""),R([]),_([]),T(""),D([]),Z(""),q(""),ae(""),je(""),$(""),P("1"),me("highest"),de(""),it("")}catch(Oe){ee(`Promotion submission failed: ${(Oe==null?void 0:Oe.message)||Oe}`)}finally{se(!1)}}function ka(oe){if(ke(oe.id))return ee("This promotion already has a revision waiting for approval.");De(oe.id),d(oe.title),f(oe.supplierName),p(oe.targetType),b(oe.targetType==="amount"||oe.targetType==="quantity"?String(oe.targetValue):""),z(oe.productName||""),R(oe.bundleItems||[]),_(oe.mixProducts||[]),D(oe.packages||[]),me(oe.rewardMode||"highest"),de(oe.benefitDescription),Re(oe.startDate),Be(oe.endDate),it(oe.notes||""),ee(`Editing ${oe.title}. Saving will create a revision and require Owner/Admin approval; the current approved rule stays active.`),window.scrollTo({top:0,behavior:"smooth"})}async function Ja(oe,Ve){if(sn){se(!0);try{const he=Date.now(),Oe=`supplierPromotionRevisions/${t.companyId}/${oe.id}`;if(Ve==="approved"){const ut=oe.proposed;await yn(re(ie),{[`supplierPromotions/${t.companyId}/${oe.promotionId}`]:{...ut,lastRevisionNo:oe.revisionNo,lastRevisedAt:he,lastRevisedByName:oe.createdByName},[`${Oe}/status`]:"approved",[`${Oe}/approvedAt`]:he,[`${Oe}/approvedByName`]:t.name||t.email||"User"}),ee(`Revision V${oe.revisionNo} approved. Promotion progress is recalculated from existing evidence; no Purchase, Stock or Accounting entry is reposted.`)}else await yn(re(ie),{[`${Oe}/status`]:"rejected",[`${Oe}/rejectedAt`]:he,[`${Oe}/rejectedByName`]:t.name||t.email||"User"}),ee(`Revision V${oe.revisionNo} rejected. Current approved promotion remains unchanged.`)}catch(he){ee(`Revision decision failed: ${(he==null?void 0:he.message)||he}`)}finally{se(!1)}}}async function _n(oe,Ve){if(!(!sn||gu(oe)==="expired")){se(!0);try{const he=Date.now(),Oe=`supplierPromotions/${t.companyId}/${oe.id}`;await yn(re(ie),Ve==="active"?{[`${Oe}/status`]:"active",[`${Oe}/approvedAt`]:he,[`${Oe}/approvedByUid`]:t.uid,[`${Oe}/approvedByName`]:t.name||t.email||"User",[`${Oe}/supplierKey`]:ar(uc(oe.supplierName))}:{[`${Oe}/status`]:"rejected",[`${Oe}/rejectedAt`]:he,[`${Oe}/rejectedByUid`]:t.uid,[`${Oe}/rejectedByName`]:t.name||t.email||"User"}),ee(Ve==="active"?"Promotion approved and moved to Active Promotions.":"Promotion rejected.")}catch(he){ee(`Promotion decision failed: ${(he==null?void 0:he.message)||he}`)}finally{se(!1)}}}function ha(oe){const Ve={};for(const he of oe.split(/\n+/)){const Oe=he.trim().match(/^(.+?)\s*[=:|,]\s*([0-9.]+)$/);if(!Oe)continue;const ut=Oe[1].trim(),At=Number(Oe[2]);ut&&At>0&&(Ve[`name:${ar(ut)}`]=(Ve[`name:${ar(ut)}`]||0)+At)}return Ve}async function ta(){const oe=s.find(ut=>ut.id===$e);
3930if(!oe)return ee("Select a promotion for Opening Achievement.");if(!Nt||Nt<oe.startDate||Nt>oe.endDate)return ee("Opening as-of date must be inside the promotion period.");const Ve=Number(jt||0),he=Number(tn||0),Oe=ha(xe);if(Ve<=0&&he<=0&&!Object.keys(Oe).length)return ee("Enter opening amount, quantity, or product-wise quantities.");se(!0);try{const ut=Ta(re(ie,`supplierPromotionOpeningAchievements/${t.companyId}`)),At=ut.key;await Pn(ut,{id:At,promotionId:oe.id,asOfDate:Nt,amount:Ve,qty:he,productContributions:Oe,note:ht.trim(),status:"pending",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name||t.email||"User",stockImpact:!1,accountingImpact:!1}),bt(""),B(""),tt(""),dt(""),ee("Opening Achievement submitted for approval. It will never change stock, Purchase, supplier payable, or accounting.")}catch(ut){ee(`Opening Achievement failed: ${(ut==null?void 0:ut.message)||ut}`)}finally{se(!1)}}async function W(oe,Ve){sn&&(await yn(re(ie,`supplierPromotionOpeningAchievements/${t.companyId}/${oe.id}`),{status:Ve,approvedAt:Date.now(),approvedByUid:t.uid,approvedByName:t.name||t.email||"User"}),ee(Ve==="approved"?"Opening Achievement approved and included in promotion progress.":"Opening Achievement rejected."))}async function ft(){var he;const oe=s.find(Oe=>Oe.id===we);if(!oe)return ee("Select an achieved promotion.");const Ve=Number(Sn||0);if(!St||!Wt.trim())return ee("Settlement date and description are required.");se(!0);try{const Oe=Ta(re(ie,`supplierPromotionRewardSettlements/${t.companyId}`)).key,ut=Date.now();let At="";const en={};if(gn==="ledger_adjustment"&&Ve>0){const[It,Pt]=await Promise.all([mn(re(ie,`accountingAccounts/${t.companyId}`)),mn(re(ie,`accountingSettings/${t.companyId}`))]),Jn=String(((he=Pt.val())==null?void 0:he.lockedThrough)||"");if(Jn&&St.slice(0,7)<=Jn)throw new Error(`Accounting period ${St.slice(0,7)} is locked.`);const na=Object.entries(It.val()||{}).map(([Vn,ua])=>({id:Vn,...ua})),Mn=na.find(Vn=>Vn.active!==!1&&!Vn.isGroup&&(Vn.systemKey==="accounts_payable"||Vn.code==="2100")),Ea=na.find(Vn=>Vn.active!==!1&&!Vn.isGroup&&(Vn.systemKey==="purchase_rebate"||Vn.code==="5190"||/purchase rebate|supplier rebate/i.test(String(Vn.name||""))));if(!Mn||!Ea)throw new Error("Accounts Payable and Purchase/Supplier Rebate ledger are required before posting a supplier ledger adjustment.");At=`promotion_settlement_${Oe}`;const ga=`PR-${St.replaceAll("-","")}-${Oe.slice(-6).toUpperCase()}`,zn=t.branchId||"",Xn=[{id:"line_001",accountId:Mn.id,accountCode:Mn.code,accountName:Mn.name,debit:Ve,credit:0,narration:`Promotion reward adjustment · ${oe.title}`},{id:"line_002",accountId:Ea.id,accountCode:Ea.code,accountName:Ea.name,debit:0,credit:Ve,narration:`Promotion reward adjustment · ${oe.title}`}];en[`accountingVouchers/${t.companyId}/${At}`]={voucherNo:ga,type:"journal",status:"posted",voucherDate:St,branchId:zn,reference:$t.trim()||oe.id,narration:`Promotion Reward Settlement · ${oe.title} · ${Wt.trim()}`,lines:Xn,totalDebit:Ve,totalCredit:Ve,createdAt:ut,updatedAt:ut,postedAt:ut,createdByUid:t.uid,createdByName:t.name||t.email||"User",postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"promotion_reward_settlement",sourceId:Oe,autoPosted:!0},Xn.forEach((Vn,ua)=>en[`accountingLedgerEntries/${t.companyId}/${At}_${ua+1}`]={id:`${At}_${ua+1}`,voucherId:At,voucherNo:ga,voucherType:"journal",voucherDate:St,branchId:zn,reference:$t.trim()||oe.id,narration:Vn.narration,accountId:Vn.accountId,accountCode:Vn.accountCode,accountName:Vn.accountName,debit:Vn.debit,credit:Vn.credit,status:"posted",createdAt:ut,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"promotion_reward_settlement",sourceId:Oe,autoPosted:!0})}en[`supplierPromotionRewardSettlements/${t.companyId}/${Oe}`]={id:Oe,promotionId:oe.id,settlementDate:St,type:gn,amount:Ve,description:Wt.trim(),reference:$t.trim(),accountingVoucherId:At,createdAt:ut,createdByUid:t.uid,createdByName:t.name||t.email||"User"},await yn(re(ie),en),Xt(""),Gt(""),Vt(""),ee(gn==="ledger_adjustment"&&Ve>0?"Reward settlement saved and supplier payable ledger adjustment posted.":"Reward settlement saved. No stock/accounting entry was created for this settlement type.")}catch(Oe){ee(`Reward settlement failed: ${(Oe==null?void 0:Oe.message)||Oe}`)}finally{se(!1)}}async function Zt(oe){if(!wa.length){ee("No matching promotion is available for the PDF report.");return}se(!0);try{const he=(await fc(t.companyId).catch(()=>({name:"",logoUrl:""}))).name||"Company",Oe=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),ut=Oe.internal.pageSize.getWidth(),At=[10,61,98],en=[24,43,59],It=[101,119,136],Pt=[218,226,234];Oe.setFillColor(...At),Oe.rect(0,0,ut,4,"F"),Oe.setTextColor(...en),Oe.setFont("helvetica","bold"),Oe.
3930setFontSize(18),Oe.text(he,12,14),Oe.setTextColor(...At),Oe.setFontSize(16),Oe.text("SUPPLIER PROMOTION REPORT",ut-12,13,{align:"right"}),Oe.setTextColor(...It),Oe.setFont("helvetica","normal"),Oe.setFontSize(8.5),Oe.text(`Promotion search: ${pe.trim()||"All Promotions"}`,12,20),Oe.text(`Generated: ${new Date().toLocaleString("en-GB")}`,ut-12,20,{align:"right"}),Oe.setDrawColor(...Pt),Oe.line(12,25,ut-12,25),oi(Oe,{startY:30,head:[["Promotion Name","Supplier / Party","Target","Purchase Applied","Remaining","Benefit / Reward","Period","Status"]],body:wa.map(Mn=>{const Ea=Rt[Mn.id]||0,ga=Math.max(0,Mn.targetValue-Ea),zn=Ea>=Mn.targetValue,Xn=Vn=>Mn.targetType==="amount"?h7(Vn):Mn.targetType==="bundle"?`${Vn.toLocaleString("en-US",{maximumFractionDigits:2})} package`:Mn.targetType==="tiered"?`${Vn.toLocaleString("en-US",{maximumFractionDigits:0})} qualified`:`${Vn.toLocaleString("en-US")} qty`;return[Mn.title,Mn.supplierName,Mn.targetType==="bundle"?`${(Mn.bundleItems||[]).length} products / package`:Mn.targetType==="tiered"?`${(Mn.packages||[]).length} package tier(s)`:Xn(Mn.targetValue),Xn(Ea),Xn(ga),Mn.benefitDescription,`${Mn.startDate} to ${Mn.endDate}`,jj(Mn,zn)]}),theme:"grid",styles:{font:"helvetica",fontSize:7.3,textColor:en,cellPadding:2,lineColor:Pt,lineWidth:.15,overflow:"linebreak"},headStyles:{fillColor:At,textColor:[255,255,255],fontStyle:"bold",halign:"center"},columnStyles:{0:{cellWidth:34},1:{cellWidth:34},2:{cellWidth:28,halign:"right"},3:{cellWidth:28,halign:"right"},4:{cellWidth:28,halign:"right"},5:{cellWidth:48},6:{cellWidth:35},7:{cellWidth:24}},didDrawPage:()=>{const Mn=Oe.internal.pageSize.getHeight();Oe.setFont("helvetica","normal"),Oe.setFontSize(7.5),Oe.setTextColor(...It),Oe.text("VERIXO ERP · Supplier Promotion Center",12,Mn-7),Oe.text(`Page ${Oe.getNumberOfPages()}`,ut-12,Mn-7,{align:"right"})}});const na=`Supplier_Promotion_Report_${(pe.trim()||"All-Promotions").replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}_${rb()}.pdf`;oe==="download"?Oe.save(na):(Me&&URL.revokeObjectURL(Me),ot(URL.createObjectURL(Oe.output("blob"))),ct(na)),ee(`PDF report generated with ${wa.length} matching promotion(s).`)}catch(Ve){ee(`Promotion PDF generation failed: ${(Ve==null?void 0:Ve.message)||Ve}`)}finally{se(!1)}}function vt(){Me&&URL.revokeObjectURL(Me),ot(""),ct("")}x.useEffect(()=>()=>{Me&&URL.revokeObjectURL(Me)},[Me]);function Ae(oe){var At,en;const Ve=Rt[oe.id]||0,he=Math.max(0,oe.targetValue-Ve),Oe=Ve>=oe.targetValue,ut=gu(oe);return e.jsxs("article",{className:`promotion-card ${ut} ${Oe?"achieved":""}`,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("small",{children:oe.targetType==="amount"?"AMOUNT TARGET":oe.targetType==="bundle"?"FIXED BUNDLE":oe.targetType==="mix"?"PRODUCT GROUP / MIX":oe.targetType==="tiered"?"MULTI-PACKAGE / TIERED":"SINGLE PRODUCT QTY"}),e.jsx("h3",{children:oe.title}),e.jsx("span",{children:oe.supplierName})]}),e.jsx("b",{children:jj(oe,Oe)})]}),e.jsxs("div",{className:"promotion-target",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Target"}),e.jsx("strong",{children:oe.targetType==="amount"?Dc(oe.targetValue):oe.targetType==="bundle"?`${(oe.bundleItems||[]).length} products / package`:oe.targetType==="tiered"?`${(oe.packages||[]).length} package tier(s)`:`${oe.targetValue.toLocaleString("en-BD")} qty`})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Purchase Applied"}),e.jsx("strong",{children:oe.targetType==="amount"?Dc(Ve):oe.targetType==="bundle"?`${Ve.toLocaleString("en-BD",{maximumFractionDigits:2})} package`:oe.targetType==="tiered"?`${Ve.toLocaleString("en-BD")} qualified`:`${Ve.toLocaleString("en-BD")} qty`})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Remaining"}),e.jsx("strong",{children:oe.targetType==="amount"?Dc(he):oe.targetType==="bundle"?`${he.toLocaleString("en-BD",{maximumFractionDigits:2})} package`:oe.targetType==="tiered"?`${he.toLocaleString("en-BD")} tier(s)`:`${he.toLocaleString("en-BD")} qty`})]})]}),e.jsx("div",{className:"promotion-progress",children:e.jsx("i",{style:{width:`${Math.min(100,oe.targetType==="bundle"?Ve*100:oe.targetValue?Ve/oe.targetValue*100:0)}%`}})}),oe.targetType==="bundle"&&!!((At=oe.bundleItems)!=null&&At.length)&&e.jsxs("div",{className:"promotion-bundle-summary",children:[e.jsx("strong",{children:"1 Package:"}),oe.bundleItems.map(It=>e.jsxs("span",{children:[It.productName," à ",It.requiredQty]},It.productId))]}),oe.targetType==="tiered"&&xj(oe).length>0&&e.jsxs("div",{className:"promotion-bundle-summary",children:[e.jsxs("strong",{children:["Reward Mode: ",oe.rewardMode==="cumulative"?"Cumulative Packages":oe.rewardMode==="repeatable"?"Repeatable Packages":"Highest Qualified Package"]}),xj(oe).map((It,Pt)=>{const Jn=Et(oe,It);return e.jsxs("span",{children:[e.jsxs("b",{children:[Pt+1,". ",It.name]}
3930)," · ",[It.targetAmount?`Amount target ${Dc(It.targetAmount)}`:"",...(It.items||[]).map(na=>`${na.productName} à ${na.requiredQty}`)].filter(Boolean).join(" · ")," · Reward: ",It.rewardDescription,It.freeProductName?` · Free: ${It.freeProductName} à ${It.freeProductQty||1}`:""," · ",Jn>=1?`Qualified${oe.rewardMode==="repeatable"?` Ã${Math.floor(Jn)}`:""}`:`${Math.min(100,Jn*100).toFixed(0)}%`]},It.id)})]}),oe.targetType==="mix"&&!!((en=oe.mixProducts)!=null&&en.length)&&e.jsxs("div",{className:"promotion-bundle-summary",children:[e.jsx("strong",{children:"Eligible Mix:"}),e.jsx("span",{children:oe.mixProducts.map(It=>It.productName).join(" · ")})]}),oe.targetType==="quantity"&&oe.productName&&e.jsxs("div",{className:"promotion-bundle-summary",children:[e.jsx("strong",{children:"Product:"}),e.jsx("span",{children:oe.productName})]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Benefit:"})," ",oe.benefitDescription]}),e.jsxs("footer",{children:[e.jsxs("span",{children:[oe.startDate," â ",oe.endDate]}),e.jsxs("span",{children:["Entered by ",oe.createdByName]})]}),ut==="active"&&on&&e.jsx("div",{className:"promotion-actions",children:e.jsx("button",{disabled:qe||!!ke(oe.id),onClick:()=>ka(oe),children:ke(oe.id)?"Revision Pending":"Edit Promotion"})}),Object.values(le).filter(It=>It.promotionId===oe.id).sort((It,Pt)=>It.revisionNo-Pt.revisionNo).length>0&&e.jsxs("details",{className:"promotion-revision-history",children:[e.jsxs("summary",{children:["Revision History (",Object.values(le).filter(It=>It.promotionId===oe.id).length,")"]}),Object.values(le).filter(It=>It.promotionId===oe.id).sort((It,Pt)=>Pt.revisionNo-It.revisionNo).map(It=>e.jsxs("div",{children:[e.jsxs("span",{children:[e.jsxs("b",{children:["V",It.revisionNo]})," · ",It.status.toUpperCase()," · ",It.createdByName]}),e.jsx("small",{children:new Date(It.createdAt).toLocaleString("en-BD")}),It.status==="pending"&&sn&&e.jsxs("span",{children:[e.jsx("button",{disabled:qe,onClick:()=>void Ja(It,"rejected"),children:"Reject Revision"}),e.jsx("button",{disabled:qe,onClick:()=>void Ja(It,"approved"),children:"Approve Revision"})]})]},It.id))]}),ut==="pending"&&sn&&e.jsxs("div",{className:"promotion-actions",children:[e.jsxs("button",{disabled:qe,onClick:()=>void _n(oe,"rejected"),children:[e.jsx(AD,{size:16})," Reject"]}),e.jsxs("button",{className:"primary-button",disabled:qe,onClick:()=>void _n(oe,"active"),children:[e.jsx(Oy,{size:16})," Approve Promotion"]})]})]},oe.id)}return e.jsxs("div",{className:"promotion-panel",children:[e.jsxs("div",{className:"promotion-intro",children:[e.jsx(CD,{size:22}),e.jsxs("div",{children:[e.jsx("strong",{children:"Supplier Promotion Center"}),e.jsx("p",{children:"Enter any supplier promotion first. Approved promotions automatically receive progress only from Historical Purchases of the exact same supplier during the campaign period."})]})]}),_e&&e.jsx("div",{className:"pdf-import-message",children:_e}),e.jsxs("details",{className:"promotion-user-guide",children:[e.jsxs("summary",{children:[e.jsx("b",{children:"Promotion User Guide"}),e.jsx("small",{children:"Quick entry & revision help"})]}),e.jsxs("div",{children:[e.jsxs("p",{children:[e.jsx("b",{children:"1. Create:"})," Enter Promotion Name, exact Supplier/Party name, period and Target Type."]}),e.jsxs("p",{children:[e.jsx("b",{children:"2. Tiered mode:"})," Highest = only best qualified slab; Cumulative = every qualified slab reward; Repeatable = same package can complete multiple times."]}),e.jsxs("p",{children:[e.jsx("b",{children:"3. Approval:"})," New promotion stays Pending until Owner/Admin/Super Admin approves it."]}),e.jsxs("p",{children:[e.jsx("b",{children:"4. Edit later:"})," Open an Active promotion and choose Edit Promotion. Saving creates a Revision; it never overwrites the approved rule immediately."]}),e.jsxs("p",{children:[e.jsx("b",{children:"5. Re-Approval:"})," Owner/Admin reviews and approves/rejects the revision. Until approval, the old rule continues to calculate progress."]}),e.jsxs("p",{children:[e.jsx("b",{children:"6. Safe recalculation:"})," After approval VERIXO recalculates promotion progress from existing purchase/opening evidence only. It does not duplicate Purchase, Stock, A/P or Accounting postings."]}),e.jsxs("p",{children:[e.jsx("b",{children:"7. Old entries:"})," If the same Pending amount promotion was entered as separate slabs, use Convert Old Entries to Multi-Package. Open Review / E
3930dit Before Merge and correct Product/Model, Purchase Qty, Billing Amount and Reward/Free Qty from the supplier offer before confirming. Amount + Product/Qty means both conditions must qualify. Only untouched rows with zero applied progress are eligible; originals remain as merged audit history."]}),e.jsxs("p",{children:[e.jsx("b",{children:"8. Audit:"})," Revision History shows V1/V2-style changes, status, editor and approval trail."]})]})]}),e.jsxs("section",{className:"promotion-dashboard",children:[e.jsxs("div",{children:[e.jsx("small",{children:"ACTIVE"}),e.jsx("strong",{children:Ln.length}),e.jsx("span",{children:"Running promotions"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"PENDING"}),e.jsx("strong",{children:dn.length}),e.jsx("span",{children:"Waiting approval"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"ACHIEVED"}),e.jsx("strong",{children:s.filter(oe=>(Rt[oe.id]||0)>=oe.targetValue&&gu(oe)!=="expired").length}),e.jsx("span",{children:"Target completed"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"REWARD PENDING"}),e.jsx("strong",{children:s.filter(oe=>(Rt[oe.id]||0)>=oe.targetValue&&!Object.values(Ge).some(Ve=>Ve.promotionId===oe.id)).length}),e.jsx("span",{children:"Needs settlement"})]})]}),sn&&Ca.length>0&&e.jsxs("details",{className:"promotion-workflow promotion-merge-workflow",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx(Oy,{size:18}),e.jsx("b",{children:"Convert Old Entries to Multi-Package"})]}),e.jsxs("small",{children:[Ca.length," safe group(s) found"]})]}),e.jsx("div",{className:"promotion-merge-groups",children:Ca.map(oe=>{const Ve=oe[0],he=[ar(uc(Ve.title)),Ve.supplierKey||ar(uc(Ve.supplierName)),Ve.startDate,Ve.endDate].join("|"),Oe=Te===he;return e.jsxs("article",{children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[Ve.title," · ",Ve.supplierName]}),e.jsxs("small",{children:[Ve.startDate," â ",Ve.endDate," · ",oe.length," pending amount entries · no applied progress"]})]}),Oe?e.jsxs("div",{className:"promotion-merge-editor",children:[e.jsxs("div",{className:"promotion-merge-warning",children:[e.jsx("b",{children:"Safe Merge Preview"}),e.jsx("span",{children:"Correct the supplier offer before conversion. Amount + Product/Qty together means both conditions must be achieved. Free product is reward evidence only and does not add stock automatically."})]}),Ye.map((ut,At)=>{const en=ut.items[0];return e.jsxs("div",{className:"promotion-merge-package",children:[e.jsxs("strong",{children:["Package ",At+1]}),e.jsxs("label",{children:[e.jsx("small",{children:"Package Name"}),e.jsx("input",{value:ut.name,onChange:It=>aa(ut.id,{name:It.target.value})})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Billing / Amount Target"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:ut.targetAmount||"",onChange:It=>aa(ut.id,{targetAmount:Number(It.target.value)})})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Required Product / Model"}),e.jsx("input",{value:(en==null?void 0:en.productName)||"",placeholder:"e.g. XZ000-G7",onChange:It=>$a(ut.id,It.target.value,(en==null?void 0:en.requiredQty)||0)})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Required Purchase Qty"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:(en==null?void 0:en.requiredQty)||"",onChange:It=>$a(ut.id,(en==null?void 0:en.productName)||"",Number(It.target.value))})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Reward Description"}),e.jsx("input",{value:ut.rewardDescription,onChange:It=>aa(ut.id,{rewardDescription:It.target.value})})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Free Product / Model"}),e.jsx("input",{value:ut.freeProductName||"",placeholder:"optional",onChange:It=>aa(ut.id,{freeProductName:It.target.value})})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Free Qty"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:ut.freeProductQty||"",onChange:It=>aa(ut.id,{freeProductQty:Number(It.target.value)})})]})]},ut.id)}),e.jsxs("div",{className:"promotion-actions",children:[e.jsx("button",{type:"button",disabled:qe,onClick:()=>{ce(""),Je([])},children:"Cancel"}),e.jsx("button",{type:"button",className:"primary-button",disabled:qe,onClick:()=>void jn(oe,Ye),children:"Confirm Reviewed Merge"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"promotion-merge-tiers",children:oe.map((ut,At)=>e.jsxs("span",{children:["Package ",At+1,": ",Dc(ut.targetValue)," â ",ut.benefitDescription]},ut.id))}),e.jsx("button",{type:"button",className:"primary-button",disabled:qe,onClick:()=>
3930Sa(oe),children:"Review / Edit Before Merge"})]})]},he)})})]}),on?e.jsxs("details",{className:"promotion-workflow",open:s.length===0,children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx(as,{size:18}),e.jsx("b",{children:"New Promotion"})]}),e.jsx("small",{children:"Create supplier offer"})]}),e.jsxs("form",{className:"promotion-form",onSubmit:vs,children:[e.jsxs("div",{className:"promotion-form-title",children:[e.jsx(as,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:Ce?"Edit Promotion · Re-Approval":"New Promotion Entry"}),e.jsx("span",{children:Ce?"Changes are saved as a revision. Current approved rules stay active until re-approved.":"Submission remains pending until Owner/Admin/Super Admin approval."})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Promotion Name *"}),e.jsx("input",{value:m,onChange:oe=>d(oe.target.value),placeholder:"Example: Q3 Dealer Rebate"})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Supplier / Party Name *"}),e.jsx("input",{value:u,onChange:oe=>f(oe.target.value),placeholder:"Use the same party name shown in Purchase PDF"})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Target Type *"}),e.jsxs("select",{value:g,onChange:oe=>p(oe.target.value),children:[e.jsx("option",{value:"amount",children:"Purchase Amount"}),e.jsx("option",{value:"quantity",children:"Single Product Quantity"}),e.jsx("option",{value:"bundle",children:"Fixed Product Bundle"}),e.jsx("option",{value:"mix",children:"Product Group / Mix Quantity"}),e.jsx("option",{value:"tiered",children:"Multi-Package / Tiered Offer"})]})]}),g!=="bundle"&&g!=="tiered"&&e.jsxs("label",{children:[e.jsxs("span",{children:[g==="amount"?"Target Amount":"Target Quantity"," *"]}),e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:y,onChange:oe=>b(oe.target.value)})]}),g==="quantity"&&e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:"Target Product * · supplier offer product"}),e.jsx("input",{value:G,onChange:oe=>z(oe.target.value),placeholder:"Type supplier offer product name / model"}),e.jsx("small",{children:"Product does not need to exist in current stock."})]}),g==="bundle"&&e.jsxs("div",{className:"promotion-bundle-builder wide",children:[e.jsx("span",{children:"Bundle Items · 1 Package *"}),e.jsxs("div",{className:"promotion-bundle-add",children:[e.jsx("input",{value:H,onChange:oe=>K(oe.target.value),placeholder:"Type supplier offer product name / model"}),e.jsx("button",{type:"button",onClick:xn,children:"Add Product"})]}),C.map(oe=>e.jsxs("div",{className:"promotion-bundle-row",children:[e.jsx("strong",{children:oe.productName}),e.jsxs("label",{children:[e.jsx("small",{children:"Required Qty"}),e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:oe.requiredQty,onChange:Ve=>R(he=>he.map(Oe=>Oe.productId===oe.productId?{...Oe,requiredQty:Number(Ve.target.value)}:Oe))})]}),e.jsx("button",{type:"button",onClick:()=>R(Ve=>Ve.filter(he=>he.productId!==oe.productId)),children:"Remove"})]},oe.productId))]}),g==="mix"&&e.jsxs("div",{className:"promotion-bundle-builder wide",children:[e.jsx("span",{children:"Eligible Products * · manually add every product included in the supplier offer"}),e.jsxs("div",{className:"promotion-bundle-add",children:[e.jsx("input",{value:J,onChange:oe=>T(oe.target.value),placeholder:"Type supplier offer product name / model"}),e.jsx("button",{type:"button",onClick:()=>{const oe=J.trim();!oe||I.some(Ve=>ar(Ve.productName)===ar(oe))||(_(Ve=>[...Ve,{productId:`manual_${ar(oe).replace(/ /g,"_")}`,productName:oe}]),T(""))},children:"Add Product"})]}),I.map(oe=>e.jsxs("div",{className:"promotion-bundle-row",children:[e.jsx("strong",{children:oe.productName}),e.jsx("span",{}),e.jsx("button",{type:"button",onClick:()=>_(Ve=>Ve.filter(he=>he.productId!==oe.productId)),children:"Remove"})]},oe.productId)),e.jsx("small",{children:"Products do not need to exist in current stock. VERIXO stores the supplier-offer product name and matches purchase evidence when that product is purchased/imported."})]}),g==="tiered"&&e.jsxs("div",{className:"promotion-bundle-builder wide",children:[e.jsx("span",{children:"Multi-Package / Tiered Offer *"}),e.jsxs("details",{className:"promotion-inline-advanced",children:[e.jsxs("summary",{children:["Advanced Settings ",e.jsx("small",{children:"Default: Highest Qualified Package"})]}),e.jsxs("label",{children:[e.jsx("small",{children:"Reward Qualification Mode"}),e.jsxs("select",{value:ue,onChange:oe=>me(oe.target.value),children:[e.jsx("option",{value:"highest",children:"Highe
3930st Qualified Package Only"}),e.jsx("option",{value:"cumulative",children:"Cumulative Qualified Packages"}),e.jsx("option",{value:"repeatable",children:"Repeatable Package Completion"})]})]})]}),e.jsxs("div",{className:"promotion-bundle-add",children:[e.jsx("input",{value:M,onChange:oe=>Z(oe.target.value),placeholder:"Package name · e.g. Package 1 / Silver"}),e.jsx("input",{value:fe,onChange:oe=>q(oe.target.value),placeholder:"Reward · e.g. 7% rebate / Nepal Tour"})]}),e.jsxs("div",{className:"promotion-bundle-add",children:[e.jsx("input",{value:ne,onChange:oe=>ae(oe.target.value),placeholder:"Buy X Get Y: free product (optional)"}),e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:Y,onChange:oe=>je(oe.target.value),placeholder:"Free qty"})]}),e.jsxs("div",{className:"promotion-bundle-add",children:[e.jsx("input",{value:V,onChange:oe=>$(oe.target.value),placeholder:"Required supplier offer product / model"}),e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:F,onChange:oe=>P(oe.target.value),placeholder:"Required qty"}),e.jsx("button",{type:"button",onClick:()=>{const oe=V.trim(),Ve=Number(F);if(!oe||!(Ve>0)||!M.trim())return ee("Enter package name, required product and quantity first.");const he=`manual_${ar(oe).replace(/ /g,"_")}`;D(Oe=>{const ut=Oe.findIndex(At=>ar(At.name)===ar(M));return ut<0?[...Oe,{id:`tier_${Date.now()}`,name:M.trim(),rewardDescription:fe.trim(),freeProductName:ne.trim()||void 0,freeProductQty:Number(Y)||void 0,items:[{productId:he,productName:oe,requiredQty:Ve}]}]:Oe.map((At,en)=>en===ut?{...At,rewardDescription:fe.trim()||At.rewardDescription,freeProductName:ne.trim()||At.freeProductName,freeProductQty:Number(Y)||At.freeProductQty,items:At.items.some(It=>ar(It.productName)===ar(oe))?At.items:[...At.items,{productId:he,productName:oe,requiredQty:Ve}]}:At)}),$(""),P("1")},children:"Add Requirement"})]}),L.map(oe=>e.jsxs("div",{className:"promotion-tier-package",children:[e.jsxs("div",{children:[e.jsx("strong",{children:oe.name}),e.jsxs("small",{children:[oe.targetAmount?`Amount Target: ${Dc(oe.targetAmount)} · `:"","Reward: ",oe.rewardDescription||"â",oe.freeProductName?` · Free ${oe.freeProductName} à ${oe.freeProductQty||1}`:""]})]}),oe.targetAmount?e.jsxs("label",{children:[e.jsx("small",{children:"Package Amount Target"}),e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:oe.targetAmount,onChange:Ve=>D(he=>he.map(Oe=>Oe.id===oe.id?{...Oe,targetAmount:Number(Ve.target.value)}:Oe))})]}):null,oe.items.map(Ve=>e.jsxs("div",{className:"promotion-bundle-row",children:[e.jsx("strong",{children:Ve.productName}),e.jsxs("label",{children:[e.jsx("small",{children:"Required Qty"}),e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:Ve.requiredQty,onChange:he=>D(Oe=>Oe.map(ut=>ut.id===oe.id?{...ut,items:ut.items.map(At=>At.productId===Ve.productId?{...At,requiredQty:Number(he.target.value)}:At)}:ut))})]}),e.jsx("button",{type:"button",onClick:()=>D(he=>he.map(Oe=>Oe.id===oe.id?{...Oe,items:Oe.items.filter(ut=>ut.productId!==Ve.productId)}:Oe).filter(Oe=>Oe.items.length)),children:"Remove"})]},Ve.productId)),e.jsx("button",{type:"button",onClick:()=>D(Ve=>Ve.filter(he=>he.id!==oe.id)),children:"Remove Package"})]},oe.id)),e.jsx("small",{children:"Each package can contain one or more supplier-offer products. Products do not need to exist in current stock. Buy X Get Y is recorded as the package reward and never increases stock until a real reward settlement is received."})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Start Date *"}),e.jsx("input",{type:"date",value:Pe,onChange:oe=>Re(oe.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"End Date *"}),e.jsx("input",{type:"date",value:Ee,onChange:oe=>Be(oe.target.value)})]}),e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:g==="tiered"?"Overall Promotion / Reward Summary *":"Promotion Benefit / Reward *"}),e.jsx("input",{value:ge,onChange:oe=>de(oe.target.value),placeholder:"Example: 7% rebate / cash adjustment / tour"})]}),e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:"Notes"}),e.jsx("textarea",{value:We,onChange:oe=>it(oe.target.value),rows:2})]}),e.jsxs("button",{className:"primary-button wide",disabled:qe,children:[e.jsx(gs,{size:17})," ",Ce?"Submit Revision for Re-Approval":"Submit for Approval"]})]})]}):e.jsxs("div",{className:"promotion-readonly",children:[e.jsx(gs,{size:18}),e.jsxs("span",{children:[e.jsx("strong",{children:"View-only access"}),e.jsx("small",{children:"Promotion Manage permission is required to create a new promotion."})]})]}),e.jsxs("details",{className:"promotion-workflow promotion-advanced",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx(gs,{size:18}),e.jsx("b",{children:"Opening Achievement"})]}),e.jsx("small",{children:"Only for pre-VERIXO progress"})]}),e.jsxs("section",{className:"promotion-report",children:[e.jsx("div",{className:"promotion-report-head",children:e.jsxs("div",{children:[e.jsx(gs,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Opening Achievement / Brought Forward"}),e.jsx("small",{children:"For promotions that started before VERIXO cutover. Ap
3930proved opening values affect promotion progress only â never Stock, Purchase, A/P or accounting."})]})]})}),e.jsxs("div",{className:"promotion-opening-grid",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Promotion *"}),e.jsxs("select",{value:$e,onChange:oe=>st(oe.target.value),children:[e.jsx("option",{value:"",children:"Select promotion"}),s.filter(oe=>oe.status==="active"||oe.status==="pending").map(oe=>e.jsxs("option",{value:oe.id,children:[oe.title," · ",oe.supplierName]},oe.id))]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Opening As Of *"}),e.jsx("input",{type:"date",value:Nt,onChange:oe=>be(oe.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Opening Amount"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:jt,onChange:oe=>bt(oe.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Opening Total Qty"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:tn,onChange:oe=>B(oe.target.value)})]}),e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:"Product-wise Opening Qty"}),e.jsx("textarea",{rows:3,value:xe,onChange:oe=>tt(oe.target.value),placeholder:`One per line: Product Name = Qty 3931Example: TY1 PRO 3MP = 180 3932C6N G1 5MP = 40`}),e.jsx("small",{children:"Use the supplier-offer product/model wording. This is promotion evidence only."})]}),e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:"Source / Note"}),e.jsx("input",{value:ht,onChange:oe=>dt(oe.target.value),placeholder:"Supplier statement / JanuaryâJuly achievement reference"})]}),e.jsx("button",{type:"button",className:"primary-button wide",disabled:qe||!on,onClick:()=>void ta(),children:"Submit Opening Achievement for Approval"})]}),!!Object.values(xt).length&&e.jsx("div",{className:"promotion-list-wrap",children:e.jsxs("table",{className:"promotion-list",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Promotion"}),e.jsx("th",{children:"As Of"}),e.jsx("th",{children:"Opening"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:Object.values(xt).sort((oe,Ve)=>Ve.createdAt-oe.createdAt).map(oe=>{const Ve=s.find(he=>he.id===oe.promotionId);return e.jsxs("tr",{children:[e.jsx("td",{children:(Ve==null?void 0:Ve.title)||oe.promotionId}),e.jsx("td",{children:oe.asOfDate}),e.jsxs("td",{children:[oe.amount>0?Dc(oe.amount):`${oe.qty||0} qty`,Object.keys(oe.productContributions||{}).length?` · ${Object.keys(oe.productContributions||{}).length} product(s)`:""]}),e.jsx("td",{children:e.jsx("b",{children:oe.status})}),e.jsx("td",{children:oe.status==="pending"&&sn?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void W(oe,"approved"),children:"Approve"})," ",e.jsx("button",{type:"button",onClick:()=>void W(oe,"rejected"),children:"Reject"})]}):"â"})]},oe.id)})})]})})]})]}),e.jsxs("details",{className:"promotion-workflow promotion-advanced",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx(Oy,{size:18}),e.jsx("b",{children:"Reward Settlement"})]}),e.jsx("small",{children:"Record reward after achievement"})]}),e.jsxs("section",{className:"promotion-report",children:[e.jsx("div",{className:"promotion-report-head",children:e.jsxs("div",{children:[e.jsx(Oy,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Reward Settlement"}),e.jsx("small",{children:"Keep the original reward and record what was actually received: tour/gift, cash/bank, free product, converted reward, or supplier ledger adjustment."})]})]})}),e.jsxs("div",{className:"promotion-opening-grid",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Promotion *"}),e.jsxs("select",{value:we,onChange:oe=>rt(oe.target.value),children:[e.jsx("option",{value:"",children:"Select promotion"}),s.filter(oe=>(Rt[oe.id]||0)>=oe.targetValue).map(oe=>e.jsxs("option",{value:oe.id,children:[oe.title," · ",oe.benefitDescription]},oe.id))]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Settlement Date *"}),e.jsx("input",{type:"date",value:St,onChange:oe=>Qt(oe.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Actual Settlement Type *"}),e.jsxs("select",{value:gn,onChange:oe=>An(oe.target.value),children:[e.jsx("option",{value:"tour_gift",children:"Tour / Gift Taken"}),e.jsx("option",{value:"ledger_adjustment",children:"Supplier Ledger Adjustment"}),e.jsx("option",{value:"cash",children:"Cash Received"}),e.jsx("option",{value:"bank",children:"Bank Received"}),e.jsx("option",{value:"free_product",children:"Free Product"}),e.jsx("option",{value:"converted",children:"Converted Reward"}),e.jsx("option",{value:"other",children:"Other"})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Settlement Value"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:Sn,onChange:oe=>Xt(oe.target.value)})]}),e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:"Actual Settlement Description *"}
3932),e.jsx("input",{value:Wt,onChange:oe=>Gt(oe.target.value),placeholder:"Example: Bhutan Tour converted to BDT 80,000 supplier ledger adjustment"})]}),e.jsxs("label",{className:"wide",children:[e.jsx("span",{children:"Reference / Credit Note"}),e.jsx("input",{value:$t,onChange:oe=>Vt(oe.target.value)})]}),e.jsx("button",{type:"button",className:"primary-button wide",disabled:qe||!on,onClick:()=>void ft(),children:"Save Reward Settlement"})]}),!!Object.values(Ge).length&&e.jsx("div",{className:"promotion-list-wrap",children:e.jsxs("table",{className:"promotion-list",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Promotion"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Original Reward"}),e.jsx("th",{children:"Actual Settlement"}),e.jsx("th",{children:"Value"}),e.jsx("th",{children:"Reference"})]})}),e.jsx("tbody",{children:Object.values(Ge).sort((oe,Ve)=>Ve.createdAt-oe.createdAt).map(oe=>{const Ve=s.find(he=>he.id===oe.promotionId);return e.jsxs("tr",{children:[e.jsx("td",{children:(Ve==null?void 0:Ve.title)||oe.promotionId}),e.jsx("td",{children:oe.settlementDate}),e.jsx("td",{children:(Ve==null?void 0:Ve.benefitDescription)||"â"}),e.jsx("td",{children:oe.description}),e.jsx("td",{children:oe.amount>0?Dc(oe.amount):"â"}),e.jsx("td",{children:oe.reference||"â"})]},oe.id)})})]})})]})]}),e.jsxs("section",{className:"promotion-report",children:[e.jsxs("div",{className:"promotion-report-head",children:[e.jsxs("div",{children:[e.jsx(Zs,{size:19}),e.jsxs("span",{children:[e.jsx("strong",{children:"Promotion List & Report"}),e.jsx("small",{children:"Search by Promotion Name to compare the same promotion across every Supplier / Party."})]})]}),e.jsxs("div",{className:"promotion-report-actions",children:[e.jsxs("button",{type:"button",disabled:qe||!wa.length,onClick:()=>void Zt("view"),children:[e.jsx(ui,{size:16})," View PDF"]}),e.jsxs("button",{type:"button",className:"primary-button",disabled:qe||!wa.length,onClick:()=>void Zt("download"),children:[e.jsx(Mi,{size:16})," Download PDF"]})]})]}),e.jsxs("label",{className:"promotion-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:pe,onChange:oe=>Se(oe.target.value),placeholder:"Search Promotion Name, e.g. Q3 HikVision"}),e.jsxs("b",{children:[wa.length," result(s)"]})]}),e.jsx("div",{className:"promotion-list-wrap",children:e.jsxs("table",{className:"promotion-list",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Promotion Name"}),e.jsx("th",{children:"Supplier / Party"}),e.jsx("th",{children:"Target"}),e.jsx("th",{children:"Applied"}),e.jsx("th",{children:"Remaining"}),e.jsx("th",{children:"Benefit / Reward"}),e.jsx("th",{children:"Period"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:wa.length?wa.map(oe=>{const Ve=Rt[oe.id]||0,he=Math.max(0,oe.targetValue-Ve),Oe=Ve>=oe.targetValue;return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:oe.title})}),e.jsx("td",{children:oe.supplierName}),e.jsx("td",{children:oe.targetType==="amount"?Dc(oe.targetValue):oe.targetType==="bundle"?`${(oe.bundleItems||[]).length} products / package`:oe.targetType==="tiered"?`${(oe.packages||[]).length} package tier(s)`:`${oe.targetValue.toLocaleString("en-BD")} qty`}),e.jsx("td",{children:oe.targetType==="amount"?Dc(Ve):oe.targetType==="bundle"?`${Ve.toLocaleString("en-BD",{maximumFractionDigits:2})} package`:oe.targetType==="tiered"?`${Ve.toLocaleString("en-BD")} qualified`:`${Ve.toLocaleString("en-BD")} qty`}),e.jsx("td",{children:oe.targetType==="amount"?Dc(he):oe.targetType==="bundle"?`${he.toLocaleString("en-BD",{maximumFractionDigits:2})} package`:oe.targetType==="tiered"?`${he.toLocaleString("en-BD")} tier(s)`:`${he.toLocaleString("en-BD")} qty`}),e.jsx("td",{children:oe.benefitDescription}),e.jsxs("td",{children:[oe.startDate,e.jsxs("small",{children:["to ",oe.endDate]})]}),e.jsx("td",{children:e.jsx("span",{className:`promotion-status ${gu(oe)}`,children:jj(oe,Oe)})})]},oe.id)}):e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"promotion-list-empty",children:"No promotion matches this Promotion Name."})})})]})})]}),e.jsxs("section",{className:"promotion-section",children:[e.jsxs("div",{className:"promotion-section-head",children:[e.jsx(Ho,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Pending Approval"}),e.jsxs("span",{children:[dn.length," promotion(s)"]})]})]}),dn.length?e.jsx("div",{className:"promotion-cards",children:dn.map(Ae)}):e.jsx("div",{className:"promotion-empty",children:"No promotion is waiting for approval."})]}),Me&&e.jsx("div",{className:"promotion-pdf-modal",role:"dialog","aria-modal":"true","aria-label":"Promotion PDF Preview",children:e.jsxs("div",{className:"promotion-pdf-dialog",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Supplier Promotion Report"}),e.jsx("small",{children:wt})]}),e.jsx("button",{type:"button",onClick:vt,"aria-label":"Close PDF preview",children:e.jsx(ja,{size:20})})]}),e.jsx("iframe",{title:"Supplier Promotion PDF Preview",src:Me}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",onClick:vt,children:"Close"}),e.jsxs("button",{type:"button",className:"primary-button",onClick:()=>void Zt("download"),children:[e.jsx(Mi,{size:16})," Download PDF"]})]})]})})]})}function Sp(t){return t.role==="owner"||t.role==="super_admin"||t.allBranches===!0?!0:t.role==="admin"&&typeof t.allBranches>"u"&&typeof t.branchIds>"u"}function _h(t){if(Sp(t))return[];
3932const n=Array.isArray(t.branchIds)?t.branchIds.filter(Boolean):[];return t.branchId&&!n.includes(t.branchId)&&n.unshift(t.branchId),[...new Set(n)]}const Tv={journal:"Journal Voucher",payment:"Payment Voucher",receipt:"Receipt Voucher",contra:"Contra / Transfer"},p7={journal:"JV",payment:"PV",receipt:"RV",contra:"CV"},wj=()=>new Date().toISOString().slice(0,10),Mv=t=>t.slice(0,7),ki=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`;function f7(t){return(t||"VRX").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"VRX"}function dh(){return{id:`line_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,accountId:"",accountCode:"",accountName:"",debit:0,credit:0,narration:""}}function g7({profile:t,branches:n,selectedBranchId:a,companyCode:s}){var st,Nt;const i=sa(t,"finance.manage"),c=Sp(t),l=_h(t),m=c?"":t.branchId||l[0]||"",d=a!=="all"?a:"",u=d||m,f=c?n.filter(be=>be.active):n.filter(be=>be.active&&be.id===m),g=be=>u||(!c&&be&&l.includes(be)?be:be||""),[p,y]=x.useState([]),[b,N]=x.useState({}),[w,C]=x.useState([]),[R,I]=x.useState([]),[_,J]=x.useState(""),[T,G]=x.useState("all"),[z,H]=x.useState(""),[K,L]=x.useState(""),[D,M]=x.useState(""),[Z,fe]=x.useState(!1),[q,ne]=x.useState(!1),[ae,Y]=x.useState(null),[je,V]=x.useState(""),[$,F]=x.useState("journal"),[P,ue]=x.useState(wj()),[me,ge]=x.useState(g(a==="all"?"":a)),[de,Pe]=x.useState(""),[Re,Ee]=x.useState(""),[Be,We]=x.useState([dh(),dh()]);x.useEffect(()=>{if(u){ge(u);return}me&&!f.some(be=>be.id===me)&&ge("")},[u,f,me]),x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),be=>{const jt=be.exists()?Object.entries(be.val()).map(([bt,tn])=>({id:bt,...tn})):[];y(jt.filter(bt=>bt.active!==!1).sort((bt,tn)=>bt.code.localeCompare(tn.code,void 0,{numeric:!0})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingSettings/${t.companyId}`),be=>{N(be.exists()?be.val():{})}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingVouchers/${t.companyId}`),be=>{const jt=be.exists()?Object.entries(be.val()).map(([bt,tn])=>({id:bt,...tn})):[];C(jt.sort((bt,tn)=>Number(tn.createdAt||0)-Number(bt.createdAt||0)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingLedgerEntries/${t.companyId}`),be=>{const jt=be.exists()?Object.entries(be.val()).map(([bt,tn])=>({id:bt,...tn})):[];I(jt.filter(bt=>bt.status==="posted"))}),[t.companyId]);const it=x.useMemo(()=>p.filter(be=>!be.isGroup),[p]),_e=x.useMemo(()=>new Set(it.filter(be=>be.systemKey==="cash"||be.systemKey==="bank").map(be=>be.id)),[it]),ee=x.useMemo(()=>{var be;return((be=it.find(jt=>jt.systemKey==="cash"))==null?void 0:be.id)||""},[it]),qe=x.useMemo(()=>{const be={};return ee&&R.filter(jt=>jt.accountId===ee).forEach(jt=>{const bt=jt.branchId||"unassigned";be[bt]=(be[bt]||0)+Number(jt.debit||0)-Number(jt.credit||0)}),be},[R,ee]),se=x.useMemo(()=>Object.values(qe).reduce((be,jt)=>be+jt,0),[qe]),pe=x.useMemo(()=>it.map(be=>{const jt=R.filter(xe=>xe.accountId===be.id&&(a==="all"||xe.branchId===a)),bt=jt.reduce((xe,tt)=>xe+Number(tt.debit||0),0),tn=jt.reduce((xe,tt)=>xe+Number(tt.credit||0),0),B=be.type==="liability"||be.type==="equity"||be.type==="income"?tn-bt:bt-tn;return{...be,debit:bt,credit:tn,balance:B,entryCount:jt.length}}),[it,R,a]),Se=x.useMemo(()=>pe.find(be=>be.id===z)||null,[pe,z]),Me=x.useMemo(()=>{if(!Se)return[];const be=Se.type==="liability"||Se.type==="equity"||Se.type==="income";let jt=0;return R.filter(bt=>bt.accountId===Se.id&&(a==="all"||bt.branchId===a)).sort((bt,tn)=>String(bt.voucherDate||"").localeCompare(String(tn.voucherDate||""))||Number(bt.createdAt||0)-Number(tn.createdAt||0)).map(bt=>(jt+=be?Number(bt.credit||0)-Number(bt.debit||0):Number(bt.debit||0)-Number(bt.credit||0),{...bt,running:jt}))},[Se,R,a]),ot=x.useMemo(()=>{const be=K.trim().toLowerCase();return pe.filter(jt=>!be||jt.code.toLowerCase().includes(be)||jt.name.toLowerCase().includes(be))},[pe,K]),wt=x.useMemo(()=>Be.reduce((be,jt)=>({debit:be.debit+Number(jt.debit||0),credit:be.credit+Number(jt.credit||0)}),{debit:0,credit:0}),[Be]),ct=Math.abs(wt.debit-wt.credit)<.005&&wt.debit>0,Ce=be=>{const jt=(b.lockedThrough||"").trim();return!!(jt&&Mv(be)<=jt)},De=be=>{const jt=n.find(bt=>bt.id===be);return f7((jt==null?void 0:jt.code)||s||"VRX")},Te=async(be,jt,bt)=>{const tn=new Date(`${jt}T00:00:00`).getFullYear(),B=p7[be],xe=De(bt),tt=`${xe}-${B}-${tn}`,ht=await Ep(re(ie,`accountingVoucherCounters/${t.companyId}/${tt}`),dt=>({lastNumber:Number((dt==null?void 0:dt.lastNumber)||0)+1,branchCode:xe,prefix:B,year:tn,updatedAt:Date.now()}));if(!ht.committed)throw new Error("Voucher number could not be generated.");return`${xe}-${B}-${tn}
3932-${String(Number(ht.snapshot.val().lastNumber||0)).padStart(6,"0")}`},ce=()=>{V(""),F("journal"),ue(wj()),ge(g(a==="all"?"":a)),Pe(""),Ee(""),We([dh(),dh()])},Ye=()=>{ce(),M(""),ne(!0)},Je=be=>{var jt;if(be.status==="draft"){if(u&&be.branchId&&be.branchId!==u){M("This voucher belongs to another branch. Change the workspace Branch first if you are authorized.");return}if(!c&&be.branchId&&!l.includes(be.branchId)){M("This voucher belongs to a branch outside your assignment.");return}V(be.id),F(be.type),ue(be.voucherDate),ge(g(be.branchId||"")),Pe(be.reference||""),Ee(be.narration||""),We((jt=be.lines)!=null&&jt.length?be.lines:[dh(),dh()]),M(""),ne(!0)}},le=(be,jt,bt)=>{We(tn=>tn.map(B=>{if(B.id!==be)return B;if(jt==="accountId"){const xe=it.find(tt=>tt.id===bt);return{...B,accountId:String(bt),accountCode:(xe==null?void 0:xe.code)||"",accountName:(xe==null?void 0:xe.name)||""}}if(jt==="debit"){const xe=Math.max(0,Number(bt||0));return{...B,debit:xe,credit:xe>0?0:B.credit}}if(jt==="credit"){const xe=Math.max(0,Number(bt||0));return{...B,credit:xe,debit:xe>0?0:B.debit}}return{...B,[jt]:bt}}))},nt=be=>{const jt=Be.filter(tn=>tn.accountId&&(Number(tn.debit||0)>0||Number(tn.credit||0)>0)),bt=Date.now();return{voucherNo:(be==null?void 0:be.voucherNo)||"DRAFT",type:$,status:"draft",voucherDate:P,branchId:me||"",reference:de.trim(),narration:Re.trim(),lines:jt,totalDebit:wt.debit,totalCredit:wt.credit,createdAt:(be==null?void 0:be.createdAt)||bt,createdByUid:(be==null?void 0:be.createdByUid)||t.uid,createdByName:(be==null?void 0:be.createdByName)||t.name||t.email||"User",updatedAt:bt}},xt=async be=>{if(be==null||be.preventDefault(),!i||Z)return;if(u&&me!==u){M("Accounting entry is fixed to the selected/assigned branch.");return}if(!me){M("Choose an actual Branch before creating an accounting entry.");return}if(!c&&!l.includes(me)){M("You can create accounting entries only for your assigned branches.");return}if(Ce(P)){M(`Cannot save in locked period ${Mv(P)}.`);return}const jt=Be.filter(bt=>bt.accountId&&(Number(bt.debit||0)>0||Number(bt.credit||0)>0));if(!P||jt.length===0){M("Voucher Date and at least one accounting line are required for a draft.");return}fe(!0),M("");try{const bt=w.find(xe=>xe.id===je),tn=je||Ta(re(ie,`accountingVouchers/${t.companyId}`)).key,B=nt(bt);await Pn(re(ie,`accountingVouchers/${t.companyId}/${tn}`),B),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:je?"accounting.voucher_updated":"accounting.voucher_created",entityType:"accounting",entityId:tn,summary:`${Tv[$]} draft ${je?"updated":"created"}.`,branchId:me||void 0,metadata:{type:$,date:P,totalDebit:wt.debit,totalCredit:wt.credit}}),ne(!1),ce(),M("Voucher draft saved.")}catch(bt){console.error(bt),M(`Draft save failed: ${bt instanceof Error?bt.message:"Unknown error"}`)}finally{fe(!1)}},te=async be=>{if(!i||Z||be.status!=="draft")return;if(u&&be.branchId!==u){M("You can post vouchers only for the fixed workspace/assigned branch.");return}if(!c&&be.branchId&&!l.includes(be.branchId)){M("You cannot post a voucher outside your assigned branches.");return}if(Ce(be.voucherDate)){M(`Cannot post ${be.voucherNo==="DRAFT"?"draft":be.voucherNo}: period ${Mv(be.voucherDate)} is locked.`);return}const jt=be.lines||[],bt=jt.reduce((xe,tt)=>xe+Number(tt.debit||0),0),tn=jt.reduce((xe,tt)=>xe+Number(tt.credit||0),0),B=jt.length<2?"At least two posting lines are required.":Math.abs(bt-tn)>=.005||bt<=0?`Voucher must balance. Difference: ${ki(Math.abs(bt-tn))}.`:jt.some(xe=>xe.accountId===ee)&&!be.branchId?"Select a Branch for every Cash in Hand transaction. Cash is one master ledger, but its balance is tracked by branch.":be.type==="payment"&&!jt.some(xe=>_e.has(xe.accountId)&&Number(xe.credit||0)>0)?"Payment Voucher requires Cash/Bank on the Credit side.":be.type==="receipt"&&!jt.some(xe=>_e.has(xe.accountId)&&Number(xe.debit||0)>0)?"Receipt Voucher requires Cash/Bank on the Debit side.":be.type==="contra"&&jt.some(xe=>!_e.has(xe.accountId))?"Contra / Transfer may use only Cash and Bank accounts.":"";if(B){M(B);return}fe(!0),M("");try{const xe=be.voucherNo==="DRAFT"?await Te(be.type,be.voucherDate,be.branchId):be.voucherNo,tt=Date.now(),ht={[`accountingVouchers/${t.companyId}/${be.id}/voucherNo`]:xe,[`accountingVouchers/${t.companyId}/${be.id}/status`]:"posted",[`accountingVouchers/${t.companyId}/${be.id}/totalDebit`]:bt,[`accountingVouchers/${t.companyId}/${be.id}/totalCredit`]:tn,[`accountingVouchers/${t.companyId}/${be.id}/postedAt`]:tt,[`accountingVouchers/${t.companyId}/${be.id}/postedByUid`]:t.uid,[`accountingVouchers/${t.companyId}/${be.id}/postedByName`]:t.name||t.email||"User",[`accountingVouchers/${t.companyId}/${be.id}/updatedAt`]:tt};jt.forEach((dt,we)=>{const rt=`${be.id}_${String(we+1).padStart(3,"0")}`;ht[`accountingLedgerEntries/${t.companyId}/${rt}`]={id:rt,voucherId:be.id,voucherNo:xe,voucherType:be.type,voucherDate:be.voucherDate,branchId:be.branchId||"",reference:be.reference||"",narration:dt.narration||be.narration||"",accountId:dt.accountId,accountCode:dt.accountCode,accountName:dt.accountName,debit:Number(dt.debit||0),credit:Number(dt.credit||0),status:"posted",createdAt:tt,postedByUid:t.uid,postedByName:t.name||t.email||"User"}}),await yn(re(ie),ht),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.voucher_posted",entityType:"accounting",entityId:be.id,summary:`${xe} posted.`,branchId:be.branchId||void 0,metadata:{type:be.type,total:bt}}),M(`${xe} posted successfully. Double-entry ledger lines created.`)}catch(xe){console.error(xe),M(`Posting failed: ${xe instanceof Error?xe.message:"Unknown error"}`)}finally{fe(!1)}},Ge=async be=>{if(!i||Z||be.status!=="posted")return;if(be.reversalOfVoucherId){M("A reversal voucher cannot be reversed again."),Y(null);return}if(u&&be.branchId!==u){M("You can reverse vouchers only for the fixed workspace/assigned branch."),Y(null);return}if(!c&&be.branchId&&!l.includes(be.branchId)){M("You cannot reverse a voucher outside your assigned branches."),Y(null);return}const jt=wj();if(Ce(jt)){M(`Current period ${Mv(jt)} is locked;
3932 reversal cannot be posted.`),Y(null);return}if(jt<be.voucherDate){M("Reversal date cannot be earlier than the original voucher date."),Y(null);return}fe(!0),M("");try{const bt=Ta(re(ie,`accountingVouchers/${t.companyId}`)).key,tn=await Te("journal",jt,be.branchId),B=Date.now(),xe=(be.lines||[]).map((dt,we)=>({...dt,id:`rev_${we+1}`,debit:Number(dt.credit||0),credit:Number(dt.debit||0),narration:`Reversal of ${be.voucherNo}${dt.narration?` · ${dt.narration}`:""}`})),tt={voucherNo:tn,type:"journal",status:"posted",voucherDate:jt,branchId:be.branchId||"",reference:be.voucherNo,narration:`Reversal of ${be.voucherNo}`,lines:xe,totalDebit:be.totalCredit,totalCredit:be.totalDebit,createdAt:B,createdByUid:t.uid,createdByName:t.name||t.email||"User",updatedAt:B,postedAt:B,postedByUid:t.uid,postedByName:t.name||t.email||"User",reversalOfVoucherId:be.id},ht={[`accountingVouchers/${t.companyId}/${bt}`]:tt,[`accountingVouchers/${t.companyId}/${be.id}/status`]:"reversed",[`accountingVouchers/${t.companyId}/${be.id}/reversedAt`]:B,[`accountingVouchers/${t.companyId}/${be.id}/reversedByUid`]:t.uid,[`accountingVouchers/${t.companyId}/${be.id}/reversedByName`]:t.name||t.email||"User",[`accountingVouchers/${t.companyId}/${be.id}/reversalVoucherId`]:bt,[`accountingVouchers/${t.companyId}/${be.id}/updatedAt`]:B};xe.forEach((dt,we)=>{const rt=`${bt}_${String(we+1).padStart(3,"0")}`;ht[`accountingLedgerEntries/${t.companyId}/${rt}`]={id:rt,voucherId:bt,voucherNo:tn,voucherType:"journal",voucherDate:jt,branchId:be.branchId||"",reference:be.voucherNo,narration:dt.narration,accountId:dt.accountId,accountCode:dt.accountCode,accountName:dt.accountName,debit:dt.debit,credit:dt.credit,status:"posted",createdAt:B,postedByUid:t.uid,postedByName:t.name||t.email||"User"}}),await yn(re(ie),ht),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"accounting.voucher_reversed",entityType:"accounting",entityId:be.id,summary:`${be.voucherNo} reversed by ${tn}.`,branchId:be.branchId||void 0,metadata:{reversalVoucherId:bt,reversalVoucherNo:tn}}),M(`${be.voucherNo} reversed. Reversal voucher: ${tn}.`),Y(null)}catch(bt){console.error(bt),M(`Reversal failed: ${bt instanceof Error?bt.message:"Unknown error"}`)}finally{fe(!1)}},pt=x.useMemo(()=>w.filter(be=>a!=="all"?be.branchId===a:c?!0:!!(be.branchId&&l.includes(be.branchId))),[w,a,c,l]),$e=x.useMemo(()=>{const be=_.trim().toLowerCase();return pt.filter(jt=>(T==="all"||jt.status===T)&&(!be||`${jt.voucherNo} ${Tv[jt.type]} ${jt.reference||""} ${jt.narration||""}`.toLowerCase().includes(be)))},[pt,_,T]);return e.jsxs("section",{className:"voucher-page",children:[e.jsxs("header",{className:"voucher-page-head",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h1",{children:"Vouchers & Journal"}),e.jsx("p",{children:"Controlled double-entry posting with Draft â Post â Reverse workflow."})]}),i&&e.jsxs("button",{className:"primary",onClick:Ye,children:[e.jsx(Eb,{size:17})," New Voucher"]})]}),D&&e.jsx("div",{className:"voucher-message",children:D}),e.jsx("div",{className:`voucher-lock-banner ${b.lockedThrough?"locked":"open"}`,children:e.jsxs("div",{children:[e.jsx("strong",{children:b.lockedThrough?`Period Lock Active · Through ${b.lockedThrough}`:"Period Lock · Not Set"}),e.jsx("span",{children:b.lockedThrough?"Draft save and posting are blocked for voucher dates in or before the locked month. Reversals post only in an unlocked current period.":"No accounting period is locked. Close and lock a month only after reconciliation is complete."})]})}),e.jsxs("div",{className:"cash-position",children:[e.jsx("div",{className:"cash-position-head",children:e.jsxs("div",{children:[e.jsx("span",{children:"CASH IN HAND · MASTER LEDGER"}),e.jsx("strong",{children:ki(a==="all"?se:qe[a]||0)}),e.jsx("small",{children:a==="all"?"All Branches accumulated balance":"Selected branch balance"})]})}),a==="all"&&e.jsxs("div",{className:"cash-branch-grid",children:[n.filter(be=>be.active).map(be=>e.jsxs("div",{children:[e.jsx("span",{children:be.name}),e.jsx("strong",{children:ki(qe[be.id]||0)})]},be.id)),qe.unassigned!==void 0&&e.jsxs("div",{className:"warning",children:[e.jsx("span",{children:"Unassigned / Legacy"}),e.jsx("strong",{children:ki(qe.unassigned||0)})]})]})]}),e.jsxs("section",{className:"account-ledger-panel",children:[e.jsxs("div",{className:"account-ledger-head",children:[e.jsxs("div",{children:[e.jsx("span",{className:"ledger-kicker",children:"ACCOUNT LEDGER"}),e.jsx("h2",{children:"Account Transactions"}),e.jsx("p",{children:"Posted debit, credit and running balance from the double-entry ledger."})]}),e.jsx("div",{className:"ledger-scope",children:a==="all"?"All Branches":((st=n.find(be=>be.id===a))==null?void 0:st.name)||"Selected Branch"})]}),e.jsxs("div",{className:"ledger-account-picker",children:[e.jsxs("label",{children:[e.jsx(xr,{size:16}),e.jsx("input",{value:K,onChange:be=>L(be.target.value),placeholder:"Find account by code or name..."})]}),e.jsxs("select",{value:z,onChange:be=>H(be.target.value),children:[e.jsx("option",{value:"",children:"Select account to view ledger"}),ot.map(be=>e.jsxs("option",{value:be.id,children:[be.code," · ",be.name," · ",ki(be.balance)]},be.id))]})]}),Se&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"ledger-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Account"}),e.jsxs("strong",{children:[Se.code," · ",Se.name]}),e.jsx("small",{children:Se.type})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Debit"}),e.jsx("strong",{children:ki(Se.debit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Credit"}),e.jsx("strong",{children:ki(Se.credit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Current Balance"}),e.jsx("strong",{children:ki(Se.balance)}),e.jsxs("small",{children:[Se.entryCount," posted line",Se.entryCount===1?"":"s"]})]})]}),e.jsx("div",{className:"ledger-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"VOUCHER"}),e.jsx("th",{children:"BRANCH"}),e.jsx("th",{children:"REFERENCE / NARRATION"}),e.jsx("th",{children:"DEBIT"}),e.jsx("th",{children:"CREDIT"}),e.jsx("th",{children:"BALANCE"})]})}),e.jsx("tbody",{children:Me.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"empty",children:"No posted ledger transaction found for this account."})}):Me.map(be=>{var jt;return e.jsxs("tr",{children:[e.jsx("td",{children:be.voucherDate||"â"}),e.jsx("td",{children:e.jsx("strong",{children:be.voucherNo||"â"})}),e.jsx("td",{children:((jt=n.find(bt=>bt.id===be.branchId))==null?void 0:jt.name)||(be.branchId?"Unknown Branch":"Company / Legacy")}),e.jsxs("td",{children:[e.jsx("span",{children:be.reference||"â"}),e.jsx("small",{children:be.narration||""})]}),e.jsx("td",{children:be.debit?ki(be.debit):"â"}),e.jsx("td",{children:be.credit?ki(be.credit):"â"}),e.jsx("td",{children:e.jsx("strong",{children:ki(be.running)})})]},be.id)})})]})})]})]}),e.jsxs("div",{className:"voucher-cards",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Draft"}),e.jsx("strong",{children:pt.filter(be=>be.status==="draft").length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Posted"}),e.jsx("strong",{children:pt.filter(be=>be.status==="posted").length})]}
3932),e.jsxs("article",{children:[e.jsx("span",{children:"Reversed"}),e.jsx("strong",{children:pt.filter(be=>be.status==="reversed").length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Posted Value"}),e.jsx("strong",{children:ki(pt.filter(be=>be.status==="posted").reduce((be,jt)=>be+Number(jt.totalDebit||0),0))})]})]}),e.jsxs("div",{className:"voucher-toolbar",children:[e.jsxs("label",{children:[e.jsx(xr,{size:17}),e.jsx("input",{placeholder:"Search voucher, reference or narration...",value:_,onChange:be=>J(be.target.value)})]}),e.jsxs("select",{value:T,onChange:be=>G(be.target.value),children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"posted",children:"Posted"}),e.jsx("option",{value:"reversed",children:"Reversed"})]})]}),e.jsx("div",{className:"voucher-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"VOUCHER"}),e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"REFERENCE"}),e.jsx("th",{children:"DEBIT"}),e.jsx("th",{children:"CREDIT"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:$e.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty",children:"No accounting voucher found."})}):$e.map(be=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:be.voucherNo}),e.jsx("small",{children:be.narration||"â"})]}),e.jsx("td",{children:be.voucherDate}),e.jsx("td",{children:Tv[be.type]}),e.jsx("td",{children:be.reference||"â"}),e.jsx("td",{children:ki(be.totalDebit)}),e.jsx("td",{children:ki(be.totalCredit)}),e.jsx("td",{children:e.jsx("span",{className:`voucher-status ${be.status}`,children:be.status[0].toUpperCase()+be.status.slice(1)})}),e.jsx("td",{children:e.jsxs("div",{className:"voucher-actions",children:[be.status==="draft"&&i&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Je(be),children:"Edit"}),e.jsxs("button",{disabled:Z,className:"post",onClick:()=>te(be),children:[e.jsx(Zw,{size:15})," Post"]})]}),be.status==="posted"&&i&&!be.reversalOfVoucherId&&e.jsxs("button",{disabled:Z,onClick:()=>Y(be),children:[e.jsx(Id,{size:15})," Reverse"]}),be.status==="posted"&&be.reversalOfVoucherId&&e.jsx("span",{className:"voucher-action-muted",children:"â"}),be.status==="reversed"&&e.jsx("span",{className:"voucher-action-muted",children:"â"})]})})]},be.id))})]})}),ae&&e.jsx("div",{className:"voucher-modal-bg",onMouseDown:be=>{be.currentTarget===be.target&&!Z&&Y(null)},children:e.jsxs("div",{className:"reverse-confirm-modal",role:"dialog","aria-modal":"true","aria-labelledby":"reverse-voucher-title",children:[e.jsxs("header",{className:"reverse-confirm-head",children:[e.jsx("div",{className:"reverse-confirm-icon",children:e.jsx(Id,{size:22})}),e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"VOUCHER REVERSAL"}),e.jsx("h2",{id:"reverse-voucher-title",children:"Reverse Voucher?"})]}),e.jsx("button",{type:"button",className:"voucher-close",disabled:Z,onClick:()=>Y(null),"aria-label":"Close",children:e.jsx(ja,{size:18})})]}),e.jsxs("div",{className:"reverse-confirm-body",children:[e.jsxs("div",{className:"reverse-voucher-card",children:[e.jsx("span",{children:"Voucher No."}),e.jsx("strong",{children:ae.voucherNo}),e.jsxs("small",{children:[Tv[ae.type]," · ",ae.voucherDate," · ",ki(ae.totalDebit)]})]}),e.jsx("p",{children:"The original voucher and original ledger date remain unchanged. VERIXO will post a separate reversing Journal Voucher dated today with the opposite debit and credit entries. If the original month is locked, that closed-period report therefore remains unchanged."})]}),e.jsxs("footer",{className:"reverse-confirm-footer",children:[e.jsx("button",{type:"button",className:"voucher-cancel",disabled:Z,onClick:()=>Y(null),children:"Cancel"}),e.jsxs("button",{type:"button",className:"reverse-confirm-button",disabled:Z,onClick:()=>Ge(ae),children:[e.jsx(Id,{size:16}),Z?"Reversing...":"Reverse Voucher"]})]})]})}),q&&e.jsx("div",{className:"voucher-modal-bg",onMouseDown:be=>{be.currentTarget===be.target&&ne(!1)},children:e.jsxs("form",{className:"voucher-modal voucher-modal-pro",onSubmit:xt,children:[e.jsxs("header",{className:"voucher-modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:je?"EDIT DRAFT":"NEW VOUCHER"}),e.jsx("h2",{children:je?"Update Voucher Draft":"Create Voucher Draft"}),e.jsx("span",{className:"voucher-modal-subtitle",children:"Record a balanced accounting entry and save it as Draft before posting."})]}),e.jsx("button",{type:"button",className:"voucher-close",onClick:()=>ne(!1),"aria-label":"Close",children:e.jsx(ja,{size:18})})]}),e.jsxs("section",{className:"voucher-section",children:[e.jsx("div",{className:"voucher-section-title",children:"Voucher Details"}),e.jsxs("div",{className:"voucher-grid voucher-grid-pro",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Voucher Type"}),e.jsxs("select",{value:$,onChange:be=>F(be.target.value),children:[e.jsx("option",{value:"journal",children:"Journal Voucher"}),e.jsx("option",{value:"payment",children:"Payment Voucher"}),e.jsx("option",{value:"receipt",children:"Receipt Voucher"}),e.jsx("option",{value:"contra",children:"Contra / Transfer"})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Voucher Date"}),e.jsx("input",{type:"date",value:P,onChange:be=>ue(be.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Branch"}),u?e.jsxs("div",{className:"voucher-fixed-branch voucher-fixed-branch-pro",children:[e.jsx("strong",{children:((Nt=n.find(be=>be.id===u))==null?void 0:Nt.name)||"Assigned Branch"}),e.jsx("small",{children:d?"Workspace branch":"Assigned branch"})]}):e.jsxs("select",{value:me,onChange:be=>ge(be.target.value),required:!0,children:[e.jsx("option",{value:"",children:"Select Branch"}),f.map(be=>e.jsx("option",{value:be.id,children:be.name},be.id))]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Reference"}),e.jsx("input",{value:de,onChange:be=>Pe(be.target.value),placeholder:"Cheque / bill / external reference"})]})]}),e.jsxs("label",{className:"wide voucher-narration",children:[e.jsx("span",{children:"Narration"}),e.jsx("input",{value:Re,onChange:be=>Ee(be.target.value),placeholder:"Purpose or description of this voucher"})]})]}),e.jsxs("section",{className:"voucher-section voucher-entry-section",children:[e.jsxs("div",{className:"voucher-section-head-row",children:[e.jsxs("div",{children:[e.jsx("div",{className:"voucher-section-title",children:"Accounting Entries"}),e.jsx("small",{children:"Enter debit and credit lines for this voucher."})]}),e.jsxs("button",{className:"voucher-add-line-top",type:"button",onClick:()=>We([...Be,dh()]),children:[e.jsx(Eb,{size:15})," Add Line"]})]}),e.jsx("div",{className:"voucher-lines voucher-lines-pro",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"ACCOUNT"}),e.jsx("th",{className:"amount-head",children:"DEBIT"}),e.jsx("th",{className:"amount-head",children:"CREDIT"}),e.jsx("th",{children:"LINE NARRATION"}),e.jsx("th",{className:"remove-head"})]})}),e.jsx("tbody",{children:Be.map((be,jt)=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("select",{value:be.accountId,onChange:bt=>le(be.id,"accountId",bt.target.value),children:[e.jsx("option",{value:"",children:"Select account"}),it.map(bt=>e.jsxs("option",{value:bt.id,children:[bt.code," · ",bt.name]},bt.id))]})}),e.jsx("td",{children:e.jsx("input",{className:"voucher-amount-input",type:"number",min:"0",value:be.debit||"",onChange:bt=>le(be.id,"debit",Number(bt.target.value)),placeholder:"0.00"})}),e.jsx("td",{children:e.jsx("input",{className:"voucher-amount-input",type:"number",min:"0",value:be.credit||"",onChange:bt=>le(be.id,"credit",Number(bt.target.value)),placeholder:"0.00"})}),e.jsx("td",{children:e.jsx("input",{value:be.narration||"",onChange:bt=>le(be.id,"narration",bt.target.value),placeholder:"Optional"})}),e.jsx("td",{children:e.jsx("button",{className:"voucher-remove-line",type:"button",disabled:Be.length<=2,onClick:()=>We(Be.filter(bt=>bt.id!==be.id)),children:e.jsx(ja,{size:15})})})]},be.id))})]})}),e.jsxs("div",{className:"voucher-summary-bar",children:[e.jsxs("div",{className:"voucher-summary-item",children:[e.jsx("span",{children:"Total Debit"}),e.jsx("strong",{children:ki(wt.debit)})]}),e.jsxs("div",{className:"voucher-summary-item",children:[e.jsx("span",{children:"Total Credit"}),e.jsx("strong",{children:ki(wt.credit)})]}),e.jsx("div",{className:`voucher-balance-chip ${ct?"balanced":"unbalanced"}`,children:ct?"Balanced":`Difference ${ki(Math.abs(wt.debit-wt.credit))}`})]})]}),e.jsxs("footer",{className:"voucher-modal-footer",children:[e.jsx("button",{type:"button",className:"voucher-cancel",onClick:()=>ne(!1),children:"Cancel"}),e.jsxs("button",{className:"primary voucher-save",disabled:Z,children:[e.jsx(hr,{size:16})," ",Z?"Saving...":"Save Draft"]})]})]})})]})}const y7=()=>new Date().toISOString().slice(0,10),v7=()=>{const t=new Date;return`${t.getFullYear()}
3932-${String(t.getMonth()+1).padStart(2,"0")}-01`},Di=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,lc=t=>Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2}),Nj={asset:"Asset",liability:"Liability",equity:"Equity",income:"Income",expense:"Expense"};function b7({profile:t,branches:n,selectedBranchId:a}){var ne;const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState({}),[u,f]=x.useState(v7()),[g,p]=x.useState(y7()),[y,b]=x.useState(""),[N,w]=x.useState(!0),[C,R]=x.useState(!1),[I,_]=x.useState(""),[J,T]=x.useState("");x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),ae=>{const Y=ae.exists()?Object.entries(ae.val()).map(([je,V])=>({id:je,...V})):[];i(Y.filter(je=>je.active!==!1&&!je.isGroup).sort((je,V)=>je.code.localeCompare(V.code,void 0,{numeric:!0})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingLedgerEntries/${t.companyId}`),ae=>{const Y=ae.exists()?Object.entries(ae.val()).map(([je,V])=>({id:je,...V})):[];l(Y.filter(je=>je.status==="posted"))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingOpeningBalances/${t.companyId}`),ae=>{d(ae.exists()?ae.val():{})}),[t.companyId]);const G=x.useMemo(()=>s.map(ae=>{const Y=c.filter(_e=>_e.accountId===ae.id&&(a==="all"||_e.branchId===a)),je=a==="all"?m[ae.id]:void 0,V=Number((je==null?void 0:je.debit)||0),$=Number((je==null?void 0:je.credit)||0),F=Y.filter(_e=>!_e.voucherDate||_e.voucherDate<u),P=Y.filter(_e=>(!_e.voucherDate||_e.voucherDate>=u)&&(!_e.voucherDate||_e.voucherDate<=g)),ue=F.reduce((_e,ee)=>_e+Number(ee.debit||0),0),me=F.reduce((_e,ee)=>_e+Number(ee.credit||0),0),ge=V+ue-($+me),de=ge>0?ge:0,Pe=ge<0?Math.abs(ge):0,Re=P.reduce((_e,ee)=>_e+Number(ee.debit||0),0),Ee=P.reduce((_e,ee)=>_e+Number(ee.credit||0),0),Be=ge+Re-Ee,We=Be>0?Be:0,it=Be<0?Math.abs(Be):0;return{...ae,openingDebit:de,openingCredit:Pe,movementDebit:Re,movementCredit:Ee,debitBalance:We,creditBalance:it}}),[s,c,m,u,g,a]),z=x.useMemo(()=>G.filter(ae=>{const Y=Math.abs(ae.debitBalance)>.004||Math.abs(ae.creditBalance)>.004||Math.abs(ae.movementDebit)>.004||Math.abs(ae.movementCredit)>.004||Math.abs(ae.openingDebit)>.004||Math.abs(ae.openingCredit)>.004;return!N||Y}),[G,N]),H=x.useMemo(()=>{const ae=y.trim().toLowerCase();return z.filter(Y=>!ae||`${Y.code} ${Y.name} ${Nj[Y.type]}`.toLowerCase().includes(ae))},[z,y]),K=x.useMemo(()=>G.reduce((ae,Y)=>(ae.openingDebit+=Y.openingDebit,ae.openingCredit+=Y.openingCredit,ae.movementDebit+=Y.movementDebit,ae.movementCredit+=Y.movementCredit,ae.debit+=Y.debitBalance,ae.credit+=Y.creditBalance,ae),{openingDebit:0,openingCredit:0,movementDebit:0,movementCredit:0,debit:0,credit:0}),[G]),L=Math.abs(K.debit-K.credit),D=L<.005,M=!!(u&&g&&u>g),Z=a==="all"?"All Branches":((ne=n.find(ae=>ae.id===a))==null?void 0:ne.name)||"Selected Branch",fe=async ae=>{var Y,je;if(!M){R(!0);try{const V=await fc(t.companyId).catch(()=>({name:"",logoUrl:""})),$=V.name||"Company",F=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),P=F.internal.pageSize.getWidth(),ue=[10,61,98],me=[24,43,59],ge=[101,119,136],de=[245,248,251],Pe=[218,226,234];F.setFillColor(...ue),F.rect(0,0,P,4,"F");let Re=!1;if((Y=V.logoUrl)!=null&&Y.startsWith("data:image/"))try{const _e=await new Promise((ee,qe)=>{const se=new Image;se.onload=()=>{const pe=document.createElement("canvas"),Se=Math.min(1,560/se.width,180/se.height);pe.width=Math.max(1,Math.round(se.width*Se)),pe.height=Math.max(1,Math.round(se.height*Se));const Me=pe.getContext("2d");if(!Me)return qe(new Error("Canvas unavailable"));Me.fillStyle="#ffffff",Me.fillRect(0,0,pe.width,pe.height),Me.drawImage(se,0,0,pe.width,pe.height),ee(pe.toDataURL("image/jpeg",.94))},se.onerror=()=>qe(new Error("Logo could not be loaded")),se.src=V.logoUrl});F.addImage(_e,"JPEG",12,8,30,12,void 0,"FAST"),Re=!0}catch(_e){console.warn("Trial Balance PDF logo skipped:",_e)}F.setTextColor(...me),F.setFont("helvetica","bold"),F.setFontSize(18),F.text($,Re?47:12,13),F.setFont("helvetica","normal"),F.setTextColor(...ge),F.setFontSize(8.5),F.text(`Branch: ${Z}`,Re?47:12,18),F.setTextColor(...ue),F.setFont("helvetica","bold"),F.setFontSize(16),F.text("TRIAL BALANCE",P-12,12,{al
3932ign:"right"}),F.setTextColor(...ge),F.setFont("helvetica","normal"),F.setFontSize(8.5),F.text(`Period: ${u} to ${g}`,P-12,17,{align:"right"}),F.text(`Generated: ${new Date().toLocaleString("en-GB")}`,P-12,21,{align:"right"}),F.setDrawColor(...Pe),F.line(12,26,P-12,26),oi(F,{startY:31,head:[["Account","Type","Opening Dr","Opening Cr","Period Dr","Period Cr","Closing Dr","Closing Cr"]],body:z.map(_e=>[`${_e.code} · ${_e.name}`,Nj[_e.type],_e.openingDebit?lc(_e.openingDebit):"-",_e.openingCredit?lc(_e.openingCredit):"-",_e.movementDebit?lc(_e.movementDebit):"-",_e.movementCredit?lc(_e.movementCredit):"-",_e.debitBalance?lc(_e.debitBalance):"-",_e.creditBalance?lc(_e.creditBalance):"-"]),foot:[["TOTAL","",lc(K.openingDebit),lc(K.openingCredit),lc(K.movementDebit),lc(K.movementCredit),lc(K.debit),lc(K.credit)]],theme:"grid",styles:{font:"helvetica",fontSize:7.4,textColor:me,cellPadding:2.2,lineColor:Pe,lineWidth:.15},headStyles:{fillColor:ue,textColor:[255,255,255],fontStyle:"bold",halign:"center"},footStyles:{fillColor:de,textColor:me,fontStyle:"bold",lineColor:Pe},columnStyles:{0:{cellWidth:63},1:{cellWidth:23},2:{halign:"right"},3:{halign:"right"},4:{halign:"right"},5:{halign:"right"},6:{halign:"right"},7:{halign:"right"}},didDrawPage:()=>{const _e=F.internal.pageSize.getHeight();F.setFont("helvetica","normal"),F.setFontSize(7.5),F.setTextColor(...ge),F.text("VERIXO ERP · Accounts & Finance",12,_e-7),F.text(`Page ${F.getNumberOfPages()}`,P-12,_e-7,{align:"right"})}});const Ee=((je=F.lastAutoTable)==null?void 0:je.finalY)||150,Be=Math.min(Ee+8,F.internal.pageSize.getHeight()-17);F.setFont("helvetica","bold"),F.setFontSize(9.5),D?(F.setTextColor(8,120,62),F.text("BALANCED · Closing Debit = Closing Credit",12,Be)):(F.setTextColor(180,35,24),F.text(`DIFFERENCE · ${lc(L)}`,12,Be));const it=`${$.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")||"Company"}_Trial_Balance_${u}_to_${g}.pdf`;if(ae==="download")F.save(it);else{I&&URL.revokeObjectURL(I);const _e=F.output("blob");_(URL.createObjectURL(_e)),T(it)}}finally{R(!1)}}},q=()=>{I&&URL.revokeObjectURL(I),_(""),T("")};return x.useEffect(()=>()=>{I&&URL.revokeObjectURL(I)},[I]),e.jsxs("section",{className:"trial-balance-page",children:[e.jsxs("header",{className:"trial-balance-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h1",{children:"Trial Balance"}),e.jsx("p",{children:"Opening position, period movement and closing balances from the posted double-entry ledger."})]}),e.jsxs("div",{className:"trial-header-actions",children:[e.jsxs("button",{className:"trial-view-button",disabled:C||M,onClick:()=>fe("preview"),children:[e.jsx(ui,{size:17}),C?"Preparing...":"View PDF"]}),e.jsxs("button",{className:"trial-pdf-button",disabled:C||M,onClick:()=>fe("download"),children:[e.jsx(Uu,{size:17}),"Download PDF"]}),e.jsxs("div",{className:`trial-balance-status ${D&&!M?"balanced":"unbalanced"}`,children:[e.jsx(G4,{size:18}),e.jsxs("div",{children:[e.jsx("span",{children:M?"Invalid Period":D?"Balanced":"Difference"}),e.jsx("strong",{children:M?"From date must be before To date":D?"Debit = Credit":Di(L)})]})]})]})]}),e.jsxs("div",{className:"trial-balance-controls trial-period-controls",children:[e.jsxs("label",{className:"trial-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:y,onChange:ae=>b(ae.target.value),placeholder:"Search account code or name..."})]}),e.jsxs("label",{className:"trial-date",children:[e.jsx(wi,{size:16}),e.jsx("span",{children:"From"}),e.jsx("input",{type:"date",value:u,onChange:ae=>f(ae.target.value)})]}),e.jsxs("label",{className:"trial-date",children:[e.jsx(wi,{size:16}),e.jsx("span",{children:"To"}),e.jsx("input",{type:"date",value:g,onChange:ae=>p(ae.target.value)})]}),e.jsxs("div",{className:"trial-scope",children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:Z})]}),e.jsxs("label",{className:"trial-zero-toggle",children:[e.jsx("input",{type:"checkbox",checked:N,onChange:ae=>w(ae.target.checked)}),e.jsx("span",{children:"Hide zero accounts"})]})]}),e.jsxs("div",{className:"trial-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Opening Debit"}),e.jsx("strong",{children:Di(K.openingDebit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Opening Credit"}),e.jsx("strong",{children:Di(K.openingCredit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Period Debit"}),e.jsx("strong",{children:Di(K.movementDebit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Period Credit"}),e.jsx("strong",{children:Di(K.movementCredit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Closing Debit"}),e.jsx("strong",{children:Di(K.debit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Closing Credit"}),e.jsx("strong",{children:Di(K.credit)})]})]}),M&&e.jsx("div",{className:"trial-period-error",children:"From Date cannot be after To Date."}),e.jsx("div",{className:"trial-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"ACCOUNT"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{className:"amount",children:"OPENING DR"}),e.jsx("th",{className:"amount",children:"OPENING CR"}),e.jsx("th",{className:"amount",children:"PERIOD DR"}),e.jsx("th",{className:"amount",children:"PERIOD CR"}),e.jsx("th",{className:"amount",children:"CLOSING DR"}
3932),e.jsx("th",{className:"amount",children:"CLOSING CR"})]})}),e.jsx("tbody",{children:H.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty",children:"No account balance found for this period and scope."})}):H.map(ae=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("strong",{children:[ae.code," · ",ae.name]})}),e.jsx("td",{children:e.jsx("span",{className:`trial-type ${ae.type}`,children:Nj[ae.type]})}),e.jsx("td",{className:"amount",children:ae.openingDebit?Di(ae.openingDebit):"â"}),e.jsx("td",{className:"amount",children:ae.openingCredit?Di(ae.openingCredit):"â"}),e.jsx("td",{className:"amount",children:ae.movementDebit?Di(ae.movementDebit):"â"}),e.jsx("td",{className:"amount",children:ae.movementCredit?Di(ae.movementCredit):"â"}),e.jsx("td",{className:"amount closing",children:ae.debitBalance?Di(ae.debitBalance):"â"}),e.jsx("td",{className:"amount closing",children:ae.creditBalance?Di(ae.creditBalance):"â"})]},ae.id))}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("td",{colSpan:2,children:"TOTAL"}),e.jsx("td",{className:"amount",children:Di(K.openingDebit)}),e.jsx("td",{className:"amount",children:Di(K.openingCredit)}),e.jsx("td",{className:"amount",children:Di(K.movementDebit)}),e.jsx("td",{className:"amount",children:Di(K.movementCredit)}),e.jsx("td",{className:"amount",children:Di(K.debit)}),e.jsx("td",{className:"amount",children:Di(K.credit)})]})})]})}),I&&e.jsxs("div",{className:"trial-pdf-fullscreen",role:"dialog","aria-modal":"true","aria-label":"Trial Balance PDF Preview",children:[e.jsxs("header",{className:"trial-pdf-fullscreen-header",children:[e.jsxs("div",{className:"trial-pdf-fullscreen-title",children:[e.jsx("span",{children:"PDF PREVIEW"}),e.jsx("strong",{children:"Trial Balance"}),e.jsxs("small",{children:[u," to ",g," · ",Z]})]}),e.jsxs("div",{className:"trial-pdf-fullscreen-actions",children:[e.jsxs("a",{className:"trial-preview-download",href:I,download:J,children:[e.jsx(Uu,{size:16})," Download PDF"]}),e.jsxs("button",{type:"button",className:"trial-pdf-fullscreen-close",onClick:q,"aria-label":"Close preview",children:[e.jsx(ja,{size:20}),e.jsx("span",{children:"Close"})]})]})]}),e.jsx("main",{className:"trial-pdf-fullscreen-frame",children:e.jsx("iframe",{src:I,title:"Trial Balance PDF Preview"})})]})]})}const x7=()=>new Date().toISOString().slice(0,10),i_=t=>{const n=String(t.reference||"").trim(),a=String(t.narration||"").trim();return/^ADVLOAN-/i.test(n)?a?a.replace(/\s+issued to\s+/i," · "):"Employee Advance / Loan":n||""},Sj=t=>{const n=String(t.reference||"").trim();return/^ADVLOAN-/i.test(n)?"":String(t.narration||"").trim()},j7=()=>{const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-01`},bu=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,ip=t=>`BDT ${Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2})}`,If=(t,n)=>{if(Math.abs(n)<.005)return ip(0);const a=wg(t)?"Cr":"Dr",s=wg(t)?"Dr":"Cr";return`${ip(Math.abs(n))} ${n>=0?a:s}`},o_={journal:"Journal",payment:"Payment",receipt:"Receipt",contra:"Contra"},wg=t=>t==="liability"||t==="equity"||t==="income",$v=(t,n,a)=>wg(t)?a-n:n-a,_f=(t,n)=>{if(Math.abs(n)<.005)return`${bu(0)}`;const a=wg(t)?"Cr":"Dr",s=wg(t)?"Dr":"Cr";return`${bu(Math.abs(n))} ${n>=0?a:s}`};function w7({profile:t,branches:n,selectedBranchId:a}){var q;const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState({}),[u,f]=x.useState(""),[g,p]=x.useState(""),[y,b]=x.useState(j7()),[N,w]=x.useState(x7()),[C,R]=x.useState(""),[I,_]=x.useState(!1),[J,T]=x.useState(""),[G,z]=x.useState("");x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),ne=>{const ae=ne.exists()?Object.entries(ne.val()).map(([Y,je])=>({id:Y,...je})):[];i(ae.filter(Y=>Y.active!==!1&&!Y.isGroup).sort((Y,je)=>Y.code.localeCompare(je.code,void 0,{numeric:!0})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingLedgerEntries/${t.companyId}`),ne=>{const ae=ne.exists()?Object.entries(ne.val()).map(([Y,je])=>({id:Y,...je})):[];l(ae.filter(Y=>Y.status==="posted"))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingOpeningBalances/${t.companyId}`),ne=>{d(ne.exists()?ne.val():{})}),[t.companyId]);const H=x.useMemo(()=>s.find(ne=>ne.id===u)||null,[s,u]),K=x.useMemo(()=>{const ne=g.trim().toLowerCase();return s.filter(ae=>!ne||`${ae.code} ${ae.name}`.toLowerCase().includes(ne))},[s,g]),L=!!(y&&N&&y>N),D=a==="all"?"All Branches":((q=n.find(ne=>ne.id===a))==null?void 0:q.name)||"Selected Branch",M=x.useMemo(()=>
3932{if(!H)return{openingBalance:0,rows:[],totalDebit:0,totalCredit:0,closingBalance:0};const ne=c.filter(Re=>Re.accountId===H.id&&(a==="all"||Re.branchId===a)),ae=a==="all"?m[H.id]:void 0,Y=$v(H.type,Number((ae==null?void 0:ae.debit)||0),Number((ae==null?void 0:ae.credit)||0)),V=ne.filter(Re=>!Re.voucherDate||Re.voucherDate<y).reduce((Re,Ee)=>Re+$v(H.type,Number(Ee.debit||0),Number(Ee.credit||0)),Y);let $=V;const F=C.trim().toLowerCase(),P=ne.filter(Re=>(!Re.voucherDate||Re.voucherDate>=y)&&(!Re.voucherDate||Re.voucherDate<=N)).sort((Re,Ee)=>String(Re.voucherDate||"").localeCompare(String(Ee.voucherDate||""))||Number(Re.createdAt||0)-Number(Ee.createdAt||0)),me=P.map(Re=>($+=$v(H.type,Number(Re.debit||0),Number(Re.credit||0)),{...Re,running:$})).filter(Re=>!F||`${Re.voucherNo||""} ${Re.reference||""} ${Re.narration||""}`.toLowerCase().includes(F)),ge=P.reduce((Re,Ee)=>Re+Number(Ee.debit||0),0),de=P.reduce((Re,Ee)=>Re+Number(Ee.credit||0),0),Pe=V+$v(H.type,ge,de);return{openingBalance:V,rows:me,totalDebit:ge,totalCredit:de,closingBalance:Pe}},[H,c,m,a,y,N,C]),Z=()=>{J&&URL.revokeObjectURL(J),T(""),z("")};x.useEffect(()=>()=>{J&&URL.revokeObjectURL(J)},[J]);const fe=async ne=>{var ae;if(!(!H||L)){_(!0);try{const Y=await fc(t.companyId).catch(()=>({name:"",logoUrl:""})),je=Y.name||"Company",V=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),$=V.internal.pageSize.getWidth(),F=[10,61,98],P=[24,43,59],ue=[101,119,136],me=[245,248,251],ge=[218,226,234];V.setFillColor(...F),V.rect(0,0,$,4,"F");let de=!1;if((ae=Y.logoUrl)!=null&&ae.startsWith("data:image/"))try{const Ee=await new Promise((Be,We)=>{const it=new Image;it.onload=()=>{const _e=document.createElement("canvas"),ee=Math.min(1,560/it.width,180/it.height);_e.width=Math.max(1,Math.round(it.width*ee)),_e.height=Math.max(1,Math.round(it.height*ee));const qe=_e.getContext("2d");if(!qe)return We(new Error("Canvas unavailable"));qe.fillStyle="#fff",qe.fillRect(0,0,_e.width,_e.height),qe.drawImage(it,0,0,_e.width,_e.height),Be(_e.toDataURL("image/jpeg",.94))},it.onerror=()=>We(new Error("Logo could not be loaded")),it.src=Y.logoUrl});V.addImage(Ee,"JPEG",12,8,30,12,void 0,"FAST"),de=!0}catch(Ee){console.warn("General Ledger PDF logo skipped:",Ee)}V.setTextColor(...P),V.setFont("helvetica","bold"),V.setFontSize(18),V.text(je,de?47:12,13),V.setFont("helvetica","normal"),V.setTextColor(...ue),V.setFontSize(8.5),V.text(`Branch: ${D}`,de?47:12,18),V.setTextColor(...F),V.setFont("helvetica","bold"),V.setFontSize(16),V.text("GENERAL LEDGER",$-12,12,{align:"right"}),V.setTextColor(...ue),V.setFont("helvetica","normal"),V.setFontSize(8.5),V.text(`Period: ${y} to ${N}`,$-12,17,{align:"right"}),V.text(`Generated: ${new Date().toLocaleString("en-GB")}`,$-12,21,{align:"right"}),V.setDrawColor(...ge),V.line(12,26,$-12,26),V.setTextColor(...P),V.setFont("helvetica","bold"),V.setFontSize(10.5),V.text(`${H.code} · ${H.name}`,12,32),V.setFont("helvetica","normal"),V.setTextColor(...ue),V.setFontSize(8.5),V.text(`Opening Balance: ${If(H.type,M.openingBalance)}`,12,37),V.text(`Closing Balance: ${If(H.type,M.closingBalance)}`,$-12,37,{align:"right"}),oi(V,{startY:42,head:[["Date","Voucher","Type","Reference / Narration","Debit","Credit","Running Balance"]],body:[["","OPENING","","Balance brought forward","","",If(H.type,M.openingBalance)],...M.rows.map(Ee=>[Ee.voucherDate||"-",Ee.voucherNo||"-",Ee.voucherType?o_[Ee.voucherType]:"-",[i_(Ee),Sj(Ee)].filter(Boolean).join(" · ")||"-",Ee.debit?ip(Ee.debit):"-",Ee.credit?ip(Ee.credit):"-",If(H.type,Ee.running)])],foot:[["","","","PERIOD TOTAL",ip(M.totalDebit),ip(M.totalCredit),If(H.type,M.closingBalance)]],theme:"grid",styles:{font:"helvetica",fontSize:7.4,textColor:P,cellPadding:2.2,lineColor:ge,lineWidth:.15},headStyles:{fillColor:F,textColor:[255,255,255],fontStyle:"bold"},footStyles:{fillColor:me,textColor:P,fontStyle:"bold"},columnStyles:{0:{cellWidth:22},1:{cellWidth:48,overflow:"linebreak"},2:{cellWidth:20},3:{cellWidth:82},4:{halign:"right",cellWidth:30},5:{halign:"right",cellWidth:30},6:{halign:"right",cellWidth:39}},didDrawPage:()=>{const Ee=V.internal.pageSize.getHeight();V.setFont("helvetica","normal"),V.setFontSize(7.5),V.setTextColor(...ue),V.text("VERIXO ERP · Accounts & Finance",12,Ee-7),V.text(`Page ${V.getNumberOfPages()}`,$-12,Ee-7,{align:"right"})}});const Re=`${je.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")||"Company"}_General_Ledger_${H.code}_${y}_to_${N}.pdf`;if(ne==="download")V.save(Re);else{J&&URL.revokeObjectURL(J);const Ee=V.output("blob");T(URL.createObjectURL(Ee)),z(Re)}}finally{_(!1)}}};return e.jsxs("section",{className:"general-ledger-page",children:[e.jsxs("header",{className:"general-ledger-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h1",{children:"General Ledger"}),e.jsx("p",{children:"Account-wise posted transactions with opening and running balance."})]}),e.jsxs("div",{className:"general-ledger-actions",children:[e.jsxs("button",{className:"gl-view-button",disabled:!H||L||I,onClick:()=>fe("preview"),children:[e.jsx(ui,{size:17}
3932),I?"Preparing...":"View PDF"]}),e.jsxs("button",{className:"gl-download-button",disabled:!H||L||I,onClick:()=>fe("download"),children:[e.jsx(Uu,{size:17}),"Download PDF"]})]})]}),e.jsxs("div",{className:"gl-account-selector",children:[e.jsxs("label",{className:"gl-account-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:g,onChange:ne=>p(ne.target.value),placeholder:"Find account code or name..."})]}),e.jsxs("select",{value:u,onChange:ne=>f(ne.target.value),children:[e.jsx("option",{value:"",children:"Select account"}),K.map(ne=>e.jsxs("option",{value:ne.id,children:[ne.code," · ",ne.name]},ne.id))]})]}),e.jsxs("div",{className:"gl-controls",children:[e.jsxs("label",{children:[e.jsx(wi,{size:16}),e.jsx("span",{children:"From"}),e.jsx("input",{type:"date",value:y,onChange:ne=>b(ne.target.value)})]}),e.jsxs("label",{children:[e.jsx(wi,{size:16}),e.jsx("span",{children:"To"}),e.jsx("input",{type:"date",value:N,onChange:ne=>w(ne.target.value)})]}),e.jsxs("div",{className:"gl-scope",children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:D})]}),e.jsxs("label",{className:"gl-text-search",children:[e.jsx(xr,{size:16}),e.jsx("input",{value:C,onChange:ne=>R(ne.target.value),placeholder:"Voucher, reference or narration..."})]})]}),L&&e.jsx("div",{className:"gl-error",children:"From Date cannot be after To Date."}),H?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gl-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Account"}),e.jsxs("strong",{children:[H.code," · ",H.name]}),e.jsx("small",{children:H.type})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Opening Balance"}),e.jsx("strong",{children:_f(H.type,M.openingBalance)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Period Debit"}),e.jsx("strong",{children:bu(M.totalDebit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Period Credit"}),e.jsx("strong",{children:bu(M.totalCredit)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Closing Balance"}),e.jsx("strong",{children:_f(H.type,M.closingBalance)})]})]}),e.jsx("div",{className:"gl-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"VOUCHER"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"BRANCH"}),e.jsx("th",{children:"REFERENCE / NARRATION"}),e.jsx("th",{className:"amount",children:"DEBIT"}),e.jsx("th",{className:"amount",children:"CREDIT"}),e.jsx("th",{className:"amount",children:"RUNNING BALANCE"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"opening-row",children:[e.jsx("td",{children:"â"}),e.jsx("td",{children:"OPENING"}),e.jsx("td",{children:"â"}),e.jsx("td",{children:D}),e.jsx("td",{children:"Balance brought forward"}),e.jsx("td",{children:"â"}),e.jsx("td",{children:"â"}),e.jsx("td",{className:"amount",children:e.jsx("strong",{children:_f(H.type,M.openingBalance)})})]}),M.rows.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty",children:"No posted transaction found in this period."})}):M.rows.map(ne=>{var ae;return e.jsxs("tr",{children:[e.jsx("td",{children:ne.voucherDate||"â"}),e.jsx("td",{children:e.jsx("strong",{children:ne.voucherNo||"â"})}),e.jsx("td",{children:ne.voucherType?o_[ne.voucherType]:"â"}),e.jsx("td",{children:((ae=n.find(Y=>Y.id===ne.branchId))==null?void 0:ae.name)||(ne.branchId?"Unknown Branch":"Company / Legacy")}),e.jsxs("td",{children:[e.jsx("span",{children:i_(ne)||"â"}),Sj(ne)&&e.jsx("small",{children:Sj(ne)})]}),e.jsx("td",{className:"amount",children:ne.debit?bu(ne.debit):"â"}),e.jsx("td",{className:"amount",children:ne.credit?bu(ne.credit):"â"}),e.jsx("td",{className:"amount",children:e.jsx("strong",{children:_f(H.type,ne.running)})})]},ne.id)})]}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("td",{colSpan:5,children:"PERIOD TOTAL"}),e.jsx("td",{className:"amount",children:bu(M.totalDebit)}),e.jsx("td",{className:"amount",children:bu(M.totalCredit)}),e.jsx("td",{className:"amount",children:_f(H.type,M.closingBalance)})]})})]})})]}):e.jsxs("div",{className:"gl-empty-state",children:[e.jsx("strong",{children:"Select an account"}),e.jsx("span",{children:"Choose an account above to view its General Ledger."})]}),J&&e.jsxs("div",{className:"gl-pdf-fullscreen",role:"dialog","aria-modal":"true","aria-label":"General Ledger PDF Preview",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"PDF PREVIEW"}),e.jsx("strong",{children:"General Ledger"}),e.jsxs("small",{children:[H==null?void 0:H.code," · ",H==null?void 0:H.name," · ",y," to ",N," · ",D]})]}),e.jsxs("div",{children:[e.jsxs("a",{href:J,download:G,children:[e.jsx(Uu,{size:16}),"Download PDF"]}),e.jsxs("button",{type:"button",onClick:Z,children:[e.jsx(ja,{size:20}),e.jsx("span",{children:"Close"})]})]})]}),e.jsx("main",{children:e.jsx("iframe",{src:J,title:"General Ledger PDF Preview"})})]})]})}const N7=()=>new Date().toISOString().slice(0,10),S7=()=>{const t=new Date;return`${t.getFullYear()}
3932-${String(t.getMonth()+1).padStart(2,"0")}-01`},kf=t=>Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2});function C7({profile:t,branches:n,selectedBranchId:a}){var $;const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState(S7()),[u,f]=x.useState(N7()),[g,p]=x.useState(!1),[y,b]=x.useState(!0),[N,w]=x.useState(""),[C,R]=x.useState(""),[I,_]=x.useState(null),[J,T]=x.useState(a),[G,z]=x.useState("accounts");x.useEffect(()=>T(a),[a]),x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),F=>{const P=F.exists()?Object.entries(F.val()).map(([ue,me])=>({id:ue,...me})):[];i(P.filter(ue=>ue.active!==!1&&(ue.type==="income"||ue.type==="expense")).sort((ue,me)=>ue.code.localeCompare(me.code,void 0,{numeric:!0})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingLedgerEntries/${t.companyId}`),F=>{const P=F.exists()?Object.entries(F.val()).map(([ue,me])=>({id:ue,...me})):[];l(P.filter(ue=>ue.status==="posted"))}),[t.companyId]);const H=!!(m&&u&&m>u),K=J==="all"?"All Branches":(($=n.find(F=>F.id===J))==null?void 0:$.name)||"Selected Branch",L=x.useMemo(()=>s.filter(F=>!F.isGroup).map(F=>{const P=c.filter(de=>de.accountId===F.id&&(J==="all"||de.branchId===J)&&(!de.voucherDate||de.voucherDate>=m)&&(!de.voucherDate||de.voucherDate<=u)),ue=P.reduce((de,Pe)=>de+Number(Pe.debit||0),0),me=P.reduce((de,Pe)=>de+Number(Pe.credit||0),0),ge=F.type==="income"?me-ue:ue-me;return{...F,amount:ge}}),[s,c,J,m,u]),D=x.useMemo(()=>Jf(s,L.filter(F=>F.type==="income"),G).filter(F=>!y||Math.abs(F.amount)>.004),[s,L,G,y]),M=x.useMemo(()=>Jf(s,L.filter(F=>F.type==="expense"),G).filter(F=>!y||Math.abs(F.amount)>.004),[s,L,G,y]),Z=L.filter(F=>F.type==="income").reduce((F,P)=>F+Number(P.amount||0),0),fe=L.filter(F=>F.type==="expense").reduce((F,P)=>F+Number(P.amount||0),0),q=Z-fe,ne=async()=>{var F;if(!H){p(!0);try{const P=await fc(t.companyId).catch(()=>({name:"",logoUrl:""})),ue=new Ra({orientation:"portrait",unit:"mm",format:"a4",compress:!0}),me=ue.internal.pageSize.getWidth();ue.setFillColor(10,61,98),ue.rect(0,0,me,4,"F"),ue.setTextColor(24,43,59),ue.setFont("helvetica","bold"),ue.setFontSize(18),ue.text(P.name||"Company",12,15),ue.setTextColor(10,61,98),ue.setFontSize(15),ue.text("INCOME STATEMENT",me-12,15,{align:"right"}),ue.setFont("helvetica","normal"),ue.setTextColor(101,119,136),ue.setFontSize(8.5),ue.text(`Branch: ${K}`,12,21),ue.text(`View: ${G==="control"?"Control Wise":G==="subsidiary"?"Subsidiary Wise":"Ledger Accounts Wise"}`,12,25),ue.text(`Period: ${m} to ${u}`,me-12,21,{align:"right"});const ge=[];ge.push([{content:"INCOME",colSpan:2,styles:{fontStyle:"bold",fillColor:[245,248,251]}}]),D.forEach(Be=>ge.push([`${Be.code} · ${Be.name}`,kf(Be.amount)])),ge.push([{content:"Total Income",styles:{fontStyle:"bold"}},{content:kf(Z),styles:{fontStyle:"bold",halign:"right"}}]),ge.push([{content:"EXPENSES",colSpan:2,styles:{fontStyle:"bold",fillColor:[245,248,251]}}]),M.forEach(Be=>ge.push([`${Be.code} · ${Be.name}`,kf(Be.amount)])),ge.push([{content:"Total Expenses",styles:{fontStyle:"bold"}},{content:kf(fe),styles:{fontStyle:"bold",halign:"right"}}]),oi(ue,{startY:31,head:[["Account","Amount"]],body:ge,theme:"grid",styles:{font:"helvetica",fontSize:9,cellPadding:2.6,lineColor:[218,226,234],lineWidth:.15},headStyles:{fillColor:[10,61,98],textColor:[255,255,255],fontStyle:"bold"},columnStyles:{1:{halign:"right",cellWidth:42}}});const de=((F=ue.lastAutoTable)==null?void 0:F.finalY)||100;ue.setFillColor(q>=0?232:253,q>=0?247:235,q>=0?238:235),ue.roundedRect(12,de+7,me-24,16,2,2,"F"),ue.setFont("helvetica","bold"),ue.setFontSize(12),ue.setTextColor(q>=0?20:170,q>=0?110:40,q>=0?60:40),ue.text(q>=0?"NET PROFIT":"NET LOSS",16,de+17),ue.text(kf(Math.abs(q)),me-16,de+17,{align:"right"}),N&&URL.revokeObjectURL(N);const Pe=`Income_Statement_${m}_to_${u}.pdf`,Re=ue.output("blob"),Ee=URL.createObjectURL(Re);R(Pe),_(Re),w(`${Ee}#toolbar=0&navpanes=0&scrollbar=1&zoom=75`)}finally{p(!1)}}},ae=F=>{F&&URL.revokeObjectURL(F.split("#")[0])},Y=()=>{ae(N),w(""),R(""),_(null)},je=()=>{if(!I)return;const F=URL.createObjectURL(I),P=document.createElement("a");P.href=F,P.download=C||"Income_Statement.pdf",document.body.appendChild(P),P.click(),P.remove(),setTimeout(()=>URL.revokeObjectURL(F),0)},V=()=>
3932{if(!I)return;const F=URL.createObjectURL(I),P=document.createElement("iframe");P.style.position="fixed",P.style.right="0",P.style.bottom="0",P.style.width="0",P.style.height="0",P.style.border="0",P.src=F,P.onload=()=>{var ue,me;try{(ue=P.contentWindow)==null||ue.focus(),(me=P.contentWindow)==null||me.print()}finally{setTimeout(()=>{P.remove(),URL.revokeObjectURL(F)},1e3)}},document.body.appendChild(P)};return x.useEffect(()=>()=>{ae(N)},[N]),e.jsxs("section",{className:"trial-balance-page",children:[e.jsxs("header",{className:"trial-balance-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h1",{children:"Income Statement"}),e.jsx("p",{children:"Professional period income statement from posted ledger entries."})]}),e.jsxs("button",{className:"button primary",disabled:g||H,onClick:ne,children:[e.jsx(Uu,{size:17}),g?"Preparing...":"View Report"]})]}),e.jsxs("div",{className:"trial-balance-filterbar",children:[e.jsxs("label",{children:[e.jsx("span",{children:"From Date"}),e.jsxs("div",{className:"tb-input-icon",children:[e.jsx(wi,{size:16}),e.jsx("input",{type:"date",value:m,onChange:F=>d(F.target.value)})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"To Date"}),e.jsxs("div",{className:"tb-input-icon",children:[e.jsx(wi,{size:16}),e.jsx("input",{type:"date",value:u,onChange:F=>f(F.target.value)})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Branch"}),e.jsxs("select",{value:J,onChange:F=>T(F.target.value),children:[e.jsx("option",{value:"all",children:"All Branches"}),n.filter(F=>F.active!==!1).map(F=>e.jsx("option",{value:F.id,children:F.name},F.id))]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Report Level"}),e.jsxs("select",{value:G,onChange:F=>z(F.target.value),children:[e.jsx("option",{value:"control",children:"Control Wise"}),e.jsx("option",{value:"subsidiary",children:"Subsidiary Wise"}),e.jsx("option",{value:"accounts",children:"Ledger Accounts Wise"})]})]}),e.jsxs("label",{className:"tb-check",children:[e.jsx("input",{type:"checkbox",checked:y,onChange:F=>b(F.target.checked)}),e.jsx("span",{children:"Skip Zero"})]})]}),H&&e.jsx("div",{className:"tb-alert danger",children:"From Date cannot be later than To Date."}),e.jsx("section",{className:"income-statement-ready-card",children:e.jsxs("div",{children:[e.jsx("strong",{children:"Report ready"}),e.jsx("span",{children:"Select Date From, Date To, Branch and Report Level, then open View Report."})]})}),N&&e.jsx("div",{className:"tb-pdf-overlay",role:"dialog","aria-modal":"true","aria-label":"Income Statement PDF Preview",children:e.jsxs("div",{className:"tb-pdf-modal tb-pdf-modal-full",children:[e.jsxs("div",{className:"tb-pdf-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Income Statement"}),e.jsxs("span",{children:[K," · ",m," to ",u]})]}),e.jsxs("div",{className:"tb-pdf-actions",children:[e.jsx("button",{type:"button",className:"button primary",onClick:V,children:"Print"}),e.jsx("button",{type:"button",className:"button primary",onClick:je,children:"Download PDF"}),e.jsx("button",{type:"button",className:"button secondary",onClick:Y,children:"Close"})]})]}),e.jsx("iframe",{title:C||"Income Statement PDF",src:N})]})})]})}const A7=()=>new Date().toISOString().slice(0,10),fd=t=>Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2});function I7({profile:t,branches:n,selectedBranchId:a}){var me;const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState({}),[u,f]=x.useState(A7()),[g,p]=x.useState(a),[y,b]=x.useState(!0),[N,w]=x.useState(!1),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState(null),[G,z]=x.useState("accounts");x.useEffect(()=>p(a),[a]),x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),ge=>{const de=ge.exists()?Object.entries(ge.val()).map(([Pe,Re])=>({id:Pe,...Re})):[];i(de.filter(Pe=>Pe.active!==!1).sort((Pe,Re)=>Pe.code.localeCompare(Re.code,void 0,{numeric:!0})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingLedgerEntries/${t.companyId}`),ge=>{const de=ge.exists()?Object.entries(ge.val()).map(([Pe,Re])=>({id:Pe,...Re})):[];l(de.filter(Pe=>Pe.status==="posted"))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingOpeningBalances/${t.companyId}`),ge=>{d(ge.exists()?ge.val():{})}),[t.companyId]);const H=g==="all"?"All Branches":((me=n.find(ge=>ge.id===g))==null?void 0:me.name)||"Selected Branch",K=x.useMemo(()=>s.filter(ge=>!ge.isGroup).map(ge=>{const de=g==="all"?m[ge.id]:void 0,Pe=Number((de==null?void 0:de.debit)||0),Re=Number((de==null?void 0:de.credit)||0),Ee=c.filter(ee=>ee.accountId===ge.id&&(g==="all"||ee.branchId===g)&&(!ee.voucherDate||ee.voucherDate<=u)),Be=Pe+Ee.reduce((ee,qe)=>ee+Number(qe.debit||0),0),We=Re+Ee.reduce((ee,qe)=>ee+Number(qe.credit||0),0),it=Be-We,_e=ge.type==="asset"||ge.type==="expense"?it:-it;return{...ge,amount:_e}}),[s,c,m,g,u]),L=x.useMemo(()=>Jf(s,K.filter(ge=>ge.type==="asset"),G).filter(ge=>!y||Math.abs(ge.amount)>.004),[s,K,G,y]),D=x.useMemo(()=>Jf(s,K.filter(ge=>ge.type==="liability"),G).filter(ge=>!y||Math.abs(ge.amount)>.004),[s,K,G,y]),M=x.useMemo(()=>Jf(s,K.filter(ge=>ge.type==="equity"),G).filter(ge=>!y||Math.abs(ge.amount)>.004),[s,K,G,y]),Z=x.useMemo(()=>{const ge=K.filter(Pe=>Pe.type==="income").reduce((Pe,Re)=>Pe+Number(Re.amount||0),0),de=K.filter(Pe=>Pe.type==="expense").reduce((Pe,Re)=>Pe+Number(Re.amount||0),0);return ge-de},[K]),fe=K.filter(ge=>ge.type==="asset").reduce((ge,de)=>ge+Number(de.amount||0),0),q=K.filter(ge=>ge.type==="liability").reduce((ge,de)=>ge+Number(de.amount||0),0),ne=K.filter(ge=>ge.type==="equity").reduce((ge,de)=>ge+Number(de.amount||0),0)+Z,ae=q+ne,je=Math.abs(fe-ae)<.005,V=async()=>{var ge;w(!0);try{const de=await fc(t.companyId).catch(()=>({name:"",logoUrl:""})),Pe=new Ra({orientation:"portrait",unit:"mm",format:"a4",compress:!0}),Re=Pe.internal.pageSize.getWidth();
3932Pe.setFillColor(10,61,98),Pe.rect(0,0,Re,4,"F"),Pe.setTextColor(24,43,59),Pe.setFont("helvetica","bold"),Pe.setFontSize(18),Pe.text(de.name||"Company",12,15),Pe.setTextColor(10,61,98),Pe.setFontSize(15),Pe.text("BALANCE SHEET",Re-12,15,{align:"right"}),Pe.setFont("helvetica","normal"),Pe.setTextColor(101,119,136),Pe.setFontSize(8.5),Pe.text(`Branch: ${H}`,12,21),Pe.text(`View: ${G==="control"?"Control Wise":G==="subsidiary"?"Subsidiary Wise":"Ledger Accounts Wise"}`,12,25),Pe.text(`As of: ${u}`,Re-12,21,{align:"right"});const Ee=[];Ee.push([{content:"ASSETS",colSpan:2,styles:{fontStyle:"bold",fillColor:[245,248,251]}}]),L.forEach(ee=>Ee.push([`${ee.code} · ${ee.name}`,fd(ee.amount)])),Ee.push([{content:"Total Assets",styles:{fontStyle:"bold"}},{content:fd(fe),styles:{fontStyle:"bold",halign:"right"}}]),Ee.push([{content:"LIABILITIES",colSpan:2,styles:{fontStyle:"bold",fillColor:[245,248,251]}}]),D.forEach(ee=>Ee.push([`${ee.code} · ${ee.name}`,fd(ee.amount)])),Ee.push([{content:"Total Liabilities",styles:{fontStyle:"bold"}},{content:fd(q),styles:{fontStyle:"bold",halign:"right"}}]),Ee.push([{content:"EQUITY",colSpan:2,styles:{fontStyle:"bold",fillColor:[245,248,251]}}]),M.forEach(ee=>Ee.push([`${ee.code} · ${ee.name}`,fd(ee.amount)])),Ee.push(["Current Period Profit / (Loss)",fd(Z)]),Ee.push([{content:"Total Equity",styles:{fontStyle:"bold"}},{content:fd(ne),styles:{fontStyle:"bold",halign:"right"}}]),oi(Pe,{startY:31,head:[["Account","Amount"]],body:Ee,theme:"grid",styles:{font:"helvetica",fontSize:9,cellPadding:2.6,lineColor:[218,226,234],lineWidth:.15},headStyles:{fillColor:[10,61,98],textColor:[255,255,255],fontStyle:"bold"},columnStyles:{1:{halign:"right",cellWidth:44}}});const Be=((ge=Pe.lastAutoTable)==null?void 0:ge.finalY)||120;Pe.setFillColor(je?232:253,je?247:235,je?238:235),Pe.roundedRect(12,Be+7,Re-24,18,2,2,"F"),Pe.setFont("helvetica","bold"),Pe.setFontSize(11),Pe.setTextColor(je?20:170,je?110:40,je?60:40),Pe.text("Assets",16,Be+18),Pe.text(fd(fe),70,Be+18,{align:"right"}),Pe.text("Liabilities + Equity",85,Be+18),Pe.text(fd(ae),Re-16,Be+18,{align:"right"});const We=`Balance_Sheet_${u}.pdf`,it=Pe.output("blob"),_e=URL.createObjectURL(it);_(We),T(it),R(`${_e}#toolbar=0&navpanes=0&scrollbar=1&zoom=75`)}finally{w(!1)}},$=ge=>{ge&&URL.revokeObjectURL(ge.split("#")[0])},F=()=>{$(C),R(""),_(""),T(null)},P=()=>{if(!J)return;const ge=URL.createObjectURL(J),de=document.createElement("a");de.href=ge,de.download=I||"Balance_Sheet.pdf",document.body.appendChild(de),de.click(),de.remove(),setTimeout(()=>URL.revokeObjectURL(ge),0)},ue=()=>{if(!J)return;const ge=URL.createObjectURL(J),de=document.createElement("iframe");de.style.position="fixed",de.style.right="0",de.style.bottom="0",de.style.width="0",de.style.height="0",de.style.border="0",de.src=ge,de.onload=()=>{var Pe,Re;try{(Pe=de.contentWindow)==null||Pe.focus(),(Re=de.contentWindow)==null||Re.print()}finally{setTimeout(()=>{de.remove(),URL.revokeObjectURL(ge)},1e3)}},document.body.appendChild(de)};return x.useEffect(()=>()=>{$(C)},[C]),e.jsxs("section",{className:"trial-balance-page",children:[e.jsxs("header",{className:"trial-balance-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h1",{children:"Balance Sheet"}),e.jsx("p",{children:"Financial position as of a selected date from posted ledger entries."})]}),e.jsxs("button",{className:"button primary",disabled:N,onClick:V,children:[e.jsx(Uu,{size:17}),N?"Preparing...":"View Report"]})]}),e.jsxs("div",{className:"trial-balance-filterbar",children:[e.jsxs("label",{children:[e.jsx("span",{children:"As of Date"}),e.jsxs("div",{className:"tb-input-icon",children:[e.jsx(wi,{size:16}),e.jsx("input",{type:"date",value:u,onChange:ge=>f(ge.target.value)})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Branch"}),e.jsxs("select",{value:g,onChange:ge=>p(ge.target.value),children:[e.jsx("option",{value:"all",children:"All Branches"}),n.filter(ge=>ge.active!==!1).map(ge=>e.jsx("option",{value:ge.id,children:ge.name},ge.id))]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Report Level"}),e.jsxs("select",{value:G,onChange:ge=>z(ge.target.value),children:[e.jsx("option",{value:"control",children:"Control Wise"}),e.jsx("option",{value:"subsidiary",children:"Subsidiary Wise"}),e.jsx("option",{value:"accounts",children:"Ledger Accounts Wise"})]})]}),e.jsxs("label",{className:"tb-check",children:[e.jsx("input",{type:"checkbox",checked:y,onChange:ge=>b(ge.target.checked)}),e.jsx("span",{children:"Skip Zero"})]})]}),e.jsx("section",{className:"income-statement-ready-card",children:e.jsxs("div",{children:[e.jsx("strong",{children:"Report ready"}),e.jsx("span",{children:"Select As of Date, Branch and Report Level, then open View Report."})]})}),C&&e.jsx("div",{className:"tb-pdf-overlay",role:"dialog","aria-modal":"true","aria-label":"Balance Sheet PDF Preview",children:e.jsxs("div",{className:"tb-pdf-modal tb-pdf-modal-full",children:[e.jsxs("div",{className:"tb-pdf-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Balance Sheet"}),e.jsxs("span",{children:[H," · As of ",u]}
3932)]}),e.jsxs("div",{className:"tb-pdf-actions",children:[e.jsx("button",{type:"button",className:"button primary",onClick:ue,children:"Print"}),e.jsx("button",{type:"button",className:"button primary",onClick:P,children:"Download PDF"}),e.jsx("button",{type:"button",className:"button secondary",onClick:F,children:"Close"})]})]}),e.jsx("iframe",{title:I||"Balance Sheet PDF",src:C})]})})]})}const Rl=t=>{const n=Number(t);return Number.isFinite(n)?n:0},Cj=t=>{if(t==null||t==="")return null;const n=Number(t);return Number.isFinite(n)?n:null},Vr=t=>t.toLocaleString("en-BD",{maximumFractionDigits:3}),qm=t=>t.toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2});function Df(t){return t.serialRequired?t.serialPendingQty<=0&&t.serialLinkedQty>0?"Reconciled":t.serialLinkedQty>0?"Partial":t.serialCount>0?"Reference available":"Pending / unverified":"Not Required"}function _7({profile:t,branches:n,selectedBranchId:a}){const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState(!1),[u,f]=x.useState(""),[g,p]=x.useState(()=>{const pe=sessionStorage.getItem("verixoStockTraceSerial")||"";return pe&&sessionStorage.removeItem("verixoStockTraceSerial"),pe}),[y,b]=x.useState("all"),[N,w]=x.useState("all"),[C,R]=x.useState(!0),[I,_]=x.useState(!1),[J,T]=x.useState(""),[G,z]=x.useState(""),[H,K]=x.useState(null),[L,D]=x.useState(null),[M,Z]=x.useState(""),[fe,q]=x.useState(!1),[ne,ae]=x.useState(""),[Y,je]=x.useState([]),V=x.useMemo(()=>new Map(n.map(pe=>[pe.id,pe.name])),[n]),$=x.useMemo(()=>n.filter(pe=>pe.active!==!1&&!["all","all_branches","all-branches"].includes(String(pe.id||"").toLowerCase())),[n]),F=x.useCallback(pe=>V.has(pe)?pe:$.length===1?$[0].id:pe,[V,$]),P=x.useCallback(async()=>{var pe,Se;d(!0),f("");try{const Me=t.companyId,[ot,wt,ct,Ce,De]=await Promise.all([mn(re(ie,`inventoryProducts/${Me}`)),mn(re(ie,`inventoryStock/${Me}`)),mn(re(ie,`inventoryOpeningBatches/${Me}`)),mn(re(ie,`inventoryOpeningItems/${Me}`)),mn(re(ie,`historicalSales/${Me}`)).catch(()=>null)]),Te=ot.val()||{},ce=wt.val()||{},Ye=Object.values(ct.val()||{}),Je=Ce.val()||{},le=((pe=De==null?void 0:De.val)==null?void 0:pe.call(De))||{},nt=[];Object.values(le).forEach(te=>{a!=="all"&&te.branchId!==a||(te.items||[]).forEach(Ge=>(Ge.serials||[]).forEach(pt=>{const $e=String(pt||"").trim();$e&&nt.push({serial:$e,product:String(Ge.product||""),branchId:String(te.branchId||""),branchName:String(te.branchName||V.get(String(te.branchId||""))||""),invoice:String(te.sourceInvoiceNo||""),customer:[te.customer,te.customerContact].filter(Boolean).join(" · "),saleDate:String(te.saleDate||""),salesperson:String(te.salespersonName||te.sourceSalesmanName||"")})}))}),je(nt);const xt=[];for(const[te,Ge]of Object.entries(ce)){const pt=F(te);if(!(a!=="all"&&pt!==a))for(const[$e,st]of Object.entries(Ge||{})){if(!st)continue;const Nt=String(st.productId||$e),be=Te[Nt]||{id:Nt},jt=Rl(st.qty),bt=Cj(st.currentReferenceCostPerUnit)??Cj(st.lastPurchaseCostPerUnit),tn=st.sourceBatchId?(Se=Je[st.sourceBatchId])==null?void 0:Se[Nt]:void 0,B=((tn==null?void 0:tn.reliableCurrentReferenceSerials)||[]).map($t=>String($t||"").trim()).filter(Boolean),xe=(st.postCutoverPurchaseSerials||[]).map($t=>String($t||"").trim()).filter(Boolean),tt=(st.manualReconciledSerials||[]).map($t=>String($t||"").trim()).filter(Boolean),ht=new Set((st.postCutoverSoldSerials||[]).map($t=>String($t||"").trim()).filter(Boolean)),dt=[...new Set([...B,...xe,...tt])].filter($t=>!ht.has($t)),we=Rl(st.referenceSerialLinkedQty),rt=Rl(st.referenceSerialPendingQty),St=Rl(st.postCutoverPurchaseQty),Qt=Math.max(0,St-new Set(xe).size),gn=new Set(tt).size,An=!!(be.serialControlled||be.serialTracking||be.requiresSerial||be.hasSerial||be.serialized),Sn=dt.length>0||B.length>0||xe.length>0||tt.length>0,Xt=An||Sn,Wt=Xt?Math.min(jt,Math.max(we,B.length)+new Set(xe).size+gn):0,Gt=Xt?Math.max(0,rt+Qt-gn):0;xt.push({key:`${pt}:${Nt}`,branchId:pt,branchName:V.get(pt)||pt,productId:Nt,productName:String(be.name||Nt),category:String(be.category||"Uncategorized"),model:String(be.model||""),unit:String(be.unit||"Unit"),qty:jt,openingQty:Rl(st.openingQty),openingDate:String(st.openingDate||""),cost:bt,value:bt===null?null:jt*bt,currentReferenceQty:Cj(st.currentReferenceQty),serialCount:Xt?Math.max(Rl(st.currentReferenceSerialCount),dt.length):0,serialRequired:Xt,serialLinkedQty:Wt,serialPendingQty:Gt,serialStatus:String(st.serialStatus||""),serialNumbers:dt})}}xt.sort((te,Ge)=>te.branchName.localeCompare(Ge.branchName)||te.productName.localeCompare(Ge.productName)),i(xt),l(Ye.filter(te=>a==="all"||te.branchId===a))}catch(Me){console.error("Stock report load failed",Me),i([]),l([]),f(Me instanceof Error?Me.message:"Stock report could not be loaded.")}finally{d(!1)}},[t.companyId,a,V,F]);x.useEffect(()=>{P()},[P]);const ue=async()=>
3932{if(!L)return;const pe=[...new Set(M.split(/[\s,;]+/).map(Me=>Me.trim()).filter(Boolean))];if(!pe.length){ae("Enter at least one serial number.");return}if(pe.length>L.serialPendingQty){ae(`Only ${Vr(L.serialPendingQty)} serial(s) are pending for this stock row.`);return}const Se=new Map;s.forEach(Me=>Me.serialNumbers.forEach(ot=>Se.set(ot.toLowerCase(),Me)));for(const Me of pe){const ot=Se.get(Me.toLowerCase());if(ot){ae(`Serial ${Me} is already linked to ${ot.productName} (${ot.branchName}).`);return}}q(!0),ae("");try{const ot=`inventoryStock/${t.companyId}/${L.branchId}/${L.productId}`,ct=(await mn(re(ie,ot))).val()||{},Ce=(ct.manualReconciledSerials||[]).map(String).filter(Boolean),De=[...new Set([...Ce,...pe])],Te=`${Date.now()}_${Math.random().toString(36).slice(2,8)}`;await yn(re(ie,ot),{manualReconciledSerials:De,[`serialReconciliationAudit/${Te}`]:{serials:pe,count:pe.length,source:"manual_missing_serial_reconciliation",addedAt:Date.now(),addedByUid:t.uid||"",addedByName:t.name||t.email||"",qtyBefore:Rl(ct.qty),qtyAfter:Rl(ct.qty)}}),D(null),Z(""),await P()}catch(Me){ae(Me instanceof Error?Me.message:"Serial reconciliation failed.")}finally{q(!1)}},me=x.useMemo(()=>[...new Set(s.map(pe=>pe.category).filter(Boolean))].sort((pe,Se)=>pe.localeCompare(Se)),[s]),ge=x.useMemo(()=>{const pe=g.trim().toLowerCase();return s.filter(Se=>C&&Se.qty<=0&&!(pe&&Se.openingQty>0)||y!=="all"&&Se.category!==y||N!=="all"&&Df(Se)!==N?!1:pe?[Se.productName,Se.productId,Se.category,Se.model,Se.branchName,...Se.serialNumbers].some(Me=>Me.toLowerCase().includes(pe)):!0)},[s,g,y,N,C]),de=x.useMemo(()=>s.filter(pe=>pe.openingQty>0&&pe.qty<=0),[s]),Pe=x.useMemo(()=>{const pe=ge.reduce((Ce,De)=>Ce+De.qty,0),Se=ge.reduce((Ce,De)=>Ce+De.openingQty,0),Me=ge.filter(Ce=>Ce.cost!==null),ot=Me.reduce((Ce,De)=>Ce+(De.value||0),0),wt=ge.reduce((Ce,De)=>Ce+De.serialLinkedQty,0),ct=ge.reduce((Ce,De)=>Ce+De.serialPendingQty,0);return{totalQty:pe,totalOpeningQty:Se,totalValue:ot,valuedRows:Me.length,serialLinked:wt,serialPending:ct}},[ge]),Re=x.useMemo(()=>[...c].sort((Se,Me)=>Rl(Me.createdAt)-Rl(Se.createdAt))[0]||null,[c]),Ee=s.filter(pe=>pe.openingQty!==0),Be=!!Re&&Number((Re==null?void 0:Re.productCount)||0)===Ee.length&&Math.abs(Number((Re==null?void 0:Re.totalQty)||0)-s.reduce((pe,Se)=>pe+Se.openingQty,0))<.001,We=pe=>{pe&&URL.revokeObjectURL(pe.split("#")[0])},it=()=>{We(J),T(""),z(""),K(null)},_e=()=>{if(!H)return;const pe=URL.createObjectURL(H),Se=document.createElement("a");Se.href=pe,Se.download=G||"VERIXO_Stock_Report.pdf",document.body.appendChild(Se),Se.click(),Se.remove(),setTimeout(()=>URL.revokeObjectURL(pe),0)},ee=()=>{if(!H)return;const pe=URL.createObjectURL(H),Se=document.createElement("iframe");Se.style.position="fixed",Se.style.right="0",Se.style.bottom="0",Se.style.width="0",Se.style.height="0",Se.style.border="0",Se.src=pe,Se.onload=()=>{var Me,ot;try{(Me=Se.contentWindow)==null||Me.focus(),(ot=Se.contentWindow)==null||ot.print()}finally{setTimeout(()=>{Se.remove(),URL.revokeObjectURL(pe)},1e3)}},document.body.appendChild(Se)},qe=async()=>{var pe;if(!(!ge.length||I)){_(!0),f("");try{const Se=await fc(t.companyId).catch(()=>({name:"",logoUrl:""})),Me=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),ot=Me.internal.pageSize.getWidth(),wt=a==="all"?"All Branches":V.get(a)||a,ct=(Re==null?void 0:Re.openingDate)||((pe=ge.find(le=>le.openingDate))==null?void 0:pe.openingDate)||"â";Me.setFillColor(10,61,98),Me.rect(0,0,ot,4,"F"),Me.setTextColor(24,43,59),Me.setFont("helvetica","bold"),Me.setFontSize(17),Me.text(Se.name||"Company",10,14),Me.setTextColor(10,61,98),Me.setFontSize(14),Me.text("STOCK REPORT",ot-10,14,{align:"right"}),Me.setFont("helvetica","normal"),Me.setTextColor(94,110,124),Me.setFontSize(7.8),Me.text(`Branch: ${wt}`,10,20),Me.text(`Opening Date: ${ct}`,10,24),Me.text(`Products: ${ge.length.toLocaleString("en-BD")} | Stock Qty: ${Vr(Pe.totalQty)} | Opening Qty: ${Vr(Pe.totalOpeningQty)} | Serial Linked/Pending: ${Vr(Pe.serialLinked)} / ${Vr(Pe.serialPending)}`,ot-10,20,{align:"right"}),Me.text(`Stock Value (safe cost references only): BDT ${qm(Pe.totalValue)} | Cost available: ${Pe.valuedRows}/${ge.length}`,ot-10,24,{align:"right"});const Ce=ge.map((le,nt)=>[String(nt+1),`${le.productName} 3933${le.productId}`,`${le.category}${le.model?` 3934${le.model}`:""}`,...a==="all"?[le.branchName]:[],Vr(le.qty),le.currentReferenceQty===null?"â":Vr(le.currentReferenceQty),le.cost===null?"Pending":qm(le.cost),le.value===null?"â":qm(le.value),le.serialRequired?le.serialNumbers.length?le.serialNumbers.join(", "):"â":"Not required",le.serialRequired?`${Df(le)} 3935${Vr(le.serialLinkedQty)} linked / ${Vr(le.serialPendingQty)} pending`:"Not Required"]),De=[["#","Product","Category / Model",...a==="all"?["Branch"]:[],"Qty","Ref Qty","Cost/Unit","Stock Value","Serial Number(s)","Serial Status"]];let Te;a==="all"?Te={0:{cellWidth:7,halign:"right"},1:{cellWidth:45},2:{cellWidth:37},3:{cellWidth:20},4:{cellWidth:14,halign:"right"},5:{cellWidth:14,halign:"right"},6:{cellWidth:19,halign:"right"},7:{cellWidth:22,halign:"right"},8:{cellWidth:55},9:{cellWidth:44}}:Te={0:{cellWidth:7,halign:"right"},1:{cellWidth:50},2:{cellWidth:42},3:{cellWidth:15,halign:"right"},4:{cellWidth:15,halign:"right"},5:{cellWidth:21,halign:"right"},6:{cellWidth:25,halign:"right"},7:{cellWidth:70},8:{cellWidth:36}},oi(Me,{startY:29,head:De,body:Ce,theme:"grid",styles:{font:"helvetica",fontSize:6.2,cellPadding:1.4,lineColor:[218,226,234],lineWidth:.12,overflow:"linebreak",valign:"top"},headStyles:{fillColor:[10,61,98],textColor:[255,255,255],fontStyle:"bold",fontSize:6.5},columnStyles:Te,margin:{left:8,right:8,bottom:10},didDrawPage:le=>{const nt=Me.getNumberOfPages();Me.setFont("helvetica","normal"),Me.setFontSize(6.5),Me.setTextColor(110,124,137),Me.text(`VERIXO Stock Report · ${wt} · Page ${le.pageNumber}`,8,Me.internal.pageSize.getHeight()-4),nt>1}});const ce=`VERIXO_Stock_Report_${a==="all"?"All_Branches":V.get(a)||a}.pdf`;We(J);
3935const Ye=Me.output("blob"),Je=URL.createObjectURL(Ye);z(ce),K(Ye),T(`${Je}#toolbar=0&navpanes=0&scrollbar=1&view=FitH`)}catch(Se){console.error("Stock report PDF generation failed",Se),f(Se instanceof Error?Se.message:"Stock report PDF could not be generated.")}finally{_(!1)}}};x.useEffect(()=>()=>{We(J)},[J]);const se=()=>{const pe=["Branch","Product ID","Product","Category","Model","Unit","Qty","Opening Qty","Opening Date","Reference Qty","Cost/Unit","Stock Value","Serial Evidence","Serial Numbers","Serial Linked Qty","Serial Pending Qty","Serial Status"],Se=Ce=>`"${String(Ce??"").replace(/"/g,'""')}"`,Me=ge.map(Ce=>[Ce.branchName,Ce.productId,Ce.productName,Ce.category,Ce.model,Ce.unit,Ce.qty,Ce.openingQty,Ce.openingDate,Ce.currentReferenceQty??"",Ce.cost??"",Ce.value??"",Ce.serialCount,Ce.serialNumbers.join(" | "),Ce.serialLinkedQty,Ce.serialPendingQty,Df(Ce)].map(Se).join(",")),ot=new Blob([[pe.map(Se).join(","),...Me].join(` 3936`)],{type:"text/csv;charset=utf-8"}),wt=URL.createObjectURL(ot),ct=document.createElement("a");ct.href=wt,ct.download=`VERIXO_Stock_Report_${a==="all"?"All_Branches":V.get(a)||a}.csv`,ct.click(),URL.revokeObjectURL(wt)};return e.jsxs("section",{className:"stock-report-page",children:[de.length>0&&e.jsxs("div",{className:"stock-report-alert warning",children:[e.jsx(gs,{size:19}),e.jsxs("div",{children:[e.jsx("strong",{children:"Opening stock depleted / quantity review"}),e.jsxs("span",{children:[de.length," product(s) have Opening Qty > 0 and current Live Qty ⤠0. This can be valid after post-cutover sales; VERIXO does not change stock automatically."]}),e.jsxs("details",{children:[e.jsx("summary",{children:"View affected product(s)"}),de.slice(0,50).map(pe=>e.jsxs("span",{children:[e.jsx("b",{children:pe.productName})," · ",pe.branchName," · Opening ",Vr(pe.openingQty)," · Live ",Vr(pe.qty)]},pe.key))]})]})]}),e.jsxs("div",{className:"stock-report-hero",children:[e.jsxs("div",{children:[e.jsx("div",{className:"stock-report-eyebrow",children:"VERIXO INVENTORY CONTROL"}),e.jsx("h1",{children:"Stock Report"}),e.jsx("p",{children:"Verify branch stock, opening quantity, cost reference, stock value and the actual serial evidence retained from Opening Stock Phase 2."})]}),e.jsxs("div",{className:"stock-report-actions no-print",children:[e.jsxs("button",{type:"button",onClick:()=>void P(),disabled:m,children:[e.jsx(Hi,{size:16}),m?"Refreshing...":"Refresh"]}),e.jsxs("button",{type:"button",onClick:se,disabled:!ge.length,children:[e.jsx(Mi,{size:16}),"Export CSV"]}),e.jsxs("button",{type:"button",onClick:()=>void qe(),disabled:!ge.length||I,children:[e.jsx(ui,{size:16}),I?"Preparing PDF...":"View PDF"]})]})]}),u&&e.jsxs("div",{className:"stock-report-alert error",children:[e.jsx("strong",{children:"Stock report unavailable"}),e.jsx("span",{children:u})]}),e.jsxs("div",{className:"stock-report-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Products / Rows"}),e.jsx("strong",{children:ge.length.toLocaleString("en-BD")}),e.jsx("small",{children:"Visible stock lines"})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Stock Qty"}),e.jsx("strong",{children:Vr(Pe.totalQty)}),e.jsx("small",{children:"Live inventory quantity"})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Opening Qty"}),e.jsx("strong",{children:Vr(Pe.totalOpeningQty)}),e.jsx("small",{children:"Opening authority retained"})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Stock Value"}),e.jsxs("strong",{children:["à§³ ",qm(Pe.totalValue)]}),e.jsxs("small",{children:["Cost available for ",Pe.valuedRows,"/",ge.length," rows"]})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Serial Linked / Pending"}),e.jsxs("strong",{children:[Vr(Pe.serialLinked)," / ",Vr(Pe.serialPending)]}),e.jsx("small",{children:"Reference evidence only"})]})]}),Re&&e.jsxs("div",{className:`stock-report-alert ${Be?"success":"warning"}`,children:[e.jsx(gs,{size:19}),e.jsxs("div",{children:[e.jsx("strong",{children:Be?"Opening migration reconciles with live stock":"Opening migration reconciliation needs review"}),e.jsxs("span",{children:["Batch ",Re.id||"â"," · ",Number(Re.productC
3936ount||0).toLocaleString("en-BD")," products · ",Vr(Number(Re.totalQty||0))," qty · Opening date ",Re.openingDate||"â"," · ",Re.referenceStatus||Re.status||"posted"]})]})]}),e.jsxs("div",{className:"stock-report-filters no-print",children:[e.jsxs("label",{className:"stock-search",children:[e.jsx(xr,{size:16}),e.jsx("input",{value:g,onChange:pe=>p(pe.target.value),placeholder:"Search product, model, ID, branch or serial"})]}),e.jsxs("select",{value:y,onChange:pe=>b(pe.target.value),children:[e.jsx("option",{value:"all",children:"All Categories"}),me.map(pe=>e.jsx("option",{value:pe,children:pe},pe))]}),e.jsxs("select",{value:N,onChange:pe=>w(pe.target.value),children:[e.jsx("option",{value:"all",children:"All Serial Status"}),e.jsx("option",{children:"Not Required"}),e.jsx("option",{children:"Reconciled"}),e.jsx("option",{children:"Partial"}),e.jsx("option",{children:"Reference available"}),e.jsx("option",{children:"Pending / unverified"})]}),e.jsxs("label",{className:"stock-positive-only",children:[e.jsx("input",{type:"checkbox",checked:C,onChange:pe=>R(pe.target.checked)})," Positive stock only"]})]}),g.trim()&&Y.filter(pe=>[pe.serial,pe.product,pe.invoice,pe.customer,pe.salesperson,pe.branchName].some(Se=>Se.toLowerCase().includes(g.trim().toLowerCase()))).length>0&&e.jsxs("div",{className:"stock-report-alert success no-print",children:[e.jsx(gs,{size:19}),e.jsxs("div",{children:[e.jsx("strong",{children:"Sold serial lifecycle match"}),Y.filter(pe=>[pe.serial,pe.product,pe.invoice,pe.customer,pe.salesperson,pe.branchName].some(Se=>Se.toLowerCase().includes(g.trim().toLowerCase()))).slice(0,10).map(pe=>e.jsxs("span",{children:[e.jsx("b",{children:pe.serial})," · ",pe.product," · SOLD · Invoice ",pe.invoice||"â"," · ",pe.customer||"Customer â"," · ",pe.saleDate||"Date â"," · ",pe.salesperson||"Salesperson â"," · ",pe.branchName||"Branch â"]}
3936,`${pe.invoice}:${pe.serial}`)),e.jsx("span",{children:"Traceability only â sold serials are not returned to live stock."})]})]}),e.jsx("div",{className:"stock-report-table-wrap",children:e.jsxs("table",{className:"stock-report-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Category / Model"}),a==="all"&&e.jsx("th",{children:"Branch"}),e.jsx("th",{className:"num",children:"Qty"}),e.jsx("th",{className:"num",children:"Ref Qty"}),e.jsx("th",{className:"num",children:"Cost / Unit"}),e.jsx("th",{className:"num",children:"Stock Value"}),e.jsx("th",{children:"Serial Number(s)"}),e.jsx("th",{children:"Serial Status"})]})}),e.jsxs("tbody",{children:[!m&&!ge.length&&e.jsx("tr",{children:e.jsxs("td",{colSpan:a==="all"?10:9,className:"stock-report-empty",children:[e.jsx(yu,{size:28}),e.jsx("strong",{children:"No stock rows found"}),e.jsx("span",{children:"Change the filters or confirm that Opening Stock Phase 1 has been posted for this branch."})]})}),ge.map((pe,Se)=>e.jsxs("tr",{children:[e.jsx("td",{children:Se+1}),e.jsxs("td",{children:[e.jsx("strong",{children:pe.productName}),e.jsxs("small",{children:[pe.unit,pe.openingDate?` · Open ${pe.openingDate}`:""]})]}),e.jsxs("td",{children:[e.jsx("strong",{children:pe.category}),e.jsx("small",{children:pe.model||"â"})]}),a==="all"&&e.jsx("td",{children:pe.branchName}),e.jsxs("td",{className:"num",children:[e.jsx("strong",{children:Vr(pe.qty)}),e.jsxs("small",{children:["Opening ",Vr(pe.openingQty)]})]}),e.jsx("td",{className:"num",children:pe.currentReferenceQty===null?"â":Vr(pe.currentReferenceQty)}),e.jsx("td",{className:"num",children:pe.cost===null?e.jsx("span",{className:"stock-muted",children:"Pending"}):`à§³ ${qm(pe.cost)}`}),e.jsx("td",{className:"num",children:pe.value===null?e.jsx("span",{className:"stock-muted",children:"â"}):`à§³ ${qm(pe.value)}`}),e.jsx("td",{className:"stock-serial-values",children:pe.serialRequired?pe.serialNumbers.length?e.jsxs("details",{children:[e.jsxs("summary",{children:[pe.serialNumbers.length.toLocaleString("en-BD")," serial(s)"]}),e.jsx("div",{children:pe.serialNumbers.map(Me=>e.jsx("code",{children:Me},Me))})]}):e.jsx("span",{className:"stock-muted",children:"No serial evidence"}):e.jsx("span",{className:"stock-muted",children:"Not required"})}),e.jsxs("td",{children:[e.jsx("span",{className:`stock-serial-badge ${Df(pe).toLowerCase().replace(/[^a-z]+/g,"-")}`,children:Df(pe)}),pe.serialRequired&&e.jsxs("small",{children:[Vr(pe.serialLinkedQty)," linked · ",Vr(pe.serialPendingQty)," pending"]}),pe.serialRequired&&pe.serialPendingQty>0&&e.jsx("button",{className:"stock-add-serial",onClick:()=>{D(pe),Z(""),ae("")},children:"Add Missing Serial"})]})]},pe.key))]})]})}),e.jsx("div",{className:"stock-report-footnote",children:"Stock Value uses a safe Phase 2 cost reference, with post-cutover Purchase cost only as a fallback where no Phase 2 cost exists. Missing cost is never guessed. Serial Number(s) combine reliable Opening Phase 2 evidence with actual post-cutover Purchase serial provenance; duplicates are removed and no fake serial is created. Opening Qty remains the detected-date authority while live Qty can move after cutover."}),L&&e.jsx("div",{className:"stock-pdf-overlay",role:"dialog","aria-modal":"true","aria-label":"Add Missing Serial",children:e.jsxs("div",{className:"stock-serial-modal",children:[e.jsx("h3",{children:"Add Missing Serial"}),e.jsx("p",{children:e.jsx("strong",{children:L.productName})}),e.jsxs("p",{children:["Qty ",Vr(L.qty)," · ",Vr(L.serialLinkedQty)," linked · ",e.jsxs("strong",{children:[Vr(L.serialPendingQty)," pending"]}),". Stock quantity will not change."]}),e.jsx("textarea",{autoFocus:!0,value:M,onChange:pe=>Z(pe.target.value),placeholder:"Enter 1 or more serials (space, comma or new line separated)"}),e.jsx("small",{children:"You may add only 1 serial now and add the remaining serials later."}),ne&&e.jsx("div",{className:"stock-serial-error",children:ne}),e.jsxs("div",{className:"stock-serial-actions",children:[e.jsx("button",{onClick:()=>D(null),disabled:fe,children:"Cancel"}),e.jsx("button",{onClick:()=>void ue(),disabled:fe,children:fe?"Savingâ¦":"Save Serial"})]})]})}),J&&e.jsx("div",{className:"stock-pdf-overlay",role:"dialog","aria-modal":"true","aria-label":"Stock Report PDF Preview",children:e.jsxs("div",{className:"stock-pdf-modal",children:[e.jsxs("div",{className:"stock-pdf-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Stock Report"}),e.jsxs("span",{children:[a==="all"?"All Branches":V.get(a)||a," · ",ge.length.toLocaleStr
3936ing("en-BD")," row(s)"]})]}),e.jsxs("div",{className:"stock-pdf-actions",children:[e.jsx("button",{type:"button",className:"primary",onClick:ee,children:"Print"}),e.jsx("button",{type:"button",className:"primary",onClick:_e,children:"Download PDF"}),e.jsx("button",{type:"button",onClick:it,children:"Close"})]})]}),e.jsx("iframe",{title:G||"Stock Report PDF",src:J})]})})]})}const qs=t=>`৳${Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Ki=t=>Math.round((Number(t)||0)*100)/100,Y1=t=>String(t||"").trim(),Ec=t=>[...new Set(String(t||"").split(/[\n,;]+/).map(Y1).filter(Boolean))],Ov=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"supplier",du=()=>({key:`line_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,productId:"",qty:1,rate:0,serialText:"",serialControlled:!1,discountType:"amount",discountValue:0,mrp:0}),Ng=t=>Math.max(0,Number(t.qty||0))*Math.max(0,Number(t.rate||0)),Q1=t=>Ki(t.discountType==="percent"?Ng(t)*Math.min(100,Math.max(0,Number(t.discountValue||0)))/100:Math.min(Ng(t),Math.max(0,Number(t.discountValue||0)))),Ef=t=>Ki(Ng(t)-Q1(t)),c_=(t,n)=>`PUR-${t}-${String(n).padStart(6,"0")}`,l_=t=>/^PUR-\d{4}-\d{6}$/i.test(String(t||"")),Aj=(t,n,a)=>typeof t=="string"?t.split(n).join(a):t,uh=t=>{const n=String(t||"").trim().toLowerCase();return!!n&&n!=="all"&&n!=="all_branches"&&n!=="all-branches"};function k7({profile:t,branches:n,selectedBranchId:a,onAddNewProduct:s,onAddNewSupplier:i,companyName:c="VERIXO",companyPhone:l="",companyAddress:m=""}){var Ae,oe,Ve;const d=sa(t,"purchase.manage"),[u,f]=x.useState({}),[g,p]=x.useState({}),[y,b]=x.useState({}),[N,w]=x.useState([]),[C,R]=x.useState([]),[I,_]=x.useState([]),[J,T]=x.useState({}),[G,z]=x.useState([]),H=n.filter(he=>uh(he.id)),K=H.length===1?H[0].id:"",L=K||(uh(a)?a:uh(t.branchId)?String(t.branchId):""),[D,M]=x.useState(L),[Z,fe]=x.useState(new Date().toISOString().slice(0,10)),[q,ne]=x.useState(""),[ae,Y]=x.useState(""),[je,V]=x.useState(""),[$,F]=x.useState(""),[P,ue]=x.useState("N/A"),[me,ge]=x.useState("BDT"),[de,Pe]=x.useState("local"),[Re,Ee]=x.useState(1),[Be,We]=x.useState([]),[it,_e]=x.useState(!1),[ee,qe]=x.useState(""),[se,pe]=x.useState(""),[Se,Me]=x.useState(""),[ot,wt]=x.useState(""),[ct,Ce]=x.useState(""),[De,Te]=x.useState(du()),[ce,Ye]=x.useState(!1),[Je,le]=x.useState(!1),[nt,xt]=x.useState(""),[te,Ge]=x.useState(new Date().toISOString().slice(0,10)),[pt,$e]=x.useState(new Date().toISOString().slice(0,10)),[st,Nt]=x.useState(""),[be,jt]=x.useState("credit"),[bt,tn]=x.useState(0),[B,xe]=x.useState(""),[tt,ht]=x.useState(""),[dt,we]=x.useState(""),[rt,St]=x.useState(new Date().toISOString().slice(0,10)),[Qt,gn]=x.useState(!1),[An,Sn]=x.useState(0),[Xt,Wt]=x.useState("");x.useEffect(()=>qt(re(ie,`inventoryProducts/${t.companyId}`),he=>f(he.val()||{})),[t.companyId]),x.useEffect(()=>qt(re(ie,`inventoryStock/${t.companyId}`),he=>{const Oe=he.val()||{},ut={};Object.values(Oe).forEach(At=>Object.entries(At||{}).forEach(([en,It])=>{const Pt=String((It==null?void 0:It.productId)||en);ut[Pt]||(ut[Pt]=It||{})})),p(ut)}),[t.companyId]),x.useEffect(()=>{const he=sessionStorage.getItem("verixo.purchase.createdProductId");if(!he||!u[he])return;const Oe=u[he];Ce(he),wt([Oe.name,Oe.model].filter(Boolean).join(" · ")),Te({...du(),productId:he,qty:1,serialControlled:!!(Oe.serialControlled||Oe.serialTracking),mrp:Number(Oe.mrp||0)}),sessionStorage.removeItem("verixo.purchase.createdProductId")},[u]),x.useEffect(()=>qt(re(ie,`supplierMaster/${t.companyId}`),he=>b(he.val()||{})),[t.companyId]),x.useEffect(()=>{const he=sessionStorage.getItem("verixo.purchase.createdSupplierId");if(!he||!y[he])return;const Oe=y[he];ne(Oe.name||""),Me(Oe.name||""),ue(Oe.paymentTerms||"N/A"),sessionStorage.removeItem("verixo.purchase.createdSupplierId")},[y]),x.useEffect(()=>qt(re(ie,`historicalPurchases/${t.companyId}`),he=>w(Object.entries(he.val()||{}).map(([Oe,ut])=>({id:Oe,...ut})))),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierOpeningPayables/${t.companyId}`),he=>R(Object.values(he.val()||{}))),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierPayments/${t.companyId}`),he=>_(Object.values(he.val()||{}))),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingBankAccounts/${t.companyId}`),he=>{const Oe=he.val()||{};z(Object.entries(Oe).map(([ut,At])=>({id:ut,...At})).filter(ut=>ut.active!==!1&&!!ut.ledgerAccountId))}),[t.companyId]),x.useEffect(()=>{if(!D){T({});return}return qt(re(ie,`inventoryStock/${t.companyId}/${D}`),he=>T(he.val()||{}))},[t.companyId,D]),x.useEffect(()=>{if(K){M(K);return}if(uh(a)){M(a);return}uh(D)||M("")},[a,K]),x.useEffect(()=>{const he=String(t.role||"");if(!d||!["super_admin","owner"].includes(he))return;let Oe=!1;return(async()=>{var ut;try{const At=await mn(re(ie,`historicalPurchases/${t.companyId}`));if(Oe)return;const en=Object.entries(At.val()||{}).map(([Vn,ua])=>({id:Vn,...ua})).filter(Vn=>Vn.sourceSystem==="verixo_live_purchase"&&!Vn.cancelled),It=en.filter(Vn=>!l_(String(Vn.sourceInvoiceNo||""))).sort((Vn,ua)=>String(Vn.purchaseDate||"").localeCompare(String(ua.purchaseDate||""))||Number(Vn.createdAt||0)-Number(ua.createdAt||0)||String(Vn.id).localeCompare(String(ua.id)));if(!It.length)return;const Pt=new Map;
3936en.forEach(Vn=>{const ua=String(Vn.sourceInvoiceNo||"").match(/^PUR-(\d{4})-(\d{6})$/i);ua&&Pt.set(ua[1],Math.max(Pt.get(ua[1])||0,Number(ua[2])))});const[Jn,na,Mn]=await Promise.all([mn(re(ie,`accountingVouchers/${t.companyId}`)),mn(re(ie,`accountingLedgerEntries/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}`))]);if(Oe)return;const Ea=Jn.val()||{},ga=na.val()||{},zn=Mn.val()||{},Xn={};for(const Vn of It){const ua=String(Vn.purchaseDate||new Date(Number(Vn.createdAt||Date.now())).toISOString().slice(0,10)).slice(0,4)||String(new Date().getFullYear()),Ma=(Pt.get(ua)||0)+1,Xe=c_(ua,Ma),Jt=String(Vn.sourceInvoiceNo||"");Pt.set(ua,Ma),Xn[`historicalPurchases/${t.companyId}/${Vn.id}/sourceInvoiceNo`]=Xe,Xn[`historicalPurchases/${t.companyId}/${Vn.id}/previousPurchaseNo`]=Jt,Xn[`historicalPurchases/${t.companyId}/${Vn.id}/purchaseNoMigratedAt`]=Date.now();const Ht=`live_purchase_${Vn.id}`,xa=Ea[Ht];xa&&(Xn[`accountingVouchers/${t.companyId}/${Ht}/voucherNo`]=`AUTO-${Xe}`,Xn[`accountingVouchers/${t.companyId}/${Ht}/reference`]=Xe,Xn[`accountingVouchers/${t.companyId}/${Ht}/narration`]=Aj(xa.narration,Jt,Xe),(xa.lines||[]).forEach((ra,Ha)=>{Xn[`accountingVouchers/${t.companyId}/${Ht}/lines/${Ha}/narration`]=Aj(ra.narration,Jt,Xe),String(ra.billNumber||"")===Jt&&(Xn[`accountingVouchers/${t.companyId}/${Ht}/lines/${Ha}/billNumber`]=Xe)})),Object.entries(ga).forEach(([ra,Ha])=>{String(Ha.sourceType||"")==="live_purchase"&&String(Ha.sourceId||"")===Vn.id&&(Xn[`accountingLedgerEntries/${t.companyId}/${ra}/voucherNo`]=`AUTO-${Xe}`,Xn[`accountingLedgerEntries/${t.companyId}/${ra}/reference`]=Xe,Xn[`accountingLedgerEntries/${t.companyId}/${ra}/narration`]=Aj(Ha.narration,Jt,Xe),String(Ha.billNumber||"")===Jt&&(Xn[`accountingLedgerEntries/${t.companyId}/${ra}/billNumber`]=Xe))});for(const ra of Vn.items||[]){const Ha=(ut=zn==null?void 0:zn[Vn.branchId])==null?void 0:ut[ra.productId];Ha&&String(Ha.lastLivePurchaseNo||"")===Jt&&(Xn[`inventoryStock/${t.companyId}/${Vn.branchId}/${ra.productId}/lastLivePurchaseNo`]=Xe)}}Pt.forEach((Vn,ua)=>Xn[`purchaseNumberSequences/${t.companyId}/${ua}`]=Vn),Object.keys(Xn).length&&await yn(re(ie),Xn)}catch(At){console.warn("Purchase number migration skipped",At)}})(),()=>{Oe=!0}},[t.companyId,t.role,d]);const Gt=x.useMemo(()=>[...new Set([...Object.keys(u),...Object.keys(g)])].map(Oe=>{const ut=u[Oe]||{id:Oe},At=g[Oe];return{...ut,id:Oe,name:ut.name||(At==null?void 0:At.productName)||(At==null?void 0:At.name)||Oe,model:ut.model||(At==null?void 0:At.model)||"",category:ut.category||(At==null?void 0:At.category)||"",unit:ut.unit||(At==null?void 0:At.unit)||"PCS"}}).filter(Oe=>Oe.deleted!==!0&&Oe.archived!==!0&&String(Oe.status||"").toLowerCase()!=="deleted").sort((Oe,ut)=>String(Oe.name||"").localeCompare(String(ut.name||""))),[u,g]),$t=x.useMemo(()=>Object.fromEntries(Gt.map(he=>[he.id,he])),[Gt]),Vt=x.useMemo(()=>{const he=new Map;return Object.entries(y).forEach(([Oe,ut])=>{(ut==null?void 0:ut.active)!==!1&&(ut!=null&&ut.name)&&he.set(ut.name.trim().toLowerCase(),{...ut,id:Oe})}),N.forEach(Oe=>{Oe.supplier&&!he.has(Oe.supplier.trim().toLowerCase())&&he.set(Oe.supplier.trim().toLowerCase(),{id:Ov(Oe.supplier),name:Oe.supplier})}),C.forEach(Oe=>{Oe.supplier&&!he.has(Oe.supplier.trim().toLowerCase())&&he.set(Oe.supplier.trim().toLowerCase(),{id:Ov(Oe.supplier),name:Oe.supplier})}),I.forEach(Oe=>{Oe.supplier&&!he.has(Oe.supplier.trim().toLowerCase())&&he.set(Oe.supplier.trim().toLowerCase(),{id:Ov(Oe.supplier),name:Oe.supplier})}),[...he.values()].filter(Oe=>Oe.name).sort((Oe,ut)=>String(Oe.name).localeCompare(String(ut.name)))},[y,N,C,I]),sn=x.useMemo(()=>{const he=Se.trim().toLowerCase();return Vt.filter(Oe=>!he||String(Oe.name||"").toLowerCase().includes(he)||String(Oe.mobile||"").includes(he)).slice(0,12)},[Vt,Se]),on=x.useMemo(()=>{const Oe=ot.trim().toLowerCase().replace(/\s+/g," ").split(" ").filter(Boolean);return Gt.filter(ut=>{if(!Oe.length)return!0;const At=[ut.name,ut.model,ut.code,ut.sku,ut.category,ut.sourceName,ut.productName].map(en=>String(en||"").toLowerCase()).join(" ").replace(/\s+/g," ");return Oe.every(en=>At.includes(en))})},[Gt,ot]),ke=x.useMemo(()=>Vt.find(he=>he.name===q),[Vt,q]),Ct=x.useMemo(()=>
3936{if(!ct)return!1;const he=u[ct],Oe=J[ct];return!!(he!=null&&he.serialControlled||he!=null&&he.serialTracking||he!=null&&he.requiresSerial||he!=null&&he.hasSerial||he!=null&&he.serialized||((Oe==null?void 0:Oe.postCutoverPurchaseSerials)||[]).length||((Oe==null?void 0:Oe.manualReconciledSerials)||[]).length||((Oe==null?void 0:Oe.reliableCurrentReferenceSerials)||[]).length||/serial|linked/i.test(String((Oe==null?void 0:Oe.serialStatus)||"")))},[ct,u,J]),Et=x.useMemo(()=>{if(!q)return 0;const he=q.trim().toLowerCase(),Oe=C.filter(en=>String(en.supplier||"").trim().toLowerCase()===he).reduce((en,It)=>en+Number(It.amount||0),0),ut=N.filter(en=>!en.cancelled&&String(en.supplier||"").trim().toLowerCase()===he).reduce((en,It)=>en+Number(It.totalAmount||0),0),At=I.filter(en=>String(en.supplier||"").trim().toLowerCase()===he).reduce((en,It)=>en+Number(It.amount||0),0);return Ki(Oe+ut-At)},[q,N,C,I]),Rt=Be.reduce((he,Oe)=>he+Math.max(0,Number(Oe.qty||0)),0),xn=Ki(Be.reduce((he,Oe)=>he+Ng(Oe),0)),dn=Ki(Be.reduce((he,Oe)=>he+Q1(Oe),0)),Ln=Ki(Be.reduce((he,Oe)=>he+Ef(Oe),0)),wa=Qt?Ki(Math.max(0,Number(An||0))):0,Ca=Ki(Ln+wa),In=be==="credit"?0:be==="cash"||be==="bank"||be==="cheque"?Ca:Ki(Math.max(0,Math.min(Ca,Number(bt||0)))),Sa=Ki(Math.max(0,Ca-In)),aa=G.find(he=>he.id===B),$a=x.useMemo(()=>N.filter(he=>!he.cancelled&&(he.sourceSystem==="verixo_live_purchase"||he.migrationMode==="live_purchase"||l_(String(he.sourceInvoiceNo||"")))).filter(he=>(!te||String(he.purchaseDate||"")>=te)&&(!pt||String(he.purchaseDate||"")<=pt)).filter(he=>a==="all"?!0:he.branchId===a).filter(he=>{const Oe=nt.trim().toLowerCase();return!Oe||[he.sourceInvoiceNo,he.previousPurchaseNo,he.supplierInvoiceRefNo,he.supplier,he.id].some(ut=>String(ut||"").toLowerCase().includes(Oe))}).sort((he,Oe)=>String(Oe.purchaseDate||"").localeCompare(String(he.purchaseDate||""))||Number(Oe.createdAt||0)-Number(he.createdAt||0)),[N,te,pt,a,nt]),jn=$a.find(he=>he.id===se)||N.find(he=>he.id===se);function vs(he){We(Oe=>Oe.filter(ut=>ut.key!==he))}function ka(){if(!ct||!De.serialControlled)return;const he=Y1(st);if(!he)return;const Oe=Ec(De.serialText);if(Oe.some(At=>At.toLowerCase()===he.toLowerCase())){qe(`Duplicate serial: ${he}`);return}const ut=[...Oe,he];Te(At=>({...At,serialText:ut.join(` 3937`),qty:ut.length})),Nt(""),qe("")}function Ja(he){const Oe=Ec(De.serialText).filter(ut=>ut.toLowerCase()!==he.toLowerCase());Te(ut=>({...ut,serialText:Oe.join(` 3938`),qty:Oe.length}))}function _n(){const he=Gt.find(At=>At.id===ct);if(!he){qe("Select a product from Product Search first."),le(!0);return}if(Be.some(At=>At.productId===he.id)){qe("This product is already added. Remove the existing line before adding it again.");return}const Oe=Ec(De.serialText);if(De.serialControlled&&Oe.length<1){qe("Enter at least one serial number for this serial-controlled product.");return}const ut=De.serialControlled?Oe.length:Number(De.qty||0);if(ut<=0){qe("Quantity must be greater than zero.");return}if(Number(De.rate||0)<0){qe("Price / Unit cannot be negative.");return}We(At=>[...At,{...De,qty:ut,key:du().key,productId:he.id}]),wt(""),Ce(""),Te(du()),Nt(""),le(!1),qe("")}function ha(){ne(""),Me(""),Ye(!1),wt(""),Ce(""),Te(du()),Nt(""),le(!1),Y(""),V(""),F(""),ue("N/A"),ge("BDT"),Pe("local"),Ee(1),We([]),jt("credit"),tn(0),xe(""),ht(""),we(""),St(new Date().toISOString().slice(0,10)),gn(!1),Sn(0),Wt(""),qe("")}function ta(he){return N.filter(Oe=>!Oe.cancelled&&Array.isArray(Oe.items)&&Oe.items.some(ut=>ut.productId===he)).sort((Oe,ut)=>String(ut.purchaseDate||"").localeCompare(String(Oe.purchaseDate||""))||Number(ut.createdAt||0)-Number(Oe.createdAt||0)).slice(0,3).map(Oe=>{var At;const ut=(At=Oe.items)==null?void 0:At.find(en=>en.productId===he);return{date:Oe.purchaseDate||"",supplier:Oe.supplier||"",ref:Oe.sourceInvoiceNo||Oe.supplierInvoiceRefNo||"",rate:Number((ut==null?void 0:ut.rate)||0),qty:Number((ut==null?void 0:ut.qty)||0)}})}function W(he){var Ea;const Oe=window.open("","_blank","width=1100,height=800");if(!Oe)return qe("Print popup was blocked by the browser.");const ut=ga=>String(ga??"").replace(/[&<>\"']/g,zn=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[zn]||zn),At=n.find(ga=>ga.id===he.branchId),en=he.branchName||(At==null?void 0:At.name)||"â",It=Number(he.grossAmount??he.totalAmount??0),Pt=Number(he.discountAmount||0),Jn=Number(he.totalAmount||0),na=Number(he.carryingChargeAmount||0),Mn=(he.items||[]).map((ga,zn)=>{var Xn,Vn;return`<tr><td>${zn+1}</td><td><strong>${ut(ga.product||"â")}</strong>${(Xn=ga.serials)!=null&&Xn.length?`<small>${ga.serials.map(ut).join(", ")}</small>`:""}</td><td>${Number(ga.qty||0)}</td><td>${ut(ga.unit||((Vn=$t[String(ga.productId||"")])==null?void 0:Vn.unit)||"â")}</td><td>${ut(en)}</td><td>${qs(Number(ga.rate||0))}</td><td>${qs(Number(ga.discountAmount||0))}</td><td class="num">${qs(Number(ga.amount||0))}</td></tr>`}).join("");Oe.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>${ut(he.sourceInvoiceNo||"Purchase")}</title><style>@page{size:A4 portrait;margin:10mm}*{box-sizing:border-box}body{margin:0;font-family:Arial,sans-serif;color:#14213d;font-size:11px}.sheet{width:100%;min-height:277mm;display:flex;flex-direction:column}.head{display:grid;grid-template-columns:1.35fr 1fr;border:1px solid #1e3a5f}.head>div{padding:10px 12px}.head>div+div{border-left:1px solid #1e3a5f}.head h1{font-size:18px;margin:0 0 5px}.head h2{font-size:18px;margin:0 0 6px;text-transform:uppercase}.head p,.supplier p,.summary p{margin:3px 0}.supplier{border:1px solid #1e3a5f;border-top:0;padding:8px 12px}.supplier strong{display:block;margin-bottom:4px;font-size:12px}table{width:100%;border-collapse:collapse;table-layout:fixed;margin-top:8px}th,td{border:1px solid #1e3a5f;padding:6px 5px;vertical-align:top}th{background:#f1f5f9;font-size:9px;text-transform:uppercase}td small{display:block;margin-top:3px;word-break:break-word}.num{text-align:right}.qty{border:1px solid #1e3a5f;border-top:0;padding:6px 8px}.summary{display:grid;grid-template-columns:1fr 280px;border:1px solid #1e3a5f;border-top:0}.summary>div{padding:8px 10px}.summary>div+div{border-left:1px solid #1e3a5f}.summary .line{display:flex;justify-content:space-between;gap:15px}.summary .grand{font-size:12px;border-top:1px solid #1e3a5f;padding-top:5px;margin-top:5px}.sign{display:grid;grid-template-columns:1fr 1fr;gap:80px;margin-top:42px;text-align:center}.sign span{border-top:1px solid #1e3a5f;padding-top:5px}.footer{margin-top:auto;border-top:1px solid #94a3b8;padding-top:6px;display:flex;justify-content:space-between;color:#475569;font-size:9px}@media print{body{-webkit-print-color-adjust:exact;print-color-adjust:exact}}</style></head><body><div class="sheet"><div class="head"><div><h1>${ut(c.toUpperCase())}</h1>${m?`<p>${ut(m)}</p>`:""}${l?`<p>${ut(l)}</p>`:""}</div><div><h2>Purchase</h2><p><b>Purchase No. :</b> ${ut(he.sourceInvoiceNo||"â")}</p><p><b>Date :</b> ${ut(he.purchaseDate||"â")}</p><p><b>Status :</b> ${ut(he.status||"Posted")}</p><p><b>Payment Mode :</b> ${ut(((Ea=he.paymentReview)==null?void 0:Ea.mode)||"Credit")}</p><p><b>Entry By :</b> ${ut(he.createdByName||t.name||"â")}</p></div></div><div class="supplier"><strong>Supplier Info</strong><p><b>Name :</b> ${ut(he.supplier||"â")}</p><p><b>Supplier Ref :</b> ${ut(he.supplierInvoiceRefNo||"â")}</p><p><b>Branch / Warehouse :</b> ${ut(en)}</p></div><table><colgroup><col style="width:4%"><col style="width:35%"><col style="width:8%"><col style="width:8%"><col style="width:12%"><col style="width:11%"><col style="width:10%"><col style="width:12%"></colgroup><thead><tr><th>
3938#</th><th>Product Name / Serial</th><th>Quantity</th><th>Unit</th><th>Warehouse</th><th>Price/Unit</th><th>Disc./Unit</th><th>Total</th></tr></thead><tbody>${Mn}</tbody></table><div class="qty">Total Qty. # <strong>${Number(he.totalQty||0)}</strong></div><div class="summary"><div><p><b>Remarks :</b> ${ut(he.note||"")}</p>${he.carryingChargeRemarks?`<p><b>Carrying :</b> ${ut(he.carryingChargeRemarks)}</p>`:""}</div><div><p class="line"><span>Grand Total (BDT)</span><strong>${qs(It)}</strong></p><p class="line"><span>Discount (BDT)</span><strong>${qs(Pt)}</strong></p>${na>0?`<p class="line"><span>Carrying Charge (BDT)</span><strong>${qs(na)}</strong></p>`:""}<p class="line grand"><span>Net Total (BDT)</span><strong>${qs(Jn)}</strong></p></div></div><div class="sign"><span>Supplier Signature</span><span>For - ${ut(c.toUpperCase())}</span></div><div class="footer"><span>By: ${ut(t.name||he.createdByName||"â")}</span><span>VERIXO ERP</span><span>${ut(he.sourceInvoiceNo||"Purchase")}</span></div></div><script>window.addEventListener('load',()=>{setTimeout(()=>window.print(),150)});<\/script></body></html>`),Oe.document.close(),Oe.opener=null}async function ft(he){var At,en,It,Pt;if(he.preventDefault(),qe(""),!d)return qe("Purchase Manage permission is required.");if(it)return;if(!uh(D))return qe(H.length>1?"Select a specific branch / warehouse. All Branches is for viewing only.":"A valid default branch is required before posting.");if(!q.trim())return qe("Select a supplier.");if(!Z)return qe("Purchase Date is required.");if((be==="bank"||be==="partial_bank"||be==="cheque")&&!aa)return qe(be==="cheque"?"Select the bank account for this cheque.":"Select the Bank / TT account used for this payment.");if(be==="cheque"&&!dt.trim())return qe("Cheque No. is required.");if(be==="cheque"&&!/^\d{4}-\d{2}-\d{2}$/.test(rt))return qe("Valid Cheque Date is required.");if(Qt&&wa<=0)return qe("Enter a Carrying Charge amount greater than zero, or untick Add Carrying Charge.");if((be==="partial_cash"||be==="partial_bank")&&(In<=0||In>=Ca))return qe("Partial payment amount must be greater than zero and less than the Purchase total.");const Oe=Be.filter(Jn=>Jn.productId&&Number(Jn.qty)>0&&Number(Jn.rate)>=0);if(!Oe.length||Oe.length!==Be.length)return qe("Complete Product, Quantity and Price for every purchase line.");for(const Jn of Oe){const na=Ec(Jn.serialText);if(Jn.serialControlled&&na.length!==Number(Jn.qty))return qe(`${((At=u[Jn.productId])==null?void 0:At.name)||"Product"}: serial count must equal purchase quantity.`);if(!Jn.serialControlled&&na.length>
3938Number(Jn.qty))return qe(`${((en=u[Jn.productId])==null?void 0:en.name)||"Product"}: serial count cannot exceed purchase quantity.`)}const ut=Oe.flatMap(Jn=>Ec(Jn.serialText).map(na=>na.toLowerCase()));if(new Set(ut).size!==ut.length)return qe("Duplicate serial number found inside this Purchase.");_e(!0);try{const[Jn,na]=await Promise.all([mn(re(ie,`historicalPurchases/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}/${D}`))]);if(Object.values(Jn.val()||{}).some(oa=>!oa.cancelled&&String(oa.branchId||"")===D&&String(oa.supplier||"").trim().toLowerCase()===q.trim().toLowerCase()&&String(oa.supplierInvoiceRefNo||oa.sourceInvoiceNo||"").trim().toLowerCase()===ae.trim().toLowerCase()))throw new Error("Duplicate blocked: this supplier invoice/reference already exists for the selected branch.");const Ea=na.val()||{};for(const oa of Oe){const qa=Ea[oa.productId]||{},bs=new Set((qa.postCutoverSoldSerials||[]).map($s=>String($s).toLowerCase())),Wa=new Set((qa.postCutoverPurchaseSerials||[]).map($s=>String($s).toLowerCase()).filter($s=>!bs.has($s)));for(const $s of Ec(oa.serialText))if(Wa.has($s.toLowerCase()))throw new Error(`${((It=u[oa.productId])==null?void 0:It.name)||"Product"}: serial ${$s} is already in stock.`)}const ga={id:"acct_1300",code:"1300",name:"Inventory"},zn={id:"acct_2100",code:"2100",name:"Accounts Payable"},Xn=Ta(re(ie,`historicalPurchases/${t.companyId}`)).key,Vn=Date.now(),ua=Z.slice(0,4),Ma=re(ie,`purchaseNumberSequences/${t.companyId}/${ua}`),Xe=await Ep(Ma,oa=>Math.max(0,Number(oa||0))+1,{applyLocally:!1});if(!Xe.committed)throw new Error("Could not reserve Purchase No.");const Jt=c_(ua,Number(Xe.snapshot.val()||0)),Ht={};for(const oa of Oe){const qa=Ea[oa.productId]||{},bs=Ec(oa.serialText),Wa=(qa.postCutoverPurchaseSerials||[]).map(String),$s=Number(qa.postCutoverPurchaseQty||0)+Number(oa.qty);Ht[`inventoryStock/${t.companyId}/${D}/${oa.productId}`]={...qa,productId:oa.productId,branchId:D,qty:Number(qa.qty||0)+Number(oa.qty),openingQty:Number(qa.openingQty||0),openingDate:qa.openingDate||"",source:qa.source||"live_purchase",postCutoverPurchaseQty:$s,postCutoverPurchaseSerials:[...new Set([...Wa,...bs])],postCutoverPurchaseUnserializedQty:Math.max(0,Number(qa.postCutoverPurchaseUnserializedQty||0)+(Number(oa.qty)-bs.length)),lastPurchaseCostPerUnit:Ki((Ef(oa)+(Ln>0?wa*(Ef(oa)/Ln):0))/Number(oa.qty)),lastLivePurchaseAt:Vn,lastLivePurchaseNo:Jt,updatedAt:Vn}}const xa=Oe.map(oa=>{var qa,bs,Wa;return{productId:oa.productId,product:((qa=$t[oa.productId])==null?void 0:qa.name)||oa.productId,model:((bs=$t[oa.productId])==null?void 0:bs.model)||"",unit:((Wa=$t[oa.productId])==null?void 0:Wa.unit)||"PCS",qty:Number(oa.qty),rate:Ki(oa.rate),grossAmount:Ki(Ng(oa)),discountType:oa.discountType,discountValue:Ki(oa.discountValue),discountAmount:Q1(oa),amount:Ef(oa),mrp:Ki(oa.mrp),serials:Ec(oa.serialText)}}),ra={id:Xn,companyId:t.companyId,branchId:D,branchName:((Pt=n.find(oa=>oa.id===D))==null?void 0:Pt.name)||"",purchaseDate:Z,referenceDate:je||"",sourceInvoiceNo:Jt,supplierInvoiceRefNo:ae.trim(),supplier:q.trim(),supplierId:(ke==null?void 0:ke.id)||Ov(q),purchaseOrigin:de,currency:me,exchangeRate:Number(Re||1),paymentTerms:P,sourceSystem:"verixo_live_purchase",migrationMode:"live_purchase",stockImpact:!0,itemCount:xa.length,totalQty:xa.reduce((oa,qa)=>oa+qa.qty,0),grossAmount:xn,discountAmount:dn,carryingChargeEnabled:wa>0,carryingChargeAmount:wa,carryingChargeRemarks:Xt.trim(),productNetAmount:Ln,totalAmount:Ca,items:xa,note:$.trim(),paymentReview:{status:"confirmed",mode:be,paidAmount:In,payableAmount:Sa,accountId:be==="bank"||be==="partial_bank"||be==="cheque"?B:"",reference:be==="cheque"?dt.trim():tt.trim(),reviewedAt:Vn,reviewedByUid:t.uid,reviewedByName:t.name||t.email||"User"},accountingPosted:!0,accountingVoucherId:`live_purchase_${Xn}`,status:"posted",createdAt:Vn,updatedAt:Vn,createdByUid:t.uid,createdByName:t.name||t.email||"User"};Ht[`historicalPurchases/${t.companyId}/${Xn}`]=ra;const Ha=`live_purchase_${Xn}`,is=`AUTO-${Jt}`,hs=[{id:"line_001",accountId:ga.id,accountCode:ga.code,accountName:ga.name,debit:Ca,credit:0,narration:`Purchase inventory · ${Jt}`},{id:"line_002",accountId:zn.id,accountCode:zn.code,accountName:zn.name,debit:0,credit:Ca,narration:`Supplier payable · ${q.trim()} · ${Jt}`,billNumber:Jt,purchaseKey:Xn}];if(In>0){const oa=be==="bank"||be==="partial_bank"||be==="cheque"?{id:aa.ledgerAccountId,code:aa.ledgerCode||"",name:aa.ledgerName||aa.name||"Bank / TT"}:{id:"acct_1110",code:"1110",name:"Cash in Hand"};hs.push({id:"line_003",accountId:zn.id,accountCode:zn.code,accountName:zn.name,debit:In,credit:0,narration:`Immediate supplier payment · ${q.trim()} · ${Jt}`,billNumber:Jt,purchaseKey:Xn},{id:"line_004",accountId:oa.id,accountCode:oa.code,accountName:oa.name,debit:0,credit:In,narration:`Purchase payment · ${be==="cheque"?"Cheque":be.includes("bank")?"Bank / TT":"Cash"} · ${Jt}${(be==="cheque"?dt.trim():tt.trim())?` · ${be==="cheque"?dt.trim():tt.trim()}`:""}`});const qa=`purchase_payment_${Xn}`;Ht[`supplierPayments/${t.companyId}/${qa}`]={id:qa,paymentDate:Z,branchId:D,supplier:q.trim(),amount:In,method:be==="cheque"?"cheque":be.includes("bank")?"bank":"cash",paymentAccountId:be.includes("bank")||be==="cheque"?B:"acct_1110",reference:(be==="cheque"?dt.trim():tt.trim())||Jt,note:`Immediate payment with Purchase ${Jt}`,allocationMode:"purchase_direct",allocations:[{sourceKind:"purchase",purchaseKey:Xn,billNumber:Jt,purchaseDate:Z,amount:In,outstandingBefore:Ca,outstandingAfter:Sa}],unallocatedAmount:0,accountingVoucherId:Ha,sourceType:"live_purchase",sourceId:Xn,createdAt:Vn,createdByUid:t.uid,createdByName:t.name||t.email||"User"}}if(be==="cheque"&&In>0){const oa=`purchase_payment_${Xn}_chq_001`,qa=aa;Ht[`chequeManagement/${t.companyId}/${oa}`]={id:oa,direction:"payable",party:q.trim(),chequeNo:dt.trim(),bank:qa.bankName||qa.name||"",bankId:B,amount:In,chequeDate:rt,promisedDate:rt,status:"pending",reference:Jt,sourceType:"live_purchase",sourceId:Xn,branchId:D,createdAt:Vn,createdByUid:t.uid,createdByName:t.name||t.email||"User",history:{[String(Vn)]:{at:Vn,by:t.name||t.email||"User",action:"created_from_live_purchase",to:"pending",date:rt}}}}Ht[`accountingVouchers/${t.companyId}/${Ha}`]={voucherNo:is,type:"purchase",status:"posted",voucherDate:Z,branchId:D,reference:Jt,n
3938arration:`Live Purchase · ${q.trim()} · Supplier Ref ${ae.trim()}`,lines:hs,totalDebit:Ki(Ca+In),totalCredit:Ki(Ca+In),createdAt:Vn,updatedAt:Vn,postedAt:Vn,createdByUid:t.uid,createdByName:t.name||t.email||"User",postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"live_purchase",sourceId:Xn,postingMonth:Z.slice(0,7),autoPosted:!0,paymentMode:be,paidAmount:In,payableAmount:Sa},hs.forEach((oa,qa)=>Ht[`accountingLedgerEntries/${t.companyId}/${Ha}_${qa+1}`]={id:`${Ha}_${qa+1}`,voucherId:Ha,voucherNo:is,voucherType:"purchase",voucherDate:Z,branchId:D,reference:Jt,narration:oa.narration,accountId:oa.accountId,accountCode:oa.accountCode,accountName:oa.accountName,debit:oa.debit,credit:oa.credit,status:"posted",createdAt:Vn,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"live_purchase",sourceId:Xn,postingMonth:Z.slice(0,7),autoPosted:!0,...oa.billNumber?{billNumber:oa.billNumber,purchaseKey:oa.purchaseKey}:{}}),await yn(re(ie),Ht);const rs=`Purchase ${Jt} posted successfully. Stock +${Rt}, Paid ${qs(In)}, Supplier Payable ${qs(Sa)}.`;ha(),qe(rs)}catch(Jn){qe(`Purchase failed: ${(Jn==null?void 0:Jn.message)||String(Jn)}`)}finally{_e(!1)}}const Zt=ct||"",vt=Zt?ta(Zt):[];return e.jsxs("div",{className:"panel live-purchase-page",children:[e.jsx("div",{className:"section-heading",children:e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"PURCHASE & INVENTORY"}),e.jsx("h2",{children:"Direct Purchase"}),e.jsx("p",{children:"Supplier purchase entry with stock, serial, payable and accounting posting in one transaction."})]})}),e.jsxs("form",{onSubmit:ft,className:"live-purchase-form",children:[e.jsxs("div",{className:"purchase-header-grid",children:[e.jsxs("div",{children:[e.jsx("h3",{style:{margin:"0 0 12px"},children:"Supplier Info"}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Purchase Type",e.jsxs("div",{style:{display:"flex",gap:14,height:38,alignItems:"center"},children:[e.jsxs("span",{children:[e.jsx("input",{type:"radio",checked:de==="local",onChange:()=>Pe("local")})," Local"]}),e.jsxs("span",{children:[e.jsx("input",{type:"radio",checked:de==="foreign",onChange:()=>Pe("foreign")})," Foreign"]})]})]}),e.jsxs("label",{children:["Currency",e.jsxs("select",{value:me,onChange:he=>ge(he.target.value),children:[e.jsx("option",{value:"BDT",children:"৳ - BDT"}),e.jsx("option",{value:"USD",children:"$ - USD"})]})]}),de==="foreign"&&e.jsxs("label",{children:["Exchange Rate",e.jsx("input",{type:"number",min:"0.0001",step:"0.0001",value:Re,onChange:he=>Ee(Number(he.target.value))})]}),e.jsxs("label",{children:["Date *",e.jsx("input",{type:"date",value:Z,onChange:he=>fe(he.target.value)})]}),e.jsxs("label",{style:{gridColumn:"1 / -1",position:"relative"},children:["Supplier *",e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("input",{style:{flex:1},value:Se,autoComplete:"off",onFocus:()=>Ye(!0),onBlur:()=>window.setTimeout(()=>Ye(!1),150),onKeyDown:he=>{he.key==="Escape"&&Ye(!1)},onChange:he=>{Me(he.target.value),ne(""),Ye(!0)},placeholder:"Search by name or mobile no."}),e.jsx("button",{type:"button",className:"secondary-action",title:"Add New Supplier","aria-label":"Add New Supplier",onClick:()=>{sessionStorage.setItem("verixo.purchase.addSupplierReturn","1"),i==null||i()},style:{minWidth:42,padding:"0 12px"},children:e.jsx(as,{size:18})})]}),ce&&e.jsx("div",{style:{position:"absolute",zIndex:40,left:0,right:0,top:"calc(100% - 2px)",maxHeight:260,overflowY:"auto",background:"#fff",border:"1px solid var(--border, #dbe3ea)",borderRadius:10,boxShadow:"0 10px 28px rgba(15,23,42,.14)"},children:sn.length?sn.map(he=>e.jsxs("button",{type:"button",onMouseDown:Oe=>Oe.preventDefault(),onClick:()=>{ne(he.name||""),Me(he.name||""),ue(he.paymentTerms||"N/A"),Ye(!1),qe("")},style:{display:"flex",width:"100%",border:0,borderBottom:"1px solid #eef2f6",background:"#fff",padding:"10px 12px",textAlign:"left",cursor:"pointer",justifyContent:"space-between",gap:12},children:[e.jsx("span",{style:{fontWeight:700},children:he.name}),e.jsx("span",{style:{color:"#667085",whiteSpace:"nowrap"},children:he.mobile||""})]},he.id)):e.jsx("div",{style:{padding:"12px",color:"#667085"},children:"No supplier found."})}),q&&e.jsxs("small",{style:{display:"block",marginTop:5},children:["Ledger Balance: ",e.jsx("b",{children:qs(Et)})]})]}),e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Payment Terms",e.jsx("input",{value:P,onChange:he=>ue(he.target.value),placeholder:"N/A"})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{style:{margin:"0 0 12px"},children:"Purchase Reference"}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Payment Mode *",e.jsxs("select",{value:be,onChange:he=>{const Oe=he.target.value;jt(Oe),tn(0),xe(""),ht(""),we(""),St(Z)},children:[e.jsx("option",{value:"credit",children:"Credit · Supplier Payable"}),e.jsx("option",{value:"cash",children:"Paid · Cash"}),e.jsx("option",{value:"bank",children:"Paid · Bank Transfer / TT"}),e.jsx("option",{value:"cheque",children:"Paid · Cheque"}),e.jsx("option",{value:"partial_cash",children:"Partial · Cash + Payable"}),e.jsx("option",{value:"partial_bank",children:"Partial · Bank / TT + Payable"})]})]}),e.jsxs("label",{children:["Purchase No.",e.jsx("input",{readOnly:!0,value:"Auto on Post"})]}),(be==="partial_cash"||be==="partial_bank")&&e.jsxs("label",{children:["Paid Amount *",e.jsx("input",{type:"number",min:"0.01",max:Math.max(0,Ca-.01),step:"0.01",value:bt||"",onChange:he=>tn(Number(he.target.value||0)),placeholder:"Immediate paid amount"})]}),(be==="bank"||be==="partial_bank"||be==="cheque")&&e.jsxs("label",{children:[be==="cheque"?"Cheque Bank Account *":"Bank / TT Account *",e.jsxs("select",{value:B,onChange:he=>xe(he.target.value),children:[e.jsx("option",{value:"",children:"Select bank account"}),G.filter(he=>he.kind!=="mfs").map(he=>e.jsxs("option",{value:he.id,children:[he.bankName||he.name,he.accountNumber?` · ${he.accountNumber}`:""]},he.id))]})]}),be==="cheque"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Cheque No. *",e.jsx("input",{value:dt,onChange:he=>we(he.target.value),placeholder:"Cheque no."})]}),e.jsxs("label",{children:["Cheque Date *",e.jsx("input",{type:"date",value:rt,onChange:he=>St(he.target.value)})]})]}),be!=="credit"&&be!=="cheque"&&e.jsxs("label",{style:{gridColumn:"1 / -1"}
3938,children:["Payment Reference",e.jsx("input",{value:tt,onChange:he=>ht(he.target.value),placeholder:be.includes("bank")?"TT / transaction / bank reference":"Cash payment reference (optional)"})]}),be!=="credit"&&e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Payment Summary",e.jsx("input",{readOnly:!0,value:`Paid ${qs(In)} · Supplier Payable ${qs(Sa)}`})]}),e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Reference No.",e.jsx("input",{value:ae,onChange:he=>Y(he.target.value),placeholder:"Supplier invoice / reference no."})]}),e.jsxs("label",{children:["Reference Date",e.jsx("input",{type:"date",value:je,onChange:he=>V(he.target.value)})]}),e.jsxs("label",{children:["Branch / Warehouse",e.jsxs("select",{value:D,onChange:he=>M(he.target.value),disabled:!!K||uh(a),children:[e.jsx("option",{value:"",children:H.length===1?"Default branch":"Select branch"}),H.map(he=>e.jsx("option",{value:he.id,children:he.name},he.id))]}),K&&e.jsxs("small",{style:{display:"block",marginTop:4,color:"#64748b"},children:["Single-branch workspace · fixed to ",((Ae=H[0])==null?void 0:Ae.name)||"default branch"]})]}),e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Remarks",e.jsx("textarea",{rows:2,value:$,onChange:he=>F(he.target.value),placeholder:"Direct purchase remarks"})]})]})]})]}),e.jsxs("div",{className:"purchase-product-section",children:[e.jsx("h3",{style:{margin:"0 0 12px"},children:"Product Detail"}),e.jsxs("div",{className:"purchase-product-grid",children:[e.jsxs("div",{children:[e.jsxs("label",{style:{display:"block",position:"relative",fontWeight:700},children:["Product",e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("input",{style:{flex:1},value:ot,autoComplete:"off",onFocus:()=>le(!0),onBlur:()=>window.setTimeout(()=>le(!1),150),onKeyDown:he=>{he.key==="Escape"&&le(!1)},onChange:he=>{wt(he.target.value),Ce(""),Te(du()),le(!0)},placeholder:"Search product by name, model or code..."}),e.jsx("button",{type:"button",className:"secondary-action",title:"Add New Product","aria-label":"Add New Product",onClick:()=>{sessionStorage.setItem("verixo.purchase.addProductReturn","1"),s==null||s()},style:{minWidth:42,padding:"0 12px"},children:e.jsx(as,{size:18})})]}),Je&&e.jsx("div",{style:{position:"absolute",zIndex:40,left:0,right:0,top:"calc(100% - 2px)",maxHeight:300,overflowY:"auto",background:"#fff",border:"1px solid var(--border, #dbe3ea)",borderRadius:10,boxShadow:"0 10px 28px rgba(15,23,42,.14)"},children:on.length?on.map(he=>e.jsxs("button",{type:"button",onMouseDown:Oe=>Oe.preventDefault(),onClick:()=>{var Oe;Ce(he.id),wt([he.name,he.model].filter(Boolean).join(" · "));{const ut=J[he.id],At=!!(he.serialControlled||he.serialTracking||he.requiresSerial||he.hasSerial||he.serialized||((ut==null?void 0:ut.postCutoverPurchaseSerials)||[]).length||((ut==null?void 0:ut.manualReconciledSerials)||[]).length||((ut==null?void 0:ut.reliableCurrentReferenceSerials)||[]).length||/serial|linked/i.test(String((ut==null?void 0:ut.serialStatus)||"")));Te({...du(),productId:he.id,qty:At?0:1,serialControlled:At,rate:Number(((Oe=J[he.id])==null?void 0:Oe.lastPurchaseCostPerUnit)||0),mrp:Number(he.mrp||0)}),Nt("")}le(!1),qe("")},style:{display:"flex",width:"100%",border:0,borderBottom:"1px solid #eef2f6",background:"#fff",padding:"10px 12px",textAlign:"left",cursor:"pointer",justifyContent:"space-between",gap:12},children:[e.jsxs("span",{children:[e.jsx("b",{children:he.name}),he.model&&e.jsxs("span",{style:{color:"#667085"},children:[" · ",he.model]})]}),e.jsx("span",{style:{color:"#667085",whiteSpace:"nowrap"},children:he.code||he.sku||""})]},he.id)):e.jsx("div",{style:{padding:"12px",color:"#667085"},children:"No product found."})})]}),e.jsxs("div",{className:"purchase-product-fields",children:[e.jsxs("label",{children:["Unit Type",e.jsx("input",{readOnly:!0,value:ct?((oe=$t[ct])==null?void 0:oe.unit)||"PCS":""})]}),e.jsxs("label",{children:["Quantity",e.jsx("input",{type:"number",min:De.serialControlled?0:1,step:"1",value:ct?De.qty:"",disabled:!ct||De.serialControlled,readOnly:De.serialControlled,onChange:he=>Te(Oe=>({...Oe,qty:Number(he.target.value)}))}),ct&&e.jsxs("small",{style:{display:"block",marginTop:4},children:[De.serialControlled?e.jsx(e.Fragment,{children:"Auto from serial count · "}):null,"Available: ",e.jsx("b",{children:Number(((Ve=J[ct])==null?void 0:Ve.qty)||0)})]})]}),e.jsxs("label",{children:["Price / Unit",e.jsx("input",{type:"number",min:"0",step:"0.01",value:ct&&De.rate||"",disabled:!ct,placeholder:"Price / Unit",onCh
3938ange:he=>Te(Oe=>({...Oe,rate:Number(he.target.value)}))})]}),e.jsxs("label",{children:["Discount Type",e.jsxs("select",{value:De.discountType,disabled:!ct,onChange:he=>Te(Oe=>({...Oe,discountType:he.target.value})),children:[e.jsx("option",{value:"amount",children:"Amount"}),e.jsx("option",{value:"percent",children:"%"})]})]}),e.jsxs("label",{children:["MRP",e.jsx("input",{type:"number",min:"0",step:"0.01",value:ct&&De.mrp||"",disabled:!ct,placeholder:"MRP / Unit",onChange:he=>Te(Oe=>({...Oe,mrp:Number(he.target.value)}))})]}),e.jsxs("label",{children:["Discount Value",e.jsx("input",{type:"number",min:"0",step:"0.01",value:ct&&De.discountValue||"",disabled:!ct,placeholder:De.discountType==="percent"?"Discount %":"Discount amount",onChange:he=>Te(Oe=>({...Oe,discountValue:Number(he.target.value)}))})]}),e.jsxs("div",{style:{gridColumn:"1 / -1",border:"1px solid var(--border, #dbe3ea)",borderRadius:10,padding:12},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontWeight:700,marginBottom:De.serialControlled?10:0},children:[e.jsx("input",{type:"checkbox",style:{width:16,height:16},checked:!!De.serialControlled,disabled:!ct,onChange:he=>{const Oe=he.target.checked;Te(ut=>({...ut,serialControlled:Oe,serialText:Oe?ut.serialText:"",qty:Oe?Ec(ut.serialText).length:Math.max(1,ut.qty||1)})),Nt("")}})," Serial Tracking ",Ct&&e.jsx("small",{style:{fontWeight:500,color:"#667085"},children:"Auto-detected"})]}),De.serialControlled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("input",{value:st,disabled:!ct,autoComplete:"off",placeholder:"Scan / type serial and press Enter",onChange:he=>Nt(he.target.value),onKeyDown:he=>{he.key==="Enter"&&(he.preventDefault(),ka())}}),e.jsxs("button",{type:"button",className:"secondary-action",onClick:ka,disabled:!Y1(st),children:[e.jsx(as,{size:15})," Add Serial"]})]}),e.jsxs("small",{style:{display:"block",marginTop:6},children:["Serial count = Purchase Quantity · ",e.jsx("b",{children:Ec(De.serialText).length})," unit(s)"]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:8},children:Ec(De.serialText).map(he=>e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,border:"1px solid #dbe3ea",borderRadius:999,padding:"5px 9px",background:"#f8fafc"},children:[e.jsx("b",{children:he}),e.jsx("button",{type:"button",onClick:()=>Ja(he),title:"Remove serial",style:{border:0,background:"transparent",cursor:"pointer",padding:0,lineHeight:1},children:"Ã"})]},he))})]})]})]}),e.jsxs("div",{className:"purchase-product-actions",children:[e.jsxs("button",{type:"button",className:"secondary-action",onClick:_n,disabled:!ct,children:[e.jsx(as,{size:16})," Add Product"]}),e.jsxs("button",{type:"button",className:"secondary-action",onClick:()=>{wt(""),Ce(""),Te(du()),Nt(""),le(!1)},children:[e.jsx(Id,{size:16})," Clear"]})]})]}),e.jsxs("div",{className:"purchase-cost-history",children:[e.jsx("b",{children:"Last 3 purchase cost of selected product"}),e.jsx("div",{className:"table-wrap",style:{marginTop:8},children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Supplier"}),e.jsx("th",{children:"Cost / Unit"}),e.jsx("th",{children:"Qty"})]})}),e.jsx("tbody",{children:vt.length?vt.map((he,Oe)=>e.jsxs("tr",{children:[e.jsx("td",{children:he.date}),e.jsx("td",{children:he.supplier}),e.jsx("td",{children:qs(he.rate)}),e.jsx("td",{children:he.qty})]},`${he.ref}_${Oe}`)):e.jsx("tr",{children:e.jsx("td",{colSpan:4,children:"No previous purchase cost found."})})})]})})]})]})]}),e.jsx("div",{className:"table-wrap purchase-lines-table",style:{marginTop:18},children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Product / Model"}),e.jsx("th",{children:"Unit"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Price / Unit"}),e.jsx("th",{children:"Discount"}),e.jsx("th",{children:"MRP"}),e.jsx("th",{children:"Serial No(s)"}),e.jsx("th",{children:"Net Amount"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:Be.length?Be.map((he,Oe)=>{const ut=$t[he.productId];return e.jsxs("tr",{children:[e.jsx("td",{children:Oe+1}),e.jsxs("td",{children:[e.jsx("div",{style:{fontWeight:700},children:(ut==null?void 0:ut.name)||"-"}),(ut==null?void 0:ut.model)&&e.jsx("small",{style:{display:"block",marginTop:3,color:"var(--muted, #667085)"},children:ut.model})]}),e.jsx("td",{children:(ut==null?void 0:ut.unit)||"-"}),e.jsx("td",{children:he.qty}),e.jsx("td",{children:qs(he.rate)}),e.jsx("td",{children:he.discountType==="percent"?`${he.discountValue}%`:qs(he.discountValue)}),e.jsx("td",{children:qs(he.mrp)}),e.jsx("td",{style:{maxWidth:260,whiteSpace:"normal",wordBreak:"break-word"},children:Ec(he.serialText).join(", ")||"-"}),e.jsx("td",{children:e.jsx("b",{children:qs(Ef(he))})}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>vs(he.key),title:"Remove",children:e.jsx(po,{size:15})})})]}
3938,he.key)}):e.jsx("tr",{children:e.jsx("td",{colSpan:10,style:{textAlign:"center",padding:"24px 12px"},children:"No product added yet. Select a product, enter its purchase details and click Add Product."})})}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("th",{colSpan:3,children:"TOTAL"}),e.jsx("th",{children:Rt}),e.jsxs("th",{children:["Gross ",qs(xn)]}),e.jsx("th",{children:qs(dn)}),e.jsx("th",{colSpan:2}),e.jsx("th",{children:qs(Ca)}),e.jsx("th",{})]})})]})}),e.jsxs("div",{style:{marginTop:14,border:"1px solid var(--border, #dbe3ea)",borderRadius:10,padding:12},children:[e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontWeight:700,margin:0},children:[e.jsx("input",{type:"checkbox",style:{width:16,height:16},checked:Qt,onChange:he=>{gn(he.target.checked),he.target.checked||(Sn(0),Wt(""))}})," Add Carrying Charge"]}),Qt&&e.jsxs("div",{className:"form-grid",style:{marginTop:10},children:[e.jsxs("label",{children:["Carrying Charge Amount",e.jsx("input",{type:"number",min:"0",step:"0.01",value:An||"",onChange:he=>Sn(Number(he.target.value)),placeholder:"0.00"})]}),e.jsxs("label",{children:["Remarks (Optional)",e.jsx("input",{value:Xt,onChange:he=>Wt(he.target.value),placeholder:"Transport / delivery details"})]}),e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Purchase Total",e.jsx("input",{readOnly:!0,value:`${qs(Ln)} + Carrying ${qs(wa)} = ${qs(Ca)}`})]})]})]}),e.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"space-between",marginTop:14,flexWrap:"wrap"},children:[e.jsx("div",{style:{display:"flex",gap:8},children:e.jsxs("button",{type:"button",className:"secondary-action",onClick:ha,children:[e.jsx(Id,{size:16})," Reset"]})}),e.jsxs("button",{className:"primary-action",disabled:!d||it||Ca<=0,children:[e.jsx(Kw,{size:17}),it?" Posting...":" Post Purchase"]})]}),ee&&e.jsx("div",{className:"notice",style:{marginTop:14},children:ee})]}),e.jsxs("div",{className:"purchase-list-section",children:[e.jsx("div",{className:"section-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Purchase List"}),e.jsx("p",{children:"Search and review live purchases posted from this page."})]})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Date From",e.jsx("input",{type:"date",value:te,onChange:he=>Ge(he.target.value)})]}),e.jsxs("label",{children:["Date To",e.jsx("input",{type:"date",value:pt,onChange:he=>$e(he.target.value)})]}),e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Search",e.jsx("input",{value:nt,onChange:he=>xt(he.target.value),placeholder:"Purchase no, supplier or reference no."})]})]}),e.jsx("div",{className:"table-wrap",style:{marginTop:12},children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Purchase No"}),e.jsx("th",{children:"Supplier"}),e.jsx("th",{children:"Ref. No."}),e.jsx("th",{children:"No. of Product"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Gross"}),e.jsx("th",{children:"Disc."}),e.jsx("th",{children:"Total"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:$a.length?$a.map(he=>{var Oe;return e.jsxs("tr",{children:[e.jsx("td",{children:he.purchaseDate}),e.jsx("td",{children:he.sourceInvoiceNo}),e.jsx("td",{children:he.supplier}),e.jsx("td",{children:he.supplierInvoiceRefNo}),e.jsx("td",{children:he.itemCount||((Oe=he.items)==null?void 0:Oe.length)||0}),e.jsx("td",{children:he.totalQty||0}),e.jsx("td",{children:qs(Number(he.grossAmount||he.totalAmount||0))}),e.jsx("td",{children:qs(Number(he.discountAmount||0))}),e.jsx("td",{children:qs(Number(he.totalAmount||0))}),e.jsx("td",{children:e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>pe(se===he.id?"":he.id),title:"View",children:e.jsx(ui,{size:15})}),e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>W(he),title:"Print",children:e.jsx(Wi,{size:15})})]})})]},he.id)}):e.jsx("tr",{children:e.jsx("td",{colSpan:10,children:"No live purchase found for the selected filters."})})})]})}),jn&&(()=>{var It;const he=n.find(Pt=>Pt.id===jn.branchId),Oe=Number(jn.grossAmount??jn.totalAmount??0),ut=Number(jn.discountAmount||0),At=Number(jn.totalAmount||0),en=jn.branchName||(he==null?void 0:he.name)||"â";return e.jsx("div",{className:"report-invoice-fullpage",children:e.jsxs("div",{className:"report-invoice-document-modal",children:[e.jsxs("div",{className:"modal-header report-invoice-toolbar",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Purchase Bill Preview"}),e.jsx("h2",{children:jn.sourceInvoiceNo||"Purchase"}),e.jsx("span",{children:jn.purchaseDate||"â"})]}),e.jsxs("div",{className:"report-invoice-toolbar-actions",children:[e.jsx("button",{type:"button",className:"report-invoice-action-button",onClick:()=>W(jn),title:"Print purchase bill","aria-label":"Print purchase bill",children:e.jsx(Wi,{size:18})}),e.jsx("button",{type:"button",className:"report-invoice-close-button",onClick:()=>pe(""),title:"Close preview","aria-label":"Close purchase preview",children:e.jsx(ja,{size:18})})]})]}),e.jsxs("div",{className:"report-invoice-sheet purchase-bill-sheet",children:[e.jsxs("div",{className:"purchase-bill-head",children:[e.jsxs("div",{children:[e.jsx("h1",{children:c.toUpperCase()}),m&&e.jsx("p",{children:m}),l&&e.jsx("p",{children:l})]}),e.jsxs("div",{children:[e.jsx("h2",{children:"Purchase"}),e.jsxs("p",{children:[e.jsx("b",{children:"Purchase No. :"})," ",jn.sourceInvoiceNo||"â"]}
3938),e.jsxs("p",{children:[e.jsx("b",{children:"Date :"})," ",jn.purchaseDate||"â"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Status :"})," ",jn.status||"Posted"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Payment Mode :"})," ",((It=jn.paymentReview)==null?void 0:It.mode)||"Credit"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Entry By :"})," ",jn.createdByName||t.name||"â"]})]})]}),e.jsxs("div",{className:"purchase-bill-supplier",children:[e.jsx("strong",{children:"Supplier Info"}),e.jsxs("p",{children:[e.jsx("b",{children:"Name :"})," ",jn.supplier||"â"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Supplier Ref :"})," ",jn.supplierInvoiceRefNo||"â"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Branch / Warehouse :"})," ",en]})]}),e.jsxs("table",{className:"report-invoice-lines purchase-bill-lines",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"purchase-col-sl"}),e.jsx("col",{className:"purchase-col-product"}),e.jsx("col",{className:"purchase-col-qty"}),e.jsx("col",{className:"purchase-col-unit"}),e.jsx("col",{className:"purchase-col-warehouse"}),e.jsx("col",{className:"purchase-col-price"}),e.jsx("col",{className:"purchase-col-discount"}),e.jsx("col",{className:"purchase-col-total"})]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Product Name / Serial"}),e.jsx("th",{children:"Quantity"}),e.jsx("th",{children:"Unit"}),e.jsx("th",{children:"Warehouse"}),e.jsx("th",{children:"Price/Unit"}),e.jsx("th",{children:"Disc./Unit"}),e.jsx("th",{className:"num",children:"Total"})]})}),e.jsx("tbody",{children:(jn.items||[]).map((Pt,Jn)=>{var na,Mn;return e.jsxs("tr",{children:[e.jsx("td",{children:Jn+1}),e.jsxs("td",{children:[e.jsx("strong",{children:Pt.product||"â"}),(na=Pt.serials)!=null&&na.length?e.jsx("small",{className:"purchase-serial",children:Pt.serials.join(", ")}):null]}),e.jsx("td",{children:Number(Pt.qty||0)}),e.jsx("td",{children:Pt.unit||((Mn=$t[String(Pt.productId||"")])==null?void 0:Mn.unit)||"â"}),e.jsx("td",{children:en}),e.jsx("td",{children:qs(Number(Pt.rate||0))}),e.jsx("td",{children:qs(Number(Pt.discountAmount||0))}),e.jsx("td",{className:"num",children:qs(Number(Pt.amount||0))})]},`${Pt.productId||"item"}_${Jn}`)})})]}),e.jsxs("div",{className:"purchase-bill-totalqty",children:["Total Qty. # ",e.jsx("strong",{children:Number(jn.totalQty||0)})]}),e.jsxs("div",{className:"purchase-bill-summary",children:[e.jsxs("div",{children:[e.jsxs("p",{children:[e.jsx("b",{children:"Remarks :"})," ",jn.note||""]}),jn.carryingChargeRemarks&&e.jsxs("p",{children:[e.jsx("b",{children:"Carrying :"})," ",jn.carryingChargeRemarks]})]}),e.jsxs("div",{children:[e.jsxs("p",{children:[e.jsx("span",{children:"Grand Total (BDT)"}),e.jsx("strong",{children:qs(Oe)})]}),e.jsxs("p",{children:[e.jsx("span",{children:"Discount (BDT)"}),e.jsx("strong",{children:qs(ut)})]}),Number(jn.carryingChargeAmount||0)>0&&e.jsxs("p",{children:[e.jsx("span",{children:"Carrying Charge (BDT)"}),e.jsx("strong",{children:qs(Number(jn.carryingChargeAmount||0))})]}),e.jsxs("p",{className:"grand",children:[e.jsx("span",{children:"Net Total (BDT)"}),e.jsx("strong",{children:qs(At)})]})]})]}),e.jsxs("div",{className:"purchase-bill-signatures",children:[e.jsx("span",{children:"Supplier Signature"}),e.jsxs("span",{children:["For - ",c.toUpperCase()]})]}),e.jsxs("div",{className:"purchase-bill-footer",children:[e.jsxs("span",{children:["By: ",t.name||jn.createdByName||"â"]}),e.jsx("span",{children:"VERIXO ERP"}),e.jsx("span",{children:jn.sourceInvoiceNo||"Purchase"})]})]})]})})})()]})]})}const uu=t=>Number.isFinite(Number(t))?Number(t):0,d_=t=>[...new Set(t.map(n=>String(n||"").trim()).filter(Boolean))];function D7({profile:t,branches:n,selectedBranchId:a,embedded:s=!1}){const[i,c]=x.useState({}),[l,m]=x.useState({}),[d,u]=x.useState({}),[f,g]=x.useState({}),[p,y]=x.useState(""),b=()=>({id:$b(),productId:"",qty:1,rate:0,discountType:"amount",discountPerUnit:0,serials:[]}),[N,w]=x.useState(()=>b()),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState(!1),[G,z]=x.useState(!1),[H,K]=x.useState([]),[L,D]=x.useState(null),M=n.find(Ee=>Ee.id===a),Z=!!M&&a!=="all";x.useEffect(()=>{if(!Z){c({}),m({}),u({});return}let Ee=!1;return(async()=>{try{const[Be,We,it]=await Promise.all([mn(re(ie,`inventoryProducts/${t.companyId}`)),mn(re(ie,`inventoryStock/${t.companyId}/${a}`)),mn(re(ie,`customers/${t.companyId}`))]);if(Ee)return;const _e=Be.val()||{},ee=We.val()||{},qe=it.val()||{},se=d_(Object.values(ee).map(Me=>String((Me==null?void 0:Me.sourceBatchId)||""))),pe=await Promise.all(se.map(Me=>mn(re(ie,`inventoryOpeningItems/${t.companyId}/${Me}`))));if(Ee)return;const Se={};se.forEach((Me,ot)=>{var wt;Se[Me]=((wt=pe[ot])==null?void 0:wt.val())||{}}),c(_e),m(ee),u(Se),g(qe)}catch{Ee||(c({}),m({}),u({}),g({}))}})(),()=>{Ee=!0}},[t.companyId,a,Z]);const fe=x.useMemo(()=>Object.entries(f).map(([Ee,Be])=>({...Be,id:Ee})).filter(Ee=>Ee.active!==!1).sort((Ee,Be)=>String(Ee.name||"").localeCompare(String(Be.name||""))),[f]),q=Ee=>{var _e;const Be=l[Ee]||{},We=Be.sourceBatchId?(_e=d[Be.sourceBatchId])==null?void 0:_e[Ee]:void 0,it=new Set((Be.postCutoverSoldSerials||[]).map(String));return d_([...(We==null?void 0:We.reliableCurrentReferenceSerials)||[],...Be.postCutoverPurchaseSerials||[],...Be.manualReconciledSerials||[]]).filter(ee=>!it.has(ee))},ne=Ee=>Math.max(0,Ee.qty*Ee.rate),ae=Ee=>Ee.discountType==="percent"?Math.max(0,Ee.rate)*Math.min(100,Math.max(0,Ee.discountPerUnit))/100:Math.max(0,Ee.discountPerUnit),Y=Ee=>Math.min(ne(Ee),Math.max(0,Ee.qty)*ae(Ee)),je=Ee=>Math.max(0,ne(Ee)-Y(Ee)),V=x.useMemo(()=>H.reduce((Ee,Be)=>Ee+je(Be),0),[H]),$=x.useMemo(()=>Object.keys(i).flatMap(Ee=>{var Be;return uu((Be=l[Ee])==null?void 0:Be.qty)<=0?[]:q(Ee).map(We=>({serial:We,productId:Ee}))}).sort((Ee,Be)=>Ee.serial.localeCompare(Be.serial)),[i,l,d]),F=Ee=>w(Be=>({...Be,...Ee})),P=x.useMemo(()=>Object.entries(i).filter(([Ee])=>{var Be;return uu((Be=l[Ee])==null?void 0:Be.qty)>0}).map(([Ee,Be])=>({...Be,id:Ee})).sort((Ee,Be)=>String(Ee.name||"").localeCompare(String(Be.name||""))),[i,l]),ue=x.useMemo(()=>{const Ee=C.trim().toLowerCase();return Ee?$.filter(Be=>{var We,it;return Be.serial.toLowerCase().includes(Ee)||String(((We=i[Be.productId])==null?void 0:We.name)||"").toLowerCase().includes(Ee)||String(((it=i[Be.productId])==null?void 0:it.model)||"").toLowerCase().includes(Ee)}).slice(0,12):[]},[$,C,i]),me=x.useMemo(()=>{const Ee=I.trim().toLowerCase();return Ee?P.filter(Be=>String(Be.name||"").toLowerCase().includes(Ee)||String(Be.model||"").toLowerCase().includes(Ee)||String(Be.category||"").toLowerCase().includes(Ee)||Be.id.toLowerCase().includes(Ee)).slice(0,12):[]},[P,I]),ge=(Ee,Be)=>{const We=i[Be];R(Ee),_([We==null?void 0:We.name,We==null?void 0:We.model].filter(
3938Boolean).join(" · ")||Be),F({serials:[Ee],productId:Be,qty:1}),T(!1),z(!1)},de=Ee=>{const Be=i[Ee];_([Be==null?void 0:Be.name,Be==null?void 0:Be.model].filter(Boolean).join(" · ")||Ee),R(""),F({productId:Ee,qty:1,serials:[]}),z(!1),T(!1)},Pe=()=>{var Be;if(!N.productId)return;const Ee=uu((Be=l[N.productId])==null?void 0:Be.qty);N.qty<=0||N.qty>Ee||(L?(K(We=>We.map(it=>it.id===L?{...N,id:L}:it)),D(null)):K(We=>[...We,{...N,id:$b()}]),w(b()),R(""),_(""))},Re=Ee=>{w({...Ee}),R(Ee.serials[0]||"");const Be=i[Ee.productId];_([Be==null?void 0:Be.name,Be==null?void 0:Be.model].filter(Boolean).join(" · ")||Ee.productId),D(Ee.id),window.scrollTo({top:Math.max(0,document.documentElement.scrollTop-180),behavior:"smooth"})};return e.jsxs("div",{className:"live-sales-page",children:[!s&&e.jsxs("div",{className:"live-sales-hero",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"SALES"}),e.jsxs("h2",{children:[e.jsx(Iu,{size:24})," Product Sale"]}),e.jsx("p",{children:"Stock-aware product billing workspace."})]}),e.jsxs("span",{className:"safe-pill",children:[e.jsx(gs,{size:16})," Stock-aware draft"]})]}),!Z&&e.jsxs("div",{className:"branch-block",children:[e.jsx(pg,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Select an operational branch first"}),e.jsx("span",{children:"Sales cannot start from All Branches. Switch branch from the VERIXO workspace; the bill itself will never ask users to choose a branch."})]})]}),e.jsxs("section",{className:"sales-card",children:[e.jsxs("div",{className:"section-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"SALE CONTEXT"}),e.jsx("h3",{children:"Bill information"})]}),e.jsxs("div",{className:"locked-branch",children:[e.jsx(pg,{size:15}),e.jsx("small",{children:"ACTIVE BRANCH · LOCKED"}),e.jsx("strong",{children:(M==null?void 0:M.name)||"No operational branch"})]})]}),e.jsxs("div",{className:"sales-grid",children:[e.jsxs("label",{children:["Customer",e.jsx("input",{disabled:!Z,list:"live-sales-customers",value:p,onChange:Ee=>y(Ee.target.value),placeholder:"Search customer by name / phone"}),e.jsx("datalist",{id:"live-sales-customers",children:fe.map(Ee=>e.jsx("option",{value:[Ee.name,Ee.phone].filter(Boolean).join(" · ")||Ee.id,children:[Ee.name,Ee.phone].filter(Boolean).join(" · ")},Ee.id))})]}),e.jsxs("label",{children:["Salesperson",e.jsx("input",{disabled:!Z,value:t.name||"",readOnly:!0})]}),e.jsxs("label",{children:["Invoice Date",e.jsx("input",{disabled:!Z,type:"date",defaultValue:new Date().toISOString().slice(0,10)})]}),e.jsxs("label",{children:["Reference / PO",e.jsx("input",{disabled:!Z,placeholder:"Optional"})]})]})]}),e.jsxs("section",{className:"sales-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("span",{children:"PRODUCTS"}),e.jsx("h3",{children:"Product entry"})]})}),(()=>{const Ee=N,Be=l[Ee.productId],We=uu(Be==null?void 0:Be.qty),it=q(Ee.productId),_e=i[Ee.productId],ee=!!Ee.productId&&Ee.qty>We;return e.jsxs("div",{className:"product-entry-card active-entry",children:[e.jsxs("div",{className:"product-entry-title",children:[e.jsx("strong",{children:L?"Edit product":"Add a product"}),L&&e.jsx("button",{className:"icon-btn",onClick:()=>{D(null),w(b()),R(""),_("")},children:"Cancel edit"})]}),e.jsxs("div",{className:"product-main-fields",children:[e.jsxs("label",{className:"full-field search-field",children:["Serial ",e.jsx("input",{disabled:!Z,value:C,autoComplete:"off",placeholder:"Type serial number",onFocus:()=>T(!0),onBlur:()=>window.setTimeout(()=>T(!1),120),onChange:qe=>{const se=qe.target.value;R(se),T(!0),Ee.serials[0]&&se!==Ee.serials[0]&&F({serials:[]})}}),J&&C.trim()&&e.jsx("div",{className:"search-suggestions",children:ue.length?ue.map(qe=>{var se,pe,Se;return e.jsxs("button",{type:"button",onMouseDown:Me=>Me.preventDefault(),onClick:()=>ge(qe.serial,qe.productId),children:[e.jsx("strong",{children:qe.serial}),e.jsxs("span",{children:["# ",((se=i[qe.productId])==null?void 0:se.name)||qe.productId,(pe=i[qe.productId])!=null&&pe.model?` · ${(Se=i[qe.productId])==null?void 0:Se.model}`:""]})]},`${qe.productId}:${qe.serial}`)}):e.jsx("div",{className:"no-match",children:"No matching in-stock serial"})}),Ee.productId&&it.length>0&&e.jsxs("small",{children:[it.length," available for selected product"]})]}),e.jsxs("label",{className:"full-field search-field",children:["Product ",e.jsx("input",{disabled:!Z,value:I,autoComplete:"off",placeholder:"Type product name / model",onFocus:()=>z(!0),onBlur:()=>window.setTimeout(()=>z(!1),120),onChange:qe=>{const se=qe.target.value;_(se),z(!0);const pe=[_e==null?void 0:_e.name,_e==null?void 0:_e.model].filter(
3938Boolean).join(" · ")||Ee.productId;Ee.productId&&se!==pe&&F({productId:"",serials:[]}),R("")}}),G&&I.trim()&&e.jsx("div",{className:"search-suggestions",children:me.length?me.map(qe=>e.jsxs("button",{type:"button",onMouseDown:se=>se.preventDefault(),onClick:()=>de(qe.id),children:[e.jsx("strong",{children:qe.name||qe.id}),e.jsx("span",{children:[qe.model,qe.category].filter(Boolean).join(" · ")})]},qe.id)):e.jsx("div",{className:"no-match",children:"No matching product"})}),_e&&e.jsx("small",{children:[_e.category,_e.model].filter(Boolean).join(" · ")})]}),e.jsxs("div",{className:"stock-status",children:[e.jsx("span",{children:"Current Stock"}),e.jsxs("strong",{className:ee?"danger-text":"",children:[e.jsx(yu,{size:17}),Ee.productId?`${We} ${(_e==null?void 0:_e.unit)||"PCS"}`:"â"]}),ee&&e.jsx("small",{className:"danger-text",children:"Insufficient stock"})]})]}),e.jsxs("div",{className:"product-value-grid",children:[e.jsxs("label",{children:["Sale Qty",e.jsx("input",{type:"number",min:"0.001",step:"0.001",disabled:!Ee.productId,value:Ee.qty,onChange:qe=>F({qty:uu(qe.target.value)})})]}),e.jsxs("label",{children:["Rate / Unit",e.jsx("input",{type:"number",min:"0",step:"0.01",disabled:!Ee.productId,value:Ee.rate,onChange:qe=>F({rate:Math.max(0,uu(qe.target.value))})})]}),e.jsxs("label",{children:["Discount Type",e.jsxs("select",{disabled:!Ee.productId,value:Ee.discountType,onChange:qe=>F({discountType:qe.target.value}),children:[e.jsx("option",{value:"amount",children:"Amount (à§³)"}),e.jsx("option",{value:"percent",children:"Percent (%)"})]})]}),e.jsxs("label",{children:["Discount / Unit",e.jsx("input",{type:"number",min:"0",max:Ee.discountType==="percent"?100:void 0,step:"0.01",disabled:!Ee.productId,value:Ee.discountPerUnit,onChange:qe=>F({discountPerUnit:Ee.discountType==="percent"?Math.min(100,Math.max(0,uu(qe.target.value))):Math.max(0,uu(qe.target.value))})}),e.jsx("small",{children:Ee.discountType==="percent"?`à§³${ae(Ee).toLocaleString("en-BD")} / unit`:`à§³${Y(Ee).toLocaleString("en-BD")} line discount`})]})]}),e.jsxs("div",{className:"entry-actions",children:[e.jsxs("div",{className:"product-line-total",children:[e.jsx("span",{children:"Line Total"}),e.jsxs("strong",{children:["à§³",je(Ee).toLocaleString("en-BD",{minimumFractionDigits:2})]})]}),e.jsxs("button",{className:"primary-add-btn",disabled:!Z||!Ee.productId||Ee.qty<=0||ee,onClick:Pe,children:[e.jsx(as,{size:17}),L?"Update Product":"Add Product"]})]})]})})(),H.length>0&&e.jsxs("div",{className:"added-items",children:[e.jsxs("div",{className:"added-items-head",children:[e.jsx("strong",{children:"Added products"}),e.jsxs("span",{children:[H.length," item",H.length===1?"":"s"]})]}),e.jsx("div",{className:"added-items-table-wrap",children:e.jsxs("table",{className:"added-items-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Product"}),e.jsx("th",{children:"Serial"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Rate"}),e.jsx("th",{children:"Discount"}),e.jsx("th",{children:"Total"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:H.map(Ee=>{const Be=i[Ee.productId];return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:(Be==null?void 0:Be.name)||Ee.productId}),(Be==null?void 0:Be.model)&&e.jsx("small",{children:Be.model})]}),e.jsx("td",{children:Ee.serials.join(", ")||"â"}),e.jsx("td",{children:Ee.qty}),e.jsxs("td",{children:["à§³",Ee.rate.toLocaleString("en-BD")]}),e.jsx("td",{children:Ee.discountType==="percent"?`${Ee.discountPerUnit}%`:`à§³${Ee.discountPerUnit.toLocaleString("en-BD")} / unit`}),e.jsx("td",{children:e.jsxs("strong",{children:["à§³",je(Ee).toLocaleString("en-BD",{minimumFractionDigits:2})]})}),e.jsxs("td",{children:[e.jsxs("button",{className:"icon-btn",onClick:()=>Re(Ee),children:[e.jsx(Zi,{size:15})," Edit"]}),e.jsxs("button",{className:"icon-btn danger-text",onClick:()=>K(We=>We.filter(it=>it.id!==Ee.id)),children:[e.jsx(po,{size:15})," Remove"]})]})]},Ee.id)})})]})})]})]}),e.jsxs("section",{className:"sales-card sales-footer",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Phase 1 safety boundary"}),e.jsx("p",{children:"This screen does not post invoices, stock, serials or accounting yet. Save will be enabled only after payment + idempotent posting gates are connected."})]}),e.jsxs("div",{className:"draft-total",children:[e.jsx("span",{children:"Draft Total"}
3938),e.jsxs("strong",{children:["à§³",V.toLocaleString("en-BD",{minimumFractionDigits:2})]}),e.jsx("button",{disabled:!0,children:"Save & Post Sale"})]})]})]})}function E7({profile:t,branches:n,selectedBranchId:a,companyName:s,companyCode:i,documentPrefixes:c,companyPhone:l,companyAddress:m}){const[d,u]=x.useState("product");return e.jsxs("div",{className:"unified-sales-entry",children:[e.jsxs("div",{className:"unified-sales-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"SALES"}),e.jsxs("h1",{children:[e.jsx(Iu,{size:23})," New Sale"]}),e.jsx("p",{children:"Use one sales workspace for product sales and service billing."})]}),e.jsxs("div",{className:"unified-sale-mode",role:"tablist","aria-label":"Sale type",children:[e.jsxs("button",{type:"button",className:d==="product"?"active":"",onClick:()=>u("product"),children:[e.jsx(PD,{size:17})," Product Sale"]}),e.jsxs("button",{type:"button",className:d==="service"?"active":"",onClick:()=>u("service"),children:[e.jsx(Go,{size:17})," Service Sale"]})]})]}),e.jsxs("div",{className:"unified-sales-mode-note",children:[e.jsx("strong",{children:d==="product"?"Product Sale":"Service Sale"}),e.jsx("span",{children:d==="product"?"Stock, serial and product rules remain unchanged.":"Service Job, Invoice Preparation and service invoice rules remain unchanged."})]}),d==="product"?e.jsx(D7,{profile:t,branches:n,selectedBranchId:a,embedded:!0}):e.jsx("div",{className:"unified-service-sale",children:e.jsx(_1,{view:"invoices",companyId:t.companyId,companyName:s,companyCode:i,documentPrefixes:c,companyPhone:l,companyAddress:m,branches:n,selectedBranchId:a,actorUid:t.uid,actorName:t.name,salesEntryMode:!0})})]})}function Ij(t){return`à§³${Number(t||0).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function gd(t){return`BDT ${Number(t||0).toLocaleString("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Lv(t){const[n,a]=t.split("-").map(Number);return!n||!a?t:new Date(n,a-1,1).toLocaleDateString("en-GB",{month:"long",year:"numeric"})}function P7({companyId:t,companyName:n,selectedBranchId:a}){const[s,i]=x.useState({}),[c,l]=x.useState(""),[m,d]=x.useState({}),[u,f]=x.useState({});x.useEffect(()=>qt(re(ie,`payrollPayables/${t}`),b=>{i(b.exists()?b.val():{})},b=>{console.error("Salary Payable ledger load failed:",b),i({})}),[t]),x.useEffect(()=>qt(re(ie,`payrollPayments/${t}`),b=>{d(b.exists()?b.val():{})},b=>{console.error("Salary Payable payment evidence load failed:",b),d({})}),[t]),x.useEffect(()=>qt(re(ie,`payrollItems/${t}`),b=>{f(b.exists()?b.val():{})},b=>{console.error("Salary Payable payroll item load failed:",b),f({})}),[t]);const g=x.useMemo(()=>Object.entries(s).map(([b,N])=>{const w=u[b]||{},C=new Set([...Object.keys(N.employees||{}),...Object.keys(w)]),R=Object.fromEntries(Array.from(C).map(H=>{const K=(N.employees||{})[H],L=w[H],D=Number((L==null?void 0:L.netPay)||0),M=(K==null?void 0:K.netPayable)!==void 0?Math.max(Number(K.netPayable||0),0):Math.max(D,0),Z=Math.max(Number((K==null?void 0:K.recoverableAmount)||0),Math.max(-D,0)),fe=Math.min(Math.max(Number((K==null?void 0:K.paidAmount)??(L==null?void 0:L.paidAmount)??0),0),M);return[H,{employeeId:(K==null?void 0:K.employeeId)||(L==null?void 0:L.employeeId)||H,employeeCode:(K==null?void 0:K.employeeCode)||(L==null?void 0:L.employeeCode)||"",employeeName:(K==null?void 0:K.employeeName)||(L==null?void 0:L.employeeName)||H,branchId:(K==null?void 0:K.branchId)||(L==null?void 0:L.branchId)||"",netPayable:M,recoverableAmount:Z,paidAmount:fe,outstandingAmount:Math.max(M-fe,0),paymentStatus:M<=0||fe<=0?"unpaid":fe>=M?"paid":"partially_paid"}]})),I=Object.fromEntries(Object.entries(R).filter(([,H])=>a==="all"?!0:!H.branchId||H.branchId===a)),_=Object.values(I),J=_.reduce((H,K)=>H+Math.max(Number(K.netPayable||0),0),0),T=_.reduce((H,K)=>H+Number(K.paidAmount||0),0);_.reduce((H,K)=>H+Number(K.outstandingAmount||0),0);const G=_.reduce((H,K)=>H+Math.max(Number(K.recoverableAmount||0),Math.max(-Number(K.netPayable||0),0)),0),z=_.length>0;return{...N,month:b,employees:I,payableTotal:a==="all"&&!z?Math.max(Number(N.payableTotal||0),0):J,paidTotal:a==="all"&&!z?Number(N.paidTotal||0):T,outstandingTotal:a==="all"&&!z?Number(N.outstandingTotal||0):Math.max(J-T,0),recoverableTotal:a==="all"&&!z?Number(N.recoverableTotal||0):G}}).filter(b=>a==="all"||Object.keys(b.employees||{}).length>0).sort((b,N)=>N.month.localeCompare(b.month)),[s,u,a]),p=x.useMemo(()=>g.length?g.find(b=>b.month===c)||g[0]:null,[g,c]);x.useEffect(()=>{if(!g.length){c&&l("");return}(!c||!g.some(b=>b.month===c))&&l(g[0].month)},[g,c]);const y=b=>{var L,D;const N=p;if(!N)return;const w=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),C=w.internal.pageSize.getWidth(),R=a==="all"?"All Branches":a,I=m[N.month]||{},_=`${n||"VERIXO"} - Salary Payable Report - ${Lv(N.month)}`;w.setProperties({title:_,subject:`Salary Payable Report for ${Lv(N.month)}`,author:n||"VERIXO",creator:"VERIXO ERP"}),(L=w.viewerPreferences)==null||L.call(w,{DisplayDocTitle:!0}),w.setFont("helvetica","bold"),w.setFontSize(18),w.text(n||"VERIXO",14,15),w.setFontSize(15),w.text("SALARY PAYABLE REPORT",C-14,15,{align:"right"}),w.setFont("helvetica","normal"),w.setFontSize(9),w.text(`${Lv(N.month)} | ${R}`,C-14,21,{align:"right"}),w.setDrawColor(20),w.line(14,25,C-14,25);const J=[[gd(N.payableTotal),gd(N.paidTotal),gd(N.outstandingTotal),gd(N.recoverableTotal),String(N.paymentStatus||"unpaid").replaceAll("_"," ").toUpperCase()]];oi(w,{startY:30,margin:{left:14,right:14}
3938,head:[["SALARY PAYABLE","PAID / SETTLED","OUTSTANDING","EMPLOYEE RECOVERABLE","STATUS"]],body:J,theme:"grid",tableWidth:"auto",styles:{fontSize:8.5,cellPadding:2.2,halign:"center"},headStyles:{fillColor:[7,59,92],fontStyle:"bold",textColor:255},bodyStyles:{fontStyle:"bold"}});const T=Object.entries(N.employees||{}).sort(([M,Z],[fe,q])=>{const ne=String(Z.employeeCode||Z.employeeId||M||""),ae=String(q.employeeCode||q.employeeId||fe||""),Y=Number(ne),je=Number(ae);return Number.isFinite(Y)&&Number.isFinite(je)&&Y!==je?Y-je:ne.localeCompare(ae,void 0,{numeric:!0,sensitivity:"base"})}).map(([M,Z])=>{const fe=Object.values(I[Z.employeeId]||I[M]||{}).filter($=>$&&$.status!=="reversed"),q=fe.reduce(($,F)=>$+Math.max(Number(F.amount||0),0),0),ne=fe.reduce(($,F)=>$+Number(F.roundingAdjustment||0),0),ae=Array.from(new Set(fe.map($=>String($.method||"").toUpperCase()).filter(Boolean))).join(" / ")||"â",Y=Array.from(new Set(fe.map($=>$.sourceBankName||($.method==="cash"?"Cash":"")).filter(Boolean))).join(" / ")||"â",je=Array.from(new Set(fe.map($=>$.paymentDate).filter(Boolean))).join(", ")||"â",V=Number(Z.recoverableAmount||0)>0?"RECOVERABLE":Math.max(Number(Z.netPayable||0),0)<=0?"NO PAYABLE":String(Z.paymentStatus||"unpaid").replaceAll("_"," ").toUpperCase();return[`${Z.employeeName} 3939${Z.employeeCode||Z.employeeId||M}`,gd(Math.max(Number(Z.netPayable||0),0)),gd(q),ne?gd(ne):"â",gd(Number(Z.paidAmount||0)),gd(Number(Z.outstandingAmount||0)),ae,Y,je,V]}),G=((D=w.lastAutoTable)==null?void 0:D.finalY)||43;oi(w,{startY:G+5,margin:{left:14,right:14,bottom:13},head:[["Employee / ID","Payable","Actual Paid","Rounding","Settled","Outstanding","Method","Paid From","Payment Date","Status"]],body:T.length?T:[["No employee payable rows found.","","","","","","","","",""]],theme:"grid",tableWidth:C-28,styles:{fontSize:6.7,cellPadding:1.35,overflow:"linebreak",valign:"middle"},headStyles:{fillColor:[7,59,92],fontStyle:"bold",textColor:255,fontSize:6.6},columnStyles:{0:{cellWidth:35.5},1:{cellWidth:28.6},2:{cellWidth:28.6},3:{cellWidth:25.2},4:{cellWidth:28.6},5:{cellWidth:28.6},6:{cellWidth:17.2},7:{cellWidth:30.9},8:{cellWidth:25.2},9:{cellWidth:20.6}},didDrawPage:M=>{w.setFontSize(7),w.setTextColor(90),w.text(`Generated by VERIXO ERP | ${N.month}`,14,w.internal.pageSize.getHeight()-7),w.text(`Page ${M.pageNumber}`,C-14,w.internal.pageSize.getHeight()-7,{align:"right"})}});const z=`VERIXO_Salary_Payable_${N.month}_${a==="all"?"All-Branches":a}.pdf`;if(b==="download"){w.save(z);return}const H=URL.createObjectURL(w.output("blob"));window.open(H,"_blank","noopener,noreferrer")||w.save(z),window.setTimeout(()=>URL.revokeObjectURL(H),6e4)};return e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-header finance-page-header",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Reports"}),e.jsx("h1",{children:"Salary Payable Report"}),e.jsxs("p",{children:[n," â select a payroll month and open the audit-ready PDF report."]})]})}),e.jsxs("section",{className:"data-card finance-data-card",children:[e.jsxs("div",{className:"table-toolbar",style:{alignItems:"end",gap:16,flexWrap:"wrap"},children:[e.jsxs("div",{style:{minWidth:260},children:[e.jsx("p",{className:"eyebrow",children:"Payroll Liability PDF"}),e.jsx("h2",{children:"Salary Payable Statement"}),e.jsx("small",{children:"Employee-wise payable, actual payment, rounding, settled amount and outstanding."})]}),e.jsxs("label",{style:{minWidth:220},children:[e.jsx("span",{style:{display:"block",fontSize:12,fontWeight:700,marginBottom:6},children:"Payroll Month"}),e.jsx("select",{value:(p==null?void 0:p.month)||"",onChange:b=>l(b.target.value),disabled:!g.length,style:{width:"100%"},children:g.map(b=>e.jsx("option",{value:b.month,children:Lv(b.month)},b.month))})]}),e.jsxs("div",{className:"salary-payable-pdf-actions",children:[e.jsxs("button",{type:"button",className:"salary-payable-pdf-button salary-payable-pdf-button-primary",disabled:!p,onClick:()=>y("view"),children:[e.jsx(ui,{size:17})," View PDF"]}),e.jsxs("button",{type:"button",className:"salary-payable-pdf-button salary-payable-pdf-button-secondary",disabled:!p,onClick:()=>y("download"),children:[e.jsx(Mi,{size:17})," Download PDF"]})]})]}),p?e.jsxs("div",{className:"finance-summary-grid",style:{marginTop:18},children:[e.jsxs("article",{children:[e.jsx("span",{children:"Salary Payable"}),e.jsx("strong",{children:Ij(p.payableTotal)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Paid / Settled"}),e.jsx("strong",{children:Ij(p.paidTotal)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Outstanding"}),e.jsx("strong",{children:Ij(p.outstandingTotal)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Status"}),e.jsx("strong",{style:{fontSize:16},children:String(p.paymentStatus||"unpaid").replaceAll("_"," ").toUpperCase()})]})]}):e.jsxs("div",{className:"empty-table",style:{padding:36},children:[e.jsx(Zs,{size:24})," No locked payroll liability has been posted yet."]})]})]})}const wo=t=>
3939`à§³${Number(t||0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`,ho=t=>Math.round((Number(t)||0)*100),hp=t=>t/100,yd=t=>hp(ho(t)),Bv=t=>hp(t.reduce((n,a)=>n+ho(a),0)),u_=(t,n)=>hp(ho(t)-ho(n)),_j=t=>({key:`chq_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,chequeNo:"",chequeDate:t,bankId:"",amount:0});function R7({profile:t,selectedBranchId:n}){const a=sa(t,"finance.manage"),[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState([]),[u,f]=x.useState([]),[g,p]=x.useState([]),[y,b]=x.useState({}),[N,w]=x.useState(""),[C,R]=x.useState(!1),[I,_]=x.useState(""),[J,T]=x.useState(new Date().toISOString().slice(0,10)),[G,z]=x.useState(0),[H,K]=x.useState(""),[L,D]=x.useState(""),[M,Z]=x.useState(new Date().toISOString().slice(0,10)),[fe,q]=x.useState("cash"),[ne,ae]=x.useState(""),[Y,je]=x.useState(0),[V,$]=x.useState(""),[F,P]=x.useState(""),[ue,me]=x.useState(""),[ge,de]=x.useState(!1),[Pe,Re]=x.useState({}),[Ee,Be]=x.useState(!1),[We,it]=x.useState([]);x.useEffect(()=>qt(re(ie,`historicalPurchases/${t.companyId}`),$e=>{const st=$e.val()||{};i(Object.entries(st).map(([Nt,be])=>({id:Nt,...be})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingVouchers/${t.companyId}`),$e=>{const st=$e.val()||{};l(Object.entries(st).map(([Nt,be])=>({id:Nt,...be})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingAccounts/${t.companyId}`),$e=>{const st=$e.val()||{};d(Object.entries(st).map(([Nt,be])=>({id:Nt,...be})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingBankAccounts/${t.companyId}`),$e=>{const st=$e.val()||{};f(Object.entries(st).map(([Nt,be])=>({id:Nt,...be})).filter(Nt=>Nt.active!==!1&&Nt.ledgerAccountId))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierOpeningPayables/${t.companyId}`),$e=>{const st=$e.val()||{};p(Object.entries(st).map(([Nt,be])=>({id:Nt,...be})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierMaster/${t.companyId}`),$e=>b($e.val()||{})),[t.companyId]);const _e=x.useMemo(()=>s.filter($e=>n==="all"||!n||$e.branchId===n).map($e=>{const st=String($e.sourceInvoiceNo||$e.supplierInvoiceRefNo||"");let Nt=0,be=0;return c.filter(jt=>jt.status==="posted").forEach(jt=>(jt.lines||[]).filter(bt=>(String(bt.accountCode)==="2100"||String(bt.accountName||"").toLowerCase().includes("accounts payable"))&&(bt.billNumber===st||bt.purchaseKey===$e.id||!bt.billNumber&&!bt.purchaseKey&&jt.reference===st)).forEach(bt=>{Nt+=Number(bt.debit||0),be+=Number(bt.credit||0)})),{id:$e.id,branchId:$e.branchId,purchaseDate:$e.purchaseDate,supplier:$e.supplier,no:st,outstanding:yd(Math.max(0,be-Nt)),sourceKind:"purchase"}}).filter($e=>$e.outstanding>.005),[s,c,n]),ee=x.useMemo(()=>g.filter($e=>n==="all"||!n||!$e.branchId||$e.branchId===n).map($e=>{let st=0;return c.filter(Nt=>Nt.status==="posted"&&Nt.sourceType==="supplier_payment").forEach(Nt=>(Nt.lines||[]).filter(be=>be.openingPayableId===$e.id).forEach(be=>st+=Number(be.debit||0))),{id:`opening:${$e.id}`,branchId:$e.branchId,purchaseDate:$e.asOfDate,supplier:$e.supplier,no:$e.reference||"OPENING PAYABLE",outstanding:yd(Math.max(0,Number($e.amount||0)-st)),sourceKind:"opening",openingPayableId:$e.id}}).filter($e=>$e.outstanding>.005),[g,c,n]),qe=x.useMemo(()=>[...ee,..._e].sort(($e,st)=>String($e.purchaseDate||"").localeCompare(String(st.purchaseDate||""))||$e.no.localeCompare(st.no)),[ee,_e]),se=x.useMemo(()=>[...new Set([...s.map($e=>$e.supplier||""),...g.map($e=>$e.supplier||""),...Object.values(y).filter($e=>$e.active!==!1).map($e=>$e.name||"")].filter(Boolean))].sort(),[s,g,y]),pe=x.useMemo(()=>qe.filter($e=>N&&$e.supplier===N),[qe,N]),Se=Bv(pe.map($e=>$e.outstanding)),Me=m.find($e=>$e.active!==!1&&!$e.isGroup&&($e.systemKey==="accounts_payable"||$e.code==="2100")),ot=m.find($e=>$e.active!==!1&&!$e.isGroup&&($e.systemKey==="migration_opening_clearing"||$e.code==="1990")),wt=Bv(g.map($e=>Number($e.amount||0))),ct=x.useMemo(()=>{let $e=Math.max(0,ho(Y));const st={};for(const Nt of pe){if($e<=0)break;const be=Math.min($e,Math.max(0,ho(Nt.outstanding)));be>0&&(st[Nt.id]=hp(be)),$e-=be}return st},[pe,Y]);x.useEffect(()=>{ge||Re(ct)},[ct,ge]),x.useEffect(()=>{Re({}),je(0),de(!1),it([])},[N]),x.useEffect(()=>{fe==="cheque"&&We.length===0&&it([_j(M)]),fe!=="cheque"&&it([])},[fe]);const Ce=ge?Pe:ct,De=Bv(Object.values(Ce).map($e=>Number($e||0))),Te=hp(Math.max(0,ho(Y)-ho(De))),ce=Bv(We.map($e=>Number($e.amount||0))),Ye=hp(ho(Y)-ho(ce)),Je=u.filter($e=>$e.kind!=="mfs");function le($e,st){const Nt=yd(Math.max(0,Math.min(Number(st||0),$e.outstanding)));Re(be=>({...be,[$e.id]:Nt}))}function nt($e,st){it(Nt=>Nt.map(be=>be.key===$e?{...be,...st}:be))}
3939function xt(){it($e=>[...$e,_j(M)])}function te($e){it(st=>st.length<=1?st:st.filter(Nt=>Nt.key!==$e))}async function Ge(){if(me(""),!(!a||Ee)){if(!I.trim())return me("Opening Payable: select a supplier first.");if(G<=0)return me("Opening Payable amount must be greater than zero.");if(!Me)return me("Accounts Payable ledger is missing. Initialize Chart of Accounts first.");Be(!0);try{const $e=Ta(re(ie,`supplierOpeningPayables/${t.companyId}`)).key,st=Date.now(),Nt=yd(G),be=n==="all"?"":n,jt=(ot==null?void 0:ot.id)||"acct_1990",bt=(ot==null?void 0:ot.code)||"1990",tn=(ot==null?void 0:ot.name)||"Migration Opening Clearing",B=`supplier_opening_${$e}`,xe=`SOP-${J.replaceAll("-","")}-${$e.slice(-6).toUpperCase()}`,tt=H.trim()||"OPENING PAYABLE",ht=[{id:"line_001",accountId:jt,accountCode:bt,accountName:tn,debit:Nt,credit:0,narration:`Supplier opening payable · ${I.trim()}`},{id:"line_002",accountId:Me.id,accountCode:Me.code,accountName:Me.name,debit:0,credit:Nt,narration:`Supplier opening payable · ${I.trim()}`}],dt={};ot||(dt[`accountingAccounts/${t.companyId}/${jt}`]={id:jt,code:bt,name:tn,type:"asset",parentId:"acct_1000",isGroup:!1,normalBalance:"debit",systemKey:"migration_opening_clearing",active:!0,createdAt:st,updatedAt:st}),dt[`supplierOpeningPayables/${t.companyId}/${$e}`]={id:$e,supplier:I.trim(),asOfDate:J,amount:Nt,reference:tt,note:L.trim(),branchId:be,accountingVoucherId:B,reconciliationStatus:"pending",createdAt:st,createdByUid:t.uid,createdByName:t.name||t.email||"User"},dt[`accountingVouchers/${t.companyId}/${B}`]={voucherNo:xe,type:"journal",status:"posted",voucherDate:J,branchId:be,reference:tt,narration:`Supplier Opening Payable · ${I.trim()}`,lines:ht,totalDebit:Nt,totalCredit:Nt,createdAt:st,updatedAt:st,postedAt:st,createdByUid:t.uid,createdByName:t.name||t.email||"User",postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"supplier_opening_payable",sourceId:$e,autoPosted:!0},ht.forEach((we,rt)=>dt[`accountingLedgerEntries/${t.companyId}/${B}_${rt+1}`]={id:`${B}_${rt+1}`,voucherId:B,voucherNo:xe,voucherType:"journal",voucherDate:J,branchId:be,reference:tt,narration:we.narration,accountId:we.accountId,accountCode:we.accountCode,accountName:we.accountName,debit:we.debit,credit:we.credit,status:"posted",createdAt:st,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"supplier_opening_payable",sourceId:$e,openingPayableId:$e,autoPosted:!0}),await yn(re(ie),dt),w(I.trim()),R(!1),_(""),z(0),K(""),D(""),me(`Supplier Opening Payable saved and auto-posted: Dr ${tn} / Cr Accounts Payable. No separate Accounting Opening entry is required.`)}catch($e){me(`Opening Payable failed: ${($e==null?void 0:$e.message)||$e}`)}finally{Be(!1)}}}async function pt($e){var tn,B;if($e.preventDefault(),me(""),Ee)return;if(!a)return me("Finance Manage permission is required.");if(!N)return me("Select a supplier first.");if(Y<=0)return me("Payment amount must be greater than zero.");if(ho(Y)>ho(Se))return me(`Payment cannot exceed this supplier's outstanding ${wo(Se)}.`);if(ho(De)!==ho(Y))return me(`Allocate the full payment. Unallocated amount: ${wo(Te)}.`);const st=pe.filter(xe=>Number(Ce[xe.id]||0)>.005);if(!st.length)return me("No supplier payable allocation found.");const Nt=m.find(xe=>xe.active!==!1&&!xe.isGroup&&(xe.systemKey==="accounts_payable"||xe.code==="2100")),be=m.find(xe=>xe.active!==!1&&!xe.isGroup&&(xe.systemKey==="cash"||xe.code==="1110"));if(!Nt)return me("Accounts Payable ledger is missing.");if(fe==="cheque"){if(!We.length)return me("Add at least one cheque.");if(ho(ce)!==ho(Y))return me(`Cheque total must equal Payment Amount. Remaining: ${wo(Ye)}.`);const xe=new Set;for(let tt=0;tt<We.length;tt++){const ht=We[tt],dt=u.find(rt=>rt.id===ht.bankId);if(!ht.chequeNo.trim())return me(`Cheque #${tt+1}: Cheque No. is required.`);if(!/^\d{4}-\d{2}-\d{2}$/.test(ht.chequeDate))return me(`Cheque #${tt+1}: valid Cheque Date is required.`);if(!(dt!=null&&dt.ledgerAccountId))return me(`Cheque #${tt+1}: select a configured bank account.`);if(!m.find(rt=>rt.id===dt.ledgerAccountId))return me(`Cheque #${tt+1}: selected bank ledger account is missing.`);if(Number(ht.amount)<=0)return me(`Cheque #${tt+1}: amount must be greater than zero.`);const we=`${ht.bankId}|${ht.chequeNo.trim().toLowerCase()}`;if(xe.has(we))return me(`Cheque #${tt+1}: duplicate Cheque No. in this payment.`);xe.add(we)}}const jt=u.find(xe=>xe.id===ne),bt=fe==="cash"?be:m.find(xe=>xe.id===(jt==null?void 0:jt.ledgerAccountId));if(fe!=="cheque"&&!bt)return me(fe==="cash"?"Cash / Accounts Payable ledger is missing.":"Select a configured Bank/MFS account with linked ledger.");Be(!0);try{const xe=await mn(re(ie,`accountingSettings/${t.companyId}`)),tt=String(((tn=xe.val())==null?void 0:tn.lockedThrough)||"");if(tt&&M.slice(0,7)<=tt)throw new Error(`Accounting period ${M.slice(0,7)} is locked.`);const ht=Ta(re(ie,`accountingVouchers/${t.companyId}`)).key,dt=Date.now(),we=`SP-${M.replaceAll("-","")}-${ht.slice(-6).toUpperCase()}`,rt=yd(Y),St=((B=st[0])==null?void 0:B.branchId)||t.branchId||"",Qt=st.map((Vt,sn)=>({id:`line_${String(sn+1).padStart(3,"0")}`,accountId:Nt.id,accountCode:Nt.code,accountName:Nt.name,debit:yd(Ce[Vt.id]),credit:0,narration:`Supplier payment allocation · ${Vt.no}`,...Vt.sourceKind==="opening"?{openingPayableId:Vt.openingPayableId}:{billNumber:Vt.no,purchaseKey:Vt.id}})),gn=fe==="cheque"?We.map((Vt,sn)=>{const on=u.find(Ct=>Ct.id===Vt.bankId),ke=m.find(Ct=>Ct.id===on.ledgerAccountId);return{id:`line_${String(Qt.length+sn+1).padStart(3,"0")}`,accountId:ke.id,accountCode:ke.code,accountName:ke.name,debit:0,credit:yd(Vt.amount),narration:`Supplier cheque · ${N} · ${Vt.chequeNo.trim()}`}}):[{id:`line_${String(Qt.length+1).padStart(3,"0")}`,accountId:bt.id,accountCode:bt.code,accountName:bt.name,debit:0,credit:rt,narration:`Supplier payment · ${N}`}];if(fe==="cheque"&&gn.some(Vt=>!Vt.accountId))throw new Error("One or more cheque bank ledger accounts are missing.");const An=[...Qt,...gn],Sn=fe==="cheque"?`${We.length} cheque(s)`:V||we,Xt={voucherNo:we,type:"payment",status:"posted",voucherDate:M,branchId:St,reference:Sn,narration:`Supplier Payment · ${N}${F?` · ${F}`:""}`,lines:An,totalDebit:rt,totalCredit:rt,createdAt:dt,updatedAt:dt,postedAt:dt,createdByUid:t.uid,createdByName:t.name||t.email||"User",postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"supplier_payment",sourceId:ht,autoPosted:!0,paymentMethod:fe,paymentReference:Sn},Wt=st.map(Vt=>({sourceKind:Vt.sourceKind,purchaseKey:Vt.sourceKind==="purchase"?Vt.id:"",openingPayableId:Vt.openingPayableId||"",billNumber:Vt.no,purchaseDate:Vt.purchaseDate||"",amount:yd(Ce[Vt.id]),outstandingBefore:Vt.outstanding,outstandingAfter:u_(Vt.outstanding,Ce[Vt.i
3939d])})),Gt=fe==="cheque"?We.map((Vt,sn)=>{const on=u.find(ke=>ke.id===Vt.bankId);return{id:`${ht}_chq_${String(sn+1).padStart(3,"0")}`,chequeNo:Vt.chequeNo.trim(),chequeDate:Vt.chequeDate,bankId:Vt.bankId,bank:on.name||"",amount:yd(Vt.amount)}}):[],$t={[`accountingVouchers/${t.companyId}/${ht}`]:Xt,[`supplierPayments/${t.companyId}/${ht}`]:{id:ht,paymentDate:M,branchId:St,supplier:N,amount:rt,method:fe,paymentAccountId:fe==="cheque"?"":bt.id,paymentAccountIds:fe==="cheque"?[...new Set(Gt.map(Vt=>Vt.bankId))]:[bt.id],reference:Sn,note:F,allocationMode:ge?"manual":"fifo_oldest_first",allocations:Wt,cheques:Gt,chequeCount:Gt.length,chequeTotal:fe==="cheque"?ce:0,unallocatedAmount:0,accountingVoucherId:ht,createdAt:dt,createdByUid:t.uid,createdByName:t.name||t.email||"User"}};fe==="cheque"&&Gt.forEach((Vt,sn)=>{const on=dt+sn,ke=Vt.id;$t[`chequeManagement/${t.companyId}/${ke}`]={id:ke,direction:"payable",party:N,chequeNo:Vt.chequeNo,bank:Vt.bank,bankId:Vt.bankId,amount:Vt.amount,chequeDate:Vt.chequeDate,promisedDate:Vt.chequeDate,status:"pending",reference:we,sourceType:"supplier_payment",sourceId:ht,sourceChequeIndex:sn+1,branchId:St,createdAt:on,createdByUid:t.uid,createdByName:t.name||t.email||"User",history:{[String(on)]:{at:on,by:t.name||t.email||"User",action:"created_from_supplier_payment",to:"pending",date:Vt.chequeDate}}}}),An.forEach((Vt,sn)=>$t[`accountingLedgerEntries/${t.companyId}/${ht}_${sn+1}`]={id:`${ht}_${sn+1}`,voucherId:ht,voucherNo:we,voucherType:"payment",voucherDate:M,branchId:St,reference:"billNumber"in Vt&&Vt.billNumber||Sn,narration:Vt.narration,accountId:Vt.accountId,accountCode:Vt.accountCode,accountName:Vt.accountName,debit:Vt.debit,credit:Vt.credit,status:"posted",createdAt:dt,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"supplier_payment",sourceId:ht,autoPosted:!0,..."billNumber"in Vt?{billNumber:Vt.billNumber,purchaseKey:Vt.purchaseKey}:{},..."openingPayableId"in Vt?{openingPayableId:Vt.openingPayableId}:{}}),await yn(re(ie),$t),me(fe==="cheque"?`Payment ${wo(rt)} posted with ${We.length} cheque(s) and allocated across ${Wt.length} invoice(s).`:`Payment ${wo(rt)} posted and allocated across ${Wt.length} invoice(s).`),je(0),$(""),P(""),Re({}),de(!1),it(fe==="cheque"?[_j(M)]:[])}catch(xe){me(`Supplier payment failed: ${(xe==null?void 0:xe.message)||xe}`)}finally{Be(!1)}}return e.jsxs("div",{className:"panel",children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"ACCOUNTS & FINANCE"}),e.jsx("h2",{children:"Supplier Payment"}),e.jsx("p",{children:"Enter one supplier payment and allocate it against opening payable and purchase bills. For Cheque payments, add all cheque instruments under the same payment batch."})]}),e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>{R($e=>!$e),_(N||"")},children:"+ Supplier Opening Payable"})]}),C&&e.jsxs("div",{className:"panel",style:{marginBottom:16},children:[e.jsx("div",{className:"section-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Supplier Opening Payable"}),e.jsx("p",{children:"Enter the supplier closing payable once. VERIXO automatically posts the balanced accounting entry to Migration Opening Clearing and Accounts Payable."})]})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Supplier",e.jsxs("select",{value:I,onChange:$e=>_($e.target.value),children:[e.jsx("option",{value:"",children:"Select supplier"}),se.map($e=>e.jsx("option",{children:$e},$e))]})]}),e.jsxs("label",{children:["As of Date",e.jsx("input",{type:"date",value:J,onChange:$e=>T($e.target.value)})]}),e.jsxs("label",{children:["Opening Payable Amount",e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:G||"",onChange:$e=>z(Number($e.target.value))})]}),e.jsxs("label",{children:["Reference",e.jsx("input",{value:H,onChange:$e=>K($e.target.value),placeholder:"e.g. Legacy opening"})]}),e.jsxs("label",{children:["Note",e.jsx("input",{value:L,onChange:$e=>D($e.target.value)})]}),e.jsxs("label",{children:["Accounting Debit",e.jsx("input",{readOnly:!0,value:"1990 · Migration Opening Clearing (Auto)"})]}),e.jsxs("label",{children:["Accounting Credit",e.jsx("input",{readOnly:!0,value:"2100 · Accounts Payable (Auto)"})]}),e.jsxs("label",{children:["Supplier Openings Entered",e.jsx("input",{readOnly:!0,value:wo(wt)})]}),e.jsx("div",{children:e.jsx("button",{type:"button",className:"primary-action",disabled:!a||Ee,onClick:Ge,children:Ee?"Saving...":"Save Opening Payable"})})]}),e.jsx("div",{className:"notice",children:"No separate Opening Balances entry is required for supplier payable. Each saved supplier opening creates one balanced, traceable accounting voucher automatically."})]}),e.jsxs("form",{onSubmit:pt,className:"form-grid",children:[e.jsxs("label",{children:["Payment Date",e.jsx("input",{type:"date",value:M,onChange:$e=>Z($e.target.value)})]}),e.jsxs("label",{children:["Supplier",e.jsxs("select",{value:N,onChange:$e=>w($e.target.value),children:[e.jsx("option",{value:"",children:"Select supplier"}),se.map($e=>e.jsx("option",{children:$e},$e))]})]}),e.jsxs("label",{children:["Total Supplier Outstanding",e.jsx("input",{readOnly:!0,value:N?wo(Se):"â"})]}),e.jsxs("label",{children:["Payment Amount",e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:Y||"",onChange:$e=>je(Number($e.target.value))})]}),e.jsxs("label",{children:["Payment Method",e.jsxs("select",{value:fe,onChange:$e=>q($e.target.value),children:[e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bank",children:"Bank / TT"}),e.jsx("option",{value:"cheque",children:"Cheque"}),e.jsx("option",{value:"mfs",children:"MFS"})]})]}),fe!=="cash"&&fe!=="cheque"&&e.jsxs("label",{children:["Bank / MFS Account",e.jsxs("select",{value:ne,onChange:$e=>ae($e.target.value),children:[e.jsx("option",{value:"",children:"Select account"}),u.filter($e=>fe==="mfs"?$e.kind==="mfs":$e.kind!=="mfs").map($e=>e.jsx("option",{value:$e.id,children:$e.name},$e.id))]})]}),fe!=="cheque"&&e.jsxs("label",{children:["Reference",e.jsx("input",{value:V,onChange:$e=>$($e.target.value)})]}),e.jsxs("label",{children:["Note",e.jsx("input",{value:F,onChange:$e=>P($e.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Allocation Mode"}),e.jsxs("select",{value:ge?"manual":"auto",onChange:$e=>{const st=$e.target.value==="manual";de(st),Re(ct)},children:[e.jsx("option",{value:"auto",children:"Auto · Oldest Invoice First"}),e.jsx("option",{value:"manual",children:"Manual Allocation"})]})]}),e.jsx("div",{children:e.jsx("button",{className:"primary-action",disabled:!a||Ee,children:Ee?"Posting...":"Post Supplier Payment"})})]}),fe==="cheque"&&e.jsxs("div",{className:"panel",style:{marginTop:16},children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Cheque Details"}),e.jsx("p",{children:"One payment can contain multiple cheques with different cheque numbers, dates, banks and amounts."})]}),e.jsx("button",{type:"button",className:"secondary-action",onClick:xt,children:"+ Add Cheque"})]}),e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Cheque No."}),e.jsx("th",{children:"Cheque Date"}),e.jsx("th",{children:"Bank"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:We.map(($e,st)=>e.jsxs("tr",{children:[e.jsx("td",{children:st+1}),e.jsx("td",{children:e.jsx("input",{value:$e.chequeNo,onChange:Nt=>nt($e.key,{chequeNo:Nt.target.value}),placeholder:"Cheque no."})}),e.jsx("td",{children:e.jsx("input",{type:"date",value:$e.chequeDate,onChange:Nt=>nt($e.key,{chequeDate:Nt.target.value})})}),e.jsx("td",{children:e.jsxs("select",{value:$e.bankId,onChange:Nt=>nt($e.key,{bankId:Nt.target.value}),children:[e.jsx("option",{value:"",children:"Select bank"}),Je.map(Nt=>e.jsx("option",{value:Nt.id,children:Nt.name},Nt.id))]})}),e.jsx("td",{children:e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:$e.amount||"",onChange:Nt=>nt($e.key,{amount:Number(Nt.target.value)})})}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"secondary-action",disabled:We.length<=1,onClick:()=>te($e.key),children:"Remove"})})]},$e.key))}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("th",{colSpan:4,children:"Cheque Total"}),e.jsx("th",{children:wo(ce)}),e.jsxs("th",{children:["Remaining ",wo(Ye)]})]})})]})})]}),ue&&e.jsx("div",{className:"notice",children:ue}),N&&e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Payable Source"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Outstanding Before"}),e.jsx("th",{children:"Adjust This Payment"}),e.jsx("th",{children:"Balance After"})]})}),e.jsxs("tbody",{children:[pe.map($e=>{const st=Number(Ce[$e.id]||0);return e.jsxs("tr",{children:[e.jsx("td",{children:$e.sourceKind==="opening"?`Opening · ${$e.no}`:$e.no}),e.jsx("td",{children:$e.purchaseDate||"â"}),e.jsx("td",{children:wo($e.outstanding)}),e.jsx("td",{children:ge?e.jsx("input",{type:"number",min:"0",max:$e.outstanding,step:"0.01",value:st||"",onChange:Nt=>le($e,Number(Nt.target.value))}):wo(st)}),e.jsx("td",{children:wo(u_($e.outstanding,st))})]},$e.id)}),!pe.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:5,children:"No outstanding opening payable or purchase invoices for this supplier."})})]}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("th",{colSpan:2,children:"Payment Allocation"}),e.jsx("th",{children:wo(Se)}),e.jsx("th",{children:wo(De)}),e.jsxs("th",{children:["Unallocated ",wo(Te)]})]})})]})})]})}const h_=t=>t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"supplier",m_=t=>
3939`৳${Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2})}`,hu=t=>`BDT ${Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2})}`;function T7({profile:t,onReturnToPurchase:n}){var ne,ae,Y,je,V,$,F,P,ue;const a=sa(t,"purchase.manage")||sa(t,"finance.manage"),s=sessionStorage.getItem("verixo.purchase.addSupplierReturn")==="1",[i,c]=x.useState([]),[l,m]=x.useState([]),[d,u]=x.useState([]),[f,g]=x.useState({}),[p,y]=x.useState(""),[b,N]=x.useState(""),[w,C]=x.useState(""),[R,I]=x.useState(!1),[_,J]=x.useState(""),[T,G]=x.useState("");x.useEffect(()=>qt(re(ie,`historicalPurchases/${t.companyId}`),me=>c(Object.entries(me.val()||{}).map(([ge,de])=>({id:ge,...de})))),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierOpeningPayables/${t.companyId}`),me=>m(Object.entries(me.val()||{}).map(([ge,de])=>({id:ge,...de})))),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierPayments/${t.companyId}`),me=>u(Object.entries(me.val()||{}).map(([ge,de])=>({id:ge,...de})))),[t.companyId]),x.useEffect(()=>qt(re(ie,`supplierMaster/${t.companyId}`),me=>g(me.val()||{})),[t.companyId]),x.useEffect(()=>()=>{_&&URL.revokeObjectURL(_)},[_]);const z=x.useMemo(()=>[...new Set([...i.map(me=>me.supplier||""),...l.map(me=>me.supplier||""),...d.map(me=>me.supplier||""),...Object.values(f).map(me=>me.name||"")].filter(Boolean))].sort((me,ge)=>me.localeCompare(ge)),[i,l,d,f]),H=x.useMemo(()=>z.map(me=>{const ge=h_(me),de=f[ge],Pe=i.filter(Be=>Be.supplier===me).length,Re=l.filter(Be=>Be.supplier===me).reduce((Be,We)=>Be+Number(We.amount||0),0),Ee=d.filter(Be=>Be.supplier===me).reduce((Be,We)=>Be+Number(We.amount||0),0);return{id:ge,name:me,master:de,purchases:Pe,opening:Re,payments:Ee}}).filter(me=>{var ge;return!p||me.name.toLowerCase().includes(p.toLowerCase())||String(((ge=me.master)==null?void 0:ge.mobile)||"").includes(p)}),[z,f,i,l,d,p]),K=b?H.find(me=>me.name===b):void 0,L=x.useMemo(()=>{if(!b)return[];const me=[...l.filter(de=>de.supplier===b).map(de=>({date:de.asOfDate||"",type:"Opening Payable",ref:de.reference||"OPENING PAYABLE",debit:0,credit:Number(de.amount||0)})),...i.filter(de=>de.supplier===b).map(de=>({date:de.purchaseDate||"",type:"Historical Purchase",ref:de.sourceInvoiceNo||de.supplierInvoiceRefNo||de.id,debit:0,credit:0})),...d.filter(de=>de.supplier===b).map(de=>({date:de.paymentDate||"",type:`Supplier Payment · ${de.method||""}`,ref:de.reference||de.id,debit:Number(de.amount||0),credit:0}))].sort((de,Pe)=>de.date.localeCompare(Pe.date)||de.type.localeCompare(Pe.type));let ge=0;return me.map(de=>(ge+=de.credit-de.debit,{...de,balance:ge}))},[b,l,i,d]),D=x.useMemo(()=>L.reduce((me,ge)=>({debit:me.debit+ge.debit,credit:me.credit+ge.credit}),{debit:0,credit:0}),[L]);async function M(me){if(me.preventDefault(),!a)return;const ge=new FormData(me.currentTarget),de=String(ge.get("name")||"").trim(),Pe=String(ge.get("mobile")||"").trim();if(!de)return C("Supplier name is required.");if(Object.values(f).find(_e=>_e.active!==!1&&_e.name.trim().toLowerCase()===de.toLowerCase()&&(Pe?String(_e.mobile||"").trim()===Pe:!0)))return C("This supplier already exists in Supplier Master.");const Ee=h_(de),Be=f[Ee]?`${Ee}_${Date.now()}`:Ee,We=Date.now(),it={id:Be,name:de,code:String(ge.get("code")||"").trim(),contactPerson:String(ge.get("contactPerson")||"").trim(),mobile:Pe,email:String(ge.get("email")||"").trim(),address:String(ge.get("address")||"").trim(),bin:String(ge.get("bin")||"").trim(),tin:String(ge.get("tin")||"").trim(),paymentTerms:String(ge.get("paymentTerms")||"").trim(),active:!0,createdAt:We,createdByUid:t.uid,updatedAt:We,updatedByUid:t.uid};await Pn(re(ie,`supplierMaster/${t.companyId}/${Be}`),it),N(de),C("Supplier created successfully."),me.currentTarget.reset(),s&&(sessionStorage.setItem("verixo.purchase.createdSupplierId",Be),sessionStorage.removeItem("verixo.purchase.addSupplierReturn"),n==null||n())}async function Z(me){if(me.preventDefault(),!a||!K)return;const ge=new FormData(me.currentTarget),de=K.id,Pe=f[de],Re={...Pe,id:de,name:K.name,code:String(ge.get("code")||(Pe==null?void 0:Pe.code)||""),contactPerson:String(ge.get("contactPerson")||""),mobile:String(ge.get("mobile")||""),email:String(ge.get("email")||""),address:String(ge.get("address")||""),bin:String(ge.get("bin")||""),tin:String(ge.get("tin")||""),paymentTerms:String(ge.get("paymentTerms")||""),active:!0,updatedAt:Date.now(),updatedByUid:t.uid};await Pn(re(ie,`supplierMaster/${t.companyId}/${de}`),Re),C("Supplier Master saved.")}const fe=()=>{_&&URL.revokeObjectURL(_),J(""),G("")},q=async me=>{var ge,de,Pe,Re;if(K){I(!0);try{const Ee=await fc(t.companyId).catch(()=>({name:"",logoUrl:""})),Be=Ee.name||"Company",We=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),it=We.internal.pageSize.getWidth(),_e=[10,61,98],ee=[24,43,59],qe=[101,119,136],se=[245,248,251],pe=[218,226,234];We.setFillColor(..._e),We.rect(0,0,it,4,"F");let Se=!1;if((ge=Ee.logoUrl)!=null&&ge.startsWith("data:image/"))try{const Ce=await new Promise((De,Te)=>{const ce=new Image;ce.onload=()=>{const Ye=document.createElement("canvas"),Je=Math.min(1,560/ce.width,180/ce.height);Ye.width=Math.max(1,Math.round(ce.width*Je)),Ye.height=Math.max(1,Math.round(ce.he
3939ight*Je));const le=Ye.getContext("2d");if(!le)return Te(new Error("Canvas unavailable"));le.fillStyle="#fff",le.fillRect(0,0,Ye.width,Ye.height),le.drawImage(ce,0,0,Ye.width,Ye.height),De(Ye.toDataURL("image/jpeg",.94))},ce.onerror=()=>Te(new Error("Logo could not be loaded")),ce.src=Ee.logoUrl});We.addImage(Ce,"JPEG",12,8,30,12,void 0,"FAST"),Se=!0}catch(Ce){console.warn("Supplier Ledger PDF logo skipped:",Ce)}We.setTextColor(...ee),We.setFont("helvetica","bold"),We.setFontSize(18),We.text(Be,Se?47:12,13),We.setFont("helvetica","normal"),We.setTextColor(...qe),We.setFontSize(8.5),We.text("Supplier sub-ledger report",Se?47:12,18),We.setTextColor(..._e),We.setFont("helvetica","bold"),We.setFontSize(16),We.text("SUPPLIER LEDGER",it-12,12,{align:"right"}),We.setTextColor(...qe),We.setFont("helvetica","normal"),We.setFontSize(8.5),We.text(`Generated: ${new Date().toLocaleString("en-GB")}`,it-12,18,{align:"right"}),We.setDrawColor(...pe),We.line(12,26,it-12,26),We.setTextColor(...ee),We.setFont("helvetica","bold"),We.setFontSize(11),We.text(K.name,12,33),We.setFont("helvetica","normal"),We.setTextColor(...qe),We.setFontSize(8.3);const Me=[((de=K.master)==null?void 0:de.mobile)&&`Mobile: ${K.master.mobile}`,((Pe=K.master)==null?void 0:Pe.contactPerson)&&`Contact: ${K.master.contactPerson}`,((Re=K.master)==null?void 0:Re.paymentTerms)&&`Terms: ${K.master.paymentTerms}`].filter(Boolean).join(" · ");Me&&We.text(Me,12,38);const ot=L.length?L[L.length-1].balance:0;We.setFont("helvetica","bold"),We.setTextColor(...ee),We.text(`Total Payment: ${hu(D.debit)}`,it-12,33,{align:"right"}),We.text(`Running Balance: ${hu(ot)}`,it-12,38,{align:"right"}),oi(We,{startY:44,head:[["Date","Type","Reference","Debit / Payment","Credit / Payable","Running Balance"]],body:L.map(Ce=>[Ce.date||"-",Ce.type,Ce.ref||"-",Ce.debit?hu(Ce.debit):"-",Ce.credit?hu(Ce.credit):"-",hu(Ce.balance)]),foot:[["","","TOTAL / CURRENT BALANCE",hu(D.debit),hu(D.credit),hu(ot)]],theme:"grid",styles:{font:"helvetica",fontSize:8,textColor:ee,cellPadding:2.4,lineColor:pe,lineWidth:.15},headStyles:{fillColor:_e,textColor:[255,255,255],fontStyle:"bold"},footStyles:{fillColor:se,textColor:ee,fontStyle:"bold"},columnStyles:{0:{cellWidth:27},1:{cellWidth:45},2:{cellWidth:75},3:{halign:"right",cellWidth:42},4:{halign:"right",cellWidth:42},5:{halign:"right",cellWidth:42}},didDrawPage:()=>{const Ce=We.internal.pageSize.getHeight();We.setFont("helvetica","normal"),We.setFontSize(7.3),We.setTextColor(...qe),We.text("Historical purchases are shown for traceability; unverified invoice liability is not guessed.",12,Ce-11),We.text("VERIXO ERP · Accounts & Finance",12,Ce-6),We.text(`Page ${We.getNumberOfPages()}`,it-12,Ce-6,{align:"right"})}});const ct=`Supplier_Ledger_${K.name.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")||"Supplier"}.pdf`;if(me==="download")We.save(ct);else{_&&URL.revokeObjectURL(_);const Ce=We.output("blob");J(URL.createObjectURL(Ce)),G(ct)}}finally{I(!1)}}};return e.jsxs("div",{className:"panel",children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"ADMINISTRATION · SUPPLIER"}),e.jsx("h2",{children:"Supplier Master"}),e.jsx("p",{children:"Create and maintain one supplier master shared by Purchase, Supplier Payable and Supplier Payment. Historical suppliers remain discoverable without rewriting old transactions."})]}),s&&e.jsxs("button",{type:"button",className:"secondary-action",onClick:()=>{sessionStorage.removeItem("verixo.purchase.addSupplierReturn"),n==null||n()},children:[e.jsx(SD,{size:16})," Back to Purchase"]})]}),e.jsxs("div",{className:"panel",style:{marginTop:16},children:[e.jsx("h3",{children:"Add New Supplier"}),e.jsxs("form",{className:"form-grid",onSubmit:M,children:[e.jsxs("label",{children:["Supplier Name *",e.jsx("input",{name:"name",required:!0,autoFocus:!0,placeholder:"Supplier name"})]}),e.jsxs("label",{children:["Supplier Code",e.jsx("input",{name:"code",placeholder:"Optional code"})]}),e.jsxs("label",{children:["Mobile",e.jsx("input",{name:"mobile",placeholder:"Mobile no."})]}),e.jsxs("label",{children:["Contact Person",e.jsx("input",{name:"contactPerson",placeholder:"Contact person"})]}),e.jsxs("label",{children:["Email",e.jsx("input",{name:"email",type:"email",placeholder:"Email"})]}),e.jsxs("label",{children:["Payment Terms",e.jsx("input",{name:"paymentTerms",placeholder:"e.g. 30 days"})]}),e.jsxs("label",{style:{gridColumn:"1 / -1"},children:["Address",e.jsx("input",{name:"address",placeholder:"Address"})]}),e.jsxs("label",{children:["BIN",e.jsx("input",{name:"bin",placeholder:"BIN"})]}),e.jsxs("label",{children:["TIN",e.jsx("input",{name:"tin",placeholder:"TIN"})]}),e.jsx("div",{style:{alignSelf:"end"},children:e.jsxs("button",{className:"primary-action",disabled:!a,children:[e.jsx(as,{size:16})," Add Supplier"]})})]}),e.jsx("p",{style:{marginTop:10,color:"#667085"},children:"Opening payable is not created here. Use the controlled Opening Payable flow for opening liability."})]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Search Supplier",e.jsx("input",{value:p,onChange:me=>y(me.target.value),placeholder:"Name or mobile"})]}),e.jsxs("label",{children:["Supplier",e.jsxs("select",{value:b,onChange:me=>{N(me.target.value),C("")},children:[e.jsx("option",{value:"",children:"Select supplier"}),H.map(me=>e.jsx("option",{children:me.name},me.name))]})]})]}),e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Supplier"}),e.jsx("th",{children:"Historical Bills"}),e.jsx("th",{children:"Opening Payable"}),e.jsx("th",{children:"Payments"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:H.map(me=>e.jsxs("tr",{style:{cursor:"pointer"},onClick:()=>N(me.name),children:[e.jsx("td",{children:e.jsx("strong",{children:me.name})}),e.jsx("td",{children:me.purchases}),e.jsx("td",{children:m_(me.opening)}),e.jsx("td",{children:m_(me.payments)}),e.jsx("td",{children:me.master?"Master Saved":"Historical / Auto"})]},me.name))})]})}),K&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"panel",style:{marginTop:16}
3939,children:[e.jsxs("h3",{children:["Supplier Details · ",K.name]}),e.jsxs("form",{className:"form-grid",onSubmit:Z,children:[e.jsxs("label",{children:["Supplier Code",e.jsx("input",{name:"code",defaultValue:((ne=K.master)==null?void 0:ne.code)||""})]}),e.jsxs("label",{children:["Contact Person",e.jsx("input",{name:"contactPerson",defaultValue:((ae=K.master)==null?void 0:ae.contactPerson)||""})]}),e.jsxs("label",{children:["Mobile",e.jsx("input",{name:"mobile",defaultValue:((Y=K.master)==null?void 0:Y.mobile)||""})]}),e.jsxs("label",{children:["Email",e.jsx("input",{name:"email",defaultValue:((je=K.master)==null?void 0:je.email)||""})]}),e.jsxs("label",{children:["Address",e.jsx("input",{name:"address",defaultValue:((V=K.master)==null?void 0:V.address)||""})]}),e.jsxs("label",{children:["BIN",e.jsx("input",{name:"bin",defaultValue:(($=K.master)==null?void 0:$.bin)||""})]}),e.jsxs("label",{children:["TIN",e.jsx("input",{name:"tin",defaultValue:((F=K.master)==null?void 0:F.tin)||""})]}),e.jsxs("label",{children:["Payment Terms",e.jsx("input",{name:"paymentTerms",defaultValue:((P=K.master)==null?void 0:P.paymentTerms)||"",placeholder:"e.g. 30 days"})]}),e.jsx("div",{children:e.jsx("button",{className:"primary-action",disabled:!a,children:"Save Supplier Master"})})]},K.name+String(((ue=K.master)==null?void 0:ue.updatedAt)||0)),w&&e.jsx("div",{className:"notice",children:w})]}),e.jsxs("div",{className:"panel",style:{marginTop:16},children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsxs("h3",{children:["Supplier Ledger · ",K.name]}),e.jsx("p",{children:"Ledger is presented as a professional PDF report instead of an on-page transaction table."})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[e.jsxs("button",{type:"button",onClick:()=>void q("preview"),disabled:R||!L.length,children:[e.jsx(ui,{size:16}),R?"Preparing...":"View PDF"]}),e.jsxs("button",{type:"button",onClick:()=>void q("download"),disabled:R||!L.length,children:[e.jsx(Uu,{size:16}),"Download PDF"]})]})]}),!L.length&&e.jsx("div",{className:"notice",children:"No supplier ledger movement found."})]})]}),_&&e.jsxs("div",{className:"gl-pdf-fullscreen",role:"dialog","aria-modal":"true","aria-label":"Supplier Ledger PDF Preview",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"PDF PREVIEW"}),e.jsx("strong",{children:"Supplier Ledger"}),e.jsx("small",{children:K==null?void 0:K.name})]}),e.jsxs("div",{children:[e.jsxs("a",{href:_,download:T,children:[e.jsx(Uu,{size:16}),"Download PDF"]}),e.jsxs("button",{type:"button",onClick:fe,children:[e.jsx(ja,{size:20}),e.jsx("span",{children:"Close"})]})]})]}),e.jsx("main",{children:e.jsx("iframe",{src:_,title:"Supplier Ledger PDF Preview"})})]})]})}const p_=t=>t==="brand"?"productBrands":t==="group"?"productGroups":"productCategories",Tl=t=>t.charAt(0).toUpperCase()+t.slice(1),pa=t=>String(t||"").trim();function Fv({profile:t,view:n,onNavigate:a,onReturnToPurchase:s}){var _e;const i=sa(t,"purchase.manage")||sa(t,"finance.manage"),[c,l]=x.useState({}),[m,d]=x.useState({}),[u,f]=x.useState({}),[g,p]=x.useState({}),[y,b]=x.useState({}),[N,w]=x.useState(""),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState(""),[G,z]=x.useState("all"),[H,K]=x.useState("all"),[L,D]=x.useState("all"),[M,Z]=x.useState([]),[fe,q]=x.useState(""),[ne,ae]=x.useState(""),[Y,je]=x.useState(""),V=sessionStorage.getItem("verixo.purchase.addProductReturn")==="1";x.useEffect(()=>qt(re(ie,`productBrands/${t.companyId}`),ee=>l(ee.val()||{}),ee=>R(`Brand Master read failed: ${ee.message}`)),[t.companyId]),x.useEffect(()=>qt(re(ie,`productGroups/${t.companyId}`),ee=>d(ee.val()||{}),ee=>R(`Group Master read failed: ${ee.message}`)),[t.companyId]),x.useEffect(()=>qt(re(ie,`productCategories/${t.companyId}`),ee=>f(ee.val()||{}),ee=>R(`Category Master read failed: ${ee.message}`)),[t.companyId]),x.useEffect(()=>qt(re(ie,`inventoryProducts/${t.companyId}`),ee=>{p(ee.val()||{}),R("")},ee=>R(`Product Master read failed: ${ee.message}`)),[t.companyId]),x.useEffect(()=>qt(re(ie,`inventoryStock/${t.companyId}`),ee=>{const qe=ee.val()||{},se={};Object.values(qe).forEach(pe=>Object.entries(pe||{}
3939).forEach(([Se,Me])=>{const ot=String((Me==null?void 0:Me.productId)||Se);se[ot]||(se[ot]=Me||{})})),b(se)},ee=>R(`Inventory catalogue read failed: ${ee.message}`)),[t.companyId]);const $=x.useMemo(()=>{const ee={};return new Set([...Object.keys(g),...Object.keys(y)]).forEach(se=>{const pe=g[se]||{id:se},Se=y[se]||{};ee[se]={...Se,...pe,id:se,name:pa(pe.name)||pa(pe.productName)||pa(Se.productName)||pa(Se.name)||se,model:pa(pe.model)||pa(Se.model),unit:pa(pe.unit)||pa(Se.unit)||"PCS",brand:pa(pe.brand)||pa(pe.brandName)||pa(pe.company)||pa(pe.companyName)||pa(pe.manufacturer)||pa(pe.make)||pa(Se.brand)||pa(Se.brandName)||pa(Se.company)||pa(Se.companyName)||pa(Se.manufacturer)||pa(Se.make),group:pa(pe.group)||pa(pe.groupName)||pa(pe.productGroup)||pa(pe.itemGroup)||pa(Se.group)||pa(Se.groupName)||pa(Se.productGroup)||pa(Se.itemGroup),category:pa(pe.category)||pa(pe.categoryName)||pa(pe.productCategory)||pa(Se.category)||pa(Se.categoryName)||pa(Se.productCategory)}}),ee},[g,y]),F=x.useMemo(()=>{const ee=qe=>{const se={};return Object.values($).forEach(pe=>{const Se=qe.map(ot=>pa(pe[ot])).find(Boolean)||"";if(!Se)return;const Me=`legacy_${Se.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}`;se[Me]={id:Me,name:Se,active:!0}}),se};return{brands:ee(["brand","brandName","company","companyName","manufacturer","make"]),groups:ee(["group","groupName","productGroup","itemGroup"]),categories:ee(["category","categoryName","productCategory"])}},[$]),P=x.useMemo(()=>({...F.brands,...c}),[F.brands,c]),ue=x.useMemo(()=>({...F.groups,...m}),[F.groups,m]),me=x.useMemo(()=>({...F.categories,...u}),[F.categories,u]),ge=x.useMemo(()=>Object.entries(n==="brand"?P:n==="group"?ue:n==="category"?me:$).map(([ee,qe])=>({...qe,id:ee})).filter(ee=>n!=="product"?ee.active!==!1:ee.deleted!==!0&&ee.archived!==!0&&pa(ee.status).toLowerCase()!=="deleted").sort((ee,qe)=>pa(ee.name).localeCompare(pa(qe.name))),[n,P,ue,me,$]);async function de(ee){var se;if(ee.preventDefault(),n==="product"||!i)return;const qe=ee.currentTarget;w("");try{const pe=new FormData(qe),Se=pa(pe.get("name"));if(!Se)return w(`${Tl(n)} name is required.`);if(ge.some(Ce=>pa(Ce.name).toLowerCase()===Se.toLowerCase()))return w(`${Tl(n)} already exists.`);const ot=Ta(re(ie,`${p_(n)}/${t.companyId}`)),wt=String(ot.key);await Pn(ot,{id:wt,name:Se,active:!0,sourceSystem:"VERIXO Product Master",createdAt:Date.now(),createdByUid:t.uid,updatedAt:Date.now()});const ct=await mn(re(ie,`${p_(n)}/${t.companyId}/${wt}`));if(!ct.exists()||pa((se=ct.val())==null?void 0:se.name)!==Se)throw new Error("Firebase read-back verification failed. Record was not confirmed after write.");qe.reset(),w(`${Tl(n)} saved and verified in Firebase.`)}catch(pe){w(`${Tl(n)} save failed: ${(pe==null?void 0:pe.message)||String(pe)}`)}}async function Pe(ee){var se,pe,Se;if(ee.preventDefault(),!i)return;const qe=ee.currentTarget;w("");try{const Me=new FormData(qe),ot=pa(Me.get("name")),wt=pa(Me.get("model")),ct=pa(Me.get("code"));if(!ot)return w("Product name is required.");if(Object.values($).some(Ge=>Ge.id!==I&&Ge.active!==!1&&pa(Ge.name).toLowerCase()===ot.toLowerCase()&&pa(Ge.model).toLowerCase()===wt.toLowerCase()))return w("A product with the same Name + Model already exists.");const De=pa(Me.get("brandId")),Te=pa(Me.get("groupId")),ce=pa(Me.get("categoryId")),Ye=I?g[I]:void 0,Je=I||String(Ta(re(ie,`inventoryProducts/${t.companyId}`)).key),le=re(ie,`inventoryProducts/${t.companyId}/${Je}`),nt={id:Je,name:ot,model:wt,code:ct,sku:ct,brandId:De,brand:((se=P[De])==null?void 0:se.name)||"",groupId:Te,group:((pe=ue[Te])==null?void 0:pe.name)||"",categoryId:ce,category:((Se=me[ce])==null?void 0:Se.name)||"",unit:pa(Me.get("unit"))||"PCS",mrp:Number(Me.get("mrp")||0),serialTracking:Me.get("serialTracking")==="on",serialControlled:Me.get("serialTracking")==="on",active:!0,updatedAt:Date.now(),updatedByUid:t.uid};I?await yn(le,{...nt,sourceSystem:(Ye==null?void 0:Ye.sourceSystem)||"VERIXO Product Master"}):await Pn(le,{...nt,sourceSystem:"VERIXO Product Master",createdAt:Date.now(),createdByUid:t.uid});const xt=await mn(le),te=xt.val();if(!xt.exists()||pa(te==null?void 0:te.id)!==Je||pa(te==null?void 0:te.name)!==ot||pa(te==null?void 0:te.model)!==wt)throw new Error("Firebase read-back verification failed. Product was not confirmed after write.");_(""),qe.reset(),w(I?"Product updated and verified in Firebase.":"Product saved and verified in Firebase."),V&&!I&&(sessionStorage.setItem("verixo.purchase.createdProductId",Je),sessionStorage.removeItem("verixo.purchase.addProductReturn"),s(Je))}catch(Me){w(`Product save failed: ${(Me==null?void 0:Me.message)||String(Me)}`)}}async function Re(ee){var Se,Me;if(ee.preventDefault(),!i||!Y)return;const qe=new FormData(ee.currentTarget),se=pa(qe.get("name")),pe=pa((Se=m[Y])==null?void 0:Se.name);if(!se)return w("Group name is required.");try{if(Object.entries(m).some(([Ce,De])=>Ce!==Y&&pa(De.name).toLowerCase()===se.toLowerCase()))return w("Group already exists.");const wt={};wt[`productGroups/${t.companyId}/${Y}/name`]=se,wt[`productGroups/${t.companyId}/${Y}/updatedAt`]=Date.now(),wt[`productGroups/${t.companyId}/${Y}/updatedByUid`]=t.uid,Object.values($).forEach(Ce=>{(pa(Ce.groupId)===Y||pa(Ce.group).toLowerCase()===pe.toLowerCase())&&g[Ce.id]&&(wt[`inventoryProducts/${t.companyId}/${Ce.id}/groupId`]=Y,wt[`inventoryProducts/${t.companyId}/${Ce.id}/group`]=se,wt[`inventoryProducts/${t.companyId}/${Ce.id}/updatedAt`]=Date.now(),wt[`inventoryProducts/${t.companyId}/${Ce.id}/updatedByUid`]=t.uid)}),await yn(re(ie),wt);const ct=await mn(re(ie,`productGroups/${t.companyId}/${Y}`));if(!ct.exists()||pa((Me=ct.val())==null?void 0:Me.name)!==se)throw new Error("Firebase read-back verification failed after group rename.");je(""),w(`Group renamed to ${se} and assigned products synchronized.`)}catch(ot){w(`Group rename failed: ${(ot==null?void 0:ot.message)||String(ot)}`)}}async function Ee(){var ee,qe;if(!i||!M.length)return w("Select at least one product.");if(!fe&&!ne)return w("Choose a Brand and/or Group for bulk assignment.");try{const se={},pe=Date.now();for(const Se of M){const Me=$[Se];Me&&(g[Se]||(se[`inventoryProducts/${t.companyId}/${Se}`]={id:Se,name:pa(Me.name),model:pa(Me.model),unit:pa(Me.unit)||"PCS",category:pa(Me.category),sourceSystem:pa(Me.sourceSystem)||"Legacy Inventory Catalogue",active:!0,updatedAt:pe,updatedByUid:t.uid}),fe&&(se[`inventoryProducts/${t.companyId}/${Se}/brandId`]=fe,se[`inventoryProducts/${t.companyId}/${Se}/brand`]=pa((ee=P[fe])==null?void 0:ee.name)),ne&&(se[`inventoryProducts/${t.companyId}/${Se}/groupId`]=ne,se[`inventoryProducts/${t.companyId}/${Se}/group`]=pa((qe=ue[ne])==null?void 0:qe.name)),se[`inventoryProducts/${t.companyId}/${Se}/updatedAt`]=pe,se[`inventoryProducts/${t.companyId}/${Se}/updatedByUid`]=t.uid)}await yn(re(ie),se);for(const Se of M){const Me=await mn(re(ie,`inventoryProducts/${t.companyId}/${Se}`));if(!Me.exists())throw new Error(`Read-back verification failed for ${Se}.`);const ot=Me.val();if(fe&&pa(ot==null?void 0:ot.brandId)!==fe)throw new Error(`Brand verification failed for ${Se}.`);if(ne&&pa(ot==null?void 0:ot.groupId)!==ne)throw new Error(`Group verification failed for ${Se}.`)}w(`${M.length} product(s) updated and verified in Firebase.`),Z([]),q(""),ae("")}catch(se){w(`Bulk update failed: ${(se==null?void 0:se.message)||String(se)}`)}}const Be=ee=>Object.entries(ee).filter(([,qe])=>qe.active!==!1).sort((qe,se)=>pa(qe[1].name).localeCompare(pa(se[1].name))),We=x.useMemo(()=>
3939{if(n!=="product")return ge;const ee=J.trim().toLowerCase();return ge.filter(qe=>{const se=pa(qe.brand),pe=pa(qe.group),Se=pa(qe.category);return G==="unassigned"&&se||G!=="all"&&G!=="unassigned"&&se.toLowerCase()!==G.toLowerCase()||H==="unassigned"&&pe||H!=="all"&&H!=="unassigned"&&pe.toLowerCase()!==H.toLowerCase()||L!=="all"&&Se.toLowerCase()!==L.toLowerCase()?!1:ee?[qe.name,qe.productName,qe.model,qe.code,qe.sku,se,pe,Se,qe.unit].map(pa).join(" ").toLowerCase().includes(ee):!0})},[n,ge,J,G,H,L]),it=n==="product"?We:ge;return e.jsxs("div",{className:"page-section",children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"ADMINISTRATION · PRODUCT"}),e.jsxs("h2",{children:[Tl(n)," Master"]}),e.jsx("p",{children:"One master source shared by Purchase, Sales, Stock and Serial traceability."})]}),V&&e.jsxs("button",{className:"secondary-action",type:"button",onClick:()=>{sessionStorage.removeItem("verixo.purchase.addProductReturn"),s("")},children:[e.jsx(SD,{size:16})," Back to Purchase"]})]}),e.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:14},children:["brand","group","category","product"].map(ee=>e.jsx("button",{type:"button",className:n===ee?"primary-action":"secondary-action",onClick:()=>a(ee),children:Tl(ee)},ee))}),n!=="product"?e.jsxs("div",{className:"panel",children:[e.jsx("h3",{children:n==="group"&&Y?"Edit Group":`Add New ${Tl(n)}`}),n==="group"&&Y?e.jsxs("form",{className:"form-grid",onSubmit:Re,children:[e.jsxs("label",{children:["Group Name",e.jsx("input",{name:"name",autoFocus:!0,defaultValue:pa((_e=m[Y])==null?void 0:_e.name)})]}),e.jsxs("div",{style:{alignSelf:"end",display:"flex",gap:8},children:[e.jsxs("button",{className:"primary-action",disabled:!i,children:[e.jsx(hr,{size:16})," Update Group"]}),e.jsxs("button",{type:"button",className:"secondary-action",onClick:()=>je(""),children:[e.jsx(ja,{size:16})," Cancel"]})]})]},Y):e.jsxs("form",{className:"form-grid",onSubmit:de,children:[e.jsxs("label",{children:[Tl(n)," Name",e.jsx("input",{name:"name",autoFocus:!0,placeholder:`Enter ${n} name`})]}),e.jsx("div",{style:{alignSelf:"end"},children:e.jsxs("button",{className:"primary-action",disabled:!i,children:[e.jsx(as,{size:16})," Add ",Tl(n)]})})]})]}):e.jsxs("div",{className:"panel",children:[e.jsx("h3",{children:I?"Edit Product":"Add New Product"}),e.jsx("form",{className:"form-grid",onSubmit:Pe,children:(()=>{const ee=I?$[I]:void 0,qe=(se,pe,Se)=>{var Me;return pe&&se[pe]?pe:((Me=Object.entries(se).find(([,ot])=>pa(ot.name).toLowerCase()===pa(Se).toLowerCase()))==null?void 0:Me[0])||""};return e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Product Name *",e.jsx("input",{name:"name",autoFocus:!0,required:!0,placeholder:"Product name",defaultValue:pa(ee==null?void 0:ee.name)})]}),e.jsxs("label",{children:["Model",e.jsx("input",{name:"model",placeholder:"Model",defaultValue:pa(ee==null?void 0:ee.model)})]}),e.jsxs("label",{children:["Brand",e.jsxs("select",{name:"brandId",defaultValue:qe(P,ee==null?void 0:ee.brandId,ee==null?void 0:ee.brand),children:[e.jsx("option",{value:"",children:"Select Brand"}),Be(P).map(([se,pe])=>e.jsx("option",{value:se,children:pe.name},se))]})]}),e.jsxs("label",{children:["Group",e.jsxs("select",{name:"groupId",defaultValue:qe(ue,ee==null?void 0:ee.groupId,ee==null?void 0:ee.group),children:[e.jsx("option",{value:"",children:"Select Group"}),Be(ue).map(([se,pe])=>e.jsx("option",{value:se,children:pe.name},se))]})]}),e.jsxs("label",{children:["Category",e.jsxs("select",{name:"categoryId",defaultValue:qe(me,ee==null?void 0:ee.categoryId,ee==null?void 0:ee.category),children:[e.jsx("option",{value:"",children:"Select Category"}),Be(me).map(([se,pe])=>e.jsx("option",{value:se,children:pe.name},se))]})]}),e.jsxs("label",{children:["Unit",e.jsxs("select",{name:"unit",defaultValue:pa(ee==null?void 0:ee.unit)||"PCS",children:[e.jsx("option",{children:"PCS"}),e.jsx("option",{children:"SET"}),e.jsx("option",{children:"BOX"}),e.jsx("option",{children:"PACK"}),e.jsx("option",{children:"METER"}),e.jsx("option",{children:"KG"}),e.jsx("option",{children:"LTR"})]})]}),e.jsxs("label",{children:["Product Code / SKU",e.jsx("input",{name:"code",placeholder:"Optional code / SKU",defaultValue:pa(ee==null?void 0:ee.code)||pa(ee==null?void 0:ee.sku)})]}),e.jsxs("label",{children:["MRP / Unit",e.jsx("input",{name:"mrp",type:"number",min:"0",step:"0.01",placeholder:"0.00",defaultValue:Number((ee==null?void 0:ee.mrp)||0)})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,alignSelf:"end",minHeight:42},children:[e.jsx("input",{name:"serialTracking",type:"checkbox",defaultChecked:!!(ee!=null&&ee.serialTracking||ee!=null&&ee.serialControlled),style:{width:16,height:16}})," Serial Tracking"]}),e.jsxs("div",{style:{alignSelf:"end",display:"flex",gap:8},children:[e.jsxs("button",{className:"primary-action",disabled:!i,children:[e.jsx(hr,{size:16})," ",I?"Update Product":"Save Product"]}),I&&e.jsxs("button",{type:"button",className:"secondary-action",onClick:()=>{_(""),w("")},children:[e.jsx(ja,{size:16})," Cancel"]})]})]})})()},I||"new-product"),e.jsx("p",{style:{marginTop:10,color:"#667085"},children:"Opening stock is not created here. Legacy product edits preserve the original sourceSystem; Brand/Group can be assigned without changing imported stock identity."})]}),C&&e.jsx("div",{className:"notice",style:{marginTop:12,color:"#b42318"},children:C}),N&&e.jsx("div",{className:"notice",style:{marginTop:12},children:N}),e.jsxs("div",{className:"panel",style:{marginTop:16},children:[e.jsxs("h3",{children:[Tl(n)," List"]}),n==="product"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(240px,2fr) repeat(3,minmax(150px,1fr)) auto",gap:10,alignItems:"end",marginBottom:14},children:[e.jsxs("label",{children:["Search",e.jsx("input",{value:J,onChange:ee=>T(ee.target.value),placeholder:"Name, model, code/SKU, brand, group, category"})]}),e.jsxs("label",{children:["Brand",e.jsxs("select",{value:G,onChange:ee=>z(ee.target.value),children:[e.jsx("option",{value:"all",children:"All Brands"}),e.jsx("option",{value:"unassigned",children:"Unassigned Brand"}),Be(P).map(([ee,qe])=>e.jsx("option",{value:pa(qe.name),children:qe.name},ee))]})]}),e.jsxs("label",{children:["Group",e.jsxs("select",{value:H,onChange:ee=>K(ee.target.value),children:[e.jsx("option",{value:"all",children:"All Groups"}),e.jsx("option",{value:"unassigned",children:"Unassigned Group"}),Be(ue).map(([ee,qe])=>e.jsx("option",{value:pa(qe.name),children:qe.name},ee))]})]}),e.jsxs("label",{children:["Category",e.jsxs("select",{value:L,onChange:ee=>D(ee.target.value),children:[e.jsx("option",{value:"all",children:"All Categories"}),Be(me).map(([ee,qe])=>e.jsx("option",{value:pa(qe.name),children:qe.name},ee))]})]}),e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>{T(""),z("all"),K("all"),D("all")},children:"Clear"})]}),e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"end",flexWrap:"wrap",padding:"10px 0 14px",borderTop:"1px solid #e5e7eb"},children:[e.jsxs("label",{style:{minWidth:190},children:["Bulk Brand",e.jsxs("select",{value:fe,onChange:ee=>q(ee.target.value),children:[e.jsx("option",{value:"",children:"Keep Brand unchanged"}),Be(P).map(([ee,qe])=>e.jsx("option",{value:ee,children:qe.name},ee))]})]}),e.jsxs("label",{style:{minWidth:190},children:["Bulk Group",e.jsxs("select",{value:ne,onChange:ee=>ae(ee.target.value),children:[e.jsx("option",{value:"",children:"Keep Group unchanged"}),Be(ue).map(([ee,qe])=>e.jsx("option",{value:ee,children:qe.name},ee))]})]}),e.jsxs("button",{type:"button",className:"primary-action",disabled:!i||!M.length||!fe&&!ne,onClick:Ee,children:[e.jsx(hr,{size:16})," Apply to ",M.length," Selected"]}),M.length>0&&e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>Z([]),children:"Clear Selection"})]})]}),e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[n==="product"&&e.jsx("th",{children:e.jsx("input",{type:"checkbox","aria-label":"Select all filtered products",checked:We.length>0&&We.every(ee=>M.includes(ee.id)),onChange:ee=>Z(qe=>ee.target.checked?Array.from(new Set([...qe,...We.map(se=>se.id)])):qe.filter(se=>!We.some(pe=>pe.id===se)))})}),e.jsx("th",{children:"#"}),e.jsx("th",{children:"Name"}),n==="product"&&e.jsxs(e.Fragment,{children:[e.jsx("th",{children:"Brand"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Category"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Unit"}),e.jsx("th",{children:"Serial"}),e.jsx("th",{children:"Action"})]}),n==="group"&&e.jsx("th",{children:"Action"})]})}
3939),e.jsx("tbody",{children:it.length?it.map((ee,qe)=>e.jsxs("tr",{children:[n==="product"&&e.jsx("td",{children:e.jsx("input",{type:"checkbox",checked:M.includes(ee.id),onChange:se=>Z(pe=>se.target.checked?Array.from(new Set([...pe,ee.id])):pe.filter(Se=>Se!==ee.id))})}),e.jsx("td",{children:qe+1}),e.jsx("td",{children:e.jsx("b",{children:ee.name||"-"})}),n==="product"&&e.jsxs(e.Fragment,{children:[e.jsx("td",{children:ee.brand||"-"}),e.jsx("td",{children:ee.group||"-"}),e.jsx("td",{children:ee.category||"-"}),e.jsx("td",{children:ee.model||"-"}),e.jsx("td",{children:ee.unit||"-"}),e.jsx("td",{children:ee.serialTracking||ee.serialControlled?"Yes":"No"}),e.jsx("td",{children:e.jsxs("button",{type:"button",className:"secondary-action",disabled:!i,onClick:()=>{_(ee.id),w(""),window.scrollTo({top:0,behavior:"smooth"})},children:[e.jsx(Tb,{size:14})," Edit"]})})]}),n==="group"&&e.jsx("td",{children:m[ee.id]?e.jsxs("button",{type:"button",className:"secondary-action",disabled:!i,onClick:()=>{je(ee.id),w(""),window.scrollTo({top:0,behavior:"smooth"})},children:[e.jsx(Tb,{size:14})," Rename"]}):e.jsx("span",{style:{color:"#667085"},children:"Legacy"})})]},ee.id)):e.jsx("tr",{children:e.jsxs("td",{colSpan:n==="product"?10:n==="group"?3:2,children:["No ",n," found."]})})})]})})]})]})}const f_=t=>`à§³${Number(t||0).toLocaleString("en-BD")}`;function M7({profile:t}){const n=sa(t,"finance.manage"),[a,s]=x.useState([]),[i,c]=x.useState("");x.useEffect(()=>qt(re(ie,`chequeManagement/${t.companyId}`),d=>{const u=d.val()||{};s(Object.entries(u).map(([f,g])=>({id:f,...g})).sort((f,g)=>String(f.promisedDate||f.chequeDate).localeCompare(String(g.promisedDate||g.chequeDate))))}),[t.companyId]);const l=x.useMemo(()=>a.filter(d=>!["cleared","cancelled","replaced"].includes(d.status)),[a]);async function m(d,u){var N,w;if(!n)return;let f="",g="";if((u==="rescheduled"||u==="bounced")&&(f=((N=window.prompt(u==="rescheduled"?"Reschedule reason":"Dishonour / return reason"))==null?void 0:N.trim())||"",!f)||u==="rescheduled"&&(g=((w=window.prompt("New promised / deposit date (YYYY-MM-DD)",d.promisedDate||d.chequeDate))==null?void 0:w.trim())||"",!/^\\d{4}-\\d{2}-\\d{2}$/.test(g)))return;const p=Date.now(),y={at:p,by:t.name||t.uid,action:u,from:d.status,to:u,date:g||void 0,reason:f||void 0},b={status:u,updatedAt:p,updatedByUid:t.uid,[`history/${p}`]:y};g&&(b.promisedDate=g),await yn(re(ie,`chequeManagement/${t.companyId}/${d.id}`),b),c(`Cheque ${d.chequeNo} updated to ${u}. Original transaction and prior history were preserved.`)}return e.jsxs("div",{className:"page-shell",children:[e.jsx("div",{className:"page-header",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Accounts & Finance"}),e.jsx("h1",{children:"Cheque Management"}),e.jsx("p",{className:"muted",children:"Cheque Lifecycle Control Center. Cheques originate from Collection or Supplier Payment; this page only controls bank placement, honour, dishonour, reschedule, replacement and audit history."})]})}),i&&e.jsx("div",{className:"notice",children:i}),e.jsxs("div",{className:"panel",children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Active Cheques"}),e.jsxs("p",{children:[l.length," active / review item(s) · no standalone cheque entry is allowed here."]})]}),e.jsx(Nd,{})]}),e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Party"}),e.jsx("th",{children:"Cheque"}),e.jsx("th",{children:"Bank"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Cheque Date"}),e.jsx("th",{children:"Deposit/Promise"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[l.map(d=>e.jsxs("tr",{children:[e.jsx("td",{children:d.direction}),e.jsx("td",{children:d.party}),e.jsx("td",{children:e.jsx("b",{children:d.chequeNo})}),e.jsx("td",{children:d.bank||"â"}),e.jsx("td",{children:f_(d.amount)}),e.jsx("td",{children:d.chequeDate}),e.jsx("td",{children:d.promisedDate||"â"}),e.jsx("td",{children:d.sourceType||"Transaction"}),e.jsx("td",{children:d.status}),e.jsx("td",{children:e.jsxs("select",{value:"",disabled:!n,onChange:u=>{u.target.value&&m(d,u.target.value)},children:[e.jsx("option",{value:"",children:"Changeâ¦"}),e.jsx("option",{value:"deposited",children:"Bank Placed / Deposited"}),e.jsx("option",{value:"cleared",children:"Honoured / Cleared"}),e.jsx("option",{value:"bounced",children:"Dishonoured"}),e.jsx("option",{value:"rescheduled",children:"Reschedule"}),e.jsx("option",{value:"replaced",children:"Replaced"}),e.jsx("option",{value:"cancelled",children:"Cancelled"})]})})]},d.id)),!l.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:10,children:"No active cheques. Cheques will appear automatically from C
3939ollection / Supplier Payment."})})]})]})})]}),e.jsxs("div",{className:"panel",children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Cheque Audit History"}),e.jsx("p",{children:"Original cheque plus every bank placement, honour, dishonour and reschedule event remains visible."})]}),e.jsx(Hi,{})]}),a.slice(0,100).map(d=>e.jsxs("details",{style:{marginBottom:8},children:[e.jsxs("summary",{children:[e.jsx("b",{children:d.chequeNo})," · ",d.party," · ",f_(d.amount)," · ",d.status]}),e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Time"}),e.jsx("th",{children:"User"}),e.jsx("th",{children:"Action"}),e.jsx("th",{children:"From"}),e.jsx("th",{children:"To"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Reason"})]})}),e.jsx("tbody",{children:Object.values(d.history||{}).sort((u,f)=>u.at-f.at).map((u,f)=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(u.at).toLocaleString("en-BD")}),e.jsx("td",{children:u.by}),e.jsx("td",{children:u.action}),e.jsx("td",{children:u.from||"â"}),e.jsx("td",{children:u.to||"â"}),e.jsx("td",{children:u.date||"â"}),e.jsx("td",{children:u.reason||"â"})]},f))})]})})]},d.id))]})]})}const kj=["lead","qualified","opportunity","proposal","won","lost"],Pf={lead:"New Lead",qualified:"Qualified",opportunity:"Opportunity",proposal:"Proposal",won:"Won",lost:"Lost"},Vm=t=>`à§³${Number(t||0).toLocaleString("en-BD")}`,g_=t=>t?new Date(t).toLocaleString("en-BD"):"";function $7({profile:t,onNavigate:n}){const a=sa(t,"customer.manage"),[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState(""),[u,f]=x.useState(""),[g,p]=x.useState(""),[y,b]=x.useState(""),[N,w]=x.useState(0),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState(!1),[G,z]=x.useState(""),[H,K]=x.useState("all"),[L,D]=x.useState(null),[M,Z]=x.useState([]),[fe,q]=x.useState(!1),[ne,ae]=x.useState("");x.useEffect(()=>qt(re(ie,`crmPipeline/${t.companyId}`),Re=>{const Ee=Re.val()||{};i(Object.entries(Ee).map(([Be,We])=>({id:Be,...We})).sort((Be,We)=>We.createdAt-Be.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`customers/${t.companyId}`),Re=>{const Ee=Re.val()||{};l(Object.entries(Ee).map(([Be,We])=>({id:Be,...We})))}),[t.companyId]),x.useEffect(()=>{if(Z([]),ae(""),!(L!=null&&L.chatSessionId)){q(!1);return}q(!0);const Re=re(ie,`crmWebsiteChatMessages/${t.companyId}/${L.chatSessionId}`);return qt(Re,Ee=>{const Be=Ee.val()||{},We=Object.entries(Be).map(([it,_e])=>({id:it,..._e})).filter(it=>(it.role==="visitor"||it.role==="assistant")&&String(it.text||"").trim()!=="").sort((it,_e)=>Number(it.createdAt||0)-Number(_e.createdAt||0)||it.id.localeCompare(_e.id));Z(We),q(!1),ae("")},()=>{Z([]),q(!1),ae("Chat history could not be loaded.")})},[t.companyId,L==null?void 0:L.chatSessionId]);const Y=new Date().toISOString().slice(0,10),je=x.useMemo(()=>s.filter(Re=>!["won","lost"].includes(Re.stage)),[s]),V=x.useMemo(()=>je.filter(Re=>Re.nextFollowUp&&Re.nextFollowUp<Y),[je]),$=x.useMemo(()=>je.filter(Re=>Re.nextFollowUp===Y),[je]),F=x.useMemo(()=>je.reduce((Re,Ee)=>Re+Number(Ee.value||0),0),[je]),P=x.useMemo(()=>{const Re=G.trim().toLowerCase();return s.filter(Ee=>(H==="all"||Ee.stage===H)&&(!Re||[Ee.name,Ee.phone,Ee.company,Ee.owner,Ee.source,Ee.sourceName,Ee.email,Ee.service].some(Be=>String(Be||"").toLowerCase().includes(Re))))},[s,G,H]);async function ue(Re){if(Re.preventDefault(),_(""),!a||!m.trim())return;const Ee=u.replace(/\D/g,""),Be=Ee?c.find(it=>String(it.phone||"").replace(/\D/g,"")===Ee):void 0,We=Ta(re(ie,`crmPipeline/${t.companyId}`));await Pn(We,{id:We.key,name:m.trim(),phone:u.trim(),company:g.trim(),source:y.trim(),stage:"lead",value:N,nextFollowUp:C,owner:t.name||t.uid,customerId:(Be==null?void 0:Be.id)||"",createdAt:Date.now(),createdByUid:t.uid}),d(""),f(""),p(""),b(""),w(0),R(""),T(!1),_(Be?`Lead linked to existing customer ${Be.name||Be.id}.`:"Lead added to CRM pipeline.")}async function me(Re,Ee){a&&await yn(re(ie,`crmPipeline/${t.companyId}/${Re}`),{stage:Ee,updatedAt:Date.now(),updatedByUid:t.uid})}async function ge(Re){if(!a||Re.customerId)return;const Ee=String(Re.phone||"").replace(/\D/g,""),Be=Ee?c.find(it=>String(it.phone||"").replace(/\D/g,"")===Ee):void 0;if(Be){await yn(re(ie,`crmPipeline/${t.companyId}/${Re.id}`),{customerId:Be.id,stage:"won",convertedAt:Date.now()}),_(`Linked to existing customer ${Be.name||Be.id}.`);return}const We=Ta(re(ie,`customers/${t.companyId}`));await Pn(We,{id:We.key,companyId:t.companyId,branchId:"",name:Re.name,phone:Re.phone||"",address:"",active:!0,source:"crm",createdAt:Date.now(),createdBy:t.name||t.uid}),await yn(re(ie,`crmPipeline/${t.companyId}/${Re.id}`),{customerId:We.key,stage:"won",convertedAt:Date.now(),convertedByUid:t.uid}),_(`${Re.name} converted to Customer Master.`)}const de=Re=>e.jsxs("article",{className:"crm-deal-card",children:[e.jsxs("div",{className:"crm-deal-head",children:[e.jsx("div",{className:"crm-avatar",children:Re.n
3939ame.slice(0,1).toUpperCase()}),e.jsxs("div",{children:[e.jsx("strong",{children:Re.name}),e.jsx("small",{children:Re.company||"Individual prospect"})]}),Re.sourceType==="website"&&e.jsxs("span",{className:"crm-web-badge",children:[e.jsx(Pb,{size:11}),"Website Enquiry"]})]}),e.jsxs("div",{className:"crm-deal-meta",children:[Re.phone&&e.jsxs("span",{children:[e.jsx(fg,{size:13}),Re.phone]}),Re.email&&e.jsxs("span",{children:[e.jsx(DD,{size:13}),Re.email]}),Re.service&&e.jsxs("span",{children:[e.jsx(Mc,{size:13}),Re.service]}),e.jsxs("span",{children:[e.jsx(Mc,{size:13}),Vm(Re.value)]}),Re.nextFollowUp&&e.jsxs("span",{className:Re.nextFollowUp<Y?"overdue":"",children:[e.jsx(tA,{size:13}),Re.nextFollowUp]})]}),e.jsxs("button",{className:"crm-detail-button",onClick:()=>D(Re),children:[e.jsx(ui,{size:13}),"Details"]}),e.jsxs("div",{className:"crm-deal-footer",children:[e.jsx("select",{value:Re.stage,disabled:!a,onChange:Ee=>void me(Re.id,Ee.target.value),children:kj.map(Ee=>e.jsx("option",{value:Ee,children:Pf[Ee]},Ee))}),Re.customerId?e.jsx("button",{onClick:()=>n==null?void 0:n("estimates"),children:"Quotation"}):e.jsx("button",{disabled:!a,onClick:()=>void ge(Re),children:"Convert"})]})]},Re.id),Pe=L?[["Organization / Company",L.company],["Phone",L.phone],["Email",L.email],["Requested Service",L.service],["Project Location",L.projectLocation],["Preferred Timeline",L.preferredTimeline],["Budget / Potential Value",L.budget!==void 0&&L.budget!==""?Vm(Number(L.budget)):L.value?Vm(L.value):""],["Project Details",L.projectDetails],["Source",L.sourceName||L.source],["Received Date / Time",g_(L.submittedAt||L.createdAt)],["Assigned Owner",L.owner],["Next Follow-up",L.nextFollowUp],["Current Stage",Pf[L.stage]]]:[];return e.jsxs("div",{className:"page-shell crm-page",children:[e.jsxs("div",{className:"crm-hero",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"CUSTOMER RELATIONSHIP MANAGEMENT"}),e.jsx("h1",{children:"Sales CRM Workspace"}),e.jsx("p",{children:"Lead â Opportunity â Follow-up â Quotation â Customer. One workspace, linked with VERIXO Customer Master."})]}),e.jsxs("button",{className:"primary-action",onClick:()=>T(Re=>!Re),children:[e.jsx(as,{size:18}),J?"Close":"New Lead"]})]}),e.jsxs("div",{className:"crm-kpi-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:e.jsx(t2,{size:18})}),e.jsx("small",{children:"Open Pipeline"}),e.jsx("strong",{children:je.length}),e.jsx("em",{children:"Active prospects"})]}),e.jsxs("div",{children:[e.jsx("span",{children:e.jsx(MD,{size:18})}),e.jsx("small",{children:"Pipeline Value"}),e.jsx("strong",{children:Vm(F)}),e.jsx("em",{children:"Potential revenue"})]}),e.jsxs("div",{children:[e.jsx("span",{children:e.jsx(tA,{size:18})}),e.jsx("small",{children:"Follow-up Today"}),e.jsx("strong",{children:$.length}),e.jsxs("em",{children:[V.length," overdue"]})]}),e.jsxs("div",{children:[e.jsx("span",{children:e.jsx(Ms,{size:18})}),e.jsx("small",{children:"Won"}),e.jsx("strong",{children:s.filter(Re=>Re.stage==="won").length}),e.jsx("em",{children:"Converted / closed won"})]})]}),I&&e.jsx("div",{className:"notice",children:I}),J&&e.jsxs("section",{className:"panel crm-create-panel",children:[e.jsx("div",{className:"section-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Create Lead"}),e.jsx("p",{children:"Capture the opportunity once. Matching phone numbers are linked to existing customers."})]})}),e.jsxs("form",{className:"crm-form-grid",onSubmit:ue,children:[e.jsxs("label",{children:[e.jsxs("span",{children:[e.jsx(s6,{size:14}),"Contact Name"]}),e.jsx("input",{value:m,onChange:Re=>d(Re.target.value),required:!0,placeholder:"Contact person"})]}),e.jsxs("label",{children:[e.jsxs("span",{children:[e.jsx(fg,{size:14}),"Phone"]}),e.jsx("input",{value:u,onChange:Re=>f(Re.target.value),placeholder:"01XXXXXXXXX"})]}),e.jsxs("label",{children:[e.jsxs("span",{children:[e.jsx(Fu,{size:14}),"Company"]}),e.jsx("input",{value:g,onChange:Re=>p(Re.target.value),placeholder:"Company / organization"})]}),e.jsxs("label",{children:["Lead Source",e.jsx("input",{value:y,onChange:Re=>b(Re.target.value),placeholder:"Referral / Web / Walk-in"})]}),e.jsxs("label",{children:["Potential Value",e.jsx("input",{type:"number",min:"0",value:N||"",onChange:Re=>w(Number(Re.target.value))})]}),e.jsxs("label",{children:["Next Follow-up",e.jsx("input",{type:"date",value:C,onChange:Re=>R(Re.target.value)})]}),e.jsxs("div",{className:"crm-form-actions",children:[e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>T(!1),children:"Cancel"}),e.jsx("button",{className:"primary-action",disabled:!a,children:"Save Lead"})]})]})]}),e.jsxs("section",{className:"crm-toolbar",children:[e.jsxs("div",{className:"crm-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:G,onChange:Re=>
3939z(Re.target.value),placeholder:"Search lead, phone, company, owner..."})]}),e.jsxs("div",{className:"crm-filter",children:[e.jsx(_D,{size:16}),e.jsxs("select",{value:H,onChange:Re=>K(Re.target.value),children:[e.jsx("option",{value:"all",children:"All stages"}),kj.map(Re=>e.jsx("option",{value:Re,children:Pf[Re]},Re))]})]})]}),e.jsx("section",{className:"crm-board",children:kj.slice(0,5).map(Re=>{const Ee=P.filter(Be=>Be.stage===Re);return e.jsxs("div",{className:"crm-column",children:[e.jsxs("div",{className:"crm-column-head",children:[e.jsx("span",{children:Pf[Re]}),e.jsx("b",{children:Ee.length})]}),e.jsx("div",{className:"crm-column-value",children:Vm(Ee.reduce((Be,We)=>Be+Number(We.value||0),0))}),e.jsxs("div",{className:"crm-column-body",children:[Ee.map(de),!Ee.length&&e.jsxs("div",{className:"crm-empty",children:["No ",Pf[Re].toLowerCase()]})]})]},Re)})}),e.jsxs("section",{className:"panel crm-followup-panel",children:[e.jsx("div",{className:"panel-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Follow-up Queue"}),e.jsx("p",{children:"Overdue items first, then today's commitments"})]})}),e.jsxs("div",{className:"crm-followup-list",children:[[...V,...$].slice(0,12).map(Re=>e.jsxs("button",{children:[e.jsxs("span",{children:[e.jsx("strong",{children:Re.name}),e.jsx("small",{children:Re.company||Re.phone||"Prospect"})]}),e.jsx("span",{className:Re.nextFollowUp&&Re.nextFollowUp<Y?"overdue":"",children:Re.nextFollowUp&&Re.nextFollowUp<Y?"Overdue":"Today"}),e.jsx("b",{children:Vm(Re.value)})]},Re.id)),!V.length&&!$.length&&e.jsx("p",{className:"muted",children:"No overdue or due-today follow-up."})]})]}),L&&e.jsx("div",{className:"crm-detail-backdrop",onClick:()=>D(null),children:e.jsxs("section",{className:"crm-detail-modal",onClick:Re=>Re.stopPropagation(),children:[e.jsx("button",{className:"crm-detail-close",onClick:()=>D(null),children:e.jsx(ja,{size:18})}),e.jsxs("div",{className:"crm-detail-title",children:[L.sourceType==="website"&&e.jsxs("span",{className:"crm-web-badge",children:[e.jsx(Pb,{size:12}),"Website Enquiry"]}),e.jsx("h2",{children:L.name}),e.jsx("p",{children:L.sourceName||L.source||"CRM Lead"})]}),e.jsx("div",{className:"crm-detail-grid",children:Pe.filter(([,Re])=>Re!=null&&String(Re).trim()!=="").map(([Re,Ee])=>e.jsxs("div",{className:Re==="Project Details"?"wide":"",children:[e.jsx("small",{children:Re}),e.jsx("strong",{children:String(Ee)})]},String(Re)))}),L.chatSessionId&&e.jsxs("section",{className:"crm-chat-history",children:[e.jsxs("div",{className:"crm-chat-history-head",children:[e.jsxs("div",{children:[e.jsx(zu,{size:16}),e.jsx("span",{children:"Chat History"})]}),e.jsx("small",{children:"Read-only website conversation"})]}),fe?e.jsx("div",{className:"crm-chat-history-state",children:"Loading conversationâ¦"}):ne?e.jsx("div",{className:"crm-chat-history-state error",children:ne}):M.length?e.jsx("div",{className:"crm-chat-history-list",children:M.map(Re=>e.jsxs("article",{className:`crm-chat-message ${Re.role}`,children:[e.jsxs("div",{children:[e.jsx("strong",{children:Re.role==="visitor"?"Visitor":"Assistant"}),e.jsx("time",{children:g_(Re.createdAt)})]}),e.jsx("p",{children:Re.text})]},Re.id))}):e.jsx("div",{className:"crm-chat-history-state",children:"No conversation messages found for this chat session."})]})]})})]})}const y_=t=>Array.from(new Set(t.split(/\r?\n|,/).map(n=>n.trim()).filter(Boolean))),O7=t=>`wlc_${t.replace(/[^A-Za-z0-9_-]/g,"")}`,Dj="https://verixo-api.duckdns.org/api/public/crm/enquiry";function L7({profile:t}){const n=sa(t,"crmConnector.read"),a=sa(t,"crmConnector.manage"),[s,i]=x.useState([]),[c,l]=x.useState(""),[m,d]=x.useState(""),[u,f]=x.useState("active"),[g,p]=x.useState(""),[y,b]=x.useState(""),[N,w]=x.useState(""),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState(""),[G,z]=x.useState(!1),[H,K]=x.useState("");x.useEffect(()=>{if(n)return qt(re(ie,`crmWebsiteConnectors/${t.companyId}`),Y=>{const je=Y.val()||{};i(Object.entries(je).map(([V,$])=>({id:V,...$})).sort((V,$)=>V.name.localeCompare($.name)))})},[t.companyId,n]);const L=x.useMemo(()=>s.find(Y=>Y.id===c),[s,c]),D=x.useMemo(()=>L?JSON.stringify({endpoint:Dj,connectorId:L.publicConnectorId,allowedDomains:L.allowedDomains,services:L.services},null,2):"",[L]),M=x.useMemo(()=>L?`const VERIXO_CRM = ${D}; 3940 3941async function submitEnquiry(formData) { 3942 const submissionId = "web_" + Date.now() + "_" + Math.random().toString(36).slice(2,10); 3943 const response = await fetch(VERIXO_CRM.endpoint, { 3944 method: "POST", 3945 headers: { "Content-Type": "application/json" }, 3946 body: JSON.stringify({ 3947 connectorId: VERIXO_CRM.connectorId, 3948 submissionId, 3949 name: formData.name, 3950 phone: formData.phone || "", 3951 email: formData.email || "", 3952 company: formData.company || "", 3953 service: formData.service || "", 3954 projectLocation: formData.projectLocation || "", 3955 preferredTimeline: formData.preferredTimeline || "", 3956 budget: formData.budget || "", 3957 projectDetails: formData.projectDetails || "" 3958 }) 3959 }); 3960 const result = await response.json(); 3961 if (!response.ok) throw new Error(result.error || "VERIXO CRM submission failed"); 3962 return result; 3963}`:"",[L,D]);async function Z(Y,je){try{await navigator.clipboard.writeText(je),K(Y),window.setTimeout(()=>K(V=>V===Y?"":V),1600)}catch{T("Copy failed. Please select the value and copy it manually.")}}function fe(){l(""),d(""),f("active"),p(""),b(""),w(""),R(""),_(""),T("")}function q(Y){l(Y.id),d(Y.name),f(Y.status),p(Y.allowedDomains.join(` 3964`)),b(Y.sourceName),w(Y.defaultOwner||""),R(Y.defaultBranch||""),_(Y.services.join(` 3965`)),T("")}async function ne(Y){if(Y.preventDefault(),T(""),!a){T("Website Connector save blocked: you do not have crmConnector.manage permission.");return}if(!m.trim()||!y.trim()){T("Connector Name and Source Name are required.");return}z(!0);try{const je=Date.now(),V=c?re(ie,`crmWebsiteConnectors/${t.companyId}/${c}`):Ta(re(ie,`crmWebsiteConnectors/${t.companyId}`)),$=c||V.key;if(!$)throw new Error("Could not generate a connector ID.");const F=s.find(ue=>ue.id===$),P={id:$,name:m.trim(),status:u,allowedDomains:y_(g),sourceName:y.trim(),services:y_(I),publicConnectorId:(F==null?void 0:F.publicConnectorId)||O7($),createdAt:(F==null?void 0:F.createdAt)||je,createdByUid:(F==null?void 0:F.createdByUid)||t.uid,updatedAt:je,updatedByUid:t.uid};N.trim()&&(P.defaultOwner=N.trim()),C.trim()&&(P.defaultBranch=C.trim()),await Pn(V,P),l($),T("Website Connector saved successfully. Phase B API will accept submissions after VPS activation and origin validation.")}catch(je){const V=String((je==null?void 0:je.code)||""),$=String((je==null?void 0:je.message)||je||"Unknown Firebase error");T(`Website Connector save failed${V?` (${V})`:""}: ${$}`)}finally{z(!1)}}async function ae(Y){a&&await yn(re(ie,`crmWebsiteConnectors/${t.companyId}/${Y.id}`),{status:Y.status==="active"?"inactive":"active",updatedAt:Date.now(),updatedByUid:t.uid})}return n?e.jsxs("div",{className:"page-shell crm-connector-page",children:[e.jsxs("div",{className:"crm-hero",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"CRM SETUP"}),e.jsx("h1",{children:"Website Connectors"}),e.jsx("p",{children:"Company-scoped configuration for secure website enquiry intake. Website submissions use the Phase B VPS API; Firebase remains private to authenticated VERIXO users/server credentials."})]}),a&&e.jsxs("button",{className:"primary-action",onClick:fe,children:[e.jsx(as,{size:18}),"New Connector"]})]}),e.jsxs("div",{className:"crm-connector-layout",children:[e.jsxs("section",{className:"panel",children:[e.jsx("div",{className:"panel-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Connectors"}),e.jsxs("p",{children:[s.length," configured for this company"]})]})}),e.jsxs("div",{className:"crm-connector-list",children:[s.map(Y=>e.jsxs("button",{className:c===Y.id?"active":"",onClick:()=>q(Y),children:[e.jsxs("span",{children:[e.jsx(Pb,{size:17}),e.jsxs("span",{children:[e.jsx("strong",{children:Y.name}),e.jsx("small",{children:Y.sourceName})]})]}),e.jsx("em",{className:Y.status,children:Y.status})]},Y.id)),!s.length&&e.jsx("p",{className:"muted",children:"No website connector configured yet."})]})]}),e.jsxs("section",{className:"panel",children:[e.jsxs("div",{className:"panel-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:L?"Connector Details":"Create Connector"}),e.jsx("p",{children:"Services and domains are connector-specific; no company or website is hardcoded."})]}),L&&a&&e.jsxs("button",{className:"secondary-action",onClick:()=>void ae(L),children:[L.status==="active"?e.jsx(e6,{size:17}):e.jsx(Z4,{size:17})," ",L.status==="active"?"Deactivate":"Activate"]})]}),e.jsxs("form",{className:"crm-connector-form",onSubmit:ne,children:[e.jsxs("label",{children:["Connector Name",e.jsx("input",{required:!0,value:m,onChange:Y=>d(Y.target.value),placeholder:"Company Website"})]}),e.jsxs("label",{children:["Source Name",e.jsx("input",{required:!0,value:y,onChange:Y=>b(Y.target.value),placeholder:"Website enquiry source"})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:u,onChange:Y=>f(Y.target.value),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]}),e.jsxs("label",{children:["Default Lead Owner ",e.jsx("small",{children:"Optional"}),e.jsx("input",{value:N,onChange:Y=>w(Y.target.value),placeholder:"Owner/user reference"})]}),e.jsxs("label",{children:["Default Branch ",e.jsx("small",{children:"Optional"}),e.jsx("input",{value:C,onChange:Y=>R(Y.target.value),placeholder:"Branch reference"})]}),e.jsxs("label",{className:"wide",children:["Allowed Domains ",e.jsx("small",{children:"One per line; Phase B API validates server-side"}),e.jsx("textarea",{value:g,onChange:Y=>p(Y.target.value),placeholder:`https://example.com 3966https://www.example.com`})]}),e.jsxs("label",{className:"wide",children:["Configured Services ",e.jsx("small",{children:"One per line"}),e.jsx("textarea",{value:I,onChange:Y=>_(Y.target.value),placeholder:`Service A 3967Service B`})]}),L&&e.jsxs("div",{className:"crm-public-id",children:[e.jsx(Gh,{size:17}),e.jsxs("div",{children:[e.jsx("small",{children:"Public Connector Identifier"}),e.jsx("code",{children:L.publicConnectorId}),e.jsx("p",{children:"Identifier only â it is not a secret and grants no Firebase access."})]})]}),e.jsxs("div",{className:"crm-connector-safety",children:[e.jsx(gs,{size:18}),e.jsxs("span",{children:["Company scope: ",e.jsx("strong",{children:t.companyId}),". Public submissions require the Phase B VPS API to be active."]})]}),J&&e.jsx("div",{className:"notice wide",children:J}),a&&e.jsx("div",{className:"crm-form-actions",children:e.jsxs("button",{className:"primary-action",type:"submit",disabled:G,children:[e.jsx(hr,{size:17}),G?"Savingâ¦":"Save Connector"]})})]}),L&&e.jsxs("div",{className:"crm-integration-setup",children:[e.jsxs("div",{className:"crm-integration-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"INTEGRATION SETUP"}),e.jsx("h3",{children:"Website Integration"}),e.jsx("p",{children:"Use this connector-specific configuration on the client website. The public connector identifier resolves the correct VERIXO company on the server; companyId and Firebase credentials must never be sent from the browser."})]}),e.jsx(gs,{size:22})]}),e.jsxs("div",{className:"crm-integration-grid",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Public HTTPS Endpoint"}),e.jsx("code",{children:Dj}),e.jsxs("button",{type:"button",onClick:()=>void Z("endpoint",Dj),children:[H==="endpoint"?e.jsx(ap,{size:15}):e.jsx(sp,{size:15})," ",H==="endpoint"?"Copied":"Copy"]})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Public Connector ID"}),e.jsx("code",{children:L.publicConnectorId}),e.jsxs("button",{type:"button",onClick:()=>void Z("connector",L.publicConnectorId),children:[H==="connector"?e.jsx(ap,{size:15}):e.jsx(sp,{size:15})," ",H==="connector"?"Copied":"Copy"]})]})]}),e.jsxs("div",{className:"crm-integration-summary",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Allowed Domains"}),L.allowedDomains.length?e.jsx("ul",{children:L.allowedDomains.map(Y=>e.jsx("li",{children:Y},Y))}):e.jsx("p",{children:"No allowed domain configured."})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Configured Services"}),L.services.length?e.jsx("ul",{children:L.services.map(Y=>e.jsx("li",{children:Y},Y))}):e.jsx("p",{children:"No service restriction configured."})]})]}),e.jsxs("div",{className:"crm-integration-code",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Connector Configuration"}),e.jsxs("button",{type:"button",onClick:()=>void Z("config",D),children:[H==="config"?e.jsx(ap,{size:15}):e.jsx(sp,{size:15})," ",H==="config"?"Copied":"Copy Config"]})]}),e.jsx("pre",{children:D})]}),e.jsxs("div",{className:"crm-integration-code",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Ready JavaScript Example"}),e.jsxs("button",{type:"button",onClick:()=>void Z("example",M),children:[H==="example"?e.jsx(ap,{size:15}):e.jsx(sp,{size:15})," ",H==="example"?"Copied":"Copy Example"]})]}),e.jsx("pre",{children:M})]}),e.jsxs("div",{className:"crm-integration-note",children:[e.jsx(Gh,{size:17}),e.jsx("span",{children:"The connector ID is public, not a Firebase secret. Server-side origin validation, company resolution, rate limiting and CRM write isolation remain enforced by the VERIXO API."})]})]})]})]})]}):e.jsx("div",{className:"page-shell",children:e.jsx("div",{className:"notice",children:"You do not have Website Connector access."})})}const B7="https://verixo-api.duckdns.org/api/public/crm/internal-ai/respond",F7={dashboard:"management",company:"management",branches:"management",companyMaster:"management",versionHistory:"management",reports:"management",customers:"crm",crmWorksp
3967ace:"crm",crmWebsiteConnectors:"crm",serviceJobs:"service",estimates:"service",technicians:"service",deliveryScan:"service",performanceService:"service",rma:"service",invoices:"sales",newSale:"sales",salesDatewiseReport:"sales",performanceSales:"sales",performanceLeaderboard:"sales",purchaseDatewiseReport:"purchase",supplierMaster:"purchase",promotions:"purchase",stockReport:"inventory",dataMigration:"inventory",collections:"accounts",supplierPayment:"accounts",chequeManagement:"accounts",salaryPayable:"accounts",financeReports:"accounts",financeCollectionReport:"accounts",financeDueReport:"accounts",financeSupplierPayableReport:"accounts",dayBookReport:"accounts",chartOfAccounts:"accounts",openingBalances:"accounts",bankSetup:"accounts",accountingVouchers:"accounts",trialBalance:"accounts",generalLedger:"accounts",profitLoss:"accounts",balanceSheet:"accounts",employees:"hr",organizationSetup:"hr",userPermissions:"hr",appraisal:"hr",reportingHierarchy:"hr",employeeLifecycle:"hr",employeeRelations:"hr",hrLetters:"hr",gratuity:"hr",recruitment:"hr",payroll:"payroll",advanceLoanRequests:"payroll",attendance:"attendance",attendanceLunch:"attendance",attendanceMovement:"attendance",attendanceDevices:"attendance",attendanceFaceEnrollment:"attendance",attendanceHolidays:"attendance",attendanceShifts:"attendance",attendanceLeave:"attendance",attendanceMonthly:"attendance",attendanceDaily:"attendance",attendanceReports:"attendance"},Uv={management:"Top Management",sales:"Sales",service:"Service",crm:"CRM",purchase:"Purchase",inventory:"Inventory",accounts:"Accounts & Finance",hr:"HR",payroll:"Payroll",attendance:"Attendance"};function U7({profile:t,currentPage:n}){const[a,s]=x.useState(!1),[i,c]=x.useState(""),[l,m]=x.useState(!1),[d,u]=x.useState(""),[f,g]=x.useState([]),[p,y]=x.useState(""),b=x.useMemo(()=>F7[n]||"management",[n]),N=`${t.uid||"user"}:${t.companyId}`,w=x.useRef(N);x.useEffect(()=>{w.current!==N&&(g([]),c(""),u(""),p&&URL.revokeObjectURL(p),y(""),w.current=N)},[N,p]);const C=G=>
3967String(G||"").replace(/\\n/g,` 3968`),R=()=>{g([]),c(""),u("")},I=G=>{const z=new Ra({orientation:"portrait",unit:"mm",format:"a4"});z.setFont("helvetica","bold"),z.setFontSize(16),z.text("VERIXO AI Report",14,18),z.setFont("helvetica","normal"),z.setFontSize(9),z.text(`${Uv[b]} · Read-only authorized ERP context`,14,25),z.setDrawColor(180),z.line(14,29,196,29),z.setFontSize(10);const H=C(G).replace(/#{1,6}\s*/g,"").replace(/\*\*/g,""),K=z.splitTextToSize(H,182);let L=36;for(const D of K)L>282&&(z.addPage(),L=18),z.text(String(D),14,L),L+=5;return z},_=G=>I(G).save(`VERIXO_AI_${b}_${new Date().toISOString().slice(0,10)}.pdf`),J=G=>{try{const z=I(G).output("dataurlstring"),H=window.open(z,"_blank","noopener,noreferrer");u(H?"":"PDF preview was blocked by the browser. Please allow pop-ups for VERIXO or use Download PDF.")}catch(z){u(z instanceof Error?z.message:"Unable to open PDF preview.")}},T=async G=>{G.preventDefault();const z=i.trim();if(!z||l)return;const H=Ti.currentUser;if(!H){u("Your VERIXO login session is not available. Please sign in again.");return}m(!0),u(""),c("");try{const K=await H.getIdToken(),L=f.slice(-20);g(q=>[...q,{role:"user",content:z}]);const D=await fetch(B7,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({module:b,message:z,history:L,workspaceId:t.companyId})}),M=await D.json().catch(()=>({}));if(!D.ok||!(M!=null&&M.ok))throw new Error(String((M==null?void 0:M.error)||`AI request failed (${D.status})`));const Z=String(M.reply||""),fe=!!M.reportRequested||/\b(pdf|report)\b/i.test(z);g(q=>[...q,{role:"assistant",content:Z,pdfReady:fe}])}catch(K){u(K instanceof Error?K.message:"AI request failed.")}finally{m(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"verixo-ai-launcher",onClick:()=>s(!0),title:"VERIXO AI Assistant","aria-label":"Open VERIXO AI Assistant",children:[e.jsx(Y0,{size:19}),e.jsx("span",{children:"AI"})]}),p&&e.jsx("div",{className:"verixo-ai-backdrop",onMouseDown:G=>{G.target===G.currentTarget&&(URL.revokeObjectURL(p),y(""))},children:e.jsxs("section",{className:"verixo-ai-panel verixo-ai-pdf-panel",role:"dialog","aria-modal":"true","aria-label":"VERIXO AI PDF Preview",children:[e.jsxs("header",{className:"verixo-ai-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"VERIXO AI Report Preview"}),e.jsxs("small",{children:[Uv[b]," · PDF"]})]}),e.jsx("button",{type:"button",onClick:()=>{URL.revokeObjectURL(p),y("")},"aria-label":"Close PDF Preview",children:e.jsx(ja,{size:19})})]}),e.jsx("iframe",{title:"VERIXO AI PDF Preview",src:p,style:{width:"100%",height:"72vh",border:0}}),e.jsx("div",{className:"verixo-ai-report-actions",style:{padding:"12px"},children:e.jsxs("a",{className:"verixo-ai-reset",href:p,download:`VERIXO_AI_${b}_${new Date().toISOString().slice(0,10)}.pdf`,children:[e.jsx(Mi,{size:15}),"Download PDF"]})})]})}),a&&e.jsx("div",{className:"verixo-ai-backdrop",onMouseDown:G=>{G.target===G.currentTarget&&s(!1)},children:e.jsxs("section",{className:"verixo-ai-panel",role:"dialog","aria-modal":"true","aria-label":"VERIXO AI Assistant",children:[e.jsxs("header",{className:"verixo-ai-head",children:[e.jsx("div",{className:"verixo-ai-mark",children:e.jsx(Y0,{size:20})}),e.jsxs("div",{children:[e.jsx("strong",{children:"VERIXO AI Assistant"}),e.jsxs("small",{children:[Uv[b]," context · Read-only"]})]}),e.jsx("button",{type:"button",onClick:()=>s(!1),"aria-label":"Close AI Assistant",children:e.jsx(ja,{size:19})})]}),e.jsx("div",{className:"verixo-ai-safety",children:"AI can explain, summarize and analyze authorized context. It cannot post, approve, delete or change ERP data in this release."}),e.jsxs("div",{className:"verixo-ai-chat",children:[!f.length&&e.jsxs("div",{className:"verixo-ai-welcome",children:[e.jsx(Y0,{size:28}),e.jsx("h3",{children:"How can I help?"}),e.jsx("p",{children:"Ask in Bangla or English. The assistant automatically uses the current VERIXO module context and your authenticated ERP identity."})]}),f.map((G,z)=>e.jsxs("div",{className:`verixo-ai-message ${G.role}`,children:[e.jsx("b",{children:G.role==="assistant"?"VERIXO AI":"You"}),e.jsx("p",{children:C(G.content)}),G.role==="assistant"&&G.pdfReady&&e.jsxs("div",{className:"verixo-ai-report-actions",children:[e.jsxs("button",{type:"button",className:"verixo-ai-reset",onClick:()=>J(G.content),children:[e.jsx(ui,{size:15}),"View PDF"]}),e.jsxs("button",{type:"button",className:"verixo-ai-reset",onClick:()=>_(G.content),children:[e.jsx(Mi,{size:15}),"Download PDF"]})]})]},`${G.role}-${z}`)),l&&e.jsxs("div",{className:"verixo-ai-thinking",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})," Thinkingâ¦"]})]}),d&&e.jsx("div",{className:"verixo-ai-error",children:d}),e.jsxs("form",{className:"verixo-ai-compose",onSubmit:T,children:[e.jsx("textarea",{value:i,onChange:G=>c(G.target.value),placeholder:"Ask VERIXO AI in Bangla or Englishâ¦",rows:3,maxLength:4e3,onKeyDown:G=>{var z;G.key==="Enter"&&!G.shiftKey&&(G.preventDefault(),(z=G.currentTarget.form)==null||z.requestSubmit())}}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"verixo-ai-reset",onClick:R,disabled:l||!f.length&&!i,children:[e.jsx(Id,{size:16}),"New chat"]}),e.jsxs("button",{type:"submit",className:"verixo-ai-send",disabled:l||!i.trim(),children:[e.jsx(Zw,{size:16}),l?"Workingâ¦":"Send"]})]})]}),e.jsxs("footer",{children:["Company: ",t.companyId," · Context: ",Uv[b]," · AI Brain v1.9"]})]})})]})}const v_={mtdSales:0,mtdPurchase:0,supplierPayable:0,payableReviewed:0,openCheques:0,dishonoured:0,
3968crmOpen:0,crmOverdue:0,pipelineValue:0},mu=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`,b_=t=>String((t==null?void 0:t.saleDate)||(t==null?void 0:t.purchaseDate)||(t==null?void 0:t.invoiceDate)||(t==null?void 0:t.date)||"");function z7({profile:t,summary:n,selectedBranchId:a,branches:s,onNavigate:i}){const[c,l]=x.useState(v_),[m,d]=x.useState(!0),u=x.useMemo(()=>s.filter(b=>b.active!==!1&&!["all","all_branches","all-branches"].includes(String(b.id||"").toLowerCase())),[s]),f=x.useMemo(()=>new Set(s.map(b=>b.id)),[s]),g=(b,N)=>N==="all"||!(b!=null&&b.branchId)||b.branchId===N?!0:u.length===1&&u[0].id===N&&!f.has(String(b.branchId));x.useEffect(()=>{let b=!0;return(async()=>{d(!0);try{const N=["historicalSales","historicalPurchases","chequeManagement","crmPipeline"],w=await Promise.all(N.map(D=>mn(re(ie,`${D}/${t.companyId}`))));if(!b)return;const[C,R,I,_]=w.map(D=>Object.values(D.val()||{})),J=new Date().toISOString().slice(0,7),T=new Date().toISOString().slice(0,10),G=C.filter(D=>g(D,a)&&!D.cancelled),z=R.filter(D=>g(D,a)&&!D.cancelled),H=I.filter(D=>g(D,a)),K=_.filter(D=>g(D,a)),L=z.filter(D=>{var M;return Number.isFinite(Number((M=D==null?void 0:D.paymentReview)==null?void 0:M.payableAmount))});l({mtdSales:G.filter(D=>b_(D).startsWith(J)).reduce((D,M)=>D+Number(M.grandTotal||M.totalAmount||0),0),mtdPurchase:z.filter(D=>b_(D).startsWith(J)).reduce((D,M)=>D+Number(M.totalAmount||M.grandTotal||0),0),supplierPayable:L.reduce((D,M)=>D+Math.max(0,Number(M.paymentReview.payableAmount||0)),0),payableReviewed:L.length,openCheques:H.filter(D=>!["cleared","cancelled","replaced"].includes(String(D.status))).length,dishonoured:H.filter(D=>["bounced","dishonoured"].includes(String(D.status))).length,crmOpen:K.filter(D=>!["won","lost"].includes(String(D.stage))).length,crmOverdue:K.filter(D=>!["won","lost"].includes(String(D.stage))&&D.nextFollowUp&&String(D.nextFollowUp)<T).length,pipelineValue:K.filter(D=>!["won","lost"].includes(String(D.stage))).reduce((D,M)=>D+Number(M.value||0),0)})}catch(N){console.warn("Top Management snapshot failed",N),b&&l(v_)}finally{b&&d(!1)}})(),()=>{b=!1}},[t.companyId,a,u,f]);const p=x.useMemo(()=>[{label:"Customer receivable",value:mu(Number(n.totalDue||0)),page:"financeDueReport",warn:Number(n.totalDue||0)>0},{label:"Dishonoured cheques",value:String(c.dishonoured),page:"chequeManagement",warn:c.dishonoured>0},{label:"Overdue CRM follow-ups",value:String(c.crmOverdue),page:"crmWorkspace",warn:c.crmOverdue>0},{label:"Pending service jobs",value:String(Number(n.pendingJobs||0)),page:"serviceJobs",warn:Number(n.pendingJobs||0)>0}],[n.totalDue,n.pendingJobs,c]),y=[["MTD Sales",mu(c.mtdSales),"Historical/live posted sales available to dashboard","salesDatewiseReport",xp],["MTD Purchase",mu(c.mtdPurchase),"Purchase value this month","purchaseDatewiseReport",PD],["Today Collection",mu(Number(n.todayCollection||0)),`MTD ${mu(Number(n.monthlyCollection||0))}`,"collections",Ll],["Customer Receivable",mu(Number(n.totalDue||0)),"Outstanding invoice due","financeDueReport",RD],["Confirmed Supplier Payable",mu(c.supplierPayable),`${c.payableReviewed} reviewed purchase bill(s)`,"financeSupplierPayableReport",Nd],["Open Cheques",String(c.openCheques),c.dishonoured?`${c.dishonoured} dishonoured · attention required`:"Cheque lifecycle control","chequeManagement",Gw],["CRM Pipeline",mu(c.pipelineValue),`${c.crmOpen} open · ${c.crmOverdue} overdue follow-up`,"crmWorkspace",Mc],["Service Workload",String(Number(n.pendingJobs||0)),`${Number(n.readyForDelivery||0)} ready for delivery`,"serviceJobs",Go]];return e.jsxs("div",{className:"tm-dashboard",children:[e.jsxs("div",{className:"page-heading enterprise-heading tm-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"EXECUTIVE CONTROL CENTER"}),e.jsx("h2",{children:"Top Management Dashboard"}),e.jsxs("p",{children:["Company-wide commercial, finance, CRM and service overview · ",a==="all"?"All Branches":"Selected Branch"]})]}),e.jsxs("div",{className:"heading-actions",children:[e.jsx("button",{className:"secondary-action",onClick:()=>i("financeReports"),children:"Financial Reports"}),e.jsx("button",{className:"primary-action",onClick:()=>i("dayBookReport"),children:"Day Book"})]})]}),e.jsx("div",{className:"tm-kpi-grid",children:y.map(([b,N,w,C,R])=>e.jsxs("button",{type:"button",className:"tm-kpi-card",onClick:()=>i(C),children:[e.jsx("span",{className:"tm-kpi-icon",children:e.jsx(R,{size:19})}),e.jsx("small",{children:b}),e.jsx("strong",{children:m?"â¦":N}),e.jsx("span",{children:w})]},b))}),e.jsxs("div",{className:"tm-lower-grid",children:[e.jsxs("section",{className:"panel tm-alert-panel",children:[e.jsxs("div",{className:"panel-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Management Attention"}),e.jsx("p",{children:"Items that may require a management decision"})]}),e.jsx(qu,{size:20})]}),e.jsx("div",{className:"tm-alert-list",children:p.map(b=>e.jsxs("button",{onClick:()=>i(b.page),children:[e.jsxs("span",{children:[e.jsx("i",{className:b.warn?"warn":"ok"}),b.label]}),e.jsx("strong",{children:b.value})]},b.label))})]}),e.jsxs("section",{className:"panel",children:[e.jsx("div",{className:"panel-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Executive Shortcuts"}),e.jsx("p",{children:"Open the underlying module; dashboard never posts transactions"})]})}),e.jsxs("div",{className:"tm-shortcuts",children:[e.jsx("button",{onClick:()=>
3968i("crmWorkspace"),children:"CRM & Follow-up"}),e.jsx("button",{onClick:()=>i("chequeManagement"),children:"Cheque Control"}),e.jsx("button",{onClick:()=>i("stockReport"),children:"Stock Report"}),e.jsx("button",{onClick:()=>i("financeSupplierPayableReport"),children:"Supplier Payable"}),e.jsx("button",{onClick:()=>i("salesDatewiseReport"),children:"Sales Report"}),e.jsx("button",{onClick:()=>i("serviceJobs"),children:"Service Operations"})]})]})]}),e.jsx("p",{className:"tm-footnote",children:"Figures are read from existing VERIXO records only. Supplier Payable intentionally totals only purchase bills with a confirmed payment review; missing accounting values are not guessed."})]})}const BE=["Management","Administration","Service","Sales","Accounts","Store","HR","Delivery","Support","Marketing"],FE=["Owner","Managing Director","Chief Executive Officer","General Manager","Manager","Assistant Manager","Supervisor","Senior Executive","Executive","Service Engineer","Senior Technician","Technician","Junior Technician","Sales Manager","Sales Executive","Accounts Manager","Accounts Executive","Store Manager","Store Keeper","Delivery Executive","Receptionist","HR Executive","Office Assistant","Driver","Office Boy"];function x_(t,n,a){const s=new Map;for(const i of t)s.set(i.trim().toLowerCase(),i.trim());for(const i of n)!i.active||!i.name.trim()||s.set(i.name.trim().toLowerCase(),i.name.trim());return a!=null&&a.trim()&&s.set(a.trim().toLowerCase(),a.trim()),[...s.values()].sort((i,c)=>i.localeCompare(c))}const q7=["NID / Passport","Employee Photo","CV / Resume","Appointment Letter","Educational Certificate","Experience Certificate","Contract / Agreement","Other Document"],j_=[{value:"technician",label:"Technician"},{value:"sales",label:"Sales"},{value:"accounts",label:"Accounts"},{value:"admin",label:"Admin"},{value:"store",label:"Store"},{value:"delivery",label:"Delivery"},{value:"hr",label:"HR"},{value:"manager",label:"Manager"}],V7=["Desktop","Laptop","Printer","UPS","Networking","CCTV","Software","Windows Installation","New PC Assembly","All-Rounder"],Xm=[["documentsReceived","Employee Documents Received"],["identityDocument","NID / Passport Copy"],["appointmentLetter","Appointment Letter Issued"],["bankInformation","Bank Information Completed"],["reportingManager","Reporting Manager Assigned"],["attendanceEnrolled","Attendance / Biometric Enrolled"],["userAccount","VERIXO User Account Created"]],Zm=[["handoverCompleted","Work Handover Completed"],["companyAssetsReturned","Company Assets Returned"],["accountsClearance","Accounts / Advance Clearance"],["attendancePayrollClearance","Attendance / Payroll Clearance"],["userAccessDisabled","User Access Disabled"]];function Bb(t){return Object.fromEntries(t.map(([n])=>[n,!1]))}const w_=(t="")=>({branchId:t,employeeId:"",name:"",phone:"",email:"",department:"",designation:"",roles:[],technicianSkills:[],joiningDate:"",employmentStatus:"probation",probationEndDate:"",confirmationDate:"",lastWorkingDate:"",exitReason:"",exitNotes:"",confirmationRemarks:"",onboardingChecklist:Bb(Xm),offboardingChecklist:Bb(Zm),documents:[],reportingManagerId:"",reportingManagerUserUid:"",bankName:"",bankAccount:"",bankAccountHolder:"",shiftId:"",shiftEffectiveFrom:new Date().toISOString().slice(0,10),notes:"",active:!0});function N_(t){const n=(t||"").trim(),a=n.match(/\d+/);return{numeric:a?Number(a[0]):null,text:n.toLowerCase()}}function zv(t,n){const a=N_(t.employeeId),s=N_(n.employeeId);if(a.numeric!==null&&s.numeric!==null){const c=a.numeric-s.numeric;if(c!==0)return c}if(a.numeric!==null)return-1;if(s.numeric!==null)return 1;const i=a.text.localeCompare(s.text,void 0,{numeric:!0,sensitivity:"base"});return i!==0?i:t.name.localeCompare(n.name,void 0,{sensitivity:"base"})}function H7({profile:t,branches:n,selectedBranchId:a}){var qe;const s=a!=="all"?a:t.branchId||((qe=n.find(se=>se.active))==null?void 0:qe.id)||"",[i,c]=x.useState([]),[l,m]=x.useState([]),[d,u]=x.useState([]),[f,g]=x.useState([]),[p,y]=x.useState([]),[b,N]=x.useState([]),[w,C]=x.useState([]),[R,I]=x.useState(""),[_,J]=x.useState("all"),[T,G]=x.use
3968State(w_(s)),[z,H]=x.useState(null),[K,L]=x.useState(null),[D,M]=x.useState(!1),[Z,fe]=x.useState(!1),[q,ne]=x.useState([]),ae=["super_admin","owner","branch_manager"].includes(t.role);x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),se=>{if(!se.exists()){c([]);return}const pe=se.val();c(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me,roles:Me.roles||[],technicianSkills:Me.technicianSkills||[],source:"employee"})).sort(zv))}),[t.companyId]),x.useEffect(()=>qt(Vl(re(ie,"users"),ql("companyId"),Dh(t.companyId)),se=>{if(!se.exists()){ne([]);return}const pe=se.val();ne(Object.entries(pe).map(([Se,Me])=>({uid:Se,...Me})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`organizationSetup/${t.companyId}/departments`),se=>{if(!se.exists()){m([]);return}const pe=se.val();m(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`organizationSetup/${t.companyId}/designations`),se=>{if(!se.exists()){u([]);return}const pe=se.val();u(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`technicians/${t.companyId}`),se=>{if(!se.exists()){g([]);return}const pe=se.val();g(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`attendanceShifts/${t.companyId}`),se=>{if(!se.exists()){C([]);return}const pe=se.val();C(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me})).filter(Se=>Se.active!==!1).sort((Se,Me)=>Se.name.localeCompare(Me.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`serviceJobs/${t.companyId}`),se=>{if(!se.exists()){y([]);return}const pe=se.val();y(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`customers/${t.companyId}`),se=>{if(!se.exists()){N([]);return}const pe=se.val();N(Object.entries(pe).map(([Se,Me])=>({id:Se,...Me})))}),[t.companyId]);const Y=x.useMemo(()=>{const se=new Set(i.map(Me=>Me.id)),pe=new Set(i.map(Me=>Me.name.trim().toLowerCase())),Se=f.filter(Me=>!se.has(Me.id)&&!pe.has(Me.name.trim().toLowerCase())).map(Me=>({id:Me.id,companyId:Me.companyId,branchId:Me.branchId,employeeId:Me.employeeId||"",name:Me.name,phone:Me.phone,email:Me.email||"",department:"Service",designation:"Technician",roles:["technician"],technicianSkills:Me.specialisations||[],joiningDate:Me.joiningDate||"",notes:Me.notes||"",active:Me.active,createdAt:Me.createdAt,updatedAt:Me.updatedAt,source:"legacy_technician"}));return[...i,...Se].sort(zv)},[i,f]),je=x.useMemo(()=>x_(BE,l,T.department),[l,T.department]),V=x.useMemo(()=>x_(FE,d,T.designation),[d,T.designation]),$=x.useMemo(()=>{const se=R.trim().toLowerCase();return Y.filter(pe=>{if(a!=="all"&&pe.branchId!==a||_!=="all"&&!pe.roles.includes(_))return!1;if(!se)return!0;const Se=n.find(Me=>Me.id===pe.branchId);return[pe.employeeId,pe.name,pe.phone,pe.email,pe.department,pe.designation,pe.roles.join(" "),pe.technicianSkills.join(" "),Se==null?void 0:Se.name].filter(Boolean).some(Me=>String(Me).toLowerCase().includes(se))}).sort(zv)},[Y,a,_,R,n]),F=se=>p.filter(pe=>pe.assignedTechnicianId===se.id||!pe.assignedTechnicianId&&pe.assignedTechnician===se.name).sort((pe,Se)=>Se.createdAt-pe.createdAt),P=se=>{const pe=F(se);return{open:pe.filter(Se=>!["delivered","closed","cancelled"].includes(Se.status)).length,completed:pe.filter(Se=>["delivered","closed"].includes(Se.status)).length}},ue=()=>{H(null),G(w_(s)),M(!0)},me=se=>{H(se),G({branchId:se.branchId,employeeId:se.employeeId||"",name:se.name,phone:se.phone,email:se.email||"",department:se.department||"",designation:se.designation||"",roles:se.roles||[],technicianSkills:se.technicianSkills||[],joiningDate:se.joiningDate||"",employmentStatus:se.employmentStatus||(se.active?"confirmed":"resigned"),probationEndDate:se.probationEndDate||"",confirmationDate:se.confirmationDate||"",lastWorkingDate:se.lastWorkingDate||"",exitReason:se.exitReason||"",exitNotes:se.exitNotes||"",confirmationRemarks:se.confirmationRemarks||"",onboardingChecklist:{...Bb(Xm),...se.onboardingChecklist||{}},offboardingChecklist:{...Bb(Zm),...se.offboardingChecklist||{}},documents:se.documents||[],reportingManagerId:se.reportingManagerId||"",reportingManagerUserUid:se.reportingManagerUserUid||"",bankName:se.bankName||"",bankAccount:se.bankAccount||"",bankAccountHolder:se.bankAccountHolder||se.name||"",shiftId:se.shiftId||"",shiftEffectiveFrom:se.shiftEffectiveFrom||new Date().toISOString().slice(0,10),notes:se.n
3968otes||"",active:se.active}),M(!0)};x.useEffect(()=>{const se=window.sessionStorage.getItem("verixo.openEmployeeId");if(!se||!i.length)return;const pe=i.find(Se=>Se.id===se);pe&&(window.sessionStorage.removeItem("verixo.openEmployeeId"),me(pe))},[i]);const ge=se=>{G(pe=>{const Se=pe.roles.includes(se)?pe.roles.filter(Me=>Me!==se):[...pe.roles,se];return{...pe,roles:Se,technicianSkills:Se.includes("technician")?pe.technicianSkills:[]}})},de=se=>{G(pe=>({...pe,technicianSkills:pe.technicianSkills.includes(se)?pe.technicianSkills.filter(Se=>Se!==se):[...pe.technicianSkills,se]}))},Pe=Xm.every(([se])=>!!T.onboardingChecklist[se]),Re=Zm.every(([se])=>!!T.offboardingChecklist[se]),Ee=se=>{G(pe=>({...pe,onboardingChecklist:{...pe.onboardingChecklist,[se]:!pe.onboardingChecklist[se]}}))},Be=se=>{G(pe=>({...pe,offboardingChecklist:{...pe.offboardingChecklist,[se]:!pe.offboardingChecklist[se]}}))},We=async se=>{if(se.preventDefault(),!T.branchId||!T.name.trim()){window.alert("Branch and employee name are required.");return}if(!T.roles.length){window.alert("At least one employee role select à¦à¦°à§à¦¨à¥¤");return}if(["resigned","terminated"].includes(T.employmentStatus)&&!Re){window.alert("Final Exit cannot be completed until all Offboarding / Clearance checklist items are completed.");return}if(T.employmentStatus==="confirmed"&&!T.confirmationDate){window.alert("Confirmation Date is required when employee stage is Confirmed.");return}fe(!0);try{const pe=Date.now(),Se=z?re(ie,`employees/${t.companyId}/${z.id}`):Ta(re(ie,`employees/${t.companyId}`)),Me=(z==null?void 0:z.id)||Se.key||"",ot=i.find(De=>De.id===T.reportingManagerId),wt=q.find(De=>De.uid===T.reportingManagerUserUid);if(T.reportingManagerId&&T.reportingManagerId===Me){window.alert("An employee cannot be their own Reporting Manager."),fe(!1);return}const ct={id:Me,companyId:t.companyId,branchId:T.branchId,employeeId:T.employeeId.trim(),name:T.name.trim(),phone:T.phone.trim(),email:T.email.trim(),department:T.department.trim(),designation:T.designation.trim(),roles:T.roles,technicianSkills:T.roles.includes("technician")?T.technicianSkills:[],joiningDate:T.joiningDate,employmentStatus:T.employmentStatus,probationEndDate:T.probationEndDate,confirmationDate:T.confirmationDate,lastWorkingDate:T.lastWorkingDate,exitReason:T.exitReason.trim(),exitNotes:T.exitNotes.trim(),confirmationRemarks:T.confirmationRemarks.trim(),onboardingChecklist:T.onboardingChecklist,offboardingChecklist:T.offboardingChecklist,documents:T.documents,lifecycleUpdatedAt:pe,lifecycleUpdatedByUid:t.uid,lifecycleUpdatedByName:t.name,reportingManagerId:T.reportingManagerId,reportingManagerName:(ot==null?void 0:ot.name)||(wt==null?void 0:wt.name)||"",reportingManagerUserUid:T.reportingManagerUserUid,reportingManagerUserRole:(wt==null?void 0:wt.role)||"",bankName:T.bankName.trim(),bankAccount:T.bankAccount.trim(),bankAccountHolder:T.bankAccountHolder.trim()||T.name.trim(),shiftId:T.shiftId,shiftEffectiveFrom:T.shiftEffectiveFrom,notes:T.notes.trim(),active:["resigned","terminated"].includes(T.employmentStatus)?!1:T.active,createdAt:(z==null?void 0:z.createdAt)||pe,updatedAt:pe};if(z?await yn(Se,ct):await Pn(Se,ct),(!z||z.shiftId!==T.shiftId||z.shiftEffectiveFrom!==T.shiftEffectiveFrom)&&T.shiftId){const De=Ta(re(ie,`employeeShiftAssignments/${t.companyId}/${Me}`));await Pn(De,{shiftId:T.shiftId,effectiveFrom:T.shiftEffectiveFrom||new Date().toISOString().slice(0,10),branchId:T.branchId,createdAt:pe,createdByUid:t.uid,createdByName:t.name})}(z==null?void 0:z.source)==="legacy_technician"&&await Ao(re(ie,`technicians/${t.companyId}/${z.id}`)),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:z?"employee.updated":"employee.created",entityType:"employee",entityId:Me,branchId:T.branchId,summary:`${z?"Updated":"Created"} employee ${T.name.trim()}`,metadata:{employeeId:T.employeeId.trim(),roles:T.roles,shiftId:T.shiftId,shiftEffectiveFrom:T.shiftEffectiveFrom,migratedFromTechnician:(z==null?void 0:z.source)==="legacy_technician"}}),M(!1)}catch(pe){console.error("Employee save failed:",pe);const Se=pe instanceof Error?pe.message:String(pe);window.alert(`Employee save à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤ 3969 3970${Se}`)}finally{fe(!1)}},it=se=>q.find(pe=>pe.employeeId===se.id)||q.find(pe=>!!se.email&&pe.email.trim().toLowerCase()===String(se.email||"").trim().toLowerCase()),_e=async se=>{if(!["super_admin","owner","admin"].includes(t.role)){window.alert("Owner/Admin access is required to reset a login password.");return}const pe=it(se);if(!pe){window.alert(`${se.name}-à¦à¦° সাথৠà¦à§à¦¨à§ VERIXO Login User linked পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ à¦à¦à§ User & Role Permissions থà§à¦à§ Login User তà§à¦°à¦¿/link à¦à¦°à§à¦¨à¥¤`);return}if(pe.uid===t.uid){window.alert("নিà¦à§à¦° password à¦à¦à¦¾à¦¨à§ reset à¦à¦°à¦¾ যাবৠনা। Sidebar-à¦à¦° Password o
3970ption বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤");return}if(pe.role==="super_admin"&&t.role!=="super_admin"){window.alert("Only Super Admin can reset a Super Admin account.");return}if(pe.role==="owner"&&t.role==="admin"){window.alert("Admin cannot reset an Owner account.");return}if(window.confirm(`${se.name}-à¦à¦° login email-ঠFirebase secure password reset link পাঠাবà§à¦¨? 3971 3972Login: ${pe.email} 3973 3974Firebase Free/Spark plan-ঠঠনà§à¦¯ user-à¦à¦° password browser থà§à¦à§ সরাসরি replace à¦à¦°à¦¾ নিরাপদ নà§à¥¤ Reset link বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§ user নতà§à¦¨ password set à¦à¦°à¦¬à§à¥¤`)){fe(!0);try{await a1(Ti,pe.email);const Se=Date.now();await yn(re(ie,`users/${pe.uid}`),{forcePasswordChange:!0,passwordResetAt:Se,passwordResetByUid:t.uid,passwordResetByName:t.name,updatedAt:Se}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"user.password_reset_sent",entityType:"user",entityId:pe.uid,branchId:se.branchId,summary:`Sent secure password reset email to ${se.name}`}),window.alert(`Password reset link পাঠানৠহà§à§à¦à§à¥¤ 3975 3976Employee: ${se.name} 3977Email: ${pe.email} 3978 3979User email-à¦à¦° link থà§à¦à§ নতà§à¦¨ password set à¦à¦°à¦¬à§à¥¤ তারপর login à¦à¦°à¦²à§ VERIXO security flow পà§à¦°à§à§à¦à¦¨ হলৠpassword confirmation/change সমà§à¦ªà¦¨à§à¦¨ à¦à¦°à¦¾à¦¬à§à¥¤`)}catch(Se){console.error("Password reset email failed:",Se);const Me=Se instanceof Error?Se.message:String(Se),ot=Me.includes("auth/invalid-email")?"Login email address সঠিঠনà§à¥¤":Me.includes("auth/too-many-requests")?"ঠনà§à¦à¦¬à¦¾à¦° reset à¦à§à¦·à§à¦à¦¾ হà§à§à¦à§à¥¤ à¦à¦¿à¦à§à¦à§à¦·à¦£ পরৠà¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤":Me;window.alert(`Password reset link পাঠানৠযাà§à¦¨à¦¿. 3980 3981${ot}`)}finally{fe(!1)}}},ee=async se=>{if(!ae||!window.confirm(`${se.name} à¦à§ delete à¦à¦°à¦¬à§à¦¨? 3982 3983Existing Service Job history ঠপরিবরà§à¦¤à¦¿à¦¤ থাà¦à¦¬à§à¥¤`))return;const Se=se.source==="legacy_technician"?`technicians/${t.companyId}/${se.id}`:`employees/${t.companyId}/${se.id}`;await Ao(re(ie,Se)),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"employee.deleted",entityType:"employee",entityId:se.id,branchId:se.branchId,summary:`Deleted employee ${se.name}`})};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-header employee-page-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR"}),e.jsx("h1",{children:"Employees"}),e.jsx("p",{children:"Employee master, role à¦à¦¬à¦ technician skill à¦à¦ à¦à¦¾à§à¦à¦¾ থà§à¦à§ manage à¦à¦°à§à¦¨à¥¤"})]}),ae&&e.jsxs("button",{className:"primary-action-button",onClick:ue,children:[e.jsx(as,{size:18})," Add Employee"]})]}),e.jsxs("section",{className:"employee-summary-grid",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Total Employees"}),e.jsx("strong",{children:$.length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Active"}),e.jsx("strong",{children:$.filter(se=>se.active).length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Technicians"}),e.jsx("strong",{children:$.filter(se=>se.roles.includes("technician")).length})]})]}),e.jsxs("section",{className:"employee-data-card",children:[e.jsxs("div",{className:"employee-toolbar",children:[e.jsxs("div",{children:[e.jsx(xr,{size:18}),e.jsx("input",{value:R,onChange:se=>I(se.target.value),placeholder:"Search employee, ID, phone, role or branch"})]}),e.jsxs("select",{value:_,onChange:se=>J(se.target.value),children:[e.jsx("option",{value:"all",children:"All Roles"}),j_.map(se=>e.jsx("option",{value:se.value,children:se.label},se.value))]})]}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Department / Designation"}),e.jsx("th",{children:"Contact"}),e.jsx("th",{children:"Roles"}),e.jsx("th",{children:"Open Jobs"}),e.jsx("th",{children:"Completed"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Actions"})]})}),e.jsxs("tbody",{children:[$.map(se=>{var Se;const pe=P(se);return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"employee-name-cell",children:[e.jsx("strong",{children:se.name}),e.jsxs("span",{className:"employee-id-badge",children:["ID: ",se.employeeId||"Not assigned"]}),se.source==="legacy_technician"&&e.jsx("small",{children:"Legacy Technician"})]})}),e.jsx("td",{children:((Se=n.find(Me=>Me.id===se.branchId))==null?void 0:Se.name)||"Unknown"}),e.jsxs("td",{children:[e.jsx("strong",{children:se.department||"â"}),e.jsx("small",{children:se.designation||"â"})]}
3983),e.jsxs("td",{children:[e.jsx("strong",{children:se.phone||"Not provided"}),e.jsx("small",{children:se.email||""})]}),e.jsx("td",{children:e.jsx("div",{className:"employee-role-list",children:se.roles.map(Me=>e.jsx("span",{children:Me},Me))})}),e.jsx("td",{children:e.jsx("strong",{className:"workload-number",children:pe.open})}),e.jsx("td",{children:pe.completed}),e.jsx("td",{children:e.jsx("span",{className:`employee-status ${se.active?"active":"inactive"}`,children:se.active?"Active":"Inactive"})}),e.jsx("td",{children:e.jsxs("div",{className:"action-buttons",children:[e.jsx("button",{onClick:()=>L(se),title:"View",children:e.jsx(ui,{size:17})}),ae&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>me(se),title:"Edit",children:e.jsx(Zi,{size:17})}),["super_admin","owner","admin"].includes(t.role)&&e.jsx("button",{onClick:()=>void _e(se),title:it(se)?"Send secure password reset email":"No linked login user",className:it(se)?"employee-password-action":"employee-password-action unavailable",children:e.jsx(Gh,{size:17})}),e.jsx("button",{onClick:()=>void ee(se),title:"Delete",children:e.jsx(po,{size:17})})]})]})})]},`${se.source}-${se.id}`)}),!$.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"empty-table",children:"No employees found."})})]})]})})]}),D&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>M(!1),children:e.jsxs("section",{className:"modal employee-modal",onMouseDown:se=>se.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR Employee Master"}),e.jsx("h2",{children:z?"Edit Employee":"Add Employee"})]}),e.jsx("button",{onClick:()=>M(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:We,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Employee Name *",e.jsx("input",{value:T.name,onChange:se=>G({...T,name:se.target.value}),required:!0})]}),e.jsxs("label",{children:["Employee ID",e.jsx("input",{value:T.employeeId,onChange:se=>G({...T,employeeId:se.target.value}),placeholder:"Existing manual employee ID"})]}),e.jsxs("label",{children:["Mobile Number",e.jsx("input",{type:"tel",value:T.phone,onChange:se=>G({...T,phone:se.target.value}),placeholder:"Optional"}),e.jsx("small",{className:"field-help",children:"Mobile number à¦à¦¾à¦¨à¦¾ না থাà¦à¦²à§ পরৠEmployee Profile থà§à¦à§ যà§à¦ à¦à¦°à¦¾ যাবà§à¥¤"})]}),e.jsxs("label",{children:["Email",e.jsx("input",{type:"email",value:T.email,onChange:se=>G({...T,email:se.target.value})})]}),e.jsxs("label",{children:["Branch *",e.jsxs("select",{value:T.branchId,onChange:se=>G({...T,branchId:se.target.value}),required:!0,children:[e.jsx("option",{value:"",children:"Select branch"}),n.filter(se=>se.active).map(se=>e.jsx("option",{value:se.id,children:se.name},se.id))]})]}),e.jsxs("label",{children:["Department",e.jsxs("select",{value:T.department,onChange:se=>G({...T,department:se.target.value}),children:[e.jsx("option",{value:"",children:"Select department"}),je.map(se=>e.jsx("option",{value:se,children:se},se))]})]}),e.jsxs("label",{children:["Designation",e.jsxs("select",{value:T.designation,onChange:se=>G({...T,designation:se.target.value}),children:[e.jsx("option",{value:"",children:"Select designation"}),V.map(se=>e.jsx("option",{value:se,children:se},se))]}),e.jsx("small",{className:"field-help",children:"নতà§à¦¨ designation যà§à¦ à¦à¦°à¦¤à§ System â Organization Setup বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤"})]}),e.jsxs("label",{children:["Joining Date",e.jsx("input",{type:"date",value:T.joiningDate,onChange:se=>G({...T,joiningDate:se.target.value})})]}),e.jsxs("label",{children:["Employment Stage",e.jsxs("select",{value:T.employmentStatus,onChange:se=>G({...T,employmentStatus:se.target.value,active:["resigned","terminated"].includes(se.target.value)?!1:T.active}),children:[e.jsx("option",{value:"probation",children:"Probation / Onboarding"}),e.jsx("option",{value:"confirmed",children:"Confirmed"}),e.jsx("option",{value:"notice_period",children:"Notice Period / Offboarding"}),e.jsx("option",{value:"resigned",children:"Resigned"}),e.jsx("option",{value:"terminated",children:"Terminated"})]}),e.jsx("small",{className:"field-help",children:"Employee lifecycle status. Resigned/Terminated automatically makes the employee inactive."})]}),e.jsxs("label",{children:["Probation End Date",e.jsx("input",{type:"date",value:T.probationEndDate,onChange:se=>G({...T,probationEndDate:se.target.value})})]}),e.jsxs("label",{children:["Confirmation Date",e.jsx("input",{type:"date",value:T.confirmationDate,onChange:se=>G({...T,confirmationDate:se.target.value})})]}),e.jsxs("label",{children:["Last Working Date",e.jsx("input",{type:"date",value:T.lastWorkingDate,onChange:se=>G({...T,lastWorkingDate:se.target.value})})]}),["notice_period","resigned","terminated"].includes(T.employmentStatus)&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Exit Reason",e.jsx("input",{value:T.exitReason,onChange:se=>G({...T,exitReason:se.target.value}),placeholder:"Resignation, termination, retirement, etc."})]}),e.jsxs("label",{className:"full-field",children:["Exit / Handover Notes",e.jsx("textarea",{value:T.exitNotes,onChange:se=>G({...T,exitNotes:se.target.value}),placeholder:"Handover, company asset return, clearance or other exit notes"})]})]}),e.jsxs("div",{className:"employee-lifecycle-panel full-field",children:[e.jsxs("div",{className:"employee-lifecycle-heading",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"HR Lifecycle Checklist"}),e.jsx("small",{children:"Complete onboarding, confirmation and exit-control steps from the Employee Profile."})]}),e.jsx("span",{className:`employee-lifecycle-badge ${T.employmentStatus}`,children:T.employmentStatus==="probation"?"Probation / Onboarding":T.employmentStatus==="confirmed"?"Confirmed":T.employmentStatus==="notice_period"?"Notice Period":T.employmentStatus==="resigned"?"Resigned":"Terminated"})]}),["probation","confirmed"].includes(T.employmentStatus)&&e.jsxs("div",{className:"employee-checklist-section",children:[e.jsxs("div",{className:"employee-checklist-title",children:[e.jsx("strong",{children:"Onboarding Checklist"}),e.jsxs("span",{children:[Xm.filter(([se])=>T.onboardingChecklist[se]).length,"/",Xm.length," Complete"]})]}),e.jsx("div",{className:"employee-checklist-grid",children:Xm.map(([se,pe])=>e.jsxs("label",{className:T.onboardingChecklist[se]?"completed":"",children:[e.jsx("input",{type:"checkbox",checked:!!T.onboardingChecklist[se],onChange:()=>Ee(se)}),e.jsx("span",{children:pe})]},se))}),!Pe&&T.employmentStatus==="confirmed"&&e.jsx("small",{className:"employee-lifecycle-warning",children:"Confirmation is allowed, but onboarding checklist is still incomplete."})]}),T.employmentStatus==="confirmed"&&e.jsxs("label",{className:"employee-confirmation-remarks",children:["Confirmation Remarks",e.jsx("textarea",{value:T.confirmationRemarks,onChange:se=>G({...T,confirmationRemarks:se.target.value}),placeholder:"Confirmation decision or HR remarks"})]}),["notice_period","resigned","terminated"].includes(T.employmentStatus)&&e.jsxs("div",{className:"employee-checklist-section offboarding",children:[e.jsxs("div",{className:"employee-checklist-title",children:[e.jsx("strong",{children:"Offboarding / Clearance Checklist"}),e.jsxs("span",{children:[Zm.filter(([se])=>T.offboardingChecklist[se]).length,"/",Zm.length," Complete"]})]}),e.jsx("div",{className:"employee-checklist-grid",children:Zm.map(([se,pe])=>e.jsxs("label",{className:T.offboardingChecklist[se]?"completed":"",children:[e.jsx("input",{type:"checkbox",checked:!!T.offboardingChecklist[se],onChange:()=>Be(se)}),e.jsx("span",{children:pe})]},se))}),["resigned","terminated"].includes(T.employmentStatus)&&!Re&&e.jsx("small",{className:"employee-lifecycle-warning danger",children:"Final Exit is blocked until every clearance item is completed."})]})]}),e.jsxs("div",{className:"employee-documents-panel full-field",children:[e.jsxs("div",{className:"employee-documents-heading",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Employee Documents"}),e.jsx("small",{children:"Maintain employee document references, issue dates and expiry dates from the profile."})]}),e.jsxs("span",{children:[T.documents.length," document(s)"]})]}),e.jsxs("div",{className:"employee-document-add",children:[e.jsx("select",{id:"employee-document-type",defaultValue:"NID / Passport",children:q7.map(se=>e.jsx("option",{children:se},se))}),e.jsx("input",{id:"employee-document-title",placeholder:"Document title / number"}),e.jsx("input",{id:"employee-document-reference",placeholder:"File link / Drive URL / reference"}),e.jsx("input",{id:"employee-document-expiry",type:"date",title:"Expiry date"}),e.jsx("button",{type:"button",onClick:()=>{const se=document.getElementById("employee-document-type"),pe=document.getElementById("employee-document-title"),Se=document.getElementById("employee-document-reference"),Me=document.getElementById("employee-document-expiry"),ot=(pe==null?void 0:pe.value.trim())||"",wt=(Se==null?void 0:Se.value.trim())||"";!ot&&!wt||(G({...T,documents:[...T.documents,{id:`${Date.now()}`,type:(se==null?void 0:se.value)||"Other Document",title:ot||(se==null?void 0:se.value)||"Document",reference:wt,expiryDate:(Me==null?void 0:Me.value)||""}]}),pe&&(pe.value=""),Se&&(Se.value=""),Me&&(Me.value=""))},children:"Add Document"})]}),T.documents.length>0&&e.jsx("div",{className:"employee-document-list",children:T.documents.map(se=>{const pe=!!(se.expiryDate&&se.expiryDate<new Date().toISOString().slice(0,10));return e.jsxs("div",{className:"employee-document-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:se.title}),e.jsxs("small",{children:[se.type,se.expiryDate?` · Expiry ${se.expiryDate}`:""]})]}),pe&&e.jsx("span",{className:"employee-document-expired",children:"Expired"}),se.reference&&e.jsx("button",{type:"button",onClick:()=>window.open(se.reference,"_blank","noopener,noreferrer"),children:"View"}),e.jsx("button",{type:"button",className:"remove",onClick:()=>G({...T,documents:T.documents.filter(Se=>Se.id!==se.id)}),children:"Remove"})]},se.id)})}),e.jsx("small",{className:"employee-document-note",children:"Document references are stored in the employee profile. Use a secure company-controlled file link for confidential files."})]}),e.jsxs("label",{children:["Reporting Manager",e.jsxs("select",{value:T.reportingManagerUserUid?`user:${T.reportingManagerUserUid}`:T.reportingManagerId?`employee:${T.reportingManagerId}`:"",onChange:se=>{const pe=se.target.value;pe.startsWith("user:")?G({...T,reportingManagerId:"",reportingManagerUserUid:pe.slice(5)}):pe.startsWith("employee:")?G({...T,reportingManagerId:pe.slice(9),reportingManagerUserUid:""}):G({...T,reportingManagerId:"",reportingManagerUserUid:""})},children:[e.jsx("option",{value:"",children:"No Reporting Manager / Top Management"}),e.jsx("optgroup",{label:"Company Management",children:q.filter(se=>se.active!==!1&&["owner","super_admin"].includes(se.role)).sort((se,pe)=>se.name.localeCompare(pe.name)).map(se=>e.jsxs("option",{value:`user:${se.uid}`,children:[se.name," (",se.role==="owner"?"Owner":"Super Admin",")"]},se.uid))}),e.jsx("optgroup",{label:"Employees",children:i.filter(se=>se.active!==!1&&se.id!==(z==null?void 0:z.id)).sort(zv).map(se=>e.jsxs("option",{value:`employee:${se.id}`,children:[se.employeeId?`${se.employeeId} - `:"",se.name,se.designation?` (${se.designation})`:""]},se.id))})]}),e.jsx("small",{className:"field-help",children:"Select Owner/Super Admin for CEO or top-level managers, or select an employee for normal reporting lines."})]}),e.jsxs("label",{children:["Salary Bank",e.jsx("input",{value:T.bankName,onChange:se=>G({...T,bankName:se.target.value}),placeholder:"e.g. DBBL / BRAC Bank"})]}),e.jsxs("label",{children:["Salary Account No.",e.jsx("input",{value:T.bankAccount,onChange:se=>G({...T,bankAccount:se.target.value}),placeholder:"Bank account number"})]}),e.jsxs("label",{children:["Account Holder Name",e.jsx("input",{value:T.bankAccountHolder,onChange:se=>G({...T,bankAccountHolder:se.target.value}),placeholder:T.name||"Account holder"}),e.jsx("small",{className:"field-help",children:"Payroll Run à¦à¦¬à¦ Salary PDF-ঠà¦à¦ তথà§à¦¯ বà§à¦¯à¦¬à¦¹à¦¾à¦° হবà§à¥¤"})]}),e.jsxs("label",{children:["Assigned Shift",e.jsxs("select",{value:T.shiftId,onChange:se=>G({...T,shiftId:se.target.value}),children:[e.jsx("option",{value:"",children:"Use Branch Default Shift"}),w.filter(se=>!se.branchId||se.branchId==="all"||se.branchId===T.branchId).map(se=>e.jsxs("option",{value:se.id,children:[se.name," (",se.startTime,"â",se.endTime,")"]},se.id))]}),e.jsx("small",{className:"field-help",children:"নিরà§à¦¦à¦¿à¦·à§à¦ shift assign না à¦à¦°à¦²à§ Branch Default Shift বà§à¦¯à¦¬à¦¹à¦¾à¦° হবà§à¥¤"})]}),e.jsxs("label",{children:["Shift Effective From",e.jsx("input",{type:"date",value:T.shiftEffectiveFrom,onChange:se=>G({...T,shiftEffectiveFrom:se.target.value}),disabled:!T.shiftId}),e.jsx("small",{className:"field-help",children:"Shift change হলৠনতà§à¦¨ effective date দিন। পà§à¦°à§à¦¨à§ assignment history সà¦à¦°à¦à§à¦·à¦¿à¦¤ থাà¦à¦¬à§à¥¤"})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:T.active?"active":"inactive",onChange:se=>G({...T,active:se.target.value==="active"}),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]}),e.jsxs("fieldset",{className:"employee-options full-field",children:[e.jsx("legend",{children:"Employee Roles *"}),e.jsx("div",{children:j_.map(se=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:T.roles.includes(se.value),onChange:()=>ge(se.value)}),e.jsx("span",{children:se.label})]},se.value))})]}),T.roles.includes("technician")&&e.jsxs("fieldset",{className:"employee-options full-field",children:[e.jsx("legend",{children:"Technician Skills"}),e.jsx("div",{children:V7.map(se=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:T.technicianSkills.includes(se),onChange:()=>de(se)}),e.jsx("span",{children:se})]},se))})]}),e.jsxs("label",{className:"full-field",children:["Notes",e.jsx("textarea",{rows:3,value:T.notes,onChange:se=>G({...T,notes:se.target.value})})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary secondary-button",onClick:()=>M(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"vx-button vx-button-primary",disabled:Z,children:[e.jsx(n6,{size:17}),Z?"Saving...":z?"Update Employee":"Save Employee"]})]})]})]})}),K&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>L(null),children:e.jsxs("section",{className:"modal employee-view-modal",onMouseDown:se=>se.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Employee Profile"}),e.jsx("h2",{children:K.name})]}),e.jsx("button",{onClick:()=>L(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"employee-view-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Employee ID"}),e.jsx("strong",{children:K.employeeId||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Phone"}),e.jsx("strong",{children:K.phone})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Department"}),e.jsx("strong",{children:K.department||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Designation"}),e.jsx("strong",{children:K.designation||"â"})]}),e.jsxs("div",{className:"full",children:[e.jsx("span",{children:"Roles"}),e.jsx("strong",{children:K.roles.join(", ")})]}),K.roles.includes("technician")&&e.jsxs("div",{className:"full",children:[e.jsx("span",{children:"Technician Skills"}),e.jsx("strong",{children:K.technicianSkills.join(", ")||"Not set"})]})]}),K.roles.includes("technician")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"employee-workload",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Open Jobs"}),e.jsx("strong",{children:P(K).open})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Completed"}),e.jsx("strong",{children:P(K).completed})]})]}),e.jsxs("section",{className:"employee-job-history",children:[e.jsxs("div",{className:"section-heading-row",children:[e.jsx("h3",{ch
3983ildren:"Assigned Service Jobs"}),e.jsxs("span",{children:[F(K).length," jobs"]})]}),e.jsxs("div",{children:[F(K).slice(0,20).map(se=>{const pe=b.find(Se=>Se.id===se.customerId);return e.jsxs("article",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:se.jobNumber}),e.jsxs("span",{children:[(pe==null?void 0:pe.name)||"Unknown Customer"," ·"," ",se.deviceCategory,se.brand?` â ${se.brand}`:""]})]}),e.jsx("span",{children:se.status.replaceAll("_"," ")})]},se.id)}),!F(K).length&&e.jsx("p",{children:"No assigned service jobs yet."})]})]})]})]})})]})}function W7({profile:t}){const[n,a]=x.useState([]),[s,i]=x.useState([]),[c,l]=x.useState("departments"),[m,d]=x.useState(!1),[u,f]=x.useState(null),[g,p]=x.useState(""),[y,b]=x.useState(!0),[N,w]=x.useState(!1),[C,R]=x.useState(""),[I,_]=x.useState(""),[J,T]=x.useState("");x.useEffect(()=>{let ne=!0;return fc(t.companyId).then(ae=>{ne&&(R(ae.name),_(ae.logoUrl))}).catch(ae=>console.error("Company branding load failed:",ae)),()=>{ne=!1}},[t.companyId]);const G=ne=>{if(!ne)return;if(!ne.type.startsWith("image/")){window.alert("Please select a PNG, JPG or WebP logo.");return}const ae=new FileReader;ae.onload=()=>{const Y=new Image;Y.onload=()=>{const $=Math.min(1,480/Y.width,180/Y.height),F=document.createElement("canvas");F.width=Math.max(1,Math.round(Y.width*$)),F.height=Math.max(1,Math.round(Y.height*$));const P=F.getContext("2d");P&&(P.drawImage(Y,0,0,F.width,F.height),_(F.toDataURL("image/png",.9)),T("Logo ready. Click Save Company Branding."))},Y.src=String(ae.result||"")},ae.readAsDataURL(ne)},z=async()=>{w(!0),T("");try{await u7(t.companyId,I),T("Company logo saved successfully."),window.alert("Company logo saved successfully.")}catch(ne){console.error("Company logo save failed:",ne);const ae=ne instanceof Error?ne.message:"Unknown Firebase error";T(`Logo save failed: ${ae}`),window.alert(`Company logo save à¦à¦°à¦¾ যাà§à¦¨à¦¿: ${ae}`)}finally{w(!1)}},H=["super_admin","owner","branch_manager"].includes(t.role);x.useEffect(()=>qt(re(ie,`organizationSetup/${t.companyId}/departments`),ne=>{if(!ne.exists()){a([]);return}const ae=ne.val();a(Object.entries(ae).map(([Y,je])=>({id:Y,...je})).sort((Y,je)=>Y.name.localeCompare(je.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`organizationSetup/${t.companyId}/designations`),ne=>{if(!ne.exists()){i([]);return}const ae=ne.val();i(Object.entries(ae).map(([Y,je])=>({id:Y,...je})).sort((Y,je)=>Y.name.localeCompare(je.name)))}),[t.companyId]);const K=c==="departments"?n:s,L=c==="departments"?BE:FE,D=x.useMemo(()=>{const ne=new Set(K.map(Y=>Y.name.trim().toLowerCase())),ae=L.filter(Y=>!ne.has(Y.trim().toLowerCase())).map((Y,je)=>({id:`default-${c}-${je}`,name:Y,active:!0,createdAt:0,updatedAt:0}));return[...K,...ae].sort((Y,je)=>Y.name.localeCompare(je.name))},[c,K,L]),M=()=>{f(null),p(""),b(!0),d(!0)},Z=ne=>{f(ne.id.startsWith("default-")?null:ne),p(ne.name),b(ne.active),d(!0)},fe=async ne=>{ne.preventDefault();const ae=g.trim();if(!ae){window.alert("Name is required.");return}if(D.some(je=>je.name.trim().toLowerCase()===ae.toLowerCase()&&je.id!==(u==null?void 0:u.id))){window.alert("à¦à¦ নামà¦à¦¿ à¦à¦¤à¦¿à¦®à¦§à§à¦¯à§ তালিà¦à¦¾à§ à¦à¦à§à¥¤");return}w(!0);try{const je=Date.now(),V=`organizationSetup/${t.companyId}/${c}`,$=u?re(ie,`${V}/${u.id}`):Ta(re(ie,V)),F=(u==null?void 0:u.id)||$.key||"",P={name:ae,active:y,createdAt:(u==null?void 0:u.createdAt)||je,updatedAt:je};u?await yn($,P):await Pn($,{id:F,...P}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"organization.updated",entityType:"organization",entityId:F,summary:`${u?"Updated":"Added"} ${c==="departments"?"department":"designation"} ${ae}`,metadata:{setupType:c,active:y}}),d(!1)}catch(je){console.error(je),window.alert("Organization setup save à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤")}finally{w(!1)}},q=async ne=>{!H||ne.id.startsWith("default-")||!window.confirm(`${ne.name} delete à¦à¦°à¦¬à§à¦¨? 3984 3985Existing employee record-à¦à¦° value পরিবরà§à¦¤à¦¨ হবৠনা।`)||await Ao(re(ie,`organizationSetup/${t.companyId}/${c}/${ne.id}`))};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"organization-branding-card",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Company Branding"}),e.jsx("h2",{children:"Company Logo"}),e.jsx("p",{children:"Upload once and use the same company identity across VERIXO receipts, portals and printable reports."}),C&&e.jsx("strong",{children:C})]}),e.jsxs("div",{className:"organization-branding-actions",children:[e.jsx("div",{className:"organization-logo-preview",children:I?e.jsx("img",{src:I,alt:"Company logo"}):e.jsx("span",{children:"No logo"})}),e.jsxs("label",{className:"organization-logo-upload",children:["Choose Logo",e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:ne=>{var ae;return G((ae=ne.target.files)==null?void 0:ae[0])}})]}),I&&e.jsx("button",{type:"button",onClick:()=>{_(""),T("Logo removed locally. Click Save Company Branding.")},children:"Remove"}),e.jsxs("button",{type:"button",onClick:z,disabled:N,children:[e.jsx(hr,{size:16})," Save Company Branding"]})]}),J&&e.jsx("p",{className:"organization-branding-message",children:J})]}),e.jsxs("section",{className:"page-header organization-page-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"System Setup"}),e.jsx("h1",{children:"Organization Setup"}),e.jsx("p",{children:"Employee form-à¦à¦° Department ঠDesignation dropdown à¦à¦à¦¾à¦¨ থà§à¦à§ নিà§à¦¨à§à¦¤à§à¦°à¦£ à¦à¦°à§à¦¨à¥¤"})]}),H&&e.jsxs("button",{className:"primary-action-button",onClick:M,children:[e.jsx(as,{size:18})," Add"," ",c==="departments"?"Department":"Designation"]})]}),e.jsxs("div",{className:"organization-tabs",children:[e.jsxs("button",{className:c==="departments"?"active":"",onClick:()=>l("departments"),children:[e.jsx(Fu,{size:17})," Departments"]}),e.jsxs("button",{className:c==="designations"?"active":"",onClick:()=>l("designations"),children:[e.jsx(J4,{size:17})," Designations"]})]}),e.jsxs("section",{className:"organization-card",children:[e.jsxs("div",{className:"organization-card-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:c==="departments"?"Department List":"Designation List"}),e.jsx("p",{children:"Default values বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à¦¾ যাবà§; custom value add/edit/delete à¦à¦°à¦¾ যাবà§à¥¤"})]}),e.jsxs("span",{children:[D.length," items"]})]}),e.jsx("div",{className:"organization-list",children:D.map(ne=>{const ae=ne.id.startsWith("default-");return e.jsxs("article",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:ne.name}),e.jsxs("span",{children:[ae?"Default":"Custom"," ·"," ",ne.active?"Active":"Inactive"]})]}),H&&e.jsxs("div",{className:"action-buttons",children:[e.jsx("button",{title:"Edit",onClick:()=>Z(ne),children:e.jsx(Zi,{size:17})}),!ae&&e.jsx("button",{title:"Delete",onClick:()=>void q(ne),children:e.jsx(po,{size:17})})]})]},ne.id)})})]}),m&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>d(!1),children:e.jsxs("section",{className:"modal organization-modal",onMouseDown:ne=>ne.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Organization Setup"}),e.jsxs("h2",{children:[u?"Edit":"Add"," ",c==="departments"?"Department":"Designation"]})]}),e.jsx("button",{onClick:()=>d(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:fe,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"full-field",children:["Name *",e.jsx("input",{value:g,onChange:ne=>p(ne.target.value),required:!0})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:y?"active":"inactive",onChange:ne=>b(ne.target.value==="active"),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary secondary-button",onClick:()=>d(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"vx-button vx-button-primary",disabled:N,children:[e.jsx(hr,{size:17}),N?"Saving...":"Save"]})]})]})]})})]})}const S_=[{value:"completed_jobs",label:"Completed Jobs",unit:"jobs"},{value:"delivered_jobs",label:"Delivered Jobs",unit:"jobs"},{value:"ready_jobs",label:"Ready for Delivery",unit:"jobs"},{value:"qc_completed",label:"QC Completed",unit:"jobs"}],C_=[{value:"sales_amount",label:"Sales Amount",unit:"money"},{value:"collection_amount",label:"Collection Amount",unit:"money"},{value:"new_customers",label:"New Customers",unit:"customers"},{value:"invoice_count",label:"Invoice Count",unit:"invoices"}];function hh(t,n){const[a,s]=n.split("-").map(Number);if(t==="yearly")return{start:new Date(a,0,1,0,0,0,0).getTime(),end:new Date(a,11,31,23,59,59,999).getTime(),key:String(a),label:String(a)};if(t==="quarterly"){const c=Math.floor((s-1)/3)+1,l=(c-1)*3;return{start:new Date(a,l,1,0,0,0,0).getTime(),end:new Date(a,l+3,0,23,59,59,999).getTime(),key:`${a}-Q${c}`,label:`${a} · Q${c}`}}return{...G7(n),key:n,label:n}}function G7(t){const[n,a]=t.split("-").map(Number),s=new Date(n,a-1,1,0,0,0,0).getTime(),i=new Date(n,a,0,23,59,59,999).getTime();return{start:s,end:i}}
3985function A_(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Ml(t,n){return n==="sales_amount"||n==="collection_amount"?`à§³${Number(t||0).toLocaleString("en-GB",{maximumFractionDigits:2})}`:Number(t||0).toLocaleString("en-GB")}function qv(t,n){return n<=0?0:Math.min(999,Math.round(t/n*1e4)/100)}function Y7(t){return t>=100?"Gold":t>=85?"Silver":t>=70?"Bronze":"Progress"}function I_(){var a;const t=document.createElement("style");t.id="verixo-performance-print-override",t.textContent=`@media print { 3986 .performance-data-card th:last-child, .performance-data-card td:last-child { display: none !important; } 3987 .performance-data-card th:first-child, .performance-data-card td:first-child { white-space: nowrap !important; min-width: 110px !important; } 3988 }`,(a=document.getElementById(t.id))==null||a.remove(),document.head.appendChild(t);const n=()=>{t.remove(),window.removeEventListener("afterprint",n)};window.addEventListener("afterprint",n),window.print()}function Ej({view:t,profile:n,branches:a,selectedBranchId:s}){var nt,xt;const[i,c]=x.useState([]),[l,m]=x.useState([]),[d,u]=x.useState([]),[f,g]=x.useState([]),[p,y]=x.useState([]),[b,N]=x.useState([]),[w,C]=x.useState([]),[R,I]=x.useState([]),[_,J]=x.useState(A_()),[T,G]=x.useState("monthly"),[z,H]=x.useState(null),[K,L]=x.useState(!1),[D,M]=x.useState(null),[Z,fe]=x.useState(!1),[q,ne]=x.useState(null),[ae,Y]=x.useState(0),[je,V]=x.useState(""),$=t==="sales"?"sales":"service",[F,P]=x.useState({scopeType:"employee",scopeId:"",metric:"completed_jobs",targetValue:0,weight:100,notes:"",active:!0}),ue=["super_admin","owner","admin","branch_manager","service_incharge"].includes(n.role),me=["super_admin","owner","admin"].includes(n.role);x.useEffect(()=>qt(re(ie,`employees/${n.companyId}`),te=>{if(!te.exists())return c([]);const Ge=te.val();c(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e,roles:$e.roles||[]})))}),[n.companyId]),x.useEffect(()=>{if(t==="sales"){m([]);return}return qt(re(ie,`serviceJobs/${n.companyId}`),te=>{if(!te.exists())return m([]);const Ge=te.val();m(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))})},[n.companyId,t]),x.useEffect(()=>{if(t==="service"){y([]);return}return qt(re(ie,`historicalSales/${n.companyId}`),te=>{if(!te.exists())return y([]);const Ge=te.val();y(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))})},[n.companyId,t]),x.useEffect(()=>{if(t==="service"){u([]);return}return qt(re(ie,`invoices/${n.companyId}`),te=>{if(!te.exists())return u([]);const Ge=te.val();u(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))})},[n.companyId,t]),x.useEffect(()=>{if(t==="service"){g([]);return}return qt(re(ie,`collections/${n.companyId}`),te=>{if(!te.exists())return g([]);const Ge=te.val();g(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))})},[n.companyId,t]),x.useEffect(()=>{if(t==="service"){N([]);return}return qt(re(ie,`customers/${n.companyId}`),te=>{if(!te.exists())return N([]);const Ge=te.val();N(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))})},[n.companyId,t]),x.useEffect(()=>qt(re(ie,`performanceTargets/${n.companyId}`),te=>{if(!te.exists())return C([]);const Ge=te.val();C(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})).sort((pt,$e)=>$e.createdAt-pt.createdAt))}),[n.companyId]),x.useEffect(()=>{if(t==="service"){I([]);return}return qt(re(ie,`salesTargetOpeningAchievements/${n.companyId}`),te=>{if(!te.exists())return I([]);const Ge=te.val();I(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))})},[n.companyId,t]);const ge=x.useMemo(()=>{const te=$==="service"?"technician":"sales";return i.filter(Ge=>Ge.active&&Ge.roles.includes(te)).filter(Ge=>s==="all"||Ge.branchId===s).sort((Ge,pt)=>Ge.name.localeCompare(pt.name))},[i,$,s]),de=x.useMemo(()=>w.filter(te=>{const Ge=te.periodType||"monthly",pt=hh(T,_),$e=Ge===T&&(te.periodKey||te.periodMonth)===pt.key;if(te.category!==$||!$e)return!1;if(s==="all"||te.scopeType==="company")return!0;if(te.scopeType==="branch")return te.scopeId===s;const st=i.find(Nt=>Nt.id===te.scopeId);return(st==null?void 0:st.branchId)===s}),[w,$,_,T,s,i]),Pe=$==="service"?S_:C_,Re=te=>{const Ge=be=>!!be&&be>=te.startDate&&be<=te.endDate,pt=be=>te.scopeType==="branch"?be===te.scopeId:!0;if(te.category==="service"){const be=l.filter(jt=>{if(!pt(jt.branchId))return!1;if(te.scopeType==="employee"){const bt=i.find(B=>B.id===te.scopeId);if(!(jt.assignedTechnicianId===te.scopeId||!jt.assignedTechnicianId&&bt&&jt.assignedTechnician===bt.name))return!1}return Ge(jt.deliveredAt||jt.updatedAt||jt.createdAt)});switch(te.metric){case"completed_jobs":return be.filter(jt=>["delivered","closed"].includes(jt.status)).length;case"delivered_jobs":return be.filter(jt=>jt.status==="delivered").length;case"ready_jobs":return be.filter(jt=>jt.status==="ready").length;case"qc_completed":return be.filter(jt=>!!jt.qualityCheckedAt||jt.status==="qc_completed"||["ready","delivered","closed"].includes(jt.status)).length;default:return 0}}const $e=te.scopeType==="employee"?te.scopeId:void 0,st=be=>{const jt=String(be||"").match(/^(\d{4})-(\d{2})-(\d{2})$/);return jt?new Date(Number(jt[1]),Number(jt[2])-1,Number(jt[3]),12).getTime():0},Nt=p.filter(be=>pt(be.branchId)&&Ge(st(be.saleDate))&&(!$e||be.salespersonEmployeeId===$e));switch(te.metric){case"sales_amount":return d.filter(be=>pt(be.branchId)&&Ge(be.createdAt)&&(!$e||be.salesEmployeeId===$e)).reduce((be,jt)=>be+Number(jt.grandTotal||0),0)+Nt.reduce((be,jt)=>be+Number(jt.grandTotal||jt.totalAmount||0),0);case"collection_amount":return f.filter(be=>pt(be.branchId)&&Ge(be.collectedAt||be.createdAt)&&(!$e||be.salesEmployeeId===$e)).reduce((be,jt)=>be+Number(jt.amount||0),0)+Nt.reduce((be,jt)=>be+Number(jt.collected||0),0);
3988case"new_customers":return b.filter(be=>pt(be.branchId)&&Ge(be.createdAt)&&(!$e||be.salesEmployeeId===$e)).length;case"invoice_count":return d.filter(be=>pt(be.branchId)&&Ge(be.createdAt)&&(!$e||be.salesEmployeeId===$e)).length+Nt.length;default:return 0}},Ee=te=>{if(te.category!=="sales"||te.metric!=="sales_amount")return 0;const Ge=te.scopeType==="employee"?te.scopeId:void 0,pt=st=>te.scopeType==="branch"?st===te.scopeId:!0,$e=st=>{const Nt=String(st||"").match(/^(\d{4})-(\d{2})-(\d{2})$/);return Nt?new Date(Number(Nt[1]),Number(Nt[2])-1,Number(Nt[3]),12).getTime():0};return p.filter(st=>pt(st.branchId)&&$e(st.saleDate)>=te.startDate&&$e(st.saleDate)<=te.endDate&&(!Ge||st.salespersonEmployeeId===Ge)).reduce((st,Nt)=>st+Number(Nt.grandTotal||Nt.totalAmount||0),0)},Be=te=>R.find(Ge=>Ge.targetId===te.id),We=(te,Ge)=>{if(!Ge||te.category!=="sales"||te.metric!=="sales_amount")return 0;const pt=te.scopeType==="employee"?te.scopeId:void 0,$e=Nt=>te.scopeType==="branch"?Nt===te.scopeId:!0,st=Nt=>{const be=String(Nt||"").match(/^(\d{4})-(\d{2})-(\d{2})$/);return be?new Date(Number(be[1]),Number(be[2])-1,Number(be[3]),12).getTime():0};return p.filter(Nt=>Number(Nt.createdAt||0)<=Ge&&$e(Nt.branchId)&&st(Nt.saleDate)>=te.startDate&&st(Nt.saleDate)<=te.endDate&&(!pt||Nt.salespersonEmployeeId===pt)).reduce((Nt,be)=>Nt+Number(be.grandTotal||be.totalAmount||0),0)},it=(te,Ge)=>{if(!Ge||te.category!=="sales"||te.metric!=="sales_amount")return 0;const pt=te.scopeType==="employee"?te.scopeId:void 0,$e=st=>te.scopeType==="branch"?st===te.scopeId:!0;return d.filter(st=>Number(st.createdAt||0)<=Ge&&Number(st.createdAt||0)>=te.startDate&&Number(st.createdAt||0)<=te.endDate&&$e(st.branchId)&&(!pt||st.salesEmployeeId===pt)).reduce((st,Nt)=>st+Number(Nt.grandTotal||0),0)},_e=te=>{const Ge=Re(te),pt=Ee(te),$e=te.category==="sales"&&te.metric==="sales_amount"&&te.scopeType==="employee"?Be(te):void 0,st=Number(($e==null?void 0:$e.openingAmount)||0),Nt=Number(($e==null?void 0:$e.createdAt)||0),be=$e?Number($e.baselineHistoricalActual??We(te,Nt)):0,jt=$e?it(te,Nt):0,bt=$e?Number($e.baselineInvoiceActual??jt+be):0,tn=$e?Math.max(0,pt-be):0,B=Math.max(0,st-bt-tn);return{actual:Ge+B,invoiceActual:Ge,historicalActual:pt,openingInitial:st,openingRemaining:B}},ee=te=>_e(te).actual,qe=x.useMemo(()=>de.map(te=>{const Ge=_e(te),pt=Ge.actual,$e=qv(pt,te.targetValue),st=$e*Number(te.weight||0)/100,Nt=Date.now(),be=Math.max(1,Math.min(Nt,te.endDate)-te.startDate),jt=Math.max(1,te.endDate-te.startDate),bt=Nt<=te.startDate?0:Nt>=te.endDate?pt:pt*(jt/be),tn=Math.max(0,Number(te.targetValue||0)-pt),B=qv(bt,te.targetValue);return{target:te,achievement:$e,weightedScore:st,projected:bt,remaining:tn,projectedAchievement:B,...Ge}}),[de,l,d,f,p,b,i,R]),se=x.useMemo(()=>{var Ge,pt;const te=new Map;for(const $e of qe){const st=$e.target,Nt=st.scopeType==="employee"?((Ge=i.find(jt=>jt.id===st.scopeId))==null?void 0:Ge.name)||"Unknown Employee":((pt=a.find(jt=>jt.id===st.scopeId))==null?void 0:pt.name)||"Unknown Branch",be=te.get(st.scopeId)||{scopeId:st.scopeId,name:Nt,score:0,count:0,category:st.category};be.score+=$e.weightedScore,be.count+=Number(st.weight||0),te.set(st.scopeId,be)}return[...te.values()].map($e=>({...$e,score:$e.count>0?Math.round($e.score/$e.count*100)/100:0})).sort(($e,st)=>st.score-$e.score)},[qe,i,a]),pe=()=>{M(null),P({scopeType:"employee",scopeId:"",metric:$==="service"?"completed_jobs":"sales_amount",targetValue:0,weight:100,notes:"",active:!0})},Se=()=>{pe(),L(!0)},Me=te=>{M(te),G(te.periodType||"monthly"),J(te.periodMonth||A_()),P({scopeType:te.scopeType,scopeId:te.scopeId,metric:te.metric,targetValue:te.targetValue,weight:te.weight,notes:te.notes||"",active:te.active}),L(!0)},ot=async te=>{if(te.preventDefault(),!F.scopeId||F.targetValue<=0){window.alert("Target scope à¦à¦¬à¦ target value required.");return}fe(!0);try{const Ge=Date.now(),pt=hh(T,_),$e=D?re(ie,`performanceTargets/${n.companyId}/${D.id}`):Ta(re(ie,`performanceTargets/${n.companyId}`)),st=(D==null?void 0:D.id)||$e.key||"",Nt={companyId:n.companyId,category:$,scopeType:F.scopeType,scopeId:F.scopeId,metric:F.metric,targetValue:Number(F.targetValue),weight:Math.max(1,Math.min(100,Number(F.weight||100))),periodMonth:_,periodType:T,periodKey:pt.key,approvalStatus:(D==null?void 0:D.approvalStatus)||(me?"approved":"pending"),...D!=null&&D.approvedBy?{approvedBy:D.approvedBy}:me?{approvedBy:n.name}:{},...D!=null&&D.approvedAt?{approvedAt:D.approvedAt}:me?{approvedAt:Ge}:{},startDate:pt.start,endDate:pt.end,notes:F.notes.trim(),active:F.active,createdBy:(D==null?void 0:D.createdBy)||n.name,createdAt:(D==null?void 0:D.createdAt)||Ge,updatedAt:Ge};D?await yn($e,Nt):await Pn($e,{id:st,...Nt}),await ia({companyId:n.companyId,actorUid:n.uid,actorName:n.name,action:D?"performance.target_updated":"performance.target_created",entityType:"performanceTarget",entityId:st,summary:`${D?"Updated":"Created"} ${$} target`,metadata:{category:$,scopeType:F.scopeType,scopeId:F.scopeId,metric:F.metric,targetValue:F.targetValue,periodMonth:_,periodType:T,approvalStatus:Nt.approvalStatus}}),L(!1),pe()}finally{fe(!1)}},wt=async te=>{window.confirm("à¦à¦ target delete à¦à¦°à¦¬à§à¦¨?")&&(await Ao(re(ie,`performanceTargets/${n.companyId}/${te.id}`)),await ia({companyId:n.companyId,actorUid:n.uid,actorName:n.name,action:"performance.target_deleted",entityType:"performanceTarget",entityId:te.id,summary:`Deleted ${te.category} target`}))},ct=te=>{var Ge,pt;return te.scopeType==="company"?"Whole Company":te.scopeType==="employee"?((Ge=i.find($e=>$e.id===te.scopeId))==null?void 0:Ge.name)||"Unknown Employee":((pt=a.find($e=>$e.id===te.scopeId))==null?void 0:pt.name)||"Unknown Branch"},Ce=async(te,Ge)=>{if(!me)return;const pt=Date.now();await yn(re(ie,`performanceTargets/${n.companyId}/${te.id}`),Ge==="approved"?{approvalStatus:Ge,approvedBy:n.name,approvedAt:pt,rejectedBy:null,rejectedAt:null,active:!0,updatedAt:pt}:{approvalStatus:Ge,rejectedBy:n.name,rejectedAt:pt,active:!1,updatedAt:pt}),await ia({companyId:n.companyId,actorUid:n.uid,actorName:n.name,action:Ge==="approved"?"performance.target_approved":Ge==="rejected"?"performance.target_rejected":"performance.target_pending",entityType:"performanceTarget",entityId:te.id,summary:`${Ge} ${te.category} target`})},De=te=>{const Ge=Be(te);ne(te),Y(Number((Ge==null?void 0:Ge.openingAmount)||0)),V((Ge==null?void 0:Ge.notes)||"")},Te=async()=>
3988{if(!q||!Be(q)||Z||!window.confirm(`Clear manual opening achievement for ${ct(q)} · ${q.periodKey||q.periodMonth}? Invoice actual and target data will remain unchanged.`))return;const te=`salesTargetOpeningAchievements/${n.companyId}/${q.id}`;fe(!0);try{await Ao(re(ie,te)),await ia({companyId:n.companyId,actorUid:n.uid,actorName:n.name,action:"performance.sales_opening_achievement_cleared",entityType:"performanceTarget",entityId:q.id,summary:"Cleared manual opening sales achievement",metadata:{employeeId:q.scopeId,periodKey:q.periodKey||q.periodMonth}}),ne(null)}finally{fe(!1)}},ce=async()=>{var Ge;if(!q||Z)return;const te=Be(q);if(te){fe(!0);try{const pt=await mn(re(ie,`auditLogs/${n.companyId}`)),Nt=(pt.exists()?Object.values(pt.val()||{}):[]).filter(xe=>{var tt;return(xe==null?void 0:xe.action)==="performance.sales_opening_achievement_saved"&&(xe==null?void 0:xe.entityId)===q.id&&Number(((tt=xe==null?void 0:xe.metadata)==null?void 0:tt.openingAmount)||0)>0}).sort((xe,tt)=>Number(xe.createdAt||0)-Number(tt.createdAt||0))[0],be=Number(((Ge=Nt==null?void 0:Nt.metadata)==null?void 0:Ge.openingAmount)||0),jt=Number((Nt==null?void 0:Nt.createdAt)||te.createdAt||0);if(!(be>0)){window.alert("No original Opening Achievement value was found in the audit trail. Nothing was changed.");return}if(!window.confirm(`Legacy Opening recovery found the first saved value: ${Ml(be,"sales_amount")}. 3989 3990Current stored value: ${Ml(Number(te.openingAmount||0),"sales_amount")}. 3991 3992Restore the original audited value and lock its reconciliation baseline?`))return;const bt=We(q,jt),tn=it(q,jt)+bt,B=Date.now();await yn(re(ie,`salesTargetOpeningAchievements/${n.companyId}/${q.id}`),{openingAmount:be,legacyOriginalOpeningAmount:be,baselineHistoricalActual:bt,baselineInvoiceActual:tn,legacyReconciledAt:B,updatedBy:n.name,updatedAt:B}),await ia({companyId:n.companyId,actorUid:n.uid,actorName:n.name,action:"performance.sales_opening_achievement_saved",entityType:"performanceTarget",entityId:q.id,summary:"Recovered original manual opening sales achievement from audit trail",metadata:{employeeId:q.scopeId,periodKey:q.periodKey||q.periodMonth,openingAmount:be,previousOpeningAmount:Number(te.openingAmount||0),recoverySource:"first_audited_opening"}}),Y(be),window.alert("Original Opening Achievement restored from the audit trail. Performance will reconcile automatically.")}catch(pt){window.alert(pt instanceof Error?pt.message:"Unable to read the audit trail for legacy recovery.")}finally{fe(!1)}}},Ye=async te=>{if(te.preventDefault(),!q||q.category!=="sales"||q.metric!=="sales_amount"||q.scopeType!=="employee")return;const Ge=Math.max(0,Number(ae||0)),pt=Date.now(),$e=`salesTargetOpeningAchievements/${n.companyId}/${q.id}`;fe(!0);try{if(Ge<=0)await Ao(re(ie,$e));else{const st=Be(q),Nt=(st==null?void 0:st.createdAt)||pt,be=Number((st==null?void 0:st.baselineHistoricalActual)??We(q,Nt)),jt=Number((st==null?void 0:st.baselineInvoiceActual)??it(q,Nt)+be);await Pn(re(ie,$e),{targetId:q.id,employeeId:q.scopeId,periodKey:q.periodKey||q.periodMonth,openingAmount:Ge,baselineInvoiceActual:jt,baselineHistoricalActual:be,...(st==null?void 0:st.legacyOriginalOpeningAmount)!=null?{legacyOriginalOpeningAmount:st.legacyOriginalOpeningAmount}:{},...(st==null?void 0:st.legacyReconciledAt)!=null?{legacyReconciledAt:st.legacyReconciledAt}:{},notes:je.trim(),createdBy:(st==null?void 0:st.createdBy)||n.name,createdAt:Nt,updatedBy:n.name,updatedAt:pt})}await ia({companyId:n.companyId,actorUid:n.uid,actorName:n.name,action:Ge>0?"performance.sales_opening_achievement_saved":"performance.sales_opening_achievement_cleared",entityType:"performanceTarget",entityId:q.id,summary:`${Ge>0?"Saved":"Cleared"} manual opening sales achievement`,metadata:{employeeId:q.scopeId,periodKey:q.periodKey||q.periodMonth,openingAmount:Ge}}),ne(null)}finally{fe(!1)}},Je=te=>{var Ge;return((Ge=[...S_,...C_].find(pt=>pt.value===te))==null?void 0:Ge.label)||te};if(t==="leaderboard"){const te=w.filter($e=>$e.category==="service"&&($e.periodType||"monthly")===T&&($e.periodKey||$e.periodMonth)===hh(T,_).key).map($e=>{const st=ee($e);return{target:$e,actual:st,achievement:qv(st,$e.targetValue)}}),Ge=w.filter($e=>$e.category==="sales"&&($e.periodType||"monthly")===T&&($e.periodKey||$e.periodMonth)===hh(T,_).key).map($e=>{const st=ee($e);return{target:$e,actual:st,achievement:qv(st,$e.targetValue)}}),pt=$e=>{const st=new Map;for(const Nt of $e){const be=ct(Nt.target),jt=st.get(Nt.target.scopeId)||{name:be,total:0,weight:0};jt.total+=Nt.achievement*Nt.target.weight,jt.weight+=Nt.target.weight,st.set(Nt.target.scopeId,jt)}return[...st.entries()].map(([Nt,be])=>({id:Nt,name:be.name,score:be.weight?be.total/be.weight:0})).sort((Nt,be)=>be.score-Nt.score)};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-header performance-page-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Performance"}),e.jsx("h1",{children:"Role-based Leaderboard"}),e.jsx("p",{children:"Service ঠSales performance à¦à¦²à¦¾à¦¦à¦¾ ranking-ঠদà§à¦à¦¾à¦¨à§ হà¦à§à¦à§à¥¤"})]}),e.jsxs("div",{className:"performance-header-actions",children:[e.jsxs("label",{className:"performance-period",children:[e.jsx(wi,{size:17}),e.jsxs("select",{value:T,onChange:$e=>G($e.target.value),children:[e.jsx("option",{value:"monthly",children:"Monthly"}),e.jsx("option",{value:"quarterly",children:"Quarterly"}),e.jsx("option",{value:"yearly",children:"Yearly"})]}
3992),e.jsx("input",{type:"month",value:_,onChange:$e=>J($e.target.value)})]}),e.jsxs("button",{className:"secondary-button performance-print-button",onClick:I_,children:[e.jsx(Wi,{size:17})," Print Report"]})]})]}),e.jsx("div",{className:"performance-leaderboard-grid",children:[{title:"Service Leaderboard",rows:pt(te)},{title:"Sales Leaderboard",rows:pt(Ge)}].map($e=>e.jsxs("section",{className:"performance-board",children:[e.jsxs("div",{className:"performance-board-header",children:[e.jsx(sA,{size:20}),e.jsx("h2",{children:$e.title})]}),e.jsxs("div",{className:"performance-board-list",children:[$e.rows.map((st,Nt)=>e.jsxs("article",{children:[e.jsx("span",{className:"rank",children:Nt+1}),e.jsxs("div",{children:[e.jsx("strong",{children:st.name}),e.jsx("small",{children:Y7(st.score)})]}),e.jsxs("strong",{children:[st.score.toFixed(2),"%"]})]},st.id)),!$e.rows.length&&e.jsx("p",{children:"No target data for this month."})]})]},$e.title))})]})}qe.reduce((te,Ge)=>te+Ge.target.targetValue,0);const le=qe.length?qe.reduce((te,Ge)=>te+Ge.achievement,0)/qe.length:0;return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-header performance-page-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Performance"}),e.jsx("h1",{children:$==="service"?"Service Target & Achievement":"Sales Target & Achievement"}),e.jsx("p",{children:$==="service"?"Technician ঠService Branch-à¦à¦° target, achievement ঠforecast report।":"Sales employee ঠBranch-à¦à¦° target, achievement ঠforecast report।"})]}),e.jsxs("div",{className:"performance-header-actions",children:[e.jsxs("label",{className:"performance-period",children:[e.jsx(wi,{size:17}),e.jsxs("select",{value:T,onChange:te=>G(te.target.value),children:[e.jsx("option",{value:"monthly",children:"Monthly"}),e.jsx("option",{value:"quarterly",children:"Quarterly"}),e.jsx("option",{value:"yearly",children:"Yearly"})]}),e.jsx("input",{type:"month",value:_,onChange:te=>J(te.target.value)})]}),e.jsxs("button",{className:"secondary-button performance-print-button",onClick:I_,children:[e.jsx(Wi,{size:17})," Print Report"]}),ue&&e.jsxs("button",{className:"primary-action-button",onClick:Se,children:[e.jsx(as,{size:18})," Add Target"]})]})]}),e.jsxs("section",{className:"performance-report-meta",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Report"}),e.jsx("strong",{children:$==="service"?"Service Performance":"Sales Performance"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Period"}),e.jsxs("strong",{children:[hh(T,_).label," · ",T]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:s==="all"?"All Branches":((nt=a.find(te=>te.id===s))==null?void 0:nt.name)||"Selected Branch"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Generated"}),e.jsx("strong",{children:new Date().toLocaleDateString("en-GB")})]})]}),e.jsxs("section",{className:"performance-summary-grid",children:[e.jsxs("article",{children:[e.jsx(Mc,{size:21}),e.jsx("span",{children:"Active Targets"}),e.jsx("strong",{children:de.filter(te=>te.active).length})]}),e.jsxs("article",{children:[e.jsx(xp,{size:21}),e.jsx("span",{children:"Average Achievement"}),e.jsxs("strong",{children:[le.toFixed(2),"%"]})]}),e.jsxs("article",{children:[e.jsx(Ms,{size:21}),e.jsx("span",{children:"Targets Achieved"}),e.jsx("strong",{children:qe.filter(te=>te.achievement>=100).length})]}),e.jsxs("article",{children:[e.jsx(sA,{size:21}),e.jsx("span",{children:"Top Performer"}),e.jsx("strong",{children:((xt=se[0])==null?void 0:xt.name)||"â"})]})]}),e.jsxs("section",{className:"performance-data-card",children:[e.jsxs("div",{className:"performance-card-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:$==="service"?"Service Performance Report":"Sales Performance Report"}),e.jsx("p",{children:"Target, actual, remaining, projection, achievement, approval à¦à¦¬à¦ weighted score à¦à¦à¦¸à¦¾à¦¥à§à¥¤"})]}),e.jsx("span",{children:hh(T,_).label})]}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Assigned To"}),e.jsx("th",{children:"KPI"}),e.jsx("th",{children:"Target"}),e.jsx("th",{children:"Actual"}),e.jsx("th",{children:"Remaining"}),e.jsx("th",{children:"Projected"}),e.jsx("th",{children:"Achievement"}),e.jsx("th",{children:"Weight"}),e.jsx("th",{children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Approval"}),e.jsx("th",{children:"Actions"})]})}),e.jsxs("tbody",{children:[qe.map(te=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:ct(te.target)}),e.jsx("small",{children:te.target.scopeType})]}),e.jsx("td",{children:Je(te.target.metric)}),e.jsx("td",{children:Ml(te.target.targetValue,te.target.metric)}),e.jsxs("td",{children:[Ml(te.actual,te.target.metric),te.target.category==="sales"&&te.target.metric==="sales_amount"&&te.target.scopeType==="employee"&&te.openingInitial>0&&e.jsxs("small",{children:["Invoice ",Ml(te.invoiceActual,"sales_amount")," · Opening left ",Ml(te.openingRemaining,"sales_amount")]})]}),e.jsx("td",{children:Ml(te.remaining,te.target.metric)}),e.jsxs("td",{children:[e.jsx("strong",{children:Ml(te.projected,te.target.metric)}),e.jsxs("small",{children:[te.projectedAchievement.toFixed(1),"% forecast"]})]}),e.jsx("td",{children:e.jsxs("div",{className:"performance-progress",children:[e.jsx("div",{children:e.jsx("span",{style:{width:`${Math.min(100,te.achievement)}%`}})}),e.jsxs("strong",{children:[te.achievement.toFixed(2),"%"]})]})}),e.jsxs("td",{children:[te.target.weight,"%"]}),e.jsx("td",{children:te.weightedScore.toFixed(2)}),e.jsx("td",{children:e.jsx("span",{className:`performance-status ${te.achievement>=100?"achieved":"progress"}`,children:te.achievement>=100?"Achieved":"In Progress"})}),e.jsx("td",{children:e.jsx("span",{className:`performance-status ${(te.target.approvalStatus||"approved")==="approved"?"achieved":"progress"}`,children:te.target.approvalStatus||"approved"})}),e.jsx("td",{children:e.jsxs("div",{className:"action-buttons",children:[$==="sales"&&te.target.scopeType==="employee"&&e.jsx("button",{onClick:()=>H(te.target),title:"Sales History",children:e.jsx(xp,{size:17})}),ue&&$==="sales"&&te.target.scopeType==="employee"&&te.target.metric==="sales_amount"&&e.jsx("button",{onClick:()=>De(te.target),title:"Manual Opening Achievement",children:e.jsx(Mc,{size:17})}),me&&(te.target.approvalStatus||"approved")==="pending"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>
3992void Ce(te.target,"approved"),title:"Approve",children:e.jsx(Ms,{size:17})}),e.jsx("button",{onClick:()=>void Ce(te.target,"rejected"),title:"Reject",children:e.jsx(ja,{size:17})})]}),ue&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Me(te.target),title:"Edit",children:e.jsx(Zi,{size:17})}),e.jsx("button",{onClick:()=>void wt(te.target),title:"Delete",children:e.jsx(po,{size:17})})]})]})})]},te.target.id)),!qe.length&&e.jsx("tr",{children:e.jsxs("td",{colSpan:12,className:"empty-table",children:["No ",$," targets for ",_,"."]})})]})]})})]}),qe.some(te=>(te.target.approvalStatus||"approved")==="approved"&&te.projectedAchievement<90&&te.achievement<100)&&e.jsxs("section",{className:"performance-risk-alert",children:[e.jsx(Mc,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Target Risk Alert"}),e.jsxs("span",{children:[qe.filter(te=>(te.target.approvalStatus||"approved")==="approved"&&te.projectedAchievement<90&&te.achievement<100).length," target(s) are projected below 90% at the current pace."]})]})]}),z&&(()=>{const te=i.find(st=>st.id===z.scopeId),Ge=d.filter(st=>st.salesEmployeeId===z.scopeId&&st.createdAt>=z.startDate&&st.createdAt<=z.endDate).map(st=>({id:st.id,date:new Date(st.createdAt).toLocaleDateString("en-GB"),amount:st.grandTotal,source:"Live Invoice"})),pt=p.filter(st=>st.salespersonEmployeeId===z.scopeId).filter(st=>{const Nt=new Date(`${st.saleDate}T12:00:00`).getTime();return Nt>=z.startDate&&Nt<=z.endDate}).map(st=>({id:st.id,date:st.saleDate,amount:Number(st.grandTotal||st.totalAmount||0),source:"Historical Sale"})),$e=[...Ge,...pt].sort((st,Nt)=>String(Nt.date).localeCompare(String(st.date)));return e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>H(null),children:e.jsxs("section",{className:"modal performance-modal",onMouseDown:st=>st.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Salesperson Drill-down"}),e.jsxs("h2",{children:[(te==null?void 0:te.name)||"Salesperson"," · Sales History"]})]}),e.jsx("button",{onClick:()=>H(null),children:e.jsx(ja,{size:20})})]}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Reference"}),e.jsx("th",{children:"Amount"})]})}),e.jsxs("tbody",{children:[$e.map(st=>e.jsxs("tr",{children:[e.jsx("td",{children:st.date}),e.jsx("td",{children:st.source}),e.jsx("td",{children:st.id}),e.jsx("td",{children:Ml(st.amount,"sales_amount")})]},`${st.source}-${st.id}`)),!$e.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"empty-table",children:"No sales found in this target period."})})]})]})})]})})})(),q&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>ne(null),children:e.jsxs("section",{className:"modal performance-modal",onMouseDown:te=>te.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Sales Target Migration"}),e.jsx("h2",{children:"Manual Opening Achievement"}),e.jsxs("p",{children:[ct(q)," · ",q.periodKey||q.periodMonth]})]}),e.jsx("button",{onClick:()=>ne(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:Ye,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Opening Achievement",e.jsx("input",{type:"number",min:"0",step:"0.01",value:ae||"",onChange:te=>Y(Number(te.target.value||0)),required:!0})]}),e.jsxs("label",{children:["Target Value",e.jsx("input",{value:Ml(q.targetValue,"sales_amount"),disabled:!0})]}),e.jsxs("label",{className:"full-width",children:["Notes",e.jsx("input",{value:je,onChange:te=>V(te.target.value),placeholder:"Optional migration/reference note"})]})]}),e.jsxs("div",{className:"performance-risk-alert",children:[e.jsx(Mc,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Auto-Reconciliation"}),e.jsx("span",{children:"Historical invoice import হলৠexact salesperson mapping à¦
নà§à¦¯à¦¾à§à§ imported sales à¦à¦ opening balance consume à¦à¦°à¦¬à§à¥¤ Double count হবৠনা; opening remaining ধà§à¦°à§ ধà§à¦°à§ zero হবà§."})]})]}),e.jsxs("div",{className:"modal-actions",children:[Be(q)&&e.jsx("button",{type:"button",className:"secondary-button",onClick:ce,disabled:Z,children:"Recover Original Opening"}),Be(q)&&e.jsx("button",{type:"button",className:"secondary-button",onClick:Te,disabled:Z,children:"Clear Opening Achievement"}),e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>ne(null),children:"Cancel"}),e.jsx("button",{className:"primary-action-button",disabled:Z,children:Z?"Saving...":Be(q)?"Update Opening Achievement":"Save Opening Achievement"})]})]})]})}),K&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>L(!1),children:e.jsxs("section",{className:"modal performance-modal",onMouseDown:te=>te.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:$==="service"?"Service Target":"Sales Target"}),e.jsx("h2",{children:D?"Edit Target":"Add Target"})]}),e.jsx("button",{onClick:()=>L(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:ot,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Target Scope",e.jsxs("select",{value:F.scopeType,onCh
3992ange:te=>P({...F,scopeType:te.target.value,scopeId:te.target.value==="company"?"company":""}),children:[e.jsx("option",{value:"employee",children:"Employee"}),e.jsx("option",{value:"branch",children:"Branch"}),e.jsx("option",{value:"company",children:"Whole Company"})]})]}),e.jsxs("label",{children:["Assigned To",e.jsxs("select",{value:F.scopeId,onChange:te=>P({...F,scopeId:te.target.value}),required:!0,children:[e.jsx("option",{value:"",children:"Select"}),F.scopeType==="company"?e.jsx("option",{value:"company",children:"Whole Company"}):F.scopeType==="employee"?ge.map(te=>e.jsxs("option",{value:te.id,children:[te.name," â ",te.designation||$]},te.id)):a.filter(te=>te.active&&(s==="all"||te.id===s)).map(te=>e.jsx("option",{value:te.id,children:te.name},te.id))]})]}),e.jsxs("label",{children:["KPI",e.jsx("select",{value:F.metric,onChange:te=>P({...F,metric:te.target.value}),children:Pe.map(te=>e.jsx("option",{value:te.value,children:te.label},te.value))})]}),e.jsxs("label",{children:["Target Value",e.jsx("input",{type:"number",min:"0.01",step:"0.01",value:F.targetValue,onChange:te=>P({...F,targetValue:Number(te.target.value)}),required:!0})]}),e.jsxs("label",{children:["Weight (%)",e.jsx("input",{type:"number",min:"1",max:"100",value:F.weight,onChange:te=>P({...F,weight:Number(te.target.value)})})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:F.active?"active":"inactive",onChange:te=>P({...F,active:te.target.value==="active"}),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]}),e.jsxs("label",{children:["Target Period",e.jsxs("select",{value:T,onChange:te=>G(te.target.value),children:[e.jsx("option",{value:"monthly",children:"Monthly"}),e.jsx("option",{value:"quarterly",children:"Quarterly"}),e.jsx("option",{value:"yearly",children:"Yearly"})]})]}),e.jsxs("label",{children:["Period Reference",e.jsx("input",{type:"month",value:_,onChange:te=>J(te.target.value)}),e.jsx("small",{children:hh(T,_).label})]}),e.jsxs("label",{className:"full-field",children:["Notes",e.jsx("textarea",{rows:3,value:F.notes,onChange:te=>P({...F,notes:te.target.value})})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary secondary-button",onClick:()=>L(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"vx-button vx-button-primary",disabled:Z,children:[e.jsx(Mc,{size:17}),Z?"Savingâ¦":D?"Update Target":me?"Save & Approve":"Submit for Approval"]})]})]})]})})]})}const __=["owner","admin","branch_manager","service_incharge","reception","operator","branch_operator","technician","accountant","sales","store","hr","viewer"],Q7=[{value:"admin",label:"Administration / Top Management"},{value:"branch_manager",label:"Branch Management"},{value:"service_incharge",label:"Service"},{value:"sales",label:"Sales"},{value:"accountant",label:"Accounts"},{value:"store",label:"Purchase / Store"},{value:"hr",label:"HR"},{value:"reception",label:"Reception"},{value:"operator",label:"Operations"},{value:"branch_operator",label:"Branch Operations"},{value:"viewer",label:"Viewer"}],UE="__dot__";function k_(t){return Object.fromEntries(Object.entries(t).map(([n,a])=>[n.replaceAll(".",UE),a]))}function D_(t){return t?Object.fromEntries(Object.entries(t).map(([n,a])=>[n.replaceAll(UE,"."),a])):{}}function E_(t){return Array.isArray(t)?t.map(String).filter(Boolean).sort():t&&typeof t=="object"?Object.values(t).map(String).filter(Boolean).sort():[]}function J7(t,n){return Array.from(new Set([...Object.keys(t),...Object.keys(n)])).sort().every(s=>!!t[s]==!!n[s]&&s in t==s in n)}function Pj(){const t="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",n="!@#$",a=new Uint32Array(10);crypto.getRandomValues(a);const s=Array.from(a,i=>t[i%t.length]);return s[2]=n[a[2]%n.length],s[5]=String(a[5]%10),s.join("")}function K7(t){const n=(t==null?void 0:t.roles)||[],a=((t==null?void 0:t.designation)||"").trim().toLowerCase();return a.includes("service in-charge")||a.includes("service in charge")||a==="in-charge"||a==="in charge"?"service_incharge":n.includes("sales")&&n.includes("technician")?"branch_operator":n.includes("technician")?"technician":n.includes("sales")?"sales":n.includes("accounts")?"accountant":n.includes("admin")?"admin":n.includes("store")?"store":n.includes("hr")?"hr":n.includes("manager")?"branch_manager":"reception"}
3992class ku extends Error{constructor(a,s){super(s||a);ES(this,"code");this.name="FirebasePasswordApiError",this.code=a}}async function P_(t,n,a=15e3){var l;const s=String(ux.firebase.apiKey||"").trim();if(!s)throw new ku("MISSING_API_KEY","VERIXO runtime Firebase configuration-ঠAPI key পাà¦à§à¦¾ যাà¦à§à¦à§ না।");const i=new AbortController,c=window.setTimeout(()=>i.abort(),a);try{const m=await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:${t}?key=${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:i.signal}),d=await m.json().catch(()=>({}));if(!m.ok){const u=String(((l=d.error)==null?void 0:l.message)||`HTTP_${m.status}`),f=u.split(" : ")[0].trim();throw new ku(f,u)}if(!d.localId)throw new ku("MISSING_LOCAL_ID","Firebase user ID পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return{localId:d.localId,email:d.email}}catch(m){throw m instanceof DOMException&&m.name==="AbortError"?new ku("REQUEST_TIMEOUT","Firebase Authentication response timeout হà§à§à¦à§à¥¤"):m}finally{window.clearTimeout(c)}}async function X7(t,n,a,s){const i=async()=>(s("Checking existing userâ¦"),{uid:(await P_("signInWithPassword",{email:t,password:n,returnSecureToken:!0},12e3)).localId,linkedExistingAuth:!0}),c=async()=>(s("Creating userâ¦"),{uid:(await P_("signUp",{email:t,password:n,displayName:a,returnSecureToken:!0},15e3)).localId,linkedExistingAuth:!1});try{return await c()}catch(l){const m=l instanceof ku?l.code:"";if(m==="EMAIL_EXISTS")return await i();if(m==="REQUEST_TIMEOUT"||m==="NETWORK_REQUEST_FAILED"||l instanceof TypeError)try{return await i()}catch(d){const u=d instanceof ku?d.code:"";if(u!=="EMAIL_NOT_FOUND"&&u!=="INVALID_LOGIN_CREDENTIALS")throw d;try{return await c()}catch(f){if((f instanceof ku?f.code:"")==="EMAIL_EXISTS")return await i();throw f}}throw l}}function Z7({profile:t,branches:n}){var ot,wt,ct;const[a,s]=x.useState([]),[i,c]=x.useState([]),[l,m]=x.useState(!1),[d,u]=x.useState(""),[f,g]=x.useState("viewer"),[p,y]=x.useState(Bm("viewer")),[b,N]=x.useState(!1),[w,C]=x.useState([]),[R,I]=x.useState([]),[_,J]=x.useState(null),[T,G]=x.useState("viewer"),[z,H]=x.useState(""),[K,L]=x.useState(""),[D,M]=x.useState([]),[Z,fe]=x.useState(!1),[q,ne]=x.useState(!0),[ae,Y]=x.useState({}),[je,V]=x.useState(!1),[$,F]=x.useState(null),[P,ue]=x.useState(""),[me,ge]=x.useState(!1),[de,Pe]=x.useState({employeeId:"",name:"",email:"",password:Pj(),role:"reception",roleTemplateId:"",branchId:"",branchIds:[],allBranches:!1,active:!0});x.useEffect(()=>qt(Vl(re(ie,"users"),ql("companyId"),Dh(t.companyId)),Ce=>{if(!Ce.exists())return s([]);const De=Ce.val();s(Object.entries(De).map(([Te,ce])=>({...ce,uid:Te})).sort((Te,ce)=>Te.name.localeCompare(ce.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`roleTemplates/${t.companyId}`),Ce=>{if(!Ce.exists())return c([]);const De=Ce.val();c(Object.entries(De).map(([Te,ce])=>({id:Te,...ce})).filter(Te=>Te.active!==!1).sort((Te,ce)=>Te.name.localeCompare(ce.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),Ce=>{if(!Ce.exists())return C([]);const De=Ce.val();C(Object.entries(De).map(([Te,ce])=>({id:Te,...ce,source:"employee"})).filter(Te=>Te.active).sort((Te,ce)=>Te.name.localeCompare(ce.name)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`technicians/${t.companyId}`),Ce=>{if(!Ce.exists())return I([]);const De=Ce.val();I(Object.entries(De).map(([Te,ce])=>({id:`legacy:${Te}`,branchId:ce.branchId,employeeId:ce.employeeId,name:ce.name,phone:ce.phone,email:ce.email,department:"Service",designation:"Technician",roles:["technician"],active:ce.active,source:"legacy_technician"})).filter(Te=>Te.active).sort((Te,ce)=>Te.name.localeCompare(ce.name)))}),[t.companyId]);const Re=x.useMemo(()=>{const Ce=new Set(w.map(Te=>Te.name.trim().toLowerCase())),De=R.filter(Te=>!Ce.has(Te.name.trim().toLowerCase()));return[...w,...De].sort((Te,ce)=>Te.name.localeCompare(ce.name))},[w,R]),Ee=x.useMemo(()=>a.filter(Ce=>Ce.active).length,[a]),Be=()=>{Pe({employeeId:"",name:"",email:"",password:Pj(),role:"reception",roleTemplateId:"",branchId:"",branchIds:[],allBranches:!1,active:!0})},We=Ce=>i.find(De=>De.id===Ce),it=Ce=>{var De;return((De=We(Ce.roleTemplateId))==null?void 0:De.name)||jh[Ce.role]},_e=async()=>{const Ce=d.trim(),De=String(t.companyId||"").trim(),Te=String(t.uid||"").trim();if(!Ce)return window.alert("Role Name দিন।");if(!De||!Te)return window.alert("Company/User context পাà¦à§à¦¾ যাà¦à§à¦à§ না। Logout/Login à¦à¦°à§ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤");if(i.some(ce=>ce.name.toLowerCase()===Ce.toLowerCase()))return window.alert("à¦à¦ নামৠRole à¦à¦à§ থà§à¦à§à¦ à¦à¦à§à¥¤");if(!b){N(!0);try{const ce=`role_${Date.now()}_${Math.random().toString(36).slice(2,10)}`;await Pn(re(ie,`roleTemplates/${De}/${ce}`),{name:Ce,baseRole:f,capabilities:Array.from(new Set(p)),active:!0,createdAt:Date.now(),createdBy:Te}),u(""),g("viewer"),y(Bm("viewer")),window.alert(`${Ce} Role successfully created.`)}catch(ce){console.error("Custom role creation failed:",ce);const Ye=ce instanceof Error?ce.message:String(ce);window.alert(`Role save à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ 3993 3994${Ye}`)}finally{N(!1)}}},ee=async Ce=>{if(a.some(De=>De.roleTemplateId===Ce.id)){window.alert("à¦à¦ Role existing user-à¦à¦° সাথৠassigned à¦à¦à§à¥¤ à¦à¦à§ user-à¦à§ ঠনà§à¦¯ Role দিন।");return}window.confirm(`${Ce.name} Role delete à¦à¦°à¦¬à§à¦¨?`)&&await Pn(re(ie,`roleTemplates/${t.companyId}/${Ce.id}`),null)},qe=async(Ce,De,Te=8e3)=>{let ce;try{await Promise.race([De,new Promise((Ye,Je)=>{ce=setTimeout(()=>Je(new Error(`${Ce} timed out`)),Te)})])}catch(Ye){console.warn(`${Ce} skipped:`,Ye)}finally{ce&&clearTimeout(ce)}},se=async Ce=>{var Ye,Je;Ce.preventDefault();const De=de.name.trim(),Te=de.email.trim().toLowerCase();if(a.some(le=>le.email.trim().toLowerCase()===Te)){window.alert("à¦à¦ Email দিà§à§ à¦à¦à¦à¦¿ Login User à¦à¦à§ থà§à¦à§à¦ à¦à¦à§à¥¤");return}if(de.employeeId&&a.some(le=>le.employeeId===de.employeeId)){window.alert("à¦à¦ Employee-à¦à¦° Login User à¦à¦à§ থà§à¦à§à¦ তà§à¦°à¦¿ হà§à§à¦à§à¥¤");return}if(de.role==="owner"&&t.role!=="owner"){window.alert("শà§à¦§à§ Owner নতà§à¦¨ Owner role assign à¦à¦°à¦¤à§ পারবà§à¥¤");return}if(!De||!Te||de.password.length<6){window.alert("Name, valid Email à¦à¦¬à¦ minimum 6 character password required.");return}if(!["owner","super_admin"].includes(de.role)&&!de.allBranches&&de.branchIds.length===0){window.alert("à¦à¦ role-à¦à¦° à¦à¦¨à§à¦¯ ঠনà§à¦¤à¦¤ à¦à¦à¦à¦¿ Branch select à¦à¦°à§à¦¨ ঠথবা All Branches দিন।");return}V(!0),ue("Creating userâ¦");try{const{uid:le,linkedExistingAuth:nt}=await X7(Te,de.password,De,ue);ue("Checking user accessâ¦");const xt=await mn(re(ie,`users/${le}`));if(xt.exists()){const pt=xt.val();if(pt.companyId&&pt.companyId!==t.companyId&&t.role!=="super_admin")throw new Error("This Firebase login already belongs to another VERIXO company.")}const te=Date.now(),Ge={uid:le,name:De,email:Te,role:de.role,roleTemplateId:de.roleTemplateId||"",permissionOverrides:de.roleTemplateId?k_(Object.fromEntries(Lm.map(pt=>{var $e;return[pt,(($e=We(de.roleTemplateId))==null?void 0:$e.capabilities.includes(pt))||!1]}))):{},companyId:t.companyId,branchId:de.role==="owner"||de.role==="super_admin"||de.allBranches?"":de.branchIds[0]||de.branchId,branchIds:de.role==="owner"||de.role==="super_admin"||de.allBranches?[]:de.branchIds,allBranches:de.role==="owner"||de.role==="super_admin"?!0:de.allBranches,employeeId:de.employeeId||"",active:de.active,forcePasswordChange:!0,loginCount:xt.exists()?Number(((Ye=xt.val())==null?void 0:Ye.loginCount)||0):0,setupCompleted:!0,createdAt:xt.exists()?Number(((Je=xt.val())==null?void 0:Je.createdAt)||te):te,updatedAt:te};ue("Saving user profileâ¦"),await Pn(re(ie,`users/${le}`),Ge),ue("Finalizingâ¦"),await qe("User creation audit",ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"user.created",entityType:"user",entityId:le,branchId:Ge.branchId,summary:nt?`Linked existing Firebase login ${De}`:`Created user ${De}`,metadata:{linkedExistingAuth:nt,email:Te,role:de.role,roleTemplateId:de.roleTemplateId||"",branchId:Ge.branchId,branchIds:Ge.branchIds||[],allBranches:Ge.allBranches||!1,active:de.active,employeeId:de.employeeId||""}})),ge(!1),Be(),ue(""),window.alert(nt?`${De} existing Firebase login-à¦à¦° সাথৠVERIXO user হিসà§à¦¬à§ link হà§à§à¦à§à¥¤`:`${De} user created successfully. Temporary password user-à¦à§ দিন.`)}catch(le){console.error("User creation failed:",le);const nt=le instanceof ku?le.code:"";let xt=le instanceof Error?le.message:"Unknown Firebase error";nt==="INVALID_PASSWORD"||nt==="INVALID_LOGIN_CREDENTIALS"?(qe("Existing-user password reset email",a1(gb(),Te)),xt="à¦à¦ Email Firebase Authentication-ঠà¦à¦à§ থà§à¦à§à¦ à¦à¦à§, à¦à¦¿à¦¨à§à¦¤à§ দà§à§à¦¾ Temporary Password মিলà¦à§ না। Password reset email পাঠানà§à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à¦¾ হà§à§à¦à§à¥¤ Reset à¦à¦°à§ তারপর à¦à¦¬à¦¾à¦° Link/Create à¦à¦°à§à¦¨à¥¤"):nt==="REQUEST_TIMEOUT"?xt="Firebase Authentication নিরà§à¦§à¦¾à¦°à¦¿à¦¤ সমà§à§à¦° মধà§à¦¯à§ response দà§à§à¦¨à¦¿à¥¤ à¦à§à¦¨à§ endless Creating থাà¦à¦¬à§ না। Internet check à¦à¦°à§ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤":nt==="EMAIL_NOT_FOUND"?xt="Firebase login create/recovery সমà§à¦ªà¦¨à§à¦¨ হà§à¦¨à¦¿à¥¤ Internet check à¦à¦°à§ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤":nt==="WEAK_PASSWORD"?xt="Firebase password policy ঠনà§à¦¯à¦¾à§à§ à¦à¦°à¦ শà¦à§à¦¤à¦¿à¦¶à¦¾à¦²à§ password দিন।":nt==="OPERATION_NOT_ALLOWED"&&(xt="Firebase Authentication-ঠEmail/Password sign-in enabled নà§à¦à¥¤ Firebase Console থà§à¦à§ Email/Password provider enable à¦à¦°à§à¦¨à¥¤"),window.alert(`User create à¦à¦°à¦¾ যাà§à¦¨à¦¿: ${xt}`)}finally{V(!1),ue("")}},pe=async Ce=>{if(window.confirm(`${Ce.email}-ঠpassword reset link পাঠাবà§à¦¨?`)){V(!0);try{await a1(gb(),Ce.email),await yn(re(ie,`users/${Ce.uid}`),{forcePasswordChange:!0,updatedAt:Date.now()}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"user.password_reset_sent",entityType:"user",entityId:Ce.uid,branchId:Ce.branchId,summary:`Sent password reset email to ${Ce.name}`}),window.alert("Password reset email পাঠানৠহà§à§à¦à§à¥¤")}catch(De){console.error("Password reset failed:",De);const Te=De instanceof Error?De.message:"Unknown Firebase error";window.alert(`Password reset email পাঠানৠযাà§à¦¨à¦¿: ${Te}`)}finally{V(!1)}}},Se=Ce=>{J(Ce),G(Ce.role),H(Ce.roleTemplateId||""),L(Ce.branchId||""),M(_h(Ce)),fe(Sp(Ce)),ne(Ce.active),Y(D_(Ce.permissionOverrides))},Me=async()=>
3994{if(!_)return;const Ce=a.filter(De=>De.role==="owner"&&De.active);if(_.uid===t.uid){if(!q){window.alert("নিà¦à§à¦° Login account Inactive à¦à¦°à¦¾ যাবৠনা।");return}if(_.role==="owner"&&T!=="owner"){window.alert("বরà§à¦¤à¦®à¦¾à¦¨ Owner নিà¦à§à¦° Owner role সরাতৠপারবৠনা।");return}}if(_.role==="owner"&&Ce.length===1&&(T!=="owner"||!q)){window.alert("Company-র শà§à¦· Active Owner account পরিবরà§à¦¤à¦¨ à¦à¦°à¦¾ যাবৠনা।");return}if(T==="owner"&&t.role!=="owner"){window.alert("শà§à¦§à§ Owner à¦
নà§à¦¯ user-à¦à§ Owner role দিতৠপারবà§à¥¤");return}if(!["owner","super_admin"].includes(T)&&!Z&&D.length===0){window.alert("à¦à¦ role-à¦à¦° à¦à¦¨à§à¦¯ à¦
নà§à¦¤à¦¤ à¦à¦à¦à¦¿ Branch select à¦à¦°à§à¦¨ à¦
থবা All Branches দিন।");return}V(!0);try{const De=T==="owner"||T==="super_admin"?!0:Z,Te=De?[]:D,ce=De?"":Te[0]||K,Ye=We(z),Je=Ye?Object.fromEntries(Lm.map(B=>[B,Ye.capabilities.includes(B)])):ae,le=T==="owner"||T==="super_admin"?{}:k_(Je),nt=re(ie,`users/${_.uid}`);await yn(nt,{role:T,roleTemplateId:z||"",branchId:ce,branchIds:Te,allBranches:De,active:q,permissionOverrides:le,updatedAt:Date.now()});const xt=await mn(nt);if(!xt.exists())throw new Error("Saved user record could not be read back.");const te=xt.val(),Ge=E_(Te),pt=E_(te.branchIds),$e=D_(te.permissionOverrides),st=T==="owner"||T==="super_admin"?{}:Je,Nt=te.role===T&&(te.roleTemplateId||"")===(z||""),be=!!te.active===q,jt=!!te.allBranches===De,bt=Ge.length===pt.length&&Ge.every((B,xe)=>B===pt[xe]),tn=J7($e,st);if(!Nt||!be||!jt||!bt||!tn)throw console.error("User access read-back mismatch",{expected:{role:T,active:q,allBranches:De,branchIds:Ge,permissionOverrides:st},actual:{role:te.role,active:te.active,allBranches:te.allBranches,branchIds:pt,permissionOverrides:$e}}),new Error("Saved data verification failed. Please reload the user and try again.");await qe("User permission audit",ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"user.permission_updated",entityType:"user",entityId:_.uid,branchId:ce,summary:`Updated role and branch access for ${_.name}`,metadata:{role:T,branchId:ce,branchIds:Te,allBranches:De,active:q,permissionOverrides:le}})),J(null),F({type:"success",title:"Permissions Saved Successfully",message:`${_.name}-à¦à¦° Role, Branch Access à¦à¦¬à¦ Individual Permissions successfully updated.`})}catch(De){console.error("User access save failed:",De);const Te=De instanceof Error?De.message:"Unknown Firebase error";F({type:"error",title:"Permission Save Failed",message:`User access save à¦à¦°à¦¾ যাà§à¦¨à¦¿: ${Te}`})}finally{V(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-header permission-page-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"System Security"}),e.jsx("h1",{children:"User & Role Permissions"}),e.jsx("p",{children:"Login user তà§à¦°à¦¿ à¦à¦°à§à¦¨ à¦à¦¬à¦ role, branch access ঠactive status নিà§à¦¨à§à¦¤à§à¦°à¦£ à¦à¦°à§à¦¨à¥¤"})]}),e.jsxs("div",{className:"permission-header-actions",children:[e.jsxs("button",{type:"button",className:"permission-manage-roles-button",onClick:()=>m(!0),children:[e.jsx(gs,{size:18})," Manage Roles"]}),e.jsxs("button",{className:"primary-action-button",onClick:()=>{Be(),ge(!0)},children:[e.jsx(e2,{size:18})," Add User"]})]})]}),e.jsxs("section",{className:"permission-summary-grid",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Total Users"}),e.jsx("strong",{children:a.length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Active Users"}),e.jsx("strong",{children:Ee})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Branches"}),e.jsx("strong",{children:n.length})]})]}),e.jsxs("section",{className:"role-template-strip",children:[e.jsxs("div",{children:[e.jsx(gs,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Role Templates Active"}),e.jsx("span",{children:"Sidebar, page access, branch access à¦à¦¬à¦ action permission selected Role à¦
নà§à¦¯à¦¾à§à§ control হবà§à¥¤"})]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Reception"}),e.jsx("span",{children:"Technician"}),e.jsx("span",{children:"Accounts"}),e.jsx("span",{children:"Branch Executive"}),e.jsx("span",{children:"Manager"}),e.jsx("span",{children:"Admin"})]})]}),e.jsx("section",{className:"permission-data-card",children:e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"User / Employee"}),e.jsx("th",{children:"Email"}),e.jsx("th",{children:"Role"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Last Login"}),e.jsx("th",{children:"Access Summary"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[a.map(Ce=>{var De,Te,ce;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsxs("strong",{children:[Ce.name,Ce.role==="owner"&&e.jsx("span",{className:"owner-protected-label",children:"Protected"})]}),e.jsx("small",{children:((De=Re.find(Ye=>
3994Ye.id===Ce.employeeId))==null?void 0:De.employeeId)||((Te=Re.find(Ye=>Ye.id===Ce.employeeId))==null?void 0:Te.designation)||(Ce.employeeId?"Linked Employee":"Not linked")})]}),e.jsx("td",{children:Ce.email}),e.jsx("td",{children:it(Ce)}),e.jsx("td",{children:Sp(Ce)?"All Branches":_h(Ce).length>1?`${_h(Ce).length} Branches`:((ce=n.find(Ye=>Ye.id===_h(Ce)[0]))==null?void 0:ce.name)||"Not assigned"}),e.jsx("td",{children:e.jsx("span",{className:`permission-status ${Ce.active?"active":"inactive"}`,children:Ce.active?"Active":"Inactive"})}),e.jsx("td",{children:Ce.lastLoginAt?new Date(Ce.lastLoginAt).toLocaleString("en-GB"):"Never"}),e.jsxs("td",{children:[Lm.filter(Ye=>sa(Ce,Ye)).length," capabilities"]}),e.jsx("td",{children:e.jsxs("div",{className:"action-buttons",children:[e.jsx("button",{onClick:()=>void pe(Ce),title:"Send password reset email",children:e.jsx(DD,{size:17})}),e.jsx("button",{onClick:()=>Se(Ce),title:"Edit permission",children:e.jsx(Zi,{size:17})})]})})]},Ce.uid)}),!a.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty-table",children:"No users found."})})]})]})})}),l&&e.jsx("div",{className:"modal-backdrop",children:e.jsxs("section",{className:"role-manager-modal",onMouseDown:Ce=>Ce.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Dynamic Access Control"}),e.jsx("h2",{children:"Manage Roles"})]}),e.jsx("button",{type:"button",onClick:()=>m(!1),children:e.jsx(ja,{size:18})})]}),e.jsxs("div",{className:"role-manager-form",children:[e.jsxs("label",{children:["Role Name *",e.jsx("input",{value:d,onChange:Ce=>u(Ce.target.value),placeholder:"e.g. Purchase Manager"})]}),e.jsxs("label",{children:["Base Role / Dashboard *",e.jsx("select",{value:f,onChange:Ce=>{const De=Ce.target.value;g(De),y(Bm(De))},children:Q7.map(Ce=>e.jsx("option",{value:Ce.value,children:Ce.label},Ce.value))})]}),e.jsxs("div",{className:"full-field",children:[e.jsx("strong",{children:"Permissions"}),e.jsx("div",{className:"role-manager-permissions",children:Lm.map(Ce=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:p.includes(Ce),onChange:De=>y(Te=>De.target.checked?[...Te,Ce]:Te.filter(ce=>ce!==Ce))}),e.jsx("span",{children:bI[Ce]})]},Ce))})]})]}),e.jsxs("div",{className:"role-manager-list",children:[e.jsx("h3",{children:"Custom Roles"}),i.length===0?e.jsx("p",{className:"muted",children:"à¦à¦à¦¨à¦ à¦à§à¦¨à§ Custom Role তà§à¦°à¦¿ হà§à¦¨à¦¿à¥¤"}):i.map(Ce=>{const De=a.filter(Te=>Te.roleTemplateId===Ce.id).length;return e.jsxs("div",{className:"role-manager-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:Ce.name}),e.jsxs("span",{children:[jh[Ce.baseRole]," base · ",Ce.capabilities.length," permissions · ",De," user"]})]}),e.jsx("button",{type:"button",disabled:De>0,title:De>0?"Assigned role delete à¦à¦°à¦¾ যাবৠনা":"Delete role",onClick:()=>void ee(Ce),children:e.jsx(po,{size:17})})]},Ce.id)})]}),e.jsxs("div",{className:"role-manager-footer",children:[e.jsx("button",{type:"button",className:"role-manager-cancel",onClick:()=>m(!1),children:"Cancel"}),e.jsxs("button",{type:"button",className:"primary-action-button",disabled:b,onClick:()=>void _e(),children:[b?e.jsx(Hi,{size:17,className:"spin"}):e.jsx(as,{size:17})," ",b?"Saving...":"Add Role"]})]})]})}),me&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>ge(!1),children:e.jsxs("section",{className:"modal permission-modal",onMouseDown:Ce=>Ce.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"User Account"}),e.jsx("h2",{children:"Add User"})]}),e.jsx("button",{onClick:()=>ge(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:se,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"full-field",children:["Link Employee",e.jsxs("select",{value:de.employeeId,onChange:Ce=>{const De=Ce.target.value;if(De==="__standalone__"){Pe({...de,employeeId:"",name:"",email:"",branchId:"",branchIds:[],allBranches:!1,role:"reception"});return}const Te=Re.find(ce=>ce.id===De);Pe({...de,employeeId:De,name:(Te==null?void 0:Te.name)||"",email:(Te==null?void 0:Te.email)||"",branchId:(Te==null?void 0:Te.branchId)||"",branchIds:Te!=null&&Te.branchId?[Te.branchId]:[],allBranches:!1,role:K7(Te)})},children:[e.jsx("option",{value:"",children:"Select Employee..."}),Re.filter(Ce=>!a.some(De=>De.employeeId===Ce.id)).map(Ce=>e.jsxs("option",{value:Ce.id,children:[Ce.name,Ce.employeeId?` â ${
3994Ce.employeeId}`:"",Ce.designation?` â ${Ce.designation}`:"",Ce.source==="legacy_technician"?" â Legacy Technician":""]},Ce.id)),e.jsx("option",{value:"__standalone__",children:"Create Standalone Login (No Employee)"})]}),e.jsx("small",{className:"field-help",children:"Employee select à¦à¦°à¦²à§ Name, Email, Branch à¦à¦¬à¦ à¦à¦à¦à¦¿ suggested Role fill হবà§à¥¤ à¦à¦à¦¿ শà§à¦§à§ initial suggestion; Designation পরিবরà§à¦¤à¦¨à§ login Role/Permission auto-change হবৠনা।"})]}),e.jsxs("label",{children:["Full Name *",e.jsx("input",{value:de.name,onChange:Ce=>Pe({...de,name:Ce.target.value}),required:!0})]}),e.jsxs("label",{children:["Login Email *",e.jsx("input",{type:"email",value:de.email,onChange:Ce=>Pe({...de,email:Ce.target.value}),required:!0})]}),e.jsxs("label",{children:["Temporary Password *",e.jsxs("div",{className:"temporary-password-field",children:[e.jsx("input",{type:"text",minLength:6,value:de.password,onChange:Ce=>Pe({...de,password:Ce.target.value}),required:!0}),e.jsx("button",{type:"button",title:"Generate password",onClick:()=>Pe({...de,password:Pj()}),children:e.jsx(Hi,{size:16})}),e.jsx("button",{type:"button",title:"Copy password",onClick:()=>{navigator.clipboard.writeText(de.password),window.alert("Temporary password copied.")},children:e.jsx(sp,{size:16})})]})]}),e.jsxs("label",{children:["Role *",e.jsxs("select",{value:de.roleTemplateId?`custom:${de.roleTemplateId}`:`system:${de.role}`,onChange:Ce=>{const[De,Te]=Ce.target.value.split(":"),ce=De==="custom"?We(Te):void 0,Ye=(ce==null?void 0:ce.baseRole)||Te,Je=["owner","super_admin"].includes(Ye);Pe({...de,role:Ye,roleTemplateId:(ce==null?void 0:ce.id)||"",allBranches:Je?!0:de.allBranches,branchIds:Je?[]:de.branchIds,branchId:Je?"":de.branchId})},children:[e.jsx("optgroup",{label:"System Roles",children:__.filter(Ce=>Ce!=="owner"||t.role==="owner").map(Ce=>e.jsx("option",{value:`system:${Ce}`,children:jh[Ce]},Ce))}),i.length>0&&e.jsx("optgroup",{label:"Custom Roles",children:i.map(Ce=>e.jsx("option",{value:`custom:${Ce.id}`,children:Ce.name},Ce.id))})]})]}),de.role==="service_incharge"&&e.jsxs("div",{className:"service-incharge-note full-field",children:[e.jsx("strong",{children:"Service In-Charge Access"}),e.jsx("span",{children:"Service Operations, Technician Assignment, Estimate, QC, Ready, Delivery, Service Performance ঠAudit access থাà¦à¦¬à§à¥¤ Finance, HR, Company Settings à¦à¦¬à¦ User Management থাà¦à¦¬à§ না।"})]}),e.jsxs("div",{className:"full-field branch-access-editor",children:[e.jsx("strong",{children:"Branch Access *"}),e.jsxs("label",{className:"branch-access-all",children:[e.jsx("input",{type:"checkbox",checked:["owner","super_admin"].includes(de.role)||de.allBranches,disabled:["owner","super_admin"].includes(de.role),onChange:Ce=>Pe({...de,allBranches:Ce.target.checked,branchIds:Ce.target.checked?[]:de.branchIds,branchId:Ce.target.checked?"":de.branchId})}),e.jsx("span",{children:"All Branches"})]}),!(["owner","super_admin"].includes(de.role)||de.allBranches)&&e.jsx("div",{className:"branch-access-options",children:n.filter(Ce=>Ce.active).map(Ce=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:de.branchIds.includes(Ce.id),onChange:De=>{const Te=De.target.checked?[...de.branchIds,Ce.id]:de.branchIds.filter(ce=>ce!==Ce.id);Pe({...de,branchIds:Te,branchId:Te[0]||""})}}),e.jsx("span",{children:Ce.name})]},Ce.id))}),e.jsx("small",{className:"field-help",children:"à¦à¦ বা à¦à¦à¦¾à¦§à¦¿à¦ branch select à¦à¦°à§à¦¨à¥¤ All Branches দিলৠবরà§à¦¤à¦®à¦¾à¦¨ ঠà¦à¦¬à¦¿à¦·à§à¦¯à¦¤à§à¦° সব branch access থাà¦à¦¬à§à¥¤"})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:de.active?"active":"inactive",onChange:Ce=>Pe({...de,active:Ce.target.value==="active"}),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]}),e.jsxs("div",{className:"permission-capability-box full-field",children:[e.jsxs("div",{children:[e.jsx(gs,{size:19}),e.jsxs("strong",{children:[((ot=We(de.roleTemplateId))==null?void 0:ot.name)||jh[de.role]," Acce
3994ss"]})]}),e.jsx("div",{children:(((wt=We(de.roleTemplateId))==null?void 0:wt.capabilities)||Bm(de.role)).map(Ce=>e.jsx("span",{children:Ce.replace("."," · ")},Ce))})]})]}),e.jsxs("div",{className:"permission-security-note",children:[e.jsx(Gh,{size:18}),e.jsx("span",{children:"User পà§à¦°à¦¥à¦® login-ঠtemporary password বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à¦¬à§à¥¤ Login-à¦à¦° পর password reset email দিà§à§ নিà¦à¦¸à§à¦¬ password set à¦à¦°à¦¾à¦¨à§ à¦à¦¾à¦²à§à¥¤"})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary secondary-button",onClick:()=>ge(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"vx-button vx-button-primary",disabled:je,children:[e.jsx(as,{size:17}),je?P||"Creating userâ¦":"Create User"]})]})]})]})}),$&&e.jsx("div",{className:"modal-backdrop permission-notice-backdrop",onMouseDown:()=>F(null),children:e.jsxs("section",{className:`modal permission-notice-modal ${$.type}`,onMouseDown:Ce=>Ce.stopPropagation(),role:"dialog","aria-modal":"true","aria-labelledby":"permission-notice-title",children:[e.jsx("div",{className:`permission-notice-icon ${$.type}`,children:$.type==="success"?e.jsx(Ms,{size:28}):e.jsx(L4,{size:28})}),e.jsxs("div",{className:"permission-notice-content",children:[e.jsx("p",{className:"eyebrow",children:$.type==="success"?"VERIXO CONFIRMATION":"ACTION REQUIRED"}),e.jsx("h2",{id:"permission-notice-title",children:$.title}),e.jsx("p",{children:$.message})]}),e.jsx("div",{className:"modal-actions permission-notice-actions",children:e.jsx("button",{type:"button",className:"vx-button vx-button-primary",onClick:()=>F(null),autoFocus:!0,children:$.type==="success"?"Done":"Close"})})]})}),_&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>J(null),children:e.jsxs("section",{className:"modal permission-modal",onMouseDown:Ce=>Ce.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"User Access"}),e.jsx("h2",{children:_.name})]}),e.jsx("button",{onClick:()=>J(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("div",{className:"role-access-card full-field",children:[e.jsxs("div",{className:"role-access-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"role-access-kicker",children:"Role Template"}),e.jsx("strong",{children:jh[T]}),e.jsx("small",{children:"Role change à¦à¦°à¦²à§ নতà§à¦¨ role-à¦à¦° default permissions apply হবà§à¥¤ পরৠনিà¦à§ individual permission customize à¦à¦°à¦¾ যাবà§à¥¤"})]}),e.jsxs("span",{className:"role-capability-count",children:[(((ct=We(z))==null?void 0:ct.capabilities)||Bm(T)).length," permissions"]})]}),e.jsxs("label",{className:"role-select-field",children:[e.jsx("span",{children:"Assigned Role"}),e.jsxs("select",{value:z?`custom:${z}`:`system:${T}`,onChange:Ce=>{const[De,Te]=Ce.target.value.split(":"),ce=De==="custom"?We(Te):void 0,Ye=(ce==null?void 0:ce.baseRole)||Te;G(Ye),H((ce==null?void 0:ce.id)||""),Y(ce?Object.fromEntries(Lm.map(Je=>[Je,ce.capabilities.includes(Je)])):{}),["owner","super_admin"].includes(Ye)&&(fe(!0),M([]),L(""))},children:[e.jsx("optgroup",{label:"System Roles",children:__.filter(Ce=>Ce!=="owner"||t.role==="owner"||_.role==="owner").map(Ce=>e.jsx("option",{value:`system:${Ce}`,children:jh[Ce]},Ce))}),i.length>0&&e.jsx("optgroup",{label:"Custom Roles",children:i.map(Ce=>e.jsx("option",{value:`custom:${Ce.id}`,children:Ce.name},Ce.id))})]})]})]}),e.jsxs("div",{className:"full-field branch-access-editor",children:[e.jsx("strong",{children:"Branch Access"}),e.jsxs("label",{className:"branch-access-all",children:[e.jsx("input",{type:"checkbox",checked:["owner","super_admin"].includes(T)||Z,disabled:["owner","super_admin"].includes(T),onChange:Ce=>{fe(Ce.target.checked),Ce.target.checked&&(M([]),L(""))}}),e.jsx("span",{children:"All Branches"})]}),!(["owner","super_admin"].includes(T)||Z)&&e.jsx("div",{className:"branch-access-options",children:n.filter(Ce=>Ce.active).map(Ce=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:D.includes(Ce.id),onChange:De=>{const Te=De.target.checked?[...D,Ce.id]:D.filter(ce=>ce!==Ce.id);M(Te),L(Te[0]||"")}}),e.jsx("span",{children:Ce.name})]},Ce.id))}),e.jsx("small",{className:"field-help",children:"Admin-à¦à§ পà§à¦°à§à§à¦à¦¨ à¦
নà§à¦¯à¦¾à§à§ à¦à¦, à¦à¦à¦¾à¦§à¦¿à¦ à¦
থবা সব branch access দিতৠপারবà§à¦¨à¥¤"})]}),e.jsxs("label",{children:["Login Status",e.jsxs("select",{value:q?"active":"inactive",onChange:Ce=>ne(Ce.target.value==="active"),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]}),e.jsxs("div",{className:"permission-capability-box full-field",children:[e.jsxs("div",{children:[e.jsx(gs,{size:19}),e.jsx("strong",{children:"Individual Permissions"})]}),e.jsx("small",{className:"field-help",children:"Role শà§à¦§à§ default template। নিà¦à§ পà§à¦°à¦¤à¦¿à¦à¦¿ permission à¦à¦²à¦¾à¦¦à¦¾ à¦à¦°à§ On/Off à¦à¦°à¦¾ যাবà§à¥¤ Designation পরিবরà§à¦¤à¦¨ à¦à¦°à¦²à§ à¦à¦ permissions নিà¦à§ থà§à¦à§ পরিবরà§à¦¤à¦¨ হবৠনা।"}),e.jsx("div",{className:"individual-permission-checklist",children:Lm.map(Ce=>{const De=Bm(T).includes(Ce),Te=ae[Ce],ce=typeof Te=="boolean"?Te:De,Ye=T==="owner"||T==="super_admin";return e.jsxs("label",{className:"individual-permission-check-row",children:[e.jsx("input",{type:"checkbox",checked:Ye?!0:ce,disabled:Ye,onChange:Je=>Y(le=>({...le,[Ce]:Je.target.checked}))}),e.jsxs("span",{children:[e.jsx("strong",{children:bI[Ce]}
3994),e.jsx("small",{children:typeof Te=="boolean"?"Custom":De?"Role default: On":"Role default: Off"})]})]},Ce)})}),T!=="owner"&&T!=="super_admin"&&e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>Y({}),children:"Reset to Role Defaults"})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"vx-button vx-button-secondary secondary-button",onClick:()=>J(null),children:"Cancel"}),e.jsxs("button",{className:"vx-button vx-button-primary",onClick:()=>void Me(),disabled:je,children:[e.jsx(hr,{size:17}),je?"Savingâ¦":"Save Permission"]})]})]})})]})}const Vo={service:{id:"service",name:"Service Operations",description:"Service receive, diagnosis, estimate, repair, quality check and delivery.",defaultEnabled:!0,lifecycle:"stable",requiredCapabilities:["job.read"],dependencies:["crm"]},crm:{id:"crm",name:"CRM",description:"Customer master, customer history and service relationship management.",defaultEnabled:!0,lifecycle:"stable",requiredCapabilities:["customer.read"],dependencies:[]},finance:{id:"finance",name:"Finance",description:"Invoices, collections and service-related financial transactions.",defaultEnabled:!0,lifecycle:"stable",requiredCapabilities:["finance.read"],dependencies:["crm","service"]},reports:{id:"reports",name:"Reports & Analytics",description:"Service, collection, due, customer and branch performance reports.",defaultEnabled:!0,lifecycle:"stable",requiredCapabilities:["performance.read"],dependencies:["service","crm"]},performance:{id:"performance",name:"Performance",description:"Service performance, sales performance and leaderboard.",defaultEnabled:!0,lifecycle:"stable",requiredCapabilities:["performance.read"],dependencies:["service"]},hr:{id:"hr",name:"HR",description:"Employee master and people administration foundation.",defaultEnabled:!0,lifecycle:"beta",requiredCapabilities:["employee.read"],dependencies:[]},attendance:{id:"attendance",name:"Attendance",description:"Daily attendance, shifts, holidays, late and missing-punch management.",defaultEnabled:!0,lifecycle:"beta",requiredCapabilities:["employee.read"],dependencies:["hr"]},rma:{id:"rma",name:"RMA & Warranty",description:"Customer and supplier warranty claims, serial tracking and replacement workflow.",defaultEnabled:!0,lifecycle:"beta",requiredCapabilities:["job.read"],dependencies:[]},inventory:{id:"inventory",name:"Inventory",description:"Product, supplier, purchase, stock, serial number and warranty.",defaultEnabled:!1,lifecycle:"planned",requiredCapabilities:[],dependencies:[]},sales:{id:"sales",name:"Sales & POS",description:"Sales invoice, POS, sales return, barcode and customer due.",defaultEnabled:!1,lifecycle:"planned",requiredCapabilities:[],dependencies:["crm","inventory"]},payroll:{id:"payroll",name:"Payroll",description:"Attendance-linked salary structure, monthly payroll processing, approval and locking.",defaultEnabled:!0,lifecycle:"beta",requiredCapabilities:["employee.read"],dependencies:["hr","attendance"]}},cl=Object.keys(Vo),m2=cl.reduce((t,n)=>(t[n]=Vo[n].defaultEnabled,t),{});function Pp(t){return{...m2,...t||{}}}function eU(t,n){return Pp(t)[n]}function J1(t,n){const a=Pp(t);return Vo[n].dependencies.filter(s=>!a[s])}function tU(t){const n=Pp(t),a={};return cl.forEach(s=>{if(!n[s])return;const i=J1(n,s);i.length&&(a[s]=i)}),{valid:Object.keys(a).length===0,missingDependencies:a}}function zE(t){const n=Pp(t);return cl.forEach(a=>{const s=Vo[a];if(s.lifecycle==="planned"){n[a]=!1;return}n[a]&&s.dependencies.forEach(i=>{n[i]=!0})}),n}function zf(t){const n=Pp(t),a=tU(n),s=cl.filter(i=>Vo[i].lifecycle==="planned"&&n[i]);return{healthy:a.valid&&s.length===0,enabledCount:cl.filter(i=>n[i]).length,disabledCount:cl.filter(i=>!n[i]).length,plannedEnabled:s,missingDependencies:a.missingDependencies}}function Rj(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}function R_(t){return(t.trim().split(/\s+/).filter(Boolean).map(s=>s[0]).join("")||t).replace(/[^a-z0-9]/gi,"").slice(0,6).toUpperCase()}function nU(){const t="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",n="!@#$",a=new Uint32Array(10);crypto.getRandomValues(a);const s=Array.from(a,i=>t[i%t.length]);return s[2]=n[a[2]%n.length],s[6]=String(a[6]%10),s.join("")}const Tj=()=>({name:"",code:"",slug:"",phone:"",email:"",address:"Dhaka, Bangladesh",ownerName:"",ownerEmail:"",ownerPassword:nU(),branchName:"Main Branch",branchCode:"MAIN-01",plan:"trial",subscriptionExpiry:"",active:!0});function aU({profile:t}){const[n,a]=x.useState([]),[s,i]=x.useState(!1),[c,l]=x.useState(null),[m,d]=x.useState(Tj()),[u,f]=x.use
3994State(!1),[g,p]=x.useState(""),[y,b]=x.useState(null),[N,w]=x.useState(m2),[C,R]=x.useState(!1);x.useEffect(()=>qt(re(ie,"companies"),M=>{if(!M.exists())return a([]);const Z=M.val();a(Object.entries(Z).map(([fe,q])=>({...q,id:fe})).sort((fe,q)=>fe.name.localeCompare(q.name)))}),[]);const I=x.useMemo(()=>{const M=g.trim().toLowerCase();return M?n.filter(Z=>[Z.name,Z.companyCode,Z.slug,Z.ownerEmail].filter(Boolean).some(fe=>String(fe).toLowerCase().includes(M))):n},[n,g]),_=n.filter(M=>M.active).length,J=n.filter(M=>M.plan==="trial").length,T=M=>{b(M),w(Pp(M.features))},G=M=>{const Z=Vo[M];if(Z.lifecycle==="planned"){window.alert(`${Z.name} à¦à¦à¦¨ Planned ঠবসà§à¦¥à¦¾à§ à¦à¦à§à¥¤ Module তà§à¦°à¦¿ হলৠà¦à¦à¦¿ activate à¦à¦°à¦¾ যাবà§à¥¤`);return}w(fe=>{const q={...fe,[M]:!fe[M]};return q[M]&&Z.dependencies.forEach(ne=>{q[ne]=!0}),q})},z=async()=>{if(!y||t.role!=="super_admin")return;const M=zE(N),Z=zf(M),fe=cl.filter(ne=>M[ne]),q=fe.flatMap(ne=>{const ae=J1(N,ne);return ae.length?[`${Vo[ne].name}: ${ae.map(Y=>Vo[Y].name).join(", ")}`]:[]});if(q.length){window.alert(`Dependency missing: 3995${q.join(` 3996`)}`);return}R(!0);try{const ne=Date.now();await yn(re(ie,`companies/${y.id}`),{features:M,featureSchemaVersion:3,featureHealth:{healthy:Z.healthy,enabledCount:Z.enabledCount,disabledCount:Z.disabledCount,checkedAt:ne},updatedAt:ne}),await yn(re(ie,`settings/${y.id}/features`),{...M,schemaVersion:3,registryVersion:"4.2.0",health:{healthy:Z.healthy,enabledCount:Z.enabledCount,disabledCount:Z.disabledCount,plannedEnabled:Z.plannedEnabled,missingDependencies:Z.missingDependencies,checkedAt:ne},updatedAt:ne}),await ia({companyId:y.id,actorUid:t.uid,actorName:t.name,action:"company.modules_updated",entityType:"company",entityId:y.id,summary:`Updated modules for ${y.name}`,metadata:{enabledModules:fe,featureSchemaVersion:3,featureHealth:Z.healthy}}),b(null),window.alert("Company module settings saved.")}catch(ne){console.error("Module settings save failed:",ne),window.alert("Module settings save à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤")}finally{R(!1)}},H=M=>{d(Z=>({...Z,name:M,code:Z.code||R_(M),slug:Z.slug||Rj(M)}))},K=()=>{l(null),d(Tj()),i(!0)},L=M=>{l(M),d({name:M.name,code:M.companyCode||"",slug:M.slug||"",phone:M.phone||"",email:M.email||"",address:M.address||"",ownerName:M.ownerName||"",ownerEmail:M.ownerEmail||"",ownerPassword:"",branchName:"Main Branch",branchCode:"MAIN-01",plan:M.plan||"trial",subscriptionExpiry:M.subscriptionExpiry||"",active:M.active}),i(!0)},D=async M=>{if(M.preventDefault(),t.role!=="super_admin")return;const Z=m.name.trim(),fe=Rj(m.slug||Z),q=(m.code||R_(Z)).trim().toUpperCase(),ne=m.ownerEmail.trim().toLowerCase();if(!Z||!fe||!q){window.alert("Company Name, Code à¦à¦¬à¦ Slug required.");return}f(!0);try{if(c){const ae=c.slug||"";if(fe!==ae){const je=await mn(re(ie,`companyDirectory/${fe}`));if(je.exists()&&je.val().id!==c.id){window.alert("à¦à¦ Company Slug à¦à¦à§ থà§à¦à§à¦ বà§à¦¯à¦¬à¦¹à¦¾à¦° হà¦à§à¦à§à¥¤");return}}const Y={...c,name:Z,companyCode:q,slug:fe,phone:m.phone.trim(),email:m.email.trim(),address:m.address.trim(),ownerName:m.ownerName.trim(),ownerEmail:ne,plan:m.plan,subscriptionExpiry:m.subscriptionExpiry,active:m.active,updatedAt:Date.now()};await Pn(re(ie,`companies/${c.id}`),Y),ae&&ae!==fe&&await Pn(re(ie,`companyDirectory/${ae}`),null),await Pn(re(ie,`companyDirectory/${fe}`),{id:c.id,name:Z,slug:fe,active:m.active,plan:m.plan,subscriptionExpiry:m.subscriptionExpiry}),await Pn(re(ie,`subscriptions/${c.id}`),{companyId:c.id,plan:m.plan,expiryDate:m.subscriptionExpiry,active:m.active,updatedAt:Date.now()}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"company.updated",entityType:"company",entityId:c.id,summary:`Updated company ${Z}`,metadata:{slug:fe,code:q,plan:m.plan,active:m.active}})}else{if(!m.ownerName.trim()||!ne||m.ownerPassword.length<6){window.alert("Owner Name, Owner Email à¦à¦¬à¦ minimum 6 character password required.");return}if((await mn(re(ie,`companyDirectory/${fe}
3996`))).exists()){window.alert("à¦à¦ Company Slug à¦à¦à§ থà§à¦à§à¦ বà§à¦¯à¦¬à¦¹à¦¾à¦° হà¦à§à¦à§à¥¤");return}const Y=`company_${fe}_${Date.now()}`,je=`branch_${Date.now()}`,V={...ux.firebase};if(!String(V.apiKey||"").trim())throw new Error("VERIXO Firebase API key is missing from runtime configuration.");const $=aw(V,`verixo-company-owner-${Date.now()}`),F=gb($);let P=null;try{P=await WM(F,ne,m.ownerPassword),await QM(P.user,{displayName:m.ownerName.trim()});const ue=Date.now(),me={id:Y,name:Z,companyCode:q,slug:fe,phone:m.phone.trim(),email:m.email.trim(),address:m.address.trim(),ownerUid:P.user.uid,ownerName:m.ownerName.trim(),ownerEmail:ne,plan:m.plan,subscriptionExpiry:m.subscriptionExpiry,createdByUid:t.uid,active:m.active,createdAt:ue,updatedAt:ue};await Pn(re(ie,`companies/${Y}`),me),await Pn(re(ie,`companyDirectory/${fe}`),{id:Y,name:Z,slug:fe,active:m.active,plan:m.plan,subscriptionExpiry:m.subscriptionExpiry}),await Pn(re(ie,`branches/${Y}/${je}`),{id:je,companyId:Y,name:m.branchName.trim()||"Main Branch",code:m.branchCode.trim().toUpperCase()||"MAIN-01",managerName:m.ownerName.trim(),phone:m.phone.trim(),address:m.address.trim(),active:!0,createdAt:ue,updatedAt:ue}),await Pn(re(ie,`users/${P.user.uid}`),{uid:P.user.uid,name:m.ownerName.trim(),email:ne,role:"owner",companyId:Y,branchId:je,active:!0,forcePasswordChange:!0,setupCompleted:!0,createdAt:ue,updatedAt:ue}),await Pn(re(ie,`dashboardStats/${Y}`),{todayReceived:0,pendingJobs:0,readyForDelivery:0,deliveredToday:0,totalCustomers:0,todayCollection:0,totalDue:0}),await Pn(re(ie,`settings/${Y}`),{currency:"BDT",timezone:"Asia/Dhaka",dateFormat:"DD/MM/YYYY",createdAt:ue}),await Pn(re(ie,`subscriptions/${Y}`),{companyId:Y,plan:m.plan,expiryDate:m.subscriptionExpiry,active:m.active,createdAt:ue,updatedAt:ue}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"company.created",entityType:"company",entityId:Y,summary:`Created company ${Z}`,metadata:{slug:fe,code:q,ownerEmail:ne,plan:m.plan}}),await dl(F),await QS($),window.alert(`${Z} তà§à¦°à¦¿ হà§à§à¦à§à¥¤ 3997Login URL: ${window.location.origin}/login/${fe} 3998Temporary Password: ${m.ownerPassword}`)}catch(ue){if(P!=null&&P.user)try{await t$(P.user)}catch{}try{await dl(F),await QS($)}catch{}throw ue}}i(!1),l(null),d(Tj())}catch(ae){console.error("Company save failed:",ae);const Y=ae instanceof Error?ae.message:"Unknown Firebase error";window.alert(`Company save à¦à¦°à¦¾ যাà§à¦¨à¦¿: ${Y}`)}finally{f(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-header company-master-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Verixo Super Admin"}),e.jsx("h1",{children:"Company Master"}),e.jsx("p",{children:"Client company, owner login, subscription à¦à¦¬à¦ workspace manage à¦à¦°à§à¦¨à¥¤"})]}),e.jsxs("button",{className:"primary-action-button",onClick:K,children:[e.jsx(as,{size:18})," Add Company"]})]}),e.jsxs("section",{className:"company-master-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Total Companies"}),e.jsx("strong",{children:n.length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Active"}),e.jsx("strong",{children:_})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Trial"}),e.jsx("strong",{children:J})]})]}),e.jsxs("section",{className:"company-master-card",children:[e.jsx("div",{className:"company-master-search",children:e.jsx("input",{value:g,onChange:M=>p(M.target.value),placeholder:"Search company, code, slug or owner email"})}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Company"}),e.jsx("th",{children:"Owner"}),e.jsx("th",{children:"Plan"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Login URL"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[I.map(M=>{const Z=`${window.location.origin}/login/${M.slug||""}`;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:M.name}),e.jsxs("small",{children:[M.companyCode||"â"," · ",M.slug||"No slug"]})]}),e.jsxs("td",{children:[M.ownerName||"â",e.jsx("small",{children:M.ownerEmail||"â"})]}),e.jsx("td",{children:e.jsx("span",{className:"company-plan",children:M.plan||"trial"})}),e.jsx("td",{children:e.jsx("span",{className:`permission-status ${M.active?"active":"inactive"}`,children:M.active?"Active":"Suspended"})}),e.jsx("td",{children:e.jsxs("div",{className:"company-url-actions",children:[e.jsx("button",{title:"Copy URL",onClick:()=>void navigator.clipboard.writeText(Z),children:e.jsx(sp,{size:16})}),e.jsx("button",{title:"Open Login",onClick:()=>window.open(Z,"_blank","noopener,noreferrer"),children:e.jsx(ID,{size:16})})]})}),e.jsx("td",{children:e.jsxs("div",{className:"company-row-actions",children:[e.jsx("button",{className:"icon-action-button module-action-button",title:"Manage Modules",onClick:()=>T(M),children:e.jsx(Tu,{size:17})}),e.jsx("button",{className:"icon-action-button",title:"Edit Company",onClick:()=>L(M),children:e.jsx(Zi,{size:17})})]})})]},M.id)}),!I.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-table",children:"No companies found."})})]})]})})]}),y&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!C&&b(null),children:e.jsxs("section",{className:"modal company-modules-modal",onMouseDown:M=>M.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Company Module Manager"}),e.jsx("h2",{children:y.name}),e.jsx("span",{className:"module-manager-subtitle",children:"Registry v1 · Feature Schema v1"})]}),e.jsx("button",{disabled:C,onClick:()=>b(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"module-manager-summary",children:[e.jsxs("article",{children:[e.jsx("strong",{children:cl.filter(M=>N[M]).length}),e.jsx("span",{children:"Active Modules"})]}),e.jsxs("article",{children:[e.jsx("strong",{children:cl.filter(M=>Vo[M].lifecycle==="stable").length}),e.jsx("span",{children:"Stable"})]}),e.jsxs("article",{children:[e.jsx("strong",{children:cl.filter(M=>Vo[M].lifecycle==="planned").length}),e.jsx("span",{children:"Planned"})]})]}),e.jsxs("div",{className:`module-health-panel ${zf(N).healthy?"healthy":"warning"}`,children:[e.jsx(gs,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:zf(N).healthy?"Configuration Healthy":"Configuration Needs Review"}),e.jsx("span",{children:zf(N).healthy?"Dependencies, lifecycle and defaults are valid.":"Save Modules to repair missing dependencies or planned module states."})]})]}),e.jsx("div",{className:"company-module-grid",children:cl.map(M=>{const Z=Vo[M],fe=N[M],q=J1(N,M),ne=Z.lifecycle==="planned";return e.jsxs("article",{className:`company-module-card ${fe?"enabled":"disabled"} ${ne?"planned":""}`,children:[e.jsxs("div",{className:"company-module-card-header",children:[e.jsx("div",{className:"company-module-icon",children:e.jsx(Tu,{size:19})}),e.jsxs("div",{children:[e.jsx("h3",{children:Z.name}),e.jsx("span",{className:`module-lifecycle ${Z.lifecycle}`,children:Z.lifecycle})]})]}),e.jsx("p",{children:Z.description}),e.jsxs("div",{className:"module-meta-row",children:[e.jsx("span",{children:"Dependencies"}),e.jsx("strong",{children:Z.dependencies.length?Z.dependencies.map(ae=>Vo[ae].name).join(", "):"None"})]}),q.length>0&&fe&&e.jsxs("div",{className:"module-dependency-warning",children:[e.jsx(qu,{size:14}),"Requires"," ",q.map(ae=>
3998Vo[ae].name).join(", ")]}),e.jsxs("div",{className:"module-toggle-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:ne?"Coming Soon":fe?"Enabled":"Disabled"}),e.jsx("small",{children:ne?"Module development pending":"Saved for this company"})]}),e.jsx("button",{type:"button",className:`module-toggle ${fe?"on":"off"}`,disabled:ne||C,"aria-pressed":fe,onClick:()=>G(M),children:e.jsx("span",{})})]})]},M)})}),e.jsxs("div",{className:"module-manager-note",children:[e.jsx(qu,{size:17}),e.jsx("span",{children:"à¦à¦ release-ঠmodule configuration save হবà§à¥¤ Sidebar à¦à¦¬à¦ route control পরà§à¦° activation update-ঠà¦à¦¾à¦°à§à¦¯à¦à¦° হবà§à¥¤"})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:C,onClick:()=>b(null),children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",disabled:C,onClick:()=>void z(),children:[e.jsx(hr,{size:17}),C?"Savingâ¦":"Save Modules"]})]})]})}),s&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!u&&i(!1),children:e.jsxs("section",{className:"modal company-master-modal",onMouseDown:M=>M.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Company Workspace"}),e.jsx("h2",{children:c?"Edit Company":"Add Company"})]}),e.jsx("button",{disabled:u,onClick:()=>i(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:D,children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Company Name *",e.jsx("input",{value:m.name,onChange:M=>H(M.target.value),required:!0})]}),e.jsxs("label",{children:["Company Code *",e.jsx("input",{value:m.code,maxLength:8,onChange:M=>d({...m,code:M.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),required:!0})]}),e.jsxs("label",{children:["Company Slug *",e.jsx("input",{value:m.slug,onChange:M=>d({...m,slug:Rj(M.target.value)}),required:!0})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:m.active?"active":"inactive",onChange:M=>d({...m,active:M.target.value==="active"}),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Suspended"})]})]}),e.jsxs("label",{children:["Company Phone",e.jsx("input",{value:m.phone,onChange:M=>d({...m,phone:M.target.value})})]}),e.jsxs("label",{children:["Company Email",e.jsx("input",{type:"email",value:m.email,onChange:M=>d({...m,email:M.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Address",e.jsx("textarea",{value:m.address,onChange:M=>d({...m,address:M.target.value})})]}),e.jsxs("label",{children:["Plan",e.jsxs("select",{value:m.plan,onChange:M=>d({...m,plan:M.target.value}),children:[e.jsx("option",{value:"trial",children:"Trial"}),e.jsx("option",{value:"basic",children:"Basic"}),e.jsx("option",{value:"business",children:"Business"}),e.jsx("option",{value:"enterprise",children:"Enterprise"})]})]}),e.jsxs("label",{children:["Expiry Date",e.jsx("input",{type:"date",value:m.subscriptionExpiry,onChange:M=>d({...m,subscriptionExpiry:M.target.value})})]}),e.jsxs("div",{className:"full-field company-owner-section",children:[e.jsxs("div",{children:[e.jsx(gs,{size:19}),e.jsx("strong",{children:"Company Owner Login"})]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Owner Name *",e.jsx("input",{value:m.ownerName,onChange:M=>d({...m,ownerName:M.target.value}),required:!c})]}),e.jsxs("label",{children:["Owner Email *",e.jsx("input",{type:"email",value:m.ownerEmail,onChange:M=>d({...m,ownerEmail:M.target.value}),required:!c})]}),!c&&e.jsxs("label",{className:"full-field",children:["Temporary Password *",e.jsx("input",{value:m.ownerPassword,minLength:6,onChange:M=>d({...m,ownerPassword:M.target.value}),required:!0})]})]})]}),!c&&e.jsxs("div",{className:"full-field company-owner-section",children:[e.jsxs("div",{children:[e.jsx(Fu,{size:19}),e.jsx("strong",{children:"Initial Branch"})]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Branch Name *",e.jsx("input",{value:m.branchName,onChange:M=>d({...m,branchName:M.target.value}),required:!0})]}),e.jsxs("label",{children:["Branch Code *",e.jsx("input",{value:m.branchCode,onChange:M=>d({...m,branchCode:M.target.value.toUpperCase()}),required:!0})]})]})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:u,onClick:()=>i(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"vx-button vx-button-primary",disabled:u,children:[e.jsx(hr,{size:17}),u?"Savingâ¦":c?"Update Company":"Create Company"]})]})]})]})})]})}const mh=t=>Number(Number(t||0).toFixed(2));async function sU(t){var z;const n=`historical_purchase_${t.purchaseKey}`;if((await mn(re(ie,`accountingVouchers/${t.companyId}/${n}`))).exists())return{};const[a,s]=await Promise.all([mn(re(ie,`accountingAccounts/${t.companyId}`)),mn(re(ie,`accountingSettings/${t.companyId}`))]),i=a.exists()?Object.entries(a.val()).map(([H,K])=>({id:H,...K})):[],c=(H,K)=>i.find(L=>L.active!==!1&&!L.isGroup&&(L.systemKey===H||L.code===K)),l=c("inventory","1300"),m=c("cash","1110"),d=c("bank","1120"),u=c("accounts_payable","2100");if(!l||!m||!d||!u)throw new Error("Inventory/Cash/Bank/Accounts Payable system ledger is missing.");const f=String(((z=s.val())==null?void 0:z.lockedThrough)||"");if(f&&t.purchaseDate.slice(0,7)<=f)throw new Error(`Accounting period ${t.purchaseDate.slice(0,7)} is locked.`);const g=mh(t.totalAmount);if(g<=0)throw new Error("Purchase amount must be greater than zero.");const p=t.mode==="cash"||t.mode==="bank",y=t.mode==="partial_cash"||t.mode==="partial_bank",b=mh(p?g:y?t.paidAmount:0);if(b<0||b>g)throw new Error("Paid amount must be between zero and Purchase Value.");const N=mh(g-b),w=t.mode==="bank"||t.mode==="partial_bank";let C=w?t.paymentAccountId?i.find(H=>H.id===t.paymentAccountId&&H.active!==!1&&!H.isGroup):d:m;if(w&&t.paymentAccountId&&!C)throw new Error("Selected Bank/MFS ledger is missing or inactive.");const I=[{account:l,debit:g,credit:0,narration:`Historical Purchase inventory · ${t.billNumber}`},...b>0?[{account:C,debit:0,credit:b,narration:`Historical Purchase paid · ${t.billNumber}`}]:[],...N>0?[{account:u,debit:0,credit:N,narration:`Historical Purchase payable · ${t.billNumber}`}]:[]].map((H,K)=>({id:`line_${String(K+1).padStart(3,"0")}`,accountId:H.account.id,accountCode:H.account.code,accountName:H.account.name,debit:mh(H.debit),credit:mh(H.credit),narration:H.narration})),_=mh(I.reduce((H,K)=>
3998H+K.debit,0)),J=mh(I.reduce((H,K)=>H+K.credit,0));if(Math.abs(_-J)>=.005)throw new Error("Historical Purchase accounting entry is not balanced.");const T=`AUTO-HP-${t.billNumber}`,G={};return G[`accountingVouchers/${t.companyId}/${n}`]={voucherNo:T,type:"payment",status:"posted",voucherDate:t.purchaseDate,branchId:t.branchId,reference:t.billNumber,narration:`Historical Purchase mapped · ${t.billNumber} · ${t.supplier||"Supplier"}`,lines:I,totalDebit:_,totalCredit:J,createdAt:t.timestamp,createdByUid:t.actorUid,createdByName:t.actorName,updatedAt:t.timestamp,postedAt:t.timestamp,postedByUid:t.actorUid,postedByName:t.actorName,sourceType:"historical_purchase_import",sourceId:t.purchaseKey,autoPosted:!0},I.forEach((H,K)=>{const L=`${n}_${String(K+1).padStart(3,"0")}`;G[`accountingLedgerEntries/${t.companyId}/${L}`]={id:L,voucherId:n,voucherNo:T,voucherType:"payment",voucherDate:t.purchaseDate,branchId:t.branchId,reference:t.billNumber,narration:H.narration,accountId:H.accountId,accountCode:H.accountCode,accountName:H.accountName,debit:H.debit,credit:H.credit,status:"posted",createdAt:t.timestamp,postedByUid:t.actorUid,postedByName:t.actorName,sourceType:"historical_purchase_import",sourceId:t.purchaseKey,autoPosted:!0}}),G[`historicalPurchases/${t.companyId}/${t.purchaseKey}/paymentReview`]={status:"confirmed",mode:t.mode,paidAmount:b,payableAmount:N,paymentAccountId:t.paymentAccountId||"",reviewedAt:t.timestamp,reviewedByUid:t.actorUid,reviewedByName:t.actorName},G[`historicalPurchases/${t.companyId}/${t.purchaseKey}/accountingPosted`]=!0,G[`historicalPurchases/${t.companyId}/${t.purchaseKey}/accountingVoucherId`]=n,G[`historicalPurchaseImports/${t.companyId}/${t.purchaseKey}/paymentReview`]={status:"confirmed",mode:t.mode,paidAmount:b,payableAmount:N,paymentAccountId:t.paymentAccountId||"",reviewedAt:t.timestamp,reviewedByUid:t.actorUid,reviewedByName:t.actorName},G[`historicalPurchaseImports/${t.companyId}/${t.purchaseKey}/accountingPosted`]=!0,G[`historicalPurchaseImports/${t.companyId}/${t.purchaseKey}/accountingVoucherId`]=n,G}function rU(t){return t?new Date(`${t}T00:00:00`).getTime():0}function iU(t){return t?new Date(`${t}T23:59:59.999`).getTime():Number.MAX_SAFE_INTEGER}function lr(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()){const n=Number(t);if(Number.isFinite(n)&&n>0)return n;const a=Date.parse(t);if(Number.isFinite(a))return a}return 0}function dc(t,n){const a=lr(t);return a?a>=rU(n.from)&&a<=iU(n.to):!1}function fs(t){return`৳${Number(t||0).toLocaleString("en-BD")}`}function hc(t,n){if(!n.length)return;const a=Object.keys(n[0]),s=d=>`"${String(d??"").replaceAll('"','""')}"`,i=[a.map(s).join(","),...n.map(d=>a.map(u=>s(d[u]??"")).join(","))].join(`\r 3999`),c=new Blob(["\uFEFF",i],{type:"text/csv;charset=utf-8"}),l=URL.createObjectURL(c),m=document.createElement("a");m.href=l,m.download=t,m.click(),URL.revokeObjectURL(l)}function T_(){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),1),a=s=>`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")}`;return{from:a(n),to:a(t)}}const oU={received:"Received",diagnosing:"Diagnosing",waiting_approval:"Waiting Approval",approved:"Approved",repairing:"Repairing",quality_check:"Quality Check",qc_completed:"QC Completed",ready:"Ready",delivered:"Delivered",closed:"Closed",cancelled:"Cancelled",unknown:"Unknown Status"},cU={received:["diagnosing","cancelled"],diagnosing:["waiting_approval","repairing","cancelled"],waiting_approval:["approved","cancelled"],approved:["repairing","cancelled"],repairing:["quality_check","ready","cancelled"],quality_check:["repairing","qc_completed","ready","cancelled"],qc_completed:["ready","cancelled"],ready:["delivered","repairing","cancelled"],delivered:["closed"],closed:[],cancelled:[],unknown:["received"]};function M_(t,n){const a=Qh(t),s=Qh(n);return a===s||cU[a].includes(s)}function Qh(t){const n=String(t??"").trim().toLowerCase();if(!n)return"unknown";switch(n){case"repair_completed":case"repair complete":case"repair completed":return"quality_check";case"ready_for_delivery":case"ready for delivery":return"ready";case"waiting approval":return"waiting_approval";case"quality check":return"quality_check";case"qc completed":case"qc-completed":return"qc_completed";case"received":case"diagnosing":case"waiting_approval":case"approved":case"repairing":case"quality_check":case"qc_completed":case"ready":case"delivered":case"closed":case"cancelled":return n;case"unknown":return"unknown";default:return"unknown"}}function Dr(t){const n=Qh(t);if(n==="unknown"){const a=String(t??"").trim();return a&&a.toLowerCase()!=="unknown"?`Unknown Status (${a})`:"Unknown Status"}return oU[n]}const $_=t=>{const n=Math.max(0,Math.round(Number(t||0)));if(n===0)return"Zero Taka Only";const a=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],s=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],i=d=>{const u=[];return d>
3999=100&&(u.push(a[Math.floor(d/100)],"Hundred"),d%=100),d>=20&&(u.push(s[Math.floor(d/10)]),d%=10),d>0&&u.push(a[d]),u.join(" ")},c=[];let l=n;const m=[[1e7,"Crore"],[1e5,"Lakh"],[1e3,"Thousand"]];for(const[d,u]of m)if(l>=d){const f=Math.floor(l/d);c.push(i(f),u),l%=d}return l>0&&c.push(i(l)),`${c.join(" ")} Taka Only`},O_=t=>{if(!t)return"-";const n=t.match(/^(\d{4})-(\d{2})-(\d{2})$/);return n?`${n[3]}-${new Date(Number(n[1]),Number(n[2])-1,Number(n[3])).toLocaleString("en-GB",{month:"short"})}-${n[1]}`:t},Pc=9e4,L_=new Map,Hm=t=>{const n=L_.get(t);if(n)return n;const a={loadedAt:{}};return L_.set(t,a),a},lU=[{value:"all",label:"All Statuses"},{value:"received",label:"Received"},{value:"diagnosing",label:"Diagnosing"},{value:"waiting_approval",label:"Waiting Approval"},{value:"approved",label:"Approved"},{value:"repairing",label:"Repairing"},{value:"quality_check",label:"Quality Check"},{value:"qc_completed",label:"QC Completed"},{value:"ready",label:"Ready"},{value:"delivered",label:"Delivered"},{value:"closed",label:"Closed"},{value:"cancelled",label:"Cancelled"},{value:"unknown",label:"Unknown Status"}];function ph({profile:t,branches:n,selectedBranchId:a,onOpenServiceJob:s,scope:i="business",initialFinanceTab:c="collection",initialBusinessTab:l="service",dedicatedDatewise:m=!1,companyName:d="Service Center",companyPhone:u="",companyAddress:f=""}){const g=T_(),[p,y]=x.useState(i==="finance"?c:l);x.useEffect(()=>{y(i==="finance"?c:l)},[i,c,l]);const[b,N]=x.useState(g),[w,C]=x.useState(a),[R,I]=x.useState("all"),[_,J]=x.useState([]),[T,G]=x.useState([]),[z,H]=x.useState([]),[K,L]=x.useState([]),[D,M]=x.useState([]),[Z,fe]=x.useState([]),[q,ne]=x.useState([]),[ae,Y]=x.useState(""),[je,V]=x.useState(null),[$,F]=x.useState(null),[P,ue]=x.useState(()=>{try{return window.localStorage.getItem(`verixo:invoice-header-mode:${t.companyId}:${t.uid||"user"}`)==="letterhead"?"letterhead":"verixo"}catch{return"verixo"}}),[me,ge]=x.useState([]),[de,Pe]=x.useState(""),[Re,Ee]=x.useState("credit"),[Be,We]=x.useState(0),[it,_e]=x.useState(""),[ee,qe]=x.useState(!1),[se,pe]=x.useState("");x.useEffect(()=>{C(a)},[a]),x.useEffect(()=>{try{window.localStorage.setItem(`verixo:invoice-header-mode:${t.companyId}:${t.uid||"user"}`,P)}catch{}},[P,t.companyId,t.uid]),x.useEffect(()=>{if(i==="finance"){J([]);return}const B=Hm(t.companyId);let xe,tt;const ht=()=>{xe=qt(re(ie,`serviceJobs/${t.companyId}`),we=>{const rt=we.exists()?we.val():{},St=Object.entries(rt).map(([Qt,gn])=>({id:Qt,...gn,status:Qh(gn.status)}));J(St),B.jobs=St,B.loadedAt.jobs=Date.now()})},dt=Date.now()-(B.loadedAt.jobs||0);return B.jobs&&dt<Pc?(J(B.jobs),tt=window.setTimeout(ht,Math.max(0,Pc-dt))):ht(),()=>{tt!==void 0&&window.clearTimeout(tt),xe==null||xe()}},[t.companyId,i]),x.useEffect(()=>{if(i==="finance"&&c==="collection"){fe([]);return}const B=Hm(t.companyId);let xe,tt;const ht=()=>{xe=qt(re(ie,`historicalSales/${t.companyId}`),we=>{const rt=we.exists()?we.val():{},St=Object.entries(rt).map(([Qt,gn])=>({id:Qt,...gn}));fe(St),B.historicalSales=St,B.loadedAt.historicalSales=Date.now()})},dt=Date.now()-(B.loadedAt.historicalSales||0);return B.historicalSales&&dt<Pc?(fe(B.historicalSales),tt=window.setTimeout(ht,Math.max(0,Pc-dt))):ht(),()=>{tt!==void 0&&window.clearTimeout(tt),xe==null||xe()}},[t.companyId,i,c]),x.useEffect(()=>{if(i==="finance"&&c!=="payable"){ne([]);return}const B=Hm(t.companyId);let xe,tt;const ht=()=>{xe=qt(re(ie,`historicalPurchases/${t.companyId}`),we=>{const rt=we.exists()?we.val():{},St=Object.entries(rt).map(([Qt,gn])=>({id:Qt,...gn}));ne(St),B.historicalPurchases=St,B.loadedAt.historicalPurchases=Date.now()})},dt=Date.now()-(B.loadedAt.historicalPurchases||0);return B.historicalPurchases&&dt<Pc?(ne(B.historicalPurchases),tt=window.setTimeout(ht,Math.max(0,Pc-dt))):ht(),()=>{tt!==void 0&&window.clearTimeout(tt),xe==null||xe()}},[t.companyId,i,c]),x.useEffect(()=>qt(re(ie,`accountingBankAccounts/${t.companyId}`),B=>{const xe=B.exists()?B.val():{};ge(Object.entries(xe).map(([tt,ht])=>({id:tt,...ht})).filter(tt=>tt.active!==!1))}),[t.companyId]),x.useEffect(()=>{if(i!=="finance"||!["due","payable"].includes(c)){M([]);return}return qt(re(ie,`accountingVouchers/${t.companyId}`),B=>{const xe=B.exists()?B.val():{};M(Object.entries(xe).map(([tt,ht])=>({id:tt,...ht})))})},[t.companyId,i,c]),x.useEffect(()=>{const B=Hm(t.companyId);let xe,tt;const ht=()=>{xe=qt(re(ie,`customers/${t.companyId}`),we=>{const rt=we.exists()?we.val():{},St=Object.entries(rt).map(([Qt,gn])=>({id:Qt,...gn}));G(St),B.customers=St,B.loadedAt.customers=Date.now()})},dt=Date.now()-(B.loadedAt.customers||0);return B.customers&&dt<Pc?(G(B.customers),tt=window.setTimeout(ht,Math.max(0,Pc-dt))):ht(),()=>{tt!==void 0&&window.clearTimeout(tt),xe==null||xe()}},[t.companyId]),x.useEffect(()=>{const B=Hm(t.companyId);let xe,tt;const ht=()=>{xe=qt(re(ie,`invoices/${t.companyId}`),we=>{const rt=we.exists()?we.val():{},St=Object.entries(rt).map(([Qt,gn])=>({id:Qt,...gn}));H(St),B.invoices=St,B.loadedAt.invoices=Date.now()})},dt=Date.now()-(B.loadedAt.invoices||0);return B.invoices&&dt<Pc?(H(B.invoices),tt=window.setTimeout(ht,Math.max(0,Pc-dt))):ht(),()=>{tt!==void 0&&window.clearTimeout(tt),xe==null||xe()}},[t.companyId]),x.useEffect(()=>{const B=Hm(t.companyId);let xe,tt;const ht=()=>{xe=qt(re(ie,`collections/${t.companyId}`),we=>{const rt=we.exists()?we.val():{},St=Object.entries(rt).map(([Qt,gn])=>({id:Qt,...gn}));L(St),B.collections=St,B.loadedAt.collections=Date.now()})},dt=Date.now()-(B.loadedAt.collections||0);return B.collections&&dt<Pc?(L(B.collections),tt=window.setTimeout(ht,Math.max(0,Pc-dt))):ht(),()=>{tt!==void 0&&window.clearTimeout(tt),xe==null||xe()}},[t.companyId]);const Se=B=>w==="all"||B===w,Me=x.useMemo(()=>_.filter(B=>Se(B.branchId)&&dc(B.createdAt,b)&&(R==="all"||B.status===R)).sort((B,xe)=>lr(xe.createdAt)-lr(B.createdAt)),[_,w,b,R]),ot=x.useMemo(()=>{const B=new Map(T.map(xe=>[xe.id,xe]));return Me.filter(xe=>!["delivered","closed","cancelled"].includes(xe.status)).map(xe=>{const tt=xe.customerId?B.get(xe.customerId):void 0;return{...xe,customerName:xe.customerName||(tt==null?void 0:tt.name)||(tt==null?void 0:tt.customerName)||"",customerPhone:xe.customerPhone||(tt==null?void 0:tt.phone)||(tt==null?void 0:tt.mobile)||""}}).sort((xe,tt)=>lr(xe.createdAt)-lr(tt.createdAt))},[Me,T]),wt=x.useMemo(()=>{const B=Date.now(),xe=ot.filter(dt=>dt.status==="ready").length,tt=ot.filter(dt=>{const we=lr(dt.expectedDelivery||dt.expectedDeliveryDate);return we>0&&we<B}).length,ht=ot.length?ot.reduce((dt,we)=>dt+Math.max(0,Math.floor((B-lr(we.createdAt))/864e5)),0)/ot.length:0;return{total:ot.length,ready:xe,overdue:tt,averageDays:ht}},[ot]),ct=x.useMemo(()=>T.filter(B=>{if(!Se(B.branchId))return!1;const xe=lr(B.createdAt);return xe?dc(xe,b):!0}).sort((B,xe)=>
3999lr(xe.createdAt)-lr(B.createdAt)),[T,w,b]),Ce=x.useMemo(()=>z.filter(B=>Se(B.branchId)&&dc(B.createdAt,b)).sort((B,xe)=>Number(xe.createdAt||0)-Number(B.createdAt||0)),[z,w,b]),De=x.useMemo(()=>{const B=b.to,xe=new Map;D.forEach(dt=>{if(dt.status!=="posted"||!Se(dt.branchId)||String(dt.voucherDate||"")>B)return;const we=(dt.lines||[]).filter(Qt=>String(Qt.accountName||"").toLowerCase().includes("accounts receivable"));if(!we.length)return;const rt=String(dt.reference||dt.voucherNo||"").trim();if(!rt)return;const St=xe.get(rt)||{debit:0,credit:0};we.forEach(Qt=>{St.debit+=Number(Qt.debit||0),St.credit+=Number(Qt.credit||0)}),xe.set(rt,St)});const tt=new Map,ht=dt=>{!dt.invoiceNumber||!dc(dt.date,b)||dt.due<=.005||tt.set(dt.invoiceNumber,dt)};return z.filter(dt=>Se(dt.branchId)).forEach(dt=>{const we=String(dt.invoiceNumber||"").trim(),rt=xe.get(we),St=Number(dt.grandTotal||0),Qt=rt?rt.debit-rt.credit:Number(dt.dueAmount||0);ht({id:`live-${dt.id}`,date:String(dt.invoiceDate||new Date(dt.createdAt||0).toISOString().slice(0,10)),invoiceNumber:we,customerName:dt.customerName||"",invoiceValue:(rt==null?void 0:rt.debit)||St,settled:(rt==null?void 0:rt.credit)||Math.max(0,St-Qt),due:Qt,source:"Live"})}),Z.filter(dt=>Se(dt.branchId)).forEach(dt=>{const we=String(dt.sourceInvoiceNo||"").trim(),rt=xe.get(we),St=Number(dt.grandTotal||dt.totalAmount||0),Qt=Number(dt.due||0),gn=rt?rt.debit-rt.credit:Qt;ht({id:`historical-${dt.id}`,date:String(dt.saleDate||""),invoiceNumber:we,customerName:dt.customer||"",invoiceValue:(rt==null?void 0:rt.debit)||St,settled:(rt==null?void 0:rt.credit)||Math.max(0,St-gn),due:gn,source:"Historical"})}),[...tt.values()].sort((dt,we)=>dt.date.localeCompare(we.date)||dt.invoiceNumber.localeCompare(we.invoiceNumber))},[D,z,Z,w,b]),Te=x.useMemo(()=>{const B=b.to,xe=new Map;D.forEach(ht=>{if(ht.status!=="posted"||!Se(ht.branchId)||String(ht.voucherDate||"")>B)return;const dt=(ht.lines||[]).filter(we=>String(we.accountName||"").toLowerCase().includes("accounts payable"));dt.length&&dt.forEach(we=>{const rt=String(we.billNumber||ht.reference||ht.voucherNo||"").trim();if(!rt)return;const St=xe.get(rt)||{debit:0,credit:0};St.debit+=Number(we.debit||0),St.credit+=Number(we.credit||0),xe.set(rt,St)})});const tt=[];return q.filter(ht=>Se(ht.branchId)&&dc(ht.purchaseDate,b)).forEach(ht=>{var gn,An;
3999const dt=String(ht.sourceInvoiceNo||ht.supplierInvoiceRefNo||"").trim();if(!dt)return;const we=xe.get(dt);if(((gn=ht.paymentReview)==null?void 0:gn.status)==="confirmed"){const Sn=Number(ht.totalAmount||0),Xt=Math.max(0,Number(((An=ht.paymentReview)==null?void 0:An.payableAmount)||0)),Wt=we?Math.max(0,we.credit-we.debit):Xt,Gt=Math.max(0,Sn-Wt);tt.push({id:`historical-${ht.id}`,purchaseKey:ht.id,branchId:ht.branchId,stockImpact:ht.stockImpact,date:String(ht.purchaseDate||""),billNumber:dt,supplier:ht.supplier||"",purchaseValue:Sn,paid:Gt,payable:Wt,source:"Historical"});return}if(!we){tt.push({id:`historical-review-${ht.id}`,purchaseKey:ht.id,branchId:ht.branchId,stockImpact:ht.stockImpact,date:String(ht.purchaseDate||""),billNumber:dt,supplier:ht.supplier||"",purchaseValue:Number(ht.totalAmount||0),paid:0,payable:null,source:"Historical · Review"});return}const St=Math.max(0,we.credit-we.debit),Qt=Number(ht.totalAmount||we.credit||0);tt.push({id:`historical-${ht.id}`,purchaseKey:ht.id,branchId:ht.branchId,stockImpact:ht.stockImpact,date:String(ht.purchaseDate||""),billNumber:dt,supplier:ht.supplier||"",purchaseValue:Qt,paid:Math.max(0,Qt-St),payable:St,source:"Historical"})}),xe.forEach((ht,dt)=>{if(tt.some(Qt=>Qt.billNumber===dt))return;const we=Math.max(0,ht.credit-ht.debit);if(we<=.005)return;const rt=D.find(Qt=>String(Qt.reference||Qt.voucherNo||"").trim()===dt),St=String((rt==null?void 0:rt.voucherDate)||"");dc(St,b)&&tt.push({id:`ledger-${dt}`,date:St,billNumber:dt,supplier:"",purchaseValue:ht.credit,paid:ht.debit,payable:we,source:"Ledger"})}),tt.sort((ht,dt)=>ht.date.localeCompare(dt.date)||ht.billNumber.localeCompare(dt.billNumber))},[D,q,w,b]);async function ce(B){if(!B.purchaseKey||!B.branchId)return;if(B.stockImpact!==!0){pe("This Purchase is pre/on-cutover history-only. Post its opening supplier balance through an approved opening A/P adjustment instead of back-posting this bill.");return}const xe=Re==="partial_cash"||Re==="partial_bank",tt=Re==="bank"||Re==="partial_bank";if(xe&&(Be<0||Be>B.purchaseValue)){pe("Paid amount must be between 0 and Purchase Value.");return}if(tt&&!it){pe("Select the actual Bank/MFS account.");return}qe(!0),pe("");try{const ht=me.find(we=>we.id===it);if(tt&&!(ht!=null&&ht.ledgerAccountId)){pe("Selected Bank/MFS account has no linked accounting ledger."),qe(!1);return}const dt=await sU({companyId:t.companyId,branchId:B.branchId,purchaseKey:B.purchaseKey,purchaseDate:B.date,billNumber:B.billNumber,supplier:B.supplier,totalAmount:B.purchaseValue,mode:Re,paidAmount:xe?Be:0,paymentAccountId:tt?ht==null?void 0:ht.ledgerAccountId:void 0,actorUid:t.uid,actorName:t.name||t.email||"User",timestamp:Date.now()});Object.keys(dt).length?(await yn(re(ie),dt),pe(`Payment mapping posted for ${B.billNumber}.`)):pe("Accounting is already posted for this Purchase."),Pe("")}catch(ht){pe((ht==null?void 0:ht.message)||String(ht))}finally{qe(!1)}}const Ye=x.useMemo(()=>K.filter(B=>{const xe=B.collectedAt||B.createdAt;return Se(B.branchId)&&dc(xe,b)}).sort((B,xe)=>Number(xe.collectedAt||xe.createdAt||0)-Number(B.collectedAt||B.createdAt||0)),[K,w,b]),Je=ae.trim().toLowerCase(),le=x.useMemo(()=>Z.filter(B=>Se(B.branchId)&&dc(B.saleDate,b)).filter(B=>!Je||[B.sourceInvoiceNo,B.customer,B.customerContact,B.sourceSalesmanName,B.salespersonName].some(xe=>String(xe||"").toLowerCase().includes(Je))).sort((B,xe)=>lr(xe.saleDate)-lr(B.saleDate)),[Z,w,b,Je]),nt=x.useMemo(()=>z.filter(B=>Se(B.branchId)&&dc(B.invoiceDate||B.createdAt,b)).filter(B=>{if(!Je)return!0;const xe=T.find(tt=>tt.id===B.customerId);return[B.invoiceNumber,B.jobNumber,B.customerName,B.customerPhone,xe==null?void 0:xe.name,xe==null?void 0:xe.phone].some(tt=>String(tt||"").toLowerCase().includes(Je))}).sort((B,xe)=>lr(xe.invoiceDate||xe.createdAt)-lr(B.invoiceDate||B.createdAt)),[z,T,w,b,Je]),xt=x.useMemo(()=>{const B=nt.map(tt=>{const ht=T.find(dt=>dt.id===tt.customerId);return{key:`live-${tt.id}`,date:tt.invoiceDate||(tt.createdAt?new Date(tt.createdAt).toISOString().slice(0,10):""),invoiceNumber:tt.invoiceNumber||"â",customer:(ht==null?void 0:ht.name)||tt.customerName||"â",customerContact:(ht==null?void 0:ht.phone)||tt.customerPhone||"",description:tt.serviceJobId?`Service · ${tt.jobNumber||"Service Job"}`:"Product Sale",qty:tt.serviceJobId?1:0,sales:Number(tt.grandTotal||0),collected:Number(tt.collectedAmount||0),due:Number(tt.dueAmount||0),accounting:"Posted",source:tt.serviceJobId?"Service":"Product",liveInvoice:tt}}),xe=le.map(tt=>({key:`history-${tt.id}`,date:tt.saleDate,invoiceNumber:tt.sourceInvoiceNo||"â",customer:tt.customer||"â",customerContact:tt.customerContact||"",description:(tt.items||[]).map(ht=>{var dt;return`${ht.product||"â"}${(dt=ht.serials)!=null&&dt.length?` · SN: ${ht.serials.join(", ")}`:""}`}).join(" | "),qty:Number(tt.totalQty||0),sales:Number(tt.grandTotal||tt.totalAmount||0),collected:Number(tt.collected||0),due:Number(tt.due||0),accounting:tt.stockImpact?tt.accountingPosted?"Posted":"Pending repair":"History only",source:"Product",liveInvoice:void 0}));return[...B,...xe].sort((tt,ht)=>lr(ht.date)-lr(tt.date))},[nt,le,T]),te=x.useMemo(()=>q.filter(B=>
3999Se(B.branchId)&&dc(B.purchaseDate,b)).filter(B=>!Je||[B.sourceInvoiceNo,B.supplierInvoiceRefNo,B.supplier].some(xe=>String(xe||"").toLowerCase().includes(Je))).sort((B,xe)=>lr(xe.purchaseDate)-lr(B.purchaseDate)),[q,w,b,Je]),Ge=x.useMemo(()=>({salesCount:xt.length,salesQty:xt.reduce((B,xe)=>B+Number(xe.qty||0),0),sales:xt.reduce((B,xe)=>B+Number(xe.sales||0),0),collected:xt.reduce((B,xe)=>B+Number(xe.collected||0),0),due:xt.reduce((B,xe)=>B+Number(xe.due||0),0),purchaseCount:te.length,purchaseQty:te.reduce((B,xe)=>B+Number(xe.totalQty||0),0),purchases:te.reduce((B,xe)=>B+Number(xe.totalAmount||0),0)}),[xt,te]),pt=x.useMemo(()=>ct.map(B=>{const xe=B.name||B.customerName||"Unnamed Customer",tt=B.phone||B.mobile||"",ht=_.filter(rt=>Se(rt.branchId)?rt.customerId&&rt.customerId===B.id||tt&&rt.customerPhone&&rt.customerPhone===tt||xe&&rt.customerName&&rt.customerName.toLowerCase()===xe.toLowerCase():!1),dt=ht.reduce((rt,St)=>Math.max(rt,lr(St.createdAt)),0),we=z.filter(rt=>String(rt.customerName||"").toLowerCase()===xe.toLowerCase()).reduce((rt,St)=>rt+Number(St.dueAmount||0),0);return{...B,displayName:xe,displayPhone:tt,totalJobs:ht.length,totalDue:we||Number(B.dueAmount||0),lastVisit:dt}}),[ct,_,z,w]),$e=x.useMemo(()=>{const B=Me.filter(rt=>["delivered","closed"].includes(rt.status)).length,xe=Me.filter(rt=>!["delivered","closed","cancelled"].includes(rt.status)).length,tt=Me.filter(rt=>rt.status==="ready").length,ht=Ye.reduce((rt,St)=>rt+Number(St.amount||0),0),dt=Ce.reduce((rt,St)=>rt+Number(St.grandTotal||0),0),we=p==="due"?De.reduce((rt,St)=>rt+St.due,0):Ce.reduce((rt,St)=>rt+Number(St.dueAmount||0),0);return{totalJobs:Me.length,delivered:B,pending:xe,ready:tt,customers:pt.length,collection:ht,invoiceValue:dt,due:we}},[Me,pt,Ye,Ce,De,p]),st=x.useMemo(()=>n.map(B=>{const xe=_.filter(dt=>dt.branchId===B.id&&dc(dt.createdAt,b)),tt=K.filter(dt=>{const we=dt.collectedAt||dt.createdAt;return dt.branchId===B.id&&dc(we,b)}),ht=z.filter(dt=>dt.branchId===B.id&&dc(dt.createdAt,b));return{branch:B.name,jobs:xe.length,delivered:xe.filter(dt=>["delivered","closed"].includes(dt.status)).length,collection:tt.reduce((dt,we)=>dt+Number(we.amount||0),0),due:ht.reduce((dt,we)=>dt+Number(we.dueAmount||0),0)}}),[n,_,K,z,b]),Nt=()=>{N(T_()),C(a),I("all"),Y("")},be=()=>{const B=`${b.from}-to-${b.to}`;if(p==="service"){hc(`service-report-${B}.csv`,Me.map(xe=>({"Job No":xe.jobNumber,Date:new Date(lr(xe.createdAt)).toLocaleDateString("en-GB"),Device:[xe.deviceCategory,xe.brand,xe.model].filter(Boolean).join(" "),Technician:xe.assignedTechnician||"",Status:Dr(xe.status)})));return}if(p==="sales"){hc(`datewise-sales-${B}.csv`,le.map(xe=>({Date:xe.saleDate,"Invoice No":xe.sourceInvoiceNo||"",Customer:xe.customer||"",Salesperson:xe.salespersonName||xe.sourceSalesmanName||"",Products:(xe.items||[]).map(tt=>tt.product||"").filter(Boolean).join(" | "),Qty:Number(xe.totalQty||0),Sales:Number(xe.grandTotal||xe.totalAmount||0),"Source Collected":Number(xe.collected||0),Due:Number(xe.due||0),"Stock Impact":xe.stockImpact?"Yes":"No"})));return}if(p==="purchase"){hc(`datewise-purchase-${B}.csv`,te.map(xe=>({Date:xe.purchaseDate,"Purchase No":xe.sourceInvoiceNo||"","Supplier Ref":xe.supplierInvoiceRefNo||"",Supplier:xe.supplier||"",Products:(xe.items||[]).map(tt=>tt.product||"").filter(Boolean).join(" | "),Qty:Number(xe.totalQty||0),Amount:Number(xe.totalAmount||0),"Stock Impact":xe.stockImpact?"Yes":"No"})));return}if(p==="pending"){hc(`pending-service-report-${B}.csv`,ot.map(xe=>{const tt=lr(xe.createdAt),ht=lr(xe.expectedDelivery||xe.expectedDeliveryDate),dt=Math.max(0,Math.floor((Date.now()-tt)/864e5));return{"Job No":xe.jobNumber,"Receive Date":new Date(tt).toLocaleDateString("en-GB"),Customer:xe.customerName||"",Mobile:xe.customerPhone||"",Device:[xe.deviceCategory,xe.brand,xe.model].filter(Boolean).join(" "),Technician:xe.assignedTechnician||"",Status:Dr(xe.status),"Days Pending":dt,"Expected Delivery":ht?new Date(ht).toLocaleDateString("en-GB"):""}}));return}if(p==="collection"){hc(`collection-report-${B}.csv`,Ye.map(xe=>({Date:new Date(xe.collectedAt||xe.createdAt||0).toLocaleDateString("en-GB"),"Collection No":xe.collectionNumber||"","Invoice No":xe.invoiceNumber||"",Customer:xe.customerName||"",Method:xe.method||"",Amount:Number(xe.amount||0)})));return}if(p==="due"){hc(`due-report-${B}.csv`,De.map(xe=>({Date:xe.date,"Invoice No":xe.invoiceNumber,Customer:xe.customerName,Source:xe.source,"Invoice Value":xe.invoiceValue,Settled:xe.settled,Due:xe.due})));return}if(p==="payable"){hc(`supplier-payable-${B}.csv`,Te.map(xe=>({Date:xe.date,"Purchase / Bill No":xe.billNumber,Supplier:xe.supplier,Source:xe.source,"Purchase Value":xe.purchaseValue,"Paid / Adjusted":xe.payable===null?"Payment evidence unavailable":xe.paid,Payable:xe.payable===null?"Review Required":xe.payable})));return}if(p==="customer"){hc(`customer-report-${B}.csv`,pt.map(xe=>({"Date Added":lr(xe.createdAt)?new Date(lr(xe.createdAt)).toLocaleDateString("en-GB"):"Legacy",Customer:xe.dis
3999playName,Phone:xe.displayPhone,Address:xe.address||"","Total Jobs":xe.totalJobs,Due:xe.totalDue,"Last Visit":xe.lastVisit?new Date(xe.lastVisit).toLocaleDateString("en-GB"):""})));return}hc(`branch-report-${B}.csv`,st.map(xe=>({Branch:xe.branch,Jobs:xe.jobs,Delivered:xe.delivered,Collection:xe.collection,Due:xe.due})))},jt=B=>{var sn,on;const xe=n.find(ke=>ke.id===B.branchId),tt=Number(B.grossAmount??B.totalAmount??0),ht=Number(B.discountAmount||0),dt=Number(B.totalAmount||0),we=new Ra({orientation:"portrait",unit:"mm",format:"a4",compress:!0}),rt=we.internal.pageSize.getWidth(),St=(d==null?void 0:d.trim())||"VERIXO",Qt=B.branchName||(xe==null?void 0:xe.name)||"-",gn=new Date().toLocaleString("en-GB",{hour12:!0});we.setProperties({title:`${B.sourceInvoiceNo||"Purchase"} - ${St}`,subject:"Purchase Bill",author:St,creator:"VERIXO ERP"}),we.setDrawColor(45,55,65),we.setLineWidth(.25),we.rect(10,10,rt-20,34),we.line(118,10,118,44),we.setFont("helvetica","bold"),we.setFontSize(16),we.text(St.toUpperCase(),14,18),we.setFont("helvetica","normal"),we.setFontSize(7.5);let An=23;f&&(we.text(f,14,An,{maxWidth:98}),An+=4),u&&we.text(u,14,An),we.setFont("helvetica","bold"),we.setFontSize(13),we.text("Purchase",122,17),we.setFontSize(7.8),[["Purchase No.",B.sourceInvoiceNo||"-"],["Date",O_(B.purchaseDate)],["Status",B.status||"Posted"],["Payment Mode",((sn=B.paymentReview)==null?void 0:sn.mode)||"Credit"],["Entry By",B.createdByName||"-"]].forEach((ke,Ct)=>{const Et=22+Ct*4.2;we.setFont("helvetica","bold"),we.text(`${ke[0]} :`,122,Et),we.setFont("helvetica","normal"),we.text(String(ke[1]),148,Et,{maxWidth:47})}),we.rect(10,44,rt-20,25),we.setFont("helvetica","bold"),we.setFontSize(8.5),we.text("Supplier Info",12,49),we.line(10,51,200,51),we.setFontSize(7.7),we.text("Name :",12,57),we.setFont("helvetica","normal"),we.text(B.supplier||"-",27,57,{maxWidth:91}),we.setFont("helvetica","bold"),we.text("Supplier Ref :",122,57),we.setFont("helvetica","normal"),we.text(B.supplierInvoiceRefNo||"-",146,57,{maxWidth:50}),we.setFont("helvetica","bold"),we.text("Branch / Warehouse :",12,64),we.setFont("helvetica","normal"),we.text(Qt,43,64,{maxWidth:75}),oi(we,{startY:72,theme:"grid",margin:{left:10,right:10},head:[["#","Product Name / Serial","Quantity","Unit","Warehouse","Price/Unit","Disc./Unit","Total"]],body:(B.items||[]).map((ke,Ct)=>{var Et;return[String(Ct+1),`${ke.product||"-"}${(Et=ke.serials)!=null&&Et.length?` 4000${ke.serials.join(", ")}`:""}`,String(Number(ke.qty||0)),ke.unit||"-",Qt,fs(Number(ke.rate||0)),fs(Number(ke.discountAmount||0)),fs(Number(ke.amount||0))]}),styles:{fontSize:7,cellPadding:1.5,overflow:"linebreak",valign:"top",lineColor:[70,78,86],lineWidth:.18,textColor:[20,27,34]},headStyles:{fillColor:[242,244,246],textColor:[15,23,32],fontStyle:"bold",halign:"center"},columnStyles:{0:{cellWidth:7,halign:"center"},1:{cellWidth:82,halign:"left"},2:{cellWidth:13,halign:"center"},3:{cellWidth:13,halign:"center"},4:{cellWidth:19},5:{cellWidth:21,halign:"right"},6:{cellWidth:15,halign:"right"},7:{cellWidth:20,halign:"right"}},didParseCell:ke=>{ke.column.index===1&&(ke.cell.styles.halign="left")}});let Xt=((on=we.lastAutoTable)==null?void 0:on.finalY)||95;Xt>220&&(we.addPage(),Xt=20);const Wt=Number(B.totalQty||0);we.setFontSize(7.7),we.setFont("helvetica","bold"),we.text(`Total Qty. # ${Wt}`,198,Xt+5,{align:"right"});const Gt=132,$t=68;[["Grand Total",tt],["Discount",ht],["Net Total",dt]].forEach((ke,Ct)=>{const Et=Xt+Ct*6;we.rect(Gt,Et,$t,6),we.setFont("helvetica","bold"),we.text(`${ke[0]} (BDT)`,Gt+2,Et+4),we.text(fs(Number(ke[1])),Gt+$t-2,Et+4,{align:"right"})}),we.setFont("helvetica","normal"),we.text("In Word :",12,Xt+10),we.setFont("helvetica","bold"),we.text($_(dt),28,Xt+10,{maxWidth:98}),we.setFont("helvetica","normal"),we.text(`Remarks : ${B.note||""}`,12,Xt+22,{maxWidth:110});const Vt=Math.max(Xt+48,240);we.rect(12,Vt,88,18),we.rect(100,Vt,98,18),we.setFontSize(7.5),we.text("Supplier Signature",56,Vt+16,{align:"center"}),we.text(`For - ${St.toUpperCase()}`,149,Vt+16,{align:"center"}),we.setFontSize(6.5),we.setTextColor(80),we.text(`Print Date: ${gn}, By: ${t.name||B.createdByName||"-"}`,10,290),we.text("VERIXO ERP",rt/2,290,{align:"center"}),we.text(`${B.sourceInvoiceNo||"Purchase"} | Page: 1 of 1`,rt-10,290,{align:"right"}),we.save(`${B.sourceInvoiceNo||"purchase"}.pdf`)},bt=B=>{var gn,An;if(p!=="sales"&&p!=="purchase")return;const xe=p==="sales",tt=xe?"Datewise Sales Report":"Datewise Purchase Report",ht=w==="all"?"All Branches":((gn=n.find(Sn=>Sn.id===w))==null?void 0:gn.name)||"Selected Branch",dt=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0});dt.setProperties({title:`VERIXO - ${tt} - ${b.from} to ${b.to}`,subject:`${tt} for ${b.from} to ${b.to}`,author:"VERIXO ERP",creator:"VERIXO ERP"}),(An=dt.viewerPreferences)==null||An.call(dt,{DisplayDocTitle:!0}),dt.setFont("helvetica","bold"),dt.setFontSize(17),dt.text("VERIXO",14,14),dt.setFontSize(15),dt.text(tt,14,22),dt.setFont("helvetica","normal"),dt.setFontSize(8.5),dt.text(`Period: ${b.from} to ${b.to} | Branch: ${ht}`,14,28);const we={startY:33,theme:"grid",margin:{left:8,right:8,bottom:14},styles:{fontSize:6.5,cellPadding:1.5,overflow:"linebreak",valign:"middle",lineWidth:.15},headStyles:{fillColor:[7,59,92],textColor:255,fontStyle:"bold",lineWidth:.15},didDrawPage:()=>{const Sn=dt.getNumberOfPages();dt.setFont("helvetica","normal"),dt.setFontSize(7),dt.text(`Generated by VERIXO ERP | Page ${Sn}`,14,dt.internal.pageSize.getHeight()-6)}};if(xe){const Sn=le.reduce(($t,Vt)=>$t+Number(Vt.totalQty||0),0),Xt=le.reduce(($t,Vt)=>$t+Number(Vt.grandTotal||Vt.totalAmount||0),0),Wt=le.reduce(($t,Vt)=>$t+Number(Vt.collected||0),0),Gt=le.reduce(($t,Vt)=>$t+Number(Vt.due||0),0);oi(dt,{...we,head:[["Date","Invoice No","Customer","Salesperson","Products / Serial","Qty","Sales","Source Collected","Due","Payment","Accounting"]],body:le.map($t=>{const Vt=Number($t.collected||0),sn=Number($t.due||0),on=($t.items||[]).map(ke=>{var Ct;return`${ke.product||"-"}${(Ct=ke.serials)!=null&&Ct.length?` | SN: ${ke.serials.join(", ")}`:""}`}).join(` 4001`);return[$t.saleDate,$t.sourceInvoiceNo||"-",`${$t.customer||"-"}${$t.customerContact?` | ${$t.customerContact}`:""}`,$t.salespersonName||$t.sourceSalesmanName||"-",on||"-",String(Number($t.totalQty||0)),Number($t.grandTotal||$t.totalAmount||0).toLocaleStr
4001ing("en-BD"),Vt.toLocaleString("en-BD"),sn.toLocaleString("en-BD"),sn<=0?"Paid":Vt>0?"Partial":"Due",$t.stockImpact?$t.accountingPosted?"Posted":"Pending repair":"History only"]}),foot:[["TOTAL",`${le.length} invoice(s)`,"","","",String(Sn),Xt.toLocaleString("en-BD"),Wt.toLocaleString("en-BD"),Gt.toLocaleString("en-BD"),"",""]],footStyles:{fillColor:[235,242,247],textColor:[16,38,59],fontStyle:"bold",lineWidth:.15},columnStyles:{0:{cellWidth:18},1:{cellWidth:30},2:{cellWidth:34},3:{cellWidth:28},4:{cellWidth:63},5:{cellWidth:10,halign:"right"},6:{cellWidth:19,halign:"right"},7:{cellWidth:22,halign:"right"},8:{cellWidth:17,halign:"right"},9:{cellWidth:17},10:{cellWidth:21}}})}else{const Sn=te.reduce((Wt,Gt)=>Wt+Number(Gt.totalQty||0),0),Xt=te.reduce((Wt,Gt)=>Wt+Number(Gt.totalAmount||0),0);oi(dt,{...we,head:[["Date","Purchase No","Supplier Ref","Supplier","Products / Serial","Qty","Amount","Stock Impact"]],body:te.map(Wt=>[Wt.purchaseDate,Wt.sourceInvoiceNo||"-",Wt.supplierInvoiceRefNo||"-",Wt.supplier||"-",(Wt.items||[]).map(Gt=>{var $t;return`${Gt.product||"-"}${($t=Gt.serials)!=null&&$t.length?` | SN: ${Gt.serials.join(", ")}`:""}`}).join(` 4002`)||"-",String(Number(Wt.totalQty||0)),Number(Wt.totalAmount||0).toLocaleString("en-BD"),Wt.stockImpact?"Yes":"No"]),foot:[["TOTAL",`${te.length} purchase(s)`,"","","",String(Sn),Xt.toLocaleString("en-BD"),""]],footStyles:{fillColor:[235,242,247],textColor:[16,38,59],fontStyle:"bold",lineWidth:.15},columnStyles:{0:{cellWidth:22},1:{cellWidth:37},2:{cellWidth:34},3:{cellWidth:38},4:{cellWidth:92},5:{cellWidth:14,halign:"right"},6:{cellWidth:28,halign:"right"},7:{cellWidth:20}}})}const rt=`${xe?"datewise-sales":"datewise-purchase"}-${b.from}-to-${b.to}.pdf`;if(B==="download"){dt.save(rt);return}const St=URL.createObjectURL(dt.output("blob"));if(!window.open(St,"_blank")){URL.revokeObjectURL(St),window.alert("PDF preview was blocked by the browser. Please allow pop-ups for VERIXO or use Download PDF.");return}},tn=()=>{var ht,dt;if(p==="payable"){const we=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),rt=Te.reduce((St,Qt)=>St+Number(Qt.payable||0),0);we.setFont("helvetica","bold"),we.setFontSize(18),we.text("Supplier Payable Report",14,16),we.setFont("helvetica","normal"),we.setFontSize(9),we.text(`${b.from} to ${b.to} · ${w==="all"?"All Branches":((ht=n.find(St=>St.id===w))==null?void 0:ht.name)||"Selected Branch"}`,14,23),we.text(`Posted A/P Payable: ${rt.toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2})} BDT`,14,29),oi(we,{startY:34,head:[["Date","Purchase / Bill No","Supplier","Source","Purchase Value","Paid / Adjusted","Payable"]],body:Te.map(St=>[St.date,St.billNumber||"-",St.supplier||"-",St.source,Number(St.purchaseValue||0).toLocaleString("en-BD"),St.payable===null?"Evidence unavailable":Number(St.paid||0).toLocaleString("en-BD"),St.payable===null?"Review Required":Number(St.payable||0).toLocaleString("en-BD")]),styles:{fontSize:8,cellPadding:2},headStyles:{fillColor:[7,59,92]}}),we.save(`supplier-payable-${b.from}-to-${b.to}.pdf`);return}const B=((dt=document.querySelector(".reports-table-card"))==null?void 0:dt.innerHTML)||"",xe=i==="finance"?p==="due"?"Due Report":"Collection Report":"Business Report",tt=window.open("","_blank","width=1100,height=850");tt&&(tt.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>${xe}</title><style>@page{size:A4 landscape;margin:10mm}body{font-family:Arial,sans-serif;color:#10263b;padding:12px}h1{color:#073b5c}table{width:100%;border-collapse:collapse}th,td{border:1px solid #d8e3eb;padding:7px;font-size:11px;text-align:left}th{background:#073b5c;color:#fff}.reports-table-heading{margin-bottom:10px}.reports-empty{text-align:center}.report-status{font-weight:700}</style></head><body><h1>${xe}</h1><p>${b.from} to ${b.to}</p>${B}</body></html>`),tt.document.close(),tt.focus(),setTimeout(()=>tt.print(),250))};return e.jsxs("section",{className:"reports-page",children:[e.jsxs("header",{className:"reports-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:i==="finance"?"Accounts & Finance":"Reports & Analytics"}),e.jsx("h1",{children:i==="finance"?c==="due"?"Due Report":c==="payable"?"Supplier Payable Report":"Collection Report":"Business Reports"}),e.jsx("p",{children:i==="finance"?c==="due"?"Outstanding customer and invoice due report.":c==="payable"?"Outstanding supplier bills backed by posted Accounts Payable ledger.":"Customer collection report by date, branch and payment method.":"Company-isolated reports for service, customers and branch performance."})]}),e.jsx("div",{className:"reports-header-actions",children:m?e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"secondary-action",onClick:()=>bt("view"),children:[e.jsx(ui,{size:17})," View PDF"]}),e.jsxs("button",{className:"primary-action",onClick:()=>bt("download"),children:[e.jsx(Mi,{size:17})," Download PDF"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"secondary-action",onClick:tn,children:[e.jsx(Wi,{size:17})," ",p==="payable"?"Download PDF":"Print / PDF"]}),e.jsxs("button",{className:"primary-action",onClick:be,children:[e.jsx(Mi,{size:17})," Export CSV"]})]})})]}),e.jsxs("section",{className:"reports-filter-panel",children:[e.jsxs("div",{className:"reports-filter-title",children:[e.jsx(_D,{size:18}),e.jsx("strong",{children:"Report Filters"})]}),e.jsxs("label",{children:["From",e.jsx("input",{type:"date",value:b.from,onChange:B=>N({...b,from:B.target.value})})]}),e.jsxs("label",{children:["To",e.jsx("input",{type:"date",value:b.to,onChange:B=>N({...b,to:B.target.value})})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:w,onChange:B=>C(B.target.value),children:[["owner","admin","super_admin"].includes(t.role)&&e.jsx("option",{value:"all",children:"All Branches"}),n.map(B=>e.jsx("option",{value:B.id,children:B.name},B.id))]})]}),i==="business"&&(p==="sales"||p==="purchase")&&e.jsxs("label",{children:["Invoice / Source / Ref Search",e.jsx("input",{type:"search",value:ae,onChange:B=>Y(B.target.value),placeholder:p==="sales"?"Invoice no., customer, salesperson...":"Purchase no., supplier ref, supplier..."})]}),e.jsxs("label",{children:["Service Status",e.jsx("select",{value:R,onChange:B=>I(B.target.value),disabled:!["service","pending"].includes(p),children:lU.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]}),e.jsxs("button",{className:"reports-reset-button",onClick:Nt,children:[e.jsx(Hi,{size:16})," Reset"]}),m&&e.jsxs("div",{className:"reports-invoice-header-preference",children:[e.jsxs("label",{children:["Invoice Header",e.jsxs("select",{value:P,onChange:B=>ue(B.target.value),children:[e.jsx("option",{value:"verixo",children:"VERIXO Header"}),e.jsx("option",{value:"letterhead",children:"Letterhead / No Header"})]})]}),e.jsx("small",{children:"Saved for this user"})]})]}),e.jsxs("section",{className:"reports-summary-grid",children:[i==="business"&&p==="sales"&&e.jsxs(e.Fragment,{children:[e.jsxs("article",{children:[e.jsx(Zs,{size:20}),e.jsx("span",{children:"Sales Invoices"}),e.jsx("strong",{children:Ge.salesCount}),e.jsxs("small",{children:[Ge.salesQty," qty"]})]}),e.jsxs("article",{children:[e.jsx(Ch,{size:20}),e.jsx("span",{children:"Sales"}),e.jsx("strong",{children:fs(Ge.sales)}),e.jsx("small",{children:"Selected period"})]}),e.jsxs("article",{children:[e.jsx(Ch,{size:20}),e.jsx("span",{children:"Source Collected"}),e.jsx("strong",{children:fs(Ge.collected)}),e.jsx("small",{children:"PDF evidence"})]}),e.jsxs("article",{children:[e.jsx(Zs,{size:20}),e.jsx("span",{children:"Due"}),e.jsx("strong",{children:fs(Ge.due)}),e.jsx("small",{children:"Source outstanding"})]})]}),i==="business"&&p==="purchase"&&e.jsxs(e.Fragment,{children:[e.jsxs("article",{children:[e.jsx(Zs,{size:20}),e.jsx("span",{children:"Purchases"}),e.jsx("strong",{children:Ge.purchaseCount}),e.jsxs("small",{children:[Ge.purchaseQty," qty"]})]}),e.jsxs("article",{children:[e.jsx(Ch,{size:20}),e.jsx("span",{children:"Purchase Amount"}),e.jsx("strong",{children:fs(Ge.purchases)}),e.jsx("small",{children:"Selected period"})]})]}),i==="business"&&!["sales","purchase"].includes(p)&&e.jsxs(e.Fragment,{children:[e.jsxs("article",{children:[e.jsx(Go,{size:20}),e.jsx("span",{children:"Total Jobs"}),e.jsx("strong",{children:$e.totalJobs}),e.jsxs("small",{children:[$e.pending," pending"]})]}),e.jsxs("article",{children:[e.jsx(wi,{size:20}),e.jsx("span",{children:"Delivered"}),e.jsx("strong",{children:$e.delivered}),e.jsxs("small",{children:[$e.ready," ready"]})]}),e.jsxs("article",{children:[e.jsx(mc,{size:20}),e.jsx("span",{children:"New Customers"}),e.jsx("strong",{children:$e.customers}),e.jsx("small",{children:"Selected period"})]})]}),!(i==="business"&&["sales","purchase"].includes(p))&&e.jsxs("article",{children:[e.jsx(Ch,{size:20}),e.jsx("span",{children:"Collection"}),e.jsx("strong",{children:fs($e.collection)}
4002),e.jsxs("small",{children:["Invoice ",fs($e.invoiceValue)]})]}),!(i==="business"&&["sales","purchase"].includes(p))&&e.jsxs("article",{children:[e.jsx(Zs,{size:20}),e.jsx("span",{children:p==="payable"?"Total Payable":"Total Due"}),e.jsx("strong",{children:fs(p==="payable"?Te.reduce((B,xe)=>B+Number(xe.payable||0),0):$e.due)}),e.jsx("small",{children:p==="payable"?`${Te.filter(B=>B.payable===null).length} bill(s) need payment review`:"Outstanding"})]})]}),i==="business"&&p==="pending"&&e.jsxs("section",{className:"reports-summary-grid pending-summary-grid",children:[e.jsxs("article",{children:[e.jsx(Go,{size:20}),e.jsx("span",{children:"Pending Jobs"}),e.jsx("strong",{children:wt.total}),e.jsx("small",{children:"Not delivered"})]}),e.jsxs("article",{children:[e.jsx(wi,{size:20}),e.jsx("span",{children:"Ready for Delivery"}),e.jsx("strong",{children:wt.ready}),e.jsx("small",{children:"Customer collection pending"})]}),e.jsxs("article",{children:[e.jsx(Zs,{size:20}),e.jsx("span",{children:"Overdue"}),e.jsx("strong",{children:wt.overdue}),e.jsx("small",{children:"Expected date passed"})]}),e.jsxs("article",{children:[e.jsx(xp,{size:20}),e.jsx("span",{children:"Average Pending"}),e.jsxs("strong",{children:[wt.averageDays.toFixed(1)," days"]}),e.jsx("small",{children:"Current pending jobs"})]})]}),!m&&e.jsxs("nav",{className:"reports-tabs",children:[i==="business"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:p==="service"?"active":"",onClick:()=>y("service"),children:"Service"}),e.jsx("button",{className:p==="pending"?"active":"",onClick:()=>y("pending"),children:"Pending Service"}),e.jsx("button",{className:p==="customer"?"active":"",onClick:()=>y("customer"),children:"Customer"}),e.jsx("button",{className:p==="branch"?"active":"",onClick:()=>y("branch"),children:"Branch"})]}),i==="finance"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:p==="collection"?"active":"",onClick:()=>y("collection"),children:"Collection"}),e.jsx("button",{className:p==="due"?"active":"",onClick:()=>y("due"),children:"Due"}),e.jsx("button",{className:p==="payable"?"active":"",onClick:()=>y("payable"),children:"Supplier Payable"})]})]}),e.jsxs("section",{className:"reports-table-card",children:[e.jsx("div",{className:"reports-table-heading",children:e.jsxs("div",{children:[e.jsx(xp,{size:20}),e.jsxs("div",{children:[e.jsx("h2",{children:p==="service"?"Service Report":p==="pending"?"Pending Service Report":p==="sales"?"Datewise Sales Report":p==="purchase"?"Datewise Purchase Report":p==="collection"?"Collection Report":p==="due"?"Due Report":p==="payable"?"Supplier Payable Report":p==="customer"?"Customer Report":"Branch Performance"}),e.jsxs("p",{children:[b.from," to ",b.to]}),p==="sales"&&e.jsx("p",{children:"Post-cutover source collection is posted once to Cash/Bank and Sales accounting. âPending repairâ requires the same PDF to be re-uploaded in Sales Migration."})]})]})}),e.jsxs("div",{className:"reports-table-wrap",children:[p==="service"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Job No"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Device"}),e.jsx("th",{children:"Technician"}),e.jsx("th",{children:"Status"})]})}),e.jsxs("tbody",{children:[Me.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:B.jobNumber})}),e.jsx("td",{children:new Date(lr(B.createdAt)).toLocaleDateString("en-GB")}),e.jsx("td",{children:[B.deviceCategory,B.brand,B.model].filter(Boolean).join(" ")}),e.jsx("td",{children:B.assignedTechnician||"Unassigned"}),e.jsx("td",{children:e.jsx("span",{className:"report-status",children:Dr(B.status)})})]},B.id)),!Me.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"reports-empty",children:"No records found."})})]})]}),p==="pending"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Job No"}),e.jsx("th",{children:"Receive Date"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Mobile"}),e.jsx("th",{children:"Device"}),e.jsx("th",{children:"Technician"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Days Pending"}),e.jsx("th",{children:"Expected Delivery"})]})}),e.jsxs("tbody",{children:[ot.map(B=>{const xe=lr(B.createdAt),tt=lr(B.expectedDelivery||B.expectedDeliveryDate),ht=Math.max(0,Math.floor((Date.now()-xe)/864e5)),dt=tt>0&&tt<Date.now();return e.jsxs("tr",{className:dt?"report-overdue-row":"",children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"report-job-link",onClick:()=>s==null?void 0:s(B.id),title:`Open service job ${B.jobNumber}`,children:B.jobNumber})}),e.jsx("td",{children:new Date(xe).toLocaleDateString("en-GB")}),e.jsx("td",{children:B.customerName||"â"}),e.jsx("td",{children:B.customerPhone||"â"}),e.jsx("td",{children:[B.deviceCategory,B.brand,B.model].filter(
4002Boolean).join(" ")}),e.jsx("td",{children:B.assignedTechnician||"Unassigned"}),e.jsx("td",{children:e.jsx("span",{className:"report-status",children:Dr(B.status)})}),e.jsxs("td",{children:[e.jsx("strong",{children:ht}),dt&&e.jsx("small",{className:"overdue-label",children:" Overdue"})]}),e.jsx("td",{children:tt?new Date(tt).toLocaleDateString("en-GB"):"â"})]},B.id)}),!ot.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"reports-empty",children:"No pending service jobs found."})})]})]}),p==="sales"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Invoice No"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Reference / Products"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Sales"}),e.jsx("th",{children:"Collected"}),e.jsx("th",{children:"Due"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Accounting"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[xt.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:B.date}),e.jsx("td",{children:e.jsx("strong",{children:B.invoiceNumber})}),e.jsxs("td",{children:[B.customer,B.customerContact&&e.jsxs("small",{children:[" · ",B.customerContact]})]}),e.jsx("td",{children:e.jsx("span",{className:"report-status",children:B.source})}),e.jsx("td",{children:B.description||"â"}),e.jsx("td",{children:B.qty}),e.jsx("td",{children:fs(B.sales)}),e.jsx("td",{children:fs(B.collected)}),e.jsx("td",{children:fs(B.due)}),e.jsx("td",{children:e.jsx("span",{className:"report-status",children:B.due<=0?"Paid":B.collected>0?"Partial":"Due"})}),e.jsx("td",{children:e.jsx("span",{className:"report-status",children:B.accounting})}),e.jsx("td",{children:B.liveInvoice?e.jsx("button",{className:"reports-icon-button",title:"Preview invoice",onClick:()=>V(B.liveInvoice),children:e.jsx(ui,{size:16})}):e.jsx("span",{children:"â"})})]},B.key)),!xt.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:12,className:"reports-empty",children:"No sales found for the selected date and branch."})})]})]}),p==="purchase"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Purchase No"}),e.jsx("th",{children:"Supplier Ref"}),e.jsx("th",{children:"Supplier"}),e.jsx("th",{children:"Products / Serial"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Stock Impact"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[te.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:B.purchaseDate}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"reports-link-button",onClick:()=>F(B),title:"Preview purchase bill",children:e.jsx("strong",{children:B.sourceInvoiceNo||"â"})})}),e.jsx("td",{children:B.supplierInvoiceRefNo||"â"}),e.jsx("td",{children:B.supplier||"â"}),e.jsx("td",{children:(B.items||[]).map((xe,tt)=>{var ht;return e.jsxs("div",{children:[xe.product||"â",(ht=xe.serials)!=null&&ht.length?e.jsxs("small",{children:[" · SN: ",xe.serials.join(", ")]}):null]},tt)})}),e.jsx("td",{children:Number(B.totalQty||0)}),e.jsx("td",{children:fs(Number(B.totalAmount||0))}),e.jsx("td",{children:B.stockImpact?"Yes":"No"}),e.jsx("td",{children:e.jsx("button",{className:"reports-icon-button",title:"Preview purchase bill",onClick:()=>F(B),children:e.jsx(ui,{size:16})})})]},B.id)),!te.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"reports-empty",children:"No purchases found for the selected date and branch."})})]})]}),p==="collection"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Collection No"}),e.jsx("th",{children:"Invoice No"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Amount"})]})}),e.jsxs("tbody",{children:[Ye.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(B.collectedAt||B.createdAt||0).toLocaleDateString("en-GB")}),e.jsx("td",{children:B.collectionNumber||"â"}),e.jsx("td",{children:B.invoiceNumber||"â"}),e.jsx("td",{children:B.customerName||"â"}),e.jsx("td",{children:B.method||"â"}),e.jsx("td",{children:e.jsx("strong",{children:fs(Number(B.amount||0))})})]},B.id)),!Ye.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"reports-empty",children:"No records foun
4002d."})})]})]}),p==="due"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Invoice No"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Invoice Value"}),e.jsx("th",{children:"Settled"}),e.jsx("th",{children:"Due"})]})}),e.jsxs("tbody",{children:[De.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:B.date}),e.jsx("td",{children:e.jsx("strong",{children:B.invoiceNumber||"â"})}),e.jsx("td",{children:B.customerName||"â"}),e.jsx("td",{children:B.source}),e.jsx("td",{children:fs(B.invoiceValue)}),e.jsx("td",{children:fs(B.settled)}),e.jsx("td",{children:e.jsx("strong",{children:fs(B.due)})})]},B.id)),!De.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"reports-empty",children:"No due invoices found."})})]})]}),p==="payable"&&se&&e.jsx("div",{className:"report-notice",children:se}),p==="payable"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Purchase / Bill No"}),e.jsx("th",{children:"Supplier"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Purchase Value"}),e.jsx("th",{children:"Paid / Adjusted"}),e.jsx("th",{children:"Payable"})]})}),e.jsxs("tbody",{children:[Te.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:B.date}),e.jsx("td",{children:e.jsx("strong",{children:B.billNumber||"â"})}),e.jsx("td",{children:B.supplier||"â"}),e.jsx("td",{children:B.source}),e.jsx("td",{children:fs(B.purchaseValue)}),e.jsx("td",{children:B.payable===null?"Evidence unavailable":fs(B.paid)}),e.jsxs("td",{children:[e.jsx("strong",{children:B.payable===null?e.jsx("button",{type:"button",className:"reports-link-button",onClick:()=>{Pe(B.id),Ee("credit"),We(0),_e(""),pe("")},children:"Review Payment"}):fs(B.payable)}),de===B.id&&e.jsxs("div",{className:"payable-review-box",children:[e.jsxs("select",{value:Re,onChange:xe=>Ee(xe.target.value),children:[e.jsx("option",{value:"credit",children:"Credit · Full Payable"}),e.jsx("option",{value:"cash",children:"Paid · Cash"}),e.jsx("option",{value:"bank",children:"Paid · Bank / TT / MFS"}),e.jsx("option",{value:"partial_cash",children:"Partial · Cash"}),e.jsx("option",{value:"partial_bank",children:"Partial · Bank / TT / MFS"})]}),(Re==="partial_cash"||Re==="partial_bank")&&e.jsx("input",{type:"number",min:"0",max:B.purchaseValue,value:Be,onChange:xe=>We(Number(xe.target.value||0)),placeholder:"Paid amount"}),(Re==="bank"||Re==="partial_bank")&&e.jsxs("select",{value:it,onChange:xe=>_e(xe.target.value),children:[e.jsx("option",{value:"",children:"Select Bank/MFS account"}),me.map(xe=>e.jsxs("option",{value:xe.id,children:[xe.bankName||xe.accountName||"Bank/MFS",xe.accountNumber?` · ${xe.accountNumber}`:""]},xe.id))]}),e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"primary-button",disabled:ee,onClick:()=>void ce(B),children:ee?"Postingâ¦":"Confirm & Post"}),e.jsx("button",{type:"button",onClick:()=>Pe(""),children:"Cancel"})]})]})]})]},B.id)),!Te.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"reports-empty",children:"No posted supplier payable bills found for this period."})})]})]}),p==="customer"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date Added"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Phone"}),e.jsx("th",{children:"Address"}),e.jsx("th",{children:"Total Jobs"}),e.jsx("th",{children:"Due"}),e.jsx("th",{children:"Last Visit"})]})}),e.jsxs("tbody",{children:[pt.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:lr(B.createdAt)?new Date(lr(B.createdAt)).toLocaleDateString("en-GB"):"Legacy"}),e.jsx("td",{children:e.jsx("strong",{children:B.displayName})}),e.jsx("td",{children:B.displayPhone||"â"}),e.jsx("td",{children:B.address||"â"}),e.jsx("td",{children:B.totalJobs}),e.jsx("td",{children:fs(B.totalDue)}),e.jsx("td",{children:B.lastVisit?new Date(B.lastVisit).toLocaleDateString("en-GB"):"â"})]},B.id)),!pt.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"reports-empty",children:"No customers found for the selected branch."})})]})]}),p==="branch"&&e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Jobs"}),e.jsx("th",{children:"Delivered"}),e.jsx("th",{children:"Collection"}),e.jsx("th",{children:"Due"})]})}),e.jsx("tbody",{children:st.map(B=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:B.branch})}),e.jsx("td",{children:B.jobs}),e.jsx("td",{children:B.delivered}
4002),e.jsx("td",{children:fs(B.collection)}),e.jsx("td",{children:fs(B.due)})]},B.branch))})]})]})]}),$&&(()=>{var we;const B=$,xe=n.find(rt=>rt.id===B.branchId),tt=Number(B.grossAmount??B.totalAmount??0),ht=Number(B.discountAmount||0),dt=Number(B.totalAmount||0);return e.jsx("div",{className:"report-invoice-fullpage",children:e.jsxs("div",{className:"report-invoice-document-modal",children:[e.jsxs("div",{className:"modal-header report-invoice-toolbar",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Purchase Bill Preview"}),e.jsx("h2",{children:B.sourceInvoiceNo||"Purchase"}),e.jsx("span",{children:B.purchaseDate||"â"})]}),e.jsxs("div",{className:"report-invoice-toolbar-actions",children:[e.jsx("button",{type:"button",className:"report-invoice-action-button",onClick:()=>jt(B),title:"Download purchase bill PDF","aria-label":"Download purchase bill PDF",children:e.jsx(Mi,{size:18})}),e.jsx("button",{type:"button",className:"report-invoice-action-button",onClick:()=>window.print(),title:"Print purchase bill","aria-label":"Print purchase bill",children:e.jsx(Wi,{size:18})}),e.jsx("button",{type:"button",className:"report-invoice-close-button",onClick:()=>F(null),title:"Close preview",children:e.jsx(ja,{size:18})})]})]}),e.jsxs("div",{className:"report-invoice-sheet purchase-bill-sheet",children:[e.jsxs("div",{className:"purchase-bill-head",children:[e.jsxs("div",{children:[e.jsx("h1",{children:((d==null?void 0:d.trim())||"VERIXO").toUpperCase()}),f&&e.jsx("p",{children:f}),u&&e.jsx("p",{children:u})]}),e.jsxs("div",{children:[e.jsx("h2",{children:"Purchase"}),e.jsxs("p",{children:[e.jsx("b",{children:"Purchase No. :"})," ",B.sourceInvoiceNo||"â"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Date :"})," ",O_(B.purchaseDate)]}),e.jsxs("p",{children:[e.jsx("b",{children:"Status :"})," ",B.status||"Posted"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Payment Mode :"})," ",((we=B.paymentReview)==null?void 0:we.mode)||"Credit"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Entry By :"})," ",B.createdByName||"â"]})]})]}),e.jsxs("div",{className:"purchase-bill-supplier",children:[e.jsx("strong",{children:"Supplier Info"}),e.jsxs("p",{children:[e.jsx("b",{children:"Name :"})," ",B.supplier||"â"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Supplier Ref :"})," ",B.supplierInvoiceRefNo||"â"]}),e.jsxs("p",{children:[e.jsx("b",{children:"Branch / Warehouse :"})," ",B.branchName||(xe==null?void 0:xe.name)||"â"]})]}),e.jsxs("table",{className:"report-invoice-lines purchase-bill-lines",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"purchase-col-sl"}),e.jsx("col",{className:"purchase-col-product"}),e.jsx("col",{className:"purchase-col-qty"}),e.jsx("col",{className:"purchase-col-unit"}),e.jsx("col",{className:"purchase-col-warehouse"}),e.jsx("col",{className:"purchase-col-price"}),e.jsx("col",{className:"purchase-col-discount"}),e.jsx("col",{className:"purchase-col-total"})]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"#"}),e.jsx("th",{children:"Product Name / Serial"}),e.jsx("th",{children:"Quantity"}),e.jsx("th",{children:"Unit"}),e.jsx("th",{children:"Warehouse"}),e.jsx("th",{children:"Price/Unit"}),e.jsx("th",{children:"Disc./Unit"}),e.jsx("th",{className:"num",children:"Total"})]})}),e.jsx("tbody",{children:(B.items||[]).map((rt,St)=>{var Qt;return e.jsxs("tr",{children:[e.jsx("td",{children:St+1}),e.jsxs("td",{children:[e.jsx("strong",{children:rt.product||"â"}),(Qt=rt.serials)!=null&&Qt.length?e.jsx("small",{className:"purchase-serial",children:rt.serials.join(", ")}):null]}),e.jsx("td",{children:Number(rt.qty||0)}),e.jsx("td",{children:rt.unit||"â"}),e.jsx("td",{children:B.branchName||(xe==null?void 0:xe.name)||"â"}),e.jsx("td",{children:fs(Number(rt.rate||0))}),e.jsx("td",{children:fs(Number(rt.discountAmount||0))}),e.jsx("td",{className:"num",children:fs(Number(rt.amount||0))})]},`${rt.product||"item"}_${St}`)})})]}),e.jsxs("div",{className:"purchase-bill-totalqty",children:["Total Qty. # ",e.jsx("strong",{children:Number(B.totalQty||0)})]}),e.jsxs("div",{className:"purchase-bill-summary",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"purchase-in-word",children:[e.jsx("b",{children:"In Word :"}
4002)," ",$_(dt)]}),e.jsxs("p",{children:[e.jsx("b",{children:"Remarks :"})," ",B.note||""]})]}),e.jsxs("div",{children:[e.jsxs("p",{children:[e.jsx("span",{children:"Grand Total (BDT)"}),e.jsx("strong",{children:fs(tt)})]}),e.jsxs("p",{children:[e.jsx("span",{children:"Discount (BDT)"}),e.jsx("strong",{children:fs(ht)})]}),e.jsxs("p",{className:"grand",children:[e.jsx("span",{children:"Net Total (BDT)"}),e.jsx("strong",{children:fs(dt)})]})]})]}),e.jsxs("div",{className:"purchase-bill-signatures",children:[e.jsx("span",{children:"Supplier Signature"}),e.jsxs("span",{children:["For - ",((d==null?void 0:d.trim())||"VERIXO").toUpperCase()]})]}),e.jsxs("div",{className:"purchase-bill-footer",children:[e.jsxs("span",{children:["Print Date: ",new Date().toLocaleString("en-GB",{hour12:!0}),", By: ",t.name||B.createdByName||"â"]}),e.jsx("span",{children:"VERIXO ERP"}),e.jsxs("span",{children:[B.sourceInvoiceNo||"Purchase"," | Page: 1 of 1"]})]})]})]})})})(),je&&(()=>{const B=n.find(Qt=>Qt.id===je.branchId),xe=T.find(Qt=>Qt.id===je.customerId),tt=(xe==null?void 0:xe.name)||(xe==null?void 0:xe.customerName)||je.customerName||"Customer",ht=(xe==null?void 0:xe.phone)||(xe==null?void 0:xe.mobile)||je.customerPhone||"",dt=(xe==null?void 0:xe.address)||"",we=je.invoiceDate||(je.createdAt?new Date(je.createdAt).toLocaleDateString("en-GB"):"â"),rt=(B==null?void 0:B.address)||f||"",St=(B==null?void 0:B.phone)||u||"";return e.jsxs("div",{className:"report-invoice-fullpage",children:[" ",e.jsxs("div",{className:"report-invoice-document-modal",children:[e.jsxs("div",{className:"modal-header report-invoice-toolbar",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Invoice Preview"}),e.jsx("h2",{children:je.invoiceNumber}),e.jsx("span",{children:je.jobNumber||"Sales Invoice"})]}),e.jsxs("div",{className:"report-invoice-toolbar-actions",children:[e.jsx("button",{type:"button",className:"report-invoice-action-button",onClick:()=>window.print(),title:"Print invoice","aria-label":"Print invoice",children:e.jsx(Wi,{size:18})}),e.jsx("button",{type:"button",className:"report-invoice-close-button",onClick:()=>V(null),title:"Close preview","aria-label":"Close invoice preview",children:e.jsx(ja,{size:18})})]})]}),e.jsxs("div",{className:`report-invoice-sheet ${P==="letterhead"?"letterhead-mode":""}`,children:[e.jsx("div",{className:"report-invoice-company-header","aria-hidden":P==="letterhead",children:P==="verixo"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("h1",{children:d}),f&&e.jsx("p",{children:f}),u&&e.jsx("p",{children:u})]}),e.jsxs("div",{className:"report-invoice-title",children:[e.jsx("strong",{children:"INVOICE"}),e.jsx("span",{children:je.invoiceNumber}),e.jsx("small",{children:we})]})]})}),e.jsxs("div",{className:"report-invoice-branch",children:[e.jsx("span",{children:"LOCATION / BRANCH"}),e.jsx("strong",{children:(B==null?void 0:B.name)||"â"}),rt&&e.jsx("p",{children:rt}),St&&e.jsx("p",{children:St})]}),e.jsxs("div",{className:"report-invoice-parties",children:[e.jsxs("div",{children:[e.jsx("span",{children:"BILL TO"}),e.jsx("strong",{children:tt}),ht&&e.jsx("p",{children:ht}),dt&&e.jsx("p",{children:dt})]}),e.jsxs("div",{children:[e.jsx("span",{children:"SERVICE / REFERENCE"}),e.jsx("strong",{children:je.jobNumber||"Sales Invoice"}),je.deviceLabel&&e.jsx("p",{children:je.deviceLabel}),e.jsxs("p",{children:["Status: ",Number(je.dueAmount||0)<=0?"Paid":Number(je.collectedAmount||0)>0?"Partially Paid":"Due"]})]})]}),e.jsxs("table",{className:"report-invoice-lines",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Description"}),e.jsx("th",{children:"Qty"}),e.jsx("th",{className:"num",children:"Amount"})]})}),e.jsxs("tbody",{children:[Number(je.labourCharge||0)>0&&e.jsxs("tr",{children:[e.jsx("td",{children:"Service Charges"}),e.jsx("td",{children:"1"}),e.jsx("td",{className:"num",children:fs(Number(je.labourCharge||0))})]}),Number(je.partsTotal||0)>0&&e.jsxs("tr",{children:[e.jsx("td",{children:"Parts / Products"}),e.jsx("td",{children:"1"}),e.jsx("td",{className:"num",children:fs(Number(je.partsTotal||0))})]}),Number(je.labourCharge||0)<=0&&Number(je.partsTotal||0)<=0&&e.jsxs("tr",{children:[e.jsx("td",{children:"Sales Invoice"}),e.jsx("td",{children:"1"}),e.jsx("td",{className:"num",children:fs(Number(je.subtotal||je.grandTotal||0))})]})]})]}),e.jsxs("div",{className:"report-invoice-bottom",children:[e.jsx("div",{className:`report-payment-stamp ${Number(je.dueAmount||0)<=0?"paid":"due"}`,children:Number(je.dueAmount||0)<=0?"PAID":"DUE"}),e.jsxs("div",{className:"report-invoice-totals",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Subtotal"}),e.jsx("strong",{children:fs(Number(je.subtotal||0))})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Discount"}),e.jsxs("strong",{children:["- ",fs(Number(je.discount||0))]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"VAT"}),e.jsx("strong",{children:fs(Number(je.vat||0))})]}),e.jsxs("div",{className:"grand",children:[e.jsx("span",{children:"Grand Total"}),e.jsx("strong",{children:fs(Number(je.grandTotal||0))})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Collected"}),e.jsx("strong",{children:fs(Number(je.collectedAmount||0))})]}),e.jsxs("div",{className:"due",children:[e.jsx("span",{children:"Due"}),e.jsx("strong",{children:fs(Number(je.dueAmount||0))})]})]})]}),e.jsxs("div",{className:"report-invoice-signatures",children:[e.jsx("span",{children:"Received By"}),e.jsx("span",{children:"Checked By"}),e.jsx("span",{children:"Authorized By"})]})]})]})]})})()]})}const Mj=()=>new Date().toISOString().slice(0,10),ii=t=>String(t??"").replace(/[&<>"']/g,n=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[n]||n),zi=t=>
4002Number(t||0).toLocaleString("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2}),B_=t=>{var n;return Number(t.totalDebit||((n=t.lines)==null?void 0:n.reduce((a,s)=>a+Number(s.debit||0),0))||0)},qE=t=>`${t.sourceType||""} ${t.narration||""} ${t.reference||""}`.toLowerCase(),VE=t=>(t.lines||[]).filter(n=>Number(n.debit||0)>0).map(n=>String(n.accountName||"")).filter(Boolean),dU=t=>(t.lines||[]).filter(n=>Number(n.credit||0)>0).map(n=>String(n.accountName||"")).filter(Boolean),op=t=>{const n=VE(t).join(" ").toLowerCase();return n.includes("cash")?"Cash":n.includes("bkash")?"bKash":n.includes("nagad")?"Nagad":n.includes("cheque")?"Cheque":n.includes("bank")||n.includes("account")?"Bank / TT":n.includes("receivable")?"Credit":""};function uU(t){const n=String(t.type||"").toLowerCase(),a=qE(t);return a.includes("historical sales")||a.includes("historical_sale")?{p:"Sales",tt:op(t)||"Credit",normal:"cr"}:a.includes("sales return")?{p:"Sales Return",tt:"",normal:"dr"}:a.includes("purchase return")?{p:"Purchase Return",tt:"",normal:"cr"}:(a.includes("purchase")||a.includes("supplier"))&&n==="payment"?{p:"Payment",tt:op(t)||"Supplier",normal:"cr"}:a.includes("purchase")&&n!=="payment"?{p:"Purchase",tt:"",normal:"dr"}:n==="receipt"?{p:"Collection",tt:op(t)||"Receipt",normal:"dr"}:n==="payment"?{p:"Payment",tt:op(t)||"Payment",normal:"cr"}:n==="contra"?{p:"Contra Voucher",tt:"",normal:"dr"}:n==="journal"?{p:"Journal Voucher",tt:"",normal:"dr"}:{p:"Other Transaction",tt:"",normal:"dr"}}const hU="@page{size:A4 portrait;margin:10mm 9mm 12mm}*{box-sizing:border-box}html{background:#eef3f8}body{font-family:Arial,Helvetica,sans-serif;color:#172b3f;font-size:9px;margin:0;background:#eef3f8}.preview-shell{max-width:900px;margin:18px auto 30px}.toolbar{display:flex;justify-content:flex-end;margin:0 0 10px}.vx-action{appearance:none;border:0;border-radius:9px;background:#173f63;color:#fff;padding:9px 15px;font-size:12px;font-weight:800;letter-spacing:.1px;box-shadow:0 5px 14px rgba(23,63,99,.18);cursor:pointer}.vx-action:hover{background:#0f3150}.paper{background:#fff;border:1px solid #d6e0e9;border-radius:8px;box-shadow:0 14px 34px rgba(28,55,82,.13);padding:18px 20px 15px}.head{display:grid;grid-template-columns:1.4fr .9fr;gap:18px;align-items:end;padding-bottom:11px;border-bottom:3px solid #173f63;margin-bottom:10px}.company h1{font-size:17px;margin:0 0 4px;color:#173f63;letter-spacing:.15px}.company div{font-size:8px;color:#617386}.report-title{text-align:right}.report-title strong{display:block;font-size:15px;color:#173f63}.report-title span{display:block;margin-top:4px;color:#64748b;font-size:8px}.meta{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px}.meta-box{border:1px solid #d8e2eb;border-left:3px solid #6d8da9;border-radius:5px;padding:6px 8px;background:#f9fbfd}.meta-box b{display:block;font-size:7px;letter-spacing:.55px;text-transform:uppercase;color:#718397;margin-bottom:2px}.meta-box span{font-size:8.5px;font-weight:700}.section-title{font-size:9px;font-weight:800;color:#173f63;margin:9px 0 5px}.summary{width:100%;border-collapse:separate;border-spacing:0;border:1px solid #cdd9e4;border-radius:5px;overflow:hidden}.summary th,.summary td{padding:4px 5px;border-right:1px solid #d7e1ea;border-bottom:1px solid #d7e1ea}.summary th:last-child,.summary td:last-child{border-right:0}.summary tr:last-child td{border-bottom:0}.summary th{background:#edf3f8;text-align:center;font-size:7.5px;letter-spacing:.35px;color:#334e68}.summary tbody tr:nth-child(even):not(.grand){background:#fbfcfe}.summary .num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}.summary .type{width:16%}.summary .part{width:26%;font-weight:700}.summary .grand td{font-weight:800;background:#e8f0f6;border-top:2px solid #6d8da9;color:#173f63}.drcr{display:inline-block;min-width:20px;text-align:right;font-style:italic;font-size:7px;margin-left:3px;color:#65788a}.details{width:100%;border-collapse:separate;border-spacing:0;border:1px solid #cdd9e4;border-radius:5px;overflow:hidden;table-layout:fixed}.details th{background:#edf3f8;border-right:1px solid #d7e1ea;border-bottom:1px solid #cdd9e4;padding:4px 4px;text-align:left;
4002font-size:7px;color:#334e68}.details td{border-right:1px solid #e1e8ef;border-bottom:1px solid #e1e8ef;padding:4px;vertical-align:top;font-size:7.2px;line-height:1.25;overflow-wrap:anywhere}.details th:last-child,.details td:last-child{border-right:0}.details tr:last-child td{border-bottom:0}.details tbody tr:nth-child(even){background:#fbfcfe}.details .num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}.details tr{break-inside:avoid}.details .c-no{width:3%}.details .c-date{width:9%}.details .c-type{width:10%}.details .c-ref{width:17%}.details .c-party{width:14%}.details .c-part{width:20%}.details .c-acct{width:15%}.details .c-money{width:6%}.foot{display:flex;justify-content:space-between;margin-top:9px;padding-top:6px;border-top:1px solid #d5dee7;color:#6b7c8e;font-size:7px}@media print{html,body{background:#fff}.preview-shell{max-width:none;margin:0}.toolbar{display:none}.paper{border:0;border-radius:0;box-shadow:none;padding:0}.head{margin-top:0}.summary,.details{border-radius:0}.details thead{display:table-header-group}.foot{position:relative}}";function mU({profile:t,branches:n,selectedBranchId:a,companyName:s,companyPhone:i,companyAddress:c}){const[l,m]=x.useState(Mj()),[d,u]=x.useState(Mj()),[f,g]=x.useState(a||"all"),[p,y]=x.useState("summary"),[b,N]=x.useState([]),[w,C]=x.useState([]),[R,I]=x.useState([]),[_,J]=x.useState([]),[T,G]=x.useState([]),[z,H]=x.useState([]);x.useEffect(()=>qt(re(ie,`accountingVouchers/${t.companyId}`),V=>{const $=V.exists()?V.val():{};N(Object.entries($).map(([F,P])=>({id:F,...P})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`historicalPurchases/${t.companyId}`),V=>{const $=V.exists()?V.val():{};C(Object.entries($).map(([F,P])=>({id:F,...P})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`invoices/${t.companyId}`),V=>{const $=V.exists()?V.val():{};I(Object.entries($).map(([F,P])=>({id:F,...P})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`historicalSales/${t.companyId}`),V=>{const $=V.exists()?V.val():{};J(Object.entries($).map(([F,P])=>({id:F,...P})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`collections/${t.companyId}`),V=>{const $=V.exists()?V.val():{};G(Object.entries($).map(([F,P])=>({id:F,...P})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`inventoryStock/${t.companyId}`),V=>{const $=V.exists()?V.val():{},F=[];Object.entries($||{}).forEach(([P,ue])=>Object.values(ue||{}).forEach(me=>F.push({...me,branchKey:P}))),H(F)}),[t.companyId]);const K=x.useMemo(()=>{if(Sp(t))return n;const V=new Set(_h(t));return n.filter($=>V.has($.id))},[t,n]);x.useEffect(()=>{a&&a!=="all"&&g(a)},[a]);const L=V=>f==="all"||V.branchId===f,D=V=>{const $=String(V.type||"").toLowerCase(),F=qE(V),P=String(V.voucherNo||V.id||"").toUpperCase();return String(V.sourceType||"").toLowerCase()==="historical_purchase_import"||$==="journal"&&(P.startsWith("AUTO-")||F.includes("service invoice recognized")||F.includes("sales invoice recognized"))},M=x.useMemo(()=>b.filter(V=>V.status==="posted"&&L(V)),[b,f]),Z=x.useMemo(()=>M.filter(V=>!D(V)&&!V.reversedByVoucherId&&String(V.sourceType||"").toLowerCase()!=="historical_sales_import_reversal"),[M]),fe=x.useMemo(()=>Z.filter(V=>String(V.voucherDate||"")>=l&&String(V.voucherDate||"")<=d),[Z,l,d]),q=x.useMemo(()=>w.filter(V=>L(V)&&String(V.purchaseDate||"")>=l&&String(V.purchaseDate||"")<=d),[w,f,l,d]),ne=x.useMemo(()=>new Map(R.map(V=>[V.id,V])),[R]),ae=x.useMemo(()=>new Map(T.map(V=>[V.id,V])),[T]),Y=V=>{const $=uU(V);if(String(V.sourceType||"").toLowerCase()!=="service_collection")return $;const F=ae.get(String(V.sourceId||"")),P=F!=null&&F.invoiceId?ne.get(F.invoiceId):void 0,ue=String(V.voucherDate||""),me=String((P==null?void 0:P.invoiceDate)||"");return P&&me&&me===ue?{p:"Sales",tt:`Immediate Receipt · ${op(V)||"Receipt"}`,normal:"cr"}:{p:"Collection",tt:`Previous Due · ${op(V)||"Receipt"}`,normal:"dr"}},je=()=>{var Re;if(!l||!d||l>d){alert("Please select a valid date range.");return}const V=window.open("","_blank");if(!V){alert("PDF preview was blocked by the browser. Please allow pop-ups and try again.");return}const $=f==="all"?"All Locations":((Re=K.find(Ee=>Ee.id===f))==null?void 0:Re.name)||"Selected Location",F=new Map,P=(Ee,Be,We,it,_e)=>{const ee=`${Ee}|${Be}`,qe=F.get(ee)||{particular:Ee,transactionType:Be,opening:0,debit:0,credit:0,closing:0,normal:We};it==="opening"?qe.opening+=_e:We==="dr"?qe.debit+=_e:qe.credit+=_e,F.set(ee,qe)};Z.forEach(Ee=>{const Be=String(Ee.voucherDate||""),We=Y(Ee),it=B_(Ee);Be<l?P(We.p,We.tt,We.normal,"opening",it):Be<=d&&P(We.p,We.tt,We.normal,"period",it)}
4002),w.filter(L).forEach(Ee=>{const Be=String(Ee.purchaseDate||""),We=Number(Ee.totalAmount||0);!Be||!We||(Be<l?P("Purchase","","dr","opening",We):Be<=d&&P("Purchase","","dr","period",We))});const ue=["Sales","Sales Return","Collection","Purchase","Purchase Return","Payment","Contra Voucher","Credit Voucher","Debit Voucher","Journal Voucher","Party Adjustment (Customer)","Party Adjustment (Supplier)","Other Transaction"],me=[...F.values()].map(Ee=>({...Ee,closing:Ee.normal==="dr"?Ee.opening+Ee.debit-Ee.credit:Ee.opening+Ee.credit-Ee.debit})).sort((Ee,Be)=>ue.indexOf(Ee.particular)-ue.indexOf(Be.particular)||Ee.transactionType.localeCompare(Be.transactionType)),ge=(Ee,Be)=>`${zi(Math.abs(Ee))} <span class="drcr">(${Be==="dr"?"Dr":"Cr"})</span>`,de=`<div class="toolbar"><button class="vx-action" onclick="window.print()">Print / Save PDF</button></div><div class="paper"><div class="head"><div class="company"><h1>${ii(s||"VERIXO")}</h1><div>${ii(c||"")}${i?` · ${ii(i)}`:""}</div></div><div class="report-title"><strong>${p==="summary"?"Day Book Summary":"Day Book Details"}</strong><span>${ii(l)} â ${ii(d)}</span></div></div><div class="meta"><div class="meta-box"><b>Location / Branch</b><span>${ii($)}</span></div><div class="meta-box"><b>Currency</b><span>BDT (à§³)</span></div></div><div class="section-title">${p==="summary"?"Accounting Movement Summary":"Transaction Register"}</div>`;let Pe="";if(p==="summary"){let Ee=0,Be=0,We=0,it=0;const _e=me.map((ce,Ye)=>(Ee+=ce.opening,Be+=ce.debit,We+=ce.credit,it+=ce.closing,`<tr><td>${Ye===0||me[Ye-1].particular!==ce.particular?ii(ce.particular):""}</td><td>${ii(ce.transactionType||"")}</td><td class="num">${ge(ce.opening,ce.normal)}</td><td class="num">${ce.debit?zi(ce.debit):"-"}</td><td class="num">${ce.credit?zi(ce.credit):"-"}</td><td class="num">${ge(ce.closing,ce.normal)}</td></tr>`)).join("")||'<tr><td colspan="6" style="text-align:center;padding:18px">No transactions found for this period.</td></tr>',ee=M.filter(ce=>String(ce.voucherDate||"")<=d),qe=ce=>ee.reduce((Ye,Je)=>Ye+(Je.lines||[]).reduce((le,nt)=>ce(String(nt.accountName||""))?le+Number(nt.debit||0)-Number(nt.credit||0):le,0),0),se=qe(ce=>ce.toLowerCase().includes("cash in hand")),pe=qe(ce=>{const Ye=ce.toLowerCase();return Ye.includes("bank")&&!Ye.includes("cash")}),Se=qe(ce=>/bkash|nagad|mfs/i.test(ce)),Me=qe(ce=>ce.toLowerCase().includes("accounts receivable")),ot=-qe(ce=>ce.toLowerCase().includes("accounts payable")),wt=new Map(R.filter(L).map(ce=>[String(ce.invoiceNumber||""),ce])),ct=new Map(_.filter(L).map(ce=>[String(ce.sourceInvoiceNo||""),ce])),Ce=new Map;ee.forEach(ce=>{const Ye=(ce.lines||[]).filter(te=>String(te.accountName||"").toLowerCase().includes("accounts receivable"));if(!Ye.length)return;const Je=String(ce.reference||ce.voucherNo||ce.id),le=wt.get(Je),nt=ct.get(Je),xt=Ce.get(Je)||{invoice:Je,date:String((le==null?void 0:le.invoiceDate)||(nt==null?void 0:nt.saleDate)||ce.voucherDate||""),customer:String((le==null?void 0:le.customerName)||(nt==null?void 0:nt.customer)||""),debit:0,credit:0,balance:0};Ye.forEach(te=>{xt.debit+=Number(te.debit||0),xt.credit+=Number(te.credit||0)}),xt.balance=xt.debit-xt.credit,Ce.set(Je,xt)});const De=[...Ce.values()].filter(ce=>ce.balance>.005).sort((ce,Ye)=>ce.date.localeCompare(Ye.date)||ce.invoice.localeCompare(Ye.invoice)),Te=De.map((ce,Ye)=>`<tr><td>${Ye+1}</td><td>${ii(ce.date||"â")}</td><td><b>${ii(ce.invoice)}</b></td><td>${ii(ce.customer||"â")}</td><td class="num">${zi(ce.debit)}</td><td class="num">${zi(ce.credit)}</td><td class="num"><b>${zi(ce.balance)}</b></td></tr>`).join("")||`<tr><td colspan="7" style="text-align:center;padding:10px">No outstanding receivable bill as of ${ii(d)}.</td></tr>`;Pe=`<table class="summary"><thead><tr><th class="part">Particulars</th><th class="type">Transaction Type</th><th>Opening (à§³)</th><th>Debit (à§³)</th><th>Credit (à§³)</th><th>Closing (à§³)</th></tr></thead><tbody>${_e}<tr class="grand"><td colspan="2" style="text-align:right">Movement Total (à§³)</td><td class="num">${zi(Ee)}</td><td class="num">${zi(Be)}</td><td class="num">${zi(We)}</td><td class="num">â</td></tr></tbody></table><div class="section-title">Closing Position · As of ${ii(d)}</div><table class="summary"><thead><tr><th>
4002Position</th><th>Closing Balance (à§³)</th><th>Status</th></tr></thead><tbody><tr><td>Cash in Hand</td><td class="num">${zi(se)}</td><td>Posted ledger balance up to Date To</td></tr><tr><td>Bank Accounts</td><td class="num">${zi(pe)}</td><td>Posted bank ledgers up to Date To</td></tr><tr><td>MFS Accounts</td><td class="num">${zi(Se)}</td><td>Posted MFS ledgers up to Date To</td></tr><tr><td>Accounts Receivable</td><td class="num">${zi(Me)}</td><td>Posted A/R ledger up to Date To</td></tr><tr><td>Accounts Payable</td><td class="num">${zi(ot)}</td><td>Posted A/P ledger up to Date To</td></tr>${(()=>{const ce=Mj(),Ye=z.filter(xt=>(f==="all"||String(xt.branchId||xt.branchKey)===f)&&Number(xt.qty||0)>0),Je=Ye.filter(xt=>{const te=xt.lastPurchaseCostPerUnit??xt.currentReferenceCostPerUnit;return te!=null&&Number.isFinite(Number(te))&&Number(te)>=0}),le=Je.reduce((xt,te)=>xt+Number(te.qty||0)*Number(te.lastPurchaseCostPerUnit??te.currentReferenceCostPerUnit??0),0),nt=Ye.length>0&&Je.length===Ye.length;return d===ce&&nt?`<tr><td>Closing Stock Value</td><td class="num">${zi(le)}</td><td>Current inventory valuation · ${Je.length}/${Ye.length} positive-stock item(s) costed</td></tr>`:d===ce?`<tr><td>Closing Stock Value</td><td class="num">â</td><td>Current valuation incomplete · ${Je.length}/${Ye.length} positive-stock item(s) have cost · not guessed</td></tr>`:`<tr><td>Closing Stock Value</td><td class="num">â</td><td>Historical valuation as of ${ii(d)} unavailable from authoritative cost ledger · current/reference cost not back-applied</td></tr>`})()}</tbody></table><div class="section-title">Accounts Receivable · Outstanding Bill Breakdown</div><table class="summary"><thead><tr><th>#</th><th>Invoice Date</th><th>Invoice / Bill</th><th>Customer</th><th>A/R Debit (à§³)</th><th>Settled (à§³)</th><th>Outstanding (à§³)</th></tr></thead><tbody>${Te}<tr class="grand"><td colspan="6" style="text-align:right">Total Outstanding Receivable (à§³)</td><td class="num">${zi(De.reduce((ce,Ye)=>ce+Ye.balance,0))}</td></tr></tbody></table>`}else{const Ee=[];fe.forEach(We=>{const it=Y(We),_e=VE(We),ee=dU(We),qe=B_(We);Ee.push({date:String(We.voucherDate||""),type:it.p,reference:String(We.reference||We.voucherNo||We.id),party:"",particulars:String(We.narration||it.p),account:`${_e.join(", ")||"â"}${ee.length?` â ${ee.join(", ")}`:""}`,debit:it.normal==="dr"?qe:0,credit:it.normal==="cr"?qe:0,createdAt:Number(We.createdAt||0)})}),q.forEach(We=>Ee.push({date:String(We.purchaseDate||""),type:"Purchase",reference:String(We.sourceInvoiceNo||We.supplierInvoiceRefNo||We.id),party:String(We.supplier||""),particulars:`Historical Purchase${We.supplier?` · ${We.supplier}`:""}`,account:"Purchase / Inventory",debit:Number(We.totalAmount||0),credit:0,createdAt:Number(We.createdAt||0)})),Ee.sort((We,it)=>We.date.localeCompare(it.date)||We.createdAt-it.createdAt),Pe=`<table class="details"><thead><tr><th class="c-no">#</th><th class="c-date">Date</th><th class="c-type">Transaction</th><th class="c-ref">Invoice / Voucher</th><th class="c-party">Party</th><th class="c-part">Particulars</th><th class="c-acct">Account / Mode</th><th class="c-money">Debit</th><th class="c-money">Credit</th></tr></thead><tbody>${Ee.map((We,it)=>`<tr><td>${it+1}</td><td>${ii(We.date)}</td><td>${ii(We.type)}</td><td><b>${ii(We.reference)}</b></td><td>${ii(We.party||"â")}</td><td>${ii(We.particulars)}</td><td>${ii(We.account)}</td><td class="num">${We.debit?zi(We.debit):"-"}</td><td class="num">${We.credit?zi(We.credit):"-"}</td></tr>`).join("")||'<tr><td colspan="9" style="text-align:center;padding:18px">No transactions found for this period.</td></tr>'}</tbody></table>`}V.document.write(`<!doctype html><html><head><title>${p==="summary"?"Day Book Summary":"Day Book Details"}</title><style>${hU}</style></head><body><div class="preview-shell">${de}${Pe}<div class="foot"><span>VERIXO · Read-only Day Book</span><span>Generated ${ii(new Date().toLocaleString("en-BD"))}</span></div></div></div></body></html>`),V.document.close(),V.focus()};return e.jsx("div",{style:{maxWidth:1080,margin:"0 auto"},children:e.jsxs("div",{style:{border:"1px solid #dce5ef",borderRadius:16,background:"#fff",overflow:"hidden",boxShadow:"0 10px 28px rgba(27,55,86,.07)"},children:[e.jsxs("div",{style:{padding:"26px 30px",background:"linear-gradient(135deg,#f8fbfe 0%,#eef5fb 100%)",borderBottom:"1px solid #dce5ef",display:"flex",justifyContent:"space-between",gap:20,alignItems:"center"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12,fontWeight:800,letterSpacing:1.2,color:"#4d6f8e",textTransform:"uppercase"},children:"Accounts & Finance Reports"}),e.jsx("h2",{style:{margin:"5px 0",fontSize:27,color:"#173b60"},children:"Day Book"}),e.jsx("div",{style:{color:"#64748b"},children:"Generate a traditional accounting summary or transaction-wise supporting details."})]}),e.jsx(Zs,{size:32})]}),e.jsxs("div",{style:{padding:"28px 30px"},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2,minmax(0,1fr))",gap:18},children:[e.jsxs("div",{children:[e.jsx("label",{children:"Report Type *"}),e.jsxs("select",{value:p,onChange:V=>y(V.target.value),style:{width:"100%"},children:[e.jsx("option",{value:"summary",children:"Day Book Summary"}),e.jsx("option",{value:"details",children:"Day Book Details"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{children:[e.jsx(ED,{size:14})," Location / Branch"]}),e.jsxs("select",{value:f,onChange:V=>g(V.target.value),style:{width:"100%"},children:[e.jsx("option",{value:"all",children:"All Locations"}),K.map(V=>e.jsx("option",{value:V.id,children:V.name},V.id))]})]}),e.jsxs("div",{children:[e.jsxs("label",{children:[e.jsx(wi,{size:14})," Date From *"]}),e.jsx("input",{style:{width:"100%"}
4002,type:"date",value:l,onChange:V=>m(V.target.value)})]}),e.jsxs("div",{children:[e.jsxs("label",{children:[e.jsx(wi,{size:14})," Date To *"]}),e.jsx("input",{style:{width:"100%"},type:"date",value:d,onChange:V=>u(V.target.value)})]}),e.jsxs("div",{children:[e.jsxs("label",{children:[e.jsx(Ll,{size:14})," Currency"]}),e.jsx("select",{disabled:!0,style:{width:"100%"},children:e.jsx("option",{children:"à§³ â BDT"})})]}),e.jsxs("div",{children:[e.jsx("label",{children:"Output Format"}),e.jsx("select",{disabled:!0,style:{width:"100%"},children:e.jsx("option",{children:"PDF Preview"})})]})]}),e.jsxs("div",{style:{marginTop:26,paddingTop:20,borderTop:"1px solid #e1e8f0",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("small",{children:"Read-only · no stock, accounting or migration data is changed."}),e.jsxs("button",{className:"primary-action",onClick:je,children:[e.jsx(Zs,{size:17})," Generate Report"]})]})]})]})})}const pu={received:"Received",inspection:"Inspection",sent_to_supplier:"Sent to Supplier",supplier_received:"Supplier Received",under_process:"Under Process",repaired:"Repaired",replaced:"Replaced",rejected:"Rejected",returned:"Returned",customer_ready:"Customer Ready",delivered:"Delivered",closed:"Closed"},F_={received:["inspection","sent_to_supplier","rejected"],inspection:["sent_to_supplier","repaired","replaced","rejected"],sent_to_supplier:["supplier_received","returned"],supplier_received:["under_process","rejected"],under_process:["repaired","replaced","rejected","returned"],repaired:["returned","customer_ready","delivered"],replaced:["returned","customer_ready","delivered"],rejected:["returned","customer_ready","closed"],returned:["customer_ready","delivered","closed"],customer_ready:["delivered","closed"],delivered:["closed"],closed:[]},pU=["received","inspection","sent_to_supplier","supplier_received","under_process","repaired","replaced","returned","customer_ready"];function $j(t){return{rmaType:"customer",branchId:t,partyName:"",partyPhone:"",partyAddress:"",supplierName:"",productName:"",brand:"",model:"",serialNumber:"",invoiceReference:"",challanReference:"",purchaseSource:"",purchaseDate:"",warrantyUntil:"",problem:"",accessories:"",physicalCondition:"",notes:""}}function fU(){const n=new Date().getFullYear(),a=String(Date.now()).slice(-6);return`VRX-RMA-${n}-${a}`}function Oj(t){const n=t.closedAt||Date.now();return Math.max(0,Math.floor((n-t.createdAt)/864e5))}function gU({profile:t,branches:n,selectedBranchId:a}){var D;const s=["super_admin","owner","admin","branch_manager","service_incharge","reception","operator"].includes(t.role),i=a==="all"?((D=n[0])==null?void 0:D.id)||t.branchId||"":a,[c,l]=x.useState([]),[m,d]=x.useState(""),[u,f]=x.useState("all"),[g,p]=x.useState("all"),[y,b]=x.useState(!1),[N,w]=x.useState(null),[C,R]=x.useState(!1),[I,_]=x.useState($j(i));x.useEffect(()=>qt(re(ie,`rmas/${t.companyId}`),M=>{if(!M.exists()){l([]);return}const Z=M.val();l(Object.entries(Z).map(([fe,q])=>({id:fe,...q})).sort((fe,q)=>q.createdAt-fe.createdAt))}),[t.companyId]),x.useEffect(()=>{y&&_(M=>{var Z;return{...M,branchId:a==="all"?M.branchId||((Z=n[0])==null?void 0:Z.id)||"":a}})},[y,a,n]);const J=x.useMemo(()=>{const M=m.trim().toLowerCase();return c.filter(Z=>{const fe=a==="all"||Z.branchId===a,q=u==="all"||Z.rmaType===u,ne=g==="all"||Z.status===g,ae=!M||[Z.rmaNumber,Z.partyName,Z.partyPhone,Z.supplierName,Z.productName,Z.brand,Z.model,Z.serialNumber,Z.invoiceReference,Z.supplierClaimNumber].filter(Boolean).some(Y=>String(Y).toLowerCase().includes(M));return fe&&q&&ne&&ae})},[c,a,u,g,m]),T=x.useMemo(()=>({total:J.length,open:J.filter(M=>pU.includes(M.status)).length,supplier:J.filter(M=>["sent_to_supplier","supplier_received","under_process"].includes(M.status)).length,ready:J.filter(M=>M.status==="customer_ready").length,delivered:J.filter(M=>["delivered","closed"].includes(M.status)).length}),[J]),G=()=>{w(null),_($j(i)),b(!0)},z=async()=>{if(!I.branchId||!I.partyName.trim()||!I.productName.trim()||!I.problem.trim()||I.rmaType==="supplier"&&!I.supplierName.trim()){window.alert("Branch, Party/Customer, Product, Problem à¦à¦¬à¦ Supplier RMA হলৠSupplier Name পà§à¦°à¦£ à¦à¦°à§à¦¨à¥¤");return}R(!0);try{const M=Date.now(),Z=Ta(re(ie,`rmas/${t.companyId}`)),fe=fU(),q={companyId:t.companyId,branchId:I.branchId,rmaNumber:fe,rmaType:I.rmaType,partyName:I.partyName.trim(),partyPhone:I.partyPhone.trim(),partyAddress:I.partyAddress.trim(),supplierName:I.supplierName.trim(),productName:I.productName.trim(),brand:I.brand.trim(),model:I.model.trim(),serialNumber:I.serialNumber.trim(),invoiceReference:I.invoiceReference.trim(),challanReference:I.challanReference.trim(),purchaseSource:I.purchaseSource.trim(),purchaseDate:I.purchaseDate,warrantyUntil:I.warrantyUntil,problem:I.problem.trim(),accessories:I.accessories.trim(),physicalCondition:I.physicalCondition.trim(),notes:I.notes.trim(),status:"received",createdByUid:t.uid,createdByName:t.name,createdAt:M,updatedAt:M};await Pn(Z,q);const ne=Ta(re(ie,`rmaTimeline/${t.companyId}/${Z.key}`));await Pn(ne,{status:"received",label:pu.received,note:"RMA created",actorUid:t.uid,actorName:t.name,createdAt:M}),await ia({companyId:t.companyId,branchId:I.branchId,actorUid:t.uid,actorName:t.name,action:"rma.created",entityType:"rma",entityId:String(Z.key),summary:`${fe} created for ${I.partyName.trim()}`,metadata:{rmaType:I.rmaType,productName:I.productName.trim(),serialNumber:I.serialNumber.trim()}}),b(!1),_($j(i))}
4002catch(M){console.error("RMA create failed:",M),window.alert("RMA তà§à¦°à¦¿ à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤")}finally{R(!1)}},H=async(M,Z)=>{if(!s||Z===M.status)return;const fe=Date.now();try{await yn(re(ie,`rmas/${t.companyId}/${M.id}`),{status:Z,updatedAt:fe,closedAt:["delivered","closed"].includes(Z)?fe:null});const q=Ta(re(ie,`rmaTimeline/${t.companyId}/${M.id}`));await Pn(q,{fromStatus:M.status,status:Z,label:pu[Z],actorUid:t.uid,actorName:t.name,createdAt:fe}),await ia({companyId:t.companyId,branchId:M.branchId,actorUid:t.uid,actorName:t.name,action:"rma.updated",entityType:"rma",entityId:M.id,summary:`${M.rmaNumber} moved to ${pu[Z]}`,metadata:{previousStatus:M.status,nextStatus:Z}})}catch(q){console.error("RMA status update failed:",q),window.alert("RMA status update à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤")}},K=async(M,Z)=>{!N||!s||(await yn(re(ie,`rmas/${t.companyId}/${N.id}`),{[M]:Z,updatedAt:Date.now()}),w({...N,[M]:Z,updatedAt:Date.now()}))},L=()=>{hc(`rma-report-${new Date().toISOString().slice(0,10)}.csv`,J.map(M=>({"RMA No":M.rmaNumber,Type:M.rmaType==="customer"?"Customer RMA":"Supplier RMA",Date:new Date(M.createdAt).toLocaleDateString("en-GB"),Party:M.partyName,Supplier:M.supplierName||"",Product:[M.productName,M.brand,M.model].filter(Boolean).join(" "),Serial:M.serialNumber||"","Invoice/Challan":M.invoiceReference||M.challanReference||"",Status:pu[M.status],"Days Open":Oj(M)})))};return e.jsxs("section",{className:"rma-page",children:[e.jsxs("header",{className:"rma-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Warranty & Returns"}),e.jsx("h1",{children:"RMA Management"}),e.jsx("p",{children:"Customer and supplier warranty claims with a simple service-center workflowâno courier or tracking fields."})]}),e.jsxs("div",{className:"rma-header-actions",children:[e.jsxs("button",{className:"secondary-action",type:"button",onClick:L,children:[e.jsx(Mi,{size:17})," Export CSV"]}),s&&e.jsxs("button",{className:"primary-action",type:"button",onClick:G,children:[e.jsx(as,{size:18})," New RMA"]})]})]}),e.jsxs("section",{className:"rma-stats",children:[e.jsxs("article",{children:[e.jsx(Tu,{size:19}),e.jsx("span",{children:"Total RMA"}),e.jsx("strong",{children:T.total})]}),e.jsxs("article",{children:[e.jsx(W4,{size:19}),e.jsx("span",{children:"Open"}),e.jsx("strong",{children:T.open})]}),e.jsxs("article",{children:[e.jsx(t6,{size:19}),e.jsx("span",{children:"With Supplier"}),e.jsx("strong",{children:T.supplier})]}),e.jsxs("article",{children:[e.jsx(Jw,{size:19}),e.jsx("span",{children:"Customer Ready"}),e.jsx("strong",{children:T.ready})]}),e.jsxs("article",{children:[e.jsx(gs,{size:19}),e.jsx("span",{children:"Delivered/Closed"}),e.jsx("strong",{children:T.delivered})]})]}),e.jsxs("section",{className:"rma-filter-bar",children:[e.jsxs("label",{className:"rma-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:m,onChange:M=>d(M.target.value),placeholder:"Search RMA, customer, serial, invoice..."})]}),e.jsxs("select",{value:u,onChange:M=>f(M.target.value),children:[e.jsx("option",{value:"all",children:"All Types"}),e.jsx("option",{value:"customer",children:"Customer RMA"}),e.jsx("option",{value:"supplier",children:"Supplier RMA"})]}),e.jsxs("select",{value:g,onChange:M=>p(M.target.value),children:[e.jsx("option",{value:"all",children:"All Statuses"}),Object.entries(pu).map(([M,Z])=>e.jsx("option",{value:M,children:Z},M))]}),e.jsxs("button",{type:"button",className:"rma-reset",onClick:()=>{d(""),f("all"),p("all")},children:[e.jsx(Hi,{size:16})," Reset"]})]}),e.jsx("section",{className:"rma-table-card",children:e.jsx("div",{className:"rma-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"RMA"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Party"}),e.jsx("th",{children:"Product / Serial"}),e.jsx("th",{children:"Reference"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Age"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[J.map(M=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("button",{className:"rma-number-button",type:"button",onClick:()=>w(M),children:M.rmaNumber}),e.jsx("small",{children:new Date(M.createdAt).toLocaleDateString("en-GB")})]}),e.jsx("td",{children:e.jsx("span",{className:`rma-type ${M.rmaType}`,children:M.rmaType==="customer"?"Customer":"Supplier"})}),e.jsxs("td",{children:[e.jsx("strong",{children:M.partyName}),e.jsx("small",{children:M.partyPhone||M.supplierName||"â"})]}),e.jsxs("td",{children:[e.jsx("strong",{children:[M.productName,M.brand,M.model].filter(
4002Boolean).join(" ")}),e.jsxs("small",{children:["SN: ",M.serialNumber||"Not provided"]})]}),e.jsx("td",{children:M.invoiceReference||M.challanReference||M.supplierClaimNumber||"â"}),e.jsx("td",{children:e.jsx("span",{className:`rma-status status-${M.status}`,children:pu[M.status]})}),e.jsxs("td",{children:[Oj(M)," day(s)"]}),e.jsx("td",{children:e.jsxs("button",{className:"rma-view-button",type:"button",onClick:()=>w(M),children:["View ",e.jsx(y1,{size:14})]})})]},M.id)),!J.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"rma-empty",children:"No RMA records found."})})]})]})})}),y&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!C&&b(!1),children:e.jsxs("section",{className:"modal rma-modal",onMouseDown:M=>M.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"New Warranty Claim"}),e.jsx("h2",{children:"Create RMA"})]}),e.jsx("button",{disabled:C,onClick:()=>b(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"rma-form-grid",children:[e.jsxs("label",{children:["RMA Type *",e.jsxs("select",{value:I.rmaType,onChange:M=>_({...I,rmaType:M.target.value}),children:[e.jsx("option",{value:"customer",children:"Customer RMA"}),e.jsx("option",{value:"supplier",children:"Supplier RMA"})]})]}),e.jsxs("label",{children:["Branch *",e.jsx("select",{value:I.branchId,onChange:M=>_({...I,branchId:M.target.value}),children:n.map(M=>e.jsx("option",{value:M.id,children:M.name},M.id))})]}),e.jsxs("label",{children:[I.rmaType==="customer"?"Customer Name *":"Party / Department *",e.jsx("input",{value:I.partyName,onChange:M=>_({...I,partyName:M.target.value})})]}),e.jsxs("label",{children:["Phone",e.jsx("input",{value:I.partyPhone,onChange:M=>_({...I,partyPhone:M.target.value})})]}),e.jsxs("label",{className:"span-2",children:["Address",e.jsx("input",{value:I.partyAddress,onChange:M=>_({...I,partyAddress:M.target.value})})]}),I.rmaType==="supplier"&&e.jsxs("label",{className:"span-2",children:["Supplier Name *",e.jsx("input",{value:I.supplierName,onChange:M=>_({...I,supplierName:M.target.value})})]}),e.jsxs("label",{children:["Product Name *",e.jsx("input",{value:I.productName,onChange:M=>_({...I,productName:M.target.value})})]}),e.jsxs("label",{children:["Brand",e.jsx("input",{value:I.brand,onChange:M=>_({...I,brand:M.target.value})})]}),e.jsxs("label",{children:["Model",e.jsx("input",{value:I.model,onChange:M=>_({...I,model:M.target.value})})]}),e.jsxs("label",{children:["Serial Number",e.jsx("input",{value:I.serialNumber,onChange:M=>_({...I,serialNumber:M.target.value})})]}),e.jsxs("label",{children:["Invoice Reference",e.jsx("input",{value:I.invoiceReference,onChange:M=>_({...I,invoiceReference:M.target.value})})]}),e.jsxs("label",{children:["Challan Reference",e.jsx("input",{value:I.challanReference,onChange:M=>_({...I,challanReference:M.target.value})})]}),e.jsxs("label",{children:["Purchase Source",e.jsx("input",{value:I.purchaseSource,onChange:M=>_({...I,purchaseSource:M.target.value})})]}),e.jsxs("label",{children:["Purchase Date",e.jsx("input",{type:"date",value:I.purchaseDate,onChange:M=>_({...I,purchaseDate:M.target.value})})]}),e.jsxs("label",{children:["Warranty Until",e.jsx("input",{type:"date",value:I.warrantyUntil,onChange:M=>_({...I,warrantyUntil:M.target.value})})]}),e.jsxs("label",{className:"span-2",children:["Problem *",e.jsx("textarea",{rows:3,value:I.problem,onChange:M=>_({...I,problem:M.target.value})})]}),e.jsxs("label",{className:"span-2",children:["Accessories",e.jsx("input",{value:I.accessories,onChange:M=>_({...I,accessories:M.target.value})})]}),e.jsxs("label",{className:"span-2",children:["Physical Condition",e.jsx("input",{value:I.physicalCondition,onChange:M=>_({...I,physicalCondition:M.target.value})})]}),e.jsxs("label",{className:"span-2",children:["Internal Notes",e.jsx("textarea",{rows:2,value:I.notes,onChange:M=>_({...I,notes:M.target.value})})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"vx-button vx-button-secondary",disabled:C,onClick:()=>b(!1),children:"Cancel"}),e.jsx("button",{className:"vx-button vx-button-primary",disabled:C,onClick:()=>void z(),children:C?"Savingâ¦":"Create RMA"})]})]})}),N&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>w(null),children:e.jsxs("section",{className:"modal rma-detail-modal",onMouseDown:M=>M.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"RMA Tracking"}),e.jsx("h2",{children:N.rmaNumber})]}),e.jsx("button",{onClick:()=>w(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"rma-detail-summary",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Party"}),e.jsx("strong",{children:N.partyName})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Product"}),e.jsx("strong",{children:[N.productName,N.brand,N.model].filter(
4002Boolean).join(" ")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Serial"}),e.jsx("strong",{children:N.serialNumber||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Days Open"}),e.jsx("strong",{children:Oj(N)})]})]}),e.jsxs("div",{className:"rma-detail-grid",children:[e.jsxs("article",{children:[e.jsx("h3",{children:"RMA Information"}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:N.rmaType})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Service Job"}),e.jsx("dd",{children:N.serviceJobNumber||"Manual RMA"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Problem"}),e.jsx("dd",{children:N.problem})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Invoice"}),e.jsx("dd",{children:N.invoiceReference||"â"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Purchase Source"}),e.jsx("dd",{children:N.purchaseSource||"â"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Warranty Until"}),e.jsx("dd",{children:N.warrantyUntil||"â"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Accessories"}),e.jsx("dd",{children:N.accessories||"â"})]})]})]}),e.jsxs("article",{children:[e.jsx("h3",{children:"Supplier Claim"}),e.jsxs("label",{children:["Supplier Claim No.",e.jsx("input",{defaultValue:N.supplierClaimNumber||"",onBlur:M=>void K("supplierClaimNumber",M.target.value)})]}),e.jsxs("label",{children:["Sent Date",e.jsx("input",{type:"date",defaultValue:N.sentDate||"",onBlur:M=>void K("sentDate",M.target.value)})]}),e.jsxs("label",{children:["Supplier Received Date",e.jsx("input",{type:"date",defaultValue:N.supplierReceivedDate||"",onBlur:M=>void K("supplierReceivedDate",M.target.value)})]}),e.jsxs("label",{children:["Expected Return Date",e.jsx("input",{type:"date",defaultValue:N.expectedReturnDate||"",onBlur:M=>void K("expectedReturnDate",M.target.value)})]}),e.jsxs("label",{children:["Return Date",e.jsx("input",{type:"date",defaultValue:N.returnDate||"",onBlur:M=>void K("returnDate",M.target.value)})]})]}),e.jsxs("article",{children:[e.jsx("h3",{children:"Resolution"}),e.jsxs("label",{children:["Resolution Note",e.jsx("textarea",{rows:4,defaultValue:N.resolution||"",onBlur:M=>void K("resolution",M.target.value)})]}),e.jsxs("label",{children:["Replacement Serial",e.jsx("input",{defaultValue:N.replacementSerial||"",onBlur:M=>void K("replacementSerial",M.target.value)})]})]})]}),e.jsxs("div",{className:"rma-status-action",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Current Status"}),e.jsx("strong",{children:pu[N.status]})]}),s&&F_[N.status].length>0&&e.jsxs("select",{value:"",onChange:M=>{const Z=M.target.value;Z&&(H(N,Z),w({...N,status:Z}))},children:[e.jsx("option",{value:"",children:"Move to..."}),F_[N.status].map(M=>e.jsx("option",{value:M,children:pu[M]},M))]})]})]})})]})}const fh={present:"Present",late:"Late",absent:"Absent",leave:"Leave",half_day:"Half Day",missing_punch:"Missing Punch",weekly_off:"Weekly Off",holiday:"Holiday",official_day_off:"Official Day Off"},kr=()=>new Date().toISOString().slice(0,10),gh=(t,n)=>{const[a,s,i]=t.split("-").map(Number),[c,l,m]=n.split("-").map(Number),d=new Date(Date.UTC(a,s-1,i)),u=new Date(Date.UTC(c,l-1,m)),f=[];for(;d<=u;)f.push(d.toISOString().slice(0,10)),d.setUTCDate(d.getUTCDate()+1);return f},Rf=(t,n)=>{const a=String(t.employeeId||"").trim(),s=String(n.employeeId||"").trim();if(a&&s){const i=a.localeCompare(s,void 0,{numeric:!0,sensitivity:"base"});if(i!==0)return i}else{if(a)return-1;if(s)return 1}return String(t.name||"").localeCompare(String(n.name||""),void 0,{numeric:!0,sensitivity:"base"})};function bi(t,n){if(!t||!n)return;const[a,s]=t.split(":").map(Number),[i,c]=n.split(":").map(Number);let l=a*60+s,m=i*60+c;return m<l&&(m+=1440),m-l}function yh(t,n,a,s){const c=a.filter(u=>u.employeeId!==t||!u.active?!1:s?!(u.effectiveFrom&&s<u.effectiveFrom||u.effectiveUntil&&s>u.effectiveUntil):!0).sort((u,f)=>{const g=String(f.effectiveFrom||"").localeCompare(String(u.effectiveFrom||""));return g!==0?g:Number(f.updatedAt||0)-Number(u.updatedAt||0)})[0],l=(c==null?void 0:c.lunchMode)||((c==null?void 0:c.useShiftLunch)===!1?"fixed":"shift_default");if(c&&l==="none")return{enabled:!1,mode:"none",start:"",end:"",standardMinutes:0,autoDeduct:!1};if(c&&l==="flexible")return{enabled:!0,mode:"flexible",start:"",end:"",standardMinutes:Math.max(0,Number(c.standardLunchMinutes||0)),autoDeduct:!1};if(c&&l==="fixed"){const u=Math.max(0,Number(c.standardLunchMinutes||0));return{enabled:!0,mode:"fixed",start:c.lunchStart||"",end:c.lunchEnd||"",standardMinutes:u,autoDeduct:u>0}
4002}const m=(n==null?void 0:n.lunchMode)||"fixed",d=Math.max(0,Number((n==null?void 0:n.standardLunchMinutes)||0));return{enabled:(n==null?void 0:n.lunchEnabled)!==!1&&m!=="none",mode:m,start:m==="fixed"&&(n==null?void 0:n.lunchStart)||"",end:m==="fixed"&&(n==null?void 0:n.lunchEnd)||"",standardMinutes:d,autoDeduct:m==="fixed"&&!!(n!=null&&n.autoDeductStandardLunch)&&d>0}}function ep(t,n){if(!t||!(n!=null&&n.startTime))return 0;const[a,s]=t.split(":").map(f=>Number(f)),[i,c]=n.startTime.split(":").map(f=>Number(f));if([a,s,i,c].some(f=>!Number.isFinite(f)))return 0;const l=a*60+s,m=i*60+c,d=Math.max(0,Number(n.graceMinutes||0)),u=m+d;return l>u?l-u:0}function yU(t,n,a){if(["leave","weekly_off","holiday","official_day_off"].includes(t.status))return t.status;if(t.status==="absent"&&!t.checkIn&&!t.checkOut)return"absent";if(t.checkIn&&!t.checkOut||!t.checkIn&&t.checkOut)return"missing_punch";if(!t.checkIn&&!t.checkOut)return t.status;const s=a??bi(t.checkIn,t.checkOut);if(n&&s!==void 0){const c=Math.max(0,Number(n.minimumHalfDayMinutes||0)),l=Math.max(c,Number(n.minimumFullDayMinutes||0));if(s<c)return"absent";if(s<l)return"half_day"}return ep(t.checkIn,n)>0?"late":"present"}function U_(t){return String(t||"").trim().replace(/^0+/,"")||"0"}function sl(t){const n=new Date(t);return`${String(n.getHours()).padStart(2,"0")}:${String(n.getMinutes()).padStart(2,"0")}`}function vh(t){const n=new Date(t);return[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-")}function fu(t,n){const a=U_(t.employeeDeviceId);return n.find(s=>[s.deviceEmployeeId,s.biometricId,s.attendanceDeviceId,s.employeeId,s.id].some(i=>i!==void 0&&U_(i)===a))}function rl({profile:t,branches:n,selectedBranchId:a,initialTab:s="dashboard",hidePrimaryTabs:i=!1}){var Vs,Hn,Fa,zs,Bs;const[c,l]=x.useState([]),[m,d]=x.useState([]),[u,f]=x.useState([]),[g,p]=x.useState([]),[y,b]=x.useState([]),[N,w]=x.useState([]),[C,R]=x.useState([]),[I,_]=x.useState({}),[J,T]=x.useState(""),[G,z]=x.useState(null),H=x.useRef(null),K=x.useRef(null),[L,D]=x.useState([]),[M,Z]=x.useState([]),[fe,q]=x.useState(!1),[ne,ae]=x.useState(!1),[Y,je]=x.useState(null),[V,$]=x.useState(null),[F,P]=x.useState([]),[ue,me]=x.useState({mode:"standard",officialDutyApprovalRequired:!0,lunchAllowanceMinutes:60,personalBreakAllowanceMinutes:20,unclassifiedOutsideTreatment:"review_required"}),[ge,de]=x.useState([]),[Pe,Re]=x.useState({employeeId:"",movementDate:kr(),outTime:"",inTime:"",movementType:"official_duty",purpose:"",reference:""}),[Ee,Be]=x.useState(!1),[We,it]=x.useState("09:00, 11:00, 11:30, 13:30, 14:15, 18:00"),[_e,ee]=x.useState(""),[qe,se]=x.useState([]),[pe,Se]=x.useState([]),[Me,ot]=x.useState("paid"),[wt,ct]=x.useState(!1),[Ce,De]=x.useState([]),[Te,ce]=x.use
4002State(!1),[Ye,Je]=x.useState({employeeId:"",fromDate:kr(),toDate:kr(),reason:""}),[le,nt]=x.useState("pending"),[xt,te]=x.useState(null),[Ge,pt]=x.useState(""),[$e,st]=x.useState(!1),[Nt,be]=x.useState("overview"),[jt,bt]=x.useState(!1),[tn,B]=x.useState(s);x.useEffect(()=>{B(s)},[s]);const[xe,tt]=x.useState(kr()),[ht,dt]=x.useState(kr().slice(0,7)),[we,rt]=x.useState("monthly_summary"),[St,Qt]=x.useState("all"),[gn,An]=x.useState(""),[Sn,Xt]=x.useState("all"),[Wt,Gt]=x.useState(!1),[$t,Vt]=x.useState(null),[sn,on]=x.useState(!1),[ke,Ct]=x.useState({employeeId:"",branchId:a==="all"?((Vs=n[0])==null?void 0:Vs.id)||t.branchId||"":a,attendanceDate:kr(),checkIn:"",checkOut:"",lunchOut:"",lunchIn:"",status:"present",remarks:"",adjustmentReason:""}),[Et,Rt]=x.useState({name:"General Shift",branchId:"all",startTime:"09:00",endTime:"18:00",graceMinutes:10,halfDayAfter:"12:00",minimumFullDayMinutes:480,minimumHalfDayMinutes:240,lunchEnabled:!0,lunchMode:"fixed",lunchStart:"13:00",lunchEnd:"14:00",standardLunchMinutes:60,lunchGraceMinutes:15,autoDetectLunchPunch:!0,autoDeductStandardLunch:!0,allowEmployeeLunchOverride:!0}),[xn,dn]=x.useState({name:"",date:kr(),branchId:"all",type:"full_day"}),[Ln,wa]=x.useState({name:"Weekly Off",weekdays:[5],branchId:"all",effectiveFrom:`${new Date().getFullYear()}-01-01`,effectiveUntil:`${new Date().getFullYear()}-12-31`}),Ca={name:"",brand:"zkteco",model:"",serialNumber:"",ipAddress:"",port:4370,communicationPassword:"",deviceType:"biometric",streamUrl:"",cameraRole:"general",recognitionThreshold:.72,duplicateCooldownSeconds:60,branchId:a==="all"?((Hn=n[0])==null?void 0:Hn.id)||t.branchId||"":a,syncMode:"5_min",autoSync:!0,active:!0},[In,Sa]=x.useState(Ca),[aa,$a]=x.useState({employeeId:"",useShiftLunch:!0,lunchMode:"shift_default",lunchStart:"13:00",lunchEnd:"14:00",standardLunchMinutes:60,effectiveFrom:kr(),effectiveUntil:""}),[jn,vs]=x.useState({employeeId:"",branchId:a==="all"?((Fa=n[0])==null?void 0:Fa.id)||t.branchId||"":a,leaveType:"casual",fromDate:kr(),toDate:kr(),durationType:"full_day",halfDayPeriod:"first_half",paid:!0,reason:""}),[ka,Ja]=x.useState({leaveType:"casual",annualQuota:10,paid:!0,strictQuota:!0}),_n=sa(t,"attendance.manage"),ha=sa(t,"attendance.read"),ta=x.useMemo(()=>t.employeeId?c.find(S=>S.id===t.employeeId):void 0,[c,t.employeeId]),W=!_n&&!!t.employeeId,ft=sa(t,"attendance.device.manage"),Zt=x.useRef(null),vt=S=>{const ye=[];let Fe="",lt=!1;for(let Ot=0;Ot<S.length;Ot+=1){const Ft=S[Ot];Ft==='"'?lt&&S[Ot+1]==='"'?(Fe+='"',Ot+=1):lt=!lt:Ft===","&&!lt?(ye.push(Fe.trim()),Fe=""):Fe+=Ft}return ye.push(Fe.trim()),ye},Ae=S=>{const ye=S.trim().match(/^(\d{1,2})[-\/]([0-1]?\d)[-\/](\d{4})$/);return ye?`${ye[3]}-${ye[2].padStart(2,"0")}-${ye[1].padStart(2,"0")}`:""},oe=S=>{const ye=S.trim().match(/^([0-2]?\d):([0-5]\d)(?::[0-5]\d)?$/);if(!ye)return"";const Fe=Number(ye[1]);return Fe>23||Fe===0&&ye[2]==="00"?"":`${String(Fe).padStart(2,"0")}:${ye[2]}`},Ve=async S=>{var Ot,Ft;if(!_n)return;const ye=a==="all"?t.branchId||((Ot=n[0])==null?void 0:Ot.id)||"":a;if(!ye){window.alert("Import à¦à¦°à¦¾à¦° à¦à¦à§ à¦à¦à¦à¦¿ Branch select à¦à¦°à§à¦¨à¥¤");return}const Fe=n.find(rn=>rn.id===ye);if(window.confirm(`${(Fe==null?void 0:Fe.name)||"Selected branch"}-ঠhistorical CSV import à¦à¦°à¦¬à§à¦¨? 4003 4004Existing attendance overwrite হবৠনা। CSV-à¦à¦° Employee ID দিà§à§ VERIXO employee match à¦à¦°à¦¾ হবà§à¥¤`)){on(!0);try{const Rn=(await S.text()).replace(/^\uFEFF/,"").split(/\r?\n/).filter(tr=>tr.trim());if(Rn.length<2){window.alert("CSV file-ঠimport à¦à¦°à¦¾à¦° মতৠdata পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}const ea=vt(Rn[0]).map(tr=>tr.trim().toLowerCase()),Wn=tr=>ea.indexOf(tr.toLowerCase()),Bn=Wn("User"),Fn=Wn("Access Date"),Na=Wn("First In Time"),ya=Wn("Last Out Time");if([Bn,Fn,Na,ya].some(tr=>tr<0)){window.alert("Unsupported CSV. Required columns: User, Access Date, First In Time, Last Out Time.");return}let Ba=0,Ya=0,Os=0,ys=0;const _r=new Set;for(const tr of Rn.slice(1)){const wr=vt(tr),Wr=(wr[Bn]||"").match(/\(([^()]+)\)\s*$/),nr=((Ft=Wr==null?void 0:Wr[1])==null?void 0:Ft.trim())||"",Fs=Ae(wr[Fn]||""),Hs=oe(wr[Na]||""),sr=oe(wr[ya]||"");if(!nr||!Fs||!Hs){ys+=1;continue}const Ka=c.find(go=>String(go.employeeId||"").trim()===nr||String(go.deviceEmployeeId||"").trim()===nr||String(go.biometricId||"").trim()===nr);if(!Ka){Os+=1,_r.add(nr);continue}if(m.find(go=>go.employeeId===Ka.id&&go.attendanceDate===Fs)){Ya+=1;continue}
4004const Es=no(Ka.branchId||ye),rr=bi(Hs,sr),ao=ep(Hs,Es),xc=sr?ao>0?"late":"present":"missing_punch",Do=Date.now();await Pn(re(ie,`attendanceDaily/${t.companyId}/${Fs}/${Ka.id}`),{companyId:t.companyId,branchId:Ka.branchId||ye,employeeId:Ka.id,employeeCode:Ka.employeeId||nr,employeeName:Ka.name,attendanceDate:Fs,checkIn:Hs,checkOut:sr,lateMinutes:ao,grossWorkMinutes:rr||0,workMinutes:rr||0,lunchOut:"",lunchIn:"",lunchMinutes:0,lunchPunchMissing:!1,status:xc,source:"manual",remarks:"Historical attendance imported from legacy CSV; lunch punches unavailable in source.",adjustmentReason:"Historical CSV migration",createdByUid:t.uid,createdByName:t.name,createdAt:Do,updatedAt:Do,engineVersion:3}),Ba+=1}await ia({companyId:t.companyId,branchId:ye,actorUid:t.uid,actorName:t.name,action:"attendance.historical_import",entityType:"attendance",entityId:`historical_csv_${Date.now()}`,summary:`Historical attendance CSV imported: ${Ba} added, ${Ya} existing skipped`,metadata:{fileName:S.name,imported:Ba,existingSkipped:Ya,unmatched:Os,invalid:ys,unmatchedEmployeeCodes:Array.from(_r)}}),window.alert(`Historical import complete. 4005 4006Imported: ${Ba} 4007Existing skipped: ${Ya} 4008Employee not matched: ${Os} 4009Invalid rows: ${ys}`+(_r.size?` 4010 4011Unmatched Employee ID: ${Array.from(_r).join(", ")}`:""))}catch(rn){console.error(rn),window.alert("Historical attendance import failed.")}finally{on(!1),Zt.current&&(Zt.current.value="")}}};x.useEffect(()=>W&&t.employeeId?qt(re(ie,`employees/${t.companyId}/${t.employeeId}`),S=>{if(!S.exists()){l([]);return}const ye=S.val();l(ye.active===!1?[]:[{id:t.employeeId,...ye}])},S=>{console.error("Employee self-service profile load failed:",S),l([])}):qt(re(ie,`employees/${t.companyId}`),S=>{if(!S.exists()){l([]);return}const ye=S.val();l(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})).filter(Fe=>Fe.active!==!1).sort(Rf))},S=>{console.error("Attendance employee directory load failed:",S),l([])}),[t.companyId,t.employeeId,W]),x.useEffect(()=>{if(!ha&&!_n){d([]);return}return qt(re(ie,`attendanceDaily/${t.companyId}`),S=>{if(!S.exists()){d([]);return}const ye=S.val(),Fe=[];Object.entries(ye).forEach(([lt,Ot])=>{Object.entries(Ot||{}).forEach(([Ft,rn])=>{Fe.push({id:`${lt}_${Ft}`,...rn})})}),d(Fe)},S=>{console.error("Attendance daily source load failed:",S),d([])})},[t.companyId,ha,_n]),x.useEffect(()=>qt(re(ie,`attendanceShifts/${t.companyId}`),S=>{if(!S.exists()){f([]);return}const ye=S.val();f(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})).sort((Fe,lt)=>Number(lt.updatedAt||lt.createdAt||0)-Number(Fe.updatedAt||Fe.createdAt||0)))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`employeeShiftAssignments/${t.companyId}`),S=>{if(!S.exists()){p([]);return}const ye=S.val(),Fe=[];Object.entries(ye).forEach(([lt,Ot])=>{Object.entries(Ot||{}).forEach(([Ft,rn])=>{Fe.push({id:Ft,employeeId:lt,...rn})})}),p(Fe)}),[t.companyId]),x.useEffect(()=>qt(re(ie,`attendanceHolidays/${t.companyId}`),S=>{if(!S.exists()){b([]);return}const ye=S.val();b(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`attendanceWeeklyOffRules/${t.companyId}`),S=>{if(!S.exists()){w([]);return}const ye=S.val();w(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt,weekdays:Array.isArray(lt.weekdays)?lt.weekdays:[]})))}),[t.companyId]),x.useEffect(()=>{if(!ft||!["dashboard","devices"].includes(tn)){R([]);return}return qt(re(ie,`attendanceDevices/${t.companyId}`),S=>{if(!S.exists()){R([]);return}const ye=S.val();R(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})).sort((Fe,lt)=>Fe.name.localeCompare(lt.name)))})},[t.companyId,tn,ft]),x.useEffect(()=>{if(!ft||tn!=="face_enrollment")return;const S=re(ie,`cctvFaceEnrollments/${t.companyId}`);return qt(S,ye=>{_(ye.val()||{})})},[t.companyId,tn,ft]),x.useEffect(()=>{if(!ft||tn!=="devices"){D([]);return}const S=Vl(re(ie,`attendanceDeviceLogs/${t.companyId}`),ql("createdAt"),jD(50));return qt(S,ye=>{if(!ye.exists()){D([]);return}const Fe=ye.val();D(Object.entries(Fe).map(([lt,Ot])=>({id:lt,...Ot})).sort((lt,Ot)=>Ot.createdAt-lt.createdAt))})},[t.companyId,tn,ft]),x.useEffect(()=>{if(!ft){Z([]);return}return qt(re(ie,`attendanceRawPunches/${t.companyId}`),S=>{if(!S.exists()){Z([]);return}const ye=S.val();Z(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})).sort((Fe,lt)=>Number(Fe.punchTimestamp||0)-Number(lt.punchTimestamp||0)))})},[t.companyId,ft]),x.useEffect(()=>qt(re(ie,`attendanceEmployeeLunchSettings/${t.companyId}`),S=>{if(!S.exists()){P([]);return}const ye=S.val();P(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`attendancePolicy/${t.companyId}`),S=>{S.exists()&&me(ye=>({...ye,...S.val()}))}),[t.companyId]),x.useEffect(()=>{if(!ha&&!_n){de([]);return}return qt(re(ie,`attendanceMovements/${t.companyId}`),S=>{if(!S.exists()){de([]);return}const ye=S.val(),Fe=[];Object.values(ye).forEach(lt=>{Object.entries(lt||{}
4011).forEach(([Ot,Ft])=>Fe.push({id:Ot,...Ft}))}),de(Fe.sort((lt,Ot)=>`${Ot.movementDate} ${Ot.outTime}`.localeCompare(`${lt.movementDate} ${lt.outTime}`)))},S=>{console.error("Attendance movement source load failed:",S),de([])})},[t.companyId,ha,_n]),x.useEffect(()=>qt(re(ie,`officialDayOffs/${t.companyId}`),S=>{if(!S.exists()){De([]);return}const ye=S.val();De(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})).sort((Fe,lt)=>lt.createdAt-Fe.createdAt))}),[t.companyId]),x.useEffect(()=>{const S=re(ie,`leaveRequests/${t.companyId}`),ye=W&&t.employeeId?Vl(S,ql("employeeId"),Dh(t.employeeId)):S;return qt(ye,Fe=>{if(!Fe.exists()){se([]);return}const lt=Fe.val();se(Object.entries(lt).map(([Ot,Ft])=>({id:Ot,...Ft})).sort((Ot,Ft)=>Ft.createdAt-Ot.createdAt))},Fe=>{console.error("Leave requests load failed:",Fe),se([])})},[t.companyId,t.employeeId,W]),x.useEffect(()=>{if(tn==="leave")return qt(re(ie,`leavePolicies/${t.companyId}`),S=>{if(!S.exists()){Se([]);return}const ye=S.val();Se(Object.entries(ye).map(([Fe,lt])=>({id:Fe,...lt})))})},[t.companyId,tn]),x.useEffect(()=>{if(tn==="leave")return qt(re(ie,`leaveSettings/${t.companyId}`),S=>{var Fe;const ye=S.exists()?String(((Fe=S.val())==null?void 0:Fe.halfDayPaymentRule)||"paid"):"paid";ot(ye==="unpaid"||ye==="leave_type"?ye:"paid")},S=>{console.error("Half Day leave setup load failed:",S),ot("paid")})},[t.companyId,tn]);const he=x.useMemo(()=>c.filter(S=>a==="all"||S.branchId===a).sort(Rf),[c,a]),Oe=x.useMemo(()=>{const S=gn.trim().toLowerCase();return m.filter(ye=>ye.attendanceDate===xe&&(a==="all"||ye.branchId===a)&&(Sn==="all"||ye.status===Sn)&&(!S||ye.employeeName.toLowerCase().includes(S)||String(ye.employeeCode||"").toLowerCase().includes(S))).sort((ye,Fe)=>ye.employeeName.localeCompare(Fe.employeeName))},[m,xe,a,Sn,gn]),ut=x.useMemo(()=>new Map(Oe.map(S=>[S.employeeId,S])),[Oe]),At=x.useMemo(()=>he.filter(S=>{const ye=gn.trim().toLowerCase();return ye?S.name.toLowerCase().includes(ye)||String(S.employeeId||"").toLowerCase().includes(ye):!0}).map(S=>{const ye=ut.get(S.id);return{employee:S,record:ye}}).filter(({record:S})=>Sn==="all"?!0:(S==null?void 0:S.status)===Sn),[he,ut,gn,Sn]),en=S=>{if(!S)return;const[ye,Fe]=S.split(":").map(Number);if(!(!Number.isFinite(ye)||!Number.isFinite(Fe)||ye<0||ye>23||Fe<0||Fe>59))return ye*60+Fe},It=(S,ye,Fe,lt)=>{const Ot=en(S);let Ft=en(ye);const rn=en(Fe);let Rn=en(lt);if(Ot===void 0||Ft===void 0||rn===void 0||Rn===void 0)return 0;Ft<Ot&&(Ft+=1440),Rn<rn&&(Rn+=1440);let ea=0;return[-1440,0,1440].forEach(Wn=>{const Bn=rn+Wn,Fn=Rn+Wn;ea=Math.max(ea,Math.max(0,Math.min(Ft,Fn)-Math.max(Ot,Bn)))}),ea},Pt=(S,ye,Fe,lt)=>{const Ot=bi(S,ye)||0,Ft=bi(Fe,lt)||0;if(!Ot||!Ft)return!1;const rn=It(S,ye,Fe,lt),Rn=Math.min(Ot,Ft);return rn>=Math.max(1,Math.floor(Rn*.7))},Jn=(S,ye,Fe,lt)=>ge.filter(Ot=>Ot.employeeId===S&&Ot.movementDate===ye&&Ot.source!=="auto_punch"&&Ot.status!=="rejected"&&!!Ot.inTime&&Ot.movementType!=="unclassified"&&Pt(Fe,lt,Ot.outTime,Ot.inTime||"")).sort((Ot,Ft)=>{const rn=Rn=>Rn.movementType==="approved_permission"?4:Rn.movementType==="official_duty"?3:Rn.movementType==="lunch_break"?2:Rn.movementType==="personal"?1:0;return rn(Ft)-rn(Ot)})[0],na=(S,ye,Fe)=>{if(ue.mode!=="access_control_multi_punch")return[];const lt=[...Fe].sort((Fn,Na)=>Fn.punchTimestamp-Na.punchTimestamp),Ot=[];for(let Fn=1;Fn+1<lt.length;Fn+=2){const Na=lt[Fn],ya=lt[Fn+1],Ba=sl(Na.punchTimestamp),Ya=sl(ya.punchTimestamp),Os=bi(Ba,Ya)||0;if(Os<=0)continue;const ys=Jn(S.id,ye,Ba,Ya);Ot.push({autoMovementId:`auto_${S.id}_${Na.punchTimestamp}`,outPunch:Na,inPunch:ya,outTime:Ba,inTime:Ya,minutes:Os,movementType:(ys==null?void 0:ys.movementType)||"unclassified",status:(ys==null?void 0:ys.status)||"pending",reason:ys?`Matched explicit ${ys.movementType.replaceAll("_"," ")} movement`:"Unclassified access-control interval",matchedExplicitMovementId:ys==null?void 0:ys.id})}if(!Ot.length)return Ot;const Ft=Gi(S,ye),rn=yh(S.id,Ft,F,ye);let Rn=ge.filter(Fn=>Fn.employeeId===S.id&&Fn.movementDate===ye&&Fn.source!=="auto_punch"&&Fn.status==="approved"&&Fn.movementType==="personal"&&!!Fn.inTime).reduce((Fn,Na)=>Fn+(bi(Na.outTime,Na.inTime)||0),0),ea=-1,Wn=0;rn.enabled&&rn.mode==="fixed"&&rn.start&&rn.end&&Ot.forEach((Fn,Na)=>{var Ba;if(Fn.matchedExplicitMovementId)return;const ya=It(Fn.outTime,Fn.inTime,rn.start,rn.end);(ya>Wn||ya===Wn&&ya>0&&Fn.minutes>(((Ba=Ot[ea])==null?void 0:Ba.minutes)||0))&&(ea=Na,Wn=ya)});const Bn=Math.max(0,Number(ue.personalBreakAllowanceMinutes||0));return Ot.forEach((Fn,Na)=>{if(Fn.matchedExplicitMovementId)return;if(Na===ea&&Wn>0){Fn.movementType="lunch_break",Fn.status="approved",Fn.reason="Auto-classified from employee/shift lunch policy";return}const ya=Math.max(0,Bn-Rn);if(Fn.minutes>0&&Fn.minutes<=ya){Fn.movementType="personal",Fn.status="approved",Fn.reason=`Auto Personal Break within daily ${Bn} minute allowance`,Rn+=Fn.minutes;return}if(ue.unclassifiedOutsideTreatment==="personal_break"){Fn.movementType="personal",Fn.status="approved",Fn.reason=ya>0?"Auto Personal Break by unclassified movement policy":"Personal Break by company unclassified movement policy",Rn+=Fn.minutes;return}Fn.movementType="unclassified",Fn.status="pending",Fn.reason=Bn>0?"Outside movement exceeds remaining personal allowance; review required":"Unexplained outside movement; review required"}),Ot},Mn=(S,ye,Fe)=>{const lt=Fe!=null&&Fe.checkIn&&(Fe!=null&&Fe.checkOut)&&bi(Fe.checkIn,Fe.checkOut)||0,Ot=ge.filter(Ba=>Ba.employeeId===S&&Ba.movementDate===ye&&!!Ba.inTime),Ft=Ot.filter(Ba=>Ba.source!=="auto_punch"?!0:!Ot.some(Ya=>Ya.source!=="auto_punch"&&Ya.status!=="rejected"&&Ya.movementType!=="unclassified"&&!!Ya.inTime&&Pt(Ba.outTime,Ba.inTime||"",Ya.outTime,Ya.inTime||"")));let rn=0,Rn=0,ea=0,Wn=0,Bn=0,Fn=0;Ft.forEach(Ba=>{const Ya=bi(Ba.outTime,Ba.inTime)||0;rn+=Ya,Ba.status==="approved"&&Ba.movementType==="official_duty"?Rn+=Ya:Ba.status==="approved"&&Ba.movementType==="approved_permission"?Bn+=Ya:Ba.status==="approved"&&Ba.movementType==="lunch_break"?ea+=Ya:Ba.status==="approved"&&Ba.movementType==="personal"?Wn+=Ya:Fn+=Ya});const Na=Math.max(0,lt-rn),ya=Math.max(0,Na+Rn+Bn);return{spanMinutes:lt,insideMinutes:Na,officialDutyMinutes:Rn,lunchMinutes:ea,personalMinutes:Wn,permissionMinutes:Bn,unclassifiedMinutes:Fn,effectiveWorkMinutes:ya,movementCount:Ft.length,reviewRequired:Ft.filter(Ba=>Ba.status==="pending"||Ba.movementType==="unclassified"&&Ba.status!=="rejected").length}},Ea=x.useMemo(()=>At.map(({employee:S,record:ye})=>({employee:S,record:ye,accessSummary:Mn(S.id,xe,ye)})),[At,xe,ge]),ga=x.useMemo(()=>he.map(S=>{const ye=m.filter(lt=>lt.employeeId===S.id&<.attendanceDate.startsWith(ht)),Fe=ye.reduce((lt,Ot)=>{const Ft=Mn(S.id,Ot.attendanceDate,Ot);return{spanMinutes:lt.spanMinutes+Ft.spanMinutes,insideMinutes:lt.insideMinutes+Ft.insideMinutes,officialDutyMinutes:lt.officialDutyMinutes+Ft.officialDutyMinutes,lunchMinutes:lt.lunchMinutes+Ft.lunchMinutes,personalMinutes:lt.personalMinutes+Ft.personalMinutes,permissionMinutes:lt.permissionMinutes+Ft.permissionMinutes,unclassifiedMinutes:lt.unclassifiedMinutes+Ft.unclassifiedMinutes,effectiveWorkMinutes:lt.effectiveWorkMinutes+Ft.effectiveWorkMinutes,reviewRequired:lt.reviewRequired+Ft.reviewRequired}},{spanMinutes:0,insideMinutes:0,officialDutyMinutes:0,lunchMinutes:0,personalMinutes:0,permissionMinutes:0,unclassifiedMinutes:0,effectiveWorkMinutes:0,reviewRequired:0});return{employee:S,recordDays:ye.length,...Fe}}),[he,m,ge,ht]),zn=S=>`${Math.floor(S/60)}h ${S%60}m`,Xn=x.useMemo(()=>{const S=Array.from(ut.values());return{total:he.length,present:S.filter(ye=>["present","late"].includes(ye.status)).length,late:S.filter(ye=>ye.status==="late").length,absent:S.filter(ye=>ye.status==="absent").length,leave:S.filter(ye=>ye.status==="leave").length,missing:S.filter(ye=>ye.status==="missing_punch").length}},[ut,he]),Vn=S=>({casual:"Casual Leave",sick:"Sick Leave",earned:"Earned Leave",unpaid:"Unpaid Leave",special:"Special Leave"})[S],ua=(S,ye,Fe)=>{if(Fe==="half_day")return .5;const lt=new Date(`${S}T00:00:00`),Ot=new Date(`${ye}T00:00:00`);return Math.max(0,Math.floor((Ot.getTime()-lt.getTime())/864e5)+1)},Ma=(S,ye)=>S!=="half_day"?ye:Me==="paid"?!0:Me==="unpaid"?!1:ye,Xe=S=>pe.find(ye=>ye.leaveType===S&&ye.active),Jt=(S,ye,Fe)=>qe.filter(lt=>lt.employeeId===S&<.leaveType===ye&<.approvalStatus==="approved"&&Number(lt.fromDate.slice(0,4))===Fe).reduce((lt,Ot)=>lt+ua(Ot.fromDate,Ot.toDate,Ot.durationType),0),Ht=(S,ye,Fe)=>{const lt=Xe(ye),Ot=ye==="unpaid"?Number.POSITIVE_INFINITY:Number((lt==null?void 0:lt.annualQuota)||0),Ft=Jt(S,ye,Fe);return{allowed:Ot,used:Ft,balance:Ot===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,Ot-Ft),strictQuota:ye==="unpaid"?!1:(lt==null?void 0:lt.strictQuota)??!0,paid:ye==="unpaid"?!1:(lt==null?void 0:lt.paid)??!0}},xa=x.useMemo(()=>({pending:qe.filter(S=>S.approvalStatus==="pending").length,approved:qe.filter(S=>S.approvalStatus==="approved").length,rejected:qe.filter(S=>S.approvalStatus==="rejected").length,withdrawn:qe.filter(S=>S.approvalStatus==="withdrawn").length,cancelled:qe.filter(S=>S.approvalStatus==="cancelled").length,all:qe.length}),[qe]),ra=x.useMemo(()=>W&&ta?qe.filter(S=>S.employeeId===ta.id):qe,[qe,W,ta]),Ha=x.useMemo(()=>ra.filter(S=>!W&&a!=="all"&&S.branchId!==a?!1:le==="all"?!0:S.approvalStatus===le),[ra,le,a,W]),is=x.useMemo(()=>{const S=new Date().getFullYear(),ye=ra.filter(Fe=>Fe.approvalStatus==="approved"&&Number(Fe.fromDate.slice(0,4))===S);return{pending:ra.filter(Fe=>Fe.approvalStatus==="pending").length,approved:ye.length,rejected:ra.filter(Fe=>Fe.approvalStatus==="rejected").length,employeesOnLeaveToday:ra.filter(Fe=>Fe.approvalStatus==="approved"&&Fe.fromDate<=kr()&&Fe.toDate>=kr()).length}},[ra]),hs=x.useMemo(()=>ra.filter(S=>W||S.approvalStatus==="approved").map(S=>({id:S.id,employeeName:S.employeeName,employeeCode:S.employeeCode||"",leaveType:S.leaveType,fromDate:S.fromDate,toDate:S.toDate,days:ua(S.fromDate,S.toDate,S.durationType),durationType:S.durationType,halfDayPeriod:S.halfDayPeriod,paid:Ma(S.durationType,S.paid!==!1),status:S.approvalStatus,approvedBy:S.approvedByName||"â",approvedAt:S.approvedAt||S.updatedAt})).sort((S,ye)=>ye.approvedAt-S.approvedAt),[ra,W,Me]),rs=x.useMemo(()=>
4011{if(!W||!ta)return[];const S=new Date().getFullYear();return["casual","sick","earned","special","unpaid"].map(Fe=>({leaveType:Fe,...Ht(ta.id,Fe,S)}))},[W,ta,ra,pe]),oa=x.useMemo(()=>jn.employeeId?Ht(jn.employeeId,jn.leaveType,Number(jn.fromDate.slice(0,4))):null,[jn.employeeId,jn.leaveType,jn.fromDate,qe,pe]),qa=x.useMemo(()=>{const[S,ye]=ht.split("-").map(Number),Fe=new Date(S,ye,0).getDate();return Array.from({length:Fe},(lt,Ot)=>{const Ft=Ot+1;return{day:Ft,date:`${ht}-${String(Ft).padStart(2,"0")}`}})},[ht]),bs=[{value:0,label:"Sunday"},{value:1,label:"Monday"},{value:2,label:"Tuesday"},{value:3,label:"Wednesday"},{value:4,label:"Thursday"},{value:5,label:"Friday"},{value:6,label:"Saturday"}],Wa=(S,ye)=>y.find(Fe=>Fe.active&&Fe.date===S&&(!Fe.branchId||Fe.branchId==="all"||Fe.branchId===ye)),$s=(S,ye)=>{const Fe=new Date(`${S}T00:00:00`).getDay();return N.find(lt=>lt.active&<.weekdays.includes(Fe)&<.effectiveFrom<=S&&(!lt.effectiveUntil||lt.effectiveUntil>=S)&&(lt.branchId==="all"||lt.branchId===ye))},jr=x.useMemo(()=>{const S=new Map;return Ce.filter(ye=>ye.status==="active").forEach(ye=>{gh(ye.fromDate,ye.toDate).forEach(Fe=>{S.set(`${ye.employeeId}_${Fe}`,ye)})}),S},[Ce]),Kr=x.useMemo(()=>{const S=new Map;return qe.filter(ye=>ye.approvalStatus==="approved").forEach(ye=>{gh(ye.fromDate,ye.toDate).forEach(Fe=>{S.set(`${ye.employeeId}_${Fe}`,ye)})}),S},[qe]),Xr=(S,ye)=>{const Fe=Gi(ye,S.attendanceDate),lt=yh(ye.id,Fe,F,S.attendanceDate);if(S.checkIn&&S.checkOut&&S.status==="missing_punch"&&(lt.mode==="none"||lt.mode==="flexible")){const Ot=bi(S.checkIn,S.checkOut)||0,Ft=ep(S.checkIn,Fe);return Fe&&Ot<Fe.minimumFullDayMinutes&&Ot>=Fe.minimumHalfDayMinutes?"half_day":Ft>0?"late":"present"}return S.status},Rr=x.useMemo(()=>he.map(S=>{const ye=qa.map(({date:lt})=>{const Ot=m.find(Fn=>Fn.employeeId===S.id&&Fn.attendanceDate===lt),Ft=jr.get(`${S.id}_${lt}`);if(Ft)return{date:lt,code:"DO",label:`Official Day Off: ${Ft.reason}`,paid:!0};const rn=Kr.get(`${S.id}_${lt}`);if(rn)return{date:lt,code:rn.durationType==="half_day"?"HD":"LV",label:rn.durationType==="half_day"?"Half Day Leave":`Leave (${rn.leaveType})`,paid:Ma(rn.durationType,rn.paid!==!1)};const Rn=Wa(lt,S.branchId);if(Rn)return{date:lt,code:Rn.type==="half_day"?"HD":"H",label:Rn.name,paid:!1};const ea=$s(lt,S.branchId);if(ea)return{date:lt,code:"WO",label:ea.name,paid:!1};if(!Ot)return{date:lt,code:"",label:"Not Marked",paid:!1};const Wn={present:"P",late:"L",absent:"A",leave:"LV",half_day:"HD",missing_punch:"MP",weekly_off:"WO",holiday:"H",official_day_off:"DO"},Bn=Xr(Ot,S);return{date:lt,code:Wn[Bn],label:fh[Bn],paid:!1}}),Fe={present:ye.filter(lt=>["P","L"].includes(lt.code)).length,late:ye.filter(lt=>lt.code==="L").length,absent:ye.filter(lt=>lt.code==="A").length,halfDay:ye.filter(lt=>lt.code==="HD").length,leave:ye.filter(lt=>lt.code==="LV").length,officialDayOff:ye.filter(lt=>lt.code==="DO").length,paidLeave:ye.filter(lt=>lt.code==="LV"&<.paid).length,unpaidLeave:ye.filter(lt=>lt.code==="LV"&&!lt.paid).length,missing:ye.filter(lt=>lt.code==="MP").length};return{employee:S,dayValues:ye,summary:Fe}}),[he,qa,m,Kr,jr,y,N,F,u,g]);x.useEffect(()=>{if(!_n||!M.length||!c.length)return;const S=window.setTimeout(()=>{bc()},800);return()=>window.clearTimeout(S)},[M,c,u,F,m,_n]);const er=x.useMemo(()=>{const S=J.trim().toLowerCase();return c.filter(ye=>ye.active!==!1).filter(ye=>a==="all"||ye.branchId===a).filter(ye=>!S||ye.name.toLowerCase().includes(S)||String(ye.employeeId||ye.id).toLowerCase().includes(S))},[c,J,a]),Ir=S=>{var ye;K.current=S,(ye=H.current)==null||ye.click()},Qo=async(S,ye)=>{z(S.id);try{if(!ye.type.startsWith("image/"))throw new Error("Please select an image file.");if(ye.size>8*1024*1024)throw new Error("Photo must be 8 MB or smaller.");const Fe=await new Promise((rn,Rn)=>{const ea=new FileReader;ea.onload=()=>rn(String(ea.result||"")),ea.onerror=()=>Rn(new Error("Could not read photo.")),ea.readAsDataURL(ye)}),lt=await fetch("http://127.0.0.1:8765/enroll",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({employeeId:S.id,employeeName:S.name,imageDataUrl:Fe})}),Ot=await lt.json().catch(()=>({}));if(!lt.ok||!Ot.ok)throw new Error(Ot.message||"Local CCTV connector rejected the photo.");const Ft=Date.now();await Pn(re(ie,`cctvFaceEnrollments/${t.companyId}/${S.id}`),{employeeId:S.id,employeeName:S.name,branchId:S.branchId||"",status:"enrolled",templateCount:Number(Ot.templateCount||1),updatedAt:Ft,updatedByUid:t.uid,updatedByName:t.name||t.email||"User"}),alert(`${S.name} face enrollment completed on this connector PC.`)}catch(Fe){const lt=Fe instanceof Error?Fe.message:"Face enrollment failed.";alert(lt.includes("Failed to fetch")?"CCTV Connector is not running on this PC. Run START-CCTV-CONNECTOR.bat first.":lt)}finally{z(null),K.current=null,H.current&&(H.current.value="")}},fo=async S=>{if(confirm(`Remove local face enrollment for ${S.name}?`)){z(S.id);try{const ye=await fetch("http://127.0.0.1:8765/remove",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({employeeId:S.id})}),Fe=await ye.json().catch(()=>({}));if(!ye.ok||!Fe.ok)throw new Error(Fe.message||"Local connector could not remove enrollment.");await Ao(re(ie,`cctvFaceEnrollments/${t.companyId}/${S.id}`))}catch(ye){const Fe=ye instanceof Error?ye.message:"Remove failed.";alert(Fe.includes("Failed to fetch")?"CCTV Connector is not running on this PC.":Fe)}finally{z(null)}}},Jo=x.useMemo(()=>({total:C.length,online:C.filter(S=>S.connectionStatus==="online"&&S.active).length,offline:C.filter(S=>S.connectionStatus==="offline"&&S.active).length,errors:C.filter(S=>S.lastSyncStatus==="error").length}),[C]),pr=x.useMemo(()=>{const S=kr(),ye=m.filter(Ft=>Ft.attendanceDate===S&&(a==="all"||Ft.branchId===a)),Fe=qe.filter(Ft=>Ft.approvalStatus==="approved"&&Ft.fromDate<=S&&Ft.toDate>=S&&(a==="all"||Ft.branchId===a)),lt=S.slice(0,7),Ot=m.filter(Ft=>Ft.attendanceDate.startsWith(lt)&&(a==="all"||Ft.branchId===a));return{total:he.length,present:ye.filter(Ft=>["present","late"].includes(Ft.status)).length,late:ye.filter(Ft=>
4011Ft.status==="late").length,absent:ye.filter(Ft=>Ft.status==="absent").length,leave:Fe.length,missing:ye.filter(Ft=>Ft.status==="missing_punch").length,monthLate:Ot.filter(Ft=>Ft.status==="late").length,pendingLeave:qe.filter(Ft=>Ft.approvalStatus==="pending"&&(a==="all"||Ft.branchId===a)).length,upcomingHoliday:y.filter(Ft=>Ft.active&&Ft.date>=S&&(Ft.branchId==="all"||a==="all"||Ft.branchId===a)).sort((Ft,rn)=>Ft.date.localeCompare(rn.date))[0]||null}},[m,qe,y,he,a]),Or=x.useMemo(()=>Rr.reduce((S,ye)=>({present:S.present+ye.summary.present,late:S.late+ye.summary.late,absent:S.absent+ye.summary.absent,halfDay:S.halfDay+ye.summary.halfDay,leave:S.leave+ye.summary.leave,officialDayOff:S.officialDayOff+ye.summary.officialDayOff,paidLeave:S.paidLeave+ye.summary.paidLeave,unpaidLeave:S.unpaidLeave+ye.summary.unpaidLeave,missing:S.missing+ye.summary.missing}),{present:0,late:0,absent:0,halfDay:0,leave:0,officialDayOff:0,paidLeave:0,unpaidLeave:0,missing:0}),[Rr]),Js=x.useMemo(()=>{const S=[...St==="all"?Rr:Rr.filter(({employee:Fe})=>Fe.id===St)].sort((Fe,lt)=>String(Fe.employee.employeeId||"").localeCompare(String(lt.employee.employeeId||""),void 0,{numeric:!0,sensitivity:"base"}));if(we==="monthly_summary")return S.map(({employee:Fe,summary:lt})=>({employeeId:Fe.employeeId||"",employee:Fe.name,present:lt.present,late:lt.late,absent:lt.absent,halfDay:lt.halfDay,leave:lt.leave,officialDayOff:lt.officialDayOff,paidLeave:lt.paidLeave,unpaidLeave:lt.unpaidLeave,missingPunch:lt.missing,lateDeductionDays:Math.floor(lt.late/3)}));if(we==="payroll")return S.map(({employee:Fe,summary:lt})=>({employeeId:Fe.employeeId||"",employee:Fe.name,presentDays:lt.present,officialDayOff:lt.officialDayOff,paidLeave:lt.paidLeave,unpaidLeave:lt.unpaidLeave,halfDays:lt.halfDay,absentDays:lt.absent,lateCount:lt.late,lateDeductionDays:Math.floor(lt.late/3),payableAttendanceDays:Math.max(0,lt.present+lt.paidLeave+lt.officialDayOff+lt.halfDay*.5-Math.floor(lt.late/3))}));if(we==="leave")return qe.filter(Fe=>Fe.fromDate.startsWith(ht)||Fe.toDate.startsWith(ht)).filter(Fe=>a==="all"||Fe.branchId===a).filter(Fe=>St==="all"||Fe.employeeId===St).map(Fe=>({employeeId:Fe.employeeCode||"",employee:Fe.employeeName,leaveType:Fe.leaveType,fromDate:Fe.fromDate,toDate:Fe.toDate,duration:Fe.durationType==="half_day"?"Half Day":"Full Day",paid:Fe.paid?"Paid":"Unpaid",status:Fe.approvalStatus,reason:Fe.reason}));const ye=m.filter(Fe=>Fe.attendanceDate.startsWith(ht)).filter(Fe=>a==="all"||Fe.branchId===a).filter(Fe=>St==="all"||Fe.employeeId===St);return we==="late"?ye.filter(Fe=>Fe.status==="late").map(Fe=>({date:Fe.attendanceDate,employeeId:Fe.employeeCode||"",employee:Fe.employeeName,checkIn:Fe.checkIn||"",lateMinutes:Fe.lateMinutes||0,remarks:Fe.remarks||""})):we==="missing_punch"?ye.filter(Fe=>Fe.status==="missing_punch"||Fe.lunchPunchMissing).map(Fe=>({date:Fe.attendanceDate,employeeId:Fe.employeeCode||"",employee:Fe.employeeName,checkIn:Fe.checkIn||"",checkOut:Fe.checkOut||"",lunchOut:Fe.lunchOut||"",lunchIn:Fe.lunchIn||"",issue:Fe.status==="missing_punch"?"Office Punch Missing":"Lunch Punch Missing"})):ye.map(Fe=>({date:Fe.attendanceDate,employeeId:Fe.employeeCode||"",employee:Fe.employeeName,checkIn:Fe.checkIn||"",lunchOut:Fe.lunchOut||"",lunchIn:Fe.lunchIn||"",checkOut:Fe.checkOut||"",lateMinutes:Fe.lateMinutes||0,workHours:Fe.workMinutes?`${Math.floor(Fe.workMinutes/60)}h ${Fe.workMinutes%60}m`:"",status:fh[Fe.status],source:Fe.source}))},[we,St,Rr,m,qe,ht,a]),Ko={monthly_summary:"Monthly Attendance Summary",daily:"Daily Attendance Report",late:"Late Attendance Report",missing_punch:"Missing Punch Report",leave:"Leave Report",payroll:"Payroll Attendance Summary"}[we],to=()=>{hc(`${we}-${ht}.csv`,Js)},$i=()=>{window.print()},Bc=()=>{var ya,Ba;if(!Js.length){window.alert("No report data found.");return}const S=((ya=n.find(Ya=>Ya.id===a))==null?void 0:ya.name)||(a==="all"?"All Branches":""),ye=St==="all"?"All Employees":((Ba=he.find(Ya=>Ya.id===St))==null?void 0:Ba.name)||"Selected Employee",Fe=Object.keys(Js[0]),lt=Ya=>Ya.replace(/([A-Z])/g," $1").replace(/^./,Os=>Os.toUpperCase()),Ot=Fe.map(lt),Ft=Js.map(Ya=>Fe.map(Os=>String(Ya[Os]??""))),rn=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),Rn=rn.internal.pageSize.getWidth(),ea=new Date().toLocaleDateString("en-GB"),Wn=()=>
4011{rn.setFillColor(10,76,115),rn.rect(0,0,Rn,24,"F"),rn.setTextColor(255,255,255),rn.setFont("helvetica","bold"),rn.setFontSize(14),rn.text("VERIXO ERP",12,10),rn.setFontSize(8.5),rn.setFont("helvetica","normal"),rn.text("ATTENDANCE REPORT",12,16),rn.setFont("helvetica","bold"),rn.setFontSize(13),rn.text(Ko,Rn-12,10,{align:"right"}),rn.setFont("helvetica","normal"),rn.setFontSize(8),rn.text(`${S} | ${ht} | ${ye}`,Rn-12,16,{align:"right"})};if(Wn(),we==="monthly_summary"){const Ya=Js.reduce((Ns,Wr)=>{const nr=Wr;return{present:Ns.present+Number(nr.present||0),late:Ns.late+Number(nr.late||0),absent:Ns.absent+Number(nr.absent||0),halfDay:Ns.halfDay+Number(nr.halfDay||0),leave:Ns.leave+Number(nr.leave||0),missing:Ns.missing+Number(nr.missingPunch||0)}},{present:0,late:0,absent:0,halfDay:0,leave:0,missing:0}),Os=[["Employees",Js.length],["Present",Ya.present],["Late",Ya.late],["Absent",Ya.absent],["Half Day",Ya.halfDay],["Leave",Ya.leave],["Missing Punch",Ya.missing]],ys=12,_r=29,tr=2,wr=(Rn-24-tr*(Os.length-1))/Os.length;Os.forEach(([Ns,Wr],nr)=>{const Fs=ys+nr*(wr+tr);rn.setFillColor(244,248,251),rn.setDrawColor(217,228,236),rn.roundedRect(Fs,_r,wr,13,2,2,"FD"),rn.setTextColor(95,116,132),rn.setFont("helvetica","normal"),rn.setFontSize(6.8),rn.text(Ns,Fs+3,_r+4.4),rn.setTextColor(15,42,64),rn.setFont("helvetica","bold"),rn.setFontSize(10),rn.text(String(Wr),Fs+3,_r+10)})}const Bn=we==="monthly_summary"?47:30;oi(rn,{startY:Bn,head:[Ot],body:Ft,theme:"grid",styles:{font:"helvetica",fontSize:Ot.length>9?6.4:7.2,cellPadding:1.7,textColor:[32,55,72],lineColor:[213,224,232],lineWidth:.15,overflow:"linebreak",valign:"middle"},headStyles:{fillColor:[235,242,247],textColor:[24,67,96],fontStyle:"bold",fontSize:Ot.length>9?6.2:7},alternateRowStyles:{fillColor:[249,251,253]},margin:{top:Bn,right:10,bottom:14,left:10},didDrawPage:Ya=>{Ya.pageNumber>1&&Wn();const Os=rn.internal.pageSize.getHeight();rn.setDrawColor(220,228,234),rn.line(10,Os-10,Rn-10,Os-10),rn.setTextColor(105,122,135),rn.setFont("helvetica","normal"),rn.setFontSize(7),rn.text(`Generated: ${ea} | Records: ${Js.length}
4011`,10,Os-5),rn.text(`Page ${Ya.pageNumber}`,Rn/2,Os-5,{align:"center"}),rn.text("Prepared through VERIXO ERP",Rn-10,Os-5,{align:"right"})}});const Fn=S.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,""),Na=we.replace(/_/g,"-");rn.save(`VERIXO_Attendance_${Na}_${ht}_${Fn||"All-Branches"}.pdf`)};function no(S){const ye=u.filter(Fe=>Fe.active).sort((Fe,lt)=>Number(lt.updatedAt||lt.createdAt||0)-Number(Fe.updatedAt||Fe.createdAt||0));return ye.find(Fe=>Fe.branchId===S)||ye.find(Fe=>Fe.branchId==="all"||!Fe.branchId)}const Fc=(S,ye)=>{var Fe;Vt(ye||null),Ct({employeeId:S.id,branchId:S.branchId||(a==="all"?((Fe=n[0])==null?void 0:Fe.id)||"":a),attendanceDate:xe,checkIn:(ye==null?void 0:ye.checkIn)||"",checkOut:(ye==null?void 0:ye.checkOut)||"",lunchOut:(ye==null?void 0:ye.lunchOut)||"",lunchIn:(ye==null?void 0:ye.lunchIn)||"",status:(ye==null?void 0:ye.status)||"present",remarks:(ye==null?void 0:ye.remarks)||"",adjustmentReason:(ye==null?void 0:ye.adjustmentReason)||""}),Gt(!0)},Xo=async()=>{if(!_n)return;const S=c.find(Fn=>Fn.id===ke.employeeId);if(!S){window.alert("Employee select à¦à¦°à§à¦¨à¥¤");return}const ye=Gi(S,ke.attendanceDate),Fe=bi(ke.checkIn,ke.checkOut),lt=yh(S.id,ye,F,ke.attendanceDate),Ot=bi(ke.lunchOut,ke.lunchIn),Ft=lt.enabled&&!!(ke.lunchOut||ke.lunchIn)&&!(ke.lunchOut&&ke.lunchIn),rn=lt.enabled?lt.autoDeduct?lt.standardMinutes:Ot!==void 0?Ot:0:0,Rn=Fe!==void 0?Math.max(0,Fe-rn):void 0,ea=yU(ke,ye,Rn),Wn=ep(ke.checkIn,ye),Bn=Date.now();on(!0);try{const Fn={companyId:t.companyId,branchId:ke.branchId,employeeId:S.id,employeeCode:S.employeeId||"",employeeName:S.name,attendanceDate:ke.attendanceDate,checkIn:ke.checkIn||"",checkOut:ke.checkOut||"",lateMinutes:Wn,grossWorkMinutes:Fe||0,workMinutes:Rn||0,lunchOut:ke.lunchOut||"",lunchIn:ke.lunchIn||"",lunchMinutes:rn,lunchPunchMissing:Ft,status:ea,source:$t?$t.source==="device"?"device_adjusted":$t.source:"manual",remarks:ke.remarks.trim(),adjustmentReason:ke.adjustmentReason.trim(),createdByUid:($t==null?void 0:$t.createdByUid)||t.uid,createdByName:($t==null?void 0:$t.createdByName)||t.name,createdAt:($t==null?void 0:$t.createdAt)||Bn,updatedAt:Bn,engineVersion:2};await Pn(re(ie,`attendanceDaily/${t.companyId}/${ke.attendanceDate}/${S.id}`),Fn);const Na=Ta(re(ie,`attendanceAdjustments/${t.companyId}`));await Pn(Na,{attendanceDate:ke.attendanceDate,employeeId:S.id,employeeName:S.name,branchId:ke.branchId,previousStatus:($t==null?void 0:$t.status)||null,nextStatus:ea,reason:ke.adjustmentReason.trim()||($t?"Attendance updated":"Manual entry"),actorUid:t.uid,actorName:t.name,createdAt:Bn}),await ia({companyId:t.companyId,branchId:ke.branchId,actorUid:t.uid,actorName:t.name,action:"attendance.updated",entityType:"attendance",entityId:`${ke.attendanceDate}_${S.id}`,summary:`${S.name} attendance saved as ${fh[ea]}`,metadata:{attendanceDate:ke.attendanceDate,checkIn:ke.checkIn,checkOut:ke.checkOut,lateMinutes:Wn,grossWorkMinutes:Fe??null,workMinutes:Rn??null,lunchOut:ke.lunchOut,lunchIn:ke.lunchIn,lunchMinutes:rn,lunchPunchMissing:Ft,status:ea}}),Gt(!1)}catch(Fn){console.error("Attendance save failed:",Fn),window.alert("Attendance save à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤")}finally{on(!1)}},Yl=async S=>{const ye=c.filter(lt=>{const Ot=lt;return Ot.shiftId===S.id||Ot.attendanceShiftId===S.id});if(ye.length>0){window.alert(`${ye.length} à¦à¦¨ employee à¦à¦ shift-ঠassigned à¦à¦à§à¥¤ à¦à¦à§ তাদà§à¦° à¦
নà§à¦¯ shift-ঠassign à¦à¦°à§à¦¨, তারপর shift delete à¦à¦°à§à¦¨à¥¤`);return}window.confirm(`"${S.name}" shift permanently delete à¦à¦°à¦¬à§à¦¨? à¦à¦ action undo à¦à¦°à¦¾ যাবৠনা।`)&&(await Pn(re(ie,`attendanceShifts/${t.companyId}/${S.id}`),null),await ia({companyId:t.companyId,branchId:S.branchId||t.branchId,actorUid:t.uid,actorName:t.name,action:"attendance.updated",entityType:"attendance",entityId:S.id,summary:`Shift deleted: ${S.name}`,metadata:{shiftName:S.name,startTime:S.startTime,endTime:S.endTime}}))},Uc=async()=>{if(!Et.name.trim()){window.alert("Shift name লিà¦à§à¦¨à¥¤");return}const S=Ta(re(ie,`attendanceShifts/${t.companyId}`));await Pn(S,{...Et,active:!0,createdAt:Date.now(),updatedAt:Date.now(),createdByUid:t.uid,createdByName:t.name}),Rt({name:"General Shift",branchId:"all",startTime:"09:00",endTime:"18:00",graceMinutes:10,halfDayAfter:"12:00",minimumFullDayMinutes:480,minimumHalfDayMinutes:240,lunchEnabled:!0,lunchMode:"fixed",lunchStart:"13:00",lunchEnd:"14:00",standardLunchMinutes:60,lunchGraceMinutes:15,autoDetectLunchPunch:!0,autoDeductStandardLunch:!0,allowEmployeeLunchOverride:!0})};function Gi(S,ye=kr()){const Fe=g.filter(Ot=>Ot.employeeId===S.id&&Ot.effectiveFrom<=ye).sort((Ot,Ft)=>Ft.effectiveFrom.localeCompare(Ot.effectiveFrom))[0],lt=(Fe==null?void 0:Fe.shiftId)||S.shiftId;if(lt){const Ot=u.find(Ft=>Ft.id===lt&&Ft.active!==!1);if(Ot)return Ot}return no(S.branchId||t.branchId||"")}const zc=async(S,ye,Fe,lt)=>{await yn(re(ie,`attendanceRawPunches/${t.companyId}/${S.id}`),{processingStatus:ye,processedAt:Date.now(),matchedEmployeeId:Fe,processingMessage:lt})},Zo=async(S,ye,Fe)=>{if(ue.mode!=="access_control_multi_punch")return;const lt=na(S,ye,Fe);for(const Ot of lt){if(Ot.matchedExplicitMovementId)continue;const Ft=ge.find(ea=>ea.id===Ot.autoMovementId&&ea.movementDate===ye);if(Ft&&!(Ft.source==="auto_punch"&&Ft.status==="pending"&&Ft.movementType==="unclassified"))continue;const rn=Date.now(),Rn={id:Ot.autoMovementId,companyId:t.companyId,branchId:S.branchId||t.branchId||"",employeeId:S.id,employeeName:S.name,employeeCode:S.employeeId||"",movementDate:ye,outTime:Ot.outTime,inTime:Ot.inTime,movementType:Ot.movementType,purpose:"",reference:Ot.reason,source:"auto_punch",rawOutPunchId:Ot.outPunch.id,rawInPunchId:Ot.inPunch.id,rawOutTimestamp:Ot.outPunch.punchTimestamp,rawInTimestamp:Ot.inPunch.punchTimestamp,status:Ot.status,requestedByUid:"attendance-engine",requestedByName:"VERIXO Attendance Engine",createdAt:(Ft==null?void 0:Ft.createdAt)||rn,updatedAt:rn};await Pn(re(ie,`attendanceMovements/${t.companyId}/${ye}/${Ot.autoMovementId}`),Rn)}},qc=(S,ye,Fe)=>{const lt=en(S),Ot=en(ye.start),Ft=en(ye.end);if(lt===void 0||Ot===void 0||Ft===void 0)return!1;const rn=Math.max(0,Number((Fe==null?void 0:Fe.lunchGraceMinutes)||0));return lt>=Ot-rn&<<=Ft+rn},ec=async(S,ye,Fe,lt)=>{const Ot=[...Fe].sort((Fs,Hs)=>Fs.punchTimestamp-Hs.punchTimestamp);if(!Ot.length)return;await Zo(S,ye,Ot);const Ft=ue.mode!=="access_control_multi_punch",rn=Ft?Ot.filter((Fs,Hs,sr)=>Hs===0||Fs.punchTimestamp!==sr[Hs-1].punchTimestamp):Ot,Rn=Ot.length-rn.length,ea=Gi(S,ye),Wn=yh(S.id,ea,F,ye),Bn=sl(rn[0].punchTimestamp);let Fn=rn.length>=2?sl(rn[rn.length-1].punchTimestamp):"",Na="",ya="",Ba=!1;if(Ft&&Wn.enabled&&Wn.mode==="fixed"&&(ea==null?void 0:ea.autoDetectLunchPunch)!==!1&&Wn.start&&Wn.end){const Fs=rn.findIndex((Hs,sr)=>sr>0&&qc(sl(Hs.punchTimestamp),Wn,ea));if(Fs>0){Na=sl(rn[Fs].punchTimestamp);const Hs=rn[Fs+1];Hs&&(ya=sl(Hs.punchTimestamp)),Fn=rn[Fs+2]?sl(rn[rn.length-1].punchTimestamp):"",Ba=!ya}}else Ft&&Wn.enabled&&Wn.mode==="fixed"&&(rn.length>=4?(Na=sl(rn[1].punchTimestamp),ya=sl(rn[rn.length-2].punchTimestamp)):rn.length===3&&(Na=sl(rn[1].punchTimestamp),Ba=!0));const Ya=bi(Bn,Fn),Os=bi(Na,ya),ys=Wn.enabled?Wn.autoDeduct?Wn.standardMinutes:Os!==void 0?Os:0:0,_r=Ya!==void 0?Math.max(0,Ya-ys):0,tr=ep(Bn,ea);let wr;!Fn||Ba?wr="missing_punch":ea&&_r<Math.max(0,Number(ea.minimumHalfDayMinutes||0))?wr="absent":ea&&_r<Math.max(0,Number(ea.minimumFullDayMinutes||0))?wr="half_day":wr=tr>0?"late":"present";const Ns=m.find(Fs=>Fs.employeeId===S.id&&Fs.attendanceDate===ye),Wr=Date.now(),nr={companyId:t.companyId,branchId:S.branchId||t.branchId||"",employeeId:S.id,employeeCode:S.employeeId||"",employeeName:S.name,attendanceDate:ye,checkIn:Bn,checkOut:Fn,lateMinutes:tr,grossWorkMinutes:Ya||0,workMinutes:_r,lunchOut:Na,lunchIn:ya,lunchMinutes:ys,lunchPunchMissing:Ba,status:wr,source:(Ns==null?void 0:Ns.source)==="manual"?"device_adjusted":"device",remarks:rn.length===1?"Only one biometric punch found.":rn.length===3&&Wn.enabled&&Wn.mode==="fixed"&&!Fn?Rn>0?`Lunch sequence incomplete. ${Rn} exact duplicate punch ignored in Standard Attendance calculation; raw facts preserved.`:"Lunch sequence incomplete; final Check Out is still missing.":Rn>0?`${Rn} exact duplicate punch ignored in Standard Attendance calculation; raw facts preserved.`:"",adjustmentReason:(Ns==null?void 0:Ns.adjustmentReason)||"",createdByUid:(Ns==null?void 0:Ns.createdByUid)||"connector",createdByName:(Ns==null?void 0:Ns.createdByName)||"VERIXO Attendance Engine",createdAt:(Ns==null?void 0:Ns.createdAt)||Wr,updatedAt:Wr,engineVersion:5};await Pn(re(ie,`attendanceDaily/${t.companyId}/${ye}/${S.id}`),nr),(lt==null?void 0:lt.markRawPunchesProcessed)!==!1&&await Promise.all(rn.map(Fs=>zc(Fs,"processed",S.id,`Attendance generated for ${ye}.`)))},bc=async()=>
4011{if(fe||!c.length)return;const S=M.filter(Fe=>!Fe.processingStatus||Fe.processingStatus==="pending"?!0:Fe.processingStatus==="unmatched"&&!!fu(Fe,c)),ye=M.some(Fe=>{const lt=fu(Fe,c);if(!lt)return!1;const Ot=vh(Fe.punchTimestamp),Ft=m.find(rn=>rn.employeeId===lt.id&&rn.attendanceDate===Ot);return(Ft==null?void 0:Ft.source)==="device"&&Number(Ft.engineVersion||0)<5});if(!(!S.length&&!ye)){q(!0);try{const Fe=new Map,lt=ye?M:S;for(const Ot of lt){const Ft=fu(Ot,c);if(!Ft){(!Ot.processingStatus||Ot.processingStatus==="pending"||Ot.processingStatus==="unmatched")&&await zc(Ot,"unmatched","",`No employee matched device ID ${Ot.employeeDeviceId}.`);continue}const rn=vh(Ot.punchTimestamp),Rn=`${Ft.id}_${rn}`,ea=Fe.get(Rn);if(ea)ea.punches.push(Ot);else{const Wn=M.filter(Bn=>{var Fn;return((Fn=fu(Bn,c))==null?void 0:Fn.id)===Ft.id&&vh(Bn.punchTimestamp)===rn});Fe.set(Rn,{employee:Ft,date:rn,punches:Wn})}}for(const Ot of Fe.values())await ec(Ot.employee,Ot.date,Ot.punches)}catch(Fe){console.error("Attendance processing failed:",Fe)}finally{q(!1)}}},vl=S=>{var ye;S?(je(S),Sa({name:S.name,brand:S.brand,model:S.model||"",serialNumber:S.serialNumber||"",ipAddress:S.ipAddress,port:S.port||4370,communicationPassword:S.communicationPassword||"",deviceType:S.deviceType||"biometric",streamUrl:S.streamUrl||"",cameraRole:S.cameraRole||"general",recognitionThreshold:S.recognitionThreshold??.72,duplicateCooldownSeconds:S.duplicateCooldownSeconds??60,branchId:S.branchId,syncMode:S.syncMode,autoSync:S.autoSync,active:S.active})):(je(null),Sa({...Ca,branchId:a==="all"?((ye=n[0])==null?void 0:ye.id)||t.branchId||"":a})),ae(!0)},Oi=async(S,ye,Fe,lt)=>{const Ot=Ta(re(ie,`attendanceDeviceLogs/${t.companyId}`));await Pn(Ot,{deviceId:S.id,deviceName:S.name,branchId:S.branchId,action:ye,status:Fe,message:lt,createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name})},tc=async()=>{if(!In.name.trim()||!In.ipAddress.trim()||!In.branchId){window.alert("Device Name, IP Address à¦à¦¬à¦ Branch পà§à¦°à¦£ à¦à¦°à§à¦¨à¥¤");return}const S=Date.now(),ye=(Y==null?void 0:Y.id)||Ta(re(ie,`attendanceDevices/${t.companyId}`)).key;if(!ye){window.alert("Device ID তà§à¦°à¦¿ à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤");return}const Fe={companyId:t.companyId,branchId:In.branchId,name:In.name.trim(),brand:In.brand,model:In.model.trim(),serialNumber:In.serialNumber.trim(),ipAddress:In.ipAddress.trim(),port:Number(In.port||(In.deviceType==="cctv"?554:4370)),communicationPassword:In.deviceType==="cctv"?"":In.communicationPassword.trim(),deviceType:In.deviceType,streamUrl:In.streamUrl.trim(),cameraRole:In.cameraRole,recognitionThreshold:Number(In.recognitionThreshold||.72),duplicateCooldownSeconds:Number(In.duplicateCooldownSeconds||60),syncMode:In.syncMode,autoSync:In.autoSync,active:In.active,connectionStatus:(Y==null?void 0:Y.connectionStatus)||"unknown",lastSyncAt:(Y==null?void 0:Y.lastSyncAt)||0,lastSyncStatus:(Y==null?void 0:Y.lastSyncStatus)||"",lastError:(Y==null?void 0:Y.lastError)||"",connectorId:(Y==null?void 0:Y.connectorId)||"",createdAt:(Y==null?void 0:Y.createdAt)||S,updatedAt:S,createdByUid:(Y==null?void 0:Y.createdByUid)||t.uid,createdByName:(Y==null?void 0:Y.createdByName)||t.name};await Pn(re(ie,`attendanceDevices/${t.companyId}/${ye}`),Fe),await Oi({id:ye,name:Fe.name,branchId:Fe.branchId},Y?"updated":"created","success",Y?"Device configuration updated.":"Device added and waiting for connector."),ae(!1),je(null)},Vc=async S=>{$(S.id);try{const ye=Ta(re(ie,`attendanceConnectorCommands/${t.companyId}`));await Pn(ye,{deviceId:S.id,branchId:S.branchId,command:"test_connection",status:"pending",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name}),await yn(re(ie,`attendanceDevices/${t.companyId}/${S.id}`),{connectionStatus:"unknown",updatedAt:Date.now(),lastError:"Waiting for VERIXO Attendance Connector response."}),await Oi(S,"test","pending","Connection test queued for VERIXO Attendance Connector."),window.alert("Connection test queue-তৠযà§à¦ হà§à§à¦à§à¥¤ Connector à¦à¦¾à¦²à§ থাà¦à¦²à§ device check à¦à¦°à§ status update à¦à¦°à¦¬à§à¥¤")}finally{$(null)}},_o=async S=>{$(S.id);try{const ye=Ta(re(ie,`attendanceConnectorCommands/${t.companyId}`));await Pn(ye,{deviceId:S.id,branchId:S.branchId,command:"sync_now",status:"pending",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name}),await Oi(S,"sync","pending","Manual sync requested and queued for connector."),window.alert("Sync request queue-তৠযà§à¦ হà§à§à¦à§à¥¤ Connector online হলৠattendance logs sync à¦à¦°à¦¬à§à¥¤")}finally{$(null)}},ko=async S=>{if(window.confirm(`"${S.name}" device-à¦à¦° সমà§à¦ªà§à¦°à§à¦£ attendance history scan à¦à¦°à¦¬à§à¦¨? 4012 4013à¦à¦à¦¿ normal Sync-à¦à¦° à¦à§à§à§ বà§à¦¶à¦¿ সমৠনিতৠপারà§à¥¤ Existing/duplicate punch à¦à¦¬à¦¾à¦° attendance হিসà§à¦¬à§ তà§à¦°à¦¿ হবৠনা; Connector শà§à¦§à§ missing/new record upload à¦à¦°à¦¬à§à¥¤`)){$(S.id);try{const Fe=Ta(re(ie,`attendanceConnectorCommands/${t.companyId}`));await Pn(Fe,{deviceId:S.id,branchId:S.branchId,command:"full_verification",status:"pending",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name}),await Oi(S,"sync","pending","Full verification requested. Connector will scan the complete device punch history and upload only missing records."),window.alert("Full Verification queue-তৠযà§à¦ হà§à§à¦à§à¥¤ Connector পà§à¦°à§ device history scan à¦à¦°à¦¬à§à¥¤ শà§à¦· হলৠRecent Device Activity-তৠDevice logs / scanned / new candidates / skipped known / uploaded দà§à¦à¦¾ যাবà§à¥¤")}finally{$(null)}}},U=async S=>{window.confirm(`"${S.name}" device delete à¦à¦°à¦¬à§à¦¨? Existing attendance records delete হবৠনা।`)&&(await Pn(re(ie,`attendanceDevices/${t.companyId}/${S.id}`),null),await Oi(S,"deleted","success","Device configuration deleted."))},Ue=S=>{wa(ye=>({...ye,weekdays:ye.weekdays.includes(S)?ye.weekdays.filter(Fe=>Fe!==S):[...ye.weekdays,S].sort()}))},yt=async()=>
4013{if(!Ln.weekdays.length){window.alert("Weekly Off-à¦à¦° à¦à¦¨à§à¦¯ ঠনà§à¦¤à¦¤ à¦à¦à¦à¦¿ দিন নিরà§à¦¬à¦¾à¦à¦¨ à¦à¦°à§à¦¨à¥¤");return}if(Ln.effectiveUntil&&Ln.effectiveUntil<Ln.effectiveFrom){window.alert("Effective Until, Effective From-à¦à¦° à¦à¦à§ হতৠপারবৠনা।");return}const S=Ta(re(ie,`attendanceWeeklyOffRules/${t.companyId}`));await Pn(S,{name:Ln.name.trim()||"Weekly Off",weekdays:Ln.weekdays,branchId:Ln.branchId,effectiveFrom:Ln.effectiveFrom,effectiveUntil:Ln.effectiveUntil||"",active:!0,createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name})},kt=async()=>{if(!xn.name.trim()){window.alert("Holiday name লিà¦à§à¦¨à¥¤");return}const S=Ta(re(ie,`attendanceHolidays/${t.companyId}`));await Pn(S,{...xn,active:!0,createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name}),dn({name:"",date:kr(),branchId:"all",type:"full_day"})},an=S=>{const ye=S.lunchMode||(S.useShiftLunch?"shift_default":"fixed");$a({employeeId:S.employeeId,useShiftLunch:ye==="shift_default",lunchMode:ye,lunchStart:S.lunchStart||"13:00",lunchEnd:S.lunchEnd||"14:00",standardLunchMinutes:Math.max(0,Number(S.standardLunchMinutes||0)),effectiveFrom:S.effectiveFrom||kr(),effectiveUntil:S.effectiveUntil||""}),window.scrollTo({top:0,behavior:"smooth"})},Cn=async S=>{if(!(!_n||!window.confirm(`${S.employeeName}-à¦à¦° employee-specific Lunch Policy delete à¦à¦°à¦¬à§à¦¨? 4014 4015Delete à¦à¦°à¦²à§ employee à¦à¦¬à¦¾à¦° Shift / Company Policy follow à¦à¦°à¦¬à§à¥¤ Historical attendance automatic change হবৠনা; পà§à¦°à§à§à¦à¦¨ হলৠRecalculate Month দিন.`))){on(!0);try{await Ao(re(ie,`attendanceEmployeeLunchSettings/${t.companyId}/${S.id}`)),aa.employeeId===S.employeeId&&$a({employeeId:"",useShiftLunch:!0,lunchMode:"shift_default",lunchStart:"13:00",lunchEnd:"14:00",standardLunchMinutes:60,effectiveFrom:kr(),effectiveUntil:""}),window.alert(`${S.employeeName}-à¦à¦° Lunch Policy deleted.`)}finally{on(!1)}}},Qn=async()=>{if(!aa.employeeId){window.alert("Employee select à¦à¦°à§à¦¨à¥¤");return}const S=c.find(lt=>lt.id===aa.employeeId);if(!S){window.alert("Employee record পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}const ye=F.find(lt=>lt.employeeId===S.id),Fe=(ye==null?void 0:ye.id)||Ta(re(ie,`attendanceEmployeeLunchSettings/${t.companyId}`)).key;if(!Fe){window.alert("Lunch setting তà§à¦°à¦¿ à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤");return}await Pn(re(ie,`attendanceEmployeeLunchSettings/${t.companyId}/${Fe}`),{employeeId:S.id,employeeName:S.name,branchId:S.branchId||"",useShiftLunch:aa.lunchMode==="shift_default",lunchMode:aa.lunchMode,lunchStart:aa.lunchMode==="fixed"?aa.lunchStart:"",lunchEnd:aa.lunchMode==="fixed"?aa.lunchEnd:"",standardLunchMinutes:aa.lunchMode==="none"?0:aa.standardLunchMinutes,effectiveFrom:aa.effectiveFrom||"",effectiveUntil:aa.effectiveUntil||"",active:!0,updatedAt:Date.now(),updatedByUid:t.uid,updatedByName:t.name}),$a({employeeId:"",useShiftLunch:!0,lunchMode:"shift_default",lunchStart:"13:00",lunchEnd:"14:00",standardLunchMinutes:60,effectiveFrom:kr(),effectiveUntil:""})},E=async()=>{if(!(!_n||wt)){ct(!0);try{await Pn(re(ie,`leaveSettings/${t.companyId}`),{halfDayPaymentRule:Me,updatedAt:Date.now(),updatedByUid:t.uid,updatedByName:t.name}),window.alert("Half Day leave payment setup saved.")}finally{ct(!1)}}},Q=async()=>{const S=pe.find(lt=>lt.leaveType===ka.leaveType),ye=S?re(ie,`leavePolicies/${t.companyId}/${S.id}`):Ta(re(ie,`leavePolicies/${t.companyId}`)),Fe=Date.now();await Pn(ye,{leaveType:ka.leaveType,annualQuota:ka.leaveType==="unpaid"?0:Math.max(0,Number(ka.annualQuota||0)),paid:ka.leaveType==="unpaid"?!1:ka.paid,strictQuota:ka.leaveType==="unpaid"?!1:ka.strictQuota,active:!0,createdAt:(S==null?void 0:S.createdAt)||Fe,updatedAt:Fe,updatedByUid:t.uid,updatedByName:t.name})},Ie=async()=>{if(!_n)return;if(!Ye.employeeId||!Ye.fromDate||!Ye.toDate||!Ye.reason.trim()){window.alert("Employee, date range à¦à¦¬à¦ official reason পà§à¦°à¦£ à¦à¦°à§à¦¨à¥¤");return}if(Ye.toDate<Ye.fromDate){window.alert("To Date, From Date-à¦à¦° à¦à¦à§ হতৠপারবৠনা।");return}const S=c.find(Wn=>Wn.id===Ye.employeeId);if(!S){window.alert("Employee পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}if(Ce.some(Wn=>Wn.status==="active"&&Wn.employeeId===S.id&&Wn.fromDate<=Ye.toDate&&Wn.toDate>=Ye.fromDate)){window.alert("à¦à¦ employee-à¦à¦° selected date range-ঠOfficial Day Off already assigned à¦à¦à§à¥¤");return}if(qe.some(Wn=>Wn.approvalStatus==="approved"&&Wn.employeeId===S.id&&Wn.fromDate<=Ye.toDate&&Wn.toDate>=Ye.fromDate)){window.alert("Selected date range-ঠapproved leave à¦à¦à§à¥¤ à¦à¦à§ leave conflict resolve à¦à¦°à§à¦¨à¥¤");return}const lt={},Ot=[];for(const Wn of gh(Ye.fromDate,Ye.toDate)){const Bn=m.find(Fn=>Fn.employeeId===S.id&&Fn.attendanceDate===Wn);if(Bn)if(Bn.checkIn||Bn.checkOut||!["absent","missing_punch"].includes(Bn.status))Ot.push(Wn);
4015else{const{id:Fn,...Na}=Bn;lt[Wn]=Na}}if(Ot.length){window.alert(`Official Day Off assign à¦à¦°à¦¾ হà§à¦¨à¦¿à¥¤ Existing attendance/punch à¦à¦à§: ${Ot.join(", ")}. à¦à¦à§ attendance conflict resolve à¦à¦°à§à¦¨à¥¤`);return}const Ft=Date.now(),rn=Ta(re(ie,`officialDayOffs/${t.companyId}`)),Rn=rn.key||String(Ft),ea=S.branchId||t.branchId||"";ce(!0);try{await Pn(rn,{companyId:t.companyId,employeeId:S.id,employeeName:S.name,employeeCode:S.employeeId||"",branchId:ea,fromDate:Ye.fromDate,toDate:Ye.toDate,reason:Ye.reason.trim(),paid:!0,status:"active",assignedByUid:t.uid,assignedByName:t.name,createdAt:Ft,updatedAt:Ft,replacedAttendanceRecords:lt});for(const Wn of gh(Ye.fromDate,Ye.toDate))await Pn(re(ie,`attendanceDaily/${t.companyId}/${Wn}/${S.id}`),{companyId:t.companyId,branchId:ea,employeeId:S.id,employeeCode:S.employeeId||"",employeeName:S.name,attendanceDate:Wn,checkIn:"",checkOut:"",lateMinutes:0,grossWorkMinutes:0,workMinutes:0,lunchOut:"",lunchIn:"",lunchMinutes:0,lunchPunchMissing:!1,status:"official_day_off",source:"manual",remarks:`Official Day Off: ${Ye.reason.trim()}`,adjustmentReason:`Official Day Off ${Rn}`,createdByUid:t.uid,createdByName:t.name,createdAt:Ft,updatedAt:Ft});await ia({companyId:t.companyId,branchId:ea,actorUid:t.uid,actorName:t.name,action:"attendance.updated",entityType:"attendance",entityId:Rn,summary:`${S.name} assigned Official Day Off`,metadata:{fromDate:Ye.fromDate,toDate:Ye.toDate,reason:Ye.reason.trim(),paid:!0}}),Je({employeeId:"",fromDate:kr(),toDate:kr(),reason:""})}finally{ce(!1)}},Le=async S=>{var Fe;if(!_n||S.status!=="active"||!window.confirm(`Cancel Official Day Off for ${S.employeeName}?`))return;const ye=Date.now();ce(!0);try{await yn(re(ie,`officialDayOffs/${t.companyId}/${S.id}`),{status:"cancelled",cancelledAt:ye,cancelledByUid:t.uid,cancelledByName:t.name,updatedAt:ye});for(const lt of gh(S.fromDate,S.toDate))if(m.find(Ft=>Ft.employeeId===S.employeeId&&Ft.attendanceDate===lt&&Ft.status==="official_day_off"&&Ft.adjustmentReason===`Official Day Off ${S.id}`)){const Ft=(Fe=S.replacedAttendanceRecords)==null?void 0:Fe[lt];await Pn(re(ie,`attendanceDaily/${t.companyId}/${lt}/${S.employeeId}`),Ft||null)}await ia({companyId:t.companyId,branchId:S.branchId,actorUid:t.uid,actorName:t.name,action:"attendance.updated",entityType:"attendance",entityId:S.id,summary:`${S.employeeName} Official Day Off cancelled`,metadata:{fromDate:S.fromDate,toDate:S.toDate}})}finally{ce(!1)}},He=()=>{if(W){if(!ta){window.alert("à¦à¦ªà¦¨à¦¾à¦° Login User-à¦à¦° সাথৠEmployee profile link পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ HR/Admin-à¦à§ User & Role Permissions থà§à¦à§ Employee link à¦à¦°à¦¤à§ বলà§à¦¨à¥¤");return}vs(S=>({...S,employeeId:ta.id,branchId:ta.branchId||t.branchId||S.branchId}))}bt(!0)},gt=async()=>{var rn;const S=W?(ta==null?void 0:ta.id)||"":jn.employeeId;if(!S||!jn.fromDate||!jn.toDate||!jn.reason.trim()){window.alert("Employee, date range à¦à¦¬à¦ reason পà§à¦°à¦£ à¦à¦°à§à¦¨à¥¤");return}const ye=c.find(Rn=>Rn.id===S);if(!ye){window.alert("Employee পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}if(jn.toDate<jn.fromDate){window.alert("To Date, From Date-à¦à¦° à¦à¦à§ হতৠপারবৠনা।");return}if(jn.durationType==="half_day"&&jn.fromDate!==jn.toDate){window.alert("Half Day leave à¦à¦à¦à¦¿ single date-à¦à¦° à¦à¦¨à§à¦¯ হতৠহবà§à¥¤ From Date à¦à¦¬à¦ To Date à¦à¦à¦ রাà¦à§à¦¨à¥¤");return}const Fe=ua(jn.fromDate,jn.toDate,jn.durationType),lt=Ht(ye.id,jn.leaveType,Number(jn.fromDate.slice(0,4)));if(lt.strictQuota&&Fe>lt.balance){window.alert(`${Vn(jn.leaveType)} quota exhausted. Allowed: ${lt.allowed}, Used: ${lt.used}, Balance: ${lt.balance}. à¦à¦ leave apply à¦à¦°à¦¾ যাবৠনা।`);return}const Ot=Date.now(),Ft=Ta(re(ie,`leaveRequests/${t.companyId}`));await Pn(Ft,{companyId:t.companyId,employeeId:ye.id,employeeName:ye.name,employeeCode:ye.employeeId||"",branchId:ye.branchId||jn.branchId,leaveType:jn.leaveType,fromDate:jn.fromDate,toDate:jn.toDate,durationType:jn.durationType,halfDayPeriod:jn.durationType==="half_day"?jn.halfDayPeriod:null,paid:Ma(jn.durationType,Ht(ye.id,jn.leaveType,Number(jn.fromDate.slice(0,4))).paid),reason:jn.reason.trim(),approvalStatus:"pending",approvalComment:"",decisionHistory:{[String(Ot)]:{action:"submitted",comment:jn.reason.trim(),actorUid:t.uid,actorName:t.name,createdAt:Ot}},createdByUid:t.uid,createdByName:t.name,createdAt:Ot,updatedAt:Ot}),vs({employeeId:W&&ta?ta.id:"",branchId:W&&ta?ta.branchId||t.branchId||"":a==="all"?((rn=n[0])==null?void 0:rn.id)||t.branchId||"":a,leaveType:"casual",fromDate:kr(),toDate:kr(),durationType:"full_day",halfDayPeriod:"first_half",paid:!0,reason:""}),bt(!1),be(W?"overview":"approval"),nt(W?"all":"pending")},Dt=async(S,ye,Fe="")=>{if(["approved","rejected","cancelled"].includes(ye)&&!_n||ye==="withdrawn"&&W&&S.employeeId!==(ta==null?void 0:ta.id))return;const lt=Date.now();st(!0);try{const Ot=String(lt);if(await yn(re(ie,`leaveRequests/${t.companyId}/${S.id}`),{approvalStatus:ye,approvalComment:Fe.trim(),approvedByUid:t.uid,approvedByName:t.name,approvedAt:lt,updatedAt:lt,[`decisionHistory/${Ot}`]:{action:ye,comment:Fe.trim(),actorUid:t.uid,actorName:t.name,createdAt:lt}}),ye==="approved")for(const Ft of gh(S.fromDate,S.toDate))await Pn(re(ie,`attendanceDaily/${t.companyId}/${Ft}/${S.employeeId}`),{companyId:t.companyId,branchId:S.branchId,employeeId:S.employeeId,employeeCode:S.employeeCode||"",employeeName:S.employeeName,attendanceDate:Ft,checkIn:"",checkOut:"",lateMinutes:0,grossWorkMinutes:0,workMinutes:0,lunchOut:"",lunchIn:"",lunchMinutes:0,lunchPunchMissing:!1,status:"leave",source:"manual",remarks:`${S.leaveType} leave: ${S.reason}`,adjustmentReason:"Approved leave auto-marked",createdByUid:S.createdByUid,createdByName:S.createdByName,createdAt:S.createdAt,updatedAt:lt});if(["rejected","withdrawn","cancelled"].includes(ye))for(const Ft of gh(S.fromDate,S.toDate))m.find(Rn=>Rn.employeeId===S.employeeId&&Rn.attendanceDate===Ft&&["leave","half_day"].includes(Rn.status)&&Rn.adjustmentReason==="Approved leave auto-marked")&&await Pn(re(ie,`attendanceDaily/${t.companyId}/${Ft}/${S.employeeId}`),null);await ia({companyId:t.companyId,branchId:S.branchId,actorUid:t.uid,actorName:t.name,action:"attendance.updated",entityType:"attendance",entityId:S.id,summary:`${S.employeeName} leave ${ye}`,metadata:{leaveType:S.leaveType,fromDate:S.fromDate,toDate:S.toDate,paid:S.paid,durationType:S.durationType,approvalComment:Fe.trim()}}),te(null),pt("")}finally{st(!1)}},Yt=()=>{hc(`monthly-attendance-${ht}.csv`,Rr.map(({employee:S,summary:ye})=>({"Employee ID":S.employeeId||"",Employee:S.name,Present:ye.present,Late:ye.late,Absent:ye.absent,"Half Day":ye.halfDay,Leave:ye.leave,"Official Day Off":ye.officialDayOff,"Paid Leave":ye.paidLeave,"Unpaid Leave":ye.unpaidLeave,"Missing Punch":ye.missing,"Late Deduction Days":Math.floor(ye.late/3)})))},vn=()=>{hc(`attendance-${xe}.csv`,At.map(({employee:S,record:ye})=>{var Fe;return{"Employee ID":S.employeeId||"",Employee:S.name,Branch:((Fe=n.find(lt=>lt.id===((ye==null?void 0:ye.branchId)||S.branchId)))==null?void 0:Fe.name)||"",Date:xe,"Check In":(ye==null?void 0:ye.checkIn)||"","Check Out":(ye==null?void 0:ye.checkOut)||"","Late Minutes":(ye==null?void 0:ye.lateMinutes)||0,"Gross Work Minutes":(ye==null?void 0:ye.grossWorkMinutes)||0,"Lunch Out":(ye==null?void 0:ye.lunchOut)||"","Lunch In":(ye==null?void 0:ye.lunchIn)||"","Lunch Minutes":(ye==null?void 0:ye.lunchMinutes)||0,"Lunch Punch Missing":ye!=null&&ye.lunchPunchMissing?"Yes":"No","Net Work Minutes":(ye==null?void 0:ye.workMinutes)||0,Status:ye?fh[ye.status]:"Not Marked",Source:(ye==null?void 0:ye.source)||""}}))},zt=x.useMemo(()=>{const S=new Set(C.filter(ye=>a==="all"?!0:ye.branchId===a).map(ye=>ye.id));return L.filter(ye=>a==="all"?!0:ye.branchId?ye.branchId===a:S.has(ye.deviceId))},[C,L,a]),Bt=S=>{const ye=S.trim().match(/^(\d{1,2}):([0-5]\d)$/);if(!ye)return"";const Fe=Number(ye[1]);return Fe<0||Fe>23?"":`${String(Fe).padStart(2,"0")}:${ye[2]}`}
4015,En=We.split(",").map(Bt).filter(Boolean),wn=_e?he.find(S=>S.id===_e):void 0,ma=wn?Gi(wn,kr()):(()=>{const S=a!=="all"?a:t.branchId||"";return no(S)||u.find(ye=>ye.active&&ye.lunchEnabled!==!1&&!!ye.lunchStart&&!!ye.lunchEnd)||u.find(ye=>ye.active)})(),ca=yh((wn==null?void 0:wn.id)||"__simulator__",ma,wn?F:[],kr()),Pa=(()=>{const S=[];for(let Ft=1;Ft+1<En.length;Ft+=2){const rn=En[Ft],Rn=En[Ft+1],ea=bi(rn,Rn);ea===void 0||ea<=0||S.push({outTime:rn,inTime:Rn,minutes:ea,type:"unclassified",status:"pending",reason:"Waiting for policy classification"})}let ye=-1,Fe=0;ca.enabled&&ca.mode==="fixed"&&ca.start&&ca.end&&S.forEach((Ft,rn)=>{var ea;const Rn=It(Ft.outTime,Ft.inTime,ca.start,ca.end);(Rn>Fe||Rn===Fe&&Rn>0&&Ft.minutes>(((ea=S[ye])==null?void 0:ea.minutes)||0))&&(ye=rn,Fe=Rn)});const lt=Math.max(0,Number(ue.personalBreakAllowanceMinutes||0));let Ot=0;return S.forEach((Ft,rn)=>{if(rn===ye&&Fe>0){Ft.type="lunch_break",Ft.status="approved",Ft.reason="Auto Lunch â current shift lunch window";return}const Rn=Math.max(0,lt-Ot);if(Ft.minutes>0&&Ft.minutes<=Rn){Ft.type="personal",Ft.status="approved",Ft.reason=`Auto Personal â within ${lt} min daily allowance`,Ot+=Ft.minutes;return}if(ue.unclassifiedOutsideTreatment==="personal_break"){Ft.type="personal",Ft.status="approved",Ft.reason="Auto Personal â company unclassified policy",Ot+=Ft.minutes;return}Ft.type="unclassified",Ft.status="pending",Ft.reason="Review Required â unexplained/allowance exceeded"}),S})(),kn=(()=>{if(En.length<2)return{spanMinutes:0,insideMinutes:0,officialDutyMinutes:0,lunchMinutes:0,personalMinutes:0,permissionMinutes:0,unclassifiedMinutes:0,reviewRequired:0,effectiveWorkMinutes:0};const S=bi(En[0],En[En.length-1])||0;let ye=0,Fe=0,lt=0,Ot=0,Ft=0,rn=0;Pa.forEach(Bn=>{Bn.type==="official_duty"?ye+=Bn.minutes:Bn.type==="lunch_break"?Fe+=Bn.minutes:Bn.type==="personal"?lt+=Bn.minutes:Bn.type==="approved_permission"?Ot+=Bn.minutes:Ft+=Bn.minutes,Bn.status==="pending"&&(rn+=1)});const Rn=Pa.reduce((Bn,Fn)=>Bn+Fn.minutes,0),ea=Math.max(0,S-Rn),Wn=Math.max(0,ea+ye+Ot);return{spanMinutes:S,insideMinutes:ea,officialDutyMinutes:ye,lunchMinutes:Fe,personalMinutes:lt,permissionMinutes:Ot,unclassifiedMinutes:Ft,reviewRequired:rn,effectiveWorkMinutes:Wn}})(),Kn=S=>`${Math.floor(S/60)}h ${S%60}m`,Zn=S=>(S==null?void 0:S.source)==="manual"||(S==null?void 0:S.source)==="device_adjusted",da=async(S,ye)=>{const Fe=Ta(re(ie,`attendanceAdjustments/${t.companyId}`));await Pn(Fe,{attendanceDate:S.attendanceDate,employeeId:S.employeeId,employeeName:S.employeeName,branchId:S.branchId||"",previousStatus:S.status,nextStatus:S.status,reason:ye,action:"historical_recalculation_backup",actorUid:t.uid,actorName:t.name,createdAt:Date.now(),beforeRecord:S})},Ga=async(S,ye)=>{const Fe=Gi(ye,S.attendanceDate),lt=yh(ye.id,Fe,F,S.attendanceDate);if(Zn(S))return"skipped_manual";if(ue.mode==="access_control_multi_punch")return"skipped_access_without_raw";const Ot=S.checkIn||"",Ft=S.checkOut||"",rn=bi(Ot,Ft)||0;let Rn=S.lunchOut||"",ea=S.lunchIn||"",Wn=Number(S.lunchMinutes||0),Bn=!!S.lunchPunchMissing;lt.mode==="none"||lt.mode==="flexible"?(Rn="",ea="",Wn=0,Bn=!1):lt.mode==="fixed"&&(lt.autoDeduct?Wn=Math.max(0,Number(lt.standardMinutes||0)):Wn=bi(Rn,ea)||0);const Fn=Math.max(0,rn-Wn),Na=ep(Ot,Fe);let ya;!Ot||!Ft||lt.mode==="fixed"&&Bn?ya="missing_punch":Fe&&Fn<Math.max(0,Number(Fe.minimumHalfDayMinutes||0))?ya="absent":Fe&&Fn<Math.max(0,Number(Fe.minimumFullDayMinutes||0))?ya="half_day":ya=Na>0?"late":"present";const Ba=Date.now();return await da(S,`Safe historical recalculation using current Lunch Policy (${S.attendanceDate})`),await yn(re(ie,`attendanceDaily/${t.companyId}/${S.attendanceDate}/${ye.id}`),{grossWorkMinutes:rn,workMinutes:Fn,lunchOut:Rn,lunchIn:ea,lunchMinutes:Wn,lunchPunchMissing:Bn,lateMinutes:Na,status:ya,source:S.source==="device_adjusted"?"device_adjusted":"device",remarks:lt.mode==="none"||lt.mode==="flexible"?"":S.remarks||"",updatedAt:Ba,engineVersion:5}),"changed"},Da=async S=>{if(!_n||!S)return;const ye=m.filter(Bn=>Bn.attendanceDate===S),Fe=M.filter(Bn=>vh(Bn.punchTimestamp)===S);if(!ye.length&&!Fe.length){window.alert(`No attendance data found for ${S}.`);return}const lt=new Set(Fe.map(Bn=>{const Fn=fu(Bn,c);return(Fn==null?void 0:Fn.id)||""}
4015).filter(Boolean)).size,Ot=ue.mode==="access_control_multi_punch"?` 4016 4017Access Control safety: raw punches à¦à¦¾à§à¦¾ পà§à¦°à§à¦¨à§ saved record guess/rewrite à¦à¦°à¦¾ হবৠনা।`:"";if(!window.confirm(`${S} attendance safe recalculation à¦à¦°à¦¬à§à¦¨? 4018 4019Raw punch থাà¦à¦²à§ current engine/policy বà§à¦¯à¦¬à¦¹à¦¾à¦° হবà§à¥¤ Manual/HR-adjusted record overwrite হবৠনা। পরিবরà§à¦¤à¦¨à§à¦° à¦à¦à§ attendance snapshot audit/adjustment history-তৠরাà¦à¦¾ হবà§à¥¤${Ot} 4020 4021Detected raw-punch employee groups: ${lt}`))return;on(!0);let Ft=0,rn=0,Rn=0,ea=0,Wn=0;try{const Bn=new Map;Fe.forEach(Fn=>{const Na=fu(Fn,c);if(!Na)return;const ya=Bn.get(Na.id);ya?ya.punches.push(Fn):Bn.set(Na.id,{employee:Na,punches:[Fn]})});for(const Fn of Bn.values()){const Na=m.find(ya=>ya.employeeId===Fn.employee.id&&ya.attendanceDate===S);if(Zn(Na)){Rn+=1;continue}try{Na&&await da(Na,`Safe raw-punch historical recalculation (${S})`),await ec(Fn.employee,S,Fn.punches,{markRawPunchesProcessed:!1}),Ft+=1}catch(ya){Wn+=1,console.error("Historical raw-punch recalculation failed:",ya)}}for(const Fn of ye){if(Bn.has(Fn.employeeId))continue;const Na=c.find(ya=>ya.id===Fn.employeeId);if(Na)try{const ya=await Ga(Fn,Na);ya==="changed"?rn+=1:ya==="skipped_manual"?Rn+=1:ea+=1}catch(ya){Wn+=1,console.error("Historical saved-record recalculation failed:",ya)}}window.alert(`Safe attendance recalculation completed for ${S}. 4022 4023Raw-punch groups recalculated: ${Ft} 4024Saved records recalculated: ${rn} 4025Manual/adjusted records protected: ${Rn} 4026Access Control records skipped (no raw punches): ${ea} 4027Failed: ${Wn} 4028 4029Raw punch facts were not modified.`)}finally{on(!1)}},Ia=async()=>{if(!_n||!ht)return;const S=m.filter(Wn=>Wn.attendanceDate.startsWith(ht)),ye=M.filter(Wn=>vh(Wn.punchTimestamp).startsWith(ht));if(!S.length&&!ye.length){window.alert(`No attendance data found for ${ht}.`);return}const Fe=new Set;ye.forEach(Wn=>{const Bn=fu(Wn,c);Bn&&Fe.add(`${Bn.id}_${vh(Wn.punchTimestamp)}`)});const lt=ue.mode==="access_control_multi_punch"?` 4030 4031Access Control safety: raw punches à¦à¦¾à§à¦¾ পà§à¦°à§à¦¨à§ saved record guess/rewrite à¦à¦°à¦¾ হবৠনা।`:"";if(!window.confirm(`${ht} month-à¦à¦° attendance safe recalculation à¦à¦°à¦¬à§à¦¨? 4032 4033Raw punch থাà¦à¦²à§ current engine/policy বà§à¦¯à¦¬à¦¹à¦¾à¦° হবà§à¥¤ Manual/HR-adjusted record overwrite হবৠনা। পà§à¦°à¦¤à¦¿à¦à¦¿ পরিবরà§à¦¤à¦¨à§à¦° à¦à¦à§ snapshot attendance adjustment history-তৠরাà¦à¦¾ হবà§à¥¤${lt} 4034 4035Detected raw-punch employee/day groups: ${Fe.size}`))return;on(!0);let Ot=0,Ft=0,rn=0,Rn=0,ea=0;try{const Wn=new Map;ye.forEach(Bn=>{const Fn=fu(Bn,c);if(!Fn)return;const Na=vh(Bn.punchTimestamp),ya=`${Fn.id}_${Na}`,Ba=Wn.get(ya);Ba?Ba.punches.push(Bn):Wn.set(ya,{employee:Fn,date:Na,punches:[Bn]})});for(const Bn of Wn.values()){const Fn=m.find(Na=>Na.employeeId===Bn.employee.id&&Na.attendanceDate===Bn.date);if(Zn(Fn)){rn+=1;continue}try{Fn&&await da(Fn,`Safe raw-punch monthly recalculation (${ht})`),await ec(Bn.employee,Bn.date,Bn.punches,{markRawPunchesProcessed:!1}),Ot+=1}catch(Na){ea+=1,console.error("Monthly raw-punch recalculation failed:",Na)}}for(const Bn of S){const Fn=`${Bn.employeeId}_${Bn.attendanceDate}`;if(Wn.has(Fn))continue;const Na=c.find(ya=>ya.id===Bn.employeeId);if(Na)try{const ya=await Ga(Bn,Na);ya==="changed"?Ft+=1:ya==="skipped_manual"?rn+=1:Rn+=1}catch(ya){ea+=1,console.error("Monthly saved-record recalculation failed:",ya)}}window.alert(`${ht} safe attendance recalculation completed. 4036 4037Raw-punch employee/day groups recalculated: ${Ot} 4038Saved records recalculated: ${Ft} 4039Manual/adjusted records protected: ${rn} 4040Access Control records skipped (no raw punches): ${Rn} 4041Failed: ${ea} 4042 4043Raw punch facts were not modified. Payroll was not changed.`)}finally{on(!1)}},ls=async()=>{if(_n){on(!0);try{await Pn(re(ie,`attendancePolicy/${t.companyId}`),{...ue,updatedAt:Date.now(),updatedByUid:t.uid,updatedByName:t.name}),window.alert("Attendance policy saved.")}finally{on(!1)}}},Ua=async()=>
4043{if(!_n)return;const S=c.find(Rn=>Rn.id===Pe.employeeId);if(!S||!Pe.movementDate||!Pe.outTime){window.alert("Employee, date and OUT time are required.");return}Be(!0);const ye=Ta(re(ie,`attendanceMovements/${t.companyId}/${Pe.movementDate}`)),Fe=Date.now(),lt=ye.key||`movement_${Fe}`,Ot=Pe.movementType==="official_duty"&&ue.officialDutyApprovalRequired?"pending":"approved",Ft={id:lt,companyId:t.companyId,branchId:S.branchId||"",employeeId:S.id,employeeName:S.name,employeeCode:S.employeeId||"",movementDate:Pe.movementDate,outTime:Pe.outTime,inTime:Pe.inTime||"",movementType:Pe.movementType,purpose:Pe.purpose.trim(),reference:Pe.reference.trim(),source:"manual",status:Ot,requestedByUid:t.uid,requestedByName:t.name,createdAt:Fe,updatedAt:Fe};let rn;try{const Rn=Pn(ye,Ft),ea=new Promise((Wn,Bn)=>{rn=setTimeout(()=>Bn(new Error("MOVEMENT_SAVE_TIMEOUT")),12e3)});try{await Promise.race([Rn,ea])}catch(Wn){if(!(Wn instanceof Error&&Wn.message==="MOVEMENT_SAVE_TIMEOUT"))throw Wn;if(!(await Promise.race([mn(ye),new Promise((Na,ya)=>setTimeout(()=>ya(new Error("MOVEMENT_VERIFY_TIMEOUT")),8e3))])).exists())throw new Error("MOVEMENT_SAVE_TIMEOUT")}Re(Wn=>({...Wn,employeeId:"",outTime:"",inTime:"",purpose:"",reference:""})),window.alert(Ot==="pending"?"Movement saved. Official Duty is waiting for approval.":"Movement saved successfully.")}catch(Rn){console.error("Movement save failed:",Rn);const ea=Rn instanceof Error?Rn.message:"Unknown Firebase error";ea.includes("MOVEMENT_SAVE_TIMEOUT")||ea.includes("MOVEMENT_VERIFY_TIMEOUT")?window.alert("Movement save confirmation পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ Internet/Firebase connection check à¦à¦°à§ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤ যদি Review Queue-তৠrecord দà§à¦à¦¾ যাà§, à¦à¦¬à¦¾à¦° Save à¦à¦°à¦¬à§à¦¨ না।"):ea.includes("PERMISSION_DENIED")||ea.includes("permission_denied")?window.alert("Movement save permission denied. User/company access check à¦à¦°à§à¦¨à¥¤"):window.alert(`Movement save à¦à¦°à¦¾ যাà§à¦¨à¦¿: ${ea}`)}finally{rn&&clearTimeout(rn),Be(!1)}},va=async(S,ye)=>{if(!_n)return;const Fe=Date.now();await yn(re(ie,`attendanceMovements/${t.companyId}/${S.movementDate}/${S.id}`),{status:ye,approvedByUid:t.uid,approvedByName:t.name,approvedAt:Fe,updatedAt:Fe})},_a=ge.filter(S=>a==="all"||!a||S.branchId===a);return e.jsxs("section",{className:"attendance-page",children:[e.jsxs("header",{className:"attendance-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR Operations"}),e.jsx("h1",{children:"Attendance"}),e.jsx("p",{children:"Daily attendance, shifts and holidays with future ZKTeco sync support."})]}),e.jsxs("div",{className:"attendance-header-actions",children:[tn==="daily"&&e.jsxs(e.Fragment,{children:[_n&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Zt,type:"file",accept:".csv,text/csv",style:{display:"none"},onChange:S=>{var Fe;const ye=(Fe=S.target.files)==null?void 0:Fe[0];ye&&Ve(ye)}}),e.jsxs("button",{className:"secondary-action",disabled:sn,onClick:()=>{var S;return(S=Zt.current)==null?void 0:S.click()},children:[e.jsx(Mi,{size:17})," Import Historical CSV"]})]}),e.jsxs("button",{className:"secondary-action",onClick:vn,children:[e.jsx(Mi,{size:17})," Export CSV"]})]}),tn==="monthly"&&e.jsxs("button",{className:"secondary-action",onClick:Yt,children:[e.jsx(Mi,{size:17})," Export Monthly"]}),tn==="reports"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"primary-action",onClick:Bc,disabled:!Js.length,children:[e.jsx(Zs,{size:17})," Download PDF"]}),e.jsxs("button",{className:"secondary-action",onClick:$i,children:[e.jsx(Wi,{size:17})," Print"]}),e.jsxs("button",{className:"secondary-action",onClick:to,children:[e.jsx(Mi,{size:17})," Export CSV"]})]})]})]}),!i&&e.jsxs("div",{className:"attendance-tabs",children:[e.jsxs("button",{className:tn==="dashboard"?"active":"",onClick:()=>
4043B("dashboard"),children:[e.jsx(x1,{size:16})," Dashboard"]}),e.jsxs("button",{className:tn==="daily"?"active":"",onClick:()=>B("daily"),children:[e.jsx(wi,{size:16})," Daily"]}),e.jsxs("button",{className:tn==="monthly"?"active":"",onClick:()=>B("monthly"),children:[e.jsx(wi,{size:16})," Monthly"]}),e.jsxs("button",{className:tn==="leave"?"active":"",onClick:()=>B("leave"),children:[e.jsx(vd,{size:16})," Leave"]}),e.jsxs("button",{className:tn==="shifts"?"active":"",onClick:()=>B("shifts"),children:[e.jsx(Ho,{size:16})," Shifts"]}),e.jsxs("button",{className:tn==="holidays"?"active":"",onClick:()=>B("holidays"),children:[e.jsx(vu,{size:16})," Holidays"]}),e.jsxs("button",{className:tn==="lunch"?"active":"",onClick:()=>B("lunch"),children:[e.jsx(Ho,{size:16})," Lunch Policy"]}),e.jsxs("button",{className:tn==="movement"?"active":"",onClick:()=>B("movement"),children:[e.jsx(Ei,{size:16})," Outside Movement"]}),e.jsxs("button",{className:tn==="devices"?"active":"",onClick:()=>B("devices"),children:[e.jsx(Ly,{size:16})," Device Manager"]}),ft&&e.jsxs("button",{className:tn==="face_enrollment"?"active":"",onClick:()=>B("face_enrollment"),children:[e.jsx(vd,{size:16})," Face Enrollment"]})]}),tn==="dashboard"&&e.jsxs("section",{className:"attendance-dashboard",children:[e.jsxs("div",{className:"attendance-dashboard-kpis",children:[e.jsxs("article",{children:[e.jsx(mc,{size:19}),e.jsx("span",{children:"Total Employees"}),e.jsx("strong",{children:pr.total})]}),e.jsxs("article",{children:[e.jsx(vd,{size:19}),e.jsx("span",{children:"Present Today"}),e.jsx("strong",{children:pr.present})]}),e.jsxs("article",{children:[e.jsx(Ho,{size:19}),e.jsx("span",{children:"Late Today"}),e.jsx("strong",{children:pr.late})]}),e.jsxs("article",{children:[e.jsx(w1,{size:19}),e.jsx("span",{children:"Absent Today"}),e.jsx("strong",{children:pr.absent})]}),e.jsxs("article",{children:[e.jsx(wi,{size:19}),e.jsx("span",{children:"On Leave"}),e.jsx("strong",{children:pr.leave})]}),e.jsxs("article",{children:[e.jsx(Hi,{size:19}),e.jsx("span",{children:"Missing Punch"}),e.jsx("strong",{children:pr.missing})]})]}),e.jsxs("div",{className:"attendance-dashboard-panels",children:[e.jsxs("article",{className:"attendance-dashboard-panel",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(MD,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Monthly Attention"}),e.jsx("p",{children:"Current month exceptions"})]})]}),e.jsxs("div",{className:"dashboard-metric-list",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Total Late"}),e.jsx("strong",{children:pr.monthLate})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Pending Leave"}),e.jsx("strong",{children:pr.pendingLeave})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Late Deduction Preview"}),e.jsxs("strong",{children:[Math.floor(pr.monthLate/3)," ","day(s)"]})]})]})]}),e.jsxs("article",{className:"attendance-dashboard-panel",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(wi,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Upcoming Holiday"}),e.jsx("p",{children:"Next configured holiday"})]})]}),pr.upcomingHoliday?e.jsxs("div",{className:"upcoming-holiday-card",children:[e.jsx("strong",{children:pr.upcomingHoliday.name}),e.jsx("span",{children:pr.upcomingHoliday.date}),e.jsx("small",{children:pr.upcomingHoliday.type==="full_day"?"Full Day":"Half Day"})]}):e.jsx("p",{className:"dashboard-empty",children:"No upcoming holiday configured."})]}),e.jsxs("article",{className:"attendance-dashboard-panel",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(Zs,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Quick Reports"}),e.jsx("p",{children:"Open common reports"})]})]}),e.jsxs("div",{className:"dashboard-report-buttons",children:[e.jsx("button",{onClick:()=>{rt("monthly_summary"),B("reports")},children:"Monthly Summary"}),e.jsx("button",{onClick:()=>{rt("late"),B("reports")},children:"Late Report"}),e.jsx("button",{onClick:()=>{rt("missing_punch"),B("reports")},children:"Missing Punch"}),e.jsx("button",{onClick:()=>{rt("payroll"),B("reports")},children:"Payroll Summary"})]})]})]})]}),tn==="daily"&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"attendance-stats",children:[e.jsxs("article",{children:[e.jsx(mc,{size:18}),e.jsx("span",{children:"Total Employees"}),e.jsx("strong",{children:Xn.total})]}),e.jsxs("article",{children:[e.jsx(vd,{size:18}),e.jsx("span",{children:"Present"}),e.jsx("strong",{children:Xn.present})]}),e.jsxs("article",{children:[e.jsx(Ho,{size:18}),e.jsx("span",{children:"Late"}),e.jsx("strong",{children:Xn.late})]}),e.jsxs("article",{children:[e.jsx(w1,{size:18}),e.jsx("span",{children:"Absent"}),e.jsx("strong",{children:Xn.absent})]}),e.jsxs("article",{children:[e.jsx(wi,{size:18}),e.jsx("span",{children:"Leave"}),e.jsx("strong",{children:Xn.leave})]}),e.jsxs("article",{children:[e.jsx(Hi,{size:18}),e.jsx("span",{children:"Missing Punch"}),e.jsx("strong",{children:Xn.missing})]})]}),e.jsxs("section",{className:"attendance-filter-bar",children:[e.jsx("input",{type:"date",value:xe,onChange:S=>tt(S.target.value)}),e.jsxs("label",{className:"attendance-search",children:[e.jsx(xr,{size:16}),e.jsx("input",{value:gn,onChange:S=>An(S.target.value),placeholder:"Search employee..."})]}),e.jsxs("select",{value:Sn,onChange:S=>Xt(S.target.value),children:[e.jsx("option",{value:"all",children:"All Statuses"}
4043),Object.entries(fh).map(([S,ye])=>e.jsx("option",{value:S,children:ye},S))]}),_n&&e.jsxs("button",{className:"secondary-action",disabled:sn,onClick:()=>void Da(xe),children:[e.jsx(Hi,{size:16})," Safe Recalculate Date"]})]}),ue.mode==="access_control_multi_punch"&&e.jsxs("div",{className:"access-live-note",children:[e.jsx("strong",{children:"Access Control Live Calculation"}),e.jsx("span",{children:"Inside + Approved Official Duty + Approved Permission = Total Working Time. Pending/rejected/unclassified movement stays under Review and is not protected yet. This is attendance calculation only; Payroll is still unchanged."})]}),e.jsx("section",{className:"attendance-table-card",children:e.jsx("div",{className:"attendance-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Check In"}),e.jsx("th",{children:"Check Out"}),e.jsx("th",{children:"Lunch"}),e.jsx("th",{children:"Late"}),e.jsx("th",{children:"Work Hours"}),ue.mode==="access_control_multi_punch"&&e.jsxs(e.Fragment,{children:[e.jsx("th",{children:"Inside"}),e.jsx("th",{children:"Official Duty"}),e.jsx("th",{children:"Lunch"}),e.jsx("th",{children:"Personal"}),e.jsx("th",{children:"Review"}),e.jsx("th",{children:"Total Working Time"})]}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:(ue.mode==="access_control_multi_punch"?Ea:At.map(S=>({...S,accessSummary:void 0}))).map(({employee:S,record:ye,accessSummary:Fe})=>{var lt;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.name}),e.jsx("small",{children:S.employeeId||"â"})]}),e.jsx("td",{children:((lt=n.find(Ot=>Ot.id===((ye==null?void 0:ye.branchId)||S.branchId)))==null?void 0:lt.name)||"â"}),e.jsx("td",{children:(ye==null?void 0:ye.checkIn)||"â"}),e.jsx("td",{children:(ye==null?void 0:ye.checkOut)||"â"}),e.jsxs("td",{children:[ye!=null&&ye.lunchOut||ye!=null&&ye.lunchIn?`${(ye==null?void 0:ye.lunchOut)||"â"} â ${(ye==null?void 0:ye.lunchIn)||"â"}`:ye!=null&&ye.lunchMinutes?`${ye.lunchMinutes} min`:"â",(ye==null?void 0:ye.lunchPunchMissing)&&e.jsx("small",{children:"Lunch punch missing"})]}),e.jsx("td",{children:ye!=null&&ye.lateMinutes?`${ye.lateMinutes} min`:"0"}),e.jsx("td",{children:ye!=null&&ye.workMinutes?`${Math.floor(ye.workMinutes/60)}h ${ye.workMinutes%60}m`:"â"}),ue.mode==="access_control_multi_punch"&&Fe&&e.jsxs(e.Fragment,{children:[e.jsx("td",{children:zn(Fe.insideMinutes)}),e.jsx("td",{children:zn(Fe.officialDutyMinutes)}),e.jsx("td",{children:zn(Fe.lunchMinutes)}),e.jsx("td",{children:zn(Fe.personalMinutes)}),e.jsx("td",{children:Fe.reviewRequired>0?e.jsxs("span",{className:"movement-status pending",children:[Fe.reviewRequired," review"]}):e.jsx("span",{className:"movement-status approved",children:"clear"})}),e.jsx("td",{children:e.jsx("strong",{children:zn(Fe.effectiveWorkMinutes)})})]}),e.jsx("td",{children:e.jsx("span",{className:`attendance-status status-${ye?Xr(ye,S):"not_marked"}`,children:ye?fh[Xr(ye,S)]:"Not Marked"})}),e.jsx("td",{children:(ye==null?void 0:ye.source)||"â"}),e.jsx("td",{children:_n&&e.jsxs("button",{className:"attendance-edit-button",onClick:()=>Fc(S,ye),children:[ye?e.jsx(Tb,{size:15}):e.jsx(as,{size:15}),ye?"Edit":"Add"]})})]},S.id)})})]})})})]}),tn==="monthly"&&e.jsxs("section",{className:"monthly-attendance-section",children:[e.jsxs("div",{className:"monthly-attendance-toolbar",children:[e.jsxs("label",{children:["Month",e.jsx("input",{type:"month",value:ht,onChange:S=>dt(S.target.value)})]}),_n&&e.jsxs("button",{className:"secondary-action",disabled:sn,onClick:()=>void Ia(),children:[e.jsx(Hi,{size:16})," Safe Recalculate Month"]}),e.jsxs("div",{className:"monthly-legend",children:[e.jsxs("span",{children:[e.jsx("b",{children:"P"})," Present"]}),e.jsxs("span",{children:[e.jsx("b",{children:"L"})," Late"]}),e.jsxs("span",{children:[e.jsx("b",{children:"A"})," Absent"]}),e.jsxs("span",{children:[e.jsx("b",{children:"HD"})," Half Day"]}),e.jsxs("span",{children:[e.jsx("b",{children:"LV"})," Leave"]}),e.jsxs("span",{children:[e.jsx("b",{children:"DO"})," Official Day Off"]}),e.jsxs("span",{children:[e.jsx("b",{children:"MP"})," Missing Punch"]}),e.jsxs("span",{children:[e.jsx("b",{children:"WO"})," Weekly Off"]}),e.jsxs("span",{children:[e.jsx("b",{children:"H"})," Holiday"]})]})]}),e.jsx("div",{className:"monthly-grid-wrap",children:e.jsxs("table",{className:"monthly-grid",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"sticky-employee",children:"Employee"}),qa.map(({day:S,date:ye})=>e.jsx("th",{children:S},ye)),e.jsx("th",{children:"P"}),e.jsx("th",{children:"L"}),e.jsx("th",{children:"A"}),e.jsx("th",{children:"HD"}),e.jsx("th",{children:"LV"}),e.jsx("th",{children:"DO"}),e.jsx("th",{children:"Paid"}),e.jsx("th",{children:"Unpaid"}),e.jsx("th",{children:"MP"}),e.jsx("th",{children:"Ded."})]})}),e.jsx("tbody",{children:Rr.map(({employee:S,dayValues:ye,summary:Fe})=>e.jsxs("tr",{children:[e.jsxs("td",{className:"sticky-employee",children:[e.jsx("strong",{children:S.name}),e.jsx("small",{children:S.employeeId||"â"})]}),ye.map(lt=>e.jsx("td",{title:lt.label,children:e.jsx("span",{className:`monthly-code code-${lt.code||"empty"}`,children:lt.code||"â"})},lt.date)),e.jsx("td",{children:Fe.present}),e.jsx("td",{children:Fe.late}),e.jsx("td",{children:Fe.absent}),e.jsx("td",{children:Fe.halfDay}),e.jsx("td",{children:Fe.leave}),e.jsx("td",{children:Fe.officialDayOff}),e.jsx("td",{children:Fe.paidLeave}),e.jsx("td",{children:Fe.unpaidLeave}),e.jsx("td",{children:Fe.missing}),e.jsx("td",{children:Math.floor(Fe.late/3)})]},S.id))})]})}),e.jsxs("div",{className:"monthly-summary-strip",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Present"}),e.jsx("strong",{children:Or.present})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Late"}),e.jsx("strong",{children:Or.late})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Absent"}),e.jsx("strong",{children:Or.absent})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Half Day"}),e.jsx("strong",{children:Or.halfDay})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Leave"}),e.jsx("strong",{children:Or.leave})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Official Day Off"}),e.jsx("strong",{children:Or.officialDayOff})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Missing Punch"}),e.jsx("strong",{children:Or.missing})]})]})]}),tn==="monthly"&&ue.mode==="access_control_multi_punch"&&e.jsxs("section",{className:"access-monthly-summary",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(Ho,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Access Control Monthly Work Summary"}),e.jsxs("p",{children:["Live movement-classified time for ",ht,". Payroll is not connected yet."]})]})]}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Record Days"}),e.jsx("th",{children:"Inside"}),e.jsx("th",{children:"Official Duty"}),e.jsx("th",{children:"Approved Permission"}),e.jsx("th",{children:"Lunch"}),e.jsx("th",{children:"Personal"}),e.jsx("th",{children:"Unclassified"}),e.jsx("th",{children:"Review"}),e.jsx("th",{children:"Total Working Time"})]})}),e.jsx("tbody",{children:ga.map(S=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.employee.name}),e.jsx("small",{children:S.employee.employeeId||"â"})]}),e.jsx("td",{children:S.recordDays}),e.jsx("td",{children:zn(S.insideMinutes)}),e.jsx("td",{children:zn(S.officialDutyMinutes)}),e.jsx("td",{children:zn(S.permissionMinutes)}),e.jsx("td",{children:zn(S.lunchMinutes)}),e.jsx("td",{children:zn(S.personalMinutes)}),e.jsx("td",{children:zn(S.unclassifiedMinutes)}),e.jsx("td",{children:S.reviewRequired>0?e.jsx("span",{className:"movement-status pending",children:S.reviewRequired}):e.jsx("span",{className:"movement-status approved",children:"clear"})}),e.jsx("td",{children:e.jsx("strong",{children:zn(S.effectiveWorkMinutes)})})]},S.employee.id))})]})}),e.jsxs("div",{className:"movement-engine-note",children:[e.jsx("strong",{children:"Safety:"}),e.jsx("span",{children:"This table is calculated from existing attendance records + Outside Movement records. It does not rewrite Daily Attendance and does not create Payroll deductions."})]})]}),tn==="leave"&&e.jsxs("section",{className:"leave-workspace",children:[e.jsxs("div",{className:"leave-workspace-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:W?"Employee Self-Service":"Leave Management"}),e.jsx("h2",{children:W?"My Leave":"Employee Leave"}),e.jsx("p",{children:W?"Apply leave, check your balance and follow approval status.":"Apply, approve, manage policy and review employee leave history."})]}),e.jsxs("button",{className:"primary-action leave-new-request-button",onClick:He,children:[e.jsx(as,{size:17})," New Leave Request"]})]}),W&&e.jsxs("article",{className:"leave-full-panel",children:[e.jsx("div",{className:"leave-panel-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"My Leave Balance"}),e.jsx("p",{children:"Current year allowance, used days and remaining balance."})]})}),e.jsx("div",{className:"leave-policy-summary-grid",children:rs.map(S=>e.jsxs("div",{children:[e.jsx("strong",{children:Vn(S.leaveType)}),e.jsxs("span",{children:["Balance:"," ",S.balance===Number.POSITIVE_INFINITY?"Unlimited":`${S.balance} day(s)`]}),e.jsxs("small",{children:["Used: ",S.used," · Allowed:"," ",S.allowed===Number.POSITIVE_INFINITY?"Unlimited":S.allowed]})]},S.leaveType))})]}),e.jsxs("div",{className:"leave-overview-cards",children:[e.jsxs("article",{children:[e.jsx(Ho,{size:18}),e.jsx("span",{children:W?"My Pending":"Pending Approval"}),e.jsx("strong",{children:is.pending})]}),e.jsxs("article",{children:[e.jsx(Ms,{size:18}),e.jsx("span",{children:W?"My Approved This Year":"Approved This Year"}),e.jsx("strong",{children:is.approved})]}),e.jsxs("article",{children:[e.jsx(ja,{size:18}),e.jsx("span",{children:W?"My Rejected":"Rejected"}),e.jsx("strong",{children:is.rejected})]}),e.jsxs("article",{children:[e.jsx(vd,{size:18}),e.jsx("span",{children:"On Leave Today"}),e.jsx("strong",{children:is.employeesOnLeaveToday})]})]}),e.jsxs("div",{className:"leave-subtabs",children:[e.jsxs("button",{className:Nt==="overview"?"active":"",onClick:()=>be("overview"),children:[e.jsx(x1,{size:16}),"Overview"]}),_n&&e.jsxs("button",{className:Nt==="approval"?"active":"",onClick:()=>be("approval"),children:[e.jsx(vd,{size:16}),"Approval Queue",is.pending>0&&e.jsx("span",{children:is.pending})]}),_n&&e.jsxs("button",{className:Nt==="official_off"?"active":"",onClick:()=>be("official_off"),children:[e.jsx(wi,{size:16}),"Official Day Off"]}),_n&&e.jsxs("button",{className:Nt==="policy"?"active":"",onClick:()=>be("policy"),children:[e.jsx(vu,{size:16}),"Leave Policy"]}),e.jsxs("button",{className:Nt==="ledger"?"active":"",onClick:()=>be("ledger"),children:[e.jsx(Rb,{size:16}),W?"My Leave History":"Leave Ledger"]})]}),Nt==="official_off"&&_n&&e.jsxs("div",{className:"leave-overview-layout",children:[e.jsxs("article",{className:"leave-overview-panel",children:[e.jsx("div",{className:"leave-panel-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Assign Official Day Off"}),e.jsx("p",{children:"Company-authorized paid/protected off. It does not use Casual, Earned or other leave balance."})]})}),e.jsxs("div",{className:"leave-request-form-grid",children:[e.jsxs("label",{className:"span-2",children:["Employee",e.jsxs("select",{value:Ye.employeeId,onChange:S=>Je({...Ye,employeeId:S.target.value}),children:[e.jsx("option",{value:"",children:"Select Employee"}),[...he].sort(Rf).map(S=>e.jsxs("option",{value:S.id,children:[S.name," ",S.employeeId?`(${S.employeeId})`:""]},S.id))]})]}),e.jsxs("label",{children:["From Date",e.jsx("input",{type:"date",value:Ye.fromDate,onChange:S=>Je({...Ye,fromDate:S.target.value})})]}),e.jsxs("label",{children:["To Date",e.jsx("input",{type:"date",value:Ye.toDate,onChange:S=>Je({...Ye,toDate:S.target.value})})]}),e.jsxs("label",{className:"span-2",children:["Official / Company Reason",e.jsx("textarea",{rows:4,value:Ye.reason,onChange:S=>Je({...Ye,reason:S.target.value}),placeholder:"Training, company assignment, management-authorized off, etc."})]})]}),e.jsxs("div",{className:"leave-policy-payment-note",children:[e.jsx("strong",{children:"Protected Paid Off"}),e.jsx("span",{children:"No normal leave balance will be reduced. Employee cannot submit this type themselves."})]}),e.jsxs("button",{className:"primary-action",disabled:Te,onClick:()=>void Ie(),children:[e.jsx(as,{size:17}),Te?"Saving...":"Assign Official Day Off"]})]}),e.jsxs("article",{className:"leave-overview-panel",children:[e.jsx("div",{className:"leave-panel-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Official Day Off History"}),e.jsx("p",{children:"Latest company-authorized day-off assignments."})]})}),e.jsx("div",{className:"leave-policy-table-card",children:e.jsxs("table",{className:"leave-policy-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Reason"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Assigned By"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[Ce.filter(S=>a==="all"||S.branchId===a).map(S=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.employeeName}),e.jsx("br",{}),e.jsx("small",{children:S.employeeCode||"â"})]}),e.jsx("td",{children:S.fromDate===S.toDate?S.fromDate:`${S.fromDate} â ${S.toDate}`}),e.jsx("td",{children:S.reason}),e.jsx("td",{children:e.jsx("span",{className:`leave-status ${S.status==="active"?"approved":"cancelled"}`,children:S.status==="active"?"Active / Paid":"Cancelled"})}),e.jsx("td",{children:S.assignedByName}),e.jsx("td",{children:S.status==="active"?e.jsx("button",{className:"vx-button vx-button-secondary",disabled:Te,onClick:()=>void Le(S),children:"Cancel"}):"â"})]},S.id)),!Ce.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"leave-table-empty",children:"No Official Day Off assigned yet."})})]})]})})]})]}),Nt==="overview"&&e.jsxs("div",{className:"leave-overview-layout",children:[e.jsxs("article",{className:"leave-overview-panel",children:[e.jsxs("div",{className:"leave-panel-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Recent Leave Requests"}),e.jsx("p",{children:"Latest employee leave activity."})]}),e.jsx("button",{onClick:()=>be(W?"ledger":"approval"),children:"View all"})]}),e.jsxs("div",{className:"leave-overview-list",children:[ra.slice(0,5).map(S=>e.jsxs("button",{onClick:()=>{te(S),pt(S.approvalComment||"")},children:[e.jsxs("div",{children:[e.jsx("strong",{children:S.employeeName}),e.jsxs("span",{children:[Vn(S.leaveType)," · ",ua(S.fromDate,S.toDate,S.durationType)," ","day(s)"]})]}),e.jsx("span",{className:`leave-status ${S.approvalStatus}`,children:S.approvalStatus})]},S.id)),!ra.length&&e.jsxs("div",{className:"leave-overview-empty",children:[e.jsx(vd,{size:26}),e.jsx("strong",{children:"No leave request yet."}),e.jsx("span",{children:"New employee requests will appear here."})]})]})]}),e.jsxs("article",{className:"leave-overview-panel",children:[e.jsxs("div",{className:"leave-panel-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Configured Leave Policies"}),e.jsx("p",{children:"Annual quota and payment rules."})]}),!W&&e.jsx("button",{onClick:()=>be("policy"),children:"Manage"})]}),e.jsxs("div",{className:"leave-policy-summary-grid",children:[pe.map(S=>e.jsxs("div",{children:[e.jsx("strong",{children:Vn(S.leaveType)}),e.jsx("span",{children:S.leaveType==="unpaid"?"Unlimited":`${S.annualQuota} days`}),e.jsxs("small",{children:[S.paid?"Paid":"Unpaid"," · ",S.strictQuota?"Strict":"Flexible"]})]},S.id)),!pe.length&&e.jsxs("div",{className:"leave-overview-empty",children:[e.jsx(vu,{size:26}),e.jsx("strong",{children:"No leave policy configured."}),e.jsx("span",{children:"Configure leave quota before employees apply."})]})]})]})]}),Nt==="approval"&&_n&&e.jsxs("article",{className:"leave-approval-queue leave-full-panel",c
4043hildren:[e.jsxs("div",{className:"leave-queue-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Leave Approval Queue"}),e.jsx("p",{children:"Pending requests review à¦à¦°à§à¦¨ à¦à¦¬à¦ decision history দà§à¦à§à¦¨à¥¤"})]}),e.jsxs("span",{className:"leave-pending-count",children:[xa.pending," Pending"]})]}),e.jsx("div",{className:"leave-queue-tabs",children:["pending","approved","rejected","withdrawn","cancelled","all"].map(S=>e.jsxs("button",{className:le===S?"active":"",onClick:()=>nt(S),children:[e.jsx("span",{children:S}),e.jsx("strong",{children:xa[S]})]},S))}),e.jsx("div",{className:"leave-approval-table-wrap",children:e.jsxs("table",{className:"leave-approval-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Leave Type"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Days"}),e.jsx("th",{children:"Duration"}),e.jsx("th",{children:"Payment"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[Ha.map(S=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.employeeName}),e.jsx("small",{children:S.employeeCode||"â"})]}),e.jsx("td",{children:Vn(S.leaveType)}),e.jsxs("td",{children:[S.fromDate,e.jsxs("small",{children:["to ",S.toDate]})]}),e.jsx("td",{children:ua(S.fromDate,S.toDate,S.durationType)}),e.jsx("td",{children:S.durationType==="half_day"?S.halfDayPeriod==="second_half"?"Half Day · Second Half":"Half Day · First Half":"Full Day"}),e.jsx("td",{children:Ma(S.durationType,S.paid!==!1)?"Paid":"Unpaid"}),e.jsx("td",{children:e.jsx("span",{className:`leave-status ${S.approvalStatus}`,children:S.approvalStatus})}),e.jsx("td",{children:e.jsxs("button",{className:"leave-review-button",onClick:()=>{te(S),pt(S.approvalComment||"")},children:["Review",e.jsx(Ei,{size:15})]})})]},S.id)),!Ha.length&&e.jsx("tr",{children:e.jsxs("td",{colSpan:8,className:"leave-table-empty",children:["No"," ",le==="all"?"":le," ","leave request found."]})})]})]})})]}),Nt==="policy"&&_n&&e.jsxs("div",{className:"leave-policy-layout",children:[e.jsxs("article",{className:"leave-policy-form-card",children:[e.jsx("h3",{children:"Configure Leave Policy"}),e.jsx("p",{children:"Annual allowance, payment status and quota restriction."}),e.jsxs("div",{className:"leave-half-day-policy-box",children:[e.jsx("strong",{children:"Half Day Leave Payment Setup"}),e.jsx("p",{children:"This rule applies to every approved Half Day leave, including existing records when Payroll is regenerated."}),e.jsxs("label",{children:["Half Day Payment",e.jsxs("select",{value:Me,onChange:S=>ot(S.target.value),children:[e.jsx("option",{value:"paid",children:"Paid â no s
4043alary deduction"}),e.jsx("option",{value:"unpaid",children:"Unpaid â deduct 0.5 day salary"}),e.jsx("option",{value:"leave_type",children:"Follow selected Leave Type policy"})]})]}),e.jsx("button",{type:"button",className:"secondary-action",disabled:wt,onClick:()=>void E(),children:wt?"Saving...":"Save Half Day Setup"}),e.jsx("small",{children:"Default: Paid. Full Day leave continues to follow its Leave Type policy."})]}),e.jsxs("label",{children:["Leave Type",e.jsxs("select",{value:ka.leaveType,onChange:S=>{const ye=S.target.value,Fe=pe.find(lt=>lt.leaveType===ye);Ja({leaveType:ye,annualQuota:(Fe==null?void 0:Fe.annualQuota)??(ye==="casual"?10:ye==="sick"?14:ye==="earned"?18:ye==="special"?2:0),paid:(Fe==null?void 0:Fe.paid)??ye!=="unpaid",strictQuota:(Fe==null?void 0:Fe.strictQuota)??ye!=="unpaid"})},children:[e.jsx("option",{value:"casual",children:"Casual Leave"}),e.jsx("option",{value:"sick",children:"Sick Leave"}),e.jsx("option",{value:"earned",children:"Earned Leave"}),e.jsx("option",{value:"special",children:"Special Leave"}),e.jsx("option",{value:"unpaid",children:"Unpaid Leave"})]})]}),ka.leaveType!=="unpaid"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Annual Allowed Days",e.jsx("input",{type:"number",min:"0",step:"0.5",value:ka.annualQuota,onChange:S=>Ja({...ka,annualQuota:Number(S.target.value)||0})})]}),e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:ka.paid,onChange:S=>Ja({...ka,paid:S.target.checked})}),"Paid Leave"]}),e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:ka.strictQuota,onChange:S=>Ja({...ka,strictQuota:S.target.checked})}),"Strict Quota"]})]}),e.jsxs("button",{className:"primary-action",onClick:()=>void Q(),children:[e.jsx(as,{size:17}),"Save Leave Policy"]})]}),e.jsxs("article",{className:"leave-policy-table-card",children:[e.jsx("div",{className:"leave-panel-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Leave Policy List"}),e.jsx("p",{children:"Active policy by leave category."})]})}),e.jsxs("table",{className:"leave-policy-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Leave Type"}),e.jsx("th",{children:"Annual Quota"}),e.jsx("th",{children:"Payment"}),e.jsx("th",{children:"Quota Rule"})]})}),e.jsxs("tbody",{children:[pe.map(S=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:Vn(S.leaveType)})}),e.jsx("td",{children:S.leaveType==="unpaid"?"Unlimited":`${S.annualQuota} days`}),e.jsx("td",{children:S.paid?"Paid":"Unpaid"}),e.jsx("td",{children:S.strictQuota?"Strict":"Flexible"})]},S.id)),!pe.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"leave-table-empty",children:"No leave policy configured."})})]})]})]})]}),Nt==="ledger"&&e.jsxs("article",{className:"leave-full-panel",children:[e.jsx("div",{className:"leave-panel-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:W?"My Leave History":"Employee Leave Ledger"}),e.jsx("p",{children:W?"Your submitted leave requests and current approval status.":"Approved leave history and balance consumption."})]})}),e.jsx("div",{className:"leave-approval-table-wrap",children:e.jsxs("table",{className:"leave-approval-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Leave Type"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Days"}),e.jsx("th",{children:"Duration"}),e.jsx("th",{children:"Payment"}),W&&e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Approved By"}),e.jsx("th",{children:"Approved At"})]})}),e.jsxs("tbody",{children:[hs.map(S=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.employeeName}),e.jsx("small",{children:S.employeeCode||"â"})]}),e.jsx("td",{children:Vn(S.leaveType)}),e.jsxs("td",{children:[S.fromDate,e.jsxs("small",{children:["to ",S.toDate]})]}),e.jsx("td",{children:S.days}),e.jsx("td",{children:S.durationType==="half_day"?S.halfDayPeriod==="second_half"?"Half Day · Second Half":"Half Day · First Half":"Full Day"}),e.jsx("td",{children:S.paid?"Paid":"Unpaid"}),W&&e.jsx("td",{children:e.jsx("span",{className:`leave-status ${S.status}`,children:S.status})}),e.jsx("td",{children:S.approvedBy}),e.jsx("td",{children:new Date(S.approvedAt).toLocaleDateString("en-GB")})]},S.id)),!hs.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:W?9:8,className:"leave-table-empty",children:"No approved leave history found."})})]})]})})]})]}),jt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>bt(!1),children:e.jsxs("section",{className:"modal leave-request-modal",onMouseDown:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Leave Request"}),e.jsx("h2",{children:W?"Apply My Leave":"Apply Employee Leave"})]}),e.jsx("button",{onClick:()=>bt(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"leave-request-form-grid",children:[e.jsxs("label",{className:"span-2",children:["Employee",W?e.jsx("input",{value:ta?`${ta.name}${ta.employeeId?` (${ta.employeeId})`:""}`:"Employee profile not linked",readOnly:!0}):e.jsxs("select",{value:jn.employeeId,onChange:S=>vs({...jn,employeeId:S.target.value}),children:[e.jsx("option",{value:"",children:"Select Employee"}),[...c].sort(Rf).map(S=>e.jsxs("option",{value:S.id,children:[S.name," ",S.employeeId?`(${S.employeeId})`:""]},S.id))]})]}),e.jsxs("label",{className:"span-2",children:["Leave Type",e.jsxs("select",{value:jn.leaveType,onCh
4043ange:S=>vs({...jn,leaveType:S.target.value,paid:S.target.value!=="unpaid"}),children:[e.jsx("option",{value:"casual",children:"Casual Leave"}),e.jsx("option",{value:"sick",children:"Sick Leave"}),e.jsx("option",{value:"earned",children:"Earned Leave"}),e.jsx("option",{value:"special",children:"Special Leave"}),e.jsx("option",{value:"unpaid",children:"Unpaid Leave"})]})]}),jn.employeeId&&oa&&e.jsxs("div",{className:"leave-balance-preview span-2",children:[e.jsx("span",{children:Vn(jn.leaveType)}),e.jsxs("div",{children:[e.jsx("small",{children:"Allowed"}),e.jsx("strong",{children:oa.allowed===Number.POSITIVE_INFINITY?"Unlimited":oa.allowed})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Used"}),e.jsx("strong",{children:oa.used})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Balance"}),e.jsx("strong",{children:oa.balance===Number.POSITIVE_INFINITY?"Unlimited":oa.balance})]})]}),e.jsxs("label",{children:["From Date",e.jsx("input",{type:"date",value:jn.fromDate,onChange:S=>vs({...jn,fromDate:S.target.value})})]}),e.jsxs("label",{children:["To Date",e.jsx("input",{type:"date",value:jn.toDate,onChange:S=>vs({...jn,toDate:S.target.value})})]}),e.jsxs("label",{children:["Duration",e.jsxs("select",{value:jn.durationType,onChange:S=>vs({...jn,durationType:S.target.value,toDate:S.target.value==="half_day"?jn.fromDate:jn.toDate}),children:[e.jsx("option",{value:"full_day",children:"Full Day"}),e.jsx("option",{value:"half_day",children:"Half Day"})]})]}),jn.durationType==="half_day"&&e.jsxs("label",{children:["Half Day Period",e.jsxs("select",{value:jn.halfDayPeriod,onChange:S=>vs({...jn,halfDayPeriod:S.target.value}),children:[e.jsx("option",{value:"first_half",children:"First Half"}),e.jsx("option",{value:"second_half",children:"Second Half"})]})]}),e.jsxs("div",{className:"leave-policy-payment-note",children:[e.jsx("strong",{children:Ma(jn.durationType,(oa==null?void 0:oa.paid)!==!1)?"Paid Leave":"Unpaid Leave"}),e.jsx("span",{children:jn.durationType==="half_day"?"Controlled by Half Day Leave Payment Setup.":"Controlled by Leave Policy."})]}),e.jsxs("label",{className:"span-2",children:["Reason",e.jsx("textarea",{rows:4,value:jn.reason,onChange:S=>vs({...jn,reason:S.target.value})})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"vx-button vx-button-secondary",onClick:()=>bt(!1),children:"Cancel"}),e.jsxs("button",{className:"vx-button vx-button-primary",onClick:()=>void gt(),children:[e.jsx(as,{size:17}),"Submit Leave Request"]})]})]})}),xt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!$e&&te(null),children:e.jsxs("section",{className:"modal leave-approval-modal",onMouseDown:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Leave Approval"}),e.jsx("h2",{children:xt.employeeName})]}),e.jsx("button",{disabled:$e,onClick:()=>te(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"leave-approval-summary",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Leave Type"}),e.jsx("strong",{children:Vn(xt.leaveType)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Date"}),e.jsxs("strong",{children:[xt.fromDate," â ",xt.toDate]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Duration"}),e.jsxs("strong",{children:[ua(xt.fromDate,xt.toDate,xt.durationType)," ","day(s)"]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Payment"}),e.jsx("strong",{children:xt.paid?"Paid":"Unpaid"})]})]}),e.jsxs("div",{className:"leave-approval-reason",children:[e.jsx("span",{children:"Employee Reason"}),e.jsx("p",{children:xt.reason})]}),e.jsxs("label",{className:"leave-approval-comment",children:["Approval Comment",e.jsx("textarea",{rows:4,value:Ge,readOnly:W,onChange:S=>pt(S.target.value),placeholder:"Decision note বা rejection reason লিà¦à§à¦¨..."})]}),xt.decisionHistory&&e.jsxs("div",{className:"leave-decision-history",children:[e.jsx("h3",{children:"Decision History"}),Object.values(xt.decisionHistory).sort((S,ye)=>ye.createdAt-S.createdAt).map((S,ye)=>e.jsxs("div",{children:[e.jsx("span",{className:`leave-status ${S.action}`,children:S.action}),e.jsxs("div",{children:[e.jsx("strong",{children:S.actorName}
4043),e.jsx("small",{children:new Date(S.createdAt).toLocaleString("en-GB")}),S.comment&&e.jsx("p",{children:S.comment})]})]},`${S.createdAt}-${ye}`))]}),e.jsxs("div",{className:"modal-actions leave-approval-actions",children:[xt.approvalStatus==="pending"&&(!W||xt.employeeId===(ta==null?void 0:ta.id))&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"vx-button vx-button-secondary",disabled:$e,onClick:()=>void Dt(xt,"withdrawn",Ge),children:"Withdraw"}),_n&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"vx-button leave-reject-button",disabled:$e||!Ge.trim(),onClick:()=>void Dt(xt,"rejected",Ge),children:"Reject"}),e.jsxs("button",{className:"vx-button vx-button-primary",disabled:$e,onClick:()=>void Dt(xt,"approved",Ge),children:[e.jsx(Ms,{size:17}),"Approve Leave"]})]})]}),_n&&xt.approvalStatus==="approved"&&e.jsx("button",{className:"vx-button leave-reject-button",disabled:$e||!Ge.trim(),onClick:()=>void Dt(xt,"cancelled",Ge),children:"Cancel Approved Leave"})]})]})}),tn==="reports"&&e.jsxs("section",{className:"attendance-reports",children:[e.jsxs("div",{className:"attendance-report-filters no-print",children:[e.jsxs("label",{children:["Report",e.jsxs("select",{value:we,onChange:S=>rt(S.target.value),children:[e.jsx("option",{value:"monthly_summary",children:"Monthly Summary"}),e.jsx("option",{value:"daily",children:"Daily Attendance"}),e.jsx("option",{value:"late",children:"Late Report"}),e.jsx("option",{value:"missing_punch",children:"Missing Punch"}),e.jsx("option",{value:"leave",children:"Leave Report"}),e.jsx("option",{value:"payroll",children:"Payroll Summary"})]})]}),e.jsxs("label",{children:["Month",e.jsx("input",{type:"month",value:ht,onChange:S=>dt(S.target.value)})]}),e.jsxs("label",{children:["Employee",e.jsxs("select",{value:St,onChange:S=>Qt(S.target.value),children:[e.jsx("option",{value:"all",children:"All Employees"}),he.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]})]}),e.jsxs("article",{className:"attendance-report-paper",children:[e.jsxs("header",{className:"attendance-report-header",children:[e.jsxs("div",{children:[e.jsx("p",{children:"VERIXO ERP · ATTENDANCE REPORT"}),e.jsx("h2",{children:Ko}),e.jsxs("span",{children:["Period: ",ht]})]}),e.jsxs("div",{children:[e.jsx("strong",{children:((zs=n.find(S=>S.id===a))==null?void 0:zs.name)||(a==="all"?"All Branches":"")}),e.jsxs("span",{children:["Generated:"," ",new Date().toLocaleDateString("en-GB")]})]})]}),e.jsx("div",{className:"attendance-report-table-wrap",children:e.jsxs("table",{className:"attendance-report-table",children:[e.jsx("thead",{children:e.jsx("tr",{children:Js.length>0&&Object.keys(Js[0]).map(S=>e.jsx("th",{children:S.replace(/([A-Z])/g," $1").replace(/^./,ye=>ye.toUpperCase())},S))})}),e.jsxs("tbody",{children:[Js.map((S,ye)=>e.jsx("tr",{children:Object.values(S).map((Fe,lt)=>e.jsx("td",{children:String(Fe??"")},lt))},ye)),!Js.length&&e.jsx("tr",{children:e.jsx("td",{className:"attendance-report-empty",colSpan:12,children:"No report data found."})})]})]})}),e.jsxs("footer",{className:"attendance-report-footer",children:[e.jsxs("span",{children:["Total Records: ",Js.length]}),e.jsx("span",{children:"Prepared through VERIXO ERP"})]})]})]}),tn==="shifts"&&e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"attendance-shift-assignment-summary",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Employee Assignment"}),e.jsx("h2",{children:"Shift Assignment"}),e.jsx("p",{children:"Employee-à¦à¦° shift HR â Employees â Edit Employee থà§à¦à§ assign à¦à¦°à§à¦¨à¥¤ Assigned shift branch default-à¦à¦° à¦à¦à§ বà§à¦¯à¦¬à¦¹à¦¾à¦° হবà§à¥¤"})]}),e.jsxs("div",{className:"shift-assignment-stats",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Configured Shifts"}),e.jsx("strong",{children:u.length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Assigned Employees"}),e.jsx("strong",{children:c.filter(S=>!!S.shiftId).length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Using Branch Default"}),e.jsx("strong",{children:c.filter(S=>!S.shiftId).length})]})]})]}),e.jsxs("section",{className:"attendance-settings-grid",children:[e.jsxs("article",{className:"attendance-settings-form",children:[e.jsx("h2",{children:"Add Shift"}),e.jsxs("label",{children:["Shift Name",e.jsx("input",{value:Et.name,onChange:S=>Rt({...Et,name:S.target.value})})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:Et.branchId,onChange:S=>Rt({...Et,branchId:S.target.value}),children:[e.jsx("option",{value:"all",children:"All Branches"}),n.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:["Start Time",e.jsx("input",{type:"time",value:Et.startTime,onChange:S=>Rt({...Et,startTime:S.target.value})})]}),e.jsxs("label",{children:["End Time",e.jsx("input",{type:"time",value:Et.endTime,onChange:S=>Rt({...Et,endTime:S.target.value})})]})]}),e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:["Grace Minutes",e.jsx("input",{type:"number",value:Et.graceMinutes,onChange:S=>Rt({...Et,graceMinutes:Number(S.target.value)||0})})]}),e.jsxs("label",{children:["Half Day After",e.jsx("input",{type:"time",value:Et.halfDayAfter,onChange:S=>Rt({...Et,halfDayAfter:S.target.value})})]})]}),e.jsx("div",{className:"attendance-policy-divider",children:"Lunch Settings"}),e.jsxs("label",{children:["Lunch Policy Mode",e.jsxs("select",{value:Et.lunchMode,onChange:S=>{const ye=S.target.value;Rt({...Et,lunchMode:ye,lunchEnabled:ye!=="none",autoDeductStandardLunch:ye==="fixed"?Et.autoDeductStandardLunch:!1})},children:[e.jsx("option",{value:"fixed",children:"Fixed Lunch Break"}),e.jsx("option",{value:"flexible",children:"Flexible Lunch Break"}),e.jsx("option",{value:"none",children:"No Lunch Break"})]}),e.jsx("small",{className:"field-help",children:"Fixed = নিরà§à¦¦à¦¿à¦·à§à¦ সমà§/standard deduction; Flexible = lunch যà§à¦à§à¦¨à§ সমà§à§, blind deduction নà§; None = lunch deduction নà§à¦à¥¤"})]}),Et.lunchMode==="fixed"&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:["Lunch Start",e.jsx("input",{type:"time",value:Et.lunchStart,onCh
4043ange:S=>Rt({...Et,lunchStart:S.target.value})})]}),e.jsxs("label",{children:["Lunch End",e.jsx("input",{type:"time",value:Et.lunchEnd,onChange:S=>Rt({...Et,lunchEnd:S.target.value})})]})]})}),Et.lunchMode!=="none"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:[Et.lunchMode==="flexible"?"Lunch Allowance / Max Minutes":"Standard Lunch Minutes",e.jsx("input",{type:"number",min:"0",value:Et.standardLunchMinutes,onChange:S=>Rt({...Et,standardLunchMinutes:Number(S.target.value)||0})})]}),e.jsxs("label",{children:["Lunch Grace Minutes",e.jsx("input",{type:"number",min:"0",value:Et.lunchGraceMinutes,onChange:S=>Rt({...Et,lunchGraceMinutes:Number(S.target.value)||0})})]})]}),e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:Et.autoDetectLunchPunch,onChange:S=>Rt({...Et,autoDetectLunchPunch:S.target.checked})}),"Detect Lunch / Break Punches"]}),Et.lunchMode==="fixed"&&e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:Et.autoDeductStandardLunch,onChange:S=>Rt({...Et,autoDeductStandardLunch:S.target.checked})}),"Deduct Fixed Standard Lunch Duration"]}),e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:Et.allowEmployeeLunchOverride,onChange:S=>Rt({...Et,allowEmployeeLunchOverride:S.target.checked})}),"Allow Employee-specific Lunch Policy"]})]}),e.jsxs("button",{className:"primary-action",onClick:()=>void Uc(),children:[e.jsx(as,{size:17})," Save Shift"]})]}),e.jsxs("article",{className:"attendance-settings-list",children:[e.jsx("h2",{children:"Configured Shifts"}),u.map(S=>e.jsxs("div",{children:[e.jsx("strong",{children:S.name}),e.jsxs("span",{children:[S.startTime," â ",S.endTime]}),e.jsxs("small",{children:["Grace ",S.graceMinutes," minutes"]}),e.jsx("small",{children:(S.lunchMode||(S.lunchEnabled===!1?"none":"fixed"))==="none"?"No lunch break":(S.lunchMode||"fixed")==="flexible"?`Flexible lunch · up to ${S.standardLunchMinutes} min`:`Fixed lunch ${S.lunchStart} â ${S.lunchEnd} (${S.standardLunchMinutes} min)`}),e.jsx("div",{className:"configured-shift-actions",children:e.jsxs("button",{type:"button",className:"shift-delete-button",onClick:()=>void Yl(S),children:[e.jsx(po,{size:15}),"Delete"]})})]},S.id)),!u.length&&e.jsx("p",{children:"No shift configured yet."})]})]})]}),tn==="holidays"&&e.jsxs("section",{className:"holiday-rules-workspace",children:[e.jsx("div",{className:"holiday-section-heading",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Attendance Calendar"}),e.jsx("h2",{children:"Weekly Off & Holidays"}),e.jsx("p",{children:"Weekly off à¦à¦à¦¬à¦¾à¦° সà§à¦ à¦à¦°à§à¦¨à¥¤ বিশà§à¦· à¦à§à¦à¦¿ নিরà§à¦¦à¦¿à¦·à§à¦ তারিà¦à§ à¦à¦²à¦¾à¦¦à¦¾à¦à¦¾à¦¬à§ যà§à¦ à¦à¦°à§à¦¨à¥¤"})]})}),e.jsxs("div",{className:"holiday-rule-grid",children:[e.jsxs("article",{className:"holiday-rule-card",children:[e.jsxs("div",{className:"holiday-card-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Weekly Off Rule"}),e.jsx("p",{children:"Friday, Saturday বা à¦à¦à¦¾à¦§à¦¿à¦ দিন recurring weekly off হিসà§à¦¬à§ সà§à¦ à¦à¦°à§à¦¨à¥¤"})]}),e.jsx("span",{className:"holiday-rule-badge",children:"Recurring"})]}),e.jsxs("label",{children:["Rule Name",e.jsx("input",{value:Ln.name,onChange:S=>wa({...Ln,name:S.target.value})})]}),e.jsx("div",{className:"weekly-day-picker",children:bs.map(S=>e.jsx("button",{type:"button",className:Ln.weekdays.includes(S.value)?"active":"",onClick:()=>Ue(S.value),children:S.label.slice(0,3)},S.value))}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:Ln.branchId,onChange:S=>wa({...Ln,branchId:S.target.value}),children:[e.jsx("option",{value:"all",children:"All Branches"}),n.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:["Effective From",e.jsx("input",{type:"date",value:Ln.effectiveFrom,onChange:S=>wa({...Ln,effectiveFrom:S.target.value})})]}),e.jsxs("label",{children:["Effective Until",e.jsx("input",{type:"date",value:Ln.effectiveUntil,onCh
4043ange:S=>wa({...Ln,effectiveUntil:S.target.value})})]})]}),e.jsxs("button",{className:"primary-action",onClick:()=>void yt(),children:[e.jsx(as,{size:17})," Save Weekly Off Rule"]})]}),e.jsxs("article",{className:"holiday-rule-card",children:[e.jsxs("div",{className:"holiday-card-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Special Holiday"}),e.jsx("p",{children:"Eid, national holiday বা company holiday নিরà§à¦¦à¦¿à¦·à§à¦ তারিà¦à§ যà§à¦ à¦à¦°à§à¦¨à¥¤"})]}),e.jsx("span",{className:"holiday-rule-badge special",children:"One-time"})]}),e.jsxs("label",{children:["Holiday Name",e.jsx("input",{value:xn.name,onChange:S=>dn({...xn,name:S.target.value})})]}),e.jsxs("label",{children:["Date",e.jsx("input",{type:"date",value:xn.date,onChange:S=>dn({...xn,date:S.target.value})})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:xn.branchId,onChange:S=>dn({...xn,branchId:S.target.value}),children:[e.jsx("option",{value:"all",children:"All Branches"}),n.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),e.jsxs("label",{children:["Holiday Type",e.jsxs("select",{value:xn.type,onChange:S=>dn({...xn,type:S.target.value}),children:[e.jsx("option",{value:"full_day",children:"Full Day"}),e.jsx("option",{value:"half_day",children:"Half Day"})]})]}),e.jsxs("button",{className:"primary-action",onClick:()=>void kt(),children:[e.jsx(as,{size:17})," Save Special Holiday"]})]})]}),e.jsxs("div",{className:"holiday-list-grid",children:[e.jsxs("article",{className:"holiday-list-card",children:[e.jsx("div",{className:"holiday-card-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Weekly Off Rules"}),e.jsx("p",{children:"Active recurring weekly schedules."})]})}),e.jsxs("div",{className:"holiday-rule-list",children:[N.map(S=>{var ye;return e.jsxs("div",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:S.name}),e.jsx("span",{children:S.weekdays.map(Fe=>{var lt;return(lt=bs.find(Ot=>Ot.value===Fe))==null?void 0:lt.label}).filter(Boolean).join(", ")})]}),e.jsxs("div",{children:[e.jsx("small",{children:S.branchId==="all"?"All Branches":((ye=n.find(Fe=>Fe.id===S.branchId))==null?void 0:ye.name)||"Branch"}),e.jsxs("small",{children:[S.effectiveFrom," â ",S.effectiveUntil||"No expiry"]})]})]},S.id)}),!N.length&&e.jsx("p",{children:"No weekly off rule configured."})]})]}),e.jsxs("article",{className:"holiday-list-card",children:[e.jsx("div",{className:"holiday-card-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Special Holiday List"}),e.jsx("p",{children:"One-time full-day and half-day holidays."})]})}),e.jsxs("div",{className:"holiday-rule-list",children:[y.sort((S,ye)=>S.date.localeCompare(ye.date)).map(S=>{var ye;return e.jsxs("div",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:S.name}),e.jsx("span",{children:S.date})]}),e.jsxs("div",{children:[e.jsx("small",{children:S.type==="full_day"?"Full Day":"Half Day"}),e.jsx("small",{children:S.branchId==="all"||!S.branchId?"All Branches":((ye=n.find(Fe=>Fe.id===S.branchId))==null?void 0:ye.name)||"Branch"})]})]},S.id)}),!y.length&&e.jsx("p",{children:"No special holiday configured."})]})]})]})]}),tn==="lunch"&&e.jsxs("section",{className:"attendance-settings-grid",children:[e.jsxs("article",{className:"attendance-settings-form",children:[e.jsx("h2",{children:"Employee Lunch Setup"}),e.jsx("p",{className:"attendance-settings-help",children:"Particular employee-à¦à¦° lunch policy à¦à¦à¦¾à¦¨à§à¦ à¦à¦à¦¬à¦¾à¦° setup à¦à¦°à§à¦¨à¥¤ পà§à¦°à§à¦¨à§ attendance-ঠpolicy apply à¦à¦°à¦¤à§ Monthly Attendance â Recalculate Month বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤"}),e.jsxs("label",{children:["Employee",e.jsxs("select",{value:aa.employeeId,onChange:S=>{const ye=S.target.value,Fe=F.find(Ot=>Ot.employeeId===ye),lt=(Fe==null?void 0:Fe.lunchMode)||(Fe?Fe.useShiftLunch?"shift_default":"fixed":"shift_default");$a({employeeId:ye,useShiftLunch:lt==="shift_default",lunchMode:lt,lunchStart:(Fe==null?void 0:Fe.lunchStart)||"13:00",lunchEnd:(Fe==null?void 0:Fe.lunchEnd)||"14:00",standardLunchMinutes:(Fe==null?void 0:Fe.standardLunchMinutes)||60,effectiveFrom:(Fe==null?void 0:Fe.effectiveFrom)||kr(),effectiveUntil:(Fe==null?void 0:Fe.effectiveUntil)||""})},children:[e.jsx("option",{value:"",children:"Select Employee"}),c.map(S=>e.jsxs("option",{value:S.id,children:[S.name," ",S.employeeId?`(${S.employeeId})`:""]},S.id))]})]}
4043),e.jsxs("label",{children:["Lunch Policy",e.jsxs("select",{value:aa.lunchMode,onChange:S=>{const ye=S.target.value;$a({...aa,lunchMode:ye,useShiftLunch:ye==="shift_default"})},children:[e.jsx("option",{value:"shift_default",children:"Follow Shift / Company Policy"}),e.jsx("option",{value:"fixed",children:"Fixed Lunch Break"}),e.jsx("option",{value:"flexible",children:"Flexible Lunch Break"}),e.jsx("option",{value:"none",children:"No Lunch Break"})]})]}),aa.lunchMode==="fixed"&&e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:["Lunch Start",e.jsx("input",{type:"time",value:aa.lunchStart,onChange:S=>$a({...aa,lunchStart:S.target.value})})]}),e.jsxs("label",{children:["Lunch End",e.jsx("input",{type:"time",value:aa.lunchEnd,onChange:S=>$a({...aa,lunchEnd:S.target.value})})]})]}),aa.lunchMode!=="shift_default"&&aa.lunchMode!=="none"&&e.jsxs("label",{children:[aa.lunchMode==="flexible"?"Lunch Allowance / Max Minutes":"Standard Lunch Minutes",e.jsx("input",{type:"number",min:"0",value:aa.standardLunchMinutes,onChange:S=>$a({...aa,standardLunchMinutes:Number(S.target.value)||0})})]}),aa.employeeId&&e.jsxs("div",{className:"employee-lunch-current-policy",children:[e.jsx("strong",{children:"Policy Being Edited"}),e.jsx("span",{children:aa.lunchMode==="shift_default"?"Follow Shift / Company Policy":aa.lunchMode==="none"?"No Lunch Break":aa.lunchMode==="flexible"?`Flexible Lunch Break â ${aa.standardLunchMinutes} min`:`Fixed Lunch Break â ${aa.lunchStart} to ${aa.lunchEnd}`})]}),e.jsxs("div",{className:"settings-two-column",children:[e.jsxs("label",{children:["Effective From",e.jsx("input",{type:"date",value:aa.effectiveFrom,onChange:S=>$a({...aa,effectiveFrom:S.target.value})})]}),e.jsxs("label",{children:["Effective Until",e.jsx("input",{type:"date",value:aa.effectiveUntil,onChange:S=>$a({...aa,effectiveUntil:S.target.value})})]})]}),e.jsxs("div",{className:"employee-lunch-form-actions",children:[e.jsxs("button",{className:"primary-action",onClick:()=>void Qn(),children:[e.jsx(as,{size:17})," ",F.some(S=>S.employeeId===aa.employeeId)?"Update Lunch Policy":"Save Lunch Policy"]}),aa.employeeId&&e.jsx("button",{type:"button",className:"secondary-action",onClick:()=>$a({employeeId:"",useShiftLunch:!0,lunchMode:"shift_default",lunchStart:"13:00",lunchEnd:"14:00",standardLunchMinutes:60,effectiveFrom:kr(),effectiveUntil:""}),children:"Clear"})]})]}),e.jsxs("article",{className:"attendance-settings-list",children:[e.jsx("h2",{children:"Employee Lunch Policies"}),F.sort((S,ye)=>S.employeeName.localeCompare(ye.employeeName)).map(S=>e.jsxs("div",{className:"employee-lunch-policy-row",children:[e.jsxs("div",{className:"employee-lunch-policy-info",children:[e.jsx("strong",{children:S.employeeName}),e.jsx("span",{children:(S.lunchMode||(S.useShiftLunch?"shift_default":"fixed"))==="shift_default"?"Uses shift/company lunch policy":(S.lunchMode||"fixed")==="none"?"No lunch break":(S.lunchMode||"fixed")==="flexible"?"Flexible lunch":`${S.lunchStart} â ${S.lunchEnd}`}),e.jsx("small",{children:(S.lunchMode||(S.useShiftLunch?"shift_default":"fixed"))==="shift_default"?"Default policy":(S.lunchMode||"fixed")==="none"?"Lunch break not assigned":`${S.standardLunchMinutes} minutes`}),e.jsxs("small",{children:["Effective: ",S.effectiveFrom||"Any date",S.effectiveUntil?` â ${S.effectiveUntil}`:" â ongoing"]})]}),_n&&e.jsxs("div",{className:"employee-lunch-policy-actions",children:[e.jsxs("button",{type:"button",className:"secondary-action",onClick:()=>an(S),children:[e.jsx(Tb,{size:15})," Edit"]}),e.jsxs("button",{type:"button",className:"danger-action",disabled:sn,onClick:()=>void Cn(S),children:[e.jsx(po,{size:15})," Delete"]})]})]},S.id)),!F.length&&e.jsx("p",{children:"No employee-specific lunch policy configured."})]})]}),tn==="movement"&&e.jsxs("section",{className:"attendance-movement-page",children:[e.jsxs("article",{className:"movement-policy-card",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(vu,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Attendance & Outside Movement Policy"}),e.jsx("p",{children:"Standard attendance বা Access Control multi-punch company configuration."})]})]}),e.jsx("div",{className:"movement-policy-grid movement-mode-only",children:e.jsxs("label",{children:["Attendance Mode",e.jsxs("select",{value:ue.mode,onCh
4043ange:S=>me({...ue,mode:S.target.value}),disabled:!_n,children:[e.jsx("option",{value:"standard",children:"Standard â First IN / Last OUT"}),e.jsx("option",{value:"access_control_multi_punch",children:"Access Control â Multi Punch"})]})]})}),ue.mode==="access_control_multi_punch"&&e.jsxs("div",{className:"movement-policy-grid",children:[e.jsxs("label",{children:["Personal Break Allowance (minutes/day)",e.jsx("input",{type:"number",min:"0",value:ue.personalBreakAllowanceMinutes,onChange:S=>me({...ue,personalBreakAllowanceMinutes:Math.max(0,Number(S.target.value||0))}),disabled:!_n})]}),e.jsxs("label",{children:["Unclassified OUT â IN",e.jsxs("select",{value:ue.unclassifiedOutsideTreatment,onChange:S=>me({...ue,unclassifiedOutsideTreatment:S.target.value}),disabled:!_n,children:[e.jsx("option",{value:"review_required",children:"Review Required â no automatic deduction"}),e.jsx("option",{value:"personal_break",children:"Treat as Personal Break"})]})]}),e.jsxs("label",{className:"movement-policy-check",children:[e.jsx("input",{type:"checkbox",checked:ue.officialDutyApprovalRequired,onChange:S=>me({...ue,officialDutyApprovalRequired:S.target.checked}),disabled:!_n}),"Official Duty requires manager approval"]})]}),_n&&e.jsxs("button",{className:"primary-action",disabled:sn,onClick:()=>void ls(),children:[e.jsx(vu,{size:16})," Save Attendance Mode"]}),ue.mode==="standard"?e.jsxs("div",{className:"movement-standard-note",children:[e.jsx("strong",{children:"Standard Attendance is active."}),e.jsx("span",{children:"First IN / Last OUT attendance will continue normally. Outside Movement Entry and Review Queue are hidden because access-control movement tracking is not active."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"movement-engine-note",children:[e.jsx("strong",{children:"Access Control active:"}),e.jsx("span",{children:"OUT â IN pairs are policy-classified automatically: explicit Permission/Official Duty first, then Lunch Policy, then daily Personal Break allowance. Only genuine exceptions remain Review Required. Raw punches are never rewritten."})]}),e.jsxs("div",{className:"movement-simulator",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(vu,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Multi-Punch Policy Simulator"}),e.jsx("p",{children:"Read-only preview of the current Access Control policy. Test data is never saved to Attendance, Raw Punches, Movements or Payroll."})]})]}),e.jsxs("div",{className:"movement-entry-grid",children:[e.jsxs("label",{children:["Test Employee (optional)",e.jsxs("select",{value:_e,onChange:S=>ee(S.target.value),children:[e.jsx("option",{value:"",children:"Use branch/shift policy only"}),[...he].sort(Rf).map(S=>e.jsxs("option",{value:S.id,children:[S.employeeId?`${S.employeeId} â `:"",S.name]},S.id))]})]}),e.jsxs("label",{children:["Test Punches (comma separated)",e.jsx("input",{value:We,onChange:S=>it(S.target.value),placeholder:"09:00, 10:30, 10:38, 13:00, 13:45, 15:30, 15:37, 18:00"})]})]}),e.jsx("small",{children:"Accepts H:MM or HH:MM, for example 9:00, 10:30, 10:38, 18:00."}),e.jsxs("div",{className:"movement-engine-note",children:[e.jsx("strong",{children:"Policy used:"}),e.jsxs("span",{children:["Personal allowance ",ue.personalBreakAllowanceMinutes||0," min/day ·"," ","Unclassified: ",ue.unclassifiedOutsideTreatment==="personal_break"?"Personal Break":"Review Required"," ·"," ","Lunch: ",ca.enabled&&ca.mode==="fixed"?`${ca.start||"â"}â${ca.end||"â"}`:ca.mode==="none"?"No Lunch":"Flexible / no fixed window",wn?` · Employee: ${wn.name}`:""]})]}),We.trim()&&En.length===0&&e.jsxs("div",{className:"movement-engine-note",children:[e.jsx("strong",{children:"Invalid punch format:"}),e.jsx("span",{children:"Comma-separated H:MM / HH:MM time দিন।"})]}),e.jsx("div",{className:"simulation-interval-list",children:Pa.map((S,ye)=>e.jsxs("div",{className:"simulation-interval-row",children:[e.jsxs("strong",{children:[S.outTime," â ",S.inTime]}),e.jsx("span",{children:Kn(S.minutes)}
4043),e.jsxs("div",{children:[e.jsx("strong",{children:S.type==="personal"?"Personal Break":S.type==="lunch_break"?"Lunch Break":S.type==="official_duty"?"Official Duty":S.type==="approved_permission"?"Approved Permission":"Review Required"}),e.jsx("small",{style:{display:"block"},children:S.reason})]})]},`${S.outTime}-${S.inTime}-${ye}`))}),e.jsxs("div",{className:"simulation-summary-grid",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Total Span"}),e.jsx("strong",{children:Kn(kn.spanMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Inside Time"}),e.jsx("strong",{children:Kn(kn.insideMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Official Duty"}),e.jsx("strong",{children:Kn(kn.officialDutyMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Lunch"}),e.jsx("strong",{children:Kn(kn.lunchMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Personal Outside"}),e.jsx("strong",{children:Kn(kn.personalMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Approved Permission"}),e.jsx("strong",{children:Kn(kn.permissionMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Unclassified"}),e.jsx("strong",{children:Kn(kn.unclassifiedMinutes)})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Review Required"}),e.jsx("strong",{children:kn.reviewRequired})]}),e.jsxs("div",{className:"simulation-effective",children:[e.jsx("small",{children:"Total Working Time"}),e.jsx("strong",{children:Kn(kn.effectiveWorkMinutes)})]})]}),e.jsxs("div",{className:"movement-engine-note",children:[e.jsx("strong",{children:"Preview only â nothing is saved:"}),e.jsx("span",{children:"This simulator mirrors automatic Lunch â Personal allowance â policy fallback classification. Explicit saved Official Duty / Approved Permission matching is handled only by the real employee/device flow. Payroll deduction is still disabled."})]})]})]})]}),ue.mode==="access_control_multi_punch"&&e.jsxs(e.Fragment,{children:[e.jsxs("article",{className:"movement-entry-card",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(as,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Outside Movement Entry"}),e.jsx("p",{children:"Sales, Technician, Accounts, Manager বা à¦
নà§à¦¯ যà§à¦à§à¦¨à§ employee-à¦à¦° exit classify à¦à¦°à§à¦¨."})]})]}),e.jsxs("div",{className:"movement-entry-grid",children:[e.jsxs("label",{children:["Employee",e.jsxs("select",{value:Pe.employeeId,onChange:S=>Re({...Pe,employeeId:S.target.value}),disabled:!_n,children:[e.jsx("option",{value:"",children:"Select employee"}),c.filter(S=>a==="all"||!a||S.branchId===a).map(S=>e.jsxs("option",{value:S.id,children:[S.employeeId?`${S.employeeId} â `:"",S.name]},S.id))]})]}),e.jsxs("label",{children:["Date",e.jsx("input",{type:"date",value:Pe.movementDate,onChange:S=>Re({...Pe,movementDate:S.target.value}),disabled:!_n})]}),e.jsxs("label",{children:["OUT",e.jsx("input",{type:"time",value:Pe.outTime,onChange:S=>Re({...Pe,outTime:S.target.value}),disabled:!_n})]}),e.jsxs("label",{children:["IN",e.jsx("input",{type:"time",value:Pe.inTime,onChange:S=>Re({...Pe,inTime:S.target.value}),disabled:!_n})]}),e.jsxs("label",{children:["Movement Type",e.jsxs("select",{value:Pe.movementType,onChange:S=>Re({...Pe,movementType:S.target.value}),disabled:!_n,children:[e.jsx("option",{value:"official_duty",children:"Official Duty"}),e.jsx("option",{value:"personal",children:"Personal"}),e.jsx("option",{value:"lunch_break",children:"Lunch / Break"}),e.jsx("option",{value:"approved_permission",children:"Approved Permission"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]}),e.jsxs("label",{children:["Reference",e.jsx("input",{value:Pe.reference,onChange:S=>Re({...Pe,reference:S.target.value}),placeholder:"Client / Job / Collection / Bank / Note",disabled:!_n})]}),e.jsxs("label",{className:"movement-purpose-field",children:["Purpose",e.jsx("input",{value:Pe.purpose,onChange:S=>Re({...Pe,purpose:S.target.value}),placeholder:"Why is the employee going outside?",disabled:!_n})]})]}),_n&&e.jsxs("button",{className:"primary-action",disabled:Ee,onClick:()=>void Ua(),children:[e.jsx(as,{size:16}),Ee?"Saving...":"Save Movement"]})]}),e.jsxs("article",{className:"movement-list-card",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx(Rb,{size:18}),e.jsxs("div",{children:[e.jsx("h2",{children:"Movement Review Queue"}),e.jsx("p",{children:"OUT â IN interval-à¦à¦° business meaning à¦à¦¬à¦ approval status."})]})]}),e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"OUT"}),e.jsx("th",{children:"IN"}),e.jsx("th",{children:"Duration"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Purpose / Reference"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Approval"})]})}),e.jsxs("tbody",{children:[_a.map(S=>{const ye=S.inTime?bi(S.outTime,S.inTime):void 0;return e.jsxs("tr",{children:[e.jsx("td",{children:S.movementDate}),e.jsxs("td",{children:[e.jsx("strong",{children:S.employeeName}),e.jsx("small",{children:S.employeeCode||""})]}),e.jsx("td",{children:S.outTime}),e.jsx("td",{children:S.inTime||"Outside"}),e.jsx("td",{children:ye===void 0?"Open":`${Math.floor(ye/60)}h ${ye%60}m`}),e.jsxs("td",{children:[S.movementType.replaceAll("_"," "),S.source==="auto_punch"&&e.jsx("small",{className:"movement-auto-source",children:"AUTO PUNCH"})]}),e.jsxs("td",{children:[e.jsx("strong",{children:S.purpose||"â"}),e.jsx("small",{children:S.reference||""})]}),e.jsx("td",{children:e.jsx("span",{className:`movement-status ${S.status}`,children:S.status})}),e.jsx("td",{children:S.status==="pending"&&_n?e.jsxs("div",{className:"movement-decision-buttons",children:[e.jsx("button",{type:"button",onClick:()=>void va(S,"approved"),children:"Approve"}),e.jsx("button",{type:"button",onClick:()=>void va(S,"rejected"),children:"Reject"})]}):e.jsx("small",{children:S.approvedByName||"â"})})]},`${S.movementDate}-${S.id}`)}),!_a.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"empty-table",children:"No outside movement records yet."})})]})]})})]})]})]}),tn==="face_enrollment"&&ft&&e.jsxs("section",{className:"attendance-device-workspace face-enrollment-workspace",children:[e.jsx("div",{className:"device-page-heading",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"CCTV Attendance"}),e.jsx("h2",{children:"Face Enrollment"}),e.jsx("p",{children:"Employee photo à¦à¦ browser থà§à¦à§ সরাসরি à¦à¦ PC-à¦à¦° local CCTV Connector-ঠযাবà§à¥¤ Face image/embedding Firebase বা VPS-ঠupload হবৠনা; VERIXO শà§à¦§à§ enrollment status রাà¦à¦¬à§à¥¤"})]})}),e.jsx("input",{ref:H,type:"file",accept:"image/jpeg,image/png",style:{display:"none"},onChange:S=>{var lt;const ye=(lt=S.target.files)==null?void 0:lt[0],Fe=K.current;ye&&Fe&&Qo(Fe,ye)}}),e.jsxs("article",{className:"device-list-card",children:[e.jsxs("div",{className:"device-list-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Employees"}),e.jsx("p",{children:"Front-facing, clear, well-lit single-person photo বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤"})]}),e.jsxs("div",{className:"face-enrollment-search",children:[e.jsx(xr,{size:16}),e.jsx("input",{placeholder:"Search employee...",value:J,onChange:S=>T(S.target.value)})]})]}),e.jsx("div",{className:"device-table-wrap",children:e.jsxs("table",{className:"device-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Enrollment"}),e.jsx("th",{children:"Last Updated"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[er.map(S=>{var lt;const ye=I[S.id],Fe=(ye==null?void 0:ye.status)==="enrolled";return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.name}),e.jsx("small",{children:S.employeeId||S.id})]}),e.jsx("td",{children:((lt=n.find(Ot=>Ot.id===S.branchId))==null?void 0:lt.name)||"â"}),e.jsx("td",{children:e.jsx("span",{className:`device-status ${Fe?"online":"offline"}`,children:Fe?`Enrolled${ye!=null&&ye.templateCount?` · ${ye.templateCount} template`:""}`:"Not Enrolled"})}),e.jsx("td",{children:ye!=null&&ye.updatedAt?new Date(ye.updatedAt).toLocaleStr
4043ing("en-GB"):"â"}),e.jsx("td",{children:e.jsxs("div",{className:"device-actions",children:[e.jsx("button",{onClick:()=>Ir(S),disabled:G===S.id,children:Fe?"Re-enroll":"Enroll Face"}),Fe&&e.jsx("button",{className:"danger",onClick:()=>void fo(S),disabled:G===S.id,children:"Remove"})]})})]},S.id)}),!er.length&&e.jsx("tr",{children:e.jsxs("td",{colSpan:5,className:"device-empty",children:[e.jsx(vd,{size:28}),e.jsx("strong",{children:"No employee found."})]})})]})]})})]}),e.jsx("article",{className:"device-log-card",children:e.jsx("div",{className:"device-list-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Local Connector Requirement"}),e.jsx("p",{children:"à¦à¦ page বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à¦¾à¦° à¦à¦à§ à¦à¦à¦ PC-তৠTOOLS â VERIXO_CCTV_Attendance_Connector â START-CCTV-CONNECTOR.bat à¦à¦¾à¦²à§ থাà¦à¦¤à§ হবà§à¥¤ Local enrollment API: 127.0.0.1:8765."})]})})})]}),tn==="devices"&&ft&&e.jsxs("section",{className:"attendance-device-workspace",children:[e.jsxs("div",{className:"device-page-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Attendance Integration"}),e.jsx("h2",{children:"Attendance Device & CCTV Manager"}),e.jsx("p",{children:"Biometric device à¦
থবা CCTV/AI camera configure à¦à¦°à§à¦¨à¥¤ Existing Attendance Engine à¦à¦à¦ থাà¦à¦¬à§; CCTV recognition event-ঠraw punch হিসà§à¦¬à§ process হবà§à¥¤"})]}),e.jsxs("button",{className:"primary-action device-add-button",onClick:()=>vl(),children:[e.jsx(as,{size:17})," Add Device"]})]}),e.jsxs("div",{className:"device-summary-cards",children:[e.jsxs("article",{children:[e.jsx(Ly,{size:19}),e.jsx("span",{children:"Total Devices"}),e.jsx("strong",{children:Jo.total})]}),e.jsxs("article",{children:[e.jsx(i6,{size:19}),e.jsx("span",{children:"Online"}),e.jsx("strong",{children:Jo.online})]}),e.jsxs("article",{children:[e.jsx(r6,{size:19}),e.jsx("span",{children:"Offline"}),e.jsx("strong",{children:Jo.offline})]}),e.jsxs("article",{children:[e.jsx(Hi,{size:19}),e.jsx("span",{children:"Sync Errors"}),e.jsx("strong",{children:Jo.errors})]})]}),e.jsxs("article",{className:"device-list-card",children:[e.jsx("div",{className:"device-list-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Configured Devices"}),e.jsx("p",{children:"Device status connector sync হà¦à§à¦¾à¦° পর automatic update হবà§à¥¤"})]})}),e.jsx("div",{className:"device-table-wrap",children:e.jsxs("table",{className:"device-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Device"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Network"}),e.jsx("th",{children:"Sync"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Last Sync"}),e.jsx("th",{children:"Actions"})]})}),e.jsxs("tbody",{children:[C.map(S=>{var ye;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:S.name}),e.jsxs("small",{children:[S.deviceType==="cctv"?"CCTV · ":"BIOMETRIC · ",S.brand.toUpperCase(),S.model?` · ${S.model}`:""]})]}),e.jsx("td",{children:((ye=n.find(Fe=>Fe.id===S.branchId))==null?void 0:ye.name)||"â"}),e.jsxs("td",{children:[e.jsx("strong",{children:S.ipAddress}),e.jsxs("small",{children:["Port ",S.port]})]}),e.jsx("td",{children:S.autoSync?S.syncMode.replace("_"," "):"Manual"}),e.jsx("td",{children:e.jsx("span",{className:`device-status ${S.connectionStatus}`,children:S.connectionStatus})}),e.jsxs("td",{children:[S.lastSyncAt?new Date(S.lastSyncAt).toLocaleString("en-GB"):"Never",S.lastError&&e.jsx("small",{className:"device-error",children:S.lastError})]}),e.jsx("td",{children:e.jsxs("div",{className:"device-actions",children:[e.jsx("button",{onClick:()=>void Vc(S),disabled:V===S.id,children:"Test"}),e.jsx("button",{onClick:()=>void _o(S),disabled:V===S.id,children:"Sync"}),e.jsx("button",{title:"Scan complete device history and upload only missing punches",onClick:()=>void ko(S),disabled:V===S.id,children:"Full Verify"}),e.jsx("button",{onClick:()=>vl(S),children:"Edit"}),e.jsx("button",{className:"danger",onClick:()=>void U(S),children:"Delete"})]})})]},S.id)}),!C.length&&e.jsx("tr",{children:e.jsxs("td",{colSpan:7,className:"device-empty",children:[e.jsx(Ly,{size:28}),e.jsx("strong",{children:"No attendance device configured."}),e.jsx("span",{children:"Add the first device to prepare VERIXO Attendance Connector."})]})})]})]})})]}),e.jsxs("article",{className:"device-log-card",children:[e.jsx("div",{className:"device-list-heading",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Recent Device Activity"}),e.jsx("p",{children:"Setup, test and sync request history."})]})}),e.jsxs("div",{className:"device-log-list",children:[zt.slice(0,10).map(S=>e.jsxs("div",{children:[e.jsx("span",{className:`device-log-status ${S.status}`}),e.jsxs("div",{children:[e.jsx("strong",{children:S.deviceName}),e.jsx("p",{children:S.message})]}
4043),e.jsx("small",{children:new Date(S.createdAt).toLocaleString("en-GB")})]},S.id)),!zt.length&&e.jsx("p",{children:"No device activity yet."})]})]})]}),ne&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>ae(!1),children:e.jsxs("section",{className:"modal attendance-device-modal",onMouseDown:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Device Configuration"}),e.jsx("h2",{children:Y?"Edit Attendance Device":"Add Attendance Device"})]}),e.jsx("button",{onClick:()=>ae(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"device-form-grid",children:[e.jsxs("label",{children:["Device Name *",e.jsx("input",{value:In.name,onChange:S=>Sa({...In,name:S.target.value})})]}),e.jsxs("label",{children:["Brand",e.jsxs("select",{value:In.brand,onChange:S=>Sa({...In,brand:S.target.value}),children:[e.jsx("option",{value:"zkteco",children:"ZKTeco"}),e.jsx("option",{value:"realtime",children:"Realtime"}),e.jsx("option",{value:"hikvision",children:"Hikvision"}),e.jsx("option",{value:"dahua",children:"Dahua"}),e.jsx("option",{value:"onvif",children:"ONVIF / RTSP"}),e.jsx("option",{value:"other",children:"Other"})]})]}),e.jsxs("label",{children:["Device Type",e.jsxs("select",{value:In.deviceType,onChange:S=>Sa({...In,deviceType:S.target.value}),children:[e.jsx("option",{value:"biometric",children:"Biometric / Punch Device"}),e.jsx("option",{value:"cctv",children:"CCTV / AI Face Recognition"})]})]}),e.jsxs("label",{children:["Model",e.jsx("input",{value:In.model,onChange:S=>Sa({...In,model:S.target.value})})]}),e.jsxs("label",{children:["Serial Number",e.jsx("input",{value:In.serialNumber,onChange:S=>Sa({...In,serialNumber:S.target.value})})]}),e.jsxs("label",{children:["IP Address *",e.jsx("input",{placeholder:"192.168.1.201",value:In.ipAddress,onChange:S=>Sa({...In,ipAddress:S.target.value})})]}),e.jsxs("label",{children:["Port",e.jsx("input",{type:"number",value:In.port,onChange:S=>Sa({...In,port:Number(S.target.value)||4370})})]}),In.deviceType!=="cctv"&&e.jsxs("label",{children:["Communication Password",e.jsx("input",{type:"password",value:In.communicationPassword,onChange:S=>Sa({...In,communicationPassword:S.target.value})})]}),e.jsxs("label",{children:["Branch *",e.jsxs("select",{value:In.branchId,onChange:S=>Sa({...In,branchId:S.target.value}),children:[e.jsx("option",{value:"",children:"Select Branch"}),n.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),In.deviceType==="cctv"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["RTSP / Camera Stream URL",e.jsx("input",{placeholder:"rtsp://camera-or-nvr/stream (no username/password)",value:In.streamUrl,onChange:S=>Sa({...In,streamUrl:S.target.value})})]}),e.jsx("div",{className:"field-note",children:"Camera username/password stays only on the local CCTV connector PC. Do not put credentials in this URL."}),e.jsxs("label",{children:["Camera Role",e.jsxs("select",{value:In.cameraRole,onChange:S=>Sa({...In,cameraRole:S.target.value}),children:[e.jsx("option",{value:"entry",children:"Entry"}),e.jsx("option",{value:"exit",children:"Exit"}),e.jsx("option",{value:"movement",children:"Outside Movement"}),e.jsx("option",{value:"general",children:"General / Auto"})]})]}),e.jsxs("label",{children:["Recognition Threshold",e.jsx("input",{type:"number",min:"0.5",max:"0.99",step:"0.01",value:In.recognitionThreshold,onChange:S=>Sa({...In,recognitionThreshold:Number(S.target.value)||.72})})]}),e.jsxs("label",{children:["Duplicate Cooldown (seconds)",e.jsx("input",{type:"number",min:"10",max:"3600",value:In.duplicateCooldownSeconds,onChange:S=>Sa({...In,duplicateCooldownSeconds:Number(S.target.value)||60})})]})]}),e.jsxs("label",{children:["Sync Frequency",e.jsxs("select",{value:In.syncMode,onChange:S=>Sa({...In,syncMode:S.target.value}),children:[e.jsx("option",{value:"1_min",children:"Every 1 Minute"}),e.jsx("option",{value:"5_min",children:"Every 5 Minutes"}),e.jsx("option",{value:"15_min",children:"Every 15 Minutes"}),e.jsx("option",{value:"manual",children:"Manual Only"})]})]}),e.jsxs("div",{className:"device-checkboxes",children:[e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:In.autoSync,onChange:S=>Sa({...In,autoSync:S.target.checked})}),"Auto Sync"]}),e.jsxs("label",{className:"attendance-checkbox-field",children:[e.jsx("input",{type:"checkbox",checked:In.active,onChange:S=>Sa({...In,active:S.target.checked})}),"Active Device"]})]})]}),e.jsxs("div",{className:"device-connector-note",children:[e.jsx(Ly,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Connector Required"}),e.jsx("span",{children:"Device à¦à¦¬à¦ connector PC à¦à¦à¦ LAN-ঠথাà¦à¦¤à§ হবà§à¥¤ Connector à¦à¦¾à§à¦¾ Test/Sync request pending থাà¦à¦¬à§à¥¤"})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"vx-button vx-button-secondary",onClick:()=>ae(!1),children:"Cancel"}),e.jsxs("button",{className:"vx-button vx-button-primary",onClick:()=>void tc(),children:[e.jsx(as,{size:17}),Y?"Update Device":"Save Device"]})]})]})}),Wt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!sn&&Gt(!1),children:e.jsxs("section",{className:"modal attendance-modal",onMouseDown:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Manual Attendance"}),e.jsx("h2",{children:((Bs=c.find(S=>S.id===ke.employeeId))==null?void 0:Bs.name)||"Attendance Entry"})]}),e.jsx("button",{disabled:sn,onClick:()=>Gt(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"attendance-form-grid",children:[e.jsxs("label",{children:["Date",e.jsx("input",{type:"date",value:ke.attendanceDate,onChange:S=>Ct({...ke,attendanceDate:S.target.value})})]}),e.jsxs("label",{children:["Branch",e.jsx("select",{value:ke.branchId,onChange:S=>Ct({...ke,branchId:S.target.value}),children:n.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))})]}),e.jsxs("label",{children:["Check In",e.jsx("input",{type:"time",value:ke.checkIn,onChange:S=>Ct({...ke,checkIn:S.target.value})})]}),e.jsxs("label",{children:["Check Out",e.jsx("input",{type:"time",value:ke.checkOut,onChange:S=>Ct({...ke,checkOut:S.target.value})})]}),e.jsxs("label",{children:["Lunch Out",e.jsx("input",{type:"time",value:ke.lunchOut,onChange:S=>Ct({...ke,lunchOut:S.target.value})})]}),e.jsxs("label",{children:["Lunch In",e.jsx("input",{type:"time",value:ke.lunchIn,onChange:S=>Ct({...ke,lunchIn:S.target.value})})]}),e.jsxs("label",{children:["Manual Status",e.jsx("select",{value:ke.status,onChange:S=>Ct({...ke,status:S.target.value}),children:Object.entries(fh).map(([S,ye])=>e.jsx("option",{value:S,children:ye},S))})]}),(()=>{const S=c.find(Wn=>Wn.id===ke.employeeId),ye=S?Gi(S,ke.attendanceDate):no(ke.branchId),Fe=yh(ke.employeeId,ye,F),lt=bi(ke.checkIn,ke.checkOut),Ot=bi(ke.lunchOut,ke.lunchIn),Ft=Fe.enabled?Fe.autoDeduct?Fe.standardMinutes:Ot||0:0,rn=lt!==void 0?Math.max(0,lt-Ft):void 0;if(lt===void 0||!ye)return null;const Rn=rn!==void 0&&rn<ye.minimumFullDayMinutes&&rn>=ye.minimumHalfDayMinutes?"Half Day":rn!==void 0&&rn<ye.minimumHalfDayMinutes?"Below Half-Day Threshold":"Full Day",ea=Wn=>`${Math.floor(Wn/60)}h ${Wn%60}m`;return e.jsxs("div",{className:"attendance-calculation-note span-2",children:[e.jsx("strong",{children:"Attendance Calculation"}
4043),e.jsxs("span",{children:["Gross ",ea(lt)," â Lunch ",ea(Ft)," = ","Work ",ea(rn||0)," · ",Rn]}),e.jsxs("small",{children:["Full-day minimum: ",ea(ye.minimumFullDayMinutes),".",Fe.autoDeduct?` Fixed standard lunch (${Fe.standardMinutes} min) is used even when Lunch Out/In are farther apart.`:" Actual Lunch Out/In duration is deducted."]})]})})(),e.jsxs("label",{children:["Adjustment Reason",e.jsx("input",{value:ke.adjustmentReason,onChange:S=>Ct({...ke,adjustmentReason:S.target.value}),placeholder:"Why is this being added/edited?"})]}),e.jsxs("label",{className:"span-2",children:["Remarks",e.jsx("textarea",{rows:3,value:ke.remarks,onChange:S=>Ct({...ke,remarks:S.target.value})})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"vx-button vx-button-secondary",disabled:sn,onClick:()=>Gt(!1),children:"Cancel"}),e.jsxs("button",{className:"vx-button vx-button-primary",disabled:sn,onClick:()=>void Xo(),children:[e.jsx(Ms,{size:17}),sn?"Savingâ¦":"Save Attendance"]})]})]})})]})}const z_=(t,n)=>{const a=[],s=new Date(`${t}T00:00:00`),i=new Date(`${n}T00:00:00`);if(Number.isNaN(s.getTime())||Number.isNaN(i.getTime())||i<s)return a;const c=new Date(s);for(;c<=i;)a.push(c.toISOString().slice(0,10)),c.setDate(c.getDate()+1);return a};function vU(t,n,a){let s=[],i=[],c=[],l="paid";const m=()=>{const p=new Map;s.forEach(y=>{p.set(`${y.employeeId}_${y.attendanceDate}`,y)}),i.filter(y=>y.approvalStatus==="approved"&&!!y.employeeId&&!!y.fromDate&&!!y.toDate).forEach(y=>{z_(String(y.fromDate),String(y.toDate)).forEach(b=>{p.set(`${y.employeeId}_${b}`,{employeeId:String(y.employeeId),attendanceDate:b,status:(()=>{const N=y.paid!==!1,w=y.durationType==="half_day"?l==="paid"?!0:l==="unpaid"?!1:N:N;return y.durationType==="half_day"?w?"leave_paid_half":"leave_unpaid_half":w?"leave_paid":"leave_unpaid"})()})})}),c.filter(y=>y.status==="active"&&!!y.employeeId&&!!y.fromDate&&!!y.toDate).forEach(y=>{z_(String(y.fromDate),String(y.toDate)).forEach(b=>{p.set(`${y.employeeId}_${b}`,{employeeId:String(y.employeeId),attendanceDate:b,status:"official_day_off"})})}),n(Array.from(p.values()).sort((y,b)=>`${y.attendanceDate}_${y.employeeId}`.localeCompare(`${b.attendanceDate}_${b.employeeId}`)))},d=qt(re(ie,`attendanceDaily/${t}`),p=>{if(!p.exists()){s=[],m();return}const y=p.val(),b=[];Object.entries(y).forEach(([N,w])=>{Object.entries(w||{}).forEach(([C,R])=>{const I=R||{};b.push({employeeId:String(I.employeeId||C),attendanceDate:String(I.attendanceDate||N),status:String(I.status||"")})})}),s=b,m()}),u=qt(re(ie,`leaveRequests/${t}`),p=>{if(!p.exists()){i=[],a==null||a([]),m();return}const y=p.val();i=Object.values(y||{}),a==null||a(i),m()}),f=qt(re(ie,`officialDayOffs/${t}`),p=>{if(!p.exists()){c=[],m();return}const y=p.val();c=Object.values(y||{}),m()}),g=qt(re(ie,`leaveSettings/${t}`),p=>{var b;const y=p.exists()?String(((b=p.val())==null?void 0:b.halfDayPaymentRule)||"paid"):"paid";l=y==="unpaid"||y==="leave_type"?y:"paid",m()},()=>{l="paid",m()});return()=>{d(),u(),f(),g()}}const Vv=()=>new Date().toISOString().slice(0,10),Tf=()=>new Date().toISOString().slice(0,7),vi=t=>`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`;function bU({profile:t,branches:n,selectedBranchId:a,employees:s}){const[i,c]=x.useState([]),[l,m]=x.useState([]),[d,u]=x.useState({}),[f,g]=x.useState(!1),[p,y]=x.useState(!1),[b,N]=x.useState(""),[w,C]=x.useState(""),[R,I]=x.useState("advance"),[_,J]=x.useState(""),[T,G]=x.useState(Vv()),[z,H]=x.useState("cash"),[K,L]=x.useState(""),[D,M]=x.useState("one_time"),[Z,fe]=x.useState(Tf()),[q,ne]=x.useState(1),[ae,Y]=x.useState(""),[je,V]=x.useState(null),[$,F]=x.useState(""),[P,ue]=x.useState(null),[me,ge]=x.useState(""),[de,Pe]=x.useState("one_time"),[Re,Ee]=x.useState(Tf()),[Be,We]=x.useState(1),[it,_e]=x.useState(null),[ee,qe]=x.useState("cash"),[se,pe]=x.useState(Vv()),Se=sa(t,"payroll.manage"),Me=sa(t,"finance.manage"),ot=["super_admin","owner","admin","hr"].includes(t.role);x.useEffect(()=>qt(re(ie,`employeeAdvanceLoans/${t.companyId}`),B=>{if(!B.exists()){c([]);return}const xe=B.val();c(Object.entries(xe).map(([tt,ht])=>({id:tt,...ht})).sort((tt,ht)=>ht.createdAt-tt.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`employeeAdvanceLoanRequests/${t.companyId}`),B=>{if(!B.exists()){m([]);return}const xe=B.val();m(Object.entries(xe).map(([tt,ht])=>({id:tt,...ht})).sort((tt,ht)=>ht.createdAt-tt.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`payrollItems/${t.companyId}`),B=>{u(B.exists()?B.val():{})}),[t.companyId]);const wt=x.useMemo(()=>
4043s.filter(B=>B.active!==!1&&(a==="all"||B.branchId===a)),[s,a]),ct=x.useMemo(()=>{const B={};return Object.values(d||{}).forEach(xe=>{Object.values(xe||{}).forEach(tt=>{tt.status==="locked"&&(tt.advanceLoanRecoveryBreakdown||[]).forEach(ht=>{B[ht.recordId]=(B[ht.recordId]||0)+Math.max(0,Number(ht.amount||0))})})}),B},[d]),Ce=x.useMemo(()=>{const B={};return Object.values(d||{}).forEach(xe=>{Object.values(xe||{}).forEach(tt=>{tt.status!=="locked"||tt.paymentStatus!=="paid"||(tt.advanceLoanRecoveryBreakdown||[]).forEach(ht=>{B[ht.recordId]=(B[ht.recordId]||0)+Math.max(0,Number(ht.amount||0))})})}),B},[d]),De=x.useMemo(()=>i.filter(B=>a==="all"||B.branchId===a),[i,a]),Te=x.useMemo(()=>l.filter(B=>B.status==="pending"&&(a==="all"||B.branchId===a)),[l,a]),ce=x.useMemo(()=>l.filter(B=>B.status==="manager_approved"&&(a==="all"||B.branchId===a)),[l,a]),Ye=x.useMemo(()=>De.filter(B=>B.status==="approved"),[De]),Je=De.filter(B=>B.status!=="cancelled"&&B.status!=="approved"),le=Je.reduce((B,xe)=>B+Math.max(Number(xe.amount||0)-Number(Ce[xe.id]||0),0),0);Je.filter(B=>B.type==="advance").reduce((B,xe)=>B+Math.max(xe.amount-Number(Ce[xe.id]||0),0),0),Je.filter(B=>B.type==="loan").reduce((B,xe)=>B+Math.max(xe.amount-Number(Ce[xe.id]||0),0),0);const nt=B=>{!ot||B.status!=="manager_approved"||(ue(B),ge(String(B.requestedAmount)),Pe("one_time"),Ee(Tf()),We(1))},xt=async()=>{const B=P;if(!B||!ot||B.status!=="manager_approved")return;const xe=Math.max(0,Number(me||0));if(!xe||xe>B.requestedAmount){N("Approved amount must be greater than zero and cannot exceed the requested amount.");return}if(!Re){N("Recover From Salary Month is required.");return}const tt=de==="monthly"?Math.max(1,Math.floor(Be||1)):1,ht=Ta(re(ie,`employeeAdvanceLoans/${t.companyId}`));if(!ht.key){N("Advance/Loan record ID could not be generated.");return}const dt=Date.now();y(!0);try{await Pn(ht,{employeeId:B.employeeId,employeeCode:B.employeeCode||"",employeeName:B.employeeName,branchId:B.branchId||"",type:B.type,amount:xe,issueDate:"",paymentMethod:"cash",reference:`REQ-${B.id}`,recoveryMode:de,recoverFromSalaryMonth:Re,recoveryStartMonth:Re,installmentCount:tt,installmentAmount:de==="monthly"?xe/tt:xe,remarks:`Employee request ${B.id}`,status:"approved",createdAt:dt,createdByUid:t.uid,createdByName:t.name,sourceRequestId:B.id,approvedAt:dt,approvedByUid:t.uid,approvedByName:t.name}),await yn(re(ie,`employeeAdvanceLoanRequests/${t.companyId}/${B.id}`),{status:"approved",approvedAmount:xe,approvedAt:dt,approvedByUid:t.uid,approvedByName:t.name,recoveryMode:de,recoverFromSalaryMonth:Re,recoveryStartMonth:Re,installmentCount:tt,recoveryPlanFinalized:!0,advanceLoanRecordId:ht.key}),await ia({companyId:t.companyId,branchId:B.branchId,actorUid:t.uid,actorName:t.name,action:"advance_loan.recovery_plan_finalized",entityType:"employeeAdvanceLoanRequest",entityId:B.id,summary:`${B.employeeName} ${B.type} finalized for ${vi(xe)}; ${de==="monthly"?`${tt} monthly installments`:"one-time"} from ${Re}.`}),ue(null),N("Recovery plan finalized. The request is now Pending Disbursement.")}catch(we){N(`Recovery plan could not be finalized: ${we instanceof Error?we.message:String(we)}`)}finally{y(!1)}},te=()=>{C(""),I("advance"),J(""),G(Vv()),H("cash"),L(""),M("one_time"),fe(Tf()),ne(1),Y("")},Ge=B=>B.toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"VRX",pt=async B=>{const xe=await mn(re(ie,`accountingAccounts/${t.companyId}`));if(!xe.exists())throw new Error("Accounts & Finance Chart of Accounts is not initialized yet.");const tt=Object.entries(xe.val()).map(([we,rt])=>({id:we,...rt})),ht=B==="advance"?"employee_salary_advance_receivable":"employee_loan_receivable";let dt=tt.find(we=>we.systemKey===ht&&we.active!==!1&&!we.isGroup);if(!dt){const we=tt.find(Qt=>Qt.code==="1400")||tt.find(Qt=>Qt.code==="1000"),rt=B==="advance"?"acct_1410":"acct_1420",St={code:B==="advance"?"1410":"1420",name:B==="advance"?"Employee Salary Advance Receivable":"Employee Loan Receivable",type:"asset",parentId:(we==null?void 0:we.id)||"acct_1000",isGroup:!1,normalBalance:"debit",systemKey:ht,active:!0,createdAt:Date.now(),updatedAt:Date.now()};await Pn(re(ie,`accountingAccounts/${t.companyId}/${rt}`),St),dt={id:rt,...St}}return dt},$e=async B=>{if(!Me)throw new Error("Accounts & Finance manage permission is required to issue and post an employee Advance/Loan.");const xe=await mn(re(ie,`accountingSettings/${t.companyId}`)),ht=((xe.exists()?xe.val():{}).lockedThrough||"").trim();if(ht&&B.issueDate.slice(0,7)<=ht)throw new Error(`Accounting period ${B.issueDate.slice(0,7)} is locked.`);const dt=await pt(B.kind),we=await mn(re(ie,`accountingAccounts/${t.companyId}`)),St=Object.entries(we.val()).map(([Rt,xn])=>({id:Rt,...xn})).find(Rt=>Rt.systemKey===B.paymentMethod&&Rt.active!==!1&&!Rt.isGroup);if(!St)throw new Error(B.paymentMethod==="cash"?"Cash in Hand account is missing.":"Bank Account is missing.");const Qt=n.find(Rt=>Rt.id===B.employee.branchId),gn=Ge((Qt==null?void 0:Qt.code)||"VRX"),An=new Date(`${B.issueDate}T00:00:00`).getFullYear(),Sn=`${gn}-PV-${An}`,Xt=await Ep(re(ie,`accountingVoucherCounters/${t.companyId}/${Sn}`),Rt=>({lastNumber:Number((Rt==null?void 0:Rt.lastNumber)||0)+1,branchCode:gn,prefix:"PV",year:An,updatedAt:Date.now()}));if(!Xt.committed)throw new Error("Payment Voucher number could not be generated.");const Wt=`${gn}-PV-${An}
4043-${String(Number(Xt.snapshot.val().lastNumber||0)).padStart(6,"0")}`,Gt=Ta(re(ie,`accountingVouchers/${t.companyId}`)).key;if(!Gt)throw new Error("Payment Voucher ID could not be created.");const $t=Date.now(),Vt=B.kind==="advance"?"Salary Advance":"Employee Loan",sn=`${B.employee.name}${B.employee.employeeId?` (${B.employee.employeeId})`:""}`,on=B.reference.trim()||`${Vt} · ${sn}`,ke=`${Vt} issued to ${sn}`,Ct=[{id:"line_001",accountId:dt.id,accountCode:dt.code,accountName:dt.name,debit:B.amount,credit:0,narration:ke},{id:"line_002",accountId:St.id,accountCode:St.code,accountName:St.name,debit:0,credit:B.amount,narration:ke}],Et={[`accountingVouchers/${t.companyId}/${Gt}`]:{voucherNo:Wt,type:"payment",status:"posted",voucherDate:B.issueDate,branchId:B.employee.branchId||"",reference:on,narration:ke,lines:Ct,totalDebit:B.amount,totalCredit:B.amount,createdAt:$t,createdByUid:t.uid,createdByName:t.name||t.email||"User",updatedAt:$t,postedAt:$t,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"employee_advance_loan",sourceId:B.recordId},[`employeeAdvanceLoans/${t.companyId}/${B.recordId}/accountingVoucherId`]:Gt,[`employeeAdvanceLoans/${t.companyId}/${B.recordId}/accountingVoucherNo`]:Wt,[`employeeAdvanceLoans/${t.companyId}/${B.recordId}/accountingStatus`]:"posted"};return Ct.forEach((Rt,xn)=>{const dn=`${Gt}_${String(xn+1).padStart(3,"0")}`;Et[`accountingLedgerEntries/${t.companyId}/${dn}`]={id:dn,voucherId:Gt,voucherNo:Wt,voucherType:"payment",voucherDate:B.issueDate,branchId:B.employee.branchId||"",reference:on,narration:Rt.narration,accountId:Rt.accountId,accountCode:Rt.accountCode,accountName:Rt.accountName,debit:Rt.debit,credit:Rt.credit,status:"posted",createdAt:$t,postedByUid:t.uid,postedByName:t.name||t.email||"User",sourceType:"employee_advance_loan",sourceId:B.recordId}}),await yn(re(ie),Et),{voucherId:Gt,voucherNo:Wt}},st=async()=>{if(!Se){N("You do not have permission to manage employee Advance/Loan.");return}if(!Me){N("Advance/Loan issue requires Accounts & Finance manage permission because the payment is posted automatically.");return}if(z==="other"){N("Select Cash or Bank so the payment can be posted to Accounts automatically.");return}const B=s.find(dt=>dt.id===w),xe=Math.max(0,Number(_||0)),tt=D==="monthly"?Math.max(1,Math.floor(Number(q||1))):1;if(!B||xe<=0||!T||!Z){N("Employee, amount, issue date and recovery start month are required.");return}y(!0),N("");let ht="";try{const dt=Ta(re(ie,`employeeAdvanceLoans/${t.companyId}`)),we=dt.key;if(!we)throw new Error("Could not create Advance/Loan ID.");ht=we;const rt={id:we,employeeId:B.id,employeeCode:B.employeeId||"",employeeName:B.name,branchId:B.branchId||"",type:R,amount:xe,issueDate:T,paymentMethod:z,reference:K.trim(),recoveryMode:D,recoverFromSalaryMonth:Z,recoveryStartMonth:Z,installmentCount:tt,installmentAmount:D==="monthly"?xe/tt:xe,remarks:ae.trim(),status:"active",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name},{id:St,...Qt}=rt;await Pn(dt,Qt);const gn=await $e({recordId:we,employee:B,kind:R,amount:xe,issueDate:T,paymentMethod:z,reference:K.trim()});await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.advance_loan_created",entityType:"employeeAdvanceLoan",entityId:we,summary:`${R==="advance"?"Advance":"Loan"} BDT ${xe} issued to ${B.name}`,metadata:{employeeId:B.id,recoveryMode:D,recoverFromSalaryMonth:Z,installmentCount:tt,accountingVoucherNo:gn.voucherNo}}),te(),g(!1),N(`${R==="advance"?"Advance":"Loan"} saved and ${gn.voucherNo} posted. ${z==="cash"?"Cash in Hand":"Bank"} was credited automatically; payroll recovery will follow the selected ${D==="one_time"?"one-time":"monthly installment"} plan.`)}catch(dt){if(console.error(dt),ht)try{(await mn(re(ie,`employeeAdvanceLoans/${t.companyId}/${ht}/accountingVoucherId`))).exists()||await Ao(re(ie,`employeeAdvanceLoans/${t.companyId}/${ht}`))}catch(we){console.error("Advance/Loan rollback failed",we)}N(`Advance/Loan could not be saved: ${dt instanceof Error?dt.message:String(dt)}`)}finally{y(!1)}},Nt=B=>{if(!Se||!Me||B.status!=="approved")return;if(!s.find(tt=>tt.id===B.employeeId)){N("Employee record not found.");return}_e(B),qe("cash"),pe(Vv())},be=async()=>{const B=it;if(!B||!Se||!Me||B.status!=="approved")return;const xe=s.find(tt=>tt.id===B.employeeId);if(!xe){N("Employee record not found.");return}if(!se){N("Disbursement date is required.");return}y(!0);try{const tt=await $e({recordId:B.id,employee:xe,kind:B.type,amount:B.amount,issueDate:se,paymentMethod:ee,reference:B.reference||`ADVLOAN-${B.id}`});await yn(re(ie,`employeeAdvanceLoans/${t.companyId}/${B.id}`),{status:"active",issueDate:se,paymentMethod:ee,accountingVoucherId:tt.voucherId,accountingVoucherNo:tt.voucherNo,accountingStatus:"posted"}),B.sourceRequestId&&await yn(re(ie,`employeeAdvanceLoanRequests/${t.companyId}/${B.sourceRequestId}
4043`),{status:"disbursed",disbursedAt:Date.now(),disbursedByUid:t.uid,disbursedByName:t.name,accountingVoucherNo:tt.voucherNo}),await ia({companyId:t.companyId,branchId:B.branchId,actorUid:t.uid,actorName:t.name,action:"advance_loan.disbursed",entityType:"employeeAdvanceLoan",entityId:B.id,summary:`${B.employeeName} ${B.type} disbursed: ${vi(B.amount)} via ${ee}.`}),_e(null),N(`${tt.voucherNo} posted. Advance/Loan is now Active for payroll recovery.`)}catch(tt){N(`Disbursement failed: ${tt instanceof Error?tt.message:String(tt)}`)}finally{y(!1)}},jt=B=>{if(Number(ct[B.id]||0)>0){N("Recovery Salary Month cannot be changed after a locked payroll has already allocated an amount.");return}V(B),F(B.recoverFromSalaryMonth||B.recoveryStartMonth||Tf())},bt=async()=>{if(!(!je||!$)){y(!0);try{await yn(re(ie,`employeeAdvanceLoans/${t.companyId}/${je.id}`),{recoverFromSalaryMonth:$,recoveryStartMonth:$}),V(null),N(`Recovery will start from ${$} Salary payroll.`)}catch(B){N(`Recovery Salary Month could not be updated: ${B instanceof Error?B.message:String(B)}`)}finally{y(!1)}}},tn=async B=>{if(!Se||B.status!=="active")return;const xe=Number(ct[B.id]||0),tt=Number(Ce[B.id]||0);window.confirm(`Cancel this ${B.type}? Allocated: ${vi(xe)} · Recovered: ${vi(tt)}. Historical payroll allocation/recovery will remain unchanged.`)&&(await yn(re(ie,`employeeAdvanceLoans/${t.companyId}/${B.id}`),{status:"cancelled",cancelledAt:Date.now(),cancelledByUid:t.uid,cancelledByName:t.name}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.advance_loan_cancelled",entityType:"employeeAdvanceLoan",entityId:B.id,summary:`Cancelled ${B.type} for ${B.employeeName}`}))};return e.jsxs("section",{className:"employee-advance-loan",children:[e.jsxs("div",{className:"eal-head",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Employee Advance & Loan"}),e.jsx("p",{children:"Issue employee advances/loans and recover them once or through monthly payroll installments."})]}),Se&&e.jsxs("button",{onClick:()=>g(!0),children:[e.jsx(as,{size:16})," Direct Advance / Loan"]})]}),b&&e.jsx("div",{className:"eal-message",children:b}),e.jsxs("div",{className:"eal-workflow-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Pending Approval"}),e.jsx("strong",{children:Te.length}),e.jsx("small",{children:"Waiting for Reporting Manager"})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Recovery Plan Pending"}),e.jsx("strong",{children:ce.length}),e.jsx("small",{children:"Manager approved; waiting for HR/Admin finalization"})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Pending Disbursement"}),e.jsx("strong",{children:Ye.length}),e.jsx("small",{children:"Approved, payment not issued yet"})]})]}),e.jsxs("div",{className:"eal-pending-grid",children:[e.jsxs("section",{className:"eal-pending-card",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Pending Approval"}),e.jsx("p",{children:"Employee requests waiting for Reporting Manager approval."})]}),e.jsx("span",{children:Te.length})]}),e.jsx("div",{className:"eal-mini-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"REQUESTED"}),e.jsx("th",{children:"RECOVERY"}),e.jsx("th",{children:"REPORTING MANAGER"})]})}),e.jsx("tbody",{children:Te.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"empty",children:"No pending approval."})}):Te.map(B=>{var xe;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:B.employeeName}),e.jsxs("small",{children:[B.employeeCode||"â"," · ",((xe=n.find(tt=>tt.id===B.branchId))==null?void 0:xe.name)||"Branch"]})]}),e.jsx("td",{children:e.jsx("span",{className:`eal-type ${B.type}`,children:B.type==="advance"?"Advance":"Loan"})}),e.jsx("td",{children:e.jsx("strong",{children:vi(B.requestedAmount)})}),e.jsxs("td",{children:[B.recoveryMode==="one_time"?"One Time":`${B.installmentCount} installments`,e.jsxs("small",{children:["From ",B.recoverFromSalaryMonth||B.recoveryStartMonth]})]}),e.jsx("td",{children:B.managerName||"â"})]},B.id)})})]})})]}),e.jsxs("section",{className:"eal-pending-card",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Recovery Plan Pending"}),e.jsx("p",{children:"Reporting Manager approved. HR/Admin/Owner/Super Admin must finalize the recovery plan."})]}),e.jsx("span",{children:ce.length})]}),e.jsx("div",{className:"eal-mini-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"REQUESTED"}),e.jsx("th",{children:"REPORTING MANAGER"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:ce.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"empty",children:"No recovery plan pending."})}):ce.map(B=>{var xe;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:B.employeeName}),e.jsxs("small",{children:[B.employeeCode||"â"," · ",((xe=n.find(tt=>tt.id===B.branchId))==null?void 0:xe.name)||"Branch"]})]}),e.jsx("td",{children:e.jsx("span",{className:`eal-type ${B.type}`,children:B.type==="advance"?"Advance":"Loan"})}),e.jsx("td",{children:e.jsx("strong",{children:vi(B.requestedAmount)})}),e.jsx("td",{children:B.managerName||B.managerApprovedByName||"â"}),e.jsx("td",{children:ot?e.jsxs("button",{disabled:p,onClick:()=>nt(B),children:[e.jsx(Eh,{size:14})," Set Recovery Plan"]}):e.jsx("span",{children:"Waiting for HR/Admin"})})]},B.id)})})]})})]}),e.jsxs("section",{className:"eal-pending-card",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Pending Disbursement"}),e.jsx("p",{children:"Approved requests waiting for Cash/Bank payment."})]}),e.jsx("span",{children:Ye.length})]}),e.jsx("div",{className:"eal-mini-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"APPROVED"}),e.jsx("th",{children:"RECOVERY"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:Ye.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"empty",children:"No pending disbur
4043sement."})}):Ye.map(B=>{var xe;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:B.employeeName}),e.jsxs("small",{children:[B.employeeCode||"â"," · ",((xe=n.find(tt=>tt.id===B.branchId))==null?void 0:xe.name)||"Branch"]})]}),e.jsx("td",{children:e.jsx("span",{className:`eal-type ${B.type}`,children:B.type==="advance"?"Advance":"Loan"})}),e.jsx("td",{children:e.jsx("strong",{children:vi(B.amount)})}),e.jsxs("td",{children:[B.recoveryMode==="one_time"?"One Time":`${B.installmentCount} installments`,e.jsxs("small",{children:["From ",B.recoverFromSalaryMonth||B.recoveryStartMonth]})]}),e.jsx("td",{children:Se&&Me?e.jsx("button",{className:"eal-disburse",onClick:()=>Nt(B),children:"Disburse"}):e.jsx("span",{children:"â"})})]},B.id)})})]})})]})]}),e.jsxs("div",{className:"eal-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Outstanding Total"}),e.jsx("strong",{children:vi(le)})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Allocated in Payroll"}),e.jsx("strong",{children:vi(De.reduce((B,xe)=>B+Math.max(Number(ct[xe.id]||0)-Number(Ce[xe.id]||0),0),0))})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Recovered"}),e.jsx("strong",{children:vi(De.reduce((B,xe)=>B+Math.min(xe.amount,Number(Ce[xe.id]||0)),0))})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Active Records"}),e.jsx("strong",{children:De.filter(B=>Math.max(B.amount-Number(Ce[B.id]||0),0)>.004&&B.status!=="cancelled"&&B.status!=="approved").length})]})]}),e.jsx("div",{className:"eal-table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"ISSUED"}),e.jsx("th",{children:"RECOVERY PLAN"}),e.jsx("th",{children:"ALLOCATED"}),e.jsx("th",{children:"RECOVERED"}),e.jsx("th",{children:"OUTSTANDING"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:De.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"empty",children:"No employee Advance/Loan entry found."})}):De.map(B=>{var rt;const xe=Math.min(B.amount,Number(ct[B.id]||0)),tt=Math.min(B.amount,Number(Ce[B.id]||0)),ht=Math.max(xe-tt,0),dt=Math.max(B.amount-tt,0),we=dt<.005;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:B.employeeName}),e.jsxs("small",{children:[B.employeeCode||"â"," · ",((rt=n.find(St=>St.id===B.branchId))==null?void 0:rt.name)||"Branch"]})]}),e.jsx("td",{children:e.jsx("span",{className:`eal-type ${B.type}`,children:B.type==="advance"?"Advance":"Loan"})}),e.jsxs("td",{children:[e.jsx("strong",{children:vi(B.amount)}),e.jsxs("small",{children:[B.issueDate," · ",B.paymentMethod,B.accountingVoucherNo?` · ${B.accountingVoucherNo}`:""]})]}),e.jsx("td",{children:B.recoveryMode==="one_time"?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"One Time"}),e.jsx("small",{children:B.recoverFromSalaryMonth||B.recoveryStartMonth})]}):e.jsxs(e.Fragment,{children:[e.jsxs("strong",{children:[B.installmentCount," Monthly Installments"]}),e.jsxs("small",{children:[vi(B.installmentAmount)," / month · from ",B.recoverFromSalaryMonth||B.recoveryStartMonth]})]})}),e.jsxs("td",{children:[e.jsx("strong",{children:vi(xe)}),ht>.004&&e.jsxs("small",{children:[vi(ht)," awaiting salary payment"]})]}),e.jsx("td",{children:vi(tt)}),e.jsx("td",{children:e.jsx("strong",{children:vi(dt)})}),e.jsx("td",{children:e.jsx("span",{className:`eal-status ${we?"completed":ht>.004?"allocated":B.status}`,children:we?"Completed":B.status==="approved"?"Pending Disbursement":B.status==="cancelled"?"Cancelled":ht>.004?"Adjusted in Payroll â Awaiting Salary Payment":"Active"})}),e.jsx("td",{children:B.status==="approved"&&Se&&Me?e.jsx("button",{className:"eal-disburse",onClick:()=>Nt(B),children:"Disburse"}):B.status==="active"&&!we&&Se?e.jsxs("div",{className:"eal-row-actions",children:[e.jsx("button",{className:"eal-edit-recovery",onClick:()=>jt(B),children:"Edit Recovery"}),e.jsx("button",{className:"eal-cancel",onClick:()=>tn(B),children:"Cancel"})]}):e.jsx("span",{children:"â"})})]},B.id)})})]})}),je&&e.jsx("div",{className:"eal-modal-bg",onMouseDown:B=>{B.currentTarget===B.target&&V(null)},children:e.jsxs("div",{className:"eal-recovery-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"RECOVERY SCHEDULE"}),e.jsx("h3",{children:"Edit Recovery Salary Month"})]}),e.jsx("button",{onClick:()=>V(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"eal-recovery-body",children:[e.jsxs("p",{children:[e.jsx("strong",{children:je.employeeName})," · ",je.type==="advance"?"Advance":"Loan"," · ",vi(je.amount)]}),e.jsxs("label",{children:["Recover From Salary Month",e.jsx("input",{type:"month",value:$,onChange:B=>F(B.target.value)})]}),e.jsx("small",{children:"This controls which payroll salary month receives the deduction. It is independent of the actual salary payment date."})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"eal-secondary",onClick:()=>V(null),children:"Cancel"}),e.jsxs("button",{className:"eal-primary",disabled:p,onClick:bt,children:[e.jsx(hr,{size:16}),"Save Recovery Month"]})]})]})}),it&&e.jsx("div",{className:"eal-modal-bg",onMouseDown:B=>{B.target===B.currentTarget&&_e(null)},children:e.jsxs("div",{className:"eal-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{children:"DISBURSEMENT"}),e.jsx("h3",{children:"Record Advance / Loan Payment"}),e.jsxs("span",{children:[it.employeeName," · ",it.type==="advance"?"Advance":"Loan"," · ",vi(it.amount)]})]}),e.jsx("button",{onClick:()=>_e(null),children:e.jsx(ja,{size:18})})]}),e.jsxs("div",{className:"eal-form",children:[e.jsxs("label",{children:["Payment Method",e.jsxs("select",{value:ee,onChange:B=>qe(B.target.value),children:[e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bank",children:"Bank"})]})]}),e.jsxs("label",{children:["Disbursement Date",e.jsx("input",{type:"date",value:se,onChange:B=>pe(B.target.value)})]}),e.jsx("div",{className:"wide manager",children:"This will post the accounting payment voucher and activate payroll recovery."})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"secondary",onClick:()=>_e(null),children:"Cancel"}),e.jsxs("button",{disabled:p||!se,onClick:be,children:[e.jsx(Eh,{size:16}),p?"Posting...":"Confirm Disbursement"]})]})]})}),P&&e.jsx("div",{className:"eal-modal-bg",onMouseDown:B=>{B.target===B.currentTarget&&ue(null)},children:e.jsxs("div",{className:"eal-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Finalize Recovery Plan"}),e.jsxs("p",{children:[P.employeeName," · ",P.type==="advance"?"Advance":"Loan"," · Requested ",vi(P.requestedAmount)]})]}),e.jsx("button",{onClick:()=>ue(null),children:e.jsx(ja,{size:18})})]}),e.jsxs("div",{className:"eal-form",children:[e.jsxs("label",{children:["Approved Amount",e.jsx("input",{type:"number",min:"0",max:P.requestedAmount,value:me,onChange:B=>ge(B.target.value)})]}),e.jsxs("label",{children:["Recovery Method",e.jsxs("select",{value:de,onChange:B=>Pe(B.target.value),children:[e.jsx("option",{value:"one_time",children:"One Time"}),e.jsx("option",{value:"monthly",children:"Monthly Installment"})]})]}),e.jsxs("label",{children:["Recover From Salary Month",e.jsx("input",{type:"month",value:Re,onChange:B=>Ee(B.target.value)})]}),de==="monthly"&&e.jsxs("label",{children:["Number of Installments",e.jsx("input",{type:"number",min:"1",value:
4043Be,onChange:B=>We(Math.max(1,Number(B.target.value||1)))})]})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"secondary",onClick:()=>ue(null),children:"Cancel"}),e.jsxs("button",{disabled:p,onClick:xt,children:[e.jsx(Eh,{size:16}),p?"Saving...":"Finalize & Send to Disbursement"]})]})]})}),f&&e.jsx("div",{className:"eal-modal-bg",onMouseDown:B=>{B.currentTarget===B.target&&g(!1)},children:e.jsxs("div",{className:"eal-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"PAYROLL RECOVERY"}),e.jsx("h3",{children:"New Employee Advance / Loan"})]}),e.jsx("button",{onClick:()=>g(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"eal-form",children:[e.jsxs("label",{children:["Employee",e.jsxs("select",{value:w,onChange:B=>C(B.target.value),children:[e.jsx("option",{value:"",children:"Select employee"}),wt.map(B=>e.jsxs("option",{value:B.id,children:[B.employeeId?`${B.employeeId} · `:"",B.name]},B.id))]})]}),e.jsxs("label",{children:["Type",e.jsxs("select",{value:R,onChange:B=>I(B.target.value),children:[e.jsx("option",{value:"advance",children:"Advance"}),e.jsx("option",{value:"loan",children:"Loan"})]})]}),e.jsxs("label",{children:["Amount",e.jsx("input",{type:"number",min:"0",inputMode:"decimal",value:_,onChange:B=>J(B.target.value),placeholder:"0.00"})]}),e.jsxs("label",{children:["Issue Date",e.jsx("input",{type:"date",value:T,onChange:B=>G(B.target.value)})]}),e.jsxs("label",{children:["Paid Through",e.jsxs("select",{value:z,onChange:B=>H(B.target.value),children:[e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bank",children:"Bank"})]})]}),e.jsxs("label",{children:["Reference",e.jsx("input",{value:K,onChange:B=>L(B.target.value),placeholder:"Cheque / transfer / reference"})]}),e.jsxs("label",{children:["Recovery Method",e.jsxs("select",{value:D,onChange:B=>M(B.target.value),children:[e.jsx("option",{value:"one_time",children:"One Time"}),e.jsx("option",{value:"monthly",children:"Monthly Installment"})]})]}),e.jsxs("label",{children:["Recover From Salary Month",e.jsx("input",{type:"month",value:Z,onChange:B=>fe(B.target.value)}),e.jsx("small",{children:"Recovery follows this salary month, even if salary is paid in the next calendar month."})]}),D==="monthly"&&e.jsxs("label",{children:["Number of Installments",e.jsx("input",{type:"number",min:"1",step:"1",value:q,onChange:B=>ne(Math.max(1,Number(B.target.value||1)))}),e.jsxs("small",{children:["Approx. ",vi(Number(_||0)/Math.max(1,q))," per month"]})]}),e.jsxs("label",{className:"eal-remarks",children:["Remarks",e.jsx("textarea",{value:ae,onChange:B=>Y(B.target.value),placeholder:"Optional note"})]})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"eal-secondary",onClick:()=>g(!1),children:"Cancel"}),e.jsxs("button",{className:"eal-primary",disabled:p,onClick:st,children:[e.jsx(hr,{size:16}),p?"Saving...":"Save Advance / Loan"]})]})]})})]})}const q_={latePerDay:3,deductHalfDay:!1,halfDayDeductionRate:.5,salaryDivisor:"calendar_days",overtimeEnabled:!1,overtimeRate:150,roundNetPay:!1,statutoryEnabled:!1,taxEnabled:!1,taxCountry:"BD",taxEngineMode:"reference_only",taxRuleVersionId:"",pfEnabled:!1,pfEmployeeRate:0,pfEmployerRate:0,pfBasis:"basic",pfEligibilityRule:"after_one_year"},pn=t=>new Intl.NumberFormat("en-BD",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t||0),V_=t=>{const[n,a]=t.split("-").map(Number);return new Date(n,a,0).getDate()},xU=(t,n)=>{const[a,s,i]=t.split("-").map(Number);if(!a||!s||!i)return"";const c=new Date(a+n,s-1,i);return c.getMonth()!==s-1&&c.setDate(0),[c.getFullYear(),String(c.getMonth()+1).padStart(2,"0"),String(c.getDate()).padStart(2,"0")].join("-")},Hv=t=>{const[n,a]=t.split("-").map(Number);if(!n||!a)return"";const s=new Date(n,a,0);return[s.getFullYear(),String(s.getMonth()+1).padStart(2,"0"),String(s.getDate()).padStart(2,"0")].join("-")},jU=()=>({overtimeHours:0,festivalBonus:0,performanceBonus:0,incentive:0,otherAddition:0,advanceDeduction:0,loanDeduction:0,fineDeduction:0,otherDeduction:0,remarks:""});function wU({profile:t,branches:n,selectedBranchId:a}){var an,Cn,Qn;const s=new Date().toISOString().slice(0,7),[i,c]=x.useState("dashboard"),[l,m]=x.useState(s),[d,u]=x.useState(q_),[f,g]=x.use
4043State({}),[p,y]=x.useState(null),[b,N]=x.useState(null),[w,C]=x.useState(null),[R,I]=x.useState(!1),[_,J]=x.useState(null),[T,G]=x.useState(null),[z,H]=x.useState([]),[K,L]=x.useState([]),[D,M]=x.useState({}),[Z,fe]=x.useState({}),[q,ne]=x.useState({}),[ae,Y]=x.useState(!1),[je,V]=x.useState(!1),[$,F]=x.useState([]),[P,ue]=x.useState({}),[me,ge]=x.useState({}),[de,Pe]=x.useState([]),[Re,Ee]=x.useState({}),[Be,We]=x.useState(""),[it,_e]=x.useState({}),[ee,qe]=x.useState(""),[se,pe]=x.useState(null),[Se,Me]=x.useState(null),[ot,wt]=x.useState(null),[ct,Ce]=x.useState(null),[De,Te]=x.useState(null),[ce,Ye]=x.useState(!1),[Je,le]=x.useState(""),[nt,xt]=x.useState(null),[te,Ge]=x.useState(!0),[pt,$e]=x.useState({}),[st,Nt]=x.useState(""),[be,jt]=x.useState(!1),[bt,tn]=x.useState(null),[B,xe]=x.useState(""),[tt,ht]=x.useState(0),[dt,we]=x.useState(""),[rt,St]=x.useState(""),[Qt,gn]=x.useState([]),[An,Sn]=x.useState([]),[Xt,Wt]=x.useState("access_control_multi_punch"),[Gt,$t]=x.useState(null),[Vt,sn]=x.useState(!1),on=t.role==="super_admin",ke=E=>{const Q=z.find(Le=>Le.id===E.employeeId),Ie=Z[E.employeeId]||{};return{bankName:(Q==null?void 0:Q.bankName)||E.bankName||Ie.bankName||"",bankAccount:(Q==null?void 0:Q.bankAccount)||E.bankAccount||Ie.bankAccount||"",bankAccountHolder:Ie.bankAccountHolder||(Q==null?void 0:Q.bankAccountHolder)||E.bankAccountHolder||E.employeeName||""}},Ct=async(E="download")=>{var _a,Vs;if(!_n.length){window.alert("Generate payroll first.");return}const Q=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),Ie=Q.internal.pageSize.getWidth(),Le=Q.internal.pageSize.getHeight(),He=[10,61,98],gt=[20,39,55],Dt=[100,116,132],Yt=[245,248,251],vn=[218,226,234],zt=((_a=n.find(Hn=>Hn.id===a))==null?void 0:_a.name)||(a==="all"?"All Branches":"");let Bt=pt;try{Bt=await fc(t.companyId),$e(Bt)}catch(Hn){console.warn("Latest company branding could not be loaded:",Hn)}const En=Bt.name||"Company",wn=new Date(`${l}-01T00:00:00`).toLocaleDateString("en-US",{month:"long",year:"numeric"}),ma=new Date().toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});let ca=!1;const Pa=Bt.logoUrl||"";if(Pa.startsWith("data:image/"))try{const Hn=await new Promise((Fa,zs)=>{const Bs=new Image;Bs.onload=()=>{const S=document.createElement("canvas"),ye=Math.min(1,560/Bs.width,180/Bs.height);S.width=Math.max(1,Math.round(Bs.width*ye)),S.height=Math.max(1,Math.round(Bs.height*ye));const Fe=S.getContext("2d");if(!Fe)return zs(new Error("Canvas unavailable"));Fe.fillStyle="#ffffff",Fe.fillRect(0,0,S.width,S.height),Fe.drawImage(Bs,0,0,S.width,S.height),Fa(S.toDataURL("image/jpeg",.94))},Bs.onerror=()=>zs(new Error("Logo image could not be loaded")),Bs.src=Pa});Q.addImage(Hn,"JPEG",12,7.5,31,13,void 0,"FAST"),ca=!0}catch(Hn){console.warn("Payroll PDF logo could not be added:",Hn)}Q.setFillColor(...He),Q.rect(0,0,Ie,3.2,"F"),Q.setTextColor(...He),Q.setFont("helvetica","bold"),Q.setFontSize(16),Q.text(En,ca?47:12,13.5),Q.setFont("helvetica","normal"),Q.setFontSize(7.2),Q.setTextColor(...Dt),Q.text("HR & PAYROLL / MONTHLY MANAGEMENT REPORT",ca?47:12,18.2),Q.setTextColor(...He),Q.setFont("helvetica","bold"),Q.setFontSize(13.5),Q.text("MONTHLY PAYROLL SHEET",Ie-12,10.5,{align:"right"}),Q.setFontSize(10.2),Q.setTextColor(...gt),Q.text(wn.toUpperCase(),Ie-12,15.3,{align:"right"}),Q.setFont("helvetica","normal"),Q.setFontSize(6.8),Q.setTextColor(...Dt),Q.text(`${zt} ⢠STATUS: ${String((De==null?void 0:De.status)||"draft").toUpperCase()} ⢠PAYMENT: ${String((De==null?void 0:De.paymentStatus)||"unpaid").toUpperCase()}`,Ie-12,19.5,{align:"right"}),Q.setDrawColor(...vn),Q.setLineWidth(.35),Q.line(12,23.5,Ie-12,23.5);const kn=[["EMPLOYEES",String(_n.length)],["GROSS PAYROLL",`BDT ${pn(ha.gross)}`],["TOTAL ADDITION",`BDT ${pn(ha.addition)}`],["TOTAL DEDUCTION",`BDT ${pn(ha.deduction)}`],["NET PAYABLE",`BDT ${pn(ha.net)}`]],Kn=(Ie-24)/kn.length;kn.forEach(([Hn,Fa],zs)=>{const Bs=12+zs*Kn;Q.setFillColor(...Yt),Q.setDrawColor(...vn),Q.roundedRect(Bs,27.5,Kn-2.2,17,1.5,1.5,"FD"),zs===4&&(Q.setFillColor(232,242,248),Q.roundedRect(Bs,27.5,Kn-2.2,17,1.5,1.5,"F")),Q.setFont("helvetica","bold"),Q.setFontSize(5.8),Q.setTextColor(...Dt),Q.text(Hn,Bs+2.8,32.1),Q.setFontSize(zs===4?10.2:9.5),Q.setTextColor(...He),Q.text(Fa,Bs+2.8,40.5)});const Zn={overtime:_n.reduce((Hn,Fa)=>Hn+Fa.overtimeAmount,0),festivalBonus:_n.reduce((Hn,Fa)=>Hn+Fa.festivalBonus,0),performanceBonus:_n.reduce((Hn,Fa)=>Hn+Fa.performanceBonus,0),incentive:_n.reduce((Hn,Fa)=>Hn+Fa.incentive,0),otherAddition:_n.reduce((Hn,Fa)=>Hn+Fa.otherAddition,0),advance:_n.reduce((Hn,Fa)=>
4043Hn+Fa.advanceDeduction,0),loan:_n.reduce((Hn,Fa)=>Hn+Fa.loanDeduction,0),fine:_n.reduce((Hn,Fa)=>Hn+Fa.fineDeduction,0),otherDeduction:_n.reduce((Hn,Fa)=>Hn+Fa.otherDeduction,0)};[["Festival Bonus",Zn.festivalBonus,"add"],["Performance Bonus",Zn.performanceBonus,"add"],["Incentive",Zn.incentive,"add"],["Overtime",Zn.overtime,"add"],["Other Addition",Zn.otherAddition,"add"],["Advance",Zn.advance,"ded"],["Loan",Zn.loan,"ded"],["Fine",Zn.fine,"ded"],["Other Deduction",Zn.otherDeduction,"ded"]].filter(([,Hn])=>Number(Hn)>0);const da=_n.map(Hn=>{const Fa=ke(Hn),zs=Hn.overtimeAmount+Hn.festivalBonus+Hn.performanceBonus+Hn.incentive+Hn.otherAddition,Bs=Hn.advanceDeduction+Hn.loanDeduction,S=Hn.fineDeduction+Hn.otherDeduction;return[Hn.employeeCode||"",Hn.employeeName,pn(Hn.grossSalary),String(Hn.workingDays),String(Hn.absentDays),String(Hn.lateCount),String(Hn.halfDayCount||0),String(Hn.paidLeaveDays||0),String(Hn.unpaidLeaveDays||0),String(Hn.officialDayOffDays||0),pn(Hn.attendanceDeduction),pn(Bs+S),pn(Number(Hn.monthlyTax||0)),pn(Number(Hn.employeePf||0)),pn(Number(Hn.employerPf||0)),pn(zs),pn(Hn.netPay),Fa.bankName||"â",Fa.bankAccount||"â",Fa.bankAccountHolder||"â"]}),Ga=_n.length<=15?{fontSize:7.2,headSize:6.3,cellY:2.75}:_n.length<=25?{fontSize:6.5,headSize:5.9,cellY:2.15}:{fontSize:5.8,headSize:5.4,cellY:1.7},Da=[["Festival Bonus",Zn.festivalBonus],["Performance Bonus",Zn.performanceBonus],["Incentive",Zn.incentive],["Overtime",Zn.overtime],["Other Addition",Zn.otherAddition]].filter(([,Hn])=>Number(Hn)>0),Ia=ha.addition>0&&Da.length>0;let ls=49;if(Q.setFont("helvetica","normal"),Q.setFontSize(5.9),Q.setTextColor(...Dt),Q.text("Attendance: Paid Leave + Official Day Off are protected; Unpaid Leave is deductible.",8,47.2),ls=51,Ia){const Hn=Da.map(([zs,Bs])=>`${zs}: BDT ${pn(Bs)}`).concat([`Total Addition: BDT ${pn(ha.addition)}`]);Q.setFillColor(239,246,250),Q.setDrawColor(...vn),Q.roundedRect(12,50.5,Ie-24,8.5,1.2,1.2,"FD"),Q.setFont("helvetica","bold"),Q.setFontSize(6.4),Q.setTextColor(...He),Q.text("ADDITION SUMMARY",15,55.8),Q.setFont("helvetica","normal"),Q.setTextColor(...gt);const Fa=Q.splitTextToSize(Hn.join(" ⢠"),Ie-70);Q.text(Fa[0]||"",Ie-15,55.8,{align:"right"}),ls=62}oi(Q,{startY:ls,head:[["ID","EMPLOYEE","GROSS","WORK DAYS","ABSENT","LATE","HALF DAY","PAID LEAVE","UNPAID LEAVE","OFFICIAL DAY OFF","ATTN. DED.","ADV / LOAN / OTHER","TAX","EMP PF","ER PF","ADDITION","NET PAYABLE","BANK","A/C NO.","A/C HOLDER"]],body:da,foot:[["","GRAND TOTAL",pn(ha.gross),"","","","","","","",pn(_n.reduce((Hn,Fa)=>Hn+Fa.attendanceDeduction,0)),pn(_n.reduce((Hn,Fa)=>Hn+Fa.advanceDeduction+Fa.loanDeduction+Fa.fineDeduction+Fa.otherDeduction,0)),pn(ha.tax),pn(ha.employeePf),pn(ha.employerPf),pn(ha.addition),pn(ha.net),"","",""]],theme:"plain",styles:{font:"helvetica",fontSize:Ga.fontSize,cellPadding:{top:Ga.cellY,bottom:Ga.cellY,left:1.1,right:1.1},textColor:gt,valign:"middle",overflow:"linebreak",lineColor:vn,lineWidth:{bottom:.12}},headStyles:{fillColor:He,textColor:[255,255,255],fontStyle:"bold",fontSize:Math.max(5.5,Ga.headSize-.3),cellPadding:{top:2.4,bottom:2.4,left:1.2,right:1.2},lineWidth:0},footStyles:{fillColor:[232,242,248],textColor:He,fontStyle:"bold",fontSize:Math.max(5.8,Ga.fontSize-.4),cellPadding:{top:2.4,bottom:2.4,left:1.1,right:1.1},lineColor:He,lineWidth:{top:.35,bottom:.35}},alternateRowStyles:{fillColor:[249,251,253]},columnStyles:{0:{cellWidth:10,halign:"center"},1:{cellWidth:22},2:{cellWidth:17,halign:"right"},3:{cellWidth:11,halign:"center"},4:{cellWidth:9,halign:"center"},5:{cellWidth:8,halign:"center"},6:{cellWidth:9,halign:"center"},7:{cellWidth:11,halign:"center"},8:{cellWidth:12,halign:"center"},9:{cellWidth:14,halign:"center"},10:{cellWidth:14,halign:"right"},11:{cellWidth:14,halign:"right"},12:{cellWidth:11,halign:"right"},13:{cellWidth:12,halign:"right"},14:{cellWidth:10,halign:"right"},15:{cellWidth:13,halign:"right"},16:{cellWidth:17,halign:"right",fontStyle:"bold",textColor:He},17:{cellWidth:18},18:{cellWidth:24},19:{cellWidth:25}},margin:{left:8,right:8,bottom:22},didDrawPage:Hn=>{Q.setDrawColor(...vn),Q.line(12,Le-12,Ie-12,Le-12),Q.setTextColor(...Dt),Q.setFont("helvetica","normal"),Q.setFontSize(6.2),Q.text(`Generated ${ma} ⢠VERIXO ERP`,12,Le-7.5),Q.text(`Confidential Payroll Document ⢠Page ${Hn.pageNumber}`,Ie-12,Le-7.5,{align:"right"})}});const Ua=((Vs=Q.lastAutoTable)==null?void 0:Vs.finalY)||150;if(Ua<Le-27){const Hn=Math.max(Ua+12,Le-24),Fa=["PREPARED BY","CHECKED BY","APPROVED BY"],zs=[42,Ie/2,Ie-42];Q.setDrawColor(150,165,177),Q.setTextColor(...Dt),Q.setFont("helvetica","bold"),Q.setFontSize(6.1),Fa.forEac
4043h((Bs,S)=>{Q.line(zs[S]-22,Hn,zs[S]+22,Hn),Q.text(Bs,zs[S],Hn+4,{align:"center"})})}const va=_n.filter(Hn=>Hn.overtimeAmount>0||Hn.festivalBonus>0||Hn.performanceBonus>0||Hn.incentive>0||Hn.otherAddition>0||Hn.advanceDeduction>0||Hn.loanDeduction>0||Hn.fineDeduction>0||Hn.otherDeduction>0).map(Hn=>[Hn.employeeCode||"",Hn.employeeName,pn(Hn.festivalBonus),pn(Hn.performanceBonus),pn(Hn.incentive),pn(Hn.overtimeAmount),pn(Hn.otherAddition),pn(Hn.advanceDeduction),pn(Hn.loanDeduction),pn(Hn.fineDeduction+Hn.otherDeduction)]);if(va.length&&(Q.addPage("a4","landscape"),Q.setFillColor(...He),Q.rect(0,0,Ie,3.2,"F"),Q.setTextColor(...He),Q.setFont("helvetica","bold"),Q.setFontSize(15),Q.text("EMPLOYEE ADJUSTMENT DETAILS",12,14),Q.setFont("helvetica","normal"),Q.setFontSize(7),Q.setTextColor(...Dt),Q.text(`${En} ⢠${wn} ⢠${zt}`,12,19),oi(Q,{startY:25,head:[["ID","EMPLOYEE",`FESTIVAL 4044BONUS`,`PERFORMANCE 4045BONUS`,"INCENTIVE","OVERTIME",`OTHER 4046ADDITION`,"ADVANCE","LOAN",`FINE / OTHER 4047DEDUCTION`]],body:va,theme:"plain",styles:{font:"helvetica",fontSize:7,cellPadding:{top:2.5,bottom:2.5,left:2,right:2},textColor:gt,lineColor:vn,lineWidth:{bottom:.12}},headStyles:{fillColor:He,textColor:[255,255,255],fontStyle:"bold",fontSize:6.1},alternateRowStyles:{fillColor:[249,251,253]},columnStyles:{0:{cellWidth:12},1:{cellWidth:42},2:{halign:"right"},3:{halign:"right"},4:{halign:"right"},5:{halign:"right"},6:{halign:"right"},7:{halign:"right"},8:{halign:"right"},9:{halign:"right"}},margin:{left:12,right:12,bottom:20},didDrawPage:Hn=>{Q.setDrawColor(...vn),Q.line(12,Le-12,Ie-12,Le-12),Q.setTextColor(...Dt),Q.setFont("helvetica","normal"),Q.setFontSize(6.2),Q.text(`Generated ${ma} ⢠VERIXO ERP`,12,Le-7.5),Q.text(`Confidential Payroll Document ⢠Adjustment Detail ⢠Page ${Hn.pageNumber}`,Ie-12,Le-7.5,{align:"right"})}})),E==="preview"){st&&URL.revokeObjectURL(st),Nt(URL.createObjectURL(Q.output("blob")));return}Q.save(`VERIXO_Payroll_${l}_${zt.replace(/[^a-zA-Z0-9]+/g,"-")||"All-Branches"}.pdf`)},Et=()=>void Ct("preview"),Rt=async E=>{const Q=new Ra({orientation:"portrait",unit:"mm",format:"a4",compress:!0});let Ie=pt;try{Ie=await fc(t.companyId),$e(Ie)}catch(Da){console.warn("Payslip branding load failed:",Da)}const Le=Ie.name||"Company",He=new Date(`${l}-01T00:00:00`).toLocaleDateString("en-US",{month:"long",year:"numeric"}),gt=[10,61,98],Dt=[95,111,126],Yt=[218,226,234],vn=Number(E.overt
4047imeAmount||0)+Number(E.festivalBonus||0)+Number(E.performanceBonus||0)+Number(E.incentive||0)+Number(E.otherAddition||0),zt=Number(E.attendanceDeduction||0)+Number(E.advanceDeduction||0)+Number(E.loanDeduction||0)+Number(E.fineDeduction||0)+Number(E.otherDeduction||0),Bt=ke(E);Q.setFillColor(...gt),Q.rect(0,0,210,4,"F"),Q.setTextColor(...gt),Q.setFont("helvetica","bold"),Q.setFontSize(18),Q.text(Le,15,18),Q.setFontSize(15),Q.text("SALARY PAYSLIP",195,18,{align:"right"}),Q.setFont("helvetica","normal"),Q.setFontSize(8),Q.setTextColor(...Dt),Q.text(`${He} ⢠${String((De==null?void 0:De.status)||"draft").toUpperCase()}`,195,24,{align:"right"}),Q.setDrawColor(...Yt),Q.line(15,30,195,30),oi(Q,{startY:36,head:[["EMPLOYEE","ID","BANK","A/C NO."]],body:[[E.employeeName,E.employeeCode||"â",Bt.bankName||"â",Bt.bankAccount||"â"]],theme:"grid",styles:{fontSize:8,cellPadding:3,lineColor:Yt},headStyles:{fillColor:gt,textColor:[255,255,255],fontStyle:"bold"}});const En=[["Gross Salary",pn(E.grossSalary)],["Overtime",pn(Number(E.overt
4047imeAmount||0))],["Festival Bonus",pn(Number(E.festivalBonus||0))],["Performance Bonus",pn(Number(E.performanceBonus||0))],["Incentive",pn(Number(E.incentive||0))],["Other Addition",pn(Number(E.otherAddition||0))],["Total Addition",pn(vn)]],wn=[["Attendance Deduction",pn(Number(E.attendanceDeduction||0))],["Advance / Loan / Other",pn(zt-Number(E.attendanceDeduction||0))],["Income Tax",pn(Number(E.monthlyTax||0))],["Employee PF",pn(Number(E.employeePf||0))],["Employer PF (Company)",pn(Number(E.employerPf||0))],["Net Payable",pn(Number(E.netPay||0))]];oi(Q,{startY:Q.lastAutoTable.finalY+8,head:[["EARNINGS","AMOUNT (BDT)","DEDUCTIONS / STATUTORY","AMOUNT (BDT)"]],body:Array.from({length:Math.max(En.length,wn.length)},(Da,Ia)=>{var ls,Ua,va,_a;return[((ls=En[Ia])==null?void 0:ls[0])||"",((Ua=En[Ia])==null?void 0:Ua[1])||"",((va=wn[Ia])==null?void 0:va[0])||"",((_a=wn[Ia])==null?void 0:_a[1])||""]}),theme:"grid",styles:{fontSize:8,cellPadding:2.8,lineColor:Yt},headStyles:{fillColor:gt,textColor:[255,255,255],fontStyle:"bold"},columnStyles:{1:{halign:"right"},3:{halign:"right"}}});const ma=Object.values(me[E.employeeId]||{}).filter(Da=>Da.status!=="reversed").sort((Da,Ia)=>String(Da.paymentDate||"").localeCompare(String(Ia.paymentDate||""))||Number(Da.createdAt||0)-Number(Ia.createdAt||0)),ca=Da=>{const Ia=String(Da||"").trim();if(!Ia)return"â";const ls=Ia.slice(-4);return`${"â¢".repeat(Math.max(4,Math.min(8,Ia.length-ls.length)))}${ls}`},Pa=ma.reduce((Da,Ia)=>Da+Math.max(Number(Ia.amount||0),0),0),kn=ma.reduce((Da,Ia)=>Da+Math.max(-Number(Ia.roundingAdjustment||0),0),0),Kn=ma.reduce((Da,Ia)=>Da+Math.max(Number(Ia.settledAmount??Ia.amount??0),0),0),Zn=Math.max(Number(E.netPay||0)-Kn,0);oi(Q,{startY:Q.lastAutoTable.finalY+8,head:[["PAYMENT DETAILS","VALUE"]],body:ma.length?[["Payment Status",Zn<=0?"PAID":"PARTIALLY PAID"],["Actual Paid / Outstanding",`BDT ${pn(Pa)} / BDT ${pn(Zn)}`],...kn>0?[["Salary Rounding Adjustment",`- BDT ${pn(kn)}`]]:[],...ma.flatMap((Da,Ia)=>[[`Payment ${Ia+1}`,`${Da.paymentDate} · ${Da.method.toUpperCase()} · BDT ${pn(Da.amount)}${Da.reference?` · Ref ${Da.reference}`:""}`],["Sent To",`${Da.receivingBankName||Bt.bankName||"â"} · ${(Da.receivingBankAccountHolder&&Da.receivingBankAccountHolder!==E.employeeName?Da.receivingBankAccountHolder:Bt.bankAccountHolder)||E.employeeName} · A/C ${ca(Da.receivingBankAccount||Bt.bankAccount)}`],["Paid From",Da.method==="bank"?`${Da.sourceBankName||"â"} · ${Da.sourceBankAccountName||""} · A/C ${ca(Da.sourceBankAccountNumber)}`:Da.method.toUpperCase()]])]:[["Payment Status","UNPAID"]],theme:"grid",styles:{fontSize:7.2,cellPadding:2.2,lineColor:Yt},headStyles:{fillColor:gt,textColor:[255,255,255],fontStyle:"bold"},columnStyles:{0:{cellWidth:42,fontStyle:"bold"}}});const da=Q.lastAutoTable.finalY+7;Q.setFont("helvetica","bold"),Q.setTextColor(...gt),Q.setFontSize(9),Q.text("STATUTORY DETAILS",15,da),Q.setFont("helvetica","normal"),Q.setTextColor(...Dt),Q.setFontSize(7.5),Q.text(`Tax Rule: ${E.taxRuleVersionId||"Not Applicable"} ⢠PF: ${E.pfEligible?`Eligible from ${E.pfStartDate||"â"}`:"Not Applicable"}`,15,da+5),Q.text(`PF Basis: BDT ${pn(Number(E.pfBasisAmount||0))} ⢠Monthly Tax: BDT ${pn(Number(E.monthlyTax||0))}`,15,da+10),Q.setDrawColor(...Yt),Q.line(15,276,195,276),Q.setFontSize(6.5),Q.setTextColor(...Dt),Q.text("Generated by VERIXO ERP",15,282),Q.text(`${E.employeeCode||E.employeeId} ⢠${l}`,195,282,{align:"right"});const Ga=String(E.employeeName||E.employeeCode||"Employee").replace(/[^a-zA-Z0-9]+/g,"-");Q.save(`VERIXO_Payslip_${l}_${Ga}.pdf`)},xn=async(E="preview")=>{var ca;if(!_n.length){window.alert("Generate payroll first.");return}const Q=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),Ie=Q.internal.pageSize.getWidth(),Le=Q.internal.pageSize.getHeight(),He=[10,61,98],gt=[20,39,55],Dt=[100,116,132],Yt=[218,226,234];let vn=pt;try{vn=await fc(t.companyId),$e(vn)}catch(Pa){console.warn("Disbursement report branding load failed:",Pa)}const zt=vn.name||"Company",Bt=((ca=n.find(Pa=>Pa.id===a))==null?void 0:ca.name)||(a==="all"?"All Branches":""),En=new Date(`${l}-01T00:00:00`).toLocaleDateString("en-US",{month:"long",year:"numeric"}
4047),wn=new Date().toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});Q.setFillColor(...He),Q.rect(0,0,Ie,3.2,"F"),Q.setTextColor(...He),Q.setFont("helvetica","bold"),Q.setFontSize(16),Q.text(zt,12,13.5),Q.setFontSize(13),Q.text("SALARY DISBURSEMENT REPORT",Ie-12,10.5,{align:"right"}),Q.setFont("helvetica","normal"),Q.setFontSize(7.2),Q.setTextColor(...Dt),Q.text(`HR & PAYROLL ⢠${En.toUpperCase()} ⢠${Bt}`,12,19),Q.text(`STATUS: ${String((De==null?void 0:De.status)||"draft").toUpperCase()} ⢠PAYMENT: ${String((De==null?void 0:De.paymentStatus)||"unpaid").toUpperCase()}`,Ie-12,19,{align:"right"}),Q.setDrawColor(...Yt),Q.line(12,23,Ie-12,23);const ma=_n.map(Pa=>{var da;const kn=Math.min(Math.max(Number(Pa.paidAmount||0),0),Math.max(Pa.netPay,0)),Kn=Math.max(Pa.netPay-kn,0),Zn=ke(Pa);return[Pa.employeeCode||"",Pa.employeeName,pn(Pa.netPay),pn(kn),pn(Kn),String(Pa.paymentStatus||"unpaid").replace("_"," ").toUpperCase(),((da=Pa.paymentMethod)==null?void 0:da.toUpperCase())||"â",Pa.paymentDate||"â",Zn.bankName||"â",Zn.bankAccount||"â",Pa.paymentReference||"â"]});if(oi(Q,{startY:28,head:[["ID","EMPLOYEE","NET PAYABLE","PAID","PENDING","STATUS","METHOD","PAYMENT DATE","BANK","A/C NO.","REFERENCE"]],body:ma,theme:"plain",styles:{font:"helvetica",fontSize:6.7,cellPadding:{top:2.4,bottom:2.4,left:1.8,right:1.8},textColor:gt,lineColor:Yt,lineWidth:{bottom:.12}},headStyles:{fillColor:He,textColor:[255,255,255],fontStyle:"bold",fontSize:5.8},alternateRowStyles:{fillColor:[249,251,253]},columnStyles:{0:{cellWidth:10},1:{cellWidth:35},2:{halign:"right",cellWidth:20},3:{halign:"right",cellWidth:18},4:{halign:"right",cellWidth:18},5:{cellWidth:20},6:{cellWidth:15},7:{cellWidth:20},8:{cellWidth:28},9:{cellWidth:30},10:{cellWidth:28}},margin:{left:12,right:12,bottom:18},didDrawPage:Pa=>{Q.setDrawColor(...Yt),Q.line(12,Le-12,Ie-12,Le-12),Q.setTextColor(...Dt),Q.setFont("helvetica","normal"),Q.setFontSize(6.2),Q.text(`Generated ${wn} ⢠VERIXO ERP`,12,Le-7.5),Q.text(`Confidential Payroll Document ⢠Disbursement ⢠Page ${Pa.pageNumber}`,Ie-12,Le-7.5,{align:"right"})}}),E==="preview"){st&&URL.revokeObjectURL(st),Nt(URL.createObjectURL(Q.output("blob")));return}Q.save(`VERIXO_Salary_Disbursement_${l}_${Bt.replace(/[^a-zA-Z0-9]+/g,"-")||"All-Branches"}.pdf`)},dn=async(E="preview")=>{var Pa;if(!_n.length){window.alert("Generate payroll first.");return}const Q=_n.map(kn=>{const Kn=ke(kn),Zn=Math.min(Math.max(Number(kn.paidAmount||0),0),Math.max(kn.netPay,0)),da=Math.max(kn.netPay-Zn,0);return{item:kn,bank:Kn,pending:da}}).filter(kn=>{var Kn,Zn;return kn.pending>0&&!!((Kn=kn.bank.bankName)!=null&&Kn.trim())&&!!((Zn=kn.bank.bankAccount)!=null&&Zn.trim())});if(!Q.length){window.alert("No pending bank-transfer rows found. Add Bank Name and Account No. in Salary Structure first.");return}const Ie=new Ra({orientation:"landscape",unit:"mm",format:"a4",compress:!0}),Le=Ie.internal.pageSize.getWidth(),He=Ie.internal.pageSize.getHeight(),gt=[10,61,98],Dt=[20,39,55],Yt=[100,116,132],vn=[218,226,234];let zt=pt;try{zt=await fc(t.companyId),$e(zt)}catch(kn){console.warn("Bank payment sheet branding load failed:",kn)}const Bt=zt.name||"Company",En=((Pa=n.find(kn=>kn.id===a))==null?void 0:Pa.name)||(a==="all"?"All Branches":""),wn=new Date(`${l}-01T00:00:00`).toLocaleDateString("en-US",{month:"long",year:"numeric"}),ma=Q.reduce((kn,Kn)=>kn+Kn.pending,0),ca=new Date().toLocaleString("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});if(Ie.setFillColor(...gt),Ie.rect(0,0,Le,3.2,"F"),Ie.setTextColor(...gt),Ie.setFont("helvetica","bold"),Ie.setFontSize(16),Ie.text(Bt,12,13.5),Ie.setFontSize(13),Ie.text("BANK PAYMENT SHEET",Le-12,10.5,{align:"right"}),Ie.setFont("helvetica","normal"),Ie.setFontSize(7.2),Ie.setTextColor(...Yt),Ie.text(`${wn.toUpperCase()} ⢠${En} ⢠${Q.length} PAYMENT(S)`,12,19),Ie.setFont("helvetica","bold"),Ie.setTextColor(...gt),Ie.text(`TOTAL TRANSFER: BDT ${pn(ma)}`,Le-12,19,{align:"right"}),Ie.setDrawColor(...vn),Ie.line(12,23,Le-12,23),oi(Ie,{startY:28,head:[["SL","EMPLOYEE ID","EMPLOYEE NAME","BANK","ACCOUNT NO.","ACCOUNT HOLDER","AMOUNT TO TRANSFER","REMARKS"]],body:Q.map((kn,Kn)=>[String(Kn+1),kn.item.employeeCode||"",kn.item.employeeName,kn.bank.bankName,kn.bank.bankAccount,kn.bank.bankAccountHolder||kn.item.employeeName,pn(kn.pending),pr(kn.item).status==="partially_paid"?"Balance payment":"Salary"]),theme:"plain",styles:{font:"helvetica",fontSize:7,cellPadding:{top:2.8,bottom:2.8,left:2,right:2},textColor:Dt,lineColor:vn,lineWidth:{bottom:.12}},headStyles:{fillColor:gt,textColor:[255,255,255],fontStyle:"bold",fontSize:6},alternateRowStyles:{fillColor:[249,251,253]},columnStyles:{0:{cellWidth:10,halign:"center"},1:{cellWidth:22},2:{cellWidth:42},3:{cellWidth:38},4:{cellWidth:42},5:{cellWidth:42},6:{cellWidth:35,halign:"right"},7:{cellWidth:35}},margin:{left:12,right:12,bottom:20},didDrawPage:kn=>{Ie.setDrawColor(...vn),Ie.line(12,He-12,Le-12,He-12),Ie.setTextColor(...Yt),Ie.setFont("helvetica","normal"),Ie.setFontSize(6.2),Ie.text(`Generated ${ca} ⢠VERIXO ERP`,12,He-7.5),Ie.text(`Bank Payment Instruction Sheet ⢠Page ${kn.pageNumber}
4047`,Le-12,He-7.5,{align:"right"})}}),E==="preview"){st&&URL.revokeObjectURL(st),Nt(URL.createObjectURL(Ie.output("blob")));return}Ie.save(`VERIXO_Bank_Payment_Sheet_${l}_${En.replace(/[^a-zA-Z0-9]+/g,"-")||"All-Branches"}.pdf`)},Ln=()=>{st&&URL.revokeObjectURL(st),Nt("")},wa=["super_admin","owner","admin"].includes(t.role),Ca=sa(t,"payroll.payment.record"),In=sa(t,"payroll.payment.reverse"),Sa=sa(t,"payroll.statutory.record"),aa=sa(t,"payroll.statutory.reverse");x.useEffect(()=>qt(re(ie,`payrollSettings/${t.companyId}`),E=>u({...q_,...E.val()||{}})),[t.companyId]),x.useEffect(()=>qt(re(ie,`payrollTaxRules/${t.companyId}`),E=>{g(E.exists()?E.val():{})},E=>{console.error("Payroll tax rule registry load failed:",E),g({}),y({type:"error",text:`Tax rule registry could not be read: ${E.message||"permission denied"}`})}),[t.companyId]),x.useEffect(()=>{let E=!0;return fc(t.companyId).then(Q=>{E&&$e(Q)}).catch(Q=>console.error("Payroll company branding load failed:",Q)),()=>{E=!1}},[t.companyId]),x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),E=>{xe("");const Q=E.exists()?Object.entries(E.val()).map(([Ie,Le])=>({id:Ie,...Le})):[];ht(Q.length),H(Q.filter(Ie=>Ie.active!==!1))},E=>{console.error("Payroll employee source load failed:",E),ht(0),H([]),xe(E.message||"Employee source could not be read.")}),[t.companyId]),x.useEffect(()=>qt(re(ie,`salaryStructures/${t.companyId}`),E=>{we("");const Q=E.exists()?E.val():{};fe(Q),ne(Q),Y(!1)},E=>{console.error("Payroll salary structure source load failed:",E),fe({}),ne({}),we(E.message||"Salary structure source could not be read.")}),[t.companyId]),x.useEffect(()=>vU(t.companyId,E=>F(E),E=>gn(E)),[t.companyId]),x.useEffect(()=>qt(re(ie,`attendancePolicy/${t.companyId}`),E=>{var Ie;const Q=E.exists()?String(((Ie=E.val())==null?void 0:Ie.mode)||"standard"):"standard";Wt(Q==="access_control_multi_punch"?"access_control_multi_punch":"standard")},E=>{console.warn("Payroll pre-check attendance policy could not be read:",E),Wt("access_control_multi_punch")}),[t.companyId]),x.useEffect(()=>qt(re(ie,`attendanceMovements/${t.companyId}`),E=>{if(!E.exists()){Sn([]);return}const Q=E.val(),Ie=[];Object.entries(Q||{}).forEach(([Le,He])=>{Object.values(He||{}).forEach(gt=>{Ie.push({...gt,movementDate:gt.movementDate||Le})})}),Sn(Ie)},E=>{console.error("Payroll pre-check movement source load failed:",E),Sn([])}),[t.companyId]),x.useEffect(()=>qt(re(ie,`payrollItems/${t.companyId}/${l}`),E=>{St(""),ue(E.exists()?E.val():{})},E=>{console.error("Payroll item source load failed:",E),ue({}),St(E.message||"Payroll item source could not be read.")}),[t.companyId,l]),x.useEffect(()=>qt(re(ie,`payrollRuns/${t.companyId}/${l}`),E=>Te(E.exists()?E.val():null)),[t.companyId,l]),x.useEffect(()=>qt(re(ie,`salaryRevisions/${t.companyId}`),E=>_e(E.exists()?E.val():{})),[t.companyId]),x.useEffect(()=>qt(re(ie,`accountingBankAccounts/${t.companyId}`),E=>{const Q=E.exists()?E.val():{};Pe(Object.entries(Q).map(([Ie,Le])=>({id:Ie,...Le})).filter(Ie=>Ie.active!==!1&&Ie.kind!=="mfs"&&!!Ie.ledgerAccountId).sort((Ie,Le)=>String(Ie.bankName||Ie.name||"").localeCompare(String(Le.bankName||Le.name||""))))},E=>{console.error("Payroll bank account source load failed:",E),Pe([])}),[t.companyId]),x.useEffect(()=>qt(re(ie,`payrollPayments/${t.companyId}/${l}`),E=>ge(E.exists()?E.val():{}),E=>{console.error("Payroll payment ledger load failed:",E),ge({})}),[t.companyId,l]),x.useEffect(()=>qt(re(ie,`payrollStatutoryPayments/${t.companyId}/${l}`),E=>Ee(E.exists()?E.val():{}),E=>{console.error("Payroll statutory payment ledger load failed:",E),Ee({})}),[t.companyId,l]);const $a=x.useMemo(()=>z.filter(E=>a==="all"||!a||E.branchId===a).sort((E,Q)=>String(E.employeeId||"").localeCompare(String(Q.employeeId||""),void 0,{numeric:!0,sensitivity:"base"})),[z,a]),jn=x.useMemo(()=>{const E=`${l}-01`,Q=`${l}-${String(V_(l)).padStart(2,"0")}`,Ie=new Set($a.map(Bt=>Bt.id)),Le=$.filter(Bt=>{var En;return((En=Bt.attendanceDate)==null?void 0:En.startsWith(l))&&Bt.status==="missing_punch"&&Ie.has(Bt.employeeId)}),He=Qt.filter(Bt=>{if(Bt.approvalStatus!=="pending"||!Bt.employeeId||!Ie.has(Bt.employeeId))return!1;const En=String(Bt.fromDate||""),wn=String(Bt.toDate||En);return!!En&&En<=Q&&wn>=E}
4047),gt=An.filter(Bt=>{var En;return((En=Bt.movementDate)==null?void 0:En.startsWith(l))&&(!Bt.employeeId||Ie.has(Bt.employeeId))}),Dt=Xt==="access_control_multi_punch",Yt=Dt?gt.filter(Bt=>Bt.status==="pending"):[],vn=Dt?gt.filter(Bt=>Bt.movementType==="unclassified"):[],zt=$a.filter(Bt=>{const En=Z[Bt.id]||q[Bt.id];return Number((En==null?void 0:En.grossSalary)||0)<=0});return{missingPunch:Le.length,pendingLeave:He.length,reviewRequired:Yt.length,unclassified:vn.length,missingSalary:zt.length,missingPunchRows:Le,pendingLeaveRows:He,reviewRequiredRows:Yt,unclassifiedRows:vn,missingSalaryEmployees:zt,hasWarnings:Le.length>0||He.length>0||Yt.length>0||vn.length>0||zt.length>0}},[$,l,Qt,An,Xt,Z,q,$a]),vs={missingPunch:"Missing Punch",pendingLeave:"Pending Leave",reviewRequired:"Review Required",unclassified:"Unclassified",missingSalary:"Missing Gross Salary"},ka=E=>$a.find(Q=>Q.id===E),Ja=x.useMemo(()=>{if(!Gt)return[];const E=Le=>{var gt;const He=ka(Le);return((gt=n.find(Dt=>Dt.id===(He==null?void 0:He.branchId)))==null?void 0:gt.name)||"â"},Q=Le=>{var He;return((He=ka(Le))==null?void 0:He.name)||"Unknown / Unlinked Employee"},Ie=Le=>{var He;return((He=ka(Le))==null?void 0:He.employeeId)||""};return Gt==="missingPunch"?jn.missingPunchRows.map((Le,He)=>({key:`missing-${Le.employeeId}-${Le.attendanceDate}-${He}`,employeeId:Le.employeeId,employeeCode:Ie(Le.employeeId),employeeName:Q(Le.employeeId),branchName:E(Le.employeeId),date:Le.attendanceDate||"â",status:Le.status||"missing_punch",detail:"Attendance record has an incomplete punch pair.",reason:"Payroll cannot safely classify the day until the missing IN/OUT punch is corrected or adjusted."})):Gt==="pendingLeave"?jn.pendingLeaveRows.map((Le,He)=>({key:`leave-${Le.employeeId}-${Le.fromDate}-${He}`,employeeId:Le.employeeId,employeeCode:Ie(Le.employeeId),employeeName:Q(Le.employeeId),branchName:E(Le.employeeId),date:Le.fromDate===Le.toDate||!Le.toDate?String(Le.fromDate||"â"):`${Le.fromDate} â ${Le.toDate}`,status:Le.approvalStatus||"pending",detail:[Le.leaveType?`Type: ${Le.leaveType}`:"",Le.paid===!0?"Paid":Le.paid===!1?"Unpaid":"",Le.reason?`Reason: ${Le.reason}`:""].filter(Boolean).join(" · ")||"Leave request awaiting approval.",reason:"The leave overlaps this payroll month but is still Pending, so payroll cannot treat it as an approved paid/unpaid leave yet."})):Gt==="reviewRequired"||Gt==="unclassified"?(Gt==="reviewRequired"?jn.reviewRequiredRows:jn.unclassifiedRows).map((He,gt)=>({key:`movement-${Gt}-${He.employeeId}-${He.movementDate}-${gt}`,employeeId:He.employeeId,employeeCode:Ie(He.employeeId),employeeName:Q(He.employeeId),branchName:E(He.employeeId),date:He.movementDate||"â",status:Gt==="unclassified"?He.movementType||"unclassified":He.status||"pending",detail:[He.outTime||He.inTime?`${He.outTime||"â"} â ${He.inTime||"â"}`:"",Number.isFinite(Number(He.durationMinutes))?`${Number(He.durationMinutes)} min`:"",He.purpose?`Purpose: ${He.purpose}`:"",He.reference?`Reference: ${He.reference}`:""].filter(Boolean).join(" · ")||"Attendance movement record.",reason:Gt==="unclassified"?"This outside movement has not been assigned a recognized business category, so payroll flags it for HR review.":"This outside movement is still Pending review/approval and has not reached a final classification."})):jn.missingSalaryEmployees.map((Le,He)=>{var gt;return{key:`salary-${Le.id}-${He}`,employeeId:Le.id,employeeCode:Le.employeeId||"",employeeName:Le.name,branchName:((gt=n.find(Dt=>Dt.id===Le.branchId))==null?void 0:gt.name)||"â",date:l,status:"missing_salary",detail:"Gross salary is zero or not configured.",reason:"Payroll can generate the employee row, but salary calculation is incomplete until Gross Salary is configured."}})},[Gt,jn,$a,n,l]),_n=x.useMemo(()=>Object.values(P).filter(E=>a==="all"||!a||E.branchId===a).sort((E,Q)=>String(E.employeeCode||"").localeCompare(String(Q.employeeCode||""),void 0,{numeric:!0,sensitivity:"base"})),[P,a]),ha=x.useMemo(()=>_n.reduce((E,Q)=>({gross:E.gross+Q.grossSalary,deduction:E.deduction+Q.attendanceDeduction+Q.advanceDeduction+Q.loanDeduction+Q.fineDeduction+Q.otherDeduction+Number(Q.employeePf||0)+Number(Q.monthlyTax||0),addition:E.addition+Q.overtimeAmount+Q.festivalBonus+Q.performanceBonus+Q.incentive+Q.otherAddition,tax:E.tax+Number(Q.monthlyTax||0),employeePf:E.employeePf+Number(Q.employeePf||0),employerPf:E.employerPf+Number(Q.employerPf||0),net:E.net+Q.netPay}),{gross:0,deduction:0,addition:0,tax:0,employeePf:0,employerPf:0,net:0}),[_n]),ta=x.useMemo(()=>_n.reduce((E,Q)=>(E.payable+=Math.max(Number(Q.netPay||0),0),E.recoverable+=Math.max(-Number(Q.netPay||0),0),E),{payable:0,recoverable:0}),[_n]),W=x.useMemo(()=>{const E={};return Object.entries(me||{}
4047).forEach(([Q,Ie])=>{E[Q]=Object.values(Ie||{}).reduce((Le,He)=>(He==null?void 0:He.status)==="reversed"?Le:Le+Math.max(Number((He==null?void 0:He.settledAmount)??(He==null?void 0:He.amount)??0),0),0)}),E},[me]),ft=_n.reduce((E,Q)=>{const Ie=Math.max(Number(Q.netPay||0),0),Le=W[Q.employeeId],He=Math.max(Number(Q.paidAmount||0),0),gt=Math.min(Le!==void 0?Le:He,Ie);return E.paid+=gt,E.pending+=Math.max(Ie-gt,0),Ie<=0||(gt>=Ie?E.paidEmployees+=1:gt>0?E.partialEmployees+=1:E.unpaidEmployees+=1),E},{paid:0,pending:0,paidEmployees:0,partialEmployees:0,unpaidEmployees:0}),Zt=ft.paid<=0?"unpaid":ft.pending<=0?"paid":"partially_paid",vt={tax:Math.max(Number(ha.tax||0),0),employee_pf:Math.max(Number(ha.employeePf||0),0),employer_pf:Math.max(Number(ha.employerPf||0),0)},Ae=x.useMemo(()=>{const E={tax:0,employee_pf:0,employer_pf:0};return["tax","employee_pf","employer_pf"].forEach(Q=>{E[Q]=Object.values((Re==null?void 0:Re[Q])||{}).reduce((Ie,Le)=>(Le==null?void 0:Le.status)==="reversed"?Ie:Ie+Math.max(Number((Le==null?void 0:Le.amount)??0),0),0)}),E},[Re]),oe=x.useMemo(()=>{const E=Math.max(vt.tax-Ae.tax,0),Q=Math.max(vt.employee_pf-Ae.employee_pf,0),Ie=Math.max(vt.employer_pf-Ae.employer_pf,0),Le=vt.tax+vt.employee_pf+vt.employer_pf,He=Math.min(Ae.tax,vt.tax)+Math.min(Ae.employee_pf,vt.employee_pf)+Math.min(Ae.employer_pf,vt.employer_pf),gt=E+Q+Ie,Dt=He<=0?"unpaid":gt<=0?"paid":"partially_paid";return{liabilityTotal:Le,paidTotal:He,outstandingTotal:gt,status:Dt,taxOutstanding:E,employeePfOutstanding:Q,employerPfOutstanding:Ie}},[vt.tax,vt.employee_pf,vt.employer_pf,Ae.tax,Ae.employee_pf,Ae.employer_pf]),Ve=x.useMemo(()=>Object.entries(me||{}).flatMap(([E,Q])=>{const Ie=P[E];return Object.values(Q||{}).map(Le=>({...Le,employeeId:E,employeeName:(Ie==null?void 0:Ie.employeeName)||"Unknown Employee",employeeCode:(Ie==null?void 0:Ie.employeeCode)||""}))}).sort((E,Q)=>Number(Q.createdAt||0)-Number(E.createdAt||0)),[me,P]),he=x.useMemo(()=>Object.entries(Re||{}).flatMap(([E,Q])=>Object.values(Q||{}).map(Ie=>({...Ie,liabilityType:Ie.liabilityType||E}))).sort((E,Q)=>Number(Q.createdAt||0)-Number(E.createdAt||0)),[Re]),Oe=Object.entries((bt==null?void 0:bt.demoPayments)||{}).map(([E,Q])=>({id:E,...Q})),ut=Oe.reduce((E,Q)=>(E.net+=Number(Q.netPay||0),E.paid+=Number(Q.paidAmount||0),E.pending+=Math.max(Number(Q.netPay||0)-Number(Q.paidAmount||0),0),E),{net:0,paid:0,pending:0}),At=ut.paid>0||Oe.some(E=>E.paymentStatus==="partially_paid"||E.paymentStatus==="paid"),en=(E,Q)=>{const Ie=!!(Q!=null&&Q.pfApplicable);if(!d.statutoryEnabled||!d.pfEnabled)return{eligible:!1,startDate:"",label:"PF Disabled"};if(!Ie)return{eligible:!1,startDate:"",label:"Not Applicable"};let Le="";if(d.pfEligibilityRule==="from_joining"?Le=E.joiningDate||"":d.pfEligibilityRule==="after_one_year"?Le=E.joiningDate?xU(E.joiningDate,1):"":Le=String((Q==null?void 0:Q.pfCustomStartDate)||""),!Le)return{eligible:!1,startDate:"",label:d.pfEligibilityRule==="custom"?"Custom Start Required":"Joining Date Required"};const He=Le<=Hv(l);return{eligible:He,startDate:Le,label:He?"Eligible":`Starts ${Le}`}};x.useEffect(()=>qt(re(ie,"taxMonitor/global/current"),E=>N(E.exists()?E.val():null),E=>{console.error("NBR monitor load failed:",E),N(null)}),[]),x.useEffect(()=>{if(t.companyId)return qt(re(ie,`taxMonitorAcknowledgements/${t.companyId}`),E=>C(E.exists()?E.val():null),E=>{console.error("NBR monitor acknowledgement load failed:",E),C(null)})},[t.companyId]),x.useEffect(()=>{const E=re(ie,`employeeAdvanceLoans/${t.companyId}`);return qt(E,Q=>{if(!Q.exists()){L([]);return}const Ie=Q.val();L(Object.entries(Ie).map(([Le,He])=>({id:Le,...He})).filter(Le=>Le.status==="active"))})},[t.companyId]),x.useEffect(()=>{const E=re(ie,`payrollItems/${t.companyId}`);return qt(E,Q=>M(Q.exists()?Q.val():{}),Q=>{console.error("Advance/Loan payroll recovery history load failed:",Q),M({})})},[t.companyId]);const It=async()=>{const E="BD-NBR-2025-26",Q=f[E],Ie=Date.now(),Le={id:E,country:"BD",authority:"NBR",assessmentYear:"2025-2026",fiscalYear:"2025-2026",sourceTitle:"NBR Income Tax Paripatra (2025-2026)",sourceUrl:"https://nbr.gov.bd/taxtypes/income-tax/income-tax-paripatra/eservices/taxefiling/eng",status:(Q==null?void 0:Q.status)||"reference_only",slabs:(Q==null?void 0:Q.slabs)||[],notes:(Q==null?void 0:Q.notes)||"Official NBR reference registered. No tax deduction is activated until an approved VERIXO tax rule contains reviewed slabs/calculation parameters.",...(Q==null?void 0:Q.reviewedAt)!=null?{reviewedAt:Q.reviewedAt}:{},...Q!=null&&Q.reviewedByUid?{reviewedByUid:Q.reviewedByUid}:{},...Q!=null&&Q.reviewedByName?{reviewedByName:Q.reviewedByName}:{},createdAt:(Q==null?void 0:Q.createdAt)||Ie,updatedAt:Ie};Ye(!0),y({type:"info",text:Q?"Refreshing NBR reference...":"Initializing NBR reference..."});try{await yn(re(ie),{[`payrollTaxRules/${t.companyId}/${E}`]:Le,[`payrollSettings/${t.companyId}/taxCountry`]:"BD",[`payrollSettings/${t.companyId}/taxEngineMode`]:"reference_only",[`payrollSettings/${t.companyId}/taxRuleVersionId`]:E,[`payrollSettings/${t.companyId}/updatedAt`]:Ie,[`payrollSettings/${t.companyId}/updatedByUid`]:t.uid,[`payrollSettings/${t.companyId}/updatedByName`]:t.name}),u(He=>({...He,taxCountry:"BD",taxEngineMode:"reference_only",taxRuleVersionId:E})),g(He=>({...He,[E]:Le})),y({type:"success",text:`${E} registered successfully. Tax deduction is still OFF in Reference Only mode.`}),le("NBR tax reference registry initialized successfully.")}catch(He){console.error("NBR tax reference initialization failed:",He);const gt=He instanceof Error?He.message:String(He);y({type:"error",text:`NBR reference could not be initialized: ${gt}`}),le("NBR tax reference registry could not be initialized.")}finally{Ye(!1)}},Pt=d.taxRuleVersionId&&f[d.taxRuleVersionId]||null,Jn=d.taxScheduledRuleVersionId&&f[d.taxScheduledRuleVersionId]||null,Mn=!!(Jn&&Jn.status==="approved"&&d.taxScheduledEffectiveDate&&Hv(l)>=String(d.taxScheduledEffectiveDate))?Jn:Pt,Ea=async({title:E,message:Q,ruleId:Ie,effectiveDate:Le})=>
4047{const He=Date.now(),gt=`tax_${Ie}_${He}`;await yn(re(ie),{[`workspaceNotifications/${t.companyId}/${gt}`]:{id:gt,category:"tax_rule",audienceRoles:["super_admin","owner","admin","hr"],title:E,message:Q,ruleId:Ie,...Le?{effectiveDate:Le}:{},actionLabel:"Review Tax Update",actionPage:"payroll",createdAt:He,createdByUid:t.uid,createdByName:t.name,readBy:{}}})},ga=async()=>{var Le;const E="BD-NBR-2026-27",Q=Date.now(),Ie={id:E,country:"BD",authority:"NBR",assessmentYear:"2026-2027",fiscalYear:"2026-2027",sourceTitle:"NBR Budget tax rates for Assessment Year 2026-27",sourceUrl:"https://nbr.gov.bd/uploads/budget/English.pdf",status:"approved",slabs:[{upTo:375e3,rate:0},{upTo:675e3,rate:10},{upTo:1075e3,rate:15},{upTo:1575e3,rate:20},{upTo:3575e3,rate:25},{rate:30}],notes:"General individual taxpayer slab. Special-category thresholds and personal return adjustments are not automatically inferred.",reviewedAt:Q,reviewedByUid:t.uid,reviewedByName:t.name,createdAt:((Le=f[E])==null?void 0:Le.createdAt)||Q,updatedAt:Q};Ye(!0),y({type:"info",text:"Installing reviewed NBR 2026-27 rule..."});try{await yn(re(ie),{[`payrollTaxRules/${t.companyId}/${E}`]:Ie,[`payrollSettings/${t.companyId}/taxCountry`]:"BD",[`payrollSettings/${t.companyId}/taxEngineMode`]:"approved_rule",[`payrollSettings/${t.companyId}/taxRuleVersionId`]:E}),g(He=>({...He,[E]:Ie})),u(He=>({...He,taxCountry:"BD",taxEngineMode:"approved_rule",taxRuleVersionId:E})),await Ea({title:"NBR tax rule activated",message:`${E} was installed/activated for payroll. Owner/Admin/HR should review the active tax rule before the next payroll approval.`,ruleId:E,effectiveDate:"2026-07-01"}),y({type:"success",text:`${E} installed. Approved Rule mode is active; a tax-rule notification was sent to Owner/Admin/HR. Regenerate a Draft payroll to calculate tax.`})}catch(He){const gt=He instanceof Error?He.message:String(He);y({type:"error",text:`Reviewed NBR rule could not be installed: ${gt}`})}finally{Ye(!1)}},zn=()=>{if(!(b!=null&&b.hash)){y({type:"error",text:"NBR monitor snapshot is not available yet."});return}if(!Mn){y({type:"error",text:"Install/select a base Tax Rule before creating a versioned review draft."});return}const E=new Date().toISOString().slice(0,10),Q=String(b.hash).slice(0,8).toUpperCase();J({id:`${Mn.id}-REV-${Q}`,assessmentYear:Mn.assessmentYear,fiscalYear:Mn.fiscalYear,effectiveDate:E,sourceTitle:String(b.latestTitle||"Official NBR income-tax source update"),sourceUrl:"https://nbr.gov.bd/regulations/sros/income-tax-sros/income-tax-sros",slabs:(Mn.slabs||[]).map(Ie=>({...Ie}))})},Xn=(E,Q,Ie)=>{J(Le=>{if(!Le)return Le;const He=Le.slabs.map((gt,Dt)=>Dt!==E?gt:Q==="upTo"?Ie===""?{rate:gt.rate}:{...gt,upTo:Math.max(0,Number(Ie)||0)}:{...gt,rate:Math.max(0,Number(Ie)||0)});return{...Le,slabs:He}})},Vn=async()=>{var E;if(!(!_||!(b!=null&&b.hash))){if(!_.id.trim()||!_.effectiveDate||_.slabs.length===0){y({type:"error",text:"Rule ID, effective date and at least one slab are required."});return}I(!0);try{const Q=Date.now(),Ie={id:_.id.trim(),country:"BD",authority:"NBR",assessmentYear:_.assessmentYear.trim(),fiscalYear:_.fiscalYear.trim(),sourceTitle:_.sourceTitle.trim(),sourceUrl:_.sourceUrl.trim(),status:"reference_only",slabs:_.slabs.map(Le=>({...Le})),effectiveDate:_.effectiveDate,previousRuleId:Mn==null?void 0:Mn.id,sourceMonitorHash:String(b.hash),notes:"Versioned NBR monitor review draft. It cannot affect payroll until explicitly approved and scheduled.",createdAt:((E=f[_.id])==null?void 0:E.createdAt)||Q,updatedAt:Q};await Pn(re(ie,`payrollTaxRules/${t.companyId}/${Ie.id}`),Ie),g(Le=>({...Le,[Ie.id]:Ie})),y({type:"success",text:`${Ie.id} saved as a Reference Only review draft. Payroll calculation is unchanged.`})}catch(Q){const Ie=Q instanceof Error?Q.message:String(Q);y({type:"error",text:`Tax Rule draft could not be saved: ${Ie}`})}finally{I(!1)}}},ua=async()=>{var Q;if(!(!_||!(b!=null&&b.hash)||!window.confirm(`Approve ${_.id} and schedule it from ${_.effectiveDate}? Confirm only after reviewing the official NBR source and every slab/rate shown here.`))){I(!0);try{const Ie=Date.now(),Le={id:_.id.trim(),country:"BD",authority:"NBR",assessmentYear:_.assessmentYear.trim(),fiscalYear:_.fiscalYear.trim(),sourceTitle:_.sourceTitle.trim(),sourceUrl:_.sourceUrl.trim(),status:"approved",slabs:_.slabs.map(He=>({...He})),effectiveDate:_.effectiveDate,previousRuleId:Mn==null?void 0:Mn.id,sourceMonitorHash:String(b.hash),notes:"Reviewed/approved versioned NBR rule. Scheduled by explicit authorized-user approval.",reviewedAt:Ie,reviewedByUid:t.uid,reviewedByName:t.name,createdAt:((Q=f[_.id])==null?void 0:Q.createdAt)||Ie,updatedAt:Ie};await yn(re(ie),{[`payrollTaxRules/${t.companyId}/${Le.id}`]:Le,[`payrollSettings/${t.companyId}/taxScheduledRuleVersionId`]:Le.id,[`payrollSettings/${t.companyId}/taxScheduledEffectiveDate`]:Le.effectiveDate,[`taxMonitorAcknowledgements/${t.companyId}`]:{lastHash:String(b.hash),reviewedAt:Ie,reviewedByUid:t.uid,reviewedByName:t.name,latestTitle:String(b.latestTitle||""),decision:"rule_change_approved",scheduledRuleVersionId:Le.id,effectiveDate:Le.effectiveDate}}),g(He=>
4047({...He,[Le.id]:Le})),u(He=>({...He,taxScheduledRuleVersionId:Le.id,taxScheduledEffectiveDate:Le.effectiveDate})),await Ea({title:"NBR Tax Rule approved and scheduled",message:`${Le.id} was approved after NBR review and is scheduled from ${Le.effectiveDate}. Historical payroll keeps its applicable rule.`,ruleId:Le.id,effectiveDate:Le.effectiveDate}),y({type:"success",text:`${Le.id} approved and scheduled from ${Le.effectiveDate}. It will apply only to payroll months on/after that effective date.`}),J(null)}catch(Ie){const Le=Ie instanceof Error?Ie.message:String(Ie);y({type:"error",text:`Reviewed Tax Rule could not be approved/scheduled: ${Le}`})}finally{I(!1)}}},Ma=async()=>{const E=String((b==null?void 0:b.hash)||"");if(E){I(!0);try{const Q=Date.now();await Pn(re(ie,`taxMonitorAcknowledgements/${t.companyId}`),{lastHash:E,reviewedAt:Q,reviewedByUid:t.uid,reviewedByName:t.name,latestTitle:String((b==null?void 0:b.latestTitle)||""),decision:"no_payroll_rule_change"}),y({type:"success",text:"NBR source change reviewed: no payroll Tax Rule change is required. Existing calculation remains active."})}catch(Q){const Ie=Q instanceof Error?Q.message:String(Q);y({type:"error",text:`Review decision could not be saved: ${Ie}`})}finally{I(!1)}}},Xe=E=>{const Q=(E==null?void 0:E.taxPayerCategory)||"general";return(Q==="female_senior"?425e3:Q==="disabled"||Q==="third_gender"?5e5:Q==="war_wounded_ff"||Q==="july_warrior"?525e3:375e3)+Math.max(0,Math.floor(Number((E==null?void 0:E.disabledDependentCount)||0)))*5e4},Jt=E=>E==="dhaka_chattogram"?5e3:E==="other_city_corporation"?4e3:E==="other_area"?3e3:0,Ht=(E,Q,Ie=375e3)=>{var Yt;if(!Q||Q.status!=="approved"||!Q.slabs.length||E<=0||E<=Ie)return 0;let Le=0,He=Ie,Dt=Number(((Yt=Q.slabs[0])==null?void 0:Yt.upTo)||375e3);for(const vn of Q.slabs.slice(1)){const zt=vn.upTo,Bt=zt==null?null:Math.max(Number(zt)-Dt,0),En=Bt==null?null:He+Bt,wn=En==null?Math.max(E-He,0):Math.max(Math.min(E,En)-He,0);if(Le+=wn*(Math.max(Number(vn.rate||0),0)/100),En==null||E<=En)break;He=En,Dt=Number(zt)}return Math.max(Le,0)},xa=E=>{const[Q,Ie]=E.split("-").map(Number),Le=Ie>=7?Q:Q-1;return Array.from({length:12},(He,gt)=>{const Dt=7+gt,Yt=Le+Math.floor((Dt-1)/12),vn=(Dt-1)%12+1;return`${Yt}-${String(vn).padStart(2,"0")}`})},ra=E=>{const Q=xa(E),Ie=Math.max(0,Q.indexOf(E));return{priorMonths:Q.slice(0,Ie),monthsRemaining:Math.max(Q.length-Ie,1),incomeYearLabel:`${Q[0]} to ${Q[Q.length-1]}`}},Ha=async()=>{Ye(!0),le("");try{await Pn(re(ie,`payrollSettings/${t.companyId}`),{...d,updatedAt:Date.now(),updatedByUid:t.uid,updatedByName:t.name}),le("Payroll settings saved.")}finally{Ye(!1)}},is=(E,Q,Ie)=>{const Le=["bankName","bankAccount","bankAccountHolder","pfCustomStartDate","taxPayerCategory","taxLocationCategory"],gt=["taxApplicable","pfApplicable"].includes(Q)?!!Ie:Le.includes(Q)?String(Ie):Ie===""?0:Number(Ie);ne(Dt=>({...Dt,[E]:{...Dt[E]||Z[E]||{},[Q]:typeof gt=="number"&&!Number.isFinite(gt)?0:gt}})),V(!1),Y(!0)},hs=async()=>{var E,Q;Ye(!0),le("");try{const Ie={},Le=Date.now();for(const He of $a){const gt=q[He.id]||{},Dt=Z[He.id]||{},Yt={employeeId:He.id,grossSalary:Number(gt.grossSalary??Dt.grossSalary??0),basicSalary:Number(gt.basicSalary??Dt.basicSalary??0),houseRent:Number(gt.houseRent??Dt.houseRent??0),medicalAllowance:Number(gt.medicalAllowance??Dt.medicalAllowance??0),transportAllowance:Number(gt.transportAllowance??Dt.transportAllowance??0),otherAllowance:Number(gt.otherAllowance??Dt.otherAllowance??0),bankName:String(gt.bankName??Dt.bankName??"").trim(),bankAccount:String(gt.bankAccount??Dt.bankAccount??"").trim(),bankAccountHolder:String(gt.bankAccountHolder??Dt.bankAccountHolder??"").trim(),taxApplicable:!!(gt.taxApplicable??Dt.taxApplicable??!1),taxPayerCategory:String(gt.taxPayerCategory??Dt.taxPayerCategory??"general"),disabledDependentCount:Math.max(0,Math.floor(Number(gt.disabledDependentCount??Dt.disabledDependentCount??0))),taxLocationCategory:String(gt.taxLocationCategory??Dt.taxLocationCategory??""),annualEligibleInvestment:Math.max(0,Number(gt.annualEligibleInvestment??Dt.annualEligibleInvestment??0
4047)),taxWithheldBeforeVerixo:Math.max(0,Number(gt.taxWithheldBeforeVerixo??Dt.taxWithheldBeforeVerixo??0)),pfApplicable:!!(gt.pfApplicable??Dt.pfApplicable??!1),pfCustomStartDate:String(gt.pfCustomStartDate??Dt.pfCustomStartDate??"").trim(),active:!0,updatedAt:Le,updatedByUid:t.uid,updatedByName:t.name},vn=["grossSalary","basicSalary","houseRent","medicalAllowance","transportAllowance","otherAllowance"];if(!!Dt.employeeId&&vn.some(Bt=>Number(Yt[Bt]||0)!==Number(Dt[Bt]||0))){const Bt=(E=window.prompt(`Salary revision for ${He.name}. 4048Effective month (YYYY-MM):`,l))==null?void 0:E.trim();if(!Bt||!/^\d{4}-\d{2}$/.test(Bt))throw new Error(`Salary revision for ${He.name} was not saved: a valid Effective Month is required.`);const En=(Q=window.prompt(`Reason for ${He.name}'s salary revision effective ${Bt}:`))==null?void 0:Q.trim();if(!En)throw new Error(`Salary revision for ${He.name} was not saved: reason is required.`);if(!Object.values(it[He.id]||{}).length){const ca=`baseline_${Le}`;Ie[`salaryRevisions/${t.companyId}/${He.id}/${ca}`]={id:ca,employeeId:He.id,effectiveFrom:"1900-01-01",structure:{...Dt,employeeId:He.id},reason:"Baseline captured before first VERIXO salary revision",createdAt:Le,createdByUid:t.uid,createdByName:t.name}}const ma=`rev_${Bt.replace("-","")}_${Le}`;Ie[`salaryRevisions/${t.companyId}/${He.id}/${ma}`]={id:ma,employeeId:He.id,effectiveFrom:`${Bt}-01`,structure:Yt,reason:En,createdAt:Le,createdByUid:t.uid,createdByName:t.name},Ie[`salaryRevisionAudit/${t.companyId}/${He.id}/${ma}`]={employeeId:He.id,employeeCode:He.employeeId||"",employeeName:He.name,effectiveFrom:`${Bt}-01`,oldGross:Number(Dt.grossSalary||0),newGross:Number(Yt.grossSalary||0),reason:En,createdAt:Le,createdByUid:t.uid,createdByName:t.name}}Ie[`salaryStructures/${t.companyId}/${He.id}`]=Yt}await yn(re(ie),Ie),Y(!1),V(!0),window.setTimeout(()=>V(!1),1600),le("Salary structure saved. Salary changes were preserved as effective-dated revision history.")}catch(Ie){console.error(Ie),V(!1),le(Ie instanceof Error?Ie.message:"Salary structure could not be saved. Please check permission and try again.")}finally{Ye(!1)}},rs=(E,Q)=>{const Ie=[],Le=He=>Object.entries(D||{}).reduce((gt,[Dt,Yt])=>Dt>=Q?gt:gt+Object.values(Yt||{}).reduce((vn,zt)=>zt.status!=="locked"?vn:vn+(zt.advanceLoanRecoveryBreakdown||[]).filter(Bt=>Bt.recordId===He).reduce((Bt,En)=>Bt+Math.max(0,Number(En.amount||0)),0),0),0);return K.filter(He=>He.employeeId===E&&He.status==="active").forEach(He=>{const gt=Math.max(0,Number(He.amount||0)),Dt=String(He.recoverFromSalaryMonth||He.recoveryStartMonth||"");if(gt<=0||!Dt||Q<Dt)return;const Yt=Math.min(gt,Le(He.id)),vn=Math.max(gt-Yt,0);if(vn<=.004)return;let zt=0;if(He.recoveryMode==="one_time")zt=vn;else{const Bt=Math.max(1,Number(He.installmentCount||1)),En=Math.max(0,Number(He.installmentAmount||gt/Bt));zt=Math.min(En>0?En:gt/Bt,vn)}zt>.004&&Ie.push({recordId:He.id,type:He.type,amount:zt})}),{rows:Ie,advance:Ie.filter(He=>He.type==="advance").reduce((He,gt)=>He+gt.amount,0),loan:Ie.filter(He=>He.type==="loan").reduce((He,gt)=>He+gt.amount,0)}},oa=(E,Q)=>{const Ie=Object.values(it[E]||{}).filter(Le=>String(Le.effectiveFrom||"")<=`${Q}-01`).sort((Le,He)=>String(Le.effectiveFrom).localeCompare(String(He.effectiveFrom)));return Ie.length?Ie[Ie.length-1].structure:Z[E]||q[E]},qa=(E,Q,Ie)=>{const Le=oa(E.id,l),He=Number((Le==null?void 0:Le.grossSalary)||0),gt=V_(l),Dt=$.filter(Ka=>{var Ss;return Ka.employeeId===E.id&&((Ss=Ka.attendanceDate)==null?void 0:Ss.startsWith(l))}),Yt=Ka=>Dt.filter(Ss=>Ss.status===Ka).length,vn=Yt("present"),zt=Yt("late"),Bt=Yt("absent"),En=Yt("leave"),wn=Yt("leave_paid")+Yt("leave_paid_half")*.5+En,ma=Yt("leave_unpaid")+Yt("leave_unpaid_half")*.5,ca=wn+ma,Pa=Yt("official_day_off"),kn=Yt("holiday"),Kn=Yt("weekly_off"),Zn=Yt("half_day"),da=Dt.filter(Ka=>!["holiday","weekly_off"].includes(Ka.status)).length,Ga=Math.floor(zt/Math.max(1,d.latePerDay)),Da=d.deductHalfDay?Zn*Math.max(0,Number(d.halfDayDeductionRate??.5)):0,Ia=Bt+ma+Ga+Da,ls=d.salaryDivisor==="calendar_days"?gt:Math.max(1,Dt.length-kn-Kn),Ua=He/ls,va=Ua*Ia,_a=Q||jU(),Vs=rs(E.id,l),Hn=Math.max(0,Number(_a.advanceDeduction||0)-Number((Q==null?void 0:Q.autoAdvanceDeduction)||0)),Fa=Math.max(0,Number(_a.loanDeduction||0)-Number((Q==null?void 0:Q.autoLoanDeduction)||0)),zs=Hn+Vs.advance,Bs=Fa+Vs.loan,S=d.overtimeEnabled?Number(_a.overtimeHours||0):0,ye=d.overtimeEnabled?S*Number(d.overtimeRate||0):0,Fe=ye+Number(_a.festivalBonus||0)+Number(_a.performanceBonus||0)+Number(_a.incentive||0)+Number(_a.otherAddition||0),lt=en(E,Le),Ot=lt.eligible?d.pfBasis==="gross"?He:Number((Le==null?void 0:Le.basicSalary)||0):0,Ft=lt.eligible?Math.max(0,Ot*Math.max(0,Number(d.pfEmployeeRate||0))/100):0,rn=lt.eligible?Math.max(0,Ot*Math.max(0,Number(d.pfEmployerRate||0))/100):0,Rn=!!(d.statutoryEnabled&&d.taxEnabled&&(Le!=null&&Le.taxApplicable))&&d.taxEngineMode==="approved_rule"&&!!(Mn&&Mn.status==="approved"),ea=Rn?Math.max(He,0)*12:0,Wn=Rn?Xe(Le):0,Bn=Rn?Ht(ea,Mn,Wn):0,Fn=Rn&&ea>Wn?Jt(Le==null?void 0:Le.taxLocationCategory):0,Na=Rn?Math.max(0,Number((Le==null?void 0:Le.annualEligibleInvestment)||0)):0,ya=Rn?Math.max(0,Math.min(ea*.03,Na*.15,1e6)):0,Ba=Rn?Math.min(Bn,ya):0,Ya=Rn?Math.max(0,Bn-Ba):0,Os=Rn&&ea>Wn?Math.max(Ya,Fn):0,ys=ra(l),_r=Rn?Math.max(0,Number((Ie==null?void 0:Ie.priorVerixoTax)??(Q==null?void 0:Q.taxWithheldPriorMonths)??0)):0,tr=Rn?Math.max(0,Number((Le==null?void 0:Le.taxWithheldBeforeVerixo)||0)):0,wr=_r+tr,Ns=Rn?Math.max(Os-wr,0):0,Wr=Math.max(1,Number((Ie==null?void 0:Ie.monthsRemaining)??(Q==null?void 0:Q.taxMonthsRemaining)??ys.monthsRemaining)),nr=(Ie==null?void 0:Ie.incomeYearLabel)||(Q==null?void 0:Q.taxIncomeYearLabel)||ys.incomeYearLabel,Fs=Rn?Ns/Wr:0,Hs=va+zs+Bs+Number(_a.fineDeduction||0)+Number(_a.otherDeduction||0)+Ft+Fs;let sr=He+Fe-Hs;return d.roundNetPay&&(sr=Math.round(sr)),{employeeId:E.id,employeeCode:E.employeeId,employeeName:E.name,branchId:E.branchId,grossSalary:He,calendarDays:gt,workingDays:da,presentDays:vn,absentDays:Bt,lateCount:zt,halfDayCount:Zn,leaveDays:ca,paidLeaveDays:wn,unpaidLeaveDays:ma,officialDayOffDays:Pa,holidayDays:kn,weeklyOffDays:Kn,lateDeductionDays:Ga,deductibleDays:Ia,perDaySalary:Ua,attendanceDeduction:va,overt
4048imeHours:S,overtimeAmount:ye,festivalBonus:Number(_a.festivalBonus||0),performanceBonus:Number(_a.performanceBonus||0),incentive:Number(_a.incentive||0),otherAddition:Number(_a.otherAddition||0),advanceDeduction:zs,loanDeduction:Bs,autoAdvanceDeduction:Vs.advance,autoLoanDeduction:Vs.loan,advanceLoanRecoveryBreakdown:Vs.rows,fineDeduction:Number(_a.fineDeduction||0),otherDeduction:Number(_a.otherDeduction||0),taxApplicable:Rn,taxRuleVersionId:Rn?Mn==null?void 0:Mn.id:"",annualTaxableIncome:ea,taxFreeThreshold:Wn,taxPayerCategory:(Le==null?void 0:Le.taxPayerCategory)||"general",taxLocationCategory:(Le==null?void 0:Le.taxLocationCategory)||"",minimumAnnualTax:Fn,slabAnnualTax:Bn,annualEligibleInvestment:Na,maximumTaxRebate:ya,appliedTaxRebate:Ba,annualTaxBeforeMinimum:Ya,annualTax:Os,taxIncomeYearLabel:nr,taxWithheldPriorMonths:_r,taxExternalPriorWithheld:tr,taxTotalWithheldBeforeCurrent:wr,taxRemainingLiability:Ns,taxMonthsRemaining:Wr,monthlyTax:Fs,pfEligible:lt.eligible,pfStartDate:lt.startDate,pfBasisAmount:Ot,employeePf:Ft,employerPf:rn,remarks:String(_a.remarks||""),netPay:sr,bankName:String(E.bankName||(Le==null?void 0:Le.bankName)||""),bankAccount:String(E.bankAccount||(Le==null?void 0:Le.bankAccount)||""),bankAccountHolder:String(E.bankAccountHolder||(Le==null?void 0:Le.bankAccountHolder)||E.name||""),paymentStatus:(Q==null?void 0:Q.paymentStatus)||"unpaid",paidAmount:Number((Q==null?void 0:Q.paidAmount)||0),paymentMethod:Q==null?void 0:Q.paymentMethod,paymentDate:Q==null?void 0:Q.paymentDate,paymentReference:Q==null?void 0:Q.paymentReference,paidAt:Q==null?void 0:Q.paidAt,paidByUid:Q==null?void 0:Q.paidByUid,paidByName:Q==null?void 0:Q.paidByName,status:(De==null?void 0:De.status)||"draft",updatedAt:Date.now()}},bs=async(E=!1)=>{if(B){le(`Payroll generate blocked: employee data source cannot be read (${B}). Existing payroll data was not changed.`);return}if(z.length===0){le(`Payroll generate blocked: employees/${t.companyId} returned 0 active employees. Existing payroll data was not changed.`);return}if($a.length===0){le(a&&a!=="all"?"Payroll generate blocked: the selected branch has 0 visible employees. Select All Branches or verify employee branch assignment. Existing payroll data was not changed.":"Payroll generate blocked: no visible employees were found. Existing payroll data was not changed.");return}if(d.statutoryEnabled&&d.taxEnabled&&d.taxEngineMode==="approved_rule"){const Q=$a.filter(Ie=>{const Le=Z[Ie.id]||q[Ie.id];if(!(Le!=null&&Le.taxApplicable))return!1;const He=Math.max(Number((Le==null?void 0:Le.grossSalary)||0),0)*12,gt=Xe(Le);return He>gt&&!(Le!=null&&Le.taxLocationCategory)});if(Q.length>0){le(`Payroll generate blocked: ${Q.length} taxable employee(s) need Tax Location in Salary Structure before minimum tax can be calculated.`);return}}if(De&&De.status!=="draft"){le(De.status==="approved"?"Approved payroll is frozen. Return it to Draft with an authorized reason before regenerating.":"Locked payroll cannot be regenerated. Use the correction workflow if a change is required.");return}if(jn.hasWarnings&&E!==!0){sn(!0);return}sn(!1),Ye(!0),le("");try{const Q={},Ie=ra(l),Le={};d.statutoryEnabled&&d.taxEnabled&&d.taxEngineMode==="approved_rule"&&Ie.priorMonths.length&&(await Promise.all(Ie.priorMonths.map(Bt=>mn(re(ie,`payrollItems/${t.companyId}/${Bt}`))))).forEach(Bt=>{const En=Bt.exists()?Bt.val():{};Object.values(En||{}).forEach(wn=>{Le[wn.employeeId]=(Le[wn.employeeId]||0)+Math.max(0,Number(wn.monthlyTax||0))})}),$a.forEach(zt=>{Q[zt.id]=qa(zt,P[zt.id],{priorVerixoTax:Le[zt.id]||0,monthsRemaining:Ie.monthsRemaining,incomeYearLabel:Ie.incomeYearLabel})});const He=JSON.parse(JSON.stringify(Q)),gt=Object.values(He),Dt=gt.reduce((zt,Bt)=>({gross:zt.gross+Bt.grossSalary,deduction:zt.deduction+Bt.attendanceDeduction+Bt.advanceDeduction+Bt.loanDeduction+Bt.fineDeduction+Bt.otherDeduction+Number(Bt.employeePf||0)+Number(Bt.monthlyTax||0),addition:zt.addition+Bt.overtimeAmount+Bt.festivalBonus+Bt.performanceBonus+Bt.incentive+Bt.otherAddition,tax:zt.tax+Number(Bt.monthlyTax||0),employeePf:zt.employeePf+Number(Bt.employeePf||0),employerPf:zt.employerPf+Number(Bt.employerPf||0),net:zt.net+Bt.netPay}),{gross:0,deduction:0,addition:0,tax:0,employeePf:0,employerPf:0,net:0}),Yt={month:l,status:"draft",employeeCount:gt.length,grossTotal:Dt.gross,deductionTotal:Dt.deduction,additionTotal:Dt.addition,netTotal:Dt.net,taxTotal:Dt.tax,employeePfTotal:Dt.employeePf,employerPfTotal:Dt.employerPf,generatedAt:Date.now(),generatedByUid:t.uid,generatedByName:t.name,paymentStatus:"unpaid",correctionStatus:"none"};await yn(re(ie),{[`payrollItems/${t.companyId}/${l}`]:He,[`payrollRuns/${t.companyId}/${l}`]:Yt});try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.generated",entityType:"payrollRun",entityId:l,summary:`Generated payroll for ${l}`})}catch(zt){console.error("Payroll generated but audit log write failed:",zt)}const vn=gt.filter(zt=>zt.grossSalary<=0).length;le(vn>0?`Payroll generated for ${gt.length} employees. ${vn} employee(s) have no gross salary yet.`:`Payroll generated for ${gt.length} employees.`),c("run")}catch(Q){console.error("Payroll generate/regenerate failed:",Q);const Ie=Q instanceof Error?Q.message:String(Q);le(`Payroll generate failed: ${Ie}`)}finally{Ye(!1)}},Wa=async(E,Q,Ie)=>{if(De!=null&&De.status&&De.status!=="draft"){le("Approved/locked payroll is read-only. Reopen it through the correction workflow before editing.");return}const Le=z.find(vn=>vn.id===E);if(!Le)return;const He=P[E],gt=ra(l),Dt=qa(Le,{...He,[Q]:Ie},{priorVerixoTax:Number((He==null?void 0:He.taxWithheldPriorMonths)||0),monthsRemaining:Number((He==null?void 0:He.taxMonthsRemaining)||gt.monthsRemaining),incomeYearLabel:(He==null?void 0:He.taxIncomeYearLabel)||gt.incomeYearLabel}),Yt=JSON.parse(JSON.stringify(Dt));await Pn(re(ie,`payrollItems/${t.companyId}/${l}/${E}`),Yt)},$s=async()=>{const E=await mn(re(ie,`accountingAccounts/${t.companyId}`));return E.exists()?Object.entries(E.val()).map(([Q,Ie])=>({id:Q,...Ie})).filter(Q=>Q.active!==!1&&!Q.isGroup):[]},jr=async()=>{const E=await $s(),Q=E.find(Yt=>Yt.systemKey==="payroll_recovery_clearing")||E.find(Yt=>Yt.code==="2290");if(Q)return Q;const Ie=await mn(re(ie,`accountingAccounts/${t.companyId}`));if(!Ie.exists())throw new Error("Accounts & Finance Chart of Accounts is not initialized yet.");const Le=Object.entries(Ie.val()).map(([Yt,vn])=>({id:Yt,...vn})),He=Le.find(Yt=>String(Yt.code||"")==="2000")||Le.find(Yt=>String(Yt.code||"").startsWith("2")&&!!Yt.isGroup),gt="acct_2290",Dt={code:"2290",name:"Payroll Recovery Clearing",type:"liability",parentId:String((He==null?void 0:He.id)||"acct_2000"),isGroup:!1,normalBalance:"credit",systemKey:"payroll_recovery_clearing",active:!0,createdAt:Date.now(),updatedAt:Date.now()};return await Pn(re(ie,`accountingAccounts/${t.companyId}/${gt}`),Dt),{id:gt,...Dt}},Kr=async(E,Q)=>{await jr();const Ie=await $s();if(!Ie.length)return{};const Le=(wn,ma)=>Ie.find(ca=>ca.systemKey===wn)||Ie.find(ca=>ca.code===ma),He=Le("salary_expense","6100"),gt=Le("salary_payable","2200"),Dt=Le("tax_payable","2400"),Yt=Le("pf_payable","2500"),vn=Le("payroll_recovery_clearing","2290"),zt=Le("accounts_receivable","1200");if(!He||!gt)throw new Error("Payroll accounting requires Salary & Wages (6100) and Salary Payable (2200) accounts.");const Bt=new Map;
4048(Q||_n).forEach(wn=>{const ma=wn.branchId||"company",ca=Bt.get(ma)||[];ca.push(wn),Bt.set(ma,ca)});const En={};for(const[wn,ma]of Bt.entries()){const ca=n.find(va=>va.id===wn),Pa=String((ca==null?void 0:ca.code)||wn||"COMPANY").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10)||"COMPANY",kn=`payroll_${l.replace(/[^0-9]/g,"")}_${Pa}`,Kn=`${Pa}-PAY-JV-${l.replace("-","")}`,Zn=Hv(l),da=ma.reduce((va,_a)=>{const Vs=Number(_a.overtimeAmount||0)+Number(_a.festivalBonus||0)+Number(_a.performanceBonus||0)+Number(_a.incentive||0)+Number(_a.otherAddition||0),Hn=Math.max(Number(_a.autoAdvanceDeduction||0),0),Fa=Math.max(Number(_a.autoLoanDeduction||0),0),zs=Math.max(Number(_a.advanceDeduction||0)-Hn,0),Bs=Math.max(Number(_a.loanDeduction||0)-Fa,0);return va.salaryExpense+=Number(_a.grossSalary||0)+Vs-Number(_a.attendanceDeduction||0)-Number(_a.fineDeduction||0)-Number(_a.otherDeduction||0)-zs-Bs+Number(_a.employerPf||0),va.salaryPayable+=Math.max(Number(_a.netPay||0),0),va.employeeRecoverable+=Math.max(-Number(_a.netPay||0),0),va.tax+=Math.max(Number(_a.monthlyTax||0),0),va.pf+=Math.max(Number(_a.employeePf||0),0)+Math.max(Number(_a.employerPf||0),0),va.advance+=Hn,va.loan+=Fa,va},{salaryExpense:0,salaryPayable:0,employeeRecoverable:0,tax:0,pf:0,advance:0,loan:0}),Ga=[],Da=(va,_a,Vs,Hn)=>{if(!(Math.max(_a,Vs)<=.004)){if(!va)throw new Error(`Payroll accounting account missing for: ${Hn}`);Ga.push({account:va,debit:_a,credit:Vs,narration:Hn})}};Da(He,da.salaryExpense,0,`Payroll expense · ${l}`),Da(zt,da.employeeRecoverable,0,`Employee payroll recoverable · ${l}`),Da(gt,0,da.salaryPayable,`Salary payable · ${l}`),Da(Dt,0,da.tax,`Payroll tax payable · ${l}`),Da(Yt,0,da.pf,`Payroll provident fund payable · ${l}`),Da(vn,0,da.advance+da.loan,`Advance/Loan allocated in payroll · awaiting salary payment · ${l}`);const Ia=Ga.reduce((va,_a)=>va+_a.debit,0),ls=Ga.reduce((va,_a)=>va+_a.credit,0);if(Math.abs(Ia-ls)>.02)throw new Error(`Payroll accounting journal is not balanced for ${(ca==null?void 0:ca.name)||Pa}: Dr ${Ia.toFixed(2)} / Cr ${ls.toFixed(2)}.`);for(let va=1;va<=10;va+=1){const _a=`${kn}_${String(va).padStart(3,"0")}`;En[`accountingLedgerEntries/${t.companyId}/${_a}`]=null}const Ua=Ga.map((va,_a)=>({id:`line_${String(_a+1).padStart(3,"0")}`,accountId:va.account.id,accountCode:va.account.code,accountName:va.account.name,debit:Number(va.debit.toFixed(2)),credit:Number(va.credit.toFixed(2)),narration:va.narration}));En[`accountingVouchers/${t.companyId}/${kn}`]={voucherNo:Kn,type:"journal",status:"posted",voucherDate:Zn,branchId:wn==="company"?"":wn,reference:`Payroll ${l}`,narration:`Payroll posting · ${l}${ca!=null&&ca.name?` · ${ca.name}`:""}`,lines:Ua,totalDebit:Number(Ia.toFixed(2)),totalCredit:Number(ls.toFixed(2)),createdAt:E,createdByUid:t.uid,createdByName:t.name,updatedAt:E,postedAt:E,postedByUid:t.uid,postedByName:t.name,sourceType:"payroll",sourceId:l},Ua.forEach((va,_a)=>{const Vs=`${kn}_${String(_a+1).padStart(3,"0")}`;En[`accountingLedgerEntries/${t.companyId}/${Vs}`]={id:Vs,voucherId:kn,voucherNo:Kn,voucherType:"journal",voucherDate:Zn,branchId:wn==="company"?"":wn,reference:`Payroll ${l}`,narration:va.narration,accountId:va.accountId,accountCode:va.accountCode,accountName:va.accountName,debit:va.debit,credit:va.credit,status:"posted",createdAt:E,postedByUid:t.uid,postedByName:t.name,sourceType:"payroll",sourceId:l}})}return En},Xr=async()=>{const E=await $s(),Q=E.find(Yt=>Yt.systemKey==="payroll_rounding_adjustment")||E.find(Yt=>Yt.code==="4310");if(Q)return Q;const Ie=await mn(re(ie,`accountingAccounts/${t.companyId}`));if(!Ie.exists())throw new Error("Accounts & Finance Chart of Accounts is not initialized yet.");const Le=Object.entries(Ie.val()).map(([Yt,vn])=>({id:Yt,...vn})),He=Le.find(Yt=>String(Yt.code||"")==="4000")||Le.find(Yt=>String(Yt.code||"").startsWith("4")&&!!Yt.isGroup),gt="acct_4310",Dt={code:"4310",name:"Payroll Rounding Adjustment",type:"income",parentId:String((He==null?void 0:He.id)||"acct_4000"),isGroup:!1,normalBalance:"credit",systemKey:"payroll_rounding_adjustment",active:!0,createdAt:Date.now(),updatedAt:Date.now()};return await Pn(re(ie,`accountingAccounts/${t.companyId}/${gt}`),Dt),{id:gt,...Dt}},Rr=async E=>{var Le;const Q=await mn(re(ie,`accountingSettings/${t.companyId}`)),Ie=String(((Le=Q.val())==null?void 0:Le.lockedThrough)||"");if(Ie&&E.slice(0,7)<=Ie)throw new Error(`Accounting period ${E.slice(0,7)} is locked.`)},er=async(E,Q,Ie=!0)=>{await Rr(Q.paymentDate);const Le=await $s(),He=(Ua,va)=>Le.find(_a=>_a.systemKey===Ua)||Le.find(_a=>_a.code===va),gt=He("salary_payable","2200"),Dt=He("cash","1110");if(!gt)throw new Error("Salary Payable (2200) account is missing.");let Yt;if(Q.method==="cash"&&(Yt=Dt),Q.method==="bank"){if(Yt=Le.find(Ua=>Ua.id===Q.sourceBankLedgerAccountId),!Yt&&Q.sourceBankLedgerCode){const Ua=Le.filter(va=>va.code===Q.sourceBankLedgerCode);Ua.length===1&&(Yt=Ua[0])}if(!Yt&&Q.sourceBankLedgerName){const Ua=Le.filter(va=>va.name===Q.sourceBankLedgerName);Ua.length===1&&(Yt=Ua[0])}}if(!Yt)throw new Error(Q.method==="bank"?"Selected company bank does not have a valid linked accounting ledger.":"Cash in Hand (1110) account is missing.");
4048const vn=Math.max(-Number(Q.roundingAdjustment||0),0),zt=Math.max(Number(Q.settledAmount??Q.amount??0),0),Bt=Math.max(Number(Q.amount||0),0);if(zt<=.004||Bt<=.004)return{};if(Math.abs(zt-Bt-vn)>.02)throw new Error("Salary payment rounding accounting is inconsistent.");const En=vn>.004?await Xr():void 0,wn=Q.id.replace(/[^A-Za-z0-9_-]/g,"_"),ma=String(E.employeeCode||E.employeeId||"EMP").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,14)||"EMP",ca=n.find(Ua=>Ua.id===E.branchId),Pa=String((ca==null?void 0:ca.code)||E.branchId||"COMPANY").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10)||"COMPANY",kn=`salary_payment_${l.replace(/[^0-9]/g,"")}_${ma}_${wn}`,Kn=`${Pa}-SAL-PV-${l.replace("-","")}-${ma}-${wn.slice(-6).toUpperCase()}`,Zn=[{account:gt,debit:zt,credit:0,narration:`Salary payable settled · ${E.employeeName} · ${l}`},{account:Yt,debit:0,credit:Bt,narration:`Salary paid by ${Q.method} · ${E.employeeName} · ${l}`},...vn>.004&&En?[{account:En,debit:0,credit:vn,narration:`Salary rounding settlement · ${E.employeeName} · ${l}`}]:[]],da=Zn.reduce((Ua,va)=>Ua+va.debit,0),Ga=Zn.reduce((Ua,va)=>Ua+va.credit,0);if(Math.abs(da-Ga)>.02)throw new Error(`Salary payment journal is not balanced: Dr ${da.toFixed(2)} / Cr ${Ga.toFixed(2)}.`);const Da=Date.now(),Ia=Zn.map((Ua,va)=>({id:`line_${String(va+1).padStart(3,"0")}`,accountId:Ua.account.id,accountCode:Ua.account.code,accountName:Ua.account.name,debit:Number(Ua.debit.toFixed(2)),credit:Number(Ua.credit.toFixed(2)),narration:Ua.narration})),ls={[`accountingVouchers/${t.companyId}/${kn}`]:{voucherNo:Kn,type:"payment",status:"posted",voucherDate:Q.paymentDate,branchId:E.branchId||"",reference:Q.reference||Kn,narration:`Salary Payment · ${E.employeeName} · ${l}`,lines:Ia,totalDebit:Number(da.toFixed(2)),totalCredit:Number(Ga.toFixed(2)),createdAt:Q.createdAt||Da,createdByUid:Q.createdByUid||t.uid,createdByName:Q.createdByName||t.name,updatedAt:Da,postedAt:Da,postedByUid:t.uid,postedByName:t.name,sourceType:"salary_payment",sourceId:`${l}:${E.employeeId}:${Q.id}`,autoPosted:!0,paymentMethod:Q.method,paymentReference:Q.reference||""}};return Ie?ls[`payrollPayments/${t.companyId}/${l}/${E.employeeId}/${Q.id}/accountingVoucherId`]=kn:Q.accountingVoucherId=kn,Ia.forEach((Ua,va)=>{const _a=`${kn}_${String(va+1).padStart(3,"0")}`;ls[`accountingLedgerEntries/${t.companyId}/${_a}`]={id:_a,voucherId:kn,voucherNo:Kn,voucherType:"payment",voucherDate:Q.paymentDate,branchId:E.branchId||"",reference:Q.reference||Kn,narration:Ua.narration,accountId:Ua.accountId,accountCode:Ua.accountCode,accountName:Ua.accountName,debit:Ua.debit,credit:Ua.credit,status:"posted",createdAt:Q.createdAt||Da,postedByUid:t.uid,postedByName:t.name,sourceType:"salary_payment",sourceId:`${l}:${E.employeeId}:${Q.id}`,autoPosted:!0}}),ls},Ir=async(E,Q,Ie)=>{const Le=Q.id.replace(/[^A-Za-z0-9_-]/g,"_"),He=String(E.employeeCode||E.employeeId||"EMP").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,14)||"EMP",gt=Q.accountingVoucherId||`salary_payment_${l.replace(/[^0-9]/g,"")}_${He}_${Le}`,Dt=await mn(re(ie,`accountingVouchers/${t.companyId}/${gt}`));if(!Dt.exists())return{};const Yt=Dt.val(),vn=Array.isArray(Yt.lines)?Yt.lines:[];if(!vn.length)return{};
4048const zt=new Date().toISOString().slice(0,10);await Rr(zt);const Bt=`${gt}_REV`,En=`${String(Yt.voucherNo||"SAL-PV")}-REV`,wn=Date.now(),ma=vn.map((Kn,Zn)=>({id:`line_${String(Zn+1).padStart(3,"0")}`,accountId:Kn.accountId,accountCode:Kn.accountCode,accountName:Kn.accountName,debit:Number(Kn.credit||0),credit:Number(Kn.debit||0),narration:`Reversal · ${Kn.narration||"Salary payment"} · ${Ie}`})),ca=ma.reduce((Kn,Zn)=>Kn+Zn.debit,0),Pa=ma.reduce((Kn,Zn)=>Kn+Zn.credit,0),kn={[`accountingVouchers/${t.companyId}/${Bt}`]:{voucherNo:En,type:"journal",status:"posted",voucherDate:zt,branchId:Yt.branchId||E.branchId||"",reference:`Salary payment reversal · ${E.employeeName} · ${l}`,narration:`Salary payment reversal: ${Ie}`,lines:ma,totalDebit:Number(ca.toFixed(2)),totalCredit:Number(Pa.toFixed(2)),createdAt:wn,createdByUid:t.uid,createdByName:t.name,updatedAt:wn,postedAt:wn,postedByUid:t.uid,postedByName:t.name,sourceType:"salary_payment_reversal",sourceId:`${l}:${E.employeeId}:${Q.id}`,autoPosted:!0},[`payrollPayments/${t.companyId}/${l}/${E.employeeId}/${Q.id}/accountingReversalVoucherId`]:Bt};return ma.forEach((Kn,Zn)=>{const da=`${Bt}_${String(Zn+1).padStart(3,"0")}`;kn[`accountingLedgerEntries/${t.companyId}/${da}`]={id:da,voucherId:Bt,voucherNo:En,voucherType:"journal",voucherDate:zt,branchId:Yt.branchId||E.branchId||"",reference:`Salary payment reversal · ${E.employeeName} · ${l}`,narration:Kn.narration,accountId:Kn.accountId,accountCode:Kn.accountCode,accountName:Kn.accountName,debit:Kn.debit,credit:Kn.credit,status:"posted",createdAt:wn,postedByUid:t.uid,postedByName:t.name,sourceType:"salary_payment_reversal",sourceId:`${l}:${E.employeeId}:${Q.id}`,autoPosted:!0}}),kn},Qo=async()=>{const E={};for(const Q of _n){const Ie=Object.values(me[Q.employeeId]||{}).filter(Le=>Le.status!=="reversed");for(const Le of Ie)Object.assign(E,await er(Q,Le))}return E},fo=async(E,Q,Ie)=>{const Le=E.advanceLoanRecoveryBreakdown||[];if(!Le.length)return{};await jr();const He=await $s(),gt=(Ia,ls)=>He.find(Ua=>Ua.systemKey===Ia)||He.find(Ua=>Ua.code===ls),Dt=gt("payroll_recovery_clearing","2290"),Yt=gt("employee_salary_advance_receivable","1410"),vn=gt("employee_loan_receivable","1420");if(!Dt)throw new Error("Payroll Recovery Clearing (2290) account is missing.");const zt=Le.filter(Ia=>Ia.type==="advance").reduce((Ia,ls)=>Ia+Math.max(0,Number(ls.amount||0)),0),Bt=Le.filter(Ia=>Ia.type==="loan").reduce((Ia,ls)=>Ia+Math.max(0,Number(ls.amount||0)),0),En=zt+Bt;if(En<=.004)return{};if(zt>.004&&!Yt)throw new Error("Employee Salary Advance Receivable (1410) account is missing.");if(Bt>.004&&!vn)throw new Error("Employee Loan Receivable (1420) account is missing.");const wn=n.find(Ia=>Ia.id===E.branchId),ma=String((wn==null?void 0:wn.code)||E.branchId||"COMPANY").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10)||"COMPANY",ca=String(E.employeeCode||E.employeeId||"EMP").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,14)||"EMP",Pa=Ie.replace(/[^A-Za-z0-9_-]/g,"_"),kn=`payroll_recovery_${l.replace(/[^0-9]/g,"")}_${ca}_${Pa}`,Kn=`${ma}-REC-JV-${l.replace("-","")}-${ca}`,Zn=[{account:Dt,debit:En,credit:0,narration:`Payroll Advance/Loan allocation settled · ${E.employeeName} · ${l}`}];zt>.004&&Yt&&Zn.push({account:Yt,debit:0,credit:zt,narration:`Salary Advance recovered on salary payment · ${E.employeeName} · ${l}`}),Bt>.004&&vn&&Zn.push({account:vn,debit:0,credit:Bt,narration:`Employee Loan recovered on salary payment · ${E.employeeName} · ${l}`});const da=Date.now(),Ga={},Da=Zn.map((Ia,ls)=>({id:`line_${String(ls+1).padStart(3,"0")}`,accountId:Ia.account.id,accountCode:Ia.account.code,accountName:Ia.account.name,debit:Number(Ia.debit.toFixed(2)),credit:Number(Ia.credit.toFixed(2)),narration:Ia.narration}));return Ga[`accountingVouchers/${t.companyId}/${kn}`]={voucherNo:Kn,type:"journal",status:"posted",voucherDate:Q,branchId:E.branchId||"",reference:`Salary payment recovery · ${E.employeeName} · ${l}`,narration:"Advance/Loan recovery finalized on actual salary payment date",lines:Da,totalDebit:Number(En.toFixed(2)),totalCredit:Number(En.toFixed(2)),createdAt:da,createdByUid:t.uid,createdByName:t.name,updatedAt:da,postedAt:da,postedByUid:t.uid,postedByName:t.name,sourceType:"payroll_recovery_settlement",sourceId:`${l}:${E.employeeId}:${Ie}`}
4048,Da.forEach((Ia,ls)=>{const Ua=`${kn}_${String(ls+1).padStart(3,"0")}`;Ga[`accountingLedgerEntries/${t.companyId}/${Ua}`]={id:Ua,voucherId:kn,voucherNo:Kn,voucherType:"journal",voucherDate:Q,branchId:E.branchId||"",reference:`Salary payment recovery · ${E.employeeName} · ${l}`,narration:Ia.narration,accountId:Ia.accountId,accountCode:Ia.accountCode,accountName:Ia.accountName,debit:Ia.debit,credit:Ia.credit,status:"posted",createdAt:da,postedByUid:t.uid,postedByName:t.name,sourceType:"payroll_recovery_settlement",sourceId:`${l}:${E.employeeId}:${Ie}`}}),Ga[`payrollItems/${t.companyId}/${l}/${E.employeeId}/recoverySettlementTxId`]=Ie,Ga[`payrollItems/${t.companyId}/${l}/${E.employeeId}/recoverySettlementVoucherId`]=kn,Ga},Jo=async(E,Q,Ie)=>{const Le=E.recoverySettlementVoucherId;if(!Le)return{};const He=await mn(re(ie,`accountingVouchers/${t.companyId}/${Le}`));if(!He.exists())return{};const gt=He.val(),Dt=Array.isArray(gt.lines)?gt.lines:[];if(!Dt.length)return{};const Yt=Date.now(),vn=new Date().toISOString().slice(0,10),zt=Q.replace(/[^A-Za-z0-9_-]/g,"_"),Bt=`${Le}_REV_${zt}`,En=`${String(gt.voucherNo||"REC-JV")}-REV`,wn=Dt.map((kn,Kn)=>({id:`line_${String(Kn+1).padStart(3,"0")}`,accountId:kn.accountId,accountCode:kn.accountCode,accountName:kn.accountName,debit:Number(kn.credit||0),credit:Number(kn.debit||0),narration:`Reversal · ${kn.narration||"Payroll recovery settlement"} · ${Ie}`})),ma=wn.reduce((kn,Kn)=>kn+Kn.debit,0),ca=wn.reduce((kn,Kn)=>kn+Kn.credit,0),Pa={[`accountingVouchers/${t.companyId}/${Bt}`]:{voucherNo:En,type:"journal",status:"posted",voucherDate:vn,branchId:gt.branchId||E.branchId||"",reference:`Recovery reversal · ${E.employeeName} · ${l}`,narration:`Salary payment reversal: ${Ie}`,lines:wn,totalDebit:Number(ma.toFixed(2)),totalCredit:Number(ca.toFixed(2)),createdAt:Yt,createdByUid:t.uid,createdByName:t.name,updatedAt:Yt,postedAt:Yt,postedByUid:t.uid,postedByName:t.name,sourceType:"payroll_recovery_reversal",sourceId:`${l}:${E.employeeId}:${Q}`},[`payrollItems/${t.companyId}/${l}/${E.employeeId}/recoverySettlementTxId`]:null,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/recoverySettlementVoucherId`]:null};return wn.forEach((kn,Kn)=>{const Zn=`${Bt}_${String(Kn+1).padStart(3,"0")}`;Pa[`accountingLedgerEntries/${t.companyId}/${Zn}`]={id:Zn,voucherId:Bt,voucherNo:En,voucherType:"journal",voucherDate:vn,branchId:gt.branchId||E.branchId||"",reference:`Recovery reversal · ${E.employeeName} · ${l}`,narration:kn.narration,accountId:kn.accountId,accountCode:kn.accountCode,accountName:kn.accountName,debit:kn.debit,credit:kn.credit,status:"posted",createdAt:Yt,postedByUid:t.uid,postedByName:t.name,sourceType:"payroll_recovery_reversal",sourceId:`${l}:${E.employeeId}:${Q}`}}),Pa},pr=E=>{const Q=Math.max(Number(E.netPay||0),0),Ie=Object.values(me[E.employeeId]||{}).filter(vn=>vn.status!=="reversed").sort((vn,zt)=>Number(vn.createdAt||0)-Number(zt.createdAt||0)),Le=Ie.reduce((vn,zt)=>vn+Math.max(0,Number(zt.settledAmount??zt.amount??0)),0),He=Math.min(Le,Q),gt=Math.max(Q-He,0),Dt=Q<=0||He+.004>=Q?"paid":He<=.004?"unpaid":"partially_paid",Yt=Ie.length?Ie[Ie.length-1]:null;return{payable:Q,paid:He,outstanding:gt,status:Dt,transactions:Ie,latestTx:Yt}},Or=()=>{const E={};let Q=0,Ie=0;_n.forEach(He=>{const gt=pr(He);Q+=gt.paid,Ie+=gt.outstanding,E[`payrollItems/${t.companyId}/${l}/${He.employeeId}/paidAmount`]=gt.paid,E[`payrollItems/${t.companyId}/${l}/${He.employeeId}/paymentStatus`]=gt.status,gt.latestTx&&(E[`payrollItems/${t.companyId}/${l}/${He.employeeId}/paymentMethod`]=gt.latestTx.method,E[`payrollItems/${t.companyId}/${l}/${He.employeeId}/paymentDate`]=gt.latestTx.paymentDate,E[`payrollItems/${t.companyId}/${l}/${He.employeeId}/paymentReference`]=gt.latestTx.reference||""),E[`payrollPayables/${t.companyId}/${l}/employees/${He.employeeId}/paidAmount`]=gt.paid,E[`payrollPayables/${t.companyId}/${l}/employees/${He.employeeId}/outstandingAmount`]=gt.outstanding,E[`payrollPayables/${t.companyId}/${l}/employees/${He.employeeId}/paymentStatus`]=gt.status});const Le=Q<=.004?"unpaid":Ie<=.004?"paid":"partially_paid";return E[`payrollRuns/${t.companyId}/${l}/paidTotal`]=Q,E[`payrollRuns/${t.companyId}/${l}/outstandingTotal`]=Ie,E[`payrollRuns/${t.companyId}/${l}/paymentStatus`]=Le,E[`payrollPayables/${t.companyId}/${l}/paidTotal`]=Q,E[`payrollPayables/${t.companyId}/${l}/outstandingTotal`]=Ie,E[`payrollPayables/${t.companyId}/${l}/paymentStatus`]=Le,E},Js=E=>{const Q=pr(E);if(Q.payable<=0||Q.status!=="paid")return null;let Ie=0;for(const Le of Q.transactions)if(Ie+=Math.max(Number(Le.settledAmount??Le.amount??0),0),Ie+.004>=Q.payable)return Le;return null},Ko=async()=>{const E={};for(const Q of _n){if(!(Q.advanceLoanRecoveryBreakdown||[]).length)continue;const Ie=Js(Q);Ie&&(Object.assign(E,await fo(Q,Ie.paymentDate,Ie.id)),Object.assign(E,$i(Q.employeeId,Ie.paymentDate)))}return E},to=()=>{const E={},Q=new Map;
4048return _n.forEach(Ie=>{(Ie.advanceLoanRecoveryBreakdown||[]).forEach(Le=>{Q.set(Le.recordId,(Q.get(Le.recordId)||0)+Math.max(0,Number(Le.amount||0)))})}),K.forEach(Ie=>{(Q.get(Ie.id)||0)<=.004||(E[`employeeAdvanceLoans/${t.companyId}/${Ie.id}/status`]="active",E[`employeeAdvanceLoans/${t.companyId}/${Ie.id}/recoveryState`]="allocated",E[`employeeAdvanceLoans/${t.companyId}/${Ie.id}/lastAllocatedPayrollMonth`]=l,E[`employeeAdvanceLoans/${t.companyId}/${Ie.id}/lastAllocatedAt`]=Date.now(),E[`employeeAdvanceLoans/${t.companyId}/${Ie.id}/completedAt`]=null,E[`employeeAdvanceLoans/${t.companyId}/${Ie.id}/completedByPayrollMonth`]=null)}),E},$i=(E,Q)=>{const Ie={},Le=new Map;Object.entries(D||{}).forEach(([gt,Dt])=>{Object.values(Dt||{}).forEach(Yt=>{Yt.employeeId!==E||Yt.status!=="locked"||gt===l||!(Yt.paymentStatus==="paid")||(Yt.advanceLoanRecoveryBreakdown||[]).forEach(zt=>{Le.set(zt.recordId,(Le.get(zt.recordId)||0)+Math.max(0,Number(zt.amount||0)))})})});const He=P[E];return(He==null?void 0:He.status)==="locked"&&(He.advanceLoanRecoveryBreakdown||[]).forEach(gt=>{Object.values((D==null?void 0:D[l])||{}).some(Yt=>Yt.employeeId===E&&Yt.paymentStatus==="paid")||Le.set(gt.recordId,(Le.get(gt.recordId)||0)+Math.max(0,Number(gt.amount||0)))}),K.forEach(gt=>{if(gt.employeeId!==E)return;const Dt=Math.min(Math.max(Number(gt.amount||0),0),Le.get(gt.id)||0);Dt<=.004||(Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/recoveredAmount`]=Dt,Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/lastRecoveredAt`]=Date.now(),Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/lastRecoveredDate`]=Q,Dt+.004>=Math.max(Number(gt.amount||0),0)?(Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/status`]="completed",Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/recoveryState`]="recovered",Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/completedAt`]=Date.now(),Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/completedByPayrollMonth`]=l,Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/recoveredDate`]=Q):(Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/status`]="active",Ie[`employeeAdvanceLoans/${t.companyId}/${gt.id}/recoveryState`]="partially_recovered"))}),Ie},Bc=async()=>{if(!De){le("Generate a payroll before running the health check.");return}Ye(!0);try{const E=[];if(_n.forEach(Ie=>{const Le=pr(Ie),He=Ie.paymentStatus||"unpaid",gt=Math.max(0,Number(Ie.paidAmount||0));He!==Le.status&&E.push(`${Ie.employeeName}: stored payment status is ${He}, but Payment History resolves to ${Le.status}.`),Math.abs(gt-Le.paid)>.01&&E.push(`${Ie.employeeName}: stored paid amount differs from Payment History by BDT ${pn(Math.abs(gt-Le.paid))}.`);const Dt=(Ie.advanceLoanRecoveryBreakdown||[]).length>0;Dt&&Le.status==="paid"&&!Ie.recoverySettlementVoucherId&&E.push(`${Ie.employeeName}: salary is fully paid but Advance/Loan recovery settlement is missing.`),Dt&&Le.status!=="paid"&&Ie.recoverySettlementVoucherId&&E.push(`${Ie.employeeName}: recovery settlement exists although salary is not fully paid.`)}),De.status==="locked"){const Ie=await mn(re(ie,`accountingVouchers/${t.companyId}`)),He=(Ie.exists()?Object.values(Ie.val()):[]).filter(Dt=>["payroll","payroll_recovery_settlement","payroll_recovery_reversal"].includes(String((Dt==null?void 0:Dt.sourceType)||""))&&String((Dt==null?void 0:Dt.sourceId)||"").startsWith(l));He.forEach(Dt=>{const Yt=Number((Dt==null?void 0:Dt.totalDebit)||0),vn=Number((Dt==null?void 0:Dt.totalCredit)||0);Math.abs(Yt-vn)>.02&&E.push(`${(Dt==null?void 0:Dt.voucherNo)||"Payroll journal"}: accounting journal is not balanced (Dr ${pn(Yt)} / Cr ${pn(vn)}).`)});const gt=new Map;He.filter(Dt=>(Dt==null?void 0:Dt.sourceType)==="payroll_recovery_settlement").forEach(Dt=>{const Yt=String((Dt==null?void 0:Dt.sourceId)||"");gt.set(Yt,(gt.get(Yt)||0)+1)}),gt.forEach((Dt,Yt)=>{Yt&&Dt>1&&E.push(`Duplicate recovery settlement detected for ${Yt}.`)})}const Q={checkedAt:Date.now(),status:E.length?"warning":"healthy",issues:E};xt(Q),le(E.length?`Payroll Health Check found ${E.length} issue${E.length===1?"":"s"}. Use Sync Accounts for repairable reconciliation issues.`:"Payroll Health Check passed. Payment, Advance/Loan recovery and accounting invariants are consistent.")}catch(E){const Q=E instanceof Error?E.message:String(E);xt({checkedAt:Date.now(),status:"warning",issues:[`Health Check could not complete: ${Q}`]}),le(`Payroll Health Check failed: ${Q}`)}finally{Ye(!1)}},no=async()=>
4048{if(!(!De||De.status!=="locked")){Ye(!0),le("");try{const E=Date.now(),Q=await Kr(E),Ie=to(),Le=Or(),He=await Ko(),gt=await Qo();await yn(re(ie),{...Q,...Ie,...Le,...He,...gt,[`payrollRuns/${t.companyId}/${l}/accountsSyncedAt`]:E,[`payrollRuns/${t.companyId}/${l}/accountsSyncedByUid`]:t.uid,[`payrollRuns/${t.companyId}/${l}/accountsSyncedByName`]:t.name}),xt(null),le("Accounts and salary payment status reconciled from Payment History. Run Health Check to verify the repaired payroll.")}catch(E){console.error("Locked payroll accounting sync failed:",E),le(`Accounts sync failed: ${E instanceof Error?E.message:String(E)}`)}finally{Ye(!1)}}},Fc=async()=>{var Ie;if(!De||De.status!=="locked"||!wa)return;const E=z.find(Le=>Le.id===ee);if(!E){le("Select an employee to add to this locked payroll.");return}if(P[E.id]){le(`${E.name} is already included in ${l} payroll.`);return}if(E.joiningDate&&E.joiningDate>Hv(l)){le(`${E.name} joined after ${l}; the employee cannot be added to this payroll.`);return}const Q=(Ie=window.prompt(`Reason for adding ${E.name} to locked payroll ${l}:`))==null?void 0:Ie.trim();if(Q&&window.confirm(`Add ${E.name} to locked payroll ${l}? 4049 4050Existing employee payroll rows and payment history will not be recalculated.`)){Ye(!0),le("");try{const Le=Date.now(),He={...qa(E),status:"locked",paymentStatus:"unpaid",paidAmount:0,updatedAt:Le};if(He.grossSalary<=0)throw new Error("Gross Salary is missing for this employee.");const gt=[..._n,He],Dt=gt.reduce((Zn,da)=>Zn+Number(da.grossSalary||0),0),Yt=gt.reduce((Zn,da)=>Zn+Number(da.attendanceDeduction||0)+Number(da.advanceDeduction||0)+Number(da.loanDeduction||0)+Number(da.fineDeduction||0)+Number(da.otherDeduction||0)+Number(da.employeePf||0)+Number(da.monthlyTax||0),0),vn=gt.reduce((Zn,da)=>Zn+Number(da.overtimeAmount||0)+Number(da.festivalBonus||0)+Number(da.performanceBonus||0)+Number(da.incentive||0)+Number(da.otherAddition||0),0),zt=gt.reduce((Zn,da)=>Zn+Number(da.netPay||0),0),Bt=gt.reduce((Zn,da)=>Zn+Math.max(Number(da.netPay||0),0),0),En=gt.reduce((Zn,da)=>Zn+Math.max(-Number(da.netPay||0),0),0),wn=gt.reduce((Zn,da)=>Zn+Number(da.monthlyTax||0),0),ma=gt.reduce((Zn,da)=>Zn+Number(da.employeePf||0),0),ca=gt.reduce((Zn,da)=>Zn+Number(da.employerPf||0),0),Pa=await Kr(Le,gt),kn={};(He.advanceLoanRecoveryBreakdown||[]).forEach(Zn=>{kn[`employeeAdvanceLoans/${t.companyId}/${Zn.recordId}/status`]="active",kn[`employeeAdvanceLoans/${t.companyId}/${Zn.recordId}/recoveryState`]="allocated",kn[`employeeAdvanceLoans/${t.companyId}/${Zn.recordId}/lastAllocatedPayrollMonth`]=l,kn[`employeeAdvanceLoans/${t.companyId}/${Zn.recordId}/lastAllocatedAt`]=Le});const Kn={employeeId:He.employeeId,employeeCode:He.employeeCode||"",employeeName:He.employeeName,branchId:He.branchId||"",netPayable:Math.max(He.netPay,0),recoverableAmount:Math.max(-He.netPay,0),paidAmount:0,outstandingAmount:Math.max(He.netPay,0),paymentStatus:"unpaid"};await yn(re(ie),{[`payrollItems/${t.companyId}/${l}/${E.id}`]:JSON.parse(JSON.stringify(He)),[`payrollPayables/${t.companyId}/${l}/employees/${E.id}`]:Kn,[`payrollStatutoryLiabilities/${t.companyId}/${l}/employees/${E.id}`]:{employeeId:He.employeeId,employeeCode:He.employeeCode||"",employeeName:He.employeeName,branchId:He.branchId||"",taxApplicable:!!He.taxApplicable,taxRuleVersionId:He.taxRuleVersionId||"",employeeTax:Number(He.monthlyTax||0),pfEligible:!!He.pfEligible,pfStartDate:He.pfStartDate||"",pfBasisAmount:Number(He.pfBasisAmount||0),employeePf:Number(He.employeePf||0),employerPf:Number(He.employerPf||0),totalStatutory:Number(He.monthlyTax||0)+Number(He.employeePf||0)+Number(He.employerPf||0)},[`payrollRuns/${t.companyId}/${l}/employeeCount`]:gt.length,[`payrollRuns/${t.companyId}/${l}/grossTotal`]:Dt,[`payrollRuns/${t.companyId}/${l}/deductionTotal`]:Yt,[`payrollRuns/${t.companyId}/${l}/additionTotal`]:vn,[`payrollRuns/${t.companyId}/${l}/netTotal`]:zt,[`payrollRuns/${t.companyId}/${l}/payableTotal`]:Bt,[`payrollRuns/${t.companyId}/${l}/recoverableTotal`]:En,[`payrollRuns/${t.companyId}/${l}/outstandingTotal`]:Math.max(Bt-Number(De.paidTotal||0),0),[`payrollRuns/${t.companyId}/${l}/taxTotal`]:wn,[`payrollRuns/${t.companyId}/${l}/employeePfTotal`]:ma,[`payrollRuns/${t.companyId}/${l}/employerPfTotal`]:ca,[`payrollPayables/${t.companyId}/${l}/payableTotal`]:Bt,[`payrollPayables/${t.companyId}/${l}/recoverableTotal`]:En,[`payrollPayables/${t.companyId}/${l}/outstandingTotal`]:Math.max(Bt-Number(De.paidTotal||0),0),[`payrollStatutoryLiabilities/${t.companyId}/${l}/employeeTaxTotal`]:wn,[`payrollStatutoryLiabilities/${t.companyId}/${l}/employeePfTotal`]:ma,[`payrollStatutoryLiabilities/${t.companyId}/${l}/employerPfTotal`]:ca,[`payrollStatutoryLiabilities/${t.companyId}/${l}/totalLiability`]:wn+ma+ca,[`payrollLockedAdditions/${t.companyId}/${l}/${E.id}_${Le}`]:{employeeId:E.id,employeeCode:E.employeeId||"",employeeName:E.name,reason:Q,addedAt:Le,addedByUid:t.uid,addedByName:t.name},...kn,...Pa}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.employee_added_after_lock",entityType:"payrollRun",entityId:l,summary:`Added ${E.name} to locked payroll ${l}: ${Q}`}),qe(""),le(`${E.name} added to locked payroll. Existing payroll rows were not recalculated.`)}catch(Le){console.error("Add employee to locked payroll failed:",Le),le(`Could not add employee to locked payroll: ${Le instanceof Error?Le.message:String(Le)}`)}finally{Ye(!1)}}},Xo=async E=>{if(!De)return;if(E==="approved"&&De.status!=="draft"){le("Only a Draft payroll can be approved.");return}if(E==="locked"&&De.status!=="approved"){le("Approve the payroll before locking it.");return}if(E==="approved"?window.confirm(`Approve payroll for ${l}? 4051 4052After approval, payroll values become read-only until an authorized user returns it to Draft.`):window.confirm(`Lock payroll for ${l}? 4053 4054Locked payroll cannot be edited or regenerated. Any correction will require a reason and authorized unlock.`)){Ye(!0);try{const Ie=Date.now(),Le=E==="approved"?{status:E,approvedAt:Ie,approvedByUid:t.uid,approvedByName:t.name}:{status:E,lockedAt:Ie,lockedByUid:t.uid,lockedByName:t.name,payableTotal:ta.payable,re
4054coverableTotal:ta.recoverable,paidTotal:ft.paid,outstandingTotal:Math.max(ta.payable-ft.paid,0),payablePostedAt:Ie,paymentStatus:ft.paid<=0?"unpaid":ft.paid>=ta.payable?"paid":"partially_paid",...De.correctionStatus==="unlocked"?{lastRelockedAt:Ie}:De.lastRelockedAt?{lastRelockedAt:De.lastRelockedAt}:{},correctionStatus:"none"},He={};Object.keys(P).forEach(zt=>{He[`payrollItems/${t.companyId}/${l}/${zt}/status`]=E});const gt=E==="locked"?Object.fromEntries(_n.map(zt=>{const Bt=Math.min(Math.max(Number(zt.paidAmount||0),0),Math.max(zt.netPay,0));return[zt.employeeId,{employeeId:zt.employeeId,employeeCode:zt.employeeCode||"",employeeName:zt.employeeName,branchId:zt.branchId||"",netPayable:Math.max(zt.netPay,0),recoverableAmount:Math.max(-zt.netPay,0),paidAmount:Bt,outstandingAmount:Math.max(Math.max(zt.netPay,0)-Bt,0),paymentStatus:Bt<=0?"unpaid":Bt>=zt.netPay?"paid":"partially_paid"}]})):null,Dt=JSON.parse(JSON.stringify({...De,...Le})),Yt=E==="locked"?await Kr(Ie):{},vn=E==="locked"?to():{};await yn(re(ie),{[`payrollRuns/${t.companyId}/${l}`]:Dt,...E==="locked"?{[`payrollPayables/${t.companyId}/${l}`]:{month:l,status:"posted",payableTotal:ta.payable,recoverableTotal:ta.recoverable,paidTotal:ft.paid,outstandingTotal:Math.max(ta.payable-ft.paid,0),employeeTaxTotal:ha.tax,employeePfTotal:ha.employeePf,employerPfTotal:ha.employerPf,statutoryLiabilityTotal:ha.tax+ha.employeePf+ha.employerPf,paymentStatus:ft.paid<=0?"unpaid":ft.paid>=ta.payable?"paid":"partially_paid",postedAt:Ie,postedByUid:t.uid,postedByName:t.name,employees:gt},[`payrollStatutoryLiabilities/${t.companyId}/${l}`]:{month:l,status:"posted",taxRuleVersionId:(Mn==null?void 0:Mn.id)||"",employeeTaxTotal:ha.tax,employeePfTotal:ha.employeePf,employerPfTotal:ha.employerPf,totalLiability:ha.tax+ha.employeePf+ha.employerPf,postedAt:Ie,postedByUid:t.uid,postedByName:t.name,employees:Object.fromEntries(_n.map(zt=>[zt.employeeId,{employeeId:zt.employeeId,employeeCode:zt.employeeCode||"",employeeName:zt.employeeName,branchId:zt.branchId||"",taxApplicable:!!zt.taxApplicable,taxRuleVersionId:zt.taxRuleVersionId||"",employeeTax:Number(zt.monthlyTax||0),pfEligible:!!zt.pfEligible,pfStartDate:zt.pfStartDate||"",pfBasisAmount:Number(zt.pfBasisAmount||0),employeePf:Number(zt.employeePf||0),employerPf:Number(zt.employerPf||0),totalStatutory:Number(zt.monthlyTax||0)+Number(zt.employeePf||0)+Number(zt.employerPf||0)}]))}}:{},...He,...Yt,...vn}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:E==="approved"?"payroll.approved":"payroll.locked",entityType:"payrollRun",entityId:l,summary:`${E==="approved"?"Approved":"Locked"} payroll for ${l}`}),le(E==="approved"?"Payroll approved and frozen for editing. Review it, then Lock Payroll when final.":"Payroll locked and posted to Accounts. Advance/Loan recovery is allocated and will be finalized when salary is fully paid.")}catch(Ie){console.error("Payroll status change failed:",Ie);const Le=Ie instanceof Error?Ie.message:String(Ie);le(`Payroll status could not be changed: ${Le}`)}finally{Ye(!1)}}},Yl=async()=>{var Q;if(!De||De.status!=="approved"||!wa)return;if(De.paymentStatus==="paid"||De.paymentStatus==="partially_paid"||Number(De.paidTotal||0)>0){le("Payroll with recorded salary payment cannot be reopened. Use a next-month arrear/recovery adjustment so the payment trail remains intact.");return}const E=(Q=window.prompt("Why should this approved payroll return to Draft? A reason is mandatory."))==null?void 0:Q.trim();if(E&&window.confirm(`Return approved payroll ${l} to Draft for correction? 4055 4056Reason: ${E}`)){Ye(!0);try{const Ie=Date.now(),Le={};Object.keys(P).forEach(gt=>{Le[`payrollItems/${t.companyId}/${l}/${gt}/status`]="draft"});const He={...De,status:"draft",correctionStatus:"unlocked",correctionReason:E,correctionApprovedAt:Ie,correctionApprovedByUid:t.uid,correctionApprovedByName:t.name};await yn(re(ie),{[`payrollRuns/${t.companyId}/${l}`]:He,[`payrollCorrections/${t.companyId}/${l}/${Ie}`]:{type:"approved_returned_to_draft",reason:E,createdAt:Ie,createdByUid:t.uid,createdByName:t.name,previousStatus:"approved",newStatus:"draft",paymentStatus:De.paymentStatus||"unpaid"},...Le}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.unlocked_for_correction",entityType:"payrollRun",entityId:l,summary:`Returned approved payroll ${l} to Draft: ${E}`}),le("Approved payroll returned to Draft for correction. Re-approve it after review.")}catch(Ie){console.error("Approved payroll reopen failed:",Ie),le("Approved payroll could not be returned to Draft.")}finally{Ye(!1)}}},Uc=async()=>{var Le;if(!De||De.status!=="locked")return;if(De.paymentStatus==="paid"){le("This payroll is already paid. Correct it through a next-month arrear/recovery adjustment; the locked payroll cannot be changed.");return}const E=(Le=window.prompt("Why does this locked payroll need correction? This reason is mandatory."))==null?void 0:Le.trim();
4056if(!E||!window.confirm(`Submit correction request for ${l}? 4057 4058Reason: ${E}`))return;const Q=Date.now(),Ie={correctionStatus:"requested",correctionReason:E,correctionRequestedAt:Q,correctionRequestedByUid:t.uid,correctionRequestedByName:t.name};await yn(re(ie),{[`payrollRuns/${t.companyId}/${l}`]:{...De,...Ie},[`payrollCorrections/${t.companyId}/${l}/${Q}`]:{type:"unlock_request",reason:E,createdAt:Q,createdByUid:t.uid,createdByName:t.name,payrollStatus:De.status,paymentStatus:De.paymentStatus||"unpaid"}}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.correction_requested",entityType:"payrollRun",entityId:l,summary:`Requested payroll correction for ${l}: ${E}`}),le("Correction request submitted. An Owner, Admin or Super Admin must authorize the unlock.")},Gi=async()=>{if(!De||De.status!=="locked"||!wa)return;if(De.paymentStatus==="paid"||De.paymentStatus==="partially_paid"||Number(De.paidTotal||0)>0||Number(De.statutoryPaidTotal||0)>0||oe.paidTotal>0){le("Payroll with recorded salary or statutory Tax/PF payment cannot be unlocked. Use a next-month adjustment so the settlement audit trail remains intact.");return}const E=(De.correctionReason||window.prompt("Enter the authorized correction reason.")||"").trim();if(!E||!window.confirm(`Authorize unlock for ${l}? 4059 4060Reason: ${E}`))return;const Q=Date.now(),Ie={};Object.keys(P).forEach(Yt=>{Ie[`payrollItems/${t.companyId}/${l}/${Yt}/status`]="draft"});const Le={...De,status:"draft",correctionStatus:"unlocked",correctionReason:E,correctionApprovedAt:Q,correctionApprovedByUid:t.uid,correctionApprovedByName:t.name},He={},gt={};Array.from(new Set(_n.map(Yt=>Yt.branchId||"company"))).forEach(Yt=>{const vn=n.find(En=>En.id===Yt),zt=String((vn==null?void 0:vn.code)||Yt||"COMPANY").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10)||"COMPANY",Bt=`payroll_${l.replace(/[^0-9]/g,"")}_${zt}`;gt[`accountingVouchers/${t.companyId}/${Bt}`]=null;for(let En=1;En<=8;En+=1)gt[`accountingLedgerEntries/${t.companyId}/${Bt}_${String(En).padStart(3,"0")}`]=null}),_n.forEach(Yt=>(Yt.advanceLoanRecoveryBreakdown||[]).forEach(vn=>{He[`employeeAdvanceLoans/${t.companyId}/${vn.recordId}/status`]="active",He[`employeeAdvanceLoans/${t.companyId}/${vn.recordId}/recoveryState`]="scheduled",He[`employeeAdvanceLoans/${t.companyId}/${vn.recordId}/lastAllocatedPayrollMonth`]=null,He[`employeeAdvanceLoans/${t.companyId}/${vn.recordId}/lastAllocatedAt`]=null})),await yn(re(ie),{[`payrollRuns/${t.companyId}/${l}`]:Le,[`payrollCorrections/${t.companyId}/${l}/${Q}`]:{type:"unlock_authorized",reason:E,createdAt:Q,createdByUid:t.uid,createdByName:t.name,previousStatus:"locked",newStatus:"draft",paymentStatus:De.paymentStatus||"unpaid"},...Ie,...He,...gt}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.unlocked_for_correction",entityType:"payrollRun",entityId:l,summary:`Unlocked payroll ${l} for correction: ${E}`}),le("Payroll unlocked for correction. Edit, approve and lock it again after review.")},zc=(E,Q)=>{if(!In){le("You do not have permission to reverse salary payments.");return}if(Q.status==="reversed")return;if(!P[E]){le("Employee payroll item could not be found.");return}Me({employeeId:E,tx:Q,reason:""})},Zo=async()=>{if(!Se)return;if(!In){Me(null),le("You do not have permission to reverse salary payments.");return}const{employeeId:E,tx:Q}=Se,Ie=Se.reason.trim();if(!Ie){le("Reversal reason is required.");return}const Le=P[E];if(!Le){le("Employee payroll item could not be found.");return}Ye(!0);try{const He=Date.now(),gt=Math.max(Number(Le.netPay||0),0),Dt=Object.values(me[E]||{}),Yt=Math.min(Dt.reduce((kn,Kn)=>Kn.id===Q.id||Kn.status==="reversed"?kn:kn+Math.max(Number(Kn.settledAmount??Kn.amount??0),0),0),gt),vn=Math.max(gt-Yt,0),zt=Yt<=0?"unpaid":vn<=0?"paid":"partially_paid",Bt=_n.reduce((kn,Kn)=>{const Zn=Math.max(Number(Kn.netPay||0),0);if(Kn.employeeId===E)return kn+Yt;const da=Object.values(me[Kn.employeeId]||{}).reduce((Ga,Da)=>Da.status==="reversed"?Ga:Ga+Math.max(Number(Da.settledAmount??Da.amount??0),0),0);return kn+Math.min(da,Zn)},0),En=Math.max(ta.payable-Bt,0),wn=Bt<=0?"unpaid":En<=0?"paid":"partially_paid",ma={},ca=zt!=="paid"?await Jo(Le,Q.id,Ie):{},Pa=await Ir(Le,Q,Ie);
4060zt!=="paid"&&(Le.advanceLoanRecoveryBreakdown||[]).forEach(kn=>{const Kn=K.find(Zn=>Zn.id===kn.recordId);Kn&&(ma[`employeeAdvanceLoans/${t.companyId}/${Kn.id}/status`]="active",ma[`employeeAdvanceLoans/${t.companyId}/${Kn.id}/recoveryState`]="allocated",ma[`employeeAdvanceLoans/${t.companyId}/${Kn.id}/completedAt`]=null,ma[`employeeAdvanceLoans/${t.companyId}/${Kn.id}/completedByPayrollMonth`]=null,ma[`employeeAdvanceLoans/${t.companyId}/${Kn.id}/recoveredDate`]=null)}),await yn(re(ie),{[`payrollPayments/${t.companyId}/${l}/${E}/${Q.id}/status`]:"reversed",[`payrollPayments/${t.companyId}/${l}/${E}/${Q.id}/reversedAt`]:He,[`payrollPayments/${t.companyId}/${l}/${E}/${Q.id}/reversedByUid`]:t.uid,[`payrollPayments/${t.companyId}/${l}/${E}/${Q.id}/reversedByName`]:t.name,[`payrollPayments/${t.companyId}/${l}/${E}/${Q.id}/reversalReason`]:Ie,[`payrollItems/${t.companyId}/${l}/${E}/paidAmount`]:Yt,[`payrollItems/${t.companyId}/${l}/${E}/paymentStatus`]:zt,[`payrollRuns/${t.companyId}/${l}/paymentStatus`]:wn,[`payrollRuns/${t.companyId}/${l}/paidTotal`]:Bt,[`payrollRuns/${t.companyId}/${l}/outstandingTotal`]:En,[`payrollPayables/${t.companyId}/${l}/paymentStatus`]:wn,[`payrollPayables/${t.companyId}/${l}/paidTotal`]:Bt,[`payrollPayables/${t.companyId}/${l}/outstandingTotal`]:En,...ma,...ca,...Pa}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payment.recorded",entityType:"payrollRun",entityId:l,summary:`Reversed salary payment BDT ${pn(Q.amount)} for ${Le.employeeName} (${l})`,metadata:{event:"salary_payment_reversed",payrollMonth:l,employeeId:E,originalTransactionId:Q.id,originalAmount:Q.amount,reversalReason:Ie,reversedAt:He,reversedByUid:t.uid,reversedByName:t.name}}),Me(null),le(`Salary payment BDT ${pn(Q.amount)} reversed for ${Le.employeeName}. Audit history retained.`)}catch(He){console.error("Salary payment reversal failed:",He),le(`Salary payment reversal failed: ${He instanceof Error?He.message:String(He)}`)}finally{Ye(!1)}},qc=(E,Q)=>{if(!aa){le("You do not have permission to reverse Tax/PF settlement payments.");return}Q.status!=="reversed"&&wt({liabilityType:E,tx:Q,reason:""})},ec=async()=>{if(!ot)return;if(!aa){wt(null),le("You do not have permission to reverse Tax/PF settlement payments.");return}const{liabilityType:E,tx:Q}=ot,Ie=ot.reason.trim();if(!Ie){le("Reversal reason is required.");return}const Le={tax:"Employee Income Tax",employee_pf:"Employee PF",employer_pf:"Employer PF"};Ye(!0);try{const He=Date.now(),gt={tax:Ae.tax,employee_pf:Ae.employee_pf,employer_pf:Ae.employer_pf};gt[E]=Object.values(Re[E]||{}).reduce((Kn,Zn)=>Zn.id===Q.id||Zn.status==="reversed"?Kn:Kn+Math.max(Number(Zn.amount||0),0),0);const Dt=Math.min(gt.tax,vt.tax),Yt=Math.min(gt.employee_pf,vt.employee_pf),vn=Math.min(gt.employer_pf,vt.employer_pf),zt=Dt+Yt+vn,Bt=oe.liabilityTotal,En=Math.max(Bt-zt,0),wn=zt<=0?"unpaid":En<=0?"paid":"partially_paid",ma=vt[E],ca=Math.min(gt[E],ma),Pa=Math.max(ma-ca,0),kn=ca<=0?"unpaid":Pa<=0?"paid":"partially_paid";await yn(re(ie),{[`payrollStatutoryPayments/${t.companyId}/${l}/${E}/${Q.id}/status`]:"reversed",[`payrollStatutoryPayments/${t.companyId}/${l}/${E}/${Q.id}/reversedAt`]:He,[`payrollStatutoryPayments/${t.companyId}/${l}/${E}/${Q.id}/reversedByUid`]:t.uid,[`payrollStatutoryPayments/${t.companyId}/${l}/${E}/${Q.id}/reversedByName`]:t.name,[`payrollStatutoryPayments/${t.companyId}/${l}/${E}/${Q.id}/reversalReason`]:Ie,[`payrollStatutoryLiabilities/${t.companyId}/${l}/settlement/${E}`]:{liability:ma,paid:ca,outstanding:Pa,status:kn,lastUpdatedAt:He},[`payrollStatutoryLiabilities/${t.companyId}/${l}/paidTotal`]:zt,[`payrollStatutoryLiabilities/${t.companyId}/${l}/outstandingTotal`]:En,[`payrollStatutoryLiabilities/${t.companyId}/${l}/settlementStatus`]:wn,[`payrollRuns/${t.companyId}/${l}/statutoryPaidTotal`]:zt,[`payrollRuns/${t.companyId}/${l}/statutoryOutstandingTotal`]:En,[`payrollRuns/${t.companyId}/${l}/statutorySettlementStatus`]:wn}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payment.recorded",entityType:"payrollRun",entityId:l,summary:`Reversed ${Le[E]} payment BDT ${pn(Q.amount)} (${l})`,metadata:{event:"statutory_payment_reversed",payrollMonth:l,liabilityType:E,originalTransactionId:Q.id,originalAmount:Q.amount,reversalReason:Ie,reversedAt:He,reversedByUid:t.uid,reversedByName:t.name}}),wt(null),le(`${Le[E]} payment BDT ${pn(Q.amount)} reversed. Audit history retained.`)}catch(He){console.error("Statutory payment reversal failed:",He),le(`Statutory payment reversal failed: ${He instanceof Error?He.message:String(He)}`)}finally{Ye(!1)}},bc=E=>{if(!Sa){le("You do not have permission to record Tax/PF settlement payments.");return}if(!De||De.status!=="locked"){le("Lock the payroll before recording statutory payment.");return}const Q={tax:"Employee Income Tax",employee_pf:"Employee PF",employer_pf:"Employer PF"}
4060,Ie=vt[E],Le=Math.min(Ae[E],Ie),He=Math.max(Ie-Le,0);if(Ie<=0){le(`${Q[E]} has no liability for ${l}.`);return}if(He<=0){le(`${Q[E]} is already fully settled.`);return}Ce({liabilityType:E,amount:He.toFixed(2),method:"bank",paymentDate:new Date().toISOString().slice(0,10),reference:""})},vl=async()=>{if(!ct||!De||De.status!=="locked")return;if(!Sa){Ce(null),le("You do not have permission to record Tax/PF settlement payments.");return}const{liabilityType:E}=ct,Q={tax:"Employee Income Tax",employee_pf:"Employee PF",employer_pf:"Employer PF"},Ie=vt[E],Le=Math.min(Ae[E],Ie),He=Math.max(Ie-Le,0),gt=Number(ct.amount);if(!Number.isFinite(gt)||gt<=0){le("Payment amount must be greater than zero.");return}if(gt>He+1e-4){le(`Payment cannot exceed outstanding BDT ${pn(He)}.`);return}if(!/^\d{4}-\d{2}-\d{2}$/.test(ct.paymentDate)){le("Enter a valid payment date.");return}Ye(!0);try{const Dt=Date.now(),Yt=`stat_${E}_${Dt}`,vn=ct.reference.trim(),zt={id:Yt,liabilityType:E,amount:gt,method:ct.method,paymentDate:ct.paymentDate,reference:vn,status:"active",createdAt:Dt,createdByUid:t.uid,createdByName:t.name},Bt={...Ae,[E]:Le+gt},En=Math.min(Bt.tax,vt.tax),wn=Math.min(Bt.employee_pf,vt.employee_pf),ma=Math.min(Bt.employer_pf,vt.employer_pf),ca=En+wn+ma,Pa=vt.tax+vt.employee_pf+vt.employer_pf,kn=Math.max(Pa-ca,0),Kn=ca<=0?"unpaid":kn<=0?"paid":"partially_paid",Zn=Math.min(Le+gt,Ie),da=Math.max(Ie-Zn,0),Ga=Zn<=0?"unpaid":da<=0?"paid":"partially_paid";await yn(re(ie),{[`payrollStatutoryPayments/${t.companyId}/${l}/${E}/${Yt}`]:zt,[`payrollStatutoryLiabilities/${t.companyId}/${l}/settlement/${E}`]:{liability:Ie,paid:Zn,outstanding:da,status:Ga,lastUpdatedAt:Dt},[`payrollStatutoryLiabilities/${t.companyId}/${l}/paidTotal`]:ca,[`payrollStatutoryLiabilities/${t.companyId}/${l}/outstandingTotal`]:kn,[`payrollStatutoryLiabilities/${t.companyId}/${l}/settlementStatus`]:Kn,[`payrollRuns/${t.companyId}/${l}/statutoryPaidTotal`]:ca,[`payrollRuns/${t.companyId}/${l}/statutoryOutstandingTotal`]:kn,[`payrollRuns/${t.companyId}/${l}/statutorySettlementStatus`]:Kn}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payment.recorded",entityType:"payrollRun",entityId:l,summary:`${Q[E]} payment BDT ${pn(gt)} recorded (${l})`,metadata:{event:"statutory_payment_recorded",payrollMonth:l,liabilityType:E,paymentAmount:gt,paymentDate:ct.paymentDate,paymentMethod:ct.method,paymentReference:vn,liability:Ie,alreadyPaid:Le,paidAfter:Zn,outstandingAfter:da}}),Ce(null),le(`${Q[E]} payment BDT ${pn(gt)} recorded. Remaining BDT ${pn(da)}.`)}catch(Dt){console.error("Statutory payment recording failed:",Dt),le(`Statutory payment could not be recorded: ${Dt instanceof Error?Dt.message:String(Dt)}`)}finally{Ye(!1)}},Oi=E=>{if(!Ca){le("You do not have permission to record salary payments.");return}if(!De||De.status!=="locked"){le("Lock the payroll before recording salary payment.");return}const Q=Math.max(Number(E.netPay||0),0),Ie=W[E.employeeId],Le=Math.max(Number(E.paidAmount||0),0),He=Math.min(Ie!==void 0?Ie:Le,Q),gt=Math.max(Q-He,0);if(Q<=0){le(`${E.employeeName} has no salary payable for ${l}.`);return}if(gt<=0){le(`${E.employeeName}'s salary is already fully paid.`);return}We(""),pe({item:E,amount:gt.toFixed(2),method:"bank",paymentDate:"",reference:"",sourceBankAccountId:"",settleRounding:!1,confirmed:!1})},tc=async()=>{if(We(""),!se)return;if(!De||De.status!=="locked"){We("This payroll is no longer locked. Refresh Payroll Run and review the employee before recording payment.");return}if(!Ca){We("You do not have permission to record salary payments.");return}const E=se.item,Q=Math.max(Number(E.netPay||0),0),Ie=W[E.employeeId],Le=Math.max(Number(E.paidAmount||0),0),He=Math.min(Ie!==void 0?Ie:Le,Q),gt=Math.max(Q-He,0);if(!se.confirmed){We("Review the payment details and tick Confirm payment details before posting.");return}const Dt=Number(se.amount);if(!Number.isFinite(Dt)||Dt<=0){We("Salary payment amount must be greater than zero.");return}if(Dt>gt+1e-4){We(`Salary payment cannot exceed the outstanding BDT ${pn(gt)}.`);return}const Yt=Math.max(gt-Dt,0),vn=Yt>1e-4&&Yt<1,zt=se.settleRounding&&vn?Yt:0,Bt=zt>0?-zt:0,En=Math.min(Dt+zt,gt);if(!/^\d{4}-\d{2}-\d{2}$/.test(se.paymentDate)){We("Enter a valid salary payment date.");return}const wn=se.method==="bank"?de.find(ma=>ma.id===se.sourceBankAccountId):void 0;if(se.method==="bank"&&!wn){We("Select the company bank account that actually sent this salary payment.");return}Ye(!0);try{const ma=Date.now(),ca=`pay_${ma}`,Pa={id:ca,amount:Dt,method:se.method,paymentDate:se.paymentDate,reference:se.reference.trim(),sourceBankAccountId:(wn==null?void 0:wn.id)||"",sourceBankName:(wn==null?void 0:wn.bankName)||(wn==null?void 0:wn.name)||"",sourceBankAccountName:(wn==null?void 0:wn.accountName)||"",sourceBankAccountNumber:(wn==null?void 0:wn.accountNumber)||"",sourceBankLedgerAccountId:(wn==null?void 0:wn.ledgerAccountId)||"",sourceBankLedgerCode:(wn==null?void 0:wn.ledgerCode)||"",sourceBankLedgerName:(wn==null?void 0:wn.ledgerName)||"",receivingBankName:ke(E).bankName||"",receivingBankAccount:ke(E).bankAccount||"",receivingBankAccountHolder:ke(E).bankAccountHolder||E.employeeName,roundingAdjustment:Bt,settledAmount:En,status:"active",createdAt:ma,createdByUid:t.uid,createdByName:t.name},kn=Math.min(He+En,Q),Kn=Math.max(Q-kn,0),Zn=kn<=0?"unpaid":Kn<=0?"paid":"partially_paid",da=_n.reduce((_a,Vs)=>
4060{if(Vs.employeeId===E.employeeId)return _a+kn;const Hn=Math.max(Number(Vs.netPay||0),0),Fa=W[Vs.employeeId],zs=Math.max(Number(Vs.paidAmount||0),0);return _a+Math.min(Fa!==void 0?Fa:zs,Hn)},0),Ga=ta.payable,Da=Math.max(Ga-da,0),Ia=da<=0?"unpaid":Da<=0?"paid":"partially_paid",ls=Zn==="paid"?$i(E.employeeId,se.paymentDate):{},Ua=Zn==="paid"?await fo(E,se.paymentDate,ca):{},va=await er(E,Pa,!1);await yn(re(ie),{[`payrollPayments/${t.companyId}/${l}/${E.employeeId}/${ca}`]:Pa,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paidAmount`]:kn,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paymentStatus`]:Zn,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paymentMethod`]:se.method,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paymentDate`]:se.paymentDate,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paymentReference`]:se.reference.trim(),[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paymentSourceBankAccountId`]:(wn==null?void 0:wn.id)||"",[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paymentSourceBankName`]:(wn==null?void 0:wn.bankName)||(wn==null?void 0:wn.name)||"",[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paidAt`]:ma,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paidByUid`]:t.uid,[`payrollItems/${t.companyId}/${l}/${E.employeeId}/paidByName`]:t.name,[`payrollRuns/${t.companyId}/${l}/paymentStatus`]:Ia,[`payrollRuns/${t.companyId}/${l}/paidTotal`]:da,[`payrollRuns/${t.companyId}/${l}/outstandingTotal`]:Da,[`payrollPayables/${t.companyId}/${l}/paymentStatus`]:Ia,[`payrollPayables/${t.companyId}/${l}/paidTotal`]:da,[`payrollPayables/${t.companyId}/${l}/outstandingTotal`]:Da,...ls,...Ua,...va}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payment.recorded",entityType:"payrollRun",entityId:ca,summary:`Salary payment BDT ${pn(Dt)} recorded for ${E.employeeName} (${l})`,metadata:{payrollMonth:l,employeeId:E.employeeId,paymentAmount:Dt,roundingAdjustment:Bt,settledAmount:En,paymentDate:se.paymentDate,paymentMethod:se.method,paymentReference:se.reference.trim(),sourceBankAccountId:(wn==null?void 0:wn.id)||"",sourceBankName:(wn==null?void 0:wn.bankName)||(wn==null?void 0:wn.name)||"",sourceBankLedgerAccountId:(wn==null?void 0:wn.ledgerAccountId)||"",receivingBankName:E.bankName||"",receivingBankAccount:E.bankAccount||"",employeePaymentStatus:Zn,payrollPaymentStatus:Ia}}),pe(null),le(`Salary payment BDT ${pn(Dt)} recorded for ${E.employeeName}${zt>0?` with BDT ${pn(zt)} rounding settlement`:""}. Remaining BDT ${pn(Kn)}.`)}catch(ma){console.error("Salary payment recording failed:",ma);const ca=ma instanceof Error?ma.message:String(ma),Pa=/permission[_ -]?denied/i.test(ca)?"Firebase denied one or more atomic payroll/accounting writes. Check the user payroll-payment permission, finance posting permission and branch access for this employee.":ca;We(`Salary payment could not be recorded: ${Pa}`)}finally{Ye(!1)}},Vc=async E=>{var kn;if(!bt||bt.status!=="locked"||!on)return;const Q=(kn=bt.demoPayments)==null?void 0:kn[E];if(!Q)return;const Ie=Math.max(Number(Q.paidAmount||0),0),Le=Math.max(Q.netPay-Ie,0);if(Le<=0){window.alert(`${Q.employeeName} is already fully paid in Demo Mode.`);return}const He=window.prompt(`DEMO NEW PAYMENT â ${Q.employeeName} 4061 4062Net payable: BDT ${pn(Q.netPay)} 4063Already paid: BDT ${pn(Ie)} 4064Remaining: BDT ${pn(Le)} 4065 4066Enter THIS payment amount:`,String(Le));if(He===null)return;const gt=Number(He);if(!Number.isFinite(gt)||gt<=0||gt>Le){window.alert(`Demo payment must be greater than BDT 0 and not exceed remaining BDT ${pn(Le)}.`);return}const Dt=(window.prompt("DEMO method: bank / cash / other","bank")||"").trim().toLowerCase();if(!["bank","cash","other"].includes(Dt))return;const Yt=Dt,vn=(window.prompt("DEMO payment date (YYYY-MM-DD):",new Date().toISOString().slice(0,10))||"").trim();if(!/^\d{4}-\d{2}-\d{2}$/.test(vn))return;const zt=(window.prompt("DEMO reference (optional):","")||"").trim(),Bt=Ie+gt,En=Bt>=Q.netPay?"paid":"partially_paid",wn=Date.now(),ma=`demo_pay_${wn}`,ca={id:ma,amount:gt,method:Yt,paymentDate:vn,reference:zt,createdAt:wn,createdByUid:t.uid,createdByName:t.name},Pa={...bt,demoPayments:{...bt.demoPayments||{},[E]:{...Q,paidAmount:Bt,paymentStatus:En,paymentMethod:Yt,paymentDate:vn,paymentReference:zt,transactions:{...Q.transactions||{},[ma]:ca}}}};await Pn(re(ie,`payrollTestRuns/${t.companyId}/${bt.id}`),Pa),tn(Pa)},_o=async()=>
4066{if(!on)return;const E=`demo_${Date.now()}`,Ie={id:E,month:l,status:"draft",correctionStatus:"none",createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name,demoPayments:{demo_001:{employeeName:"Demo Employee 01",netPay:25e3,paidAmount:0,paymentStatus:"unpaid"},demo_002:{employeeName:"Demo Employee 02",netPay:32e3,paidAmount:0,paymentStatus:"unpaid"},demo_003:{employeeName:"Demo Employee 03",netPay:18500,paidAmount:0,paymentStatus:"unpaid"}}};await Pn(re(ie,`payrollTestRuns/${t.companyId}/${E}`),Ie),tn(Ie),jt(!0),le("Demo payroll created in isolated Test Mode. Live payroll data is untouched.")},ko=async E=>{if(!bt||!on)return;if(E==="draft"&&At){window.alert("Demo payroll has recorded salary payment. It cannot return to Draft. Use next-month arrear/recovery in live workflow to preserve the settlement trail.");return}const Q={...bt,status:E,correctionStatus:E==="draft"&&bt.correctionStatus==="unlocked"?"unlocked":E==="locked"?"none":bt.correctionStatus};await Pn(re(ie,`payrollTestRuns/${t.companyId}/${bt.id}`),Q),tn(Q)},U=async()=>{var Ie;if(!bt||bt.status!=="locked"||!on)return;const E=(Ie=window.prompt("Demo correction reason (test only):"))==null?void 0:Ie.trim();if(!E)return;const Q={...bt,correctionStatus:"requested",correctionReason:E};await Pn(re(ie,`payrollTestRuns/${t.companyId}/${bt.id}`),Q),tn(Q)},Ue=async()=>{if(!bt||bt.status!=="locked"||bt.correctionStatus!=="requested"||!on)return;if(At){window.alert(`Demo payroll cannot be unlocked because salary payment has already been recorded. 4067 4068Paid: BDT ${pn(ut.paid)} 4069Outstanding: BDT ${pn(ut.pending)} 4070 4071Payment audit trail is protected.`);return}const E={...bt,status:"draft",correctionStatus:"unlocked"};await Pn(re(ie,`payrollTestRuns/${t.companyId}/${bt.id}`),E),tn(E)},yt=async()=>{var Ie;if(!on||!De||!window.confirm(`INTERNAL TEST RESET â ${l} 4072 4073This will clear recorded salary payments, Salary Payable posting, correction records, and return the CURRENT LIVE payroll month to Draft. 4074 4075Use this only for development/test data. Client production payroll must never be reset this way. 4076 4077Continue?`))return;if(((Ie=window.prompt(`Type RESET ${l} exactly to confirm this destructive test reset:`))==null?void 0:Ie.trim())!==`RESET ${l}`){window.alert("Reset cancelled. Confirmation text did not match.");return}Ye(!0);try{const Le=Date.now(),He={},gt={};Array.from(new Set(Object.values(P).map(zt=>zt.branchId||"company"))).forEach(zt=>{const Bt=n.find(ma=>ma.id===zt),En=String((Bt==null?void 0:Bt.code)||zt||"COMPANY").toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,10)||"COMPANY",wn=`payroll_${l.replace(/[^0-9]/g,"")}_${En}`;gt[`accountingVouchers/${t.companyId}/${wn}`]=null;for(let ma=1;ma<=8;ma+=1)gt[`accountingLedgerEntries/${t.companyId}/${wn}_${String(ma).padStart(3,"0")}`]=null}),K.forEach(zt=>{zt.completedByPayrollMonth===l&&(gt[`employeeAdvanceLoans/${t.companyId}/${zt.id}/status`]="active",gt[`employeeAdvanceLoans/${t.companyId}/${zt.id}/completedAt`]=null,gt[`employeeAdvanceLoans/${t.companyId}/${zt.id}/completedByPayrollMonth`]=null)}),Object.entries(P).forEach(([zt,Bt])=>{He[`payrollItems/${t.companyId}/${l}/${zt}`]={...Bt,status:"draft",paymentStatus:"unpaid",paidAmount:0,paymentMethod:null,paymentDate:null,paymentReference:null,paidAt:null,paidByUid:null,paidByName:null,updatedAt:Le}});const Yt={...De,status:"draft",paymentStatus:"unpaid",paidTotal:0,outstandingTotal:Math.max(Number(De.netTotal||0),0),payablePostedAt:void 0,correctionStatus:"none",correctionReason:void 0,correctionRequestedAt:void 0,correctionRequestedByUid:void 0,correctionRequestedByName:void 0,correctionApprovedAt:void 0,correctionApprovedByUid:void 0,correctionApprovedByName:void 0,approvedAt:void 0,approvedByUid:void 0,approvedByName:void 0,lockedAt:void 0,lockedByUid:void 0,lockedByName:void 0},vn=JSON.parse(JSON.stringify(Yt));await yn(re(ie),{[`payrollRuns/${t.companyId}/${l}`]:vn,[`payrollPayments/${t.companyId}/${l}`]:null,[`payrollPayables/${t.companyId}/${l}`]:null,[`payrollStatutoryLiabilities/${t.companyId}/${l}`]:null,[`payrollStatutoryPayments/${t.companyId}/${l}`]:null,[`payrollCorrections/${t.companyId}/${l}`]:null,...He,...gt});try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"payroll.test_reset",entityType:"payrollRun",entityId:l,summary:`INTERNAL TEST RESET of payroll ${l}; payments/payable/corrections cleared and payroll returned to Draft`,metadata:{previousStatus:De.status,previousPaymentStatus:De.paymentStatus||"unpaid",previousPaidTotal:Number(De.paidTotal||0),resetAt:Le}})}catch(zt){console.error("Payroll test reset completed but audit log failed:",zt)}le(`TEST RESET completed for ${l}. Payroll is Draft, payment/payable test data is cleared. Regenerate now to apply the latest PF calculation.`),jt(!1),c("run")}catch(Le){console.error("Payroll internal test reset failed:",Le);const He=Le instanceof Error?Le.message:String(Le);window.alert(`Test reset failed: ${He}`)}finally{Ye(!1)}},kt=async()=>{!bt||!on||window.confirm("Delete this DEMO payroll? Only isolated test data will be removed.")&&(await Pn(re(ie,`payrollTestRuns/${t.companyId}/${bt.id}`),null),tn(null),jt(!1),le("Demo payroll deleted. Live payroll data was not changed."))};return e.jsxs("div",{className:"payroll-module",children:[e.jsxs("header",{className:"payroll-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Payroll"}),e.jsx("h1",{children:"Payroll"}),e.jsx("p",{children:"Attendance-linked monthly salary processing."})]}),e.jsxs("div",{className:"payroll-month",children:[e.jsxs("label",{children:["Payroll Month",e.jsx("input",{type:"month",value:l,onCh
4077ange:E=>m(E.target.value)})]}),on&&e.jsx("button",{className:"payroll-test-mode-button",onClick:bt?()=>jt(!0):_o,children:"TEST MODE"})]})]}),e.jsxs("div",{className:"payroll-tabs",children:[e.jsxs("button",{className:i==="dashboard"?"active":"",onClick:()=>c("dashboard"),children:[e.jsx(Ll,{size:17})," Dashboard"]}),e.jsxs("button",{className:i==="salary"?"active":"",onClick:()=>c("salary"),children:[e.jsx(Zs,{size:17})," Salary Structure"]}),e.jsxs("button",{className:i==="advanceLoan"?"active":"",onClick:()=>c("advanceLoan"),children:[e.jsx(Eh,{size:17})," Advance & Loan"]}),e.jsxs("button",{className:i==="run"?"active":"",onClick:()=>c("run"),children:[e.jsx(v1,{size:17})," Payroll Run"]}),e.jsxs("button",{className:i==="settings"?"active":"",onClick:()=>c("settings"),children:[e.jsx(vu,{size:17})," Settings"]})]}),Je&&e.jsx("div",{className:"payroll-message",children:Je}),i==="dashboard"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"payroll-kpis",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Employees"}),e.jsx("strong",{children:_n.length||$a.length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Gross Salary"}),e.jsxs("strong",{children:["à§³ ",pn((De==null?void 0:De.grossTotal)??ha.gross)]})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Total Deduction"}),e.jsxs("strong",{children:["à§³ ",pn((De==null?void 0:De.deductionTotal)??ha.deduction)]})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Net Payable"}),e.jsxs("strong",{children:["à§³ ",pn((De==null?void 0:De.netTotal)??ha.net)]})]})]}),e.jsxs("section",{className:"payroll-panel payroll-empty",children:[e.jsx(v1,{size:42}),e.jsx("h2",{children:De?`${l} payroll is ${De.status}`:`No payroll generated for ${l}`}),e.jsx("p",{children:"Salary structures and attendance records will be used automatically."}),e.jsxs("button",{onClick:bs,disabled:ce,children:[e.jsx(Hi,{size:17}),ce?"Generating...":"Generate Payroll"]})]})]}),i==="salary"&&e.jsxs("section",{className:"payroll-panel",children:[e.jsxs("div",{className:"panel-title",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Salary Structure"}),e.jsx("p",{children:"Set gross salary and salary components employee-wise."})]}),e.jsx("div",{className:"payroll-actions",children:e.jsxs("button",{onClick:hs,disabled:ce||!ae,children:[e.jsx(hr,{size:16}),ce?"Saving...":je?"Saved":"Save Salary Structure"]})})]}),e.jsx("div",{className:"payroll-table-wrap payroll-salary-structure-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Gross"}),e.jsx("th",{children:"Basic"}),e.jsx("th",{children:"House Rent"}),e.jsx("th",{children:"Medical"}),e.jsx("th",{children:"Transport"}),e.jsx("th",{children:"Other"}),d.statutoryEnabled&&d.taxEnabled&&e.jsxs(e.Fragment,{children:[e.jsx("th",{children:"Tax"}),e.jsx("th",{children:"Taxpayer Category"}),e.jsx("th",{children:"Disabled Dependents"}),e.jsx("th",{children:"Tax Location"}),e.jsx("th",{children:"Eligible Investment (Annual)"}),e.jsx("th",{children:"Prior Tax Withheld"})]}),d.statutoryEnabled&&d.pfEnabled&&e.jsx("th",{children:"PF"}),d.statutoryEnabled&&d.pfEnabled&&e.jsx("th",{children:"PF Eligibility"}),e.jsx("th",{children:"Bank Name"}),e.jsx("th",{children:"Account No."}),e.jsx("th",{children:"Account Holder"})]})}),e.jsx("tbody",{children:$a.map(E=>{const Q=q[E.id]||Z[E.id]||{};return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:E.name}),e.jsx("small",{children:E.employeeId||E.designation||"â"})]}),["grossSalary","basicSalary","houseRent","medicalAllowance","transportAllowance","otherAllowance"].map(Ie=>e.jsx("td",{children:e.jsx("input",{type:"number",min:"0",inputMode:"decimal",value:Q[Ie]??"",onChange:Le=>is(E.id,Ie,Le.target.value)})},Ie)),d.statutoryEnabled&&d.taxEnabled&&e.jsx("td",{children:e.jsxs("select",{value:Q.taxApplicable?"yes":"no",onChange:Ie=>is(E.id,"taxApplicable",Ie.target.value==="yes"),children:[e.jsx("option",{value:"no",children:"No"}),e.jsx("option",{value:"yes",children:"Yes"})]})}),d.statutoryEnabled&&d.taxEnabled&&e.jsx("td",{children:e.jsxs("select",{value:Q.taxPayerCategory||"general",disabled:!Q.taxApplicable,onChange:Ie=>is(E.id,"taxPayerCategory",Ie.target.value),children:[e.jsx("option",{value:"general",children:"General"}),e.jsx("option",{value:"female_senior",children:"Female / Age 65+"}),e.jsx("option",{value:"disabled",children:"Person with Disability"}),e.jsx("option",{value:"third_gender",children:"Third Gender"}),e.jsx("option",{value:"war_wounded_ff",children:"Gazetted War-wounded Freedom Fighter"}),e.jsx("option",{value:"july_warrior",children:"Gazetted Injured July Warrior"})]})}),d.statutoryEnabled&&d.taxEnabled&&e.jsx("td",{children:e.jsx("input",{type:"number",min:"0",step:"1",disabled:!Q.taxApplicable,value:Q.disabledDependentCount??0,onChange:Ie=>is(E.id,"disabledDependentCount",Ie.target.value)})}),d.statutoryEnabled&&d.taxEnabled&&e.jsx("td",{children:e.jsxs("select",{value:Q.taxLocationCategory||"",disabled:!Q.taxApplicable,onChange:Ie=>is(E.id,"taxLocationCategory",Ie.target.value),children:[e.jsx("option",{value:"",children:"Select Location"}),e.jsx("option",{value:"dhaka_chattogram",children:"DNCC / DSCC / Chattogram City"}),e.jsx("option",{value:"other_city_corporation",children:"Other City Corporation"}),e.jsx("option",{value:"other_area",children:"Other Area"})]})}),d.statutoryEnabled&&d.taxEnabled&&e.jsx("td",{children:e.jsx("input",{type:"number",min:"0",inputMode:"decimal",disabled:!Q.taxApplicable,value:Q.annualEligibleInvestment??0,onChange:Ie=>is(E.id,"annualEligibleInvestment",Ie.target.value),title:"Annual eligible investment/expenditure declared by the employee for tax rebate. VERIXO applies the statutory rebate cap;
4077 keep supporting documents outside payroll."})}),d.statutoryEnabled&&d.taxEnabled&&e.jsx("td",{children:e.jsx("input",{type:"number",min:"0",inputMode:"decimal",disabled:!Q.taxApplicable,value:Q.taxWithheldBeforeVerixo??0,onChange:Ie=>is(E.id,"taxWithheldBeforeVerixo",Ie.target.value),title:"Tax already withheld in this Jul-Jun income year before VERIXO/current payroll history"})}),d.statutoryEnabled&&d.pfEnabled&&e.jsx("td",{children:e.jsxs("select",{value:Q.pfApplicable?"yes":"no",onChange:Ie=>is(E.id,"pfApplicable",Ie.target.value==="yes"),children:[e.jsx("option",{value:"no",children:"No"}),e.jsx("option",{value:"yes",children:"Yes"})]})}),d.statutoryEnabled&&d.pfEnabled&&e.jsx("td",{children:d.pfEligibilityRule==="custom"&&Q.pfApplicable?e.jsxs("div",{className:"pf-eligibility-cell",children:[e.jsx("input",{type:"date",value:Q.pfCustomStartDate??"",onChange:Ie=>is(E.id,"pfCustomStartDate",Ie.target.value)}),e.jsx("small",{children:en(E,Q).label})]}):e.jsxs("div",{className:"pf-eligibility-cell",children:[e.jsx("strong",{children:en(E,Q).label}),en(E,Q).startDate&&e.jsx("small",{children:en(E,Q).startDate})]})}),e.jsx("td",{children:e.jsx("input",{type:"text",value:Q.bankName??"",onChange:Ie=>is(E.id,"bankName",Ie.target.value),placeholder:"Bank"})}),e.jsx("td",{children:e.jsx("input",{type:"text",value:Q.bankAccount??"",onChange:Ie=>is(E.id,"bankAccount",Ie.target.value),placeholder:"Account no."})}),e.jsx("td",{children:e.jsx("input",{type:"text",value:Q.bankAccountHolder??"",onChange:Ie=>is(E.id,"bankAccountHolder",Ie.target.value),placeholder:E.name})})]},E.id)})})]})})]}),i==="advanceLoan"&&e.jsx(bU,{profile:t,branches:n,selectedBranchId:a,employees:$a}),i==="run"&&e.jsxs("section",{className:`payroll-panel ${te?"payroll-a4-landscape":""}`,children:[e.jsxs("div",{className:"panel-title",children:[e.jsxs("div",{children:[e.jsxs("h2",{children:[l," Payroll Run"]}),e.jsxs("p",{children:["At-a-glance salary sheet · Status: ",e.jsx("b",{children:(De==null?void 0:De.status)||"not generated"})," · Payment: ",e.jsx("b",{children:(De==null?void 0:De.status)==="locked"?Zt:(De==null?void 0:De.paymentStatus)||"unpaid"})]}),(De==null?void 0:De.correctionStatus)==="requested"&&e.jsxs("p",{className:"payroll-correction-note",children:[e.jsx("strong",{children:"Correction requested:"})," ",De.correctionReason||"Reason not available"]}),(De==null?void 0:De.correctionStatus)==="unlocked"&&e.jsxs("p",{className:"payroll-correction-note",children:[e.jsx("strong",{children:"Correction mode:"})," Make the required changes, then approve and lock again."]})]}),e.jsxs("div",{className:"payroll-actions",children:[e.jsxs("button",{onClick:Et,children:[e.jsx(ui,{size:16})," View Report"]}),e.jsxs("button",{onClick:()=>void Ct("download"),children:[e.jsx(Zs,{size:16})," Download PDF"]}),e.jsxs("button",{onClick:()=>void xn("preview"),children:[e.jsx(ui,{size:16})," Disbursement Report"]}),e.jsxs("button",{onClick:()=>void dn("preview"),children:[e.jsx(Zs,{size:16})," Bank Payment Sheet"]}),e.jsxs("button",{onClick:()=>Ge(E=>!E),children:[e.jsx(Zs,{size:16}),te?"Wide Edit View":"Compact Sheet View"]}),e.jsxs("button",{onClick:bs,disabled:ce||!!(De&&De.status!=="draft"),children:[e.jsx(Hi,{size:16})," Regenerate"]}),(De==null?void 0:De.status)==="draft"&&e.jsxs("button",{onClick:()=>Xo("approved"),disabled:ce,children:[e.jsx(Ms,{size:16})," Approve"]}),(De==null?void 0:De.status)==="approved"&&e.jsxs("button",{onClick:()=>Xo("locked"),disabled:ce,children:[e.jsx(q4,{size:16})," Lock Payroll"]}),(De==null?void 0:De.status)==="approved"&&wa&&e.jsxs("button",{onClick:Yl,disabled:ce,children:[e.jsx(Id,{size:16})," Return to Draft"]}),(De==null?void 0:De.status)==="locked"&&e.jsxs("button",{onClick:no,disabled:ce,children:[e.jsx(Hi,{size:16})," Sync Accounts"]}),(De==null?void 0:De.status)==="locked"&&wa&&e.jsxs(e.Fragment,{children:[e.jsxs("select",{value:ee,onChange:E=>qe(E.target.value),disabled:ce,title:"Employee to add to locked payroll",children:[e.jsx("option",{value:"",children:"Add employeeâ¦"}),$a.filter(E=>!P[E.id]).map(E=>e.jsxs("option",{value:E.id,children:[E.employeeId?`${E.employeeId} · `:"",E.name]},E.id))]}),e.jsxs("button",{onClick:Fc,disabled:ce||!ee,children:[e.jsx(Ms,{size:16})," Add to Locked Payroll"]})]}),De&&e.jsxs("button",{onClick:Bc,disabled:ce,children:[e.jsx(gs,{size:16})," Health Check"]}),(De==null?void 0:De.status)==="locked"&&De.correctionStatus!=="requested"&&e.jsxs("button",{onClick:Uc,disabled:ce,children:[e.jsx(Id,{size:16})," Request Correction"]}),(De==null?void 0:De.status)==="locked"&&De.correctionStatus==="requested"&&wa&&e.jsxs("button",{onClick:Gi,disabled:ce,children:[e.jsx(z4,{size:16})," Authorize Unlock"]})]})]}),De&&e.jsxs("div",{className:"payroll-workflow-strip",children:[e.jsxs("span",{className:De.status==="draft"?"active":"done",children:[e.jsx("b",{children:"1"})," Draft"]}),e.jsx("i",{}),e.jsxs("span",{className:De.status==="approved"?"active":De.status==="locked"?"done":"",children:[e.jsx("b",{children:"2"})," Approved"]}),e.jsx("i",{}),e.jsxs("span",{className:De.status==="locked"?"active":"",children:[e.jsx("b",{children:"3"})," Locked"]}),De.correctionStatus==="unlocked"&&e.jsx("em",{children:"Correction Mode"}),De.correctionStatus==="requested"&&e.jsx("em",{children:"Correction Requested"})]}),nt&&e.jsxs("div",{className:`payroll-health-panel ${nt.status}`,children:[e.jsxs("div",{className:"payroll-health-heading",children:[nt.status==="healthy"?e.jsx(gs,{size:18}):e.jsx(qu,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:nt.status==="healthy"?"Payroll Health Check Passed":`Payroll Health Check · ${nt.issues.length} Issue${nt.issues.length===1?"":"s"}`}
4077),e.jsx("small",{children:new Date(nt.checkedAt).toLocaleString()})]})]}),nt.issues.length>0&&e.jsx("ul",{children:nt.issues.map((E,Q)=>e.jsx("li",{children:E},`${Q}-${E}`))})]}),e.jsxs("div",{className:"payroll-sheet-summary",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Employees"}),e.jsx("b",{children:_n.length})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Gross Payroll"}),e.jsxs("b",{children:["à§³ ",pn(ha.gross)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Total Addition"}),e.jsxs("b",{children:["à§³ ",pn(ha.addition)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Total Deduction"}),e.jsxs("b",{children:["à§³ ",pn(ha.deduction)]})]}),d.statutoryEnabled&&d.taxEnabled&&d.taxEngineMode==="approved_rule"&&e.jsxs("span",{children:[e.jsx("small",{children:"Employee Tax"}),e.jsxs("b",{children:["à§³ ",pn(_n.reduce((E,Q)=>E+Number(Q.monthlyTax||0),0))]})]}),d.statutoryEnabled&&d.pfEnabled&&e.jsxs("span",{children:[e.jsx("small",{children:"Employee PF"}),e.jsxs("b",{children:["à§³ ",pn(ha.employeePf)]})]}),d.statutoryEnabled&&d.pfEnabled&&e.jsxs("span",{children:[e.jsx("small",{children:"Employer PF"}),e.jsxs("b",{children:["à§³ ",pn(ha.employerPf)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Net Payable"}),e.jsxs("b",{children:["à§³ ",pn(ha.net)]})]})]}),(De==null?void 0:De.status)==="locked"&&e.jsxs("div",{className:"payroll-payment-summary",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Salary Payable"}),e.jsxs("b",{children:["à§³ ",pn(ta.payable)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Employee Recoverable"}),e.jsxs("b",{children:["à§³ ",pn(ta.recoverable)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Paid"}),e.jsxs("b",{children:["à§³ ",pn(ft.paid)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Outstanding"}),e.jsxs("b",{children:["à§³ ",pn(ft.pending)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Paid Employees"}),e.jsx("b",{children:ft.paidEmployees})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Partial"}),e.jsx("b",{children:ft.partialEmployees})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Unpaid"}),e.jsx("b",{children:ft.unpaidEmployees})]})]}),(De==null?void 0:De.status)==="locked"&&e.jsxs("details",{className:"payroll-salary-history",open:Ve.length>0,children:[e.jsxs("summary",{children:["Salary Payment History (",Ve.length,")"]}),Ve.length===0?e.jsx("p",{children:"No salary payment has been recorded for this payroll month."}):e.jsx("div",{className:"payroll-statutory-history-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Paid From"}),e.jsx("th",{children:"Sent To"}),e.jsx("th",{children:"Reference"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Recorded By"}),e.jsx("th",{children:"Reversal Audit"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:Ve.map(E=>
4077e.jsxs("tr",{className:E.status==="reversed"?"payment-history-row-reversed":"",children:[e.jsx("td",{children:E.paymentDate}),e.jsxs("td",{children:[e.jsx("strong",{children:E.employeeName}),(E.employeeCode||E.employeeId)&&e.jsxs("small",{className:"employee-id-inline",children:[" (",E.employeeCode||E.employeeId,")"]})]}),e.jsxs("td",{children:["à§³ ",pn(E.amount),Number(E.roundingAdjustment||0)<0&&e.jsxs("small",{className:"payment-reversal-reason",children:["Rounding -à§³ ",pn(Math.abs(Number(E.roundingAdjustment||0)))]})]}),e.jsx("td",{children:E.method.toUpperCase()}),e.jsx("td",{children:E.method==="bank"?E.sourceBankName||"â":E.method.toUpperCase()}),e.jsx("td",{children:(()=>{const Q=_n.find(Dt=>Dt.employeeId===E.employeeId),Ie=Q?ke(Q):{bankName:"",bankAccount:"",bankAccountHolder:""},Le=(E.receivingBankAccountHolder&&E.receivingBankAccountHolder!==E.employeeName?E.receivingBankAccountHolder:Ie.bankAccountHolder)||E.employeeName||"â",He=E.receivingBankAccount||Ie.bankAccount||"",gt=He?`â¢â¢â¢â¢${String(He).slice(-4)}`:"â";return e.jsxs(e.Fragment,{children:[E.receivingBankName||Ie.bankName||"â",e.jsxs("small",{className:"payment-reversal-reason",children:[Le," · A/C ",gt]})]})})()}),e.jsx("td",{children:E.reference||"â"}),e.jsxs("td",{children:[e.jsx("span",{className:`payment-history-status ${E.status==="reversed"?"reversed":"active"}`,children:E.status==="reversed"?"Reversed":"Active"}),E.status==="reversed"&&E.reversalReason&&e.jsx("small",{className:"payment-reversal-reason",children:E.reversalReason})]}),e.jsx("td",{children:E.createdByName||"â"}),e.jsx("td",{children:E.status==="reversed"?e.jsxs("span",{className:"payment-reversal-audit",children:[e.jsxs("small",{children:[e.jsx("b",{children:"Reason:"})," ",E.reversalReason||"â"]}),e.jsxs("small",{children:[e.jsx("b",{children:"By:"})," ",E.reversedByName||"â"]}),e.jsxs("small",{children:[e.jsx("b",{children:"At:"})," ",E.reversedAt?new Date(Number(E.reversedAt)).toLocaleString("en-GB"):"â"]})]}):"â"}),e.jsx("td",{children:In&&E.status!=="reversed"?e.jsx("button",{type:"button",className:"vx-button vx-button-secondary payment-reverse-button",disabled:ce,onClick:()=>zc(E.employeeId,E),children:"Reverse"}):"â"})]},`${E.employeeId}-${E.id}`))})]})})]}),(De==null?void 0:De.status)==="locked"&&(d.statutoryEnabled||ha.tax>0||ha.employeePf>0||ha.employerPf>0)&&e.jsxs("section",{className:"payroll-statutory-settlement",children:[e.jsxs("div",{className:"payroll-statutory-settlement-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Tax / PF Statutory Settlement"}),e.jsx("small",{children:"Record deposits only after payment/challan is actually completed. Every entry is retained in settlement history."})]}),e.jsx("span",{className:`statutory-status ${oe.status}`,children:oe.status==="paid"?"Fully Settled":oe.status==="partially_paid"?"Partially Settled":"Unpaid"})]}),e.jsxs("div",{className:"payroll-statutory-cards",children:[(vt.tax>0||d.taxEnabled&&d.taxEngineMode==="approved_rule")&&e.jsxs("article",{children:[e.jsx("small",{children:"Employee Income Tax"}),e.jsxs("b",{children:["à§³ ",pn(vt.tax)]}),e.jsxs("span",{children:["Paid à§³ ",pn(Math.min(Ae.tax,vt.tax))]}),e.jsxs("em",{children:["Outstanding à§³ ",pn(oe.taxOutstanding)]}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary statutory-pay-button",disabled:ce||!Sa||oe.taxOutstanding<=0,title:Sa?void 0:"Permission required: Record Tax / PF Settlement",onClick:()=>bc("tax"),children:[e.jsx(Ms,{size:15})," ",Ae.tax>0?"Add Tax Payment":"Record Tax Payment"]})]}),(d.pfEnabled||vt.employee_pf>0||vt.employer_pf>0)&&e.jsxs(e.Fragment,{children:[e.jsxs("article",{children:[e.jsx("small",{children:"Employee PF"}),e.jsxs("b",{children:["à§³ ",pn(vt.employee_pf)]}),e.jsxs("span",{children:["Paid à§³ ",pn(Math.min(Ae.employee_pf,vt.employee_pf))]}),e.jsxs("em",{children:["Outstanding à§³ ",pn(oe.employeePfOutstanding)]}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary statutory-pay-button",disabled:ce||!Sa||oe.employeePfOutstanding<=0,title:Sa?void 0:"Permission required: Record Tax / PF Settlement",onClick:()=>bc("employee_pf"),children:[e.jsx(Ms,{size:15})," ",Ae.employee_pf>0?"Add Employee PF Payment":"Record Employee PF"]})]}),e.jsxs("article",{children:[e.jsx("small",{children:"Employer PF"}),e.jsxs("b",{children:["à§³ ",pn(vt.employer_pf)]}),e.jsxs("span",{children:["Paid à§³ ",pn(Math.min(Ae.employer_pf,vt.employer_pf))]}),e.jsxs("em",{children:["Outstanding à§³ ",pn(oe.employerPfOutstanding)]}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary statutory-pay-button",disabled:ce||!Sa||oe.employerPfOutstanding<=0,title:Sa?void 0:"Permission required: Record Tax / PF Settlement",onClick:()=>bc("employer_pf"),children:[e.jsx(Ms,{size:15})," ",Ae.employer_pf>0?"Add Employer PF Payment":"Record Employer PF"]})]})]})]}),e.jsxs("div",{className:"payroll-statutory-total",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Total Liability"}),e.jsxs("b",{children:["à§³ ",pn(oe.liabilityTotal)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Total Paid"}),e.jsxs("b",{children:["à§³ ",pn(oe.paidTotal)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Total Outstanding"}),e.jsxs("b",{children:["à§³ ",pn(oe.outstandingTotal)]})]})]}),e.jsxs("details",{className:"payroll-statutory-history",children:[e.jsxs("summary",{children:["Settlement History (",he.length,")"]}),he.length===0?e.jsx("p",{children:"No statutory payment has been recorded for this payroll month."}):e.jsx("div",{className:"payroll-statutory-history-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Amount"}),e.jsx("th",{children:"Method"}),e.jsx("th",{children:"Reference"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Recorded By"}
4077),e.jsx("th",{children:"Reversal Audit"}),e.jsx("th",{children:"Action"})]})}),e.jsx("tbody",{children:he.map(E=>e.jsxs("tr",{children:[e.jsx("td",{children:E.paymentDate}),e.jsx("td",{children:E.liabilityType==="tax"?"Income Tax":E.liabilityType==="employee_pf"?"Employee PF":"Employer PF"}),e.jsxs("td",{children:["à§³ ",pn(E.amount)]}),e.jsx("td",{children:E.method.toUpperCase()}),e.jsx("td",{children:E.reference||"â"}),e.jsx("td",{children:e.jsx("span",{className:`payment-history-status ${E.status==="reversed"?"reversed":"active"}`,children:E.status==="reversed"?"Reversed":"Active"})}),e.jsx("td",{children:E.createdByName||"â"}),e.jsx("td",{children:E.status==="reversed"?e.jsxs("span",{className:"payment-reversal-audit",children:[e.jsxs("small",{children:[e.jsx("b",{children:"Reason:"})," ",E.reversalReason||"â"]}),e.jsxs("small",{children:[e.jsx("b",{children:"By:"})," ",E.reversedByName||"â"]}),e.jsxs("small",{children:[e.jsx("b",{children:"At:"})," ",E.reversedAt?new Date(Number(E.reversedAt)).toLocaleString("en-GB"):"â"]})]}):"â"}),e.jsx("td",{children:aa&&E.status!=="reversed"?e.jsx("button",{type:"button",className:"vx-button vx-button-secondary payment-reverse-button",disabled:ce,onClick:()=>qc(E.liabilityType,E),children:"Reverse"}):"â"})]},E.id))})]})})]})]}),(B||dt||rt||tt===0||z.length===0)&&e.jsxs("div",{className:"payroll-source-diagnostic",children:[e.jsx("strong",{children:"Payroll Data Source Check"}),e.jsxs("span",{children:["Company ID: ",e.jsx("code",{children:t.companyId})]}),e.jsxs("span",{children:["Employee path: ",e.jsxs("code",{children:["employees/",t.companyId]})]}),e.jsxs("span",{children:["Raw employees: ",e.jsx("b",{children:tt})," · Active employees: ",e.jsx("b",{children:z.length})," · Visible for branch: ",e.jsx("b",{children:$a.length})]}),e.jsxs("span",{children:["Salary structures: ",e.jsx("b",{children:Object.keys(Z).length})," · Payroll items (",l,"): ",e.jsx("b",{children:Object.keys(P).length})]}),B&&e.jsxs("span",{className:"payroll-source-error",children:["Employee read error: ",B]}),dt&&e.jsxs("span",{className:"payroll-source-error",children:["Salary structure read error: ",dt]}),rt&&e.jsxs("span",{className:"payroll-source-error",children:["Payroll item read error: ",rt]}),e.jsx("small",{children:"Safety guard is active: VERIXO will not regenerate/overwrite payroll while employee count is zero."})]}),e.jsxs("div",{className:"payroll-deduction-note payroll-precheck-bar",children:[e.jsx("strong",{children:"Payroll Pre-Check:"}),[["missingPunch","Missing Punch",jn.missingPunch],["pendingLeave","Pending Leave",jn.pendingLeave],["reviewRequired","Review Required",jn.reviewRequired],["unclassified","Unclassified",jn.unclassified],["missingSalary","Missing Gross Salary",jn.missingSalary]].map(([E,Q,Ie])=>e.jsxs("button",{type:"button",className:`payroll-precheck-chip ${Ie>0?"warning":"clear"}`,disabled:Ie<=0,onClick:()=>$t(E),title:Ie>0?`View ${Q} details`:`No ${Q} issue`,children:[e.jsx("span",{children:Q}),e.jsx("b",{children:Ie})]},E)),e.jsx("small",{children:jn.hasWarnings?"Generate/Regenerate à¦à¦°à¦²à§ confirmation warning দà§à¦à¦¾à¦¬à§. সà¦à¦à§à¦¯à¦¾ click à¦à¦°à§ affected records দà§à¦à§à¦¨.":"No warning detected for the selected month/branch."})]}),e.jsxs("div",{className:"payroll-deduction-note",children:["Attendance deduction = Absent days + Unpaid Leave + Late deduction days",d.deductHalfDay?` + Half Day à ${Number(d.halfDayDeductionRate??.5)}`:" (Half Day deduction is OFF)",". Paid Leave and Official Day Off are protected. Hover the Attendance Ded. amount to see the employee-level breakdown."]}),e.jsxs("div",{className:"payroll-deduction-note",children:["Advance/Loan Recovery is matched to the ",e.jsx("strong",{children:"Salary Month"}),", not the salary payment date. Example: an August advance set to recover from August Salary will be deducted from the August payroll even if that salary is paid in September."]}),d.statutoryEnabled&&d.pfEnabled&&e.jsxs("div",{className:"payroll-deduction-note payroll-pf-note",children:["PF: Eligible employees contribute ",Number(d.pfEmployeeRate||0),"% of ",d.pfBasis==="basic"?"Basic Salary":"Gross Salary","; employer contributes ",Number(d.pfEmployerRate||0),"%. Employee PF reduces Net Pay; Employer PF is tracked separately."]}),e.jsx("div",{className:"payroll-table-wrap payroll-a4-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"ID"}),e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Gross"}),e.jsx("th",{children:"Work Days"}),e.jsx("th",{children:"Absent"}),e.jsx("th",{children:"Late"}),e.jsx("th",{children:"Half Day"}),e.jsx("th",{children:"Paid Leave"}),e.jsx("th",{children:"Unpaid Leave"}),e.jsx("th",{children:"Official Day Off"}),e.jsx("th",{children:"Attendance Ded."}),e.jsx("th",{children:"Advance / Loan / Other"}),d.statutoryEnabled&&d.taxEnabled&&d.taxEngineMode==="approved_rule"&&e.jsx("th",{children:"Tax"}),d.statutoryEnabled&&d.pfEnabled&&e.jsx("th",{children:"Employee PF"}),d.statutoryEnabled&&d.pfEnabled&&e.jsx("th",{children:"Employer PF"}),e.jsx("th",{children:"Addition"}),e.jsx("th",{children:"Net Payable"}),e.jsx("th",{children:"Bank"}),e.jsx("th",{children:"A/C No."}),e.jsx("th",{children:"A/C Holder"}),e.jsx("th",{children:"Payment"}),e.jsx("th",{children:"Details"})]})}),e.jsx("tbody",{children:_n.map(E=>{const Q=E.overtimeAmount+E.festivalBonus+E.performanceBonus+E.incentive+E.otherAddition,Ie=E.advanceDeduction+E.loanDeduction,Le=E.fineDeduction+E.otherDeduction;return e.jsxs("tr",{children:[e.jsx("td",{children:E.employeeCode||"â"}),e.jsx("td",{children:e.jsx("strong",{children:E.employeeName})}),e.jsxs("td",{children:["à§³ ",pn(E.grossSalary)]}),e.jsx("td",{children:E.workingDays}),e.jsx("td",{children:E.absentDays}),e.jsx("td",{children:E.lateCount}),e.jsx("td",{children:E.halfDayCount||0}),e.jsx("td",{children:E.paidLeaveDays||0}),e.jsx("td",{children:E.unpaidLeaveDays||0}),e.jsx("td",{children:E.officialDayOffDays||0}),e.jsxs("td",{title:`Absent: ${E.absentDays} day(s), Unpaid leave: ${E.unpaidLeaveDays||0} day(s), Paid leave: ${E.paidLeaveDays||0} day(s) protected, Official Day Off: ${E.officialDayOffDays||0} day(s) protected, Late deduction: ${E.lateDeductionDays} day(s), Half day: ${E.halfDayCount||0}${d.deductHalfDay?` (${(E.halfDayCount||0)*Number(d.halfDayDeductionRate??.5)} deductible day)`:" (no salary deduction)"}`,children:["à§³ ",pn(E.attendanceDeduction)]}),e.jsxs("td",{children:["à§³ ",pn(Ie+Le)]}),d.statutoryEnabled&&d.taxEnabled&&d.taxEngineMode==="approved_rule"&&e.jsx("td",{children:E.taxApplicable?e.jsxs("button",{type:"button",className:"payroll-tax-detail-link",onClick:()=>G(E),children:["à§³ ",pn(Number(E.monthlyTax||0))]}):e.jsx("span",{children:"à§³ 0.00"})}),d.statutoryEnabled&&d.pfEnabled&&e.jsxs("td",{title:E.pfEligible?`PF basis: à§³ ${pn(Number(E.pfBasisAmount||0))} · Start: ${E.pfStartDate||"â"}`:"Not PF eligible for this payroll month",children:["à§³ ",pn(Number(E.employeePf||0))]}),d.statutoryEnabled&&d.pfEnabled&&e.jsxs("td",{title:"Employer contribution â not deducted from employee Net Pay",children:["à§³ ",pn(Number(E.employerPf||0))]}),e.jsxs("td",{children:["à§³ ",pn(Q)]}),e.jsx("td",{className:"payroll-net-cell",children:e.jsxs("strong",{children:["à§³ ",pn(E.netPay)]})}),e.jsx("td",{children:ke(E).bankName||"â"}),e.jsx("td",{className:"payroll-account-cell",children:ke(E).bankAccount||"â"}),e.jsx("td",{children:ke(E).bankAccountHolder||E.employeeName}),e.jsxs("td",{className:"payroll-payment-cell",children:[(()=>{const He=pr(E);return e.jsx("span",{className:`payroll-payment-badge ${He.status}`,children:He.status.replace("_"," ")})})(),(()=>{const He=Object.values(me[E.employeeId]||{}
4077).filter(Bt=>(Bt==null?void 0:Bt.status)!=="reversed"),gt=He.reduce((Bt,En)=>Bt+Math.max(Number((En==null?void 0:En.amount)||0),0),0),Dt=He.reduce((Bt,En)=>Bt+Math.max(-Number((En==null?void 0:En.roundingAdjustment)||0),0),0),Yt=Math.max(Number(E.netPay||0),0),vn=W[E.employeeId],zt=Math.min(vn!==void 0?vn:Number(E.paidAmount||0),Yt);return zt<=0?null:He.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("small",{children:["Bank/Cash Paid: ৳ ",pn(gt)]}),Dt>0&&e.jsxs("small",{children:["Rounding: -৳ ",pn(Dt)]}),e.jsxs("small",{children:["Outstanding: ৳ ",pn(Math.max(Yt-zt,0))]})]}):e.jsxs("small",{children:["Paid: ৳ ",pn(zt)]})})(),E.paymentMethod&&e.jsxs("small",{children:[E.paymentMethod.toUpperCase(),E.paymentDate?` · ${E.paymentDate}`:""]}),(De==null?void 0:De.status)==="locked"&&(()=>{const He=Math.max(E.netPay,0),gt=W[E.employeeId],Dt=Math.min(gt!==void 0?gt:Number(E.paidAmount||0),He);return He<=0||Dt>=He?null:e.jsx("button",{type:"button",disabled:ce||!Ca,title:Ca?void 0:"Permission required: Record Salary Payment",className:"vx-button vx-button-secondary payroll-row-pay-button",onClick:()=>Oi(E),children:Dt>0?"Add Payment":"Record Payment"})})()]}),e.jsxs("td",{children:[e.jsxs("button",{type:"button",className:"vx-button vx-button-secondary payroll-payslip-button",onClick:()=>void Rt(E),children:[e.jsx(Zs,{size:14})," Payslip"]}),e.jsxs("details",{children:[e.jsx("summary",{children:"Adjust"}),e.jsxs("div",{className:"payroll-adjust-grid",children:[d.overtimeEnabled&&e.jsxs("label",{children:["OT Hours",e.jsx("input",{type:"number",min:"0",step:"0.5",disabled:!!(De&&De.status!=="draft"),value:E.overtimeHours||0,onChange:He=>Wa(E.employeeId,"overtimeHours",Number(He.target.value))})]}),e.jsxs("label",{children:["Festival Bonus",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.festivalBonus||0,onChange:He=>Wa(E.employeeId,"festivalBonus",Number(He.target.value))})]}),e.jsxs("label",{children:["Performance Bonus",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.performanceBonus||0,onChange:He=>Wa(E.employeeId,"performanceBonus",Number(He.target.value))})]}),e.jsxs("label",{children:["Incentive",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.incentive||0,onChange:He=>Wa(E.employeeId,"incentive",Number(He.target.value))})]}),e.jsxs("label",{children:["Other Addition",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.otherAddition||0,onChange:He=>Wa(E.employeeId,"otherAddition",Number(He.target.value))})]}),e.jsxs("label",{children:["Advance",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.advanceDeduction||0,onChange:He=>Wa(E.employeeId,"advanceDeduction",Number(He.target.value))})]}),e.jsxs("label",{children:["Loan",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.loanDeduction||0,onChange:He=>Wa(E.employeeId,"loanDeduction",Number(He.target.value))})]}),e.jsxs("label",{children:["Fine",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.fineDeduction||0,onChange:He=>Wa(E.employeeId,"fineDeduction",Number(He.target.value))})]}),e.jsxs("label",{children:["Other Deduction",e.jsx("input",{type:"number",min:"0",disabled:!!(De&&De.status!=="draft"),value:E.otherDeduction||0,onChange:He=>Wa(E.employeeId,"otherDeduction",Number(He.target.value))})]}),e.jsxs("label",{className:"wide",children:["Remarks",e.jsx("input",{type:"text",disabled:!!(De&&De.status!=="draft"),value:E.remarks||"",onChange:He=>Wa(E.employeeId,"remarks",He.target.value)})]})]})]})]})]},E.employeeId)})}),e.jsx("tfoot",{children:e.jsxs("tr",{children:[e.jsx("td",{colSpan:2,children:"Grand Total"}),e.jsxs("td",{children:["৳ ",pn(ha.gross)]}),e.jsx("td",{colSpan:5}),e.jsxs("td",{children:["৳ ",pn(ha.addition)]}),e.jsxs("td",{children:["৳ ",pn(ha.net)]}),e.jsx("td",{colSpan:4})]})})]})})]}),Se&&(()=>{const E=P[Se.employeeId],Q=Se.tx;return e.jsx("div",{className:"payroll-modal-backdrop",role:"presentation",onMouseDown:Ie=>{Ie.target===Ie.currentTarget&&!ce&&Me(null)},children:e.jsxs("div",{className:"payroll-payment-modal payroll-reversal-modal",role:"dialog","aria-modal":"true","aria-labelledby":"salary-reversal-title",children:[e.jsxs("div",{className:"payroll-payment-modal-head",children:[e.jsxs("div",{children:[e.jsx("small",{children:"SALARY PAYMENT CORRECTION"}
4077),e.jsx("h3",{id:"salary-reversal-title",children:"Reverse Salary Payment"}),e.jsxs("p",{children:[(E==null?void 0:E.employeeName)||"Employee"," (",(E==null?void 0:E.employeeCode)||Se.employeeId,")"]})]}),e.jsx("button",{type:"button",className:"payroll-modal-close",disabled:ce,onClick:()=>Me(null),"aria-label":"Close",children:"Ã"})]}),e.jsxs("div",{className:"payroll-payment-kpis payroll-reversal-kpis",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Payment Amount"}),e.jsxs("b",{children:["à§³ ",pn(Q.amount)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Payment Date"}),e.jsx("b",{children:Q.paymentDate})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Method"}),e.jsx("b",{children:Q.method.toUpperCase()})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Reference"}),e.jsx("b",{children:Q.reference||"â"})]})]}),e.jsx("div",{className:"payroll-reversal-form",children:e.jsxs("label",{children:["Reversal Reason ",e.jsx("em",{children:"*"}),e.jsx("textarea",{rows:4,value:Se.reason,placeholder:"Explain why this salary payment entry is being reversed...",onChange:Ie=>Me(Le=>Le&&{...Le,reason:Ie.target.value}),autoFocus:!0})]})}),e.jsx("div",{className:"payroll-payment-modal-note payroll-reversal-warning",children:"This action does not delete the original salary payment. It marks the transaction as Reversed, recalculates Paid/Outstanding, and keeps the complete audit trail."}),e.jsxs("div",{className:"payroll-payment-modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:ce,onClick:()=>Me(null),children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",disabled:ce||!Se.reason.trim(),onClick:()=>void Zo(),children:[e.jsx(Ms,{size:16})," ",ce?"Reversing...":"Confirm Reversal"]})]})]})})})(),ct&&(()=>{const E={tax:"Employee Income Tax",employee_pf:"Employee PF",employer_pf:"Employer PF"},Q=ct.liabilityType,Ie=E[Q],Le=vt[Q],He=Math.min(Ae[Q],Le),gt=Math.max(Le-He,0),Dt=Math.max(Number(ct.amount||0),0);return e.jsx("div",{className:"payroll-modal-backdrop",role:"presentation",onMouseDown:Yt=>{Yt.target===Yt.currentTarget&&!ce&&Ce(null)},children:e.jsxs("div",{className:"payroll-payment-modal",role:"dialog","aria-modal":"true","aria-labelledby":"statutory-payment-title",children:[e.jsxs("div",{className:"payroll-payment-modal-head",children:[e.jsxs("div",{children:[e.jsx("small",{children:"STATUTORY SETTLEMENT"}),e.jsxs("h3",{id:"statutory-payment-title",children:["Record ",Ie," Payment"]}),e.jsxs("p",{children:[l," · Record only after actual payment/challan completion"]})]}),e.jsx("button",{type:"button",className:"payroll-modal-close",disabled:ce,onClick:()=>Ce(null),"aria-label":"Close",children:"Ã"})]}),e.jsxs("div",{className:"payroll-payment-kpis",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Liability"}),e.jsxs("b",{children:["à§³ ",pn(Le)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Already Paid"}),e.jsxs("b",{children:["à§³ ",pn(He)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Outstanding"}),e.jsxs("b",{children:["à§³ ",pn(gt)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"After This Payment"}),e.jsxs("b",{children:["à§³ ",pn(Math.max(gt-Dt,0))]})]})]}),e.jsxs("div",{className:"payroll-payment-form",children:[e.jsxs("label",{children:["Payment Amount (BDT)",e.jsx("input",{type:"number",min:"0.01",step:"0.01",max:gt,value:ct.amount,onChange:Yt=>Ce(vn=>vn&&{...vn,amount:Yt.target.value}),autoFocus:!0})]}),e.jsxs("label",{children:["Payment Method",e.jsxs("select",{value:ct.method,onChange:Yt=>Ce(vn=>vn&&{...vn,method:Yt.target.value}),children:[e.jsx("option",{value:"bank",children:"Bank"}),e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"other",children:"Other"})]})]}),e.jsxs("label",{children:["Payment Date",e.jsx("input",{type:"date",value:ct.paymentDate,onChange:Yt=>Ce(vn=>vn&&{...vn,paymentDate:Yt.target.value})})]}),e.jsxs("label",{children:["Challan / Reference No.",e.jsx("input",{type:"text",value:ct.reference,placeholder:"Challan no., bank ref, transaction ID...",onChange:Yt=>Ce(vn=>vn&&{...vn,reference:Yt.target.value})})]})]}),e.jsx("div",{className:"payroll-payment-modal-note",children:"This records an auditable statutory settlement transaction. It does not change payroll Tax/PF calculation or employee Net Pay."}),e.jsxs("div",{className:"payroll-payment-modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:ce,onClick:()=>Ce(null),children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",disabled:ce||Dt<=0||Dt>gt,onClick:()=>void vl(),children:[e.jsx(Ms,{size:16})," ",ce?"Saving...":"Confirm Payment"]})]})]})})})(),ot&&(()=>{const Q={tax:"Employee Income Tax",employee_pf:"Employee PF",employer_pf:"Employer PF"}[ot.liabilityType],Ie=ot.tx;return e.jsx("div",{className:"payroll-modal-backdrop",role:"presentation",onMouseDown:Le=>{Le.target===Le.currentTarget&&!ce&&wt(null)},children:e.jsxs("div",{className:"payroll-payment-modal payroll-reversal-modal",role:"dialog","aria-modal":"true","aria-labelledby":"statutory-reversal-title",children:[e.jsxs("div",{className:"payroll-payment-modal-head",children:[e.jsxs("div",{children:[e.jsx("small",{children:"STATUTORY SETTLEMENT CORRECTION"}),e.jsxs("h3",{id:"statutory-reversal-title",children:["Reverse ",Q," Payment"]}),e.jsxs("p",{children:[l," · Original transaction retained permanently"]})]}),e.jsx("button",{type:"button",className:"payroll-modal-close",disabled:ce,onClick:()=>wt(null),"aria-label":"Close",children:"Ã"})]}),e.jsxs("div",{className:"payroll-payment-kpis payroll-reversal-kpis",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Payment Amount"}),e.jsxs("b",{children:["à§³ ",pn(Ie.amount)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Payment Date"}),e.jsx("b",{children:Ie.paymentDate})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Method"}),e.jsx("b",{children:Ie.method.toUpperCase()})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Reference"}),e.jsx("b",{children:Ie.reference||"â"})]})]}),e.jsx("div",{className:"payroll-reversal-form",children:e.jsxs("label",{children:["Reversal Reason ",e.jsx("em",{children:"*"}),e.jsx("textarea",{rows:4,value:ot.reason,placeholder:"Explain why this statutory payment/ch
4077allan entry is being reversed...",onChange:Le=>wt(He=>He&&{...He,reason:Le.target.value}),autoFocus:!0})]})}),e.jsx("div",{className:"payroll-payment-modal-note payroll-reversal-warning",children:"This does not delete the original transaction. It marks it Reversed, recalculates statutory Paid/Outstanding, and preserves the complete audit trail."}),e.jsxs("div",{className:"payroll-payment-modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:ce,onClick:()=>wt(null),children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",disabled:ce||!ot.reason.trim(),onClick:()=>void ec(),children:[e.jsx(Ms,{size:16})," ",ce?"Reversing...":"Confirm Reversal"]})]})]})})})(),se&&(()=>{const E=se.item,Q=Math.max(Number(E.netPay||0),0),Ie=W[E.employeeId],Le=Math.min(Ie!==void 0?Ie:Math.max(Number(E.paidAmount||0),0),Q),He=Math.max(Q-Le,0),gt=Math.max(Number(se.amount||0),0),Dt=Math.max(He-gt,0),Yt=Dt>1e-4&&Dt<1,vn=se.settleRounding&&Yt?0:Dt;return e.jsx("div",{className:"payroll-modal-backdrop",role:"presentation",onMouseDown:zt=>{zt.target===zt.currentTarget&&!ce&&pe(null)},children:e.jsxs("div",{className:"payroll-payment-modal",role:"dialog","aria-modal":"true","aria-labelledby":"salary-payment-title",children:[e.jsxs("div",{className:"payroll-payment-modal-head",children:[e.jsxs("div",{children:[e.jsx("small",{children:"SALARY SETTLEMENT"}),e.jsx("h3",{id:"salary-payment-title",children:"Review Salary Payment"}),e.jsxs("p",{children:[E.employeeName," (",E.employeeCode||E.employeeId,")"]})]}),e.jsx("button",{type:"button",className:"payroll-modal-close",disabled:ce,onClick:()=>pe(null),"aria-label":"Close",children:"Ã"})]}),e.jsxs("div",{className:"payroll-payment-kpis",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Net Payable"}),e.jsxs("b",{children:["à§³ ",pn(Q)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Already Paid"}),e.jsxs("b",{children:["à§³ ",pn(Le)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Outstanding"}),e.jsxs("b",{children:["à§³ ",pn(He)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"After This Payment"}),e.jsxs("b",{children:["à§³ ",pn(vn)]})]})]}),e.jsxs("div",{className:"payroll-payment-form",children:[e.jsxs("label",{children:["Payment Amount (BDT)",e.jsx("input",{type:"number",min:"0.01",step:"0.01",max:He,value:se.amount,onChange:zt=>pe(Bt=>Bt&&{...Bt,amount:zt.target.value,settleRounding:!1,confirmed:!1}),autoFocus:!0})]}),e.jsxs("label",{children:["Payment Method",e.jsxs("select",{value:se.method,onChange:zt=>pe(Bt=>Bt&&{...Bt,method:zt.target.value}),children:[e.jsx("option",{value:"bank",children:"Bank"}),e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"other",children:"Other"})]})]}),se.method==="bank"&&e.jsxs("label",{children:["Paid From Bank Account *",e.jsxs("select",{value:se.sourceBankAccountId,onChange:zt=>pe(Bt=>Bt&&{...Bt,sourceBankAccountId:zt.target.value,confirmed:!1}),children:[e.jsx("option",{value:"",children:"Select company bank account"}),de.map(zt=>e.jsxs("option",{value:zt.id,children:[zt.bankName||zt.name||"Bank"," · ",zt.accountName||"Account"," · ",zt.accountNumber||"â"]},zt.id))]}),de.length===0&&e.jsx("small",{children:"No active Bank Setup account with ledger mapping is available."})]}),e.jsxs("label",{children:["Payment Date",e.jsx("input",{type:"date",value:se.paymentDate,onChange:zt=>pe(Bt=>Bt&&{...Bt,paymentDate:zt.target.value})})]}),e.jsxs("label",{children:["Reference / Transaction ID",e.jsx("input",{type:"text",value:se.reference,placeholder:"Bank ref, voucher no., note...",onChange:zt=>pe(Bt=>Bt&&{...Bt,reference:zt.target.value})})]})]}),Yt&&e.jsx("div",{className:"payroll-payment-confirm-box payroll-rounding-settlement-box",children:e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:se.settleRounding,onChange:zt=>pe(Bt=>Bt&&{...Bt,settleRounding:zt.target.checked,confirmed:!1})}),e.jsxs("span",{children:[e.jsxs("strong",{children:["Settle remaining à§³ ",pn(Dt)," as Salary Rounding Adjustment"]}),e.jsxs("small",{children:["Only a remaining amount below à§³1 can be closed here. Actual bank/cash payment stays à§³ ",pn(gt)," and the rounding adjustment is kept in the audit trail."]})]})]})}),se.method==="bank"&&e.jsxs("div",{className:"payroll-payment-modal-note",children:[e.jsx("strong",{children:"Employee Receiving Account â Read Only"}),e.jsx("br",{}),ke(E).bankName||"Bank not configured"," · ",ke(E).bankAccountHolder||E.employeeName," · A/C ",ke(E).bankAccount||"Not configured",e.jsx("br",{}),e.jsx("small",{children:"Verify that the salary was actually sent to this registered employee account. This does not control the company accounting source bank."})]}),e.jsx("div",{className:"payroll-payment-confirm-box",children:e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:se.confirmed,onChange:zt=>pe(Bt=>
4077Bt&&{...Bt,confirmed:zt.target.checked})}),e.jsxs("span",{children:[e.jsx("strong",{children:"Confirm payment details"}),e.jsx("small",{children:"I checked the employee, amount, payment method and actual payment date."})]})]})}),e.jsx("div",{className:"payroll-payment-modal-note",children:"Record Payment only opens this review form. No salary payment is posted until Confirm Payment is pressed. Payment Date must be the actual cash/bank payment date, even when the payroll belongs to an earlier salary month."}),Be&&e.jsxs("div",{className:"payroll-payment-modal-note",role:"alert",style:{borderColor:"#b91c1c",background:"#fff7f7",color:"#991b1b"},children:[e.jsx("strong",{children:"Payment not posted"}),e.jsx("br",{}),Be]}),e.jsxs("div",{className:"payroll-payment-modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:ce,onClick:()=>pe(null),children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",disabled:ce||gt<=0||gt>He||!se.paymentDate||se.method==="bank"&&!se.sourceBankAccountId||!se.confirmed,onClick:()=>void tc(),children:[e.jsx(Ms,{size:16})," ",ce?"Saving...":"Confirm Payment"]})]})]})})})(),i==="settings"&&e.jsxs("section",{className:"payroll-panel payroll-settings",children:[e.jsx("div",{className:"panel-title",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Payroll Settings"}),e.jsx("p",{children:"Company-specific payroll rules. Optional features stay hidden when disabled."})]})}),e.jsxs("div",{className:"payroll-form-grid",children:[e.jsxs("label",{children:["Late count for 1 day deduction",e.jsx("input",{type:"number",min:"1",value:d.latePerDay,onChange:E=>u({...d,latePerDay:Number(E.target.value)})})]}),e.jsxs("label",{children:["Half Day salary deduction",e.jsxs("select",{value:d.deductHalfDay?"yes":"no",onChange:E=>u({...d,deductHalfDay:E.target.value==="yes"}),children:[e.jsx("option",{value:"no",children:"No deduction"}),e.jsx("option",{value:"yes",children:"Deduct salary"})]})]}),d.deductHalfDay&&e.jsxs("label",{children:["Deduction per Half Day",e.jsxs("select",{value:String(d.halfDayDeductionRate??.5),onChange:E=>u({...d,halfDayDeductionRate:Number(E.target.value)}),children:[e.jsx("option",{value:"0.25",children:"0.25 Day Salary"}),e.jsx("option",{value:"0.5",children:"0.50 Day Salary"}),e.jsx("option",{value:"1",children:"1.00 Day Salary"})]})]}),e.jsxs("label",{children:["Salary deduction divisor",e.jsxs("select",{value:d.salaryDivisor,onChange:E=>u({...d,salaryDivisor:E.target.value}),children:[e.jsx("option",{value:"calendar_days",children:"Calendar Days"}),e.jsx("option",{value:"working_days",children:"Working Days"})]})]}),e.jsxs("label",{children:["Overtime feature",e.jsxs("select",{value:d.overtimeEnabled?"yes":"no",onChange:E=>u({...d,overtimeEnabled:E.target.value==="yes"}),children:[e.jsx("option",{value:"no",children:"Disabled"}),e.jsx("option",{value:"yes",children:"Enabled"})]})]}),d.overtimeEnabled&&e.jsxs("label",{children:["Overtime rate per hour",e.jsx("input",{type:"number",min:"0",value:d.overtimeRate,onChange:E=>u({...d,overtimeRate:Number(E.target.value)})})]}),e.jsxs("label",{children:["Net pay rounding",e.jsxs("select",{value:d.roundNetPay?"yes":"no",onChange:E=>u({...d,roundNetPay:E.target.value==="yes"}),children:[e.jsx("option",{value:"no",children:"Keep decimal"}),e.jsx("option",{value:"yes",children:"Round to nearest taka"})]})]})]}),e.jsxs("div",{className:"payroll-statutory-settings",children:[e.jsxs("div",{className:"payroll-statutory-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Tax & Provident Fund (PF)"}),e.jsx("p",{children:"Optional company-level statutory payroll foundation. Existing payroll remains unchanged while disabled."})]}),e.jsxs("label",{className:"payroll-statutory-master",children:[e.jsx("span",{children:"Enable Tax / PF"}),e.jsxs("select",{value:d.statutoryEnabled?"yes":"no",onChange:E=>u({...d,statutoryEnabled:E.target.value==="yes"}),children:[e.jsx("option",{value:"no",children:"Disabled"}),e.jsx("option",{value:"yes",children:"Enabled"})]})]})]}),d.statutoryEnabled&&e.jsxs("div",{className:"payroll-form-grid",children:[e.jsxs("label",{children:["Tax feature",e.jsxs("select",{value:d.taxEnabled?"yes":"no",onChange:E=>u({...d,taxEnabled:E.target.value==="yes"}),children:[e.jsx("option",{value:"no",children:"Disabled"}),e.jsx("option",{value:"yes",children:"Enabled"})]})]}),d.taxEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Tax Country",e.jsx("select",{value:d.taxCountry,onChange:E=>u({...d,taxCountry:E.target.value}),children:e.jsx("option",{value:"BD",children:"Bangladesh (NBR)"})})]}),e.jsxs("label",{children:["Tax Engine Mode",e.jsxs("select",{value:d.taxEngineMode,onChange:E=>u({...d,taxEngineMode:E.target.value}),children:[e.jsx("option",{value:"reference_only",children:"Reference Only (No Deduction)"}),e.jsx("option",{value:"approved_rule",disabled:!Mn||Mn.status!=="approved",children:"Approved Rule"})]})]}),e.jsxs("label",{children:["Tax Rule Version",e.jsxs("select",{value:d.taxRuleVersionId||"",onChange:E=>u({...d,taxRuleVersionId:E.target.value}),children:[e.jsx("option",{value:"",children:"Not Selected"}),Object.values(f).sort((E,Q)=>Q.assessmentYear.localeCompare(E.assessmentYear)).map(E=>e.jsxs("option",{value:E.id,children:[E.id," · ",E.status.replace("_"," ")]},E.id))]})]})]}),e.jsxs("label",{children:["Provident Fund",e.jsxs("select",{value:d.pfEnabled?"yes":"no",onChange:E=>u({...d,pfEnabled:E.target.value==="yes"}),children:[e.jsx("option",{value:"no",children:"Disabled"}),e.jsx("option",{value:"yes",children:"Enabled"})]})]}),d.pfEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["PF calculation basis",e.jsxs("select",{value:d.pfBasis,onChange:E=>u({...d,pfBasis:E.target.value}),children:[e.jsx("option",{value:"basic",children:"Basic Salary"}),e.jsx("option",{value:"gross",children:"Gross Salary"})]})]}),e.jsxs("label",{children:["PF eligibility rule",e.jsxs("select",{value:d.pfEligibilityRule,onChange:E=>u({...d,pfEligibilityRule:E.target.value}),children:[e.jsx("option",{value:"after_one_year",children:"After 1 Year of Service"}),e.jsx("option",{value:"from_joining",children:"From Joining Date"}),e.jsx("option",{value:"custom",children:"Custom Employee Start Date"})]})]}),e.jsxs("label",{children:["Employee PF contribution (%)",e.jsx("input",{type:"number",min:"0",max:"100",step:"0.01",value:d.pfEmployeeRate,onChange:E=>
4077u({...d,pfEmployeeRate:Math.max(0,Number(E.target.value))})})]}),e.jsxs("label",{children:["Employer PF contribution (%)",e.jsx("input",{type:"number",min:"0",max:"100",step:"0.01",value:d.pfEmployerRate,onChange:E=>u({...d,pfEmployerRate:Math.max(0,Number(E.target.value))})})]})]})]}),d.statutoryEnabled&&d.taxEnabled&&e.jsxs("div",{className:"payroll-tax-registry",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Bangladesh Tax Rule Registry"}),e.jsx("small",{children:Mn?`${Mn.id} · ${Mn.status.replace("_"," ")} · ${Mn.sourceTitle}`:"No NBR tax rule reference registered for this company yet."}),(Mn==null?void 0:Mn.sourceUrl)&&e.jsx("a",{href:Mn.sourceUrl,target:"_blank",rel:"noreferrer",children:"Open official NBR source"})]}),e.jsx("button",{type:"button",className:"vx-button vx-button-primary payroll-tax-registry-button",onClick:It,disabled:ce,children:ce?"Please wait...":Mn?"Refresh NBR Reference":"Initialize NBR Reference"}),e.jsx("button",{type:"button",className:"vx-button vx-button-primary payroll-tax-registry-button",onClick:ga,disabled:ce,children:((an=f["BD-NBR-2026-27"])==null?void 0:an.status)==="approved"?"Reinstall 2026-27 Rule":"Install 2026-27 Approved Rule"}),p&&e.jsx("div",{className:`payroll-tax-registry-status ${p.type}`,children:p.text})]}),d.statutoryEnabled&&d.taxEnabled&&e.jsxs("div",{className:"payroll-tax-monitor",children:[e.jsxs("div",{className:"payroll-tax-monitor-heading",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"NBR Rule Update Monitor"}),e.jsx("small",{children:b!=null&&b.hash?(w==null?void 0:w.lastHash)===b.hash?"Latest detected NBR source state has been reviewed.":"A newer NBR income-tax source state is waiting for review.":"Automatic feed is not connected yet. Configure the included GitHub monitor workflow to enable daily checks."})]}),e.jsx("span",{className:`payroll-tax-monitor-badge ${b!=null&&b.hash?(w==null?void 0:w.lastHash)===b.hash?"reviewed":"review":"offline"}`,children:b!=null&&b.hash?(w==null?void 0:w.lastHash)===b.hash?"Reviewed":"Review Required":"Not Connected"})]}),(b==null?void 0:b.hash)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"payroll-tax-monitor-meta",children:[e.jsxs("span",{children:[e.jsx("b",{children:"Detected:"})," ",b.detectedAt?new Date(Number(b.detectedAt)).toLocaleString("en-GB"):"â"]}),e.jsxs("span",{children:[e.jsx("b",{children:"Tracked Items:"})," ",Number(b.itemCount||0)]}),e.jsxs("span",{children:[e.jsx("b",{children:"Latest:"})," ",String(b.latestTitle||"NBR income-tax source update")]})]}),e.jsxs("div",{className:"payroll-tax-monitor-actions",children:[e.jsx("a",{className:"vx-button vx-button-secondary",href:"https://nbr.gov.bd/regulations/sros/income-tax-sros/income-tax-sros",target:"_blank",rel:"noreferrer",children:"Open NBR Income Tax SROs"}),e.jsx("a",{className:"vx-button vx-button-secondary",href:"https://nbr.gov.bd/information-library/publicnotice-details/income-tax/eng",target:"_blank",rel:"noreferrer",children:"Open NBR Public Notices"}),e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:Ma,disabled:R||(w==null?void 0:w.lastHash)===b.hash,children:"No Payroll Rule Change"}),e.jsx("button",{type:"button",className:"vx-button vx-button-primary",onClick:zn,disabled:R||(w==null?void 0:w.lastHash)===b.hash,children:"Create Versioned Rule Draft"})]}),d.taxScheduledRuleVersionId&&d.taxScheduledEffectiveDate&&e.jsxs("div",{className:"payroll-tax-scheduled-rule",children:[e.jsx("strong",{children:"Scheduled Tax Rule"}),e.jsxs("span",{children:[d.taxScheduledRuleVersionId," · Effective ",d.taxScheduledEffectiveDate]}),e.jsxs("small",{children:["Payroll months before the effective date continue using ",d.taxRuleVersionId||"the current rule","."]})]}),_&&e.jsxs("div",{className:"payroll-tax-review-builder",children:[e.jsxs("div",{className:"payroll-tax-review-builder-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Versioned Tax Rule Review Draft"}),e.jsx("small",{children:"Verify the official NBR material, then edit every value that changed. Saving a draft never changes payroll."})]}),e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:()=>J(null),children:"Cancel Draft"})]}),e.jsxs("div",{className:"payroll-tax-review-grid",children:[e.jsxs("label",{children:["Rule ID",e.jsx("input",{value:_.id,onChange:E=>J(Q=>Q&&{...Q,id:E.target.value})})]}),e.jsxs("label",{children:["Effective Date",e.jsx("input",{type:"date",value:_.effectiveDate,onChange:E=>J(Q=>Q&&{...Q,effectiveDate:E.target.value})})]}),e.jsxs("label",{children:["Assessment Year",e.jsx("input",{value:_.assessmentYear,onChange:E=>J(Q=>Q&&{...Q,assessmentYear:E.target.value})})]}),e.jsxs("label",{children:["Fiscal Year",e.jsx("input",{value:_.fiscalYear,onChange:E=>J(Q=>Q&&{...Q,fiscalYear:E.target.value})})]}),e.jsxs("label",{className:"wide",children:["Source Title",e.jsx("input",{value:_.sourceTitle,onChange:E=>J(Q=>Q&&{...Q,sourceTitle:E.target.value})})]}),e.jsxs("label",{className:"wide",children:["Official Source URL",e.jsx("input",{value:_.sourceUrl,onChange:E=>J(Q=>Q&&{...Q,sourceUrl:E.target.value})})]})]}),e.jsxs("div",{className:"payroll-tax-review-slabs",children:[e.jsxs("div",{className:"slab-head",children:[e.jsx("span",{children:"Up To (à§³)"}),e.jsx("span",{children:"Rate (%)"}),e.jsx("span",{})]}),_.slabs.map((E,Q)=>e.jsxs("div",{className:"slab-row",children:[e.jsx("input",{type:"number",min:"0",placeholder:Q===_.slabs.length-1?"Blank = above":"Threshold",value:E.upTo??"",onChange:Ie=>Xn(Q,"upTo",Ie.target.value)}),e.jsx("input",{type:"number",min:"0",max:"100",step:"0.01",value:E.rate,onChange:Ie=>Xn(Q,"rate",Ie.target.value)}),e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:()=>J(Ie=>Ie&&{...Ie,slabs:Ie.slabs.filter((Le,He)=>He!==Q)}),children:"Remove"})]},`${Q}-${E.upTo??"above"}`)),e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:()=>J(E=>E&&{...E,slabs:[...E.slabs,{rate:0}]}),children:"Add Slab"})]}),e.jsxs("div",{className:"payroll-tax-monitor-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",disabled:R,onClick:Vn,children:"Save Reference-Only Draft"}),e.jsx("button",{type:"button",className:"vx-button vx-button-primary",disabled:R,onClick:ua,children:"Approve & Schedule Rule"})]})]}),e.jsx("small",{className:"payroll-tax-monitor-warning",children:"Detection never activates, edits, or replaces a payroll Tax Rule automatically. A source change must be explicitly reviewed. A new rule affects payroll only after authorized approval and only from its effective date."})]})]}),d.statutoryEnabled&&e.jsx("p",{className:"payroll-statutory-note",children:"Employee applicability is configured from Salary Structure. PF calculation is active for eligible employees. Tax is version-controlled separately: Reference Only mode never changes Net Pay; only a reviewed/approved tax rule will be allowed to activate payroll tax deduction."})]}),e.jsxs("button",{onClick:Ha,disabled:ce,children:[e.jsx(hr,{size:17}),ce?"Saving...":"Save Settings"]})]}),T&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>G(null),children:e.jsxs("section",{className:"modal payroll-tax-detail-modal",onMouseDown:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Tax Calculation Details"}),e.jsx("h2",{children:T.employeeName}),e.jsxs("p",{children:[T.taxRuleVersionId||"Bangladesh Tax Rule"," · ",T.taxIncomeYearLabel||"Current income year"]})]}),e.jsx("button",{type:"button",onClick:()=>G(null),"aria-label":"Close tax details",children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"payroll-tax-detail-grid",children:[e.jsxs("span",{children:[e.jsx("small",{children:"Monthly Gross"}),e.jsxs("b",{children:["à§³ ",pn(T.grossSalary)]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Annualized Income"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.annualTaxableIncome||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Taxpayer Category"}),e.jsx("b",{children:String(T.taxPayerCategory||"general").replaceAll("_"," ")})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Tax-free Threshold"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.taxFreeThreshold||0))]})]}
4077),e.jsxs("span",{children:[e.jsx("small",{children:"Tax Location"}),e.jsx("b",{children:String(T.taxLocationCategory||"â").replaceAll("_"," ")})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Minimum Annual Tax"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.minimumAnnualTax||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Slab Annual Tax"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.slabAnnualTax||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Eligible Investment"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.annualEligibleInvestment||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Maximum Rebate"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.maximumTaxRebate||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Applied Rebate"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.appliedTaxRebate||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Tax After Rebate"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.annualTaxBeforeMinimum||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Final Annual Tax"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.annualTax||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Prior VERIXO Withheld"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.taxWithheldPriorMonths||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Prior External Withheld"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.taxExternalPriorWithheld||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Total Withheld Before Month"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.taxTotalWithheldBeforeCurrent||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Remaining Annual Liability"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.taxRemainingLiability||0))]})]}),e.jsxs("span",{children:[e.jsx("small",{children:"Months Remaining"}),e.jsx("b",{children:Number(T.taxMonthsRemaining||1)})]}),e.jsxs("span",{className:"payroll-tax-detail-current",children:[e.jsx("small",{children:"Current Month Tax"}),e.jsxs("b",{children:["à§³ ",pn(Number(T.monthlyTax||0))]})]})]}),e.jsx("div",{className:"payroll-tax-reconciliation-note",children:"Final annual tax minus prior VERIXO withholding and declared prior withholding. The remaining liability is distributed across the remaining months of the Jul-Jun income year."}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"vx-button vx-button-primary",onClick:()=>G(null),children:"Close"})})]})}),Gt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>$t(null),children:e.jsxs("section",{className:"modal payroll-precheck-modal",onMouseDown:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Payroll Pre-Check"}),e.jsx("h2",{children:vs[Gt]}),e.jsxs("p",{children:[l," · ",a==="all"?"All Branches":((Cn=n.find(E=>E.id===a))==null?void 0:Cn.name)||"Selected Branch"," ","· ",Ja.length," issue(s)"]})]}),e.jsx("button",{type:"button",onClick:()=>$t(null),"aria-label":"Close pre-check details",children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"payroll-precheck-explainer",children:[e.jsx("strong",{children:"Why this matters"}),e.jsx("span",{children:"These are diagnostic records only. Opening this list does not modify Attendance or Payroll data."})]}),e.jsx("div",{className:"table-scroll payroll-precheck-detail-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Record Detail"}),e.jsx("th",{children:"Why Flagged"})]})}),e.jsxs("tbody",{children:[Ja.map(E=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:E.employeeName}),e.jsx("small",{children:E.employeeCode||E.employeeId||"â"})]}),e.jsx("td",{children:E.branchName}),e.jsx("td",{children:E.date}),e.jsx("td",{children:e.jsx("span",{className:"payroll-precheck-status",children:String(E.status).replaceAll("_"," ")})}),e.jsx("td",{children:E.detail}),e.jsx("td",{children:E.reason})]},E.key)),!Ja.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-table",children:"No matching pre-check issue remains."})})]})]})}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"vx-button vx-button-primary",onClick:()=>$t(null),children:"Close"})})]})}),Vt&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>sn(!1),children:e.jsxs("section",{className:"modal payroll-precheck-confirm-modal",role:"dialog","aria-modal":"true","aria-labelledby":"payroll-precheck-confirm-title",onMouseDown:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Payroll Pre-Check"}),e.jsxs("h2",{id:"payroll-precheck-confirm-title",children:["Review before ",De?"regenerating":"generating"," payroll"]}),e.jsxs("p",{children:[l," · ",a==="all"?"All Branches":((Qn=n.find(E=>E.id===a))==null?void 0:Qn.name)||"Selected Branch"]})]}),e.jsx("button",{type:"button",onClick:()=>sn(!1),"aria-label":"Cancel payroll generation",children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"payroll-precheck-confirm-warning",children:[e.jsx(qu,{size:21}
4077),e.jsxs("div",{children:[e.jsx("strong",{children:"Unresolved items detected"}),e.jsx("span",{children:"Review the following attendance, leave and salary issues before proceeding. Payroll calculation rules will remain unchanged."})]})]}),e.jsx("div",{className:"payroll-precheck-confirm-grid",children:[["missingPunch","Missing Punch",jn.missingPunch],["pendingLeave","Pending Leave",jn.pendingLeave],["reviewRequired","Movement Review Required",jn.reviewRequired],["unclassified","Unclassified Movement",jn.unclassified],["missingSalary","Missing Gross Salary",jn.missingSalary]].map(([E,Q,Ie])=>e.jsxs("button",{type:"button",className:`payroll-precheck-confirm-item ${Ie>0?"warning":"clear"}`,disabled:Ie<=0,onClick:()=>$t(E),children:[e.jsx("span",{children:Q}),e.jsx("b",{children:Ie}),e.jsx("small",{children:Ie>0?"View affected records":"No issue found"})]},E))}),e.jsxs("div",{className:"payroll-precheck-confirm-note",children:["à¦à¦ªà¦¨à¦¿ à¦à¦¾à¦à¦²à§ unresolved item review না à¦à¦°à§à¦ Payroll ",De?"Regenerate":"Generate"," à¦à¦°à¦¤à§ পারবà§à¦¨à¥¤ Proceed à¦à¦°à¦²à§ existing calculation ঠPre-Check logic à¦
পরিবরà§à¦¤à¦¿à¦¤ থাà¦à¦¬à§à¥¤"]}),e.jsxs("div",{className:"modal-actions payroll-precheck-confirm-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:()=>{sn(!1),le("Payroll generation cancelled after Pre-Check. Attendance/leave/salary issues review à¦à¦°à§ à¦à¦¬à¦¾à¦° Generate/Regenerate à¦à¦°à§à¦¨.")},children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",disabled:ce,onClick:()=>void bs(!0),children:[e.jsx(Hi,{size:16}),"Proceed & ",De?"Regenerate":"Generate"]})]})]})}),st&&e.jsx("div",{className:"payroll-report-preview-backdrop",onMouseDown:Ln,children:e.jsxs("section",{className:"payroll-report-preview-modal",onMouseDown:E=>E.stopPropagation(),children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Payroll Report Preview"}),e.jsxs("h2",{children:[l," Monthly Payroll Sheet"]}),e.jsx("small",{children:"Review the exact A4 Landscape PDF before downloading or printing."})]}),e.jsxs("div",{className:"payroll-report-preview-actions",children:[e.jsxs("button",{onClick:()=>void Ct("download"),children:[e.jsx(Zs,{size:16})," Download PDF"]}),e.jsxs("button",{onClick:()=>{window.open(st,"_blank","noopener,noreferrer")||window.alert("Browser popup blocked. Please allow popups to print the report.")},children:[e.jsx(Zs,{size:16})," Open / Print"]}),e.jsx("button",{className:"icon-button",onClick:Ln,title:"Close preview",children:e.jsx(ja,{size:18})})]})]}),e.jsx("iframe",{title:"Payroll A4 PDF Preview",src:st})]})}),on&&be&&bt&&e.jsx("div",{className:"payroll-test-backdrop",onMouseDown:()=>jt(!1),children:e.jsxs("section",{className:"payroll-test-modal",onMouseDown:E=>E.stopPropagation(),children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"VERIXO INTERNAL"}),e.jsx("h2",{children:"Payroll Test Mode"}),e.jsx("small",{children:"Isolated demo workflow. Client payroll data is not used or changed."})]}),e.jsx("button",{onClick:()=>jt(!1),children:"Close"})]}),e.jsx("div",{className:"payroll-test-warning",children:"DEMO / TEST ONLY â hidden from normal client users"}),e.jsxs("div",{className:"payroll-test-status",children:[e.jsxs("span",{children:["Month ",e.jsx("b",{children:bt.month})]}),e.jsxs("span",{children:["Status ",e.jsx("b",{children:bt.status})]}),e.jsxs("span",{children:["Correction ",e.jsx("b",{children:bt.correctionStatus||"none"})]})]}),e.jsxs("div",{className:"payroll-test-flow",children:[e.jsx("button",{disabled:bt.status!=="draft",onClick:()=>ko("approved"),children:"Approve Demo"}),e.jsx("button",{disabled:bt.status!=="approved",onClick:()=>ko("locked"),children:"Lock Demo"}),e.jsx("button",{disabled:bt.status!=="approved"||At,onClick:()=>ko("draft"),title:At?"Recorded salary payment protects this payroll from returning to Draft.":"",children:"Return to Draft"}),e.jsx("button",{disabled:bt.status!=="locked"||bt.correctionStatus==="requested",onClick:U,children:"Request Correction"}),e.jsx("button",{disabled:bt.status!=="locked"||bt.correctionStatus!=="requested"||At,onClick:Ue,title:At?"Recorded salary payment protects this payroll from unlock.":"",children:"Authorize Unlock"})]}),bt.correctionReason&&e.jsxs("p",{className:"payroll-test-reason",children:[e.jsx("strong",{children:"Reason:"})," ",bt.correctionReason]}),e.jsxs("div",{className:"payroll-demo-disbursement",children:[e.jsxs("div",{className:"payroll-demo-disbursement-title",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Demo Disbursement"}),e.jsxs("small",{children:["Available after demo payroll is locked.",At?" Payment recorded â unlock/return to Draft is protected.":""]})]}),e.jsxs("span",{children:["Paid à§³ ",pn(ut.paid)," · Pending à§³ ",pn(ut.pending)]})]}),e.jsx("div",{className:"payroll-demo-payment-list",children:Oe.map(E=>e.jsxs("div",{className:"payroll-demo-payment-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:E.employeeName}),e.jsxs("small",{children:["Net à§³ ",pn(E.netPay)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:`payroll-payment-badge ${E.paymentStatus}`,children:E.paymentStatus.replace("_"," ")}),E.paidAmount>0&&e.jsxs("small",{children:["Paid à§³ ",pn(E.paidAmount)," · Pending à§³ ",pn(Math.max(E.netPay-E.paidAmount,0))]}),E.transactions&&e.jsxs("small",{children:[Object.keys(E.transactions).length," payment transaction(s)"]})]}),e.jsx("button",{disabled:bt.status!=="locked"||E.paymentStatus==="paid",onClick:()=>Vc(E.id),children:E.paidAmount>0?"Add Payment":"Pay Demo"})]},E.id))})]}),e.jsxs("div",{className:"payroll-live-test-reset",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Current Live Payroll Test Reset"}),e.jsx("small",{children:"Super Admin development tool. Clears the selected month's payroll payment/payable test trail and returns it to Draft. Do not use for real client payroll."})]}),e.jsx("button",{className:"danger",disabled:ce||!De,onClick:yt,children:ce?"Resetting...":`Reset ${l} Live Test Payroll`})]}),e.jsx("footer",{children:e.jsx("button",{className:"danger",onClick:kt,children:"Delete Demo Payroll"})})]})})]})}const H_=()=>new Date().toISOString().slice(0,7),Mf=t=>
4077`à§³${Number(t||0).toLocaleString("en-BD",{maximumFractionDigits:2})}`;function NU({profile:t,branches:n}){var ue,me,ge;const[a,s]=x.useState([]),[i,c]=x.useState([]),[l,m]=x.useState(!1),[d,u]=x.useState(""),[f,g]=x.useState(!1),[p,y]=x.useState("advance"),[b,N]=x.useState(""),[w,C]=x.useState(""),[R,I]=x.useState(""),[_,J]=x.useState(null),[T,G]=x.useState(""),[z,H]=x.useState("one_time"),[K,L]=x.useState(H_()),[D,M]=x.useState(1);x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),de=>{if(!de.exists()){s([]);return}const Pe=Object.entries(de.val()).map(([Re,Ee])=>({id:Re,...Ee}));s(Pe.filter(Re=>Re.active!==!1))}),[t.companyId]);const Z=a.find(de=>de.id===t.employeeId||de.email&&t.email&&de.email.toLowerCase()===t.email.toLowerCase());a.some(de=>de.reportingManagerUserUid===t.uid||!!(Z&&de.reportingManagerId===Z.id));const fe=["super_admin","owner","admin","hr"].includes(t.role),q=["super_admin","owner","admin","hr","accountant","branch_manager"].includes(t.role)||((ue=t.permissionOverrides)==null?void 0:ue["payroll.read"])===!0||((me=t.permissionOverrides)==null?void 0:me.payroll__dot__read)===!0;x.useEffect(()=>{const de=re(ie,`employeeAdvanceLoanRequests/${t.companyId}`),Pe=new Map,Re=[],Ee=()=>{const We=new Map;Pe.forEach(it=>it.forEach((_e,ee)=>We.set(ee,_e))),c(Array.from(We.values()).sort((it,_e)=>_e.createdAt-it.createdAt))},Be=(We,it)=>qt(We,_e=>{const ee=new Map;_e.exists()&&Object.entries(_e.val()).forEach(([qe,se])=>ee.set(qe,{id:qe,...se})),Pe.set(it,ee),Ee()});return q?Re.push(qt(de,We=>{const it=new Map;We.exists()&&Object.entries(We.val()).forEach(([_e,ee])=>it.set(_e,{id:_e,...ee})),Pe.set("all",it),Ee()})):(t.employeeId&&Re.push(Be(Vl(de,ql("employeeId"),Dh(t.employeeId)),"self")),Re.push(Be(Vl(de,ql("managerUserUid"),Dh(t.uid)),"managerUid")),t.employeeId&&Re.push(Be(Vl(de,ql("managerEmployeeId"),Dh(t.employeeId)),"managerEmployee"))),()=>Re.forEach(We=>We())},[t.companyId,t.uid,t.employeeId,q]);const ne=x.useMemo(()=>i.filter(de=>de.employeeId===(Z==null?void 0:Z.id)||de.managerUserUid===t.uid||!!(Z&&de.managerEmployeeId===Z.id)||fe),[i,Z==null?void 0:Z.id,t.uid,fe]),ae=async()=>{if(!Z){u("Your login is not linked to an Employee record.");return}const de=Math.max(0,Number(b||0));if(de<=0||!w.trim()){u("Amount and reason are required.");return}if(!Z.reportingManagerId&&!Z.reportingManagerUserUid){u("Reporting Manager is not assigned in Employee setup.");return}const Pe=a.find(Re=>Re.id===Z.reportingManagerId);g(!0);try{const Re=Ta(re(ie,`employeeAdvanceLoanRequests/${t.companyId}`));if(!Re.key)throw new Error("Request ID could not be generated.");const Ee={employeeId:Z.id,employeeCode:Z.employeeId||"",employeeName:Z.name,branchId:Z.branchId||"",managerEmployeeId:Z.reportingManagerId||"",managerUserUid:Z.reportingManagerUserUid||"",managerName:Z.reportingManagerName||(Pe==null?void 0:Pe.name)||"",type:p,requestedAmount:de,reason:w.trim(),neededDate:R,recoveryPlanFinalized:!1,status:"pending",createdAt:Date.now(),createdByUid:t.uid};await Pn(Re,Ee),await ia({companyId:t.companyId,branchId:Z.branchId,actorUid:t.uid,actorName:t.name,action:"advance_loan.requested",entityType:"employeeAdvanceLoanRequest",entityId:Re.key,summary:`${Z.name} requested ${p} ${Mf(de)}.`}),m(!1),N(""),C(""),I(""),u("Request submitted to your Reporting Manager.")}catch(Re){u(Re instanceof Error?Re.message:String(Re))}finally{g(!1)}},Y=de=>de.status==="pending"&&(de.managerUserUid===t.uid||!!(Z&&de.managerEmployeeId===Z.id)||fe),je=de=>de.status==="manager_approved"&&fe,V=async de=>{if(!Y(de))return;const Pe=Date.now();await yn(re(ie,`employeeAdvanceLoanRequests/${t.companyId}/${de.id}`),{status:"manager_approved",managerApprovedAt:Pe,managerApprovedByUid:t.uid,managerApprovedByName:t.name}),await ia({companyId:t.companyId,branchId:de.branchId,actorUid:t.uid,actorName:t.name,action:"advance_loan.manager_approved",entityType:"employeeAdvanceLoanRequest",entityId:de.id,summary:`${de.employeeName} ${de.type} request approved by Reporting Manager; recovery plan pending HR/Admin finalization.`}),u("Reporting Manager approval completed. HR/Admin/Owner/Super Admin must now set the recovery plan.")},$=de=>{je(de)&&(J(de),G(String(de.requestedAmount)),H("one_time"),L(H_()),M(1))},F=async()=>{const de=_;if(!de||!je(de))return;const Pe=Math.max(0,Number(T||0));if(!Pe||Pe>de.requestedAmount){u("Approved amount must be greater than zero and cannot exceed the requested amount.");return}if(!K){u("Recover From Salary Month is required.");return}const Re=z==="monthly"?Math.max(1,Math.floor(D||1)):1,Ee=Ta(re(ie,`employeeAdvanceLoans/${t.companyId}`));if(!Ee.key)return;const Be=Date.now();g(!0);try{await Pn(Ee,{employeeId:de.employeeId,employeeCode:de.employeeCode||"",employeeName:de.employeeName,branchId:de.branchId||"",type:de.type,amount:Pe,issueDate:"",paymentMethod:"cash",reference:`REQ-${de.id}`,recoveryMode:z,recoveryStartMonth:K,installmentCount:Re,installmentAmount:z==="monthly"?Pe/Re:Pe,remarks:de.reason,status:"approved",createdAt:Be,createdByUid:t.uid,createdByName:t.name,sourceRequestId:de.id,approvedAt:Be,approvedByUid:t.uid,approvedByName:t.name}),await yn(re(ie,`employeeAdvanceLoanRequests/${t.companyId}/${de.id}`),{status:"approved",approvedAmount:Pe,approvedAt:Be,approvedByUid:t.uid,approvedByName:t.name,recoveryMode:z,recoverFromSalaryMonth:K,recoveryStartMonth:K,installmentCount:Re,recoveryPlanFinalized:!0,advanceLoanRecordId:Ee.key}),await ia({companyId:t.companyId,branchId:de.branchId,actorUid:t.uid,actorName:t.name,action:"advance_loan.recovery_plan_finalized",entityType:"employeeAdvanceLoanRequest",entityId:de.id,summary:`${de.employeeName} ${de.type} finalized for ${Mf(Pe)}; ${z==="monthly"?`${Re} monthly installments`:"one-time"} from ${K}.`}),J(null),u("Recovery plan finalized. The Advance/Loan is now Pending Disbursement.")}catch(We){u(We instanceof Error?We.message:String(We))}finally{g(!1)}}
4077,P=async de=>{if(!Y(de))return;const Pe=window.prompt("Rejection reason:");if(!(Pe!=null&&Pe.trim()))return;const Re=Date.now();await yn(re(ie,`employeeAdvanceLoanRequests/${t.companyId}/${de.id}`),{status:"rejected",rejectedAt:Re,rejectedByUid:t.uid,rejectedByName:t.name,rejectionReason:Pe.trim()}),await ia({companyId:t.companyId,branchId:de.branchId,actorUid:t.uid,actorName:t.name,action:"advance_loan.rejected",entityType:"employeeAdvanceLoanRequest",entityId:de.id,summary:`${de.employeeName} ${de.type} request rejected.`})};return e.jsxs("section",{className:"alr-page",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{children:"EMPLOYEE SELF-SERVICE"}),e.jsx("h1",{children:"Advance & Loan Requests"}),e.jsx("span",{children:"Apply to your Reporting Manager and track approval/disbursement."})]}),Z&&e.jsxs("button",{onClick:()=>m(!0),children:[e.jsx(as,{size:17})," New Request"]})]}),d&&e.jsx("div",{className:"alr-message",children:d}),e.jsx("div",{className:"alr-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"TYPE"}),e.jsx("th",{children:"REQUESTED"}),e.jsx("th",{children:"RECOVERY"}),e.jsx("th",{children:"REPORTING MANAGER"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:ne.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"empty",children:"No Advance/Loan request found."})}):ne.map(de=>{var Pe;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:de.employeeName}),e.jsxs("small",{children:[de.employeeCode||"â"," · ",((Pe=n.find(Re=>Re.id===de.branchId))==null?void 0:Pe.name)||"Branch"]})]}),e.jsx("td",{children:de.type==="advance"?"Advance":"Loan"}),e.jsxs("td",{children:[e.jsx("strong",{children:Mf(de.requestedAmount)}),de.approvedAmount&&e.jsxs("small",{children:["Approved: ",Mf(de.approvedAmount)]})]}),e.jsxs("td",{children:[de.recoveryPlanFinalized?de.recoveryMode==="one_time"?"One Time":`${de.installmentCount} Monthly Installments`:"Set by HR/Admin",de.recoveryPlanFinalized&&e.jsxs("small",{children:["From ",de.recoverFromSalaryMonth||de.recoveryStartMonth]})]}),e.jsx("td",{children:de.managerName||"â"}),e.jsx("td",{children:e.jsx("span",{className:`alr-status ${de.status}`,children:de.status.replace("_"," ")})}),e.jsx("td",{children:Y(de)?e.jsxs("div",{className:"alr-actions",children:[e.jsxs("button",{onClick:()=>V(de),children:[e.jsx(ap,{size:14}),"Manager Approve"]}),e.jsxs("button",{className:"reject",onClick:()=>P(de),children:[e.jsx(ja,{size:14}),"Reject"]})]}):je(de)?e.jsx("div",{className:"alr-actions",children:e.jsxs("button",{onClick:()=>$(de),children:[e.jsx(Eh,{size:14}),"Set Recovery Plan"]})}):e.jsx("span",{children:"â"})})]},de.id)})})]})}),_&&e.jsx("div",{className:"alr-modal-bg",onMouseDown:de=>{de.target===de.currentTarget&&J(null)},children:e.jsxs("div",{className:"alr-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{children:"RECOVERY PLAN"}),e.jsx("h2",{children:"Finalize Advance / Loan"}),e.jsxs("span",{children:[_.employeeName," · ",_.type==="advance"?"Advance":"Loan"]})]}),e.jsx("button",{onClick:()=>J(null),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"alr-form",children:[e.jsxs("label",{children:["Approved Amount",e.jsx("input",{type:"number",min:"0",max:_.requestedAmount,value:T,onChange:de=>G(de.target.value)})]}),e.jsxs("label",{children:["Recovery Method",e.jsxs("select",{value:z,onChange:de=>H(de.target.value),children:[e.jsx("option",{value:"one_time",children:"One Time"}),e.jsx("option",{value:"monthly",children:"Monthly Installment"})]})]}),e.jsxs("label",{children:["Recover From Salary Month",e.jsx("input",{type:"month",value:K,onChange:de=>L(de.target.value)})]}),z==="monthly"&&e.jsxs("label",{children:["Number of Installments",e.jsx("input",{type:"number",min:"1",value:D,onChange:de=>M(Math.max(1,Number(de.target.value||1)))})]}),e.jsxs("div",{className:"wide manager",children:["Requested: ",e.jsx("strong",{children:Mf(_.requestedAmount)})," · Reporting Manager approval completed."]})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"secondary",onClick:()=>J(null),children:"Cancel"}),e.jsxs("button",{disabled:f,onClick:F,children:[e.jsx(Eh,{size:16}),f?"Saving...":"Finalize & Send to Disbursement"]})]})]})}),l&&e.jsx("div",{className:"alr-modal-bg",onMouseDown:de=>{de.target===de.currentTarget&&m(!1)},children:e.jsxs("div",{className:"alr-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{children:"NEW REQUEST"}),e.jsx("h2",{children:"Apply for Advance / Loan"})]}),e.jsx("button",{onClick:()=>m(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"alr-form",children:[e.jsxs("label",{children:["Type",e.jsxs("select",{value:p,onChange:de=>y(de.target.value),children:[e.jsx("option",{value:"advance",children:"Advance"}),e.jsx("option",{value:"loan",children:"Loan"})]})]}),e.jsxs("label",{children:["Requested Amount",e.jsx("input",{type:"number",min:"0",value:b,onChange:de=>N(de.target.value)})]}),e.jsxs("label",{children:["Needed Date",e.jsx("input",{type:"date",value:R,onChange:de=>I(de.target.value)})]}),e.jsxs("label",{className:"wide",children:["Reason",e.jsx("textarea",{value:w,onChange:de=>C(de.target.value),placeholder:"Why do you need this Advance/Loan?"})]}),e.jsx("div",{className:"wide manager",children:"Recovery Method and Recover From Salary Month will be set by HR/Admin after Reporting Manager approval."}),e.jsxs("div",{className:"wide manager",children:["Reporting Manager: ",e.jsx("strong",{children:(Z==null?void 0:Z.reportingManagerName)||((ge=a.find(de=>de.id===(Z==null?void 0:Z.reportingManagerId)))==null?void 0:ge.name)||"Not assigned"})]})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"secondary",onClick:()=>m(!1),children:"Cancel"}),e.jsxs("button",{disabled:f,onClick:ae,children:[e.jsx(Eh,{size:16}),f?"Submitting...":"Submit Request"]})]})]})})]})}const Wm=[{key:"attendance",label:"Attendance"},{key:"punctuality",label:"Punctuality"},{key:"productivity",label:"Productivity"},{key:"quality",label:"Quality of Work"},{key:"teamwork",label:"Teamwork"},{key:"customerService",label:"Customer Service"}];function W_(t){const n=`${(t==null?void 0:t.designation)||""} ${(t==null?void 0:t.department)||""}`.toLowerCase();return/chief executive|\bceo\b|managing director|executive director/.test(n)?"ceo":/branch manager|branch in.?charge|branch head/.test(n)?"branch_manager":/service in.?charge|service manager|service head|workshop manager/.test(n)?"service_lead":/sales manager|sales head|head of sales|business development manager/.test(n)?"sales_manager":/sales|business development|account executive/.test(n)?"sales":"employee"}const SU={employee:{attendance:"Attendance",punctuality:"Punctuality",productivity:"Productivity",quality:"Quality of Work",teamwork:"Teamwork",customerService:"Customer Service"},sales:{attendance:"Attendance",punctuality:"Punctuality",productivity:"Sales / Target Achievement",quality:"Sales Process Quality",teamwork:"Teamwork",customerService:"Customer Relationship"},sales_manager:{attendance:"Attendance & Availability",punctuality:"Management Discipline",productivity:"Team Sales / Target Achievement",quality:"Sales Process & Collection Control",teamwork:"Sales Team Leadership",customerService:"Team Customer Relationship"},service_lead:{attendance:"Attendance",punctuality:"Punctuality",productivity:"Service Target / Throughput",quality:"QC & Service Quality",teamwork:"Team Leadership",customerService:"Customer Service"},branch_manager:{attendance:"Management Attendance",punctuality:"Management Discipline",productivity:"Branch Target Achievement",quality:"Branch Operational Quality",teamwork:"Leadership & Team Performance",customerService:"Branch Customer Satisfaction"},ceo:{attendance:"Attendance & Availability",punctuality:"Executive Discipline & Governance",productivity:"Company Target & Growth",quality:"Operational / Financial Discipline",teamwork:"Leadership & Department Performance",customerService:"Company Customer Satisfaction"}},CU={employee:"Employee Performance",sales:"Sales Performance",sales_manager:"Sales Management",service_lead:"Service Leadership",branch_manager:"Branch Management",ceo:"Executive Leadership"},Gm=()=>({attendance:3,punctuality:3,productivity:3,quality:3,teamwork:3,customerService:3}),Lj=()=>new Date().toISOString().slice(0,7)+"-01",Bj=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth()+1,0).toISOString().slice(0,10)},Wv=()=>String(new Date().getFullYear()),G_=t=>`${t}-01-01`,Y_=t=>`${t}-12-31`;function No(t){return t.cycleType==="yearly"?"yearly":"monthly"}
4077function AU(t,n){if(!t||!n||t>n)return[];const a=new Date(`${t.slice(0,7)}-01T00:00:00`),s=new Date(`${n.slice(0,7)}-01T00:00:00`),i=[];for(;a<=s&&i.length<24;)i.push(`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}`),a.setMonth(a.getMonth()+1);return i}function Fj(t){return{none:"No Recommendation",increment:"Salary Increment",promotion:"Promotion",training:"Training / Development",performance_improvement_plan:"Performance Improvement Plan"}[t]}function Uj(t){return t>=4.5?"Outstanding":t>=3.75?"Very Good":t>=3?"Good":t>=2?"Needs Improvement":"Unsatisfactory"}function Gv(t){return t>=90?5:t>=80?4:t>=70?3:t>=60?2:1}function Q_(t){return t>=4.5?5:t>=3.5?4:t>=2.5?3:t>=1.5?2:1}function IU(t,n){if(!t||!n||t>n)return[];const a=[],s=new Date(`${t}T00:00:00`),i=new Date(`${n}T00:00:00`);for(;s<=i&&a.length<=370;)a.push(s.toISOString().slice(0,10)),s.setDate(s.getDate()+1);return a}function J_(t){return new Date(`${t}T00:00:00`).getTime()}function K_(t){return new Date(`${t}T23:59:59.999`).getTime()}function _U({profile:t,branches:n,selectedBranchId:a}){const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState(""),[u,f]=x.useState("all"),[g,p]=x.useState(!1),[y,b]=x.useState(null),[N,w]=x.useState(null),[C,R]=x.useState(null),[I,_]=x.useState(!1),[J,T]=x.useState(""),[G,z]=x.useState(""),[H,K]=x.useState("monthly"),[L,D]=x.useState(Wv()),[M,Z]=x.useState("Monthly Performance Review"),[fe,q]=x.useState(Lj()),[ne,ae]=x.useState(Bj()),[Y,je]=x.useState(Gm()),[V,$]=x.useState(""),[F,P]=x.useState(""),[ue,me]=x.useState(""),[ge,de]=x.useState("none"),[Pe,Re]=x.useState({}),[Ee,Be]=x.useState({}),[We,it]=x.useState(!1),[_e,ee]=x.useState(""),[qe,se]=x.useState(0),[pe,Se]=x.useState(0),[Me,ot]=x.useState(""),wt=sa(t,"appraisal.view"),ct=sa(t,"appraisal.create"),Ce=sa(t,"appraisal.edit_draft"),De=sa(t,"appraisal.submit"),Te=sa(t,"appraisal.approve"),ce=sa(t,"appraisal.finalize"),Ye=sa(t,"appraisal.view_team"),Je=sa(t,"appraisal.view_all"),le=s.find(ke=>ke.id===t.employeeId||ke.email&&t.email&&ke.email.toLowerCase()===t.email.toLowerCase()),nt=["super_admin","owner"].includes(t.role);x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),ke=>{if(!ke.exists())return i([]);const Ct=ke.val();i(Object.entries(Ct).map(([Et,Rt])=>({id:Et,...Rt})).filter(Et=>Et.active!==!1).sort((Et,Rt)=>{const xn=String(Et.employeeId||"").trim(),dn=String(Rt.employeeId||"").trim(),Ln=Number(xn),wa=Number(dn),Ca=xn!==""&&Number.isFinite(Ln),In=dn!==""&&Number.isFinite(wa);return Ca&&In&&Ln!==wa?Ln-wa:Ca!==In?Ca?-1:1:xn!==dn?xn.localeCompare(dn,void 0,{numeric:!0,sensitivity:"base"}):Et.name.localeCompare(Rt.name)}))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`companies/${t.companyId}/appraisalEffectiveFrom`),ke=>{ot(ke.exists()?String(ke.val()||""):"")}),[t.companyId]),x.useEffect(()=>qt(re(ie,`employeeAppraisals/${t.companyId}`),ke=>{if(!ke.exists())return l([]);const Ct=ke.val();l(Object.entries(Ct).map(([Et,Rt])=>({id:Et,...Rt})).sort((Et,Rt)=>Rt.updatedAt-Et.updatedAt))}),[t.companyId]);const xt=x.useMemo(()=>s.filter(ke=>a!=="all"&&ke.branchId!==a?!1:nt?!0:le?ke.reportingManagerId===le.id&&ke.id!==le.id:!1),[s,a,nt,le]),te=x.useMemo(()=>{const ke=m.trim().toLowerCase();return c.filter(Ct=>{if(!Je){if(!wt||!le)return!1;const Et=s.find(Ln=>Ln.id===Ct.employeeId),Rt=Ct.reviewerUid===t.uid,xn=Ye&&(Et==null?void 0:Et.reportingManagerId)===le.id,dn=Ct.employeeId===le.id;if(!Rt&&!xn&&!dn)return!1}return a!=="all"&&Ct.branchId!==a||u!=="all"&&Ct.status!==u?!1:ke?[Ct.employeeName,Ct.employeeCode,Ct.reviewTitle,Ct.reviewerName,Fj(Ct.recommendation)].filter(Boolean).join(" ").toLowerCase().includes(ke):!0})},[c,m,u,a,Je,wt,Ye,le,s,t.uid]),Ge=x.useMemo(()=>{const ke=te,Ct=ke.filter(Rt=>Rt.status==="final"),Et=Ct.length?Ct.reduce((Rt,xn)=>Rt+Number(xn.overallScore||0),0)/Ct.length:0;return{total:ke.length,draft:ke.filter(Rt=>Rt.status==="draft").length,final:Ct.length,average:Et}},[te]),pt=x.useMemo(()=>{const ke=Wm.map(Ct=>Number(Y[Ct.key]||0));return ke.reduce((Ct,Et)=>Ct+Et,0)/ke.length},[Y]),$e=H!=="yearly"||Object.keys(Pe).length>0,st=s.find(ke=>ke.id===G),Nt=W_(st),be=Wm.map(ke=>({...ke,label:SU[Nt][ke.key]})),jt=H==="yearly"&&!!G&&!String((st==null?void 0:st.joiningDate)||"").trim(),bt=H==="yearly"&&st&&!jt?rt(st,L):[],tn=bt[0]||"",B=H!=="yearly"||pe>
40770&&qe===pe,xe=()=>{w(null),z(""),K("monthly"),D(Wv()),Z("Monthly Performance Review"),q(Lj()),ae(Bj()),je(Gm()),$(""),P(""),me(""),de("none"),Re({}),Be({}),ee(""),se(0),Se(0)},tt=()=>{xe(),p(!0)},ht=ke=>{if(!["draft","returned"].includes(ke.status)){T("Only Draft or Returned appraisal can be edited.");return}w(ke),z(ke.employeeId);const Ct=No(ke);K(Ct),D(Ct==="yearly"?ke.periodFrom.slice(0,4):Wv()),Z(ke.reviewTitle),q(ke.periodFrom),ae(ke.periodTo),je({...Gm(),...ke.scores}),$(ke.strengths||""),P(ke.improvementAreas||""),me(ke.reviewerComments||""),de(ke.recommendation||"none"),Re(ke.autoScores||{}),Be(ke.overrideReasons||{}),ee(ke.autoScores&&Object.keys(ke.autoScores).length?"ERP-calculated scores loaded from this draft.":""),se(Number(ke.sourceMonthlyCount||0)),Se(Number(ke.expectedMonthlyCount||0)),p(!0)},dt=ke=>{if(K(ke),Re({}),Be({}),ee(""),se(0),Se(0),ke==="yearly"){const Ct=Wv();D(Ct),Z("Yearly Performance Review"),q(G_(Ct)),ae(Y_(Ct)),de("none"),je(Gm())}else Z("Monthly Performance Review"),q(Lj()),ae(Bj()),de("none")},we=ke=>{D(ke),q(G_(ke)),ae(Y_(ke)),je(Gm()),Re({}),Be({}),ee(""),se(0),Se(0),de("none")};function rt(ke,Ct){const Et=`${Ct}-01`,Rt=`${Ct}-12`,xn=Me&&Me.slice(0,7)>Et?Me.slice(0,7):Et,dn=ke.joiningDate?ke.joiningDate.slice(0,7):"",Ln=dn&&dn>xn?dn:xn;return Ln>Rt?[]:AU(`${Ln}-01`,`${Rt}-01`)}const St=()=>{const ke=s.find(Sa=>Sa.id===G);if(!ke){ee("Select an employee first.");return}if(!fe||!ne||fe>ne){ee("Select a valid yearly appraisal period first.");return}const Ct=rt(ke,L),Et=new Set(Ct),Rt=c.filter(Sa=>Sa.employeeId===ke.id&&No(Sa)==="monthly"&&Sa.status==="final"&&Et.has(Sa.periodFrom.slice(0,7))),xn=new Map;Rt.forEach(Sa=>{const aa=Sa.periodFrom.slice(0,7),$a=xn.get(aa);(!$a||Sa.updatedAt>$a.updatedAt)&&xn.set(aa,Sa)});const dn=Array.from(xn.values());if(se(dn.length),Se(Ct.length),!dn.length){je(Gm()),Re({}),Be({}),ee(Ct.length?`No finalized Monthly Appraisal was found for the ${Ct.length} required month(s).`:"No appraisal month is required for this employee in the selected year based on company effective date and employee joining date.");return}const Ln=Date.now(),wa={...Y},Ca={};Wm.forEach(Sa=>{const aa=dn.map(vs=>{var ka;return Number(((ka=vs.scores)==null?void 0:ka[Sa.key])||0)}).filter(vs=>vs>0);if(!aa.length)return;const $a=aa.reduce((vs,ka)=>vs+ka,0)/aa.length,jn=Math.max(1,Math.min(5,Math.round($a)));wa[Sa.key]=jn,Ca[Sa.key]={score:jn,source:"Finalized Monthly Appraisals",evidence:`${aa.length} month(s), average ${$a.toFixed(2)}/5`,calculatedAt:Ln}}),je(wa),Re(Ca),Be({});const In=Ct.length-dn.length;ee(`Yearly score calculated from ${dn.length} of ${Ct.length} required finalized monthly appraisal(s).`+(In>0?` ${In} required month(s) are missing.`:" All required months are complete."))},Qt=async()=>{if(H==="yearly"){St();return}const ke=s.find(Ct=>Ct.id===G);if(!ke){ee("Select an employee first.");return}if(!fe||!ne||fe>ne){ee("Select a valid appraisal period first.");return}it(!0),ee("");try{const Ct=Date.now(),Et={},Rt={...Y},xn=J_(fe),dn=K_(ne),Ln=IU(fe,ne),In=(await Promise.all(Ln.map(ka=>mn(re(ie,`attendanceDaily/${t.companyId}/${ka}/${ke.id}`))))).filter(ka=>ka.exists()).map(ka=>ka.val()).filter(ka=>!["leave","weekly_off","holiday","official_day_off"].includes(ka.status));if(In.length){const Ja=In.reduce((ta,W)=>["present","late"].includes(W.status)?ta+1:["half_day","missing_punch"].includes(W.status)?ta+.5:ta,0)/In.length*100,_n=Gv(Ja);Rt.attendance=_n,Et.attendance={score:_n,source:"ERP Attendance",evidence:`${In.length} attendance day(s), ${Ja.toFixed(1)}% attendance credit`,calculatedAt:Ct};const ha=In.filter(ta=>["present","late","half_day","missing_punch"].includes(ta.status));if(ha.length){const W=ha.reduce((Zt,vt)=>{const Ae=Math.max(Number(vt.lateMinutes||0),0);return Ae<=0&&vt.status!=="missing_punch"?Zt+1:vt.status==="missing_punch"?Zt+.4:Zt+Math.max(0,1-Math.min(Ae,60)/60)},0)/ha.length*100,ft=Gv(W);Rt.punctuality=ft,Et.punctuality={score:ft,source:"ERP Attendance",evidence:`${ha.length} workday(s), ${W.toFixed(1)}% punctuality credit`,calculatedAt:Ct}}}const Sa=await mn(re(ie,`performanceTargets/${t.companyId}`)),aa=Sa.exists()?Object.values(Sa.val()).filter(ka=>ka.active!==!1&&ka.scopeType==="employee"&&ka.scopeId===ke.id&&ka.startDate<=dn&&ka.endDate>=xn):[];if(aa.length){const ka=aa.some(At=>At.category==="service"),Ja=aa.some(At=>At.metric==="sales_amount"||At.metric==="invoice_count"),_n=aa.some(At=>At.metric==="collection_amount"),ha=aa.some(At=>At.metric==="new_customers"),[ta,W,ft,Zt]=await Promise.all([ka?mn(re(ie,`serviceJobs/${t.companyId}`)):Promise.resolve(null),Ja?mn(re(ie,`invoices/${t.companyId}`)):Promise.resolve(null),_n?mn(re(ie,`collections/${t.companyId}`)):Promise.resolve(null),ha?mn(re(ie,`customers/${t.companyId}`)):Promise.resolve(null)]),vt=ta!=null&&ta.exists()?Object.values(ta.val()):[],Ae=W!=null&&W.exists()?Object.values(W.val()):[],oe=ft!=null&&ft.exists()?Object.values(ft.val()):[],Ve=Zt!=null&&Zt.exists()?Object.values(Zt.val()):[],he=At=>{const en=It=>!!(It&&It>=Math.max(xn,At.startDate)&&It<=Math.min(dn,At.endDate));if(At.category==="service"){const It=vt.filter(Pt=>(Pt.assignedTechnicianId===ke.id||!Pt.assignedTechnicianId&&Pt.assignedTechnician===ke.name)&&en(Pt.deliveredAt||Pt.updatedAt||Pt.createdAt));return At.metric==="completed_jobs"?It.filter(Pt=>["delivered","closed"].includes(Pt.status)).length:At.metric==="delivered_jobs"?It.filter(Pt=>Pt.status==="delivered").length:At.metric==="ready_jobs"?It.filter(Pt=>Pt.status==="ready").length:At.metric==="qc_completed"?It.filter(Pt=>!!Pt.qualityCheckedAt||Pt.status==="qc_completed"||["ready","delivered","closed"].includes(Pt.status)).length:0}return At.metric==="sales_amount"?Ae.filter(It=>It.salesEmployeeId===ke.id&&en(It.createdAt)).reduce((It,Pt)=>It+Number(Pt.grandTotal||0),0):At.metric==="collection_amount"?oe.filter(It=>It.salesEmployeeId===ke.id&&en(It.collectedAt||It.createdAt)).reduce((It,Pt)=>It+Number(Pt.amount||0),0):At.metric==="new_customers"?Ve.filter(It=>It.salesEmployeeId===ke.id&&en(It.createdAt)).length:At.metric==="invoice_count"?Ae.filter(It=>It.salesEmployeeId===ke.id&&en(It.createdAt)).length:0};let Oe=0,ut=0;
4077if(aa.forEach(At=>{const en=Math.max(Number(At.targetValue||0),0);if(en<=0)return;const It=Math.min(100,he(At)/en*100),Pt=Math.max(Number(At.weight||0),1);Oe+=It*Pt,ut+=Pt}),ut>0){const At=Oe/ut,en=Gv(At);Rt.productivity=en,Et.productivity={score:en,source:"ERP Performance Targets",evidence:`${aa.length} employee target(s), ${At.toFixed(1)}% weighted achievement`,calculatedAt:Ct}}if(ka){const At=vt.filter(en=>{const It=en.assignedTechnicianId===ke.id||!en.assignedTechnicianId&&en.assignedTechnician===ke.name,Pt=en.qualityCheckedAt||en.deliveredAt||en.updatedAt||en.createdAt;return It&&Pt>=xn&&Pt<=dn&&(en.qualityResult==="pass"||en.qualityResult==="fail")});if(At.length){const en=At.filter(na=>na.qualityResult==="pass").length,It=At.filter(na=>na.qualityResult==="fail").length,Pt=en/At.length*100,Jn=Gv(Pt);Rt.quality=Jn,Et.quality={score:Jn,source:"ERP QC Pass / Fail",evidence:`${en} passed, ${It} failed of ${At.length} explicitly evaluated QC job(s) · ${Pt.toFixed(1)}% pass rate`,calculatedAt:Ct}}}}const $a=await mn(re(ie,`publicJobReviews/${t.companyId}`));if($a.exists()){const ka=Object.values($a.val()).filter(Ja=>Ja.submittedAt>=xn&&Ja.submittedAt<=dn&&(Ja.technicianId===ke.id||!Ja.technicianId&&Ja.technicianName===ke.name));if(ka.length){const Ja=ka.reduce((ta,W)=>ta+Number(W.overall||0),0)/ka.length,_n=Q_(Ja);Rt.customerService=_n,Et.customerService={score:_n,source:"Customer Feedback · Overall",evidence:`${ka.length} review(s), average overall rating ${Ja.toFixed(2)}/5`,calculatedAt:Ct};const ha=ka.filter(ta=>Number(ta.repairQuality||0)>=1);if(ha.length){const ta=ha.reduce((Zt,vt)=>Zt+Number(vt.repairQuality||0),0)/ha.length,W=Q_(ta),ft=Et.quality;if(ft){const Zt=Number(ft.score)*.7+Number(W)*.3,vt=Math.max(1,Math.min(5,Math.round(Zt)));Rt.quality=vt,Et.quality={score:vt,source:"ERP QC + Customer Repair Quality",evidence:`${ft.evidence}; ${ha.length} customer repair-quality review(s), average ${ta.toFixed(2)}/5`,calculatedAt:Ct}}else Rt.quality=W,Et.quality={score:W,source:"Customer Feedback · Repair Quality",evidence:`${ha.length} repair-quality review(s), average ${ta.toFixed(2)}/5; no explicit QC pass/fail result available`,calculatedAt:Ct}}}}const jn=W_(ke);if(["service_lead","sales_manager","branch_manager","ceo"].includes(jn)){const ka=new Set(s.filter(Ja=>Ja.active!==!1&&Ja.reportingManagerId===ke.id&&Ja.id!==ke.id).map(Ja=>Ja.id));if(ka.size){const Ja=c.filter(_n=>ka.has(_n.employeeId)&&No(_n)==="monthly"&&_n.status==="final"&&K_(_n.periodTo)>=xn&&J_(_n.periodFrom)<=dn&&Number(_n.overallScore||0)>0);if(Ja.length){const _n=Ja.reduce((W,ft)=>W+Number(ft.overallScore||0),0)/Ja.length,ha=Math.max(1,Math.min(5,Math.round(_n))),ta=new Set(Ja.map(W=>W.employeeId)).size;Rt.teamwork=ha,Et.teamwork={score:ha,source:"Finalized Direct-Report Appraisals",evidence:`${ta} direct report(s), ${Ja.length} finalized monthly appraisal(s), team average ${_n.toFixed(2)}/5`,calculatedAt:Ct}}}}je(Rt),Re(Et),Be({});const vs=Object.keys(Et);ee(vs.length?`ERP calculated ${vs.length} score(s). Only criteria without reliable ERP evidence remain reviewer assessed.`:"No reliable ERP data was found for this employee/review period. Scores remain reviewer assessed.")}catch(Ct){console.error("Appraisal ERP score calculation failed:",Ct),ee("ERP scores could not be calculated. Existing manual scores were not changed.")}finally{it(!1)}},gn=(ke,Ct)=>{je(Rt=>({...Rt,[ke]:Ct}));const Et=Pe[ke];(!Et||Number(Et.score)===Number(Ct))&&Be(Rt=>{const xn={...Rt};return delete xn[ke],xn})},An=Wm.some(ke=>{const Ct=Pe[ke.key];return Ct?Number(Y[ke.key])!==Number(Ct.score)&&!String(Ee[ke.key]||"").trim():!1}),Sn=async ke=>{if(ke.preventDefault(),!(N?Ce:ct))return;if(jt){T("Yearly Appraisal cannot be saved until this employee's Joining Date is added in Employee Profile.");return}if(An){T("Override reason is required for every ERP-calculated score that was changed manually.");return}if(H==="yearly"&&!$e){T("Yearly Appraisal cannot be saved until finalized Monthly Appraisal data is available and calculated.");return}if(H==="yearly"&&!B){const Et=Math.max(pe-qe,0);T(`Yearly Appraisal Draft cannot be saved. ${Et} required monthly appraisal(s) are still missing.`);return}const Ct=s.find(Et=>Et.id===G);if(!Ct){T("Select an employee before saving.");return}if(!nt){if(!le){T("Your employee profile is not linked to this login. Appraisal cannot be saved.");return}if(Ct.id===le.id){T("Self-appraisal is not allowed. Your appraisal must be completed by your Reporting Manager.");return}
4077if(Ct.reportingManagerId!==le.id){T("You can appraise only employees who are assigned to you as Reporting Manager.");return}}if(!fe||!ne||fe>ne){T("Review period is invalid.");return}_(!0),T("");try{const Et=Date.now(),Rt=(N==null?void 0:N.id)||Ta(re(ie,`employeeAppraisals/${t.companyId}`)).key;if(!Rt)throw new Error("Could not create appraisal ID.");const xn={companyId:t.companyId,employeeId:Ct.id,employeeCode:Ct.employeeId||"",employeeName:Ct.name,branchId:Ct.branchId,periodFrom:fe,periodTo:ne,reviewTitle:M.trim()||"Performance Review",cycleType:H,sourceMonthlyCount:H==="yearly"?qe:0,expectedMonthlyCount:H==="yearly"?pe:0,scores:Y,autoScores:Pe,overrideReasons:Ee,overallScore:Number(pt.toFixed(2)),strengths:V.trim(),improvementAreas:F.trim(),reviewerComments:ue.trim(),recommendation:ge,status:(N==null?void 0:N.status)==="returned"?"draft":(N==null?void 0:N.status)||"draft",reviewerUid:t.uid,reviewerName:t.name,createdAt:(N==null?void 0:N.createdAt)||Et,updatedAt:Et};await Pn(re(ie,`employeeAppraisals/${t.companyId}/${Rt}`),xn),await ia({companyId:t.companyId,branchId:Ct.branchId,actorUid:t.uid,actorName:t.name,action:N?"appraisal.updated":"appraisal.created",entityType:"employee_appraisal",entityId:Rt,summary:`${Ct.name} appraisal ${N?"updated":"created"} (${fe} to ${ne}).`,metadata:{autoScoreCount:Object.keys(Pe).length,overriddenAutoScores:Wm.filter(dn=>{var Ln;return Pe[dn.key]&&Number(Y[dn.key])!==Number((Ln=Pe[dn.key])==null?void 0:Ln.score)}).map(dn=>{var Ln;return{key:dn.key,autoScore:(Ln=Pe[dn.key])==null?void 0:Ln.score,finalScore:Y[dn.key],reason:Ee[dn.key]||""}})}}),p(!1),xe(),T(N?"Appraisal updated successfully.":"Appraisal saved as Draft.")}catch(Et){console.error(Et),T("Appraisal could not be saved. Please try again.")}finally{_(!1)}},Xt=async ke=>{if(!De||!["draft","returned"].includes(ke.status))return;if(ke.reviewerUid!==t.uid&&!Je){T("Only the Reporting Manager who prepared this appraisal can submit it.");return}
4077const Ct=Date.now();await yn(re(ie,`employeeAppraisals/${t.companyId}/${ke.id}`),{status:"pending_approval",submittedAt:Ct,submittedByUid:t.uid,submittedByName:t.name,returnReason:"",updatedAt:Ct}),await ia({companyId:t.companyId,branchId:ke.branchId,actorUid:t.uid,actorName:t.name,action:"appraisal.submitted",entityType:"employee_appraisal",entityId:ke.id,summary:`${ke.employeeName} appraisal submitted for higher-authority approval.`}),T("Appraisal submitted for approval.")},Wt=ke=>{if(!Te||ke.status!=="pending_approval")return!1;if(Je)return!0;if(!le)return!1;const Ct=s.find(xn=>{var dn,Ln,wa;return xn.id===ke.reviewerUid||((dn=xn.email)==null?void 0:dn.toLowerCase())===((wa=(Ln=s.find(Ca=>Ca.id===ke.employeeId))==null?void 0:Ln.reportingManagerUserUid)==null?void 0:wa.toLowerCase())}),Et=s.find(xn=>xn.id===ke.employeeId),Rt=Et?s.find(xn=>xn.id===Et.reportingManagerId):void 0;return(Rt==null?void 0:Rt.reportingManagerId)===le.id||(Ct==null?void 0:Ct.reportingManagerId)===le.id},Gt=async ke=>{if(!Wt(ke)){T("This appraisal requires approval from the Reporting Manager's higher authority.");return}
4077const Ct=Date.now();await yn(re(ie,`employeeAppraisals/${t.companyId}/${ke.id}`),{status:"approved",approvedAt:Ct,approvedByUid:t.uid,approvedByName:t.name,updatedAt:Ct}),await ia({companyId:t.companyId,branchId:ke.branchId,actorUid:t.uid,actorName:t.name,action:"appraisal.approved",entityType:"employee_appraisal",entityId:ke.id,summary:`${ke.employeeName} appraisal approved by higher authority.`}),T("Appraisal approved. Authorized HR/Management can now Finalize & Lock it.")},$t=async ke=>{if(!Wt(ke))return;const Ct=window.prompt("Return reason / correction instruction:");if(!(Ct!=null&&Ct.trim()))return;const Et=Date.now();await yn(re(ie,`employeeAppraisals/${t.companyId}/${ke.id}`),{status:"returned",returnedAt:Et,returnedByUid:t.uid,returnedByName:t.name,returnReason:Ct.trim(),updatedAt:Et}),await ia({companyId:t.companyId,branchId:ke.branchId,actorUid:t.uid,actorName:t.name,action:"appraisal.returned",entityType:"employee_appraisal",entityId:ke.id,summary:`${ke.employeeName} appraisal returned for correction.`}),T("Appraisal returned to the Reporting Manager for correction.")},Vt=ke=>{if(!ce||ke.status!=="approved")return;const Ct=No(ke);if(Ct==="yearly"){const Rt=s.find(Ca=>Ca.id===ke.employeeId),xn=ke.periodFrom.slice(0,4),dn=Rt?rt(Rt,xn):[],Ln=new Set(dn),wa=new Set(c.filter(Ca=>Ca.employeeId===ke.employeeId&&No(Ca)==="monthly"&&Ca.status==="final"&&Ln.has(Ca.periodFrom.slice(0,7))).map(Ca=>Ca.periodFrom.slice(0,7)));if(!dn.length){T("Yearly Appraisal cannot be finalized because no eligible appraisal month exists for this employee in the selected year.");return}if(wa.size<dn.length){const Ca=dn.filter(In=>!wa.has(In));T(`Yearly Appraisal cannot be finalized. ${Ca.length} required monthly appraisal(s) are still missing: ${Ca.join(", ")}.`);return}}if(c.find(Rt=>Rt.id!==ke.id&&Rt.status==="final"&&Rt.employeeId===ke.employeeId&&No(Rt)===Ct&&(Ct==="yearly"?Rt.periodFrom.slice(0,4)===ke.periodFrom.slice(0,4):Rt.periodFrom.slice(0,7)===ke.periodFrom.slice(0,7)))){T(Ct==="yearly"?`A finalized Yearly Appraisal already exists for ${ke.employeeName} in ${ke.periodFrom.slice(0,4)}.`:`A finalized Monthly Appraisal already exists for ${ke.employeeName} in ${ke.periodFrom.slice(0,7)}.`);return}R(ke)},sn=async()=>{const ke=C;if(!(!ke||!ce||ke.status!=="approved")){_(!0);try{const Ct=Date.now();await yn(re(ie,`employeeAppraisals/${t.companyId}/${ke.id}`),{status:"final",finalizedAt:Ct,finalizedByUid:t.uid,finalizedByName:t.name,updatedAt:Ct}),await ia({companyId:t.companyId,branchId:ke.branchId,actorUid:t.uid,actorName:t.name,action:"appraisal.finalized",entityType:"employee_appraisal",entityId:ke.id,summary:`${ke.employeeName} appraisal finalized.`}),R(null),T(No(ke)==="yearly"?"â Yearly Appraisal finalized and locked successfully.":"â Monthly Appraisal finalized and locked successfully. It is now available to Yearly Appraisal.")}catch(Ct){console.error("Appraisal finalize failed:",Ct),T("Appraisal could not be finalized. Please try again.")}finally{_(!1)}}},on=async ke=>{!Ce||!["draft","returned"].includes(ke.status)||window.confirm(`Delete draft appraisal for ${ke.employeeName}?`)&&(await Ao(re(ie,`employeeAppraisals/${t.companyId}/${ke.id}`)),await ia({companyId:t.companyId,branchId:ke.branchId,actorUid:t.uid,actorName:t.name,action:"appraisal.deleted",entityType:"employee_appraisal",entityId:ke.id,summary:`${ke.employeeName} draft appraisal deleted.`}),T("Draft appraisal deleted."))};return e.jsxs("section",{className:"appraisal-page",children:[e.jsxs("header",{className:"appraisal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR"}),e.jsx("h1",{children:"Employee Appraisal"}),e.jsx("p",{children:"Create review cycles, score employee performance, record feedback and finalize recommendations."})]}),ct&&e.jsxs("button",{className:"primary-action-button",onClick:tt,children:[e.jsx(as,{size:18})," New Appraisal"]})]}),J&&e.jsx("div",{className:"appraisal-message",children:J}),e.jsxs("section",{className:"appraisal-summary",children:[e.jsxs("article",{children:[e.jsx(T4,{size:20}),e.jsx("span",{children:"Total Reviews"}),e.jsx("strong",{children:Ge.total})]}),e.jsxs("article",{children:[e.jsx(Zi,{size:20}),e.jsx("span",{children:"Draft"}),e.jsx("strong",{children:Ge.draft})]}),e.jsxs("article",{children:[e.jsx(Ms,{size:20}),e.jsx("span",{children:"Finalized"}),e.jsx("strong",{children:Ge.final})]}),e.jsxs("article",{children:[e.jsx(j1,{size:20}),e.jsx("span",{children:"Avg. Final Score"}),e.jsxs("strong",{children:[Ge.average.toFixed(2)," / 5"]})]})]}),e.jsxs("section",{className:"appraisal-toolbar",children:[e.jsxs("label",{className:"appraisal-search",children:[e.jsx(xr,{size:17}),e.jsx("input",{value:m,onChange:ke=>d(ke.target.value),placeholder:"Search employee, review or recommendation..."})]}),e.jsxs("select",{value:u,onChange:ke=>f(ke.target.value),children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"draft",children:"Draft"}),e.jsx("option",{value:"pending_approval",children:"Pending Approval"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"returned",children:"Returned"}),e.jsx("option",{value:"final",children:"Finalized"})]})]}),e.jsx("section",{className:"appraisal-card",children:e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Cycle"}),e.jsx("th",{children:"Review Period"}),e.jsx("th",{children:"Score"}),e.jsx("th",{children:"Rating"}),e.jsx("th",{children:"Recommendation"}),e.jsx("th",{children:"Reviewer"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[te.map(ke=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:ke.employeeName}),e.jsx("small",{children:ke.employeeCode||"â"})]}),e.jsx("td",{children:e.jsx("strong",{children:No(ke)==="yearly"?"Yearly":"Monthly"})}),e.jsxs("td",{children:[e.jsx("strong",{children:ke.reviewTitle}),e.jsxs("small",{children:[ke.periodFrom," â ",ke.periodTo]})]}),e.jsx("td",{children:e.jsxs("strong",{children:[Number(ke.overallScore||0).toFixed(2)," / 5"]})}),e.jsx("td",{children:Uj(Number(ke.overallScore||0))}),e.jsx("td",{children:No(ke)==="yearly"?ke.recommendation==="none"?"No Change":Fj(ke.recommendation):"â"}),e.jsx("td",{children:ke.reviewerName}),e.jsx("td",{children:e.jsx("span",{className:`appraisal-status ${ke.status}`,children:ke.status==="final"?"Finalized":ke.status==="pending_approval"?"Pending Approval":ke.status==="approved"?"Approved":ke.status==="returned"?"Returned":"Draft"})}),e.jsx("td",{children:e.jsxs("div",{className:"appraisal-actions",children:[e.jsx("button",{title:"View",onClick:()=>b(ke),children:e.jsx(ui,{size:16})}),Ce&&["draft","returned"].includes(ke.status)&&e.jsxs(e.Fragment,{children:[e.jsx("button",{title:"Edit Draft",onClick:()=>ht(ke),children:e.jsx(Zi,{size:16})}),De&&e.jsx("button",{title:"Submit for Approval",onClick:()=>void Xt(ke),children:e.jsx(hr,{size:16})}),e.jsx("button",{title:"Delete Draft",onClick:()=>void on(ke),children:e.jsx(po,{size:16})})]}),Wt(ke)&&e.jsxs(e.Fragment,{children:[e.jsx("button",{title:"Ap
4077prove Appraisal",onClick:()=>void Gt(ke),children:e.jsx(Ms,{size:16})}),e.jsx("button",{title:"Return for Correction",onClick:()=>void $t(ke),children:e.jsx(ja,{size:16})})]}),ce&&ke.status==="approved"&&e.jsx("button",{title:"Finalize & Lock",onClick:()=>Vt(ke),children:e.jsx(Ms,{size:16})}),ke.status==="final"&&e.jsx("span",{className:"appraisal-locked-note",title:"Finalized records are locked",children:"Locked"})]})})]},ke.id)),!te.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"empty-table",children:"No appraisal record found."})})]})]})})}),g&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!I&&p(!1),children:e.jsxs("form",{className:"modal appraisal-modal",onSubmit:Sn,onMouseDown:ke=>ke.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Employee Appraisal"}),e.jsx("h2",{children:N?"Edit Draft Appraisal":"New Appraisal"})]}),e.jsx("button",{type:"button",onClick:()=>p(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"appraisal-form-grid",children:[e.jsxs("label",{children:["Appraisal Cycle",e.jsxs("select",{value:H,onChange:ke=>dt(ke.target.value),disabled:!!N,children:[e.jsx("option",{value:"monthly",children:"Monthly Appraisal"}),e.jsx("option",{value:"yearly",children:"Yearly Appraisal"})]})]}),e.jsxs("label",{children:["Employee",e.jsxs("select",{value:G,onChange:ke=>z(ke.target.value),required:!0,disabled:!!N,children:[e.jsx("option",{value:"",children:"Select employee"}),xt.map(ke=>e.jsxs("option",{value:ke.id,children:[ke.employeeId?`${ke.employeeId} · `:"",ke.name]},ke.id))]})]}),e.jsxs("label",{children:["Review Title",e.jsx("input",{value:M,onChange:ke=>Z(ke.target.value)})]}),H==="yearly"?e.jsxs("label",{children:["Review Year",e.jsx("select",{value:L,onChange:ke=>we(ke.target.value),children:Array.from({length:7},(ke,Ct)=>String(new Date().getFullYear()-5+Ct)).map(ke=>e.jsx("option",{value:ke,children:ke},ke))})]}):e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Period From",e.jsx("input",{type:"date",value:fe,onChange:ke=>q(ke.target.value),required:!0})]}),e.jsxs("label",{children:["Period To",e.jsx("input",{type:"date",value:ne,onChange:ke=>ae(ke.target.value),required:!0})]})]})]}),e.jsxs("div",{className:"appraisal-auto-panel",children:[e.jsxs("div",{children:[e.jsx("strong",{children:H==="yearly"?"Yearly Auto Score":"ERP Auto Score"}),e.jsx("p",{children:H==="yearly"?"Yearly scores are consolidated from finalized Monthly Appraisals. Missing months are shown clearly and are not fabricated.":Nt==="ceo"||Nt==="branch_manager"?"Management-level KPI labels are applied automatically. ERP evidence is used only where it directly belongs to the selected employee; leadership and management outcomes remain reviewer assessed.":"Attendance, punctuality, target achievement, service/QC and customer reviews will be used where reliable data exists. Leadership/teamwork remains reviewer assessed."})]}),e.jsxs("button",{type:"button",className:"vx-button vx-button-secondary",onClick:Qt,disabled:We||!G,children:[e.jsx(Hi,{size:16,className:We?"spin":""}),We?"Calculating...":H==="yearly"?"Calculate from Monthly":"Calculate from ERP"]})]}),_e&&e.jsx("div",{className:"appraisal-auto-message",children:_e}),H==="yearly"&&st&&!jt&&e.jsxs("div",{className:"appraisal-yearly-coverage",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Eligible From"}),e.jsx("strong",{children:tn||"â"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Required Months"}),e.jsx("strong",{children:bt.length})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Completed"}),e.jsx("strong",{children:qe})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Missing"}),e.jsx("strong",{children:Math.max(bt.length-qe,0)})]})]}),H==="yearly"&&$e&&e.jsx("div",{className:"appraisal-yearly-lock-note",children:"Yearly scores are read-only. They are calculated only from finalized Monthly Appraisals and cannot be manually overridden."}),jt&&e.jsx("div",{className:"appraisal-yearly-joining-warning",children:"Employee Joining Date is missing. Add the Joining Date in Employee Profile before saving the Yearly Appraisal, so VERIXO can determine the correct required months."}),H==="yearly"&&pe>0&&!B&&!jt&&e.jsxs("div",{className:"appraisal-yearly-incomplete-note",children:["Yearly Draft cannot be saved yet. ",Math.max(pe-qe,0)," required monthly appraisal(s) are still missing."]}),st&&e.jsxs("div",{className:"appraisal-template-note",children:[e.jsxs("strong",{children:[CU[Nt]," KPI Template"]}),e.jsx("span",{children:"Criteria are matched to the employee's designation/management level. ERP values are used only where reliable data exists; leadership/management criteria remain reviewer assessed."})]}),e.jsx("div",{className:"appraisal-score-grid",children:be.map(ke=>{var Ct,Et,Rt,xn;return e.jsxs("label",{className:"appraisal-score-field",children:[e.jsxs("span",{className:"appraisal-score-label",children:[ke.label,Pe[ke.key]&&e.jsx("em",{children:H==="yearly"?"Monthly Average · Locked":"ERP Calculated"}),H!=="yearly"&&ke.key==="teamwork"&&!Pe.teamwork&&e.jsx("em",{className:"manual",children:"Reviewer Assessment"})]}),e.jsxs("select",{value:$e?Y[ke.key]:"",disabled:H==="yearly","aria-readonly":H==="yearly",title:H==="yearly"?"Yearly score is locked to finalized Monthly Appraisal averages.":void 0,onChange:dn=>gn(ke.key,Number(dn.target.value)),children:[H==="yearly"&&!$e&&e.jsx("option",{value:"",children:"Not Available"}),e.jsx("option",{value:1,children:"1 - Unsatisfactory"}),e.jsx("option",{value:2,children:"2 - Needs Improvement"}),e.jsx("option",{value:3,children:"3 - Good"}),e.jsx("option",{value:4,children:"4 - Very Good"}),e.jsx("option",{value:5,children:"5 - Outstanding"})]}),Pe[ke.key]&&e.jsxs("small",{className:"appraisal-auto-evidence",children:["Auto: ",(Ct=Pe[ke.key])==null?void 0:Ct.score,"/5 · ",(Et=Pe[ke.key])==null?void 0:Et.source,e.jsx("br",{}),(Rt=Pe[ke.key])==null?void 0:Rt.evidence]}),H!=="yearly"&&Pe[ke.key]&&Number(Y[ke.key])!==Number((xn=Pe[ke.key])==null?void 0:xn.score)&&e.jsx("input",{className:"appraisal-override-reason",value:Ee[ke.key]||"",onChange:dn=>Be(Ln=>({...Ln,[ke.key]:dn.target.value})),placeholder:"Required: reason for overriding ERP score"})]},ke.key)})}),e.jsxs("div",{className:"appraisal-overall",children:[e.jsx("span",{children:"Overall Score"}),H==="yearly"&&!$e?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"â / 5"}),e.jsx("small",{children:"Not Available"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("strong",{children:[pt.toFixed(2)," / 5"]}),e.jsx("small",{children:Uj(pt)})]})]}),e.jsxs("div",{className:"appraisal-notes-grid",children:[e.jsxs("label",{children:["Strengths",e.jsx("textarea",{value:V,onChange:ke=>$(ke.target.value),rows:3})]}
4077),e.jsxs("label",{children:["Improvement Areas",e.jsx("textarea",{value:F,onChange:ke=>P(ke.target.value),rows:3})]}),e.jsxs("label",{children:["Reviewer Comments",e.jsx("textarea",{value:ue,onChange:ke=>me(ke.target.value),rows:3})]}),H==="yearly"?e.jsxs("label",{children:["Yearly Recommendation",e.jsxs("select",{value:ge,onChange:ke=>de(ke.target.value),children:[e.jsx("option",{value:"none",children:"No Change"}),e.jsx("option",{value:"increment",children:"Salary Increment"}),e.jsx("option",{value:"promotion",children:"Promotion"}),e.jsx("option",{value:"training",children:"Training / Development"}),e.jsx("option",{value:"performance_improvement_plan",children:"Performance Improvement Plan"})]})]}):e.jsxs("div",{className:"appraisal-cycle-note",children:[e.jsx("strong",{children:"Monthly Review"}),e.jsx("p",{children:"Salary Increment, Promotion and annual recommendations are intentionally reserved for Yearly Appraisal."})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:()=>p(!1),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"vx-button vx-button-primary",disabled:I||H==="yearly"&&(!B||jt),title:jt?"Add this employee's Joining Date in Employee Profile before saving the Yearly Draft.":H==="yearly"&&!B?"Complete all required finalized Monthly Appraisals before saving the Yearly Draft.":void 0,children:[e.jsx(hr,{size:16}),I?"Saving...":"Save Draft"]})]})]})}),C&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>!I&&R(null),children:e.jsxs("section",{className:"modal appraisal-finalize-modal",onMouseDown:ke=>ke.stopPropagation(),children:[e.jsx("div",{className:"appraisal-finalize-icon",children:e.jsx(Ms,{size:28})}),e.jsxs("div",{className:"appraisal-finalize-copy",children:[e.jsx("p",{className:"eyebrow",children:"Confirm Finalization"}),e.jsxs("h2",{children:["Finalize ",No(C)==="yearly"?"Yearly":"Monthly"," Appraisal?"]}),e.jsxs("p",{children:[e.jsx("strong",{children:C.employeeName})," · ",No(C)==="yearly"?C.periodFrom.slice(0,4):C.periodFrom.slice(0,7)]}),e.jsx("div",{className:"appraisal-finalize-warning",children:No(C)==="yearly"?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"This will lock the annual scores and recommendation."}),e.jsx("span",{children:"Finalized records cannot be edited or deleted."})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"This will lock the monthly scores."}),e.jsx("span",{children:"The finalized result will become available to Yearly Appraisal."}),e.jsx("span",{children:"Finalized records cannot be edited or deleted."})]})})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button vx-button-secondary",onClick:()=>R(null),disabled:I,children:"Cancel"}),e.jsxs("button",{type:"button",className:"vx-button vx-button-primary",onClick:sn,disabled:I,children:[e.jsx(Ms,{size:16}),I?"Finalizing...":"Finalize & Lock"]})]})]})}),y&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>b(null),children:e.jsxs("section",{className:"modal appraisal-view-modal",onMouseDown:ke=>ke.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Appraisal Details"}),e.jsx("h2",{children:y.employeeName}),e.jsxs("p",{children:[y.reviewTitle," · ",y.periodFrom," to ",y.periodTo]})]}),e.jsx("button",{onClick:()=>b(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"appraisal-view-score",children:[e.jsxs("strong",{children:[Number(y.overallScore||0).toFixed(2)," / 5"]}),e.jsx("span",{children:Uj(Number(y.overallScore||0))})]}),e.jsx("div",{className:"appraisal-score-grid",children:Wm.map(ke=>{var Ct,Et,Rt,xn,dn;return e.jsxs("div",{className:"appraisal-score-item appraisal-view-score-item",children:[e.jsxs("div",{children:[e.jsx("span",{children:ke.label}),((Ct=y.autoScores)==null?void 0:Ct[ke.key])&&e.jsxs("small",{children:["ERP: ",(Et=y.autoScores[ke.key])==null?void 0:Et.score,"/5 · ",(Rt=y.autoScores[ke.key])==null?void 0:Rt.source,(xn=y.overrideReasons)!=null&&xn[ke.key]?` · Override: ${y.overrideReasons[ke.key]}`:""]})]}),e.jsxs("strong",{children:[Number(((dn=y.scores)==null?void 0:dn[ke.key])||0)," / 5"]})]},ke.key)})}),e.jsxs("div",{className:"appraisal-view-notes",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Strengths"}),e.jsx("p",{children:y.strengths||"â"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Improvement Areas"}),e.jsx("p",{children:y.improvementAreas||"â"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Reviewer Comments"}),e.jsx("p",{children:y.reviewerComments||"â"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Cycle"}),e.jsx("p",{children:No(y)==="yearly"?"Yearly Appraisal":"Monthly Appraisal"})]}),No(y)==="yearly"&&e.jsxs("div",{children:[e.jsx("small",{children:"Recommendation"}),e.jsx("p",{children:y.recommendation==="none"?"No Change":Fj(y.recommendation)})]}),No(y)==="yearly"&&e.jsxs("div",{children:[e.jsx("small",{children:"Monthly Coverage"}),e.jsxs("p",{children:[Number(y.sourceMonthlyCount||0)," of ",Number(y.expectedMonthlyCount||0)," finalized month(s)"]})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Reviewer"}),e.jsx("p",{children:y.reviewerName})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Status"}),e.jsx("p",{children:y.status==="final"?"Finalized · Locked":"Draft"})]}),y.status==="final"&&e.jsxs("div",{children:[e.jsx("small",{children:"Finalized By"}),e.jsxs("p",{children:[y.finalizedByName||y.reviewerName,y.finalizedAt?` · ${new Date(y.finalizedAt).toLocaleStr
4077ing()}`:""]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"vx-button vx-button-primary",onClick:()=>b(null),children:"Close"})})]})})]})}function X_(t){return`${t.employeeId?`${t.employeeId} - `:""}${t.name}`}function $f(t,n){const a=String(t.employeeId||""),s=String(n.employeeId||"");return a.localeCompare(s,void 0,{numeric:!0,sensitivity:"base"})||t.name.localeCompare(n.name)}function kU({profile:t,branches:n,selectedBranchId:a}){var _;const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState(null);x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),J=>{if(!J.exists())return i([]);const T=J.val();i(Object.entries(T).map(([G,z])=>({id:G,...z})).filter(G=>G.active!==!1).sort($f))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`companies/${t.companyId}`),J=>{d(J.exists()?J.val():null)}),[t.companyId]),x.useEffect(()=>qt(Vl(re(ie,"users"),ql("companyId"),Dh(t.companyId)),J=>{if(!J.exists())return l([]);const T=J.val();l(Object.entries(T).map(([G,z])=>({uid:G,...z})).filter(G=>G.active!==!1&&["owner","super_admin"].includes(G.role)).sort((G,z)=>G.name.localeCompare(z.name)))}),[t.companyId]);const u=x.useMemo(()=>s.filter(J=>a==="all"||J.branchId===a),[s,a]),f=x.useMemo(()=>new Set(u.map(J=>J.id)),[u]),g=x.useMemo(()=>u.filter(J=>!J.reportingManagerId&&!J.reportingManagerUserUid).sort($f),[u]),p=x.useMemo(()=>{const J=new Map;return u.forEach(T=>{if(!T.reportingManagerId||!f.has(T.reportingManagerId))return;const G=J.get(T.reportingManagerId)||[];G.push(T),J.set(T.reportingManagerId,G)}),J.forEach(T=>T.sort($f)),J},[u,f]),y=x.useMemo(()=>u.filter(J=>{var T;return!J.reportingManagerId&&!J.reportingManagerUserUid&&!((T=J.roles)!=null&&T.includes("owner"))}),[u]),b=x.useMemo(()=>c.map(J=>({...J,directReports:u.filter(T=>T.reportingManagerUserUid===J.uid).sort($f)})).filter(J=>J.directReports.length>0),[c,u]),N=J=>{var T;return((T=n.find(G=>G.id===J))==null?void 0:T.name)||J||"-"},w=a==="all"?"All Branches":((_=n.find(J=>J.id===a))==null?void 0:_.name)||"Selected Branch",C=new Date().toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}),R=(J,T=0,G=new Set,z=!0)=>{const H=G.has(J.id),K=new Set(G);K.add(J.id);const L=H?[]:(p.get(J.id)||[]).sort($f);return e.jsxs("div",{className:`hierarchy-node depth-${Math.min(T,6)} ${z?"is-last":"has-next-sibling"}`,children:[e.jsxs("div",{className:"hierarchy-branch-row",children:[T>0&&e.jsx("div",{className:"hierarchy-branch-gutter","aria-hidden":"true",children:e.jsx("span",{className:"hierarchy-elbow"})}),e.jsxs("div",{className:"hierarchy-person",children:[e.jsxs("div",{className:"hierarchy-person-main",children:[e.jsx("strong",{children:X_(J)}),e.jsx("span",{className:"hierarchy-designation",children:J.designation||"Designation not set"})]}),e.jsxs("div",{className:"hierarchy-person-meta",children:[e.jsx("span",{children:J.department||"Department not set"}),e.jsx("i",{children:"â¢"}),e.jsx("span",{children:N(J.branchId)}),H&&e.jsx("span",{className:"hierarchy-warning",children:"Circular reporting link"})]})]})]}),L.length>0&&e.jsx("div",{className:"hierarchy-children",children:L.map((D,M)=>R(D,T+1,K,M===L.length-1))})]},`${J.id}-${T}`)},I=J=>e.jsxs("div",{className:"hierarchy-management-node",children:[e.jsxs("div",{className:"hierarchy-person hierarchy-management-person",children:[e.jsxs("div",{className:"hierarchy-person-main",children:[e.jsx("span",{className:"hierarchy-level-label",children:"TOP MANAGEMENT"}),e.jsx("strong",{children:J.name}),e.jsx("span",{className:"hierarchy-designation",children:J.role==="owner"?"Company Owner":"Super Admin"})]}),e.jsxs("div",{className:"hierarchy-person-meta",children:[e.jsx("span",{children:"Company Management"}),e.jsx("i",{children:"â¢"}),e.jsx("span",{children:(m==null?void 0:m.name)||"Company"})]})]}),J.directReports.length>0&&e.jsx("div",{className:"hierarchy-children",children:J.directReports.map((T,G)=>R(T,1,new Set,G===J.directReports.length-1))})]},J.uid);return e.jsxs("section",{className:"hierarchy-page",children:[e.jsxs("header",{className:"hierarchy-header no-print",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR Report"}),e.jsx("h1",{children:"Reporting Hierarchy"}),e.jsx("p",{children:"Employee reporting structure generated automatically from Employee Profile - Reporting Manager."})]}),e.jsxs("button",{className:"primary-action-button",onClick:()=>window.print(),children:[e.jsx(Wi,{size:17})," Print / PDF"]})]}),e.jsxs("section",{className:"hierarchy-print-sheet",children:[e.jsxs("div",{className:"hierarchy-report-head",children:[e.jsxs("div",{className:"hierarchy-brand-block",children:[e.jsx("div",{className:"hierarchy-company-mark",children:e.jsx(Fu,{size:22})}),e.jsxs("div",{children:[e.jsx("span",{className:"hierarchy-report-kicker",children:"HUMAN RESOURCES DEPARTMENT"}),e.jsx("h2",{children:(m==null?void 0:m.name)||"Company"}),e.jsx("p",{children:"Employee Reporting Structure"})]})]}),e.jsxs("div",{className:"hierarchy-report-code",children:[e.jsx("small",{children:"REPORT"}),e.jsx("strong",{children:"HR-ORG"})]})]}),e.jsxs("div",{className:"hierarchy-information-strip",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Scope"}),e.jsx("strong",{children:w})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Generated"}),e.jsx("strong",{children:C})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Active Employees"}),e.jsx("strong",{children:u.length})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Reporting Assigned"}),e.jsx("strong",{children:u.filter(J=>!!(J.reportingManagerId||J.reportingManagerUserUid)).length})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Unassigned"}),e.jsx("strong",{children:y.length})]})]}),e.jsxs("div",{className:"hierarchy-section-title",children:[e.jsxs("div",{children:[e.jsx("span",{children:"ORGANIZATION STRUCTURE"}),e.jsx("h3",{children:"Management & Reporting Lines"})]}),e.jsx("small",{children:"Official employee reporting relationship"})]}),e.jsxs("div",{className:"hierarchy-tree",children:[b.map(I),g.map(J=>R(J)),!b.length&&!g.length&&e.jsx("div",{className:"hierarchy-empty",children:"No active employee hierarchy found for this branch scope."})]}),y.length>0&&e.jsxs("section",{className:"hierarchy-unassigned",children:[e.jsxs("div",{className:"hierarchy-exception-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"EXCEPTION REVIEW"}),e.jsx("h3",{children:"Reporting Manager Not Assigned"})]}),e.jsx("strong",{children:y.length})]}),e.jsx("p",{children:"Review these employees. Genuine top-management positions may intentionally remain without a Reporting Manager."}),e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Designation"}),e.jsx("th",{children:"Department"}),e.jsx("th",{children:"Branch"})]})}),e.jsx("tbody",{children:y.map(J=>e.jsxs("tr",{children:[e.jsx("td",{children:X_(J)}
4077),e.jsx("td",{children:J.designation||"-"}),e.jsx("td",{children:J.department||"-"}),e.jsx("td",{children:N(J.branchId)})]},J.id))})]})]}),e.jsxs("footer",{className:"hierarchy-report-footer",children:[e.jsx("span",{children:"Generated by VERIXO ERP"}),e.jsx("span",{children:"HR · Employee Reporting Structure"}),e.jsxs("span",{children:[(m==null?void 0:m.name)||"Company"," · ",w]})]})]})]})}const Z_=["documentsReceived","identityDocument","appointmentLetter","bankInformation","reportingManager","attendanceEnrolled","userAccount"],e5=["handoverCompleted","companyAssetsReturned","accountsClearance","attendancePayrollClearance","userAccessDisabled"];function Ym(t){return t.employmentStatus?t.employmentStatus:t.active===!1?"resigned":"confirmed"}function DU(t){return t==="probation"?"Probation / Onboarding":t==="confirmed"?"Confirmed":t==="notice_period"?"Notice Period":t==="resigned"?"Resigned":"Terminated"}function Yv(t,n){return{complete:n.filter(s=>!!(t!=null&&t[s])).length,total:n.length}}function t5(t){if(!t)return null;const n=new Date(`${t}T00:00:00`);if(Number.isNaN(n.getTime()))return null;const a=new Date;return a.setHours(0,0,0,0),Math.ceil((n.getTime()-a.getTime())/864e5)}function EU({profile:t,branches:n,selectedBranchId:a,onOpenEmployee:s}){const[i,c]=x.useState([]),[l,m]=x.useState(""),[d,u]=x.useState("all");x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),b=>{if(!b.exists())return c([]);const N=b.val();c(Object.entries(N).map(([w,C])=>({id:w,...C})))}),[t.companyId]);const f=b=>{var N;return((N=n.find(w=>w.id===b))==null?void 0:N.name)||"â"},g=x.useMemo(()=>i.filter(b=>a==="all"||b.branchId===a),[i,a]),p=x.useMemo(()=>{const b=R=>g.filter(I=>Ym(I)===R).length,N=g.filter(R=>{if(Ym(R)!=="probation")return!1;const I=t5(R.probationEndDate);return I!==null&&I<=30}).length,w=g.filter(R=>{if(!["notice_period","resigned","terminated"].includes(Ym(R)))return!1;const I=Yv(R.offboardingChecklist,e5);return I.complete<I.total}).length,C=g.filter(R=>{const I=Ym(R);if(!["probation","confirmed"].includes(I))return!1;const _=Yv(R.onboardingChecklist,Z_);return _.complete<_.total}).length;return{active:g.filter(R=>R.active!==!1).length,probation:b("probation"),confirmed:b("confirmed"),notice:b("notice_period"),resigned:b("resigned"),terminated:b("terminated"),probationAttention:N,clearancePending:w,onboardingIncomplete:C}},[g]),y=x.useMemo(()=>{const b=l.trim().toLowerCase();return g.filter(N=>d==="all"||Ym(N)===d).filter(N=>!b||[N.name,N.employeeId,N.department,N.designation,f(N.branchId)].filter(Boolean).join(" ").toLowerCase().includes(b)).sort((N,w)=>(N.employeeId||"").localeCompare(w.employeeId||"",void 0,{numeric:!0,sensitivity:"base"}))},[g,d,l,n]);return e.jsxs("section",{className:"employee-lifecycle-page",children:[e.jsx("header",{className:"employee-lifecycle-page-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR ANALYTICS"}),e.jsx("h1",{children:"Employee Lifecycle"}),e.jsx("p",{children:"Track onboarding, probation, confirmation, notice period and final clearance from one place."})]})}),e.jsxs("section",{className:"lifecycle-summary-grid",children:[e.jsxs("article",{children:[e.jsx(mc,{size:20}),e.jsx("span",{children:"Active Employees"}),e.jsx("strong",{children:p.active})]}),e.jsxs("article",{children:[e.jsx(Ho,{size:20}),e.jsx("span",{children:"Probation"}),e.jsx("strong",{children:p.probation})]}),e.jsxs("article",{children:[e.jsx(vd,{size:20}),e.jsx("span",{children:"Confirmed"}),e.jsx("strong",{children:p.confirmed})]}),e.jsxs("article",{children:[e.jsx(qu,{size:20}),e.jsx("span",{children:"Notice Period"}),e.jsx("strong",{children:p.notice})]}),e.jsxs("article",{children:[e.jsx(w1,{size:20}),e.jsx("span",{children:"Exited"}),e.jsx("strong",{children:p.resigned+p.terminated})]})]}),(p.probationAttention>0||p.clearancePending>0||p.onboardingIncomplete>0)&&e.jsxs("section",{className:"lifecycle-attention-strip",children:[e.jsx("strong",{children:"HR Attention"}),p.onboardingIncomplete>0&&e.jsxs("span",{children:[p.onboardingIncomplete," onboarding checklist(s) incomplete"]}),p.probationAttention>0&&e.jsxs("span",{children:[p.probationAttention," probation review(s) due/within 30 days"]}),p.clearancePending>0&&e.jsxs("span",{children:[p.clearancePending," offboarding clearance(s) incomplete"]})]}),e.jsxs("section",{className:"lifecycle-toolbar",children:[e.jsxs("label",{children:[e.jsx(xr,{size:17}
4077),e.jsx("input",{value:l,onChange:b=>m(b.target.value),placeholder:"Search employee, ID, branch, department..."})]}),e.jsxs("select",{value:d,onChange:b=>u(b.target.value),children:[e.jsx("option",{value:"all",children:"All Lifecycle Stages"}),e.jsx("option",{value:"probation",children:"Probation / Onboarding"}),e.jsx("option",{value:"confirmed",children:"Confirmed"}),e.jsx("option",{value:"notice_period",children:"Notice Period"}),e.jsx("option",{value:"resigned",children:"Resigned"}),e.jsx("option",{value:"terminated",children:"Terminated"})]})]}),e.jsx("section",{className:"lifecycle-table-card",children:e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Branch / Role"}),e.jsx("th",{children:"Stage"}),e.jsx("th",{children:"Important Date"}),e.jsx("th",{children:"Onboarding"}),e.jsx("th",{children:"Clearance"}),e.jsx("th",{children:"HR Attention"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[y.map(b=>{const N=Ym(b),w=Yv(b.onboardingChecklist,Z_),C=Yv(b.offboardingChecklist,e5),R=N==="probation"?t5(b.probationEndDate):null,I=N==="probation"&&R!==null&&R<=30?R<0?`Probation overdue by ${Math.abs(R)} day(s)`:`Probation review in ${R} day(s)`:["notice_period","resigned","terminated"].includes(N)&&C.complete<C.total?`${C.total-C.complete} clearance item(s) pending`:["probation","confirmed"].includes(N)&&w.complete<w.total?`${w.total-w.complete} onboarding item(s) pending`:"â",_=N==="probation"?b.probationEndDate:N==="confirmed"?b.confirmationDate:b.lastWorkingDate,J=["probation","confirmed"].includes(N)&&w.complete<w.total,T=["notice_period","resigned","terminated"].includes(N)&&C.complete<C.total,G=T?"Complete Clearance":J?"Complete Checklist":"View Profile";return e.jsxs("tr",{className:"lifecycle-row-clickable",onClick:()=>s(b.id),title:"Open Employee Profile",children:[e.jsxs("td",{children:[e.jsx("strong",{children:b.name}),e.jsx("small",{children:b.employeeId||"â"})]}),e.jsxs("td",{children:[e.jsx("strong",{children:f(b.branchId)}),e.jsx("small",{children:b.designation||b.department||"â"})]}),e.jsx("td",{children:e.jsx("span",{className:`lifecycle-stage ${N}`,children:DU(N)})}),e.jsx("td",{children:_||"â"}),e.jsx("td",{children:e.jsxs("div",{className:"lifecycle-progress",children:[e.jsxs("span",{className:w.complete===w.total?"progress-done":"progress-pending",children:[w.complete,"/",w.total]}),e.jsx("i",{children:e.jsx("b",{style:{width:`${Math.round(w.complete/w.total*100)}%`}})})]})}),e.jsx("td",{children:["notice_period","resigned","terminated"].includes(N)?e.jsxs("div",{className:"lifecycle-progress",children:[e.jsxs("span",{className:C.complete===C.total?"progress-done":"progress-pending",children:[C.complete,"/",C.total]}),e.jsx("i",{children:e.jsx("b",{style:{width:`${Math.round(C.complete/C.total*100)}%`}})})]}):"â"}),e.jsx("td",{children:I==="â"?e.jsxs("span",{className:"lifecycle-ok",children:[e.jsx(Ms,{size:15})," OK"]}):e.jsxs("span",{className:"lifecycle-attention",children:[e.jsx(qu,{size:15}),I]})}),e.jsx("td",{children:e.jsx("button",{type:"button",className:`lifecycle-action-button ${T?"clearance":J?"checklist":"view"}`,onClick:z=>{z.stopPropagation(),s(b.id)},children:G})})]},b.id)}),!y.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty-table",children:"No employee lifecycle record found."})})]})]})})})]})}const zj={type:"grievance",employeeId:"",subject:"",incidentDate:"",priority:"normal",status:"open",description:"",investigationNotes:"",actionTaken:"",resolutionNotes:""},PU=t=>t.replaceAll("_"," ").replace(/\b\w/g,n=>n.toUpperCase());function RU({profile:t,branches:n,selectedBranchId:a}){const[s,i]=x.useState([]),[c,l]=x.useState([]),[m,d]=x.useState(""),[u,f]=x.useState("all"),[g,p]=x.useState("all"),[y,b]=x.useState(!1),[N,w]=x.useState(null),[C,R]=x.useState(zj),[I,_]=x.useState(!1),[J,T]=x.useState(""),G=sa(t,"employee.manage");x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),fe=>{if(!fe.exists())return i([]);const q=fe.val();i(Object.entries(q).map(([ne,ae])=>({id:ne,...ae})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`employeeRelations/${t.companyId}`),fe=>{if(!fe.exists())return l([]);const q=fe.val();l(Object.entries(q).map(([ne,ae])=>({id:ne,...ae})))}),[t.companyId]);const z=x.useMemo(()=>s.filter(fe=>a==="all"||fe.branchId===a),[s,a]),H=fe=>{var q;return((q=n.find(ne=>ne.id===fe))==null?void 0:q.name)||"â"},K=x.useMemo(()=>{const fe=m.trim().toLowerCase();return c.filter(q=>a==="all"||q.branchId===a).filter(q=>u==="all"||q.type===u).filter(q=>g==="all"||q.status===g).filter(q=>!fe||[q.caseNo,q.employeeName,q.subject,q.description].join(" ").toLowerCase().includes(fe)).sort((q,ne)=>ne.updatedAt-q.updatedAt)},[c,a,u,g,m]),L=x.useMemo(()=>({total:K.length,open:K.filter(fe=>["open","investigating"].includes(fe.status)).length,disciplinary:K.filter(fe=>fe.type==="disciplinary").length,resolved:K.filter(fe=>["resolved","closed"].includes(fe.status)).length}),[K]),D=()=>{w(null),R(zj),T(""),b(!0)},M=fe=>{w(fe),R({type:fe.type,employeeId:fe.employeeId,subject:fe.subject,incidentDate:fe.incidentDate||"",priority:fe.priority,status:fe.status,description:fe.description,investigationNotes:fe.investigationNotes||"",actionTaken:fe.actionTaken||"",resolutionNotes:fe.resolutionNotes||""}),T(""),b(!0)},Z=async fe=>{if(fe.preventDefault(),!G||I)return;const q=s.find(ne=>ne.id===C.employeeId);if(!q||!C.subject.trim()||!C.description.trim()){T("Employee, subject and description are required.");return}_(!0),T("");try{const ne=Date.now(),ae=(N==null?void 0:N.id)||Ta(re(ie,`employeeRelations/${t.companyId}`)).key;if(!ae)throw new Error("Could not create case ID.");const Y=(N==null?void 0:N.caseNo)||`HR-${C.type==="grievance"?"GRV":"DIS"}-${new Date().getFullYear()}
4077-${String(ne).slice(-6)}`,je={caseNo:Y,type:C.type,employeeId:q.id,employeeName:q.name,branchId:q.branchId,subject:C.subject.trim(),incidentDate:C.incidentDate,priority:C.priority,status:C.status,description:C.description.trim(),investigationNotes:C.investigationNotes.trim(),actionTaken:C.actionTaken.trim(),resolutionNotes:C.resolutionNotes.trim(),createdAt:(N==null?void 0:N.createdAt)||ne,createdByUid:(N==null?void 0:N.createdByUid)||t.uid,createdByName:(N==null?void 0:N.createdByName)||t.name,updatedAt:ne,updatedByUid:t.uid,updatedByName:t.name};await Pn(re(ie,`employeeRelations/${t.companyId}/${ae}`),je),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:N?"employee_relation.updated":"employee_relation.created",entityType:"employee_relation",entityId:ae,summary:`${Y} ${N?"updated":"created"} for ${q.name}.`}),b(!1),w(null),R(zj)}catch(ne){console.error(ne),T("Case could not be saved. Please try again.")}finally{_(!1)}};return e.jsxs("section",{className:"employee-relations-page",children:[e.jsxs("header",{className:"employee-relations-head",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR EMPLOYEE RELATIONS"}),e.jsx("h1",{children:"Grievance & Disciplinary"}),e.jsx("p",{children:"Register, investigate and resolve employee-relations cases with a controlled status history."})]}),G&&e.jsxs("button",{className:"vx-button vx-button-primary",onClick:D,children:[e.jsx(as,{size:16})," New Case"]})]}),e.jsxs("section",{className:"relations-summary",children:[e.jsxs("article",{children:[e.jsx(Qw,{size:20}),e.jsx("span",{children:"Total Cases"}),e.jsx("strong",{children:L.total})]}),e.jsxs("article",{children:[e.jsx(qu,{size:20}),e.jsx("span",{children:"Open / Investigating"}),e.jsx("strong",{children:L.open})]}),e.jsxs("article",{children:[e.jsx(Y4,{size:20}),e.jsx("span",{children:"Disciplinary"}),e.jsx("strong",{children:L.disciplinary})]}),e.jsxs("article",{children:[e.jsx(Ms,{size:20}),e.jsx("span",{children:"Resolved / Closed"}),e.jsx("strong",{children:L.resolved})]})]}),e.jsxs("section",{className:"relations-toolbar",children:[e.jsxs("label",{children:[e.jsx(xr,{size:17}),e.jsx("input",{value:m,onChange:fe=>d(fe.target.value),placeholder:"Search case, employee, subject..."})]}),e.jsxs("select",{value:u,onChange:fe=>f(fe.target.value),children:[e.jsx("option",{value:"all",children:"All Case Types"}),e.jsx("option",{value:"grievance",children:"Grievance"}),e.jsx("option",{value:"disciplinary",children:"Disciplinary"})]}),e.jsxs("select",{value:g,onChange:fe=>p(fe.target.value),children:[e.jsx("option",{value:"all",children:"All Statuses"}),e.jsx("option",{value:"open",children:"Open"}),e.jsx("option",{value:"investigating",children:"Investigating"}),e.jsx("option",{value:"action_taken",children:"Action Taken"}),e.jsx("option",{value:"resolved",children:"Resolved"}),e.jsx("option",{value:"closed",children:"Closed"})]})]}),e.jsx("section",{className:"relations-table-card",children:e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Case"}),e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Subject"}),e.jsx("th",{children:"Priority"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Updated"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[K.map(fe=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:fe.caseNo}),e.jsx("small",{children:fe.incidentDate||"â"})]}),e.jsxs("td",{children:[e.jsx("strong",{children:fe.employeeName}),e.jsx("small",{children:H(fe.branchId)})]}),e.jsx("td",{children:e.jsx("span",{className:`relations-type ${fe.type}`,children:fe.type})}),e.jsx("td",{children:fe.subject}),e.jsx("td",{children:e.jsx("span",{className:`relations-priority ${fe.priority}`,children:fe.priority})}),e.jsx("td",{children:e.jsx("span",{className:`relations-status ${fe.status}`,children:PU(fe.status)})}),e.jsx("td",{children:new Date(fe.updatedAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx("button",{className:"relations-view",onClick:()=>M(fe),children:G?"Open / Update":"View"})})]},fe.id)),!K.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"empty-table",children:"No grievance or disciplinary case found."})})]})]})})}),y&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>b(!1),children:e.jsxs("form",{className:"modal employee-relations-modal",onSubmit:Z,onMouseDown:fe=>fe.stopPropagation(),children:[e.jsxs("div",{className:"relations-modal-head",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:N?N.caseNo:"NEW HR CASE"}),e.jsx("h2",{children:N?"Case Details":"Create Employee-Relations Case"})]}),e.jsx("button",{type:"button",className:"icon-button",onClick:()=>b(!1),children:e.jsx(ja,{size:18})})]}),e.jsxs("div",{className:"relations-form-grid",children:[e.jsxs("label",{children:["Case Type",e.jsxs("select",{disabled:!G,value:C.type,onCh
4077ange:fe=>R({...C,type:fe.target.value}),children:[e.jsx("option",{value:"grievance",children:"Grievance"}),e.jsx("option",{value:"disciplinary",children:"Disciplinary"})]})]}),e.jsxs("label",{children:["Employee",e.jsxs("select",{disabled:!G||!!N,value:C.employeeId,onChange:fe=>R({...C,employeeId:fe.target.value}),children:[e.jsx("option",{value:"",children:"Select Employee"}),z.map(fe=>e.jsxs("option",{value:fe.id,children:[fe.employeeId?`${fe.employeeId} · `:"",fe.name]},fe.id))]})]}),e.jsxs("label",{children:["Incident Date",e.jsx("input",{disabled:!G,type:"date",value:C.incidentDate,onChange:fe=>R({...C,incidentDate:fe.target.value})})]}),e.jsxs("label",{children:["Priority",e.jsxs("select",{disabled:!G,value:C.priority,onChange:fe=>R({...C,priority:fe.target.value}),children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"critical",children:"Critical"})]})]}),e.jsxs("label",{className:"full-field",children:["Subject",e.jsx("input",{disabled:!G,value:C.subject,onChange:fe=>R({...C,subject:fe.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Description",e.jsx("textarea",{disabled:!G,rows:4,value:C.description,onChange:fe=>R({...C,description:fe.target.value})})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{disabled:!G,value:C.status,onChange:fe=>R({...C,status:fe.target.value}),children:[e.jsx("option",{value:"open",children:"Open"}),e.jsx("option",{value:"investigating",children:"Investigating"}),e.jsx("option",{value:"action_taken",children:"Action Taken"}),e.jsx("option",{value:"resolved",children:"Resolved"}),e.jsx("option",{value:"closed",children:"Closed"})]})]}),e.jsxs("label",{className:"full-field",children:["Investigation Notes",e.jsx("textarea",{disabled:!G,rows:3,value:C.investigationNotes,onChange:fe=>R({...C,investigationNotes:fe.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Action Taken",e.jsx("textarea",{disabled:!G,rows:3,value:C.actionTaken,onChange:fe=>R({...C,actionTaken:fe.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Resolution / Closing Notes",e.jsx("textarea",{disabled:!G,rows:3,value:C.resolutionNotes,onChange:fe=>R({...C,resolutionNotes:fe.target.value})})]})]}),J&&e.jsx("div",{className:"relations-message",children:J}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button",onClick:()=>b(!1),children:"Close"}),G&&e.jsx("button",{type:"submit",className:"vx-button vx-button-primary",disabled:I,children:I?"Saving...":N?"Save Changes":"Create Case"})]})]})})]})}const HE=()=>new Date().toISOString().slice(0,10),qj={type:"appointment",employeeId:"",issueDate:HE(),effectiveDate:"",subject:"",body:""},Qv={appointment:"Appointment Letter",confirmation:"Confirmation Letter",increment:"Salary Revision / Increment",promotion:"Promotion Letter",transfer:"Transfer Letter",warning:"Warning Letter",show_cause:"Show Cause Notice",experience:"Experience Certificate",relieving:"Relieving Letter",termination:"Termination Letter",custom:"Custom HR Letter"},TU={appointment:"APT",confirmation:"CNF",increment:"INC",promotion:"PRO",transfer:"TRF",warning:"WRN",show_cause:"SCN",experience:"EXP",relieving:"REL",termination:"TER",custom:"CUS"};function n5(t,n,a,s){const i=(n==null?void 0:n.name)||"[Employee Name]",c=(n==null?void 0:n.designation)||"[Designation]",l=(a==null?void 0:a.name)||"the Company",m=(s==null?void 0:s.name)||"[Branch]";return{appointment:{subject:`Appointment as ${c}`,body:`Dear ${i}, 4078 4079We are pleased to appoint you as ${c} at ${l}. Your employment will be governed by the company's applicable policies, rules and terms communicated to you. 4080 4081Please sign and acknowledge acceptance of this appointment. 4082 4083Sincerely, 4084Human Resources`},confirmation:{subject:"Confirmation of Employment",body:`Dear ${i}, 4085 4086Following successful completion of your probation period, we are pleased to confirm your employment with ${l} as ${c}. 4087 4088All other applicable terms and conditions of your employment remain unchanged. 4089 4090Sincerely, 4091Human Resources`},increment:{subject:"Salary Revision / Increment",body:`Dear ${i}, 4092 4093We are pleased to inform you that your salary has been revised with effect from the date stated in this letter. The revised compensation details will be reflected in payroll according to company policy. 4094 4095We appreciate your contribution to ${l}. 4096 4097Sincerely, 4098Human Resources`},promotion:{subject:"Promotion",body:`Dear ${i}, 4099 4100We are pleased to inform you of your promotion. Your new designation/responsibilities and effective date are as stated in this letter and related HR records. 4101 4102We wish you continued success in your new role. 4103 4104Sincerely, 4105Human Resources`},transfer:{subject:`Transfer to ${m}`,body:`Dear ${i}, 4106 4107This is to inform you that you are being transferred to ${m} with effect from the date stated in this letter. Please coordinate with your current and receiving supervisor for a smooth handover. 4108 4109Sincerely, 4110Human Resources`},warning:{subject:"Formal Warning",body:`Dear ${i}, 4111 4112This letter serves as a formal warning regarding the matter described below. You are expected to take immediate corrective action and comply with company policy and instructions. 4113 4114Further repetition may result in additional disciplinary action. 4115 4116Sincerely, 4117Human Resources`},show_cause:{subject:"Show Cause Notice",body:`Dear ${i}, 4118 4119You are requested to provide a written explanation regarding the matter described
4119in this notice within the timeframe communicated by management. 4120 4121Your response will be reviewed before any further decision is taken. 4122 4123Sincerely, 4124Human Resources`},experience:{subject:"Experience Certificate",body:`TO WHOM IT MAY CONCERN 4125 4126This is to certify that ${i} worked with ${l} as ${c}. During the period of employment, the employee performed assigned responsibilities under the company's policies. 4127 4128We wish ${i} success in future endeavors. 4129 4130For ${l} 4131Human Resources`},relieving:{subject:"Relieving Letter",body:`Dear ${i}, 4132 4133This is to confirm that you are relieved from your duties with ${l} effective on the date stated in this letter, subject to completion of applicable clearance and handover requirements. 4134 4135We wish you success in your future endeavors. 4136 4137Sincerely, 4138Human Resources`},termination:{subject:"Termination of Employment",body:`Dear ${i}, 4139 4140This letter confirms termination of your employment with ${l} effective on the date stated in this letter, in accordance with the applicable company policy and decision communicated to you. 4141 4142Please complete all required handover and clearance formalities. 4143 4144Sincerely, 4145Human Resources`},custom:{subject:"HR Letter",body:`Dear ${i}, 4146 4147[Write the letter content here.] 4148 4149Sincerely, 4150Human Resources`}}[t]}async function MU({companyId:t,letterType:n,timestamp:a=Date.now()}){const s=new Date(a).getFullYear(),i=TU[n],c=`HR-${i}-${s}`,l=re(ie,`documentCounters/${t}/${c}`),m=await Ep(l,u=>({lastNumber:Number((u==null?void 0:u.lastNumber)||0)+1,documentCode:`HR-${i}`,year:s,updatedAt:a}));if(!m.committed||!m.snapshot.exists())throw new Error("HR letter number could not be generated.");const d=Number(m.snapshot.val().lastNumber||0);return`HR-${i}-${s}-${String(d).padStart(6,"0")}`}function $U({profile:t,branches:n,selectedBranchId:a}){const[s,i]=x.useState([]),[c,l]=x.useState(null),[m,d]=x.useState([]),[u,f]=x.useState(""),[g,p]=x.useState("all"),[y,b]=x.useState(!1),[N,w]=x.useState(null),[C,R]=x.useState(qj),[I,_]=x.useState(!1),[J,T]=x.useState(""),G=sa(t,"employee.manage");x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),V=>{if(!V.exists())return i([]);const $=V.val();i(Object.entries($).map(([F,P])=>({id:F,...P})).filter(F=>F.active!==!1))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`companies/${t.companyId}`),V=>{l(V.exists()?V.val():null)}),[t.companyId]),x.useEffect(()=>qt(re(ie,`hrLetters/${t.companyId}`),V=>{if(!V.exists())return d([]);const $=V.val();d(Object.entries($).map(([F,P])=>({id:F,...P})))}),[t.companyId]);const z=x.useMemo(()=>s.filter(V=>a==="all"||V.branchId===a),[s,a]),H=x.useMemo(()=>{const V=u.trim().toLowerCase();return m.filter($=>a==="all"||$.branchId===a).filter($=>g==="all"||$.type===g).filter($=>!V||[$.letterNo,$.employeeName,$.employeeCode,$.subject,Qv[$.type]].filter(Boolean).join(" ").toLowerCase().includes(V)).sort(($,F)=>F.updatedAt-$.updatedAt)},[m,u,a,g]),K=()=>{w(null),R(qj),T(""),b(!0)},L=V=>{w(V),R({type:V.type,employeeId:V.employeeId,issueDate:V.issueDate,effectiveDate:V.effectiveDate||"",subject:V.subject,body:V.body}),T(""),b(!0)},D=(V,$=C.employeeId)=>{const F=s.find(me=>me.id===$),P=n.find(me=>me.id===(F==null?void 0:F.branchId)),ue=n5(V,F,c,P);R(me=>({...me,type:V,employeeId:$,...ue}))},M=V=>{const $=s.find(ue=>ue.id===V),F=n.find(ue=>ue.id===($==null?void 0:$.branchId)),P=n5(C.type,$,c,F);R(ue=>({...ue,employeeId:V,...P}))},Z=async V=>{if(V.preventDefault(),!G||I)return;const $=s.find(F=>F.id===C.employeeId);if(!$||!C.issueDate||!C.subject.trim()||!C.body.trim()){T("Employee, issue date, subject and letter body are required.");return}_(!0),T("");try{const F=Date.now(),P=(N==null?void 0:N.id)||Ta(re(ie,`hrLetters/${t.companyId}`)).key;if(!P)throw new Error("Could not create HR letter ID.");const ue=n.find(de=>de.id===$.branchId),me=(N==null?void 0:N.letterNo)||await MU({companyId:t.companyId,letterType:C.type,timestamp:F}),ge={letterNo:me,type:C.type,employeeId:$.id,employeeName:$.name,employeeCode:$.employeeId||"",employeeJoiningDate:$.joiningDate||"",employeeDepartment:$.department||"",employeeDesignation:$.designation||"",branchId:$.branchId,branchName:(ue==null?void 0:ue.name)||"",issueDate:C.issueDate,effectiveDate:C.effectiveDate,subject:C.subject.trim(),body:C.body.trim(),createdAt:(N==null?void 0:N.createdAt)||F,createdByUid:(N==null?void 0:N.createdByUid)||t.uid,createdByName:(N==null?void 0:N.createdByName)||t.name,updatedAt:F,updatedByUid:t.uid,updatedByName:t.name};await Pn(re(ie,`hrLetters/${t.companyId}/${P}`),ge),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:N?"hr_letter.updated":"hr_letter.created",entityType:"hr_letter",entityId:P,summary:`${me} ${N?"updated":"created"} for ${$.name}.`}),b(!1),w(null),R(qj)}catch(F){console.error(F),T("HR letter could not be saved. Please try again.")}finally{_(!1)}},fe=V=>{if(!V)return"â";const $=new Date(`${V}T00:00:00`);return Number.isNaN($.getTime())?V:$.toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})},q=async(V,$)=>{if(!$)return!1;try{const F=await fetch($,{mode:"cors"});if(!F.ok)return!1;const P=await F.blob(),ue=await new Promise((ge,de)=>{const Pe=new FileReader;Pe.onload=()=>ge(String(Pe.result||"")),Pe.onerror=()=>
4150de(Pe.error),Pe.readAsDataURL(P)});if(P.type.includes("webp"))return!1;const me=P.type.includes("png")?"PNG":"JPEG";return V.addImage(ue,me,18,13,40,16,void 0,"FAST"),!0}catch(F){return console.warn("HR letter logo could not be embedded in PDF.",F),!1}},ne=async V=>{const $=s.find(nt=>nt.id===V.employeeId),F=n.find(nt=>nt.id===V.branchId),P=(c==null?void 0:c.name)||"Company",ue=(F==null?void 0:F.name)||V.branchName||"",me=(F==null?void 0:F.address)||(c==null?void 0:c.address)||"",ge=[F==null?void 0:F.phone,...((F==null?void 0:F.contacts)||[]).map(nt=>nt.phone),c==null?void 0:c.phone].filter(Boolean),de=Array.from(new Set(ge)).join(" · "),Pe=($==null?void 0:$.employeeId)||V.employeeCode||"â",Re=($==null?void 0:$.department)||V.employeeDepartment||"â",Ee=($==null?void 0:$.designation)||V.employeeDesignation||"â",Be=fe(($==null?void 0:$.joiningDate)||V.employeeJoiningDate),We=fe(V.effectiveDate),it=new Ra({orientation:"portrait",unit:"mm",format:"a4",compress:!0});it.setProperties({title:`${V.letterNo} - ${V.employeeName}`,subject:V.subject,author:P,creator:"VERIXO HR"});const _e=210,ee=297,qe=18,se=18,pe=_e-qe-se;let Se=18;await q(it,c==null?void 0:c.logoUrl),it.setTextColor(11,53,88),it.setFont("helvetica","bold"),it.setFontSize(16),it.text(P,_e-se,18,{align:"right"}),it.setTextColor(71,85,105),it.setFont("helvetica","normal"),it.setFontSize(8.5);let Me=23;ue&&(it.text(ue,_e-se,Me,{align:"right"}),Me+=4),me&&(it.text(me,_e-se,Me,{align:"right"}),Me+=4),de&&(it.text(de,_e-se,Me,{align:"right"}),Me+=4),c!=null&&c.email&&it.text(c.email,_e-se,Me,{align:"right"}),Se=Math.max(36,Me+4),it.setDrawColor(11,73,111),it.setLineWidth(.7),it.line(qe,Se,_e-se,Se),Se+=9,it.setTextColor(100,116,139),it.setFont("helvetica","bold"),it.setFontSize(7),it.text("LETTER NO",qe,Se),it.text("ISSUE DATE",_e-se,Se,{align:"right"}),it.setTextColor(15,23,42),it.setFontSize(9),it.text(V.letterNo,qe,Se+4),it.text(fe(V.issueDate),_e-se,Se+4,{align:"right"}),Se+=13,it.setFontSize(11),it.setFont("helvetica","bold"),it.text(V.employeeName,qe,Se),it.setFont("helvetica","normal"),it.setFontSize(9),it.text(Ee,qe,Se+4),ue&&it.text(ue,qe,Se+8),Se+=ue?14:10;const ot=[["EMPLOYEE ID",Pe],["DEPARTMENT",Re],["JOINING DATE",Be],["EFFECTIVE DATE",We]],wt=14,ct=pe/4;it.setDrawColor(71,85,105),it.setLineWidth(.55),it.roundedRect(qe,Se,pe,wt,2,2,"S"),ot.forEach(([nt,xt],te)=>{const Ge=qe+ct*te;te&&it.line(Ge,Se,Ge,Se+wt),it.setTextColor(100,116,139),it.setFont("helvetica","bold"),it.setFontSize(6.5),it.text(nt,Ge+3,Se+4.2),it.setTextColor(15,23,42),it.setFontSize(8);const pt=it.splitTextToSize(xt||"â",ct-6);it.text(pt.slice(0,2),Ge+3,Se+9)}),Se+=wt+9,it.setTextColor(15,23,42),it.setFont("helvetica","bold"),it.setFontSize(10);const Ce=it.splitTextToSize(`Subject: ${V.subject}`,pe);it.text(Ce,qe,Se),Se+=Ce.length*4.7+3,it.setDrawColor(226,232,240),it.line(qe,Se,_e-se,Se),Se+=7,it.setFont("helvetica","normal"),it.setFontSize(10),it.setTextColor(31,41,55);const De=V.body.split(/\n/),Te=52;for(const nt of De){if(!nt.trim()){Se+=5;continue}const xt=it.splitTextToSize(nt,pe),te=xt.length*5;Se+te>ee-Te&&(it.addPage("a4","portrait"),Se=20),it.text(xt,qe,Se),Se+=te+1.5}Se=Math.max(Se+14,210),Se>238&&(it.addPage("a4","portrait"),Se=205);const ce=128,Ye=_e-se;it.setDrawColor(71,85,105),it.line(ce,Se,Ye,Se),it.setFont("helvetica","bold"),it.setFontSize(8.5),it.setTextColor(15,23,42),it.text("Authorized Signatory",(ce+Ye)/2,Se+4,{align:"center"}),it.setFont("helvetica","normal"),it.setFontSize(7),it.setTextColor(100,116,139),it.text(`For ${P}`,(ce+Ye)/2,Se+8,{align:"center"});const Je=ee-13;it.setDrawColor(203,213,225),it.line(qe,Je-4,_e-se,Je-4),it.setFontSize(6.5),it.setTextColor(100,116,139),it.text(P,qe,Je);const le=[me,de].filter(Boolean).join(" · ");return le&&it.text(le,_e-se,Je,{align:"right"}),it},ae=async V=>{try{(await ne(V)).save(`${V.letterNo}.pdf`)}catch($){console.error($),T("PDF could not be generated. Please try again.")}},Y=async V=>{try{const $=await ne(V),F=URL.createObjectURL($.output("blob"));if(!window.open(F,"_blank")){URL.revokeObjectURL(F),T("Popup blocked. Please allow popups to preview the PDF.");return}setTimeout(()=>URL.revokeObjectURL(F),6e4)}catch($){console.error($),T("PDF preview could not be generated. Please try again.")}},je=async V=>{try{const $=await ne(V),F=URL.createObjectURL($.output("blob"));if(!window.open(F,"_blank")){URL.revokeObjectURL(F),T("Popup blocked. Please allow popups to open the A4 PDF for printing.");return}setTimeout(()=>URL.revokeObjectURL(F),6e4)}catch($){console.error($),T("PDF could not be opened for printing. Please try again.")}};return e.jsxs("section",{className:"hr-letters-page",children:[e.jsxs("header",{className:"hr-letters-head",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR DOCUMENTS"}),e.jsx("h1",{children:"HR Letters"}),e.jsx("p",{children:"Create, retain and generate fixed A4 PDF employee letters from a controlled HR register."})]}),G&&e.jsxs("button",{className:"vx-button vx-button-primary",onClick:K,children:[e.jsx(as,{size:16})," New Letter"]})]}),e.jsxs("section",{className:"hr-letter-summary",children:[e.jsxs("article",{children:[e.jsx(Zs,{size:20}),e.jsx("span",{children:"Total Letters"}),e.jsx("strong",{children:H.length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"This Month"}),e.jsx("strong",{children:H.filter(V=>{var $;return(($=V.issueDate)==null?void 0:$.slice(0,7))===HE().slice(0,7)}).length})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Employees Covered"}),e.jsx("strong",{children:new Set(H.map(V=>V.employeeId)).size})]})]}),e.jsxs("section",{className:"hr-letter-toolbar",children:[e.jsxs("label",{children:[e.jsx(xr,{size:17}),e.jsx("input",{value:u,onChange:V=>f(V.target.value),placeholder:"Search letter, employee, subject..."})]}),e.jsxs("select",{value:g,onChange:V=>p(V.target.value),children:[e.jsx("option",{value:"all",children:"All Letter Types"}
4150),Object.entries(Qv).map(([V,$])=>e.jsx("option",{value:V,children:$},V))]})]}),e.jsx("section",{className:"hr-letter-table-card",children:e.jsx("div",{className:"table-scroll",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Letter"}),e.jsx("th",{children:"Employee"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Subject"}),e.jsx("th",{children:"Issue Date"}),e.jsx("th",{children:"Action"})]})}),e.jsxs("tbody",{children:[H.map(V=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:V.letterNo}),e.jsx("small",{children:V.branchName||"â"})]}),e.jsxs("td",{children:[e.jsx("strong",{children:V.employeeName}),e.jsx("small",{children:V.employeeCode||"â"})]}),e.jsx("td",{children:e.jsx("span",{className:"hr-letter-type",children:Qv[V.type]})}),e.jsx("td",{children:V.subject}),e.jsx("td",{children:V.issueDate}),e.jsx("td",{children:e.jsxs("div",{className:"hr-letter-actions",children:[e.jsx("button",{onClick:()=>L(V),children:G?"Open / Edit":"View"}),e.jsxs("button",{onClick:()=>Y(V),children:[e.jsx(ui,{size:15})," Preview"]}),e.jsxs("button",{onClick:()=>ae(V),children:[e.jsx(Mi,{size:15})," PDF"]}),e.jsxs("button",{onClick:()=>je(V),children:[e.jsx(Wi,{size:15})," Print PDF"]})]})})]},V.id)),!H.length&&e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-table",children:"No HR letter found."})})]})]})})}),y&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>b(!1),children:e.jsxs("form",{className:"modal hr-letter-modal",onSubmit:Z,onMouseDown:V=>V.stopPropagation(),children:[e.jsxs("div",{className:"hr-letter-modal-head",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:N?N.letterNo:"NEW HR LETTER"}),e.jsx("h2",{children:N?"Letter Details":"Create HR Letter"})]}),e.jsx("button",{type:"button",className:"icon-button",onClick:()=>b(!1),children:e.jsx(ja,{size:18})})]}),e.jsxs("div",{className:"hr-letter-form-grid",children:[e.jsxs("label",{children:["Letter Type",e.jsx("select",{disabled:!G,value:C.type,onChange:V=>D(V.target.value),children:Object.entries(Qv).map(([V,$])=>e.jsx("option",{value:V,children:$},V))})]}),e.jsxs("label",{children:["Employee",e.jsxs("select",{disabled:!G||!!N,value:C.employeeId,onChange:V=>M(V.target.value),children:[e.jsx("option",{value:"",children:"Select Employee"}),z.map(V=>e.jsxs("option",{value:V.id,children:[V.employeeId?`${V.employeeId} · `:"",V.name]},V.id))]})]}),e.jsxs("label",{children:["Issue Date",e.jsx("input",{disabled:!G,type:"date",value:C.issueDate,onChange:V=>R({...C,issueDate:V.target.value})})]}),e.jsxs("label",{children:["Effective Date ",e.jsx("span",{className:"optional",children:"Optional"}),e.jsx("input",{disabled:!G,type:"date",value:C.effectiveDate,onChange:V=>R({...C,effectiveDate:V.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Subject",e.jsx("input",{disabled:!G,value:C.subject,onChange:V=>R({...C,subject:V.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Letter Body",e.jsx("textarea",{disabled:!G,rows:14,value:C.body,onChange:V=>R({...C,body:V.target.value})})]})]}),J&&e.jsx("div",{className:"hr-letter-message",children:J}),e.jsxs("div",{className:"hr-letter-modal-actions",children:[e.jsx("button",{type:"button",className:"vx-button",onClick:()=>b(!1),children:"Close"}),G&&e.jsx("button",{type:"submit",className:"vx-button vx-button-primary",disabled:I,children:I?"Saving...":N?"Save Changes":"Create Letter"})]})]})})]})}const Vj={enabled:!1,minimumServiceYears:5,daysPerYear:30,salaryBasis:"basic"};function OU(t,n){if(!t)return 0;const a=new Date(`${t}T00:00:00`),s=n?new Date(`${n}T00:00:00`):new Date;if(Number.isNaN(a.getTime())||Number.isNaN(s.getTime())||s<a)return 0;let i=s.getFullYear()-a.getFullYear();const c=new Date(s.getFullYear(),a.getMonth(),a.getDate());return s<c&&(i-=1),Math.max(0,i)}async function LU(t,n=Date.now()){const a=new Date(n).getFullYear(),s=`GR-PAY-${a}`,i=re(ie,`documentCounters/${t}/${s}`),c=await Ep(i,l=>({lastNumber:Number((l==null?void 0:l.lastNumber)||0)+1,documentCode:"GR-PAY",year:a,updatedAt:n}));if(!c.committed||!c.snapshot.exists())throw new Error("Gratuity payment number could not be generated.");return`GR-PAY-${a}-${String(Number(c.snapshot.val().lastNumber||0)).padStart(6,"0")}`}function BU({profile:t,branches:n,selectedBranchId:a}){const[s,i]=x.useState([]),[c,l]=x.useState({}
4150),[m,d]=x.useState(Vj),[u,f]=x.useState(""),[g,p]=x.useState(!1),[y,b]=x.useState(Vj),[N,w]=x.useState(!1),[C,R]=x.useState(""),[I,_]=x.useState([]),[J,T]=x.useState(!1),[G,z]=x.useState(""),[H,K]=x.useState(new Date().toISOString().slice(0,10)),[L,D]=x.useState(0),[M,Z]=x.useState("Final Settlement"),[fe,q]=x.useState(""),[ne,ae]=x.useState([]),[Y,je]=x.useState(!1),[V,$]=x.useState(""),[F,P]=x.useState(0),[ue,me]=x.useState("cash"),[ge,de]=x.useState(new Date().toISOString().slice(0,10)),[Pe,Re]=x.useState(""),[Ee,Be]=x.useState(""),We=sa(t,"employee.manage");x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),te=>{if(!te.exists())return i([]);const Ge=te.val();i(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`salaryStructures/${t.companyId}`),te=>{l(te.exists()?te.val():{})}),[t.companyId]),x.useEffect(()=>qt(re(ie,`gratuitySettings/${t.companyId}`),te=>{const Ge={...Vj,...te.exists()?te.val():{}};d(Ge),b(Ge)}),[t.companyId]),x.useEffect(()=>qt(re(ie,`gratuitySettlements/${t.companyId}`),te=>{if(!te.exists())return _([]);const Ge=te.val();_(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})).sort((pt,$e)=>$e.createdAt-pt.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`gratuityPayments/${t.companyId}`),te=>{if(!te.exists())return ae([]);const Ge=te.val();ae(Object.entries(Ge).map(([pt,$e])=>({id:pt,...$e})).sort((pt,$e)=>$e.createdAt-pt.createdAt))}),[t.companyId]);const it=async()=>{if(!We||N)return;const te=Math.max(0,Math.floor(Number(y.minimumServiceYears||0))),Ge=Math.max(1,Math.min(365,Number(y.daysPerYear||0)));w(!0),R("");try{await Pn(re(ie,`gratuitySettings/${t.companyId}`),{enabled:!!y.enabled,minimumServiceYears:te,daysPerYear:Ge,salaryBasis:y.salaryBasis==="gross"?"gross":"basic",updatedAt:Date.now(),updatedByUid:t.uid,updatedByName:t.name||t.email||"User"}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"gratuity.policy_updated",entityType:"gratuity",entityId:t.companyId,summary:`Gratuity policy ${y.enabled?"enabled/updated":"disabled"}.`,metadata:{enabled:!!y.enabled,minimumServiceYears:te,daysPerYear:Ge,salaryBasis:y.salaryBasis}}),R("Gratuity policy saved successfully."),p(!1)}catch(pt){console.error(pt),R("Gratuity policy could not be saved.")}finally{w(!1)}},_e=x.useMemo(()=>{const te=u.trim().toLowerCase();return s.filter(Ge=>a==="all"||Ge.branchId===a).filter(Ge=>!te||[Ge.name,Ge.employeeId,Ge.department,Ge.designation].filter(Boolean).join(" ").toLowerCase().includes(te)).map(Ge=>{const pt=OU(Ge.joiningDate,Ge.lastWorkingDate),$e=c[Ge.id]||{},st=m.salaryBasis==="gross"?Number($e.grossSalary||0):Number($e.basicSalary||0),Nt=!!Ge.joiningDate&&pt>=m.minimumServiceYears,be=Nt&&st>0?st/30*m.daysPerYear*pt:0;return{employee:Ge,years:pt,salary:st,eligible:Nt,estimate:be}}).sort((Ge,pt)=>(Ge.employee.employeeId||"").localeCompare(pt.employee.employeeId||"",void 0,{numeric:!0}))},[s,c,a,u,m]),ee=_e.filter(te=>te.eligible).length,qe=_e.reduce((te,Ge)=>te+Ge.estimate,0),se=_e.find(te=>
4150te.employee.id===G),pe=(se==null?void 0:se.estimate)||0,Se=Math.max(0,pe+Number(L||0)),Me=new Set(I.filter(te=>te.status==="approved").map(te=>te.employeeId)),ot=te=>ne.filter(Ge=>Ge.settlementId===te).reduce((Ge,pt)=>Ge+Number(pt.amount||0),0),wt=I.find(te=>te.id===V),ct=wt?ot(wt.id):0,Ce=wt?Math.max(0,wt.approvedAmount-ct):0,De=I.filter(te=>te.status==="approved").reduce((te,Ge)=>te+Ge.approvedAmount,0),Te=ne.reduce((te,Ge)=>te+Number(Ge.amount||0),0),ce=Math.max(0,De-Te),Ye=async()=>{if(!(!We||N||!m.enabled||!(se!=null&&se.eligible)||pe<=0)){w(!0),R("");try{const te=Ta(re(ie,`gratuitySettlements/${t.companyId}`)),Ge=Date.now(),pt={employeeId:se.employee.id,employeeName:se.employee.name,employeeCode:se.employee.employeeId||"",branchId:se.employee.branchId||"",joiningDate:se.employee.joiningDate||"",completedServiceYears:se.years,salaryBasis:m.salaryBasis,salaryAmount:se.salary,calculatedAmount:pe,adjustmentAmount:Number(L||0),approvedAmount:Se,settlementDate:H,reason:M.trim()||"Final Settlement",notes:fe.trim(),status:"draft",createdAt:Ge,createdByUid:t.uid,createdByName:t.name||t.email||"User"};await Pn(te,pt),await ia({companyId:t.companyId,actorUid:t.uid,actorName:pt.createdByName,action:"gratuity.settlement_created",entityType:"gratuity",entityId:te.key||se.employee.id,summary:`Gratuity settlement draft created for ${pt.employeeName}.`,metadata:{calculatedAmount:pt.calculatedAmount,adjustmentAmount:pt.adjustmentAmount,approvedAmount:pt.approvedAmount}}),T(!1),z(""),D(0),q(""),R("Gratuity settlement draft created.")}catch(te){console.error(te),R("Gratuity settlement could not be created.")}finally{w(!1)}}},Je=async te=>{if(!(!We||N||te.status!=="draft")){w(!0),R("");try{const Ge=Date.now(),{id:pt,...$e}=te;await Pn(re(ie,`gratuitySettlements/${t.companyId}/${te.id}`),{...$e,status:"approved",approvedAt:Ge,approvedByUid:t.uid,approvedByName:t.name||t.email||"User"}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"gratuity.settlement_approved",entityType:"gratuity",entityId:te.id,summary:`Gratuity settlement approved for ${te.employeeName}.`,metadata:{approvedAmount:te.approvedAmount}}),R("Gratuity settlement approved. No Finance/Accounts posting has been made.")}catch(Ge){console.error(Ge),R("Settlement approval failed.")}finally{w(!1)}}},le=te=>{const Ge=ot(te.id),pt=Math.max(0,te.approvedAmount-Ge);$(te.id),P(pt),me("cash"),de(new Date().toISOString().slice(0,10)),Re(""),Be(""),je(!0)},nt=async()=>{if(!We||N||!wt||wt.status!=="approved")return;const te=Number(F||0);if(te<=0||te>Ce+1e-4){R("Payment amount must be greater than zero and cannot exceed the remaining payable.");return}w(!0),R("");try{const Ge=Date.now(),pt=await LU(t.companyId,Ge),$e=Ta(re(ie,`gratuityPayments/${t.companyId}`)),st={paymentNo:pt,settlementId:wt.id,employeeId:wt.employeeId,employeeName:wt.employeeName,branchId:wt.branchId||"",amount:te,method:ue,paymentDate:ge,reference:Pe.trim(),notes:Ee.trim(),createdAt:Ge,createdByUid:t.uid,createdByName:t.name||t.email||"User"};await Pn($e,st),await ia({companyId:t.companyId,actorUid:t.uid,actorName:st.createdByName,action:"gratuity.payment_recorded",entityType:"gratuity",entityId:$e.key||wt.id,summary:`Gratuity payment ${pt} recorded for ${st.employeeName}.`,metadata:{settlementId:st.settlementId,amount:st.amount,method:st.method,paymentDate:st.paymentDate}}),je(!1),R("Gratuity payment recorded successfully.")}catch(Ge){console.error(Ge),R("Gratuity payment could not be recorded.")}finally{w(!1)}},xt=te=>{var Ge;return((Ge=n.find(pt=>pt.id===te))==null?void 0:Ge.name)||"â"};return e.jsxs("section",{className:"gratuity-page",children:[e.jsxs("div",{className:"gratuity-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"HR BENEFITS"}),e.jsx("h1",{children:"Gratuity"}),e.jsx("p",{children:"Company-optional gratuity eligibility and liability foundation using employee service and payroll salary structure."})]}),e.jsxs("div",{className:"gratuity-head-actions",children:[e.jsx("div",{className:`gratuity-status ${m.enabled?"enabled":"disabled"}`,children:m.enabled?"Enabled":"Not Enabled"}),We&&e.jsxs("button",{className:"gratuity-settings-btn",onClick:()=>{b(m),p(!0)},children:[e.jsx(vu,{size:16})," Policy Settings"]}),We&&m.enabled&&e.jsxs("button",{className:"gratuity-settings-btn secondary",onClick:()=>T(!0),children:[e.jsx(as,{size:16})," New Settlement"]})]})]}),C&&e.jsx("div",{className:"gratuity-message",children:C}),!m.enabled&&e.jsxs("div",{className:"gratuity-notice",children:[e.jsx("strong",{children:"Gratuity is currently optional and disabled for this company."}),e.jsx("span",{children:"The foundation is installed without changing payroll. Policy setup and settlement posting will be added in the next controlled update."})]}),e.jsxs("div",{className:"gratuity-summary",children:[e.jsxs("article",{children:[e.jsx(mc,{size:20}),e.jsx("span",{children:"Employees"}),e.jsx("strong",{children:_e.length})]}),e.jsxs("article",{children:[e.jsx(v1,{size:20}),e.jsx("span",{children:"Eligible by current policy"}),e.jsx("strong",{children:m.enabled?ee:0})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Estimated Liability"}
4150),e.jsx("strong",{children:m.enabled?qe.toLocaleString(void 0,{maximumFractionDigits:2}):"â"})]})]})," ",e.jsxs("div",{className:"gratuity-summary gratuity-finance-summary",children:[e.jsxs("article",{children:[e.jsx("span",{children:"Approved Payable"}),e.jsx("strong",{children:De.toLocaleString(void 0,{maximumFractionDigits:2})})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Paid"}),e.jsx("strong",{children:Te.toLocaleString(void 0,{maximumFractionDigits:2})})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Outstanding"}),e.jsx("strong",{children:ce.toLocaleString(void 0,{maximumFractionDigits:2})})]})]}),e.jsxs("div",{className:"gratuity-policy",children:[e.jsxs("div",{children:[e.jsx("small",{children:"Minimum Service"}),e.jsxs("strong",{children:[m.minimumServiceYears," completed year(s)"]})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Benefit Rate"}),e.jsxs("strong",{children:[m.daysPerYear," day(s) per completed year"]})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Salary Basis"}),e.jsx("strong",{children:m.salaryBasis==="gross"?"Gross Salary":"Basic Salary"})]}),e.jsxs("div",{children:[e.jsx("small",{children:"Management"}),e.jsx("strong",{children:We?"HR/Admin":"View only"})]})]}),e.jsx("div",{className:"gratuity-toolbar",children:e.jsxs("label",{children:[e.jsx(xr,{size:17}),e.jsx("input",{value:u,onChange:te=>f(te.target.value),placeholder:"Search employee, ID, department..."})]})}),e.jsx("div",{className:"gratuity-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"BRANCH"}),e.jsx("th",{children:"JOINING DATE"}),e.jsx("th",{children:"SERVICE"}),e.jsx("th",{children:"SALARY BASIS"}),e.jsx("th",{children:"ELIGIBILITY"}),e.jsx("th",{children:"ESTIMATE"})]})}),e.jsx("tbody",{children:_e.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"empty",children:"No employee found."})}):_e.map(({employee:te,years:Ge,salary:pt,eligible:$e,estimate:st})=>e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:te.name}),e.jsxs("small",{children:[te.employeeId||"â"," · ",te.designation||"â"]})]}),e.jsx("td",{children:xt(te.branchId)}),e.jsx("td",{children:te.joiningDate||"â"}),e.jsxs("td",{children:[Ge," year(s)"]}),e.jsx("td",{children:pt?pt.toLocaleString():"â"}),e.jsx("td",{children:e.jsx("span",{className:$e?"eligible":"not-eligible",children:m.enabled?$e?"Eligible":"Not Eligible":"Policy Disabled"})}),e.jsx("td",{children:m.enabled&&st?st.toLocaleString(void 0,{maximumFractionDigits:2}):"â"})]},te.id))})]})}),e.jsxs("div",{className:"gratuity-settlement-section",children:[e.jsxs("div",{className:"gratuity-section-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"SETTLEMENT REGISTER"}),e.jsx("h2",{children:"Gratuity Settlements"})]}),e.jsx("small",{children:"Approved settlements become Gratuity Payable here. Payments can be recorded and outstanding balances are tracked."})]}),e.jsx("div",{className:"gratuity-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"CALCULATED"}),e.jsx("th",{children:"ADJUSTMENT"}),e.jsx("th",{children:"APPROVED AMOUNT"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:I.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"empty",children:"No gratuity settlement found."})}):I.map(te=>{const Ge=ot(te.id),pt=Math.max(0,te.approvedAmount-Ge),$e=te.status!=="approved"?"Draft":pt<=0?"Paid":Ge>0?"Partially Paid":"Payable";return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:te.employeeName}),e.jsxs("small",{children:[te.employeeCode||"â"," · ",te.completedServiceYears," year(s)"]})]}),e.jsx("td",{children:te.settlementDate}),e.jsx("td",{children:te.calculatedAmount.toLocaleString()}),e.jsx("td",{children:te.adjustmentAmount.toLocaleString()}),e.jsxs("td",{children:[e.jsx("strong",{children:te.approvedAmount.toLocaleString()}
4150),e.jsxs("small",{children:["Paid ",Ge.toLocaleString()," · Due ",pt.toLocaleString()]})]}),e.jsx("td",{children:e.jsx("span",{className:pt<=0&&te.status==="approved"?"eligible":"not-eligible",children:$e})}),e.jsx("td",{children:te.status==="draft"&&We?e.jsxs("button",{className:"gratuity-inline-btn",disabled:N,onClick:()=>Je(te),children:[e.jsx(Ms,{size:15})," Approve"]}):te.status==="approved"&&pt>0&&We?e.jsxs("button",{className:"gratuity-inline-btn",disabled:N,onClick:()=>le(te),children:[e.jsx(F4,{size:15})," Record Payment"]}):"â"})]},te.id)})})]})})]}),e.jsxs("div",{className:"gratuity-settlement-section",children:[e.jsxs("div",{className:"gratuity-section-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"PAYMENT REGISTER"}),e.jsx("h2",{children:"Gratuity Payments"})]}),e.jsx("small",{children:"Payment records reduce the outstanding Gratuity Payable. They do not alter Payroll salary runs."})]}),e.jsx("div",{className:"gratuity-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"PAYMENT NO"}),e.jsx("th",{children:"EMPLOYEE"}),e.jsx("th",{children:"DATE"}),e.jsx("th",{children:"METHOD"}),e.jsx("th",{children:"REFERENCE"}),e.jsx("th",{children:"AMOUNT"})]})}),e.jsx("tbody",{children:ne.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty",children:"No gratuity payment found."})}):ne.map(te=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:te.paymentNo})}),e.jsx("td",{children:te.employeeName}),e.jsx("td",{children:te.paymentDate}),e.jsx("td",{children:te.method.replaceAll("_"," ").replace(/\b\w/g,Ge=>Ge.toUpperCase())}),e.jsx("td",{children:te.reference||"â"}),e.jsx("td",{children:e.jsx("strong",{children:te.amount.toLocaleString()})})]},te.id))})]})})]}),Y&&wt&&e.jsx("div",{className:"gratuity-modal-backdrop",onMouseDown:te=>{te.currentTarget===te.target&&je(!1)},children:e.jsxs("div",{className:"gratuity-modal",children:[e.jsxs("div",{className:"gratuity-modal-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"GRATUITY PAYMENT"}),e.jsx("h2",{children:"Record Payment"})]}),e.jsx("button",{onClick:()=>je(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"gratuity-payment-context",children:[e.jsx("strong",{children:wt.employeeName}),e.jsxs("span",{children:["Approved ",wt.approvedAmount.toLocaleString()," · Paid ",ct.toLocaleString()," · Remaining ",Ce.toLocaleString()]})]}),e.jsxs("div",{className:"gratuity-form-grid settlement",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Payment Amount"}),e.jsx("input",{type:"number",min:"0.01",max:Ce,step:"0.01",value:F,onChange:te=>P(Number(te.target.value))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Payment Date"}),e.jsx("input",{type:"date",value:ge,onChange:te=>de(te.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Method"}),e.jsxs("select",{value:ue,onChange:te=>me(te.target.value),children:[e.jsx("option",{value:"cash",children:"Cash"}),e.jsx("option",{value:"bkash",children:"bKash"}),e.jsx("option",{value:"nagad",children:"Nagad"}),e.jsx("option",{value:"card",children:"Card"}),e.jsx("option",{value:"bank_transfer",children:"Bank Transfer"}),e.jsx("option",{value:"cheque",children:"Cheque"})]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Reference"}),e.jsx("input",{value:Pe,onChange:te=>Re(te.target.value),placeholder:"Txn / cheque / bank reference"})]})]}),e.jsxs("label",{className:"gratuity-notes",children:[e.jsx("span",{children:"Notes"}),e.jsx("textarea",{value:Ee,onChange:te=>Be(te.target.value),rows:3})]}),e.jsx("div",{className:"gratuity-policy-note",children:"This records settlement payment and reduces the Gratuity Payable balance. The current VERIXO Accounts module does not yet contain a general Cash/Bank ledger, so no artificial ledger entry is created here."}),e.jsxs("div",{className:"gratuity-modal-actions",children:[e.jsx("button",{onClick:()=>je(!1),children:"Cancel"}),e.jsxs("button",{className:"primary",disabled:N||F<=0||F>Ce,onClick:nt,children:[e.jsx(hr,{size:16}),N?"Saving...":"Record Payment"]})]})]})}),J&&e.jsx("div",{className:"gratuity-modal-backdrop",onMouseDown:te=>{te.currentTarget===te.target&&T(!1)},children:e.jsxs("div",{className:"gratuity-modal",children:[e.jsxs("div",{className:"gratuity-modal-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"GRATUITY SETTLEMENT"}),e.jsx("h2",{children:"Create Settlement Draft"})]}),e.jsx("button",{onClick:()=>T(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"gratuity-form-grid settlement",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Eligible Employee"}),e.jsxs("select",{value:G,onChange:te=>z(te.target.value),children:[e.jsx("option",{value:"",children:"Select Employee"}),_e.filter(te=>te.eligible&&te.salary>0&&!Me.has(te.employee.id)).map(te=>e.jsxs("option",{value:te.employee.id,children:[te.employee.employeeId||"â"," · ",te.employee.name]},te.employee.id))]})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Settlement Date"}),e.jsx("input",{type:"date",value:H,onChange:te=>K(te.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Reason"}),e.jsx("input",{value:M,onChange:te=>Z(te.target.value)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Calculated Amount"}),e.jsx("input",{readOnly:!0,value:pe.toFixed(2)})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Adjustment (+/-)"}),e.jsx("input",{type:"number",step:"0.01",value:L,onChange:te=>D(Number(te.target.value))})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Settlement Amount"}),e.jsx("input",{readOnly:!0,value:Se.toFixed(2)})]})]}),e.jsxs("label",{className:"gratuity-notes",children:[e.jsx("span",{children:"Notes"}),e.jsx("textarea",{value:fe,onChange:te=>q(te.target.value),rows:3})]}),e.jsx("div",{className:"gratuity-policy-note",children:"Creating or approving this settlement does not create a Payroll, Finance or Accounts transaction yet. This keeps the existing stable accounting flow isolated."}),e.jsxs("div",{className:"gratuity-modal-actions",children:[e.jsx("button",{onClick:()=>T(!1),children:"Cancel"}),e.jsxs("button",{className:"primary",disabled:N||!(se!=null&&se.eligible)||pe<=0,onClick:Ye,children:[e.jsx(hr,{size:16}),N?"Saving...":"Create Draft"]})]})]})}),g&&e.jsx("div",{className:"gratuity-modal-backdrop",onMouseDown:te=>{te.currentTarget===te.target&&p(!1)},children:e.jsxs("div",{className:"gratuity-modal",children:[e.jsxs("div",{className:"gratuity-modal-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"COMPANY POLICY"}),e.jsx("h2",{children:"Gratuity Policy Settings"})]}),e.jsx("button",{onClick:()=>p(!1),children:e.jsx(ja,{size:20})})]}),e.jsxs("label",{className:"gratuity-toggle",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Enable Gratuity"}),e.jsx("small",{children:"When disabled, no employee is treated as eligible and no liability is calculated."})]}),e.jsx("input",{type:"checkbox",checked:y.enabled,onChange:te=>b({...y,enabled:te.target.checked})})]}),e.jsxs("div",{className:"gratuity-form-grid",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Minimum Completed Service (Years)"}),e.jsx("input",{type:"number",min:"0",step:"1",value:y.minimumServiceYears,onChange:te=>b({...y,minimumServiceYears:Number(te.target.value)})})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Benefit Rate (Days per Completed Year)"}),e.jsx("input",{type:"number",min:"1",max:"365",step:"1",value:y.daysPerYear,onChange:te=>b({...y,daysPerYear:Number(te.target.value)})})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Salary Basis"}),e.jsxs("select",{value:y.salaryBasis,onChange:te=>b({...y,salaryBasis:te.target.value}),children:[e.jsx("option",{value:"basic",children:"Basic Salary"}),e.jsx("option",{value:"gross",children:"Gross Salary"})]})]})]}),e.jsx("div",{className:"gratuity-policy-note",children:"Policy changes affect the eligibility/liability estimate shown here. This update does not post any gratuity amount to Payroll, Finance or Accounts."}),e.jsxs("div",{className:"gratuity-modal-actions",children:[e.jsx("button",{onClick:()=>p(!1),children:"Cancel"}),e.jsxs("button",{className:"primary",disabled:N,onClick:it,children:[e.jsx(hr,{size:16}),N?"Saving...":"Save Policy"]})]})]})})]})}const Of={applied:"Applied",shortlisted:"Shortlisted",interview:"Interview",selected:"Selected",rejected:"Rejected"},Hj={applied:["shortlisted","rejected"],shortlisted:["interview","rejected"],interview:["selected","rejected"],selected:[],rejected:[]};function FU({profile:t,branches:n,selectedBranchId:a}){const s=sa(t,"employee.manage"),[i,c]=x.useState([]),[l,m]=x.useState([]),[d,u]=x.useState([]),[f,g]=x.use
4150State({}),[p,y]=x.useState(!1),[b,N]=x.useState(""),[w,C]=x.useState(""),[R,I]=x.useState(new Date().toISOString().slice(0,10)),[_,J]=x.useState(""),[T,G]=x.useState(""),[z,H]=x.useState(""),[K,L]=x.useState("sales"),[D,M]=x.useState("permanent"),[Z,fe]=x.useState(0),[q,ne]=x.useState(0),[ae,Y]=x.useState(""),[je,V]=x.useState(""),[$,F]=x.useState(""),[P,ue]=x.useState(""),[me,ge]=x.useState(!1),[de,Pe]=x.useState(""),[Re,Ee]=x.useState(0),[Be,We]=x.useState(0),[it,_e]=x.useState(""),[ee,qe]=x.useState(""),[se,pe]=x.useState(""),[Se,Me]=x.useState(!1),[ot,wt]=x.useState(""),[ct,Ce]=x.useState(""),[De,Te]=x.useState(""),[ce,Ye]=x.useState(!1),[Je,le]=x.useState(!1),[nt,xt]=x.useState(""),[te,Ge]=x.useState(!1),[pt,$e]=x.useState(""),[st,Nt]=x.useState(""),[be,jt]=x.useState(""),[bt,tn]=x.useState(a==="all"?"":a),[B,xe]=x.useState(1),[tt,ht]=x.useState(""),[dt,we]=x.useState(""),[rt,St]=x.useState(""),[Qt,gn]=x.useState(""),[An,Sn]=x.useState(""),[Xt,Wt]=x.useState(""),[Gt,$t]=x.useState(""),[Vt,sn]=x.useState(""),[on,ke]=x.useState(""),[Ct,Et]=x.useState(""),[Rt,xn]=x.useState(""),[dn,Ln]=x.useState(0),[wa,Ca]=x.useState(""),[In,Sa]=x.useState(""),[aa,$a]=x.useState(""),[jn,vs]=x.useState(""),[ka,Ja]=x.useState("in_person"),[_n,ha]=x.useState(""),[ta,W]=x.useState("");x.useEffect(()=>qt(re(ie,`recruitmentVacancies/${t.companyId}`),Xe=>{if(!Xe.exists())return c([]);c(Object.entries(Xe.val()).map(([Jt,Ht])=>({id:Jt,...Ht})).sort((Jt,Ht)=>Ht.createdAt-Jt.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`recruitmentCandidates/${t.companyId}`),Xe=>{if(!Xe.exists())return m([]);m(Object.entries(Xe.val()).map(([Jt,Ht])=>({id:Jt,...Ht})).sort((Jt,Ht)=>Ht.createdAt-Jt.createdAt))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`employees/${t.companyId}`),Xe=>{if(!Xe.exists())return u([]);u(Object.entries(Xe.val()).map(([Jt,Ht])=>({id:Jt,...Ht})))}),[t.companyId]),x.useEffect(()=>qt(re(ie,`salaryStructures/${t.companyId}`),Xe=>{g(Xe.exists()?Xe.val():{})}),[t.companyId]);const ft=x.useMemo(()=>i.filter(Xe=>a==="all"||!a||Xe.branchId===a),[i,a]),Zt=x.useMemo(()=>l.filter(Xe=>{const Jt=i.find(is=>is.id===Xe.vacancyId),Ht=a==="all"||!a||(Jt==null?void 0:Jt.branchId)===a,xa=!se||Xe.vacancyId===se,ra=ee.trim().toLowerCase(),Ha=`${Xe.name} ${Xe.phone} ${Xe.email||""} ${(Jt==null?void 0:Jt.title)||""}`.toLowerCase();return Ht&&xa&&(!ra||Ha.includes(ra))}),[l,i,a,se,ee]),vt=ft.filter(Xe=>Xe.status==="open").length,Ae=Zt.filter(Xe=>Xe.status==="interview").length,oe=Zt.filter(Xe=>Xe.status==="selected").length,Ve=Xe=>{var Jt;return((Jt=n.find(Ht=>Ht.id===Xe))==null?void 0:Jt.name)||"All / Unassigned"},he=Xe=>l.filter(Jt=>Jt.vacancyId===Xe&&!!Jt.hiredEmployeeId).length,Oe=Xe=>Math.max(0,Number(Xe.openings||0)-he(Xe.id)),ut=Xe=>{const Jt=`${(Xe==null?void 0:Xe.department)||""} ${(Xe==null?void 0:Xe.title)||""}`.toLowerCase();return Jt.includes("technician")||Jt.includes("service")||Jt.includes("technical")?"technician":Jt.includes("account")||Jt.includes("finance")?"accounts":Jt.includes("hr")||Jt.includes("human resource")?"hr":Jt.includes("store")||Jt.includes("inventory")?"store":Jt.includes("delivery")?"delivery":Jt.includes("manager")||Jt.includes("management")?"manager":Jt.includes("admin")?"admin":"sales"},At=Xe=>{var xa;if(Xe.hiredEmployeeId){$e(`${Xe.name} has already been converted to an employee.`);return}const Jt=i.find(ra=>ra.id===Xe.vacancyId);if(!Jt||Jt.status!=="open"){$e("Hiring is blocked because this vacancy is closed.");return}if(Oe(Jt)<=0){$e(`Hiring is blocked because all ${Jt.openings} opening(s) are already filled.`);return}N(Xe.id),C(""),V(Xe.phone||""),F(Xe.email||""),ue(""),I(new Date().toISOString().slice(0,10)),J((Jt==null?void 0:Jt.branchId)||t.branchId||((xa=n.find(ra=>ra.active))==null?void 0:xa.id)||""),G((Jt==null?void 0:Jt.department)||""),H((Jt==null?void 0:Jt.title)||Xe.currentDesignation||""),L(ut(Jt)),M("permanent");const Ht=Math.max(0,Number(Xe.expectedSalary||0));fe(Ht),ne(Ht),Y(`Recruited from VERIXO Recruitment${Xe.source?` · Source: ${Xe.source}`:""}`),y(!0)},en=async()=>{const Xe=l.find(Wa=>Wa.id===b),Jt=Xe?i.find(Wa=>Wa.id===Xe.vacancyId):void 0;if(!Xe||!s||te)return;if(!Jt||Jt.status!=="open"){ue("Hiring is blocked because the vacancy is closed.");return}const Ht=he(Jt.id);if(Ht>=Jt.openings){ue(`Hiring is blocked: ${Ht}/${Jt.openings} opening(s) are already filled.`);return}const xa=w.trim(),ra=je.trim(),Ha=$.trim().toLowerCase();if(ue(""),!xa||!R||!_||!T.trim()||!z.trim()||!ra){ue("Employee ID, Joining Date, Branch, Department, Designation and Phone are required.");return}if(Xe.hiredEmployeeId){ue("This candidate has already been converted to an employee.");return}const is=d.find(Wa=>(Wa.employeeId||"").trim().toLowerCase()===xa.toLowerCase()),hs=d.find(Wa=>ra&&(Wa.phone||"").trim()===ra),rs=d.find(Wa=>Ha&&(Wa.email||"").trim().toLowerCase()===Ha),oa=is||hs||rs;if(oa){ue(`${is?"Employee ID":hs?"Phone":"Email"} ${is?xa:hs?ra:Ha} is already used by ${oa.name} (${oa.employeeId||"ID not assigned"}). Please correct it before creating the employee.`);return}const qa=Math.max(0,Number(Z||0)),bs=Math.max(0,Number(q||0));if(bs>qa){ue("Basic Salary cannot be greater than Gross Salary.");return}Ge(!0),$e("");try{const Wa=Date.now(),jr=Ta(re(ie,`employees/${t.companyId}`)).key||"";if(!jr)throw new Error("Employee key could not be generated.");const Kr={id:jr,companyId:t.companyId,branchId:_,employeeId:xa,name:Xe.name.trim(),phone:ra,email:$.trim(),department:T.trim(),designation:z.trim(),roles:[K],technicianSkills:[],joiningDate:R,employmentStatus:"probation",probationEndDate:"",confirmationDate:"",lastWorkingDate:"",exitReason:"",exitNotes:"",confirmationRemarks:"",onboardingChecklist:{documentsReceived:!1,identityDocument:!1,appointmentLetter:!1,bankInformation:!1,reportingManager:!1,attendanceEnrolled:!1,userAccount:!1},offboardingChecklist:{handoverCompleted:!1,companyAssetsReturned:!1,accountsClearance:!1,attendancePayrollClearance:!1,userAccessDisabled:!1},documents:[],reportingManagerId:"",reportingManagerName:"",reportingManagerUserUid:"",reportingManagerUserRole:"",bankName:"",bankAccount:"",bankAccountHolder:Xe.name.trim(),shiftId:"",shiftEffectiveFrom:R,notes:ae.trim(),employmentType:D,recruitmentCandidateId:Xe.id,active:!0,createdAt:Wa,updatedAt:Wa,lifecycleUpdatedAt:Wa,lifecycleUpdatedByUid:t.uid,lifecycleUpdatedByName:t.name||t.email||"User"},Xr={[`employees/${t.companyId}/${jr}`]:Kr,[`recruitmentCandidates/${t.companyId}/${Xe.id}/status`]:"selected",[`recruitmentCandidates/${t.companyId}/${Xe.id}/selectedAt`]:Wa,[`recruitmentCandidates/${t.companyId}/${Xe.id}/selectedByUid`]:t.uid,[`recruitmentCandidates/${t.companyId}/${Xe.id}/selectedByName`]:t.name||t.email||"User",[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiredEmployeeId`]:jr,[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiredEmployeeCode`]:xa,[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiredAt`]:Wa,[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot`]:{employeeCode:xa,joiningDate:R,branchId:_,department:T.trim(),designation:z.trim(),role:K,employmentType:D,grossSalary:qa,basicSalary:bs,vacancyId:Xe.vacancyId,vacancyTitle:(Jt==null?void 0:Jt.title)||""}};if((qa>0||bs>0)&&(Xr[`salaryStructures/${t.companyId}/${jr}`]=It(jr,qa,bs,Xe.name.trim(),Wa)),Ht+1>=Jt.openings&&(Xr[`recruitmentVacancies/${t.companyId}/${Jt.id}/status`]="closed",Xr[`recruitmentVacancies/${t.companyId}/${Jt.id}/closedAt`]=Wa,Xr[`recruitmentVacancies/${t.companyId}/${Jt.id}/closedByUid`]=t.uid,Xr[`recruitmentVacancies/${t.companyId}/${Jt.id}/closedByName`]=t.name||t.email||"User",Xr[`recruitmentVacancies/${t.companyId}/${Jt.id}/updatedAt`]=Wa),await yn(re(ie),Xr),qa>0||bs>0){const Rr=re(ie,`salaryStructures/${t.companyId}/${jr}`);let er=await mn(Rr),Ir=er.val();if((!Ir||Number(Ir.grossSalary||0)!==qa||Number(Ir.basicSalary||0)!==bs)&&(await Pn(Rr,It(jr,qa,bs,Xe.name.trim(),Wa)),er=await mn(Rr),Ir=er.val()),!Ir||Number(Ir.grossSalary||0)!==qa||Number(Ir.basicSalary||0)!==bs)throw new Error("Employee was created, but Payroll Salary Structure verification failed. Use Sync Payroll Salary on the Recruitment row.")}await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.candidate_hired",entityType:"recruitment",entityId:Xe.id,summary:`Selected candidate ${Xe.name} converted to employee ${xa}.`,branchId:_,metadata:{employeeId:jr,employeeCode:xa,vacancyId:Xe.vacancyId,grossSalary:qa,basicSalary:bs}}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"employee.created",entityType:"employee",entityId:jr,summary:`Employee ${Xe.name} (${xa}) created from Recruitment.`,branchId:_,metadata:{recruitmentCandidateId:Xe.id}}),y(!1),N(""),ue(""),$e(`${Xe.name} selected and created as employee ${xa}.`)}catch(Wa){console.error(Wa);const $s=Wa instanceof Error?Wa.message:"Unknown error";ue(`Hiring conversion could not be completed: ${$s}`)}finally{Ge(!1)}},It=(Xe,Jt,Ht,xa,ra=Date.now())=>({employeeId:Xe,grossSalary:Math.max(0,Jt),basicSalary:Math.max(0,Ht),houseRent:0,medicalAllowance:0,transportAllowance:0,otherAllowance:Math.max(0,Jt-Ht),bankName:"",bankAccount:"",bankAccountHolder:xa,taxApplicable:!1,taxPayerCategory:"general",disabledDependentCount:0,taxLocationCategory:"",annualEligibleInvestment:0,taxWithheldBeforeVerixo:0,pfApplicable:!1,pfCustomStartDate:"",active:!0,updatedAt:ra,updatedByUid:t.uid,updatedByName:t.name||t.email||"User"}),Pt=Xe=>{var rs,oa;if(!Xe.hiredEmployeeId)return;const Jt=f[Xe.hiredEmployeeId],Ht=Number(((rs=Xe.hiringSnapshot)==null?void 0:rs.grossSalary)||0),xa=Number(((oa=Xe.hiringSnapshot)==null?void 0:oa.basicSalary)||0),ra=Number((Jt==null?void 0:Jt.grossSalary)||0),Ha=Number((Jt==null?void 0:Jt.basicSalary)||0),is=Ht>0?Ht:ra>0?ra:Number(Xe.expectedSalary||0),hs=xa>
41500?xa:Ha>0?Ha:0;Pe(Xe.id),Ee(is),We(hs),_e(""),ge(!0)},Jn=async()=>{var xa,ra,Ha,is;const Xe=l.find(hs=>hs.id===de);if(!(Xe!=null&&Xe.hiredEmployeeId)||te||!s)return;const Jt=Math.max(0,Number(Re||0)),Ht=Math.max(0,Number(Be||0));if(Jt<=0){_e("Gross Salary must be greater than zero.");return}if(Ht<0||Ht>Jt){_e("Basic Salary must be zero or greater and cannot exceed Gross Salary.");return}Ge(!0),_e(""),$e("");try{const hs=Date.now(),rs=d.find($s=>$s.id===Xe.hiredEmployeeId),oa=It(Xe.hiredEmployeeId,Jt,Ht,(rs==null?void 0:rs.name)||Xe.name,hs),qa={[`salaryStructures/${t.companyId}/${Xe.hiredEmployeeId}`]:oa,[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot/grossSalary`]:Jt,[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot/basicSalary`]:Ht,[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot/employeeCode`]:Xe.hiredEmployeeCode||(rs==null?void 0:rs.employeeId)||"",[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot/branchId`]:(rs==null?void 0:rs.branchId)||((xa=Xe.hiringSnapshot)==null?void 0:xa.branchId)||"",[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot/department`]:(rs==null?void 0:rs.department)||((ra=Xe.hiringSnapshot)==null?void 0:ra.department)||"",[`recruitmentCandidates/${t.companyId}/${Xe.id}/hiringSnapshot/designation`]:(rs==null?void 0:rs.designation)||((Ha=Xe.hiringSnapshot)==null?void 0:Ha.designation)||""};await yn(re(ie),qa);const Wa=(await mn(re(ie,`salaryStructures/${t.companyId}/${Xe.hiredEmployeeId}`))).val();if(!Wa||Number(Wa.grossSalary||0)!==Jt||Number(Wa.basicSalary||0)!==Ht)throw new Error("Salary Structure verification failed after repair.");await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.salary_structure_repaired",entityType:"recruitment",entityId:Xe.id,summary:`Payroll Salary Structure repaired for ${Xe.name}.`,branchId:(rs==null?void 0:rs.branchId)||((is=Xe.hiringSnapshot)==null?void 0:is.branchId),metadata:{employeeId:Xe.hiredEmployeeId,grossSalary:Jt,basicSalary:Ht}}),ge(!1),Pe(""),$e(`Payroll Salary Structure repaired for ${Xe.name}: Gross ${Jt.toLocaleString()}, Basic ${Ht.toLocaleString()}.`)}catch(hs){console.error(hs),_e(`Payroll Salary repair failed: ${hs instanceof Error?hs.message:"Unknown error"}`)}finally{Ge(!1)}},na=()=>{wt(""),Nt(""),jt(""),tn(a==="all"?"":a),xe(1),ht(""),we(""),Ce("")},Mn=()=>{na(),Me(!0)},Ea=Xe=>{wt(Xe.id),Nt(Xe.title),jt(Xe.department),tn(Xe.branchId||""),xe(Xe.openings),ht(Xe.closingDate||""),we(Xe.description||""),Ce(""),Me(!0)},ga=async()=>{if(!s||te)return;const Xe=Math.max(1,Math.floor(Number(B||1)));if(!st.trim()||!be.trim()){Ce("Position Title and Department are required.");return}if(ot){const Jt=i.find(xa=>xa.id===ot),Ht=Jt?he(Jt.id):0;if(Xe<Ht){Ce(`Openings cannot be reduced below ${Ht} because ${Ht} candidate(s) are already hired.`);return}}Ge(!0),Ce(""),$e("");try{const Jt=Date.now();if(ot){const Ht=i.find(xa=>xa.id===ot);if(!Ht)throw new Error("Vacancy no longer exists.");await yn(re(ie,`recruitmentVacancies/${t.companyId}/${ot}`),{title:st.trim(),department:be.trim(),branchId:bt||"",openings:Xe,closingDate:tt||"",description:dt.trim(),updatedAt:Jt}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.vacancy_updated",entityType:"recruitment",entityId:ot,summary:`Recruitment vacancy updated: ${st.trim()}.`,branchId:bt||void 0,metadata:{openings:Xe,status:Ht.status}}),$e("Job vacancy updated successfully.")}else{const Ht=Ta(re(ie,`recruitmentVacancies/${t.companyId}`));await Pn(Ht,{title:st.trim(),department:be.trim(),branchId:bt||"",openings:Xe,status:"open",closingDate:tt||"",description:dt.trim(),createdAt:Jt,updatedAt:Jt}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.vacancy_created",entityType:"recruitment",entityId:Ht.key||"vacancy",summary:`Recruitment vacancy created: ${st.trim()}.`,branchId:bt||void 0,metadata:{openings:Xe}}),$e("Job vacancy created successfully.")}Me(!1),na()}catch(Jt){console.error(Jt),Ce(`Job vacancy could not be saved: ${Jt instanceof Error?Jt.message:"Unknown error"}`)}finally{Ge(!1)}},zn=async(Xe,Jt)=>{if(!s||te||Xe.status===Jt)return;const Ht=he(Xe.id);if(Jt==="open"&&Ht>=Xe.openings){$e(`Cannot reopen ${Xe.title}: all ${Xe.openings} opening(s) are already filled. Increase Openings first.`);return}Ge(!0),$e("");
4150try{const xa=Date.now(),ra={status:Jt,updatedAt:xa};Jt==="closed"?(ra.closedAt=xa,ra.closedByUid=t.uid,ra.closedByName=t.name||t.email||"User"):(ra.closedAt=null,ra.closedByUid=null,ra.closedByName=null),await yn(re(ie,`recruitmentVacancies/${t.companyId}/${Xe.id}`),ra),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.vacancy_status_changed",entityType:"recruitment",entityId:Xe.id,summary:`Recruitment vacancy ${Xe.title} ${Jt}.`,branchId:Xe.branchId,metadata:{from:Xe.status,to:Jt,hired:Ht,openings:Xe.openings}}),$e(`${Xe.title} ${Jt==="closed"?"closed":"reopened"} successfully.`)}catch(xa){console.error(xa),$e("Vacancy status could not be updated.")}finally{Ge(!1)}},Xn=async()=>{if(!s||te)return;Te("");const Xe=i.find(ra=>ra.id===rt),Jt=An.trim(),Ht=Xt.trim().toLowerCase();if(!Xe||Xe.status!=="open"){Te("Please select an Open vacancy.");return}if(!Qt.trim()||!Jt){Te("Candidate Name and Phone are required.");return}if(Oe(Xe)<=0){Te("This vacancy is already fully filled.");return}const xa=l.find(ra=>ra.vacancyId===rt&&(Jt&&(ra.phone||"").trim()===Jt||Ht&&(ra.email||"").trim().toLowerCase()===Ht));if(xa){const ra=(xa.phone||"").trim()===Jt?"Phone":"Email";Te(`${ra} already has an application for this vacancy (${xa.name} · ${Of[xa.status]}).`);return}Ge(!0),$e("");try{const ra=Date.now(),Ha=Ta(re(ie,`recruitmentCandidates/${t.companyId}`));await Pn(Ha,{vacancyId:rt,name:Qt.trim(),phone:Jt,email:Xt.trim(),experience:Gt.trim(),source:Vt.trim(),currentCompany:Ct.trim(),currentDesignation:Rt.trim(),expectedSalary:Number(dn||0),resumeUrl:wa.trim(),status:"applied",notes:on.trim(),createdAt:ra,updatedAt:ra}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.candidate_created",entityType:"recruitment",entityId:Ha.key||"candidate",summary:`Candidate application created: ${Qt.trim()}.`,branchId:Xe.branchId,metadata:{vacancyId:rt}}),Ye(!1),Te(""),gn(""),Sn(""),Wt(""),$t(""),sn(""),ke(""),Et(""),xn(""),Ln(0),Ca(""),$e("Candidate application created successfully.")}catch(ra){console.error(ra),Te(`Candidate application could not be created: ${ra instanceof Error?ra.message:"Unknown error"}`)}finally{Ge(!1)}},Vn=Xe=>{xt(Xe.id),Sa(Xe.interviewDate||""),$a(Xe.interviewTime||""),vs(Xe.interviewer||""),Ja(Xe.interviewType||"in_person"),ha(Xe.interviewLocation||""),W(Xe.interviewRemarks||""),le(!0)},ua=async()=>{const Xe=l.find(Jt=>Jt.id===nt);if(!(!Xe||!s||te||!In||!aa||!jn.trim())){Ge(!0),$e("");try{const Jt={status:"interview",interviewDate:In,interviewTime:aa,interviewer:jn.trim(),interviewType:ka,interviewLocation:_n.trim(),interviewRemarks:ta.trim(),updatedAt:Date.now()};await yn(re(ie,`recruitmentCandidates/${t.companyId}/${Xe.id}`),Jt),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.interview_scheduled",entityType:"recruitment",entityId:Xe.id,summary:`Interview scheduled for ${Xe.name} on ${In} ${aa}.`,metadata:{date:In,time:aa,interviewer:jn,type:ka}}),le(!1),$e(`Interview details saved for ${Xe.name}.`)}catch(Jt){console.error(Jt),$e("Interview details could not be saved.")}finally{Ge(!1)}}},Ma=async(Xe,Jt)=>{if(!(!s||te||!Hj[Xe.status].includes(Jt))){Ge(!0),$e("");try{await yn(re(ie,`recruitmentCandidates/${t.companyId}/${Xe.id}`),{status:Jt,updatedAt:Date.now()}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name||t.email||"User",action:"recruitment.candidate_status_changed",entityType:"recruitment",entityId:Xe.id,summary:`Candidate ${Xe.name} moved to ${Of[Jt]}.`,metadata:{from:Xe.status,to:Jt}}),$e(`${Xe.name} moved to ${Of[Jt]}.`)}catch(Ht){console.error(Ht),$e("Candidate status could not be updated.")}finally{Ge(!1)}}};return e.jsxs("section",{className:"recruitment-page",children:[e.jsxs("div",{className:"recruitment-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"HR TALENT ACQUISITION"}),e.jsx("h1",{children:"Recruitment & Applicant Tracking"}),e.jsx("p",{children:"Manage vacancies and candidate progress without changing the Employee master until hiring is finalized."})]}),s&&e.jsxs("div",{className:"recruitment-actions",children:[e.jsxs("button",{onClick:Mn,children:[e.jsx(as,{size:16})," New Vacancy"]}),e.jsxs("button",{className:"secondary",onClick:()=>{Te(""),Ye(!0)},children:[e.jsx(a6,{size:16})," Add Candidate"]})]})]}),pt&&e.jsx("div",{className:"recruitment-message",children:pt}),e.jsxs("div",{className:"recruitment-summary",children:[e.jsxs("article",{children:[e.jsx(Gw,{size:20}),e.jsx("span",{children:"Open Vacancies"}),e.jsx("strong",{children:vt})]}),e.jsxs("article",{children:[e.jsx(t2,{size:20}),e.jsx("span",{children:"Applicants"}),e.jsx("strong",{children:Zt.length})]}),e.jsxs("article",{children:[e.jsx(wi,{size:20}),e.jsx("span",{children:"Interview Stage"}),e.jsx("strong",{children:Ae})]}),e.jsxs("article",{children:[e.jsx("span",{children:"Selected"}),e.jsx("strong",{children:oe})]})]}),e.jsxs("div",{className:"recruitment-section",children:[e.jsx("div",{className:"recruitment-section-head",children:e.jsxs("div",{children:[e.jsx("span",{children:"VACANCIES"}),e.jsx("h2",{children:"Job Openings"})]})}),e.jsx("div",{className:"recruitment-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"POSITION"}),e.jsx("th",{children:"DEPARTMENT"}),e.jsx("th",{children:"BRANCH"}),e.jsx("th",{children:"OPENINGS"}),e.jsx("th",{children:"HIRED"}),e.jsx("th",{children:"REMAINING"}),e.jsx("th",{children:"CLOSING"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"ACTION"})]})}),e.jsx("tbody",{children:ft.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:9,className:"empty",children:"No recruitment vacancy found."})}):ft.map(Xe=>{const Jt=he(Xe.id),Ht=Oe(Xe);return e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("strong",{children:Xe.title})}),e.jsx("td",{children:Xe.department}),e.jsx("td",{children:Ve(Xe.branchId)}),e.jsx("td",{children:Xe.openings}),e.jsx("td",{children:Jt}),e.jsx("td",{children:e.jsx("strong",{children:Ht})}),e.jsx("td",{children:Xe.closingDate||"â"}),e.jsx("td",{children:e.jsx("span",{className:`recruitment-status ${Xe.status}`,children:Xe.status[0].toUpperCase()+Xe.status.slice(1)})}),e.jsx("td",{children:e.jsxs("div",{className:"recruitment-next",children:[s&&e.jsx("button",{disabled:te,onClick:()=>Ea(Xe),children:"Edit"}),s&&Xe.status==="open"&&e.jsx("button",{disabled:te,onClick:()=>zn(Xe,"closed"),children:"Close"}),s&&Xe.status==="closed"&&e.jsx("button",{disabled:te||Ht<=0,onClick:()=>
4150zn(Xe,"open"),children:"Reopen"})]})})]},Xe.id)})})]})})]}),e.jsxs("div",{className:"recruitment-section",children:[e.jsxs("div",{className:"recruitment-section-head",children:[e.jsxs("div",{children:[e.jsx("span",{children:"APPLICANT TRACKING"}),e.jsx("h2",{children:"Candidates"})]}),e.jsxs("div",{className:"recruitment-filters",children:[e.jsxs("label",{children:[e.jsx(xr,{size:16}),e.jsx("input",{placeholder:"Search candidate, phone, email...",value:ee,onChange:Xe=>qe(Xe.target.value)})]}),e.jsxs("select",{value:se,onChange:Xe=>pe(Xe.target.value),children:[e.jsx("option",{value:"",children:"All Vacancies"}),ft.map(Xe=>e.jsx("option",{value:Xe.id,children:Xe.title},Xe.id))]})]})]}),e.jsx("div",{className:"recruitment-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"CANDIDATE"}),e.jsx("th",{children:"VACANCY"}),e.jsx("th",{children:"CONTACT"}),e.jsx("th",{children:"EXPERIENCE"}),e.jsx("th",{children:"STATUS"}),e.jsx("th",{children:"NEXT ACTION"})]})}),e.jsx("tbody",{children:Zt.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty",children:"No candidate application found."})}):Zt.map(Xe=>{const Jt=i.find(Ht=>Ht.id===Xe.vacancyId);return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:Xe.name}),e.jsx("small",{children:Xe.source||"Direct"})]}),e.jsx("td",{children:(Jt==null?void 0:Jt.title)||"â"}),e.jsxs("td",{children:[Xe.phone,e.jsx("small",{children:Xe.email||""})]}),e.jsxs("td",{children:[Xe.experience||"â",e.jsx("small",{children:[Xe.currentDesignation,Xe.currentCompany].filter(Boolean).join(" · ")}),Xe.expectedSalary?e.jsxs("small",{children:["Expected: ",Number(Xe.expectedSalary).toLocaleString()]}):null,Xe.resumeUrl?e.jsx("small",{children:e.jsx("a",{href:Xe.resumeUrl,target:"_blank",rel:"noreferrer",children:"Open CV / Resume"})}):null]}),e.jsx("td",{children:e.jsx("span",{className:`recruitment-status ${Xe.status}`,children:Of[Xe.status]})}),e.jsx("td",{children:e.jsxs("div",{className:"recruitment-next",children:[Xe.status==="shortlisted"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{disabled:te,onClick:()=>Vn(Xe),children:"Interview"}),e.jsx("button",{disabled:te,onClick:()=>Ma(Xe,"rejected"),children:"Rejected"})]}),Xe.status==="interview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{disabled:te,onClick:()=>Vn(Xe),children:"Interview Details"}),e.jsx("button",{disabled:te||!!Xe.hiredEmployeeId,onClick:()=>At(Xe),children:Xe.hiredEmployeeId?`Employee ${Xe.hiredEmployeeCode||""}`:"Selected / Hire"}),e.jsx("button",{disabled:te,onClick:()=>Ma(Xe,"rejected"),children:"Rejected"})]}),Xe.status!=="shortlisted"&&Xe.status!=="interview"&&Hj[Xe.status].map(Ht=>e.jsx("button",{disabled:te,onClick:()=>Ma(Xe,Ht),children:Of[Ht]},Ht)),Hj[Xe.status].length===0&&(Xe.status==="selected"&&Xe.hiredEmployeeId?(()=>{var oa,qa;const Ht=f[Xe.hiredEmployeeId],xa=Number((Ht==null?void 0:Ht.grossSalary)||0),ra=Number((Ht==null?void 0:Ht.basicSalary)||0),Ha=Number(((oa=Xe.hiringSnapshot)==null?void 0:oa.grossSalary)||0),is=Number(((qa=Xe.hiringSnapshot)==null?void 0:qa.basicSalary)||0),rs=Ha>0||is>0?!!Ht&&xa===Ha&&ra===is:!!Ht&&xa>0;return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"recruitment-hired-link",children:["Employee ",Xe.hiredEmployeeCode||"Created"]}),rs?e.jsx("span",{className:"recruitment-payroll-linked",children:"Payroll Linked"}):e.jsx("button",{disabled:te,onClick:()=>Pt(Xe),children:"Repair Payroll Salary"})]})})():"â")]})})]},Xe.id)})})]})})]}),Se&&e.jsx("div",{className:"recruitment-modal-bg",onMouseDown:Xe=>{Xe.currentTarget===Xe.target&&(Me(!1),na())},children:e.jsxs("div",{className:"recruitment-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:ot?"EDIT VACANCY":"NEW VACANCY"}),e.jsx("h2",{children:ot?"Update Job Opening":"Create Job Opening"})]}),e.jsx("button",{onClick:()=>{Me(!1),na()},children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"recruitment-grid",children:[e.jsxs("label",{children:["Position Title",e.jsx("input",{value:st,onChange:Xe=>{Nt(Xe.target.value),Ce("")}})]}),e.jsxs("label",{children:["Department",e.jsx("input",{value:be,onChange:Xe=>{jt(Xe.target.value),Ce("")}})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:bt,onCh
4150ange:Xe=>tn(Xe.target.value),children:[e.jsx("option",{value:"",children:"All / Unassigned"}),n.filter(Xe=>Xe.active).map(Xe=>e.jsx("option",{value:Xe.id,children:Xe.name},Xe.id))]})]}),e.jsxs("label",{children:["Openings",e.jsx("input",{type:"number",min:"1",value:B,onChange:Xe=>{xe(Number(Xe.target.value)),Ce("")}})]}),e.jsxs("label",{children:["Closing Date",e.jsx("input",{type:"date",value:tt,onChange:Xe=>ht(Xe.target.value)})]})]}),e.jsxs("label",{className:"wide",children:["Description",e.jsx("textarea",{rows:4,value:dt,onChange:Xe=>we(Xe.target.value)})]}),ct&&e.jsx("div",{className:"recruitment-hiring-error",children:ct}),ot&&e.jsxs("div",{className:"recruitment-info-note",children:["Already hired: ",he(ot),". Openings cannot be reduced below the hired count."]}),e.jsxs("footer",{children:[e.jsx("button",{onClick:()=>{Me(!1),na()},children:"Cancel"}),e.jsx("button",{className:"primary",disabled:te||!st.trim()||!be.trim(),onClick:ga,children:te?"Saving...":ot?"Save Changes":"Create Vacancy"})]})]})}),ce&&e.jsx("div",{className:"recruitment-modal-bg",onMouseDown:Xe=>{Xe.currentTarget===Xe.target&&Ye(!1)},children:e.jsxs("div",{className:"recruitment-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"NEW APPLICANT"}),e.jsx("h2",{children:"Add Candidate"})]}),e.jsx("button",{onClick:()=>Ye(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"recruitment-grid",children:[e.jsxs("label",{children:["Vacancy",e.jsxs("select",{value:rt,onChange:Xe=>{St(Xe.target.value),Te("")},children:[e.jsx("option",{value:"",children:"Select Vacancy"}),ft.filter(Xe=>Xe.status==="open"&&Oe(Xe)>0).map(Xe=>e.jsxs("option",{value:Xe.id,children:[Xe.title," · ",Oe(Xe)," remaining"]},Xe.id))]})]}),e.jsxs("label",{children:["Candidate Name",e.jsx("input",{value:Qt,onChange:Xe=>gn(Xe.target.value)})]}),e.jsxs("label",{children:["Phone",e.jsx("input",{value:An,onChange:Xe=>Sn(Xe.target.value)})]}),e.jsxs("label",{children:["Email",e.jsx("input",{value:Xt,onChange:Xe=>Wt(Xe.target.value)})]}),e.jsxs("label",{children:["Experience",e.jsx("input",{placeholder:"e.g. 3 years",value:Gt,onChange:Xe=>$t(Xe.target.value)})]}),e.jsxs("label",{children:["Source",e.jsx("input",{placeholder:"Direct / Referral / Portal",value:Vt,onChange:Xe=>sn(Xe.target.value)})]}),e.jsxs("label",{children:["Current Company",e.jsx("input",{value:Ct,onChange:Xe=>Et(Xe.target.value)})]}),e.jsxs("label",{children:["Current Designation",e.jsx("input",{value:Rt,onChange:Xe=>xn(Xe.target.value)})]}),e.jsxs("label",{children:["Expected Salary",e.jsx("input",{type:"number",min:"0",value:dn||"",onChange:Xe=>Ln(Number(Xe.target.value))})]}),e.jsxs("label",{children:["CV / Resume Link",e.jsx("input",{type:"url",placeholder:"https://...",value:wa,onChange:Xe=>Ca(Xe.target.value)})]})]}),e.jsxs("label",{className:"wide",children:["Notes",e.jsx("textarea",{rows:3,value:on,onChange:Xe=>ke(Xe.target.value)})]}),De&&e.jsx("div",{className:"recruitment-hiring-error",children:De}),e.jsxs("footer",{children:[e.jsx("button",{onClick:()=>Ye(!1),children:"Cancel"}),e.jsx("button",{className:"primary",disabled:te||!rt||!Qt.trim()||!An.trim(),onClick:Xn,children:"Add Candidate"})]})]})}),me&&de&&(()=>{var Ht,xa;const Xe=l.find(ra=>ra.id===de),Jt=Xe!=null&&Xe.hiredEmployeeId?d.find(ra=>ra.id===Xe.hiredEmployeeId):void 0;return Xe?e.jsx("div",{className:"recruitment-modal-bg",onMouseDown:ra=>{ra.currentTarget===ra.target&&ge(!1)},children:e.jsxs("div",{className:"recruitment-modal salary-repair-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"PAYROLL REPAIR"}),e.jsx("h2",{children:"Repair Initial Salary Structure"})]}),e.jsx("button",{onClick:()=>ge(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"hiring-candidate-card",children:[e.jsx("strong",{children:Xe.name}),e.jsxs("span",{children:["Employee ",Xe.hiredEmployeeCode||(Jt==null?void 0:Jt.employeeId)||"â"," · ",(Jt==null?void 0:Jt.department)||((Ht=Xe.hiringSnapshot)==null?void 0:Ht.department)||"â"," · ",(Jt==null?void 0:Jt.designation)||((xa=Xe.hiringSnapshot)==null?void 0:xa.designation)||"â"]}
4150)]}),e.jsxs("div",{className:"recruitment-grid salary-repair-grid",children:[e.jsxs("label",{children:["Gross Salary",e.jsx("input",{type:"number",min:"0",value:Re||"",onChange:ra=>{Ee(Number(ra.target.value)),_e("")}})]}),e.jsxs("label",{children:["Basic Salary",e.jsx("input",{type:"number",min:"0",value:Be||"",onChange:ra=>{We(Number(ra.target.value)),_e("")}})]}),e.jsxs("label",{children:["Other Allowance",e.jsx("input",{readOnly:!0,value:Math.max(0,Number(Re||0)-Number(Be||0))})]})]}),it&&e.jsx("div",{className:"recruitment-hiring-error",children:it}),e.jsx("div",{className:"recruitment-hiring-note",children:"Use the salary values confirmed during hiring. This repairs only the missing initial Payroll Salary Structure for the already-created employee; it does not create a second employee or change recruitment status."}),e.jsxs("footer",{children:[e.jsx("button",{onClick:()=>ge(!1),children:"Cancel"}),e.jsx("button",{className:"primary",disabled:te||Number(Re||0)<=0||Number(Be||0)>Number(Re||0),onClick:Jn,children:te?"Repairing...":"Repair Payroll Salary"})]})]})}):null})(),p&&b&&(()=>{const Xe=l.find(Ht=>Ht.id===b),Jt=Xe?i.find(Ht=>Ht.id===Xe.vacancyId):void 0;return Xe?e.jsx("div",{className:"recruitment-modal-bg",onMouseDown:Ht=>{Ht.currentTarget===Ht.target&&y(!1)},children:e.jsxs("div",{className:"recruitment-modal hiring-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"SELECTION & HIRING"}),e.jsx("h2",{children:"Create Employee from Candidate"})]}),e.jsx("button",{onClick:()=>y(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"hiring-candidate-card",children:[e.jsx("strong",{children:Xe.name}),e.jsxs("span",{children:[(Jt==null?void 0:Jt.title)||"â"," · ",Xe.phone,Xe.email?` · ${Xe.email}`:""]})]}),e.jsxs("div",{className:"recruitment-grid hiring-grid",children:[e.jsxs("label",{children:["Employee ID",e.jsx("input",{value:w,onChange:Ht=>{C(Ht.target.value),ue("")},placeholder:"e.g. 124"})]}),e.jsxs("label",{children:["Phone",e.jsx("input",{value:je,onChange:Ht=>{V(Ht.target.value),ue("")}})]}),e.jsxs("label",{children:["Email",e.jsx("input",{value:$,onChange:Ht=>{F(Ht.target.value),ue("")}})]}),e.jsxs("label",{children:["Joining Date",e.jsx("input",{type:"date",value:R,onChange:Ht=>I(Ht.target.value)})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:_,onChange:Ht=>J(Ht.target.value),children:[e.jsx("option",{value:"",children:"Select Branch"}),n.filter(Ht=>Ht.active).map(Ht=>e.jsx("option",{value:Ht.id,children:Ht.name},Ht.id))]})]}),e.jsxs("label",{children:["Department",e.jsx("input",{value:T,onChange:Ht=>G(Ht.target.value)})]}),e.jsxs("label",{children:["Designation",e.jsx("input",{value:z,onChange:Ht=>H(Ht.target.value)})]}),e.jsxs("label",{children:["Employee Role",e.jsxs("select",{value:K,onChange:Ht=>L(Ht.target.value),children:[e.jsx("option",{value:"sales",children:"Sales"}),e.jsx("option",{value:"technician",children:"Technician"}),e.jsx("option",{value:"accounts",children:"Accounts"}),e.jsx("option",{value:"admin",children:"Admin"}),e.jsx("option",{value:"store",children:"Store"}),e.jsx("option",{value:"delivery",children:"Delivery"}),e.jsx("option",{value:"hr",children:"HR"}),e.jsx("option",{value:"manager",children:"Manager"})]})]}),e.jsxs("label",{children:["Employment Type",e.jsxs("select",{value:D,onChange:Ht=>M(Ht.target.value),children:[e.jsx("option",{value:"permanent",children:"Permanent"}),e.jsx("option",{value:"contract",children:"Contract"}),e.jsx("option",{value:"part_time",children:"Part Time"}),e.jsx("option",{value:"intern",children:"Intern"})]})]}),e.jsxs("label",{children:["Gross Salary",e.jsx("input",{type:"number",min:"0",value:Z||"",onChange:Ht=>fe(Number(Ht.target.value))})]}),e.jsxs("label",{children:["Basic Salary",e.jsx("input",{type:"number",min:"0",value:q||"",onChange:Ht=>ne(Number(Ht.target.value))})]})]}),e.jsxs("label",{className:"wide",children:["Hiring Notes",e.jsx("textarea",{rows:3,value:ae,onChange:Ht=>Y(Ht.target.value)})]}),P&&e.jsx("div",{className:"recruitment-hiring-error",children:P}),e.jsx("div",{className:"recruitment-hiring-note",children:"This creates one Employee Master record and, when s
4150alary is entered, an initial Payroll Salary Structure. The candidate remains linked to that employee for recruitment history. Duplicate Employee ID, phone or email is blocked."}),e.jsxs("footer",{children:[e.jsx("button",{onClick:()=>y(!1),children:"Cancel"}),e.jsx("button",{className:"primary",disabled:te||!w.trim()||!je.trim()||!R||!_||!T.trim()||!z.trim(),onClick:en,children:te?"Creating...":"Select & Create Employee"})]})]})}):null})(),Je&&e.jsx("div",{className:"recruitment-modal-bg",onMouseDown:Xe=>{Xe.currentTarget===Xe.target&&le(!1)},children:e.jsxs("div",{className:"recruitment-modal",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("span",{children:"INTERVIEW MANAGEMENT"}),e.jsx("h2",{children:"Schedule / Update Interview"})]}),e.jsx("button",{onClick:()=>le(!1),children:e.jsx(ja,{})})]}),e.jsxs("div",{className:"recruitment-grid",children:[e.jsxs("label",{children:["Interview Date",e.jsx("input",{type:"date",value:In,onChange:Xe=>Sa(Xe.target.value)})]}),e.jsxs("label",{children:["Interview Time",e.jsx("input",{type:"time",value:aa,onChange:Xe=>$a(Xe.target.value)})]}),e.jsxs("label",{children:["Interviewer",e.jsx("input",{placeholder:"Name / panel",value:jn,onChange:Xe=>vs(Xe.target.value)})]}),e.jsxs("label",{children:["Interview Type",e.jsxs("select",{value:ka,onChange:Xe=>Ja(Xe.target.value),children:[e.jsx("option",{value:"in_person",children:"In Person"}),e.jsx("option",{value:"online",children:"Online"}),e.jsx("option",{value:"phone",children:"Phone"})]})]}),e.jsxs("label",{children:["Location / Meeting Link",e.jsx("input",{value:_n,onChange:Xe=>ha(Xe.target.value)})]})]}),e.jsxs("label",{className:"wide",children:["Interview Remarks",e.jsx("textarea",{rows:4,value:ta,onChange:Xe=>W(Xe.target.value),placeholder:"Interview notes / result summary"})]}),e.jsx("div",{className:"recruitment-info-note",children:"Saving this form records the interview details and moves a shortlisted candidate to Interview. It does not create an employee or change Payroll."}),e.jsxs("footer",{children:[e.jsx("button",{onClick:()=>le(!1),children:"Cancel"}),e.jsx("button",{className:"primary",disabled:te||!In||!aa||!jn.trim(),onClick:ua,children:te?"Saving...":"Save Interview"})]})]})})]})}const Dd="5.4.648",Wj=14;function UU(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function zU(t){if(!["owner","super_admin"].includes(t.role))return;const n=re(ie,`settings/${t.companyId}/system`),a=await mn(n),s=a.exists()?a.val():{},i=re(ie,`companies/${t.companyId}`),c=await mn(i),l=c.exists()?c.val():null;if(l){const d=l.slug||UU(l.name)||t.companyId.toLowerCase(),u=zE(l.features),f=zf(u);await yn(i,{slug:d,features:u,featureSchemaVersion:3,featureHealth:{healthy:f.healthy,enabledCount:f.enabledCount,disabledCount:f.disabledCount,checkedAt:Date.now()},updatedAt:Date.now()}),await yn(re(ie,`settings/${t.companyId}/features`),{...m2,...u,schemaVersion:3,registryVersion:Dd,health:{healthy:f.healthy,enabledCount:f.enabledCount,disabledCount:f.disabledCount,plannedEnabled:f.plannedEnabled,missingDependencies:f.missingDependencies,checkedAt:Date.now()},updatedAt:Date.now()}),await yn(re(ie,`companyDirectory/${d}`),{id:t.companyId,name:l.name,slug:d,active:l.active!==!1})}Number(s.schemaVersion??0)>=Wj||(await yn(n,{appVersion:Dd,schemaVersion:Wj,multiCompanyReady:!0,moduleRegistryReady:!0,featureSchemaVersion:3,moduleQaReady:!0,migratedAt:Date.now()}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"system.migrated",entityType:"system",entityId:t.companyId,summary:`ERP migrated to schema ${Wj}`,metadata:{appVersion:Dd,multiCompanyReady:!0,moduleRegistryReady:!0,featureSchemaVersion:3,moduleQaReady:!0}}))}const p2=["https://verixo.web.app/mobile/android/update.json","https://service-center-cloud.web.app/mobile/android/update.json"],qU="https://github.com/ratulgoswami007/VERIXO-App-Releases/releases/download/app-v1.5.2/VERIXO_Android_v1.5.2.apk";function a5(t){const n=new URL(t);if(n.protocol!=="https:")throw new Error("Android APK URL is not a secure HTTPS URL.");window.location.assign(n.toString())}async function WE(){for(const t of p2)try{const n=await fetch(t,{cache:"no-store",headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Update metadata request failed (${n.status}).`);const a=await n.json();if(typeof a.apkUrl!="string"||!a.apkUrl.trim())throw new Error("Android update metadata does not contain apkUrl.");a5(a.apkUrl);return}catch(n){console.warn(`Android app metadata source failed: ${t}`,n)}try{a5(qU)}catch(t){console.error("Android app download fallback failed:",t),window.alert("Android app download link is temporarily unavailable. Please try again later.")}}const VU=["dashboard","company","branches","customers","serviceJobs","estimates","invoices","newSale","newPurchase","productBrand","productGroup","productCategory","productMaster","collections","supplierPayment","supplierMaster","chequeManagement","crmWorksp
4150ace","crmWebsiteConnectors","salaryPayable","salesDatewiseReport","purchaseDatewiseReport","financeReports","financeCollectionReport","financeDueReport","financeSupplierPayableReport","dayBookReport","chartOfAccounts","openingBalances","bankSetup","dataMigration","promotions","accountingVouchers","trialBalance","generalLedger","profitLoss","balanceSheet","stockReport","employees","technicians","attendance","attendanceLunch","attendanceMovement","attendanceDevices","attendanceFaceEnrollment","attendanceHolidays","attendanceShifts","attendanceLeave","attendanceMonthly","attendanceDaily","organizationSetup","deliveryScan","performanceService","performanceSales","performanceLeaderboard","userPermissions","reports","attendanceReports","payroll","advanceLoanRequests","appraisal","reportingHierarchy","employeeLifecycle","employeeRelations","hrLetters","gratuity","recruitment","rma","companyMaster","versionHistory"];function s5(){const t=new URLSearchParams(window.location.search),n=t.get("page"),a=VU.includes(n)?n:"dashboard",s=t.get("job")||void 0;return{page:a,jobId:s}}const Lf=t=>({repair:"Repair",new_pc_assembly:"New PC Assembly",upgrade:"Upgrade",windows_installation:"Windows Installation",networking:"Networking",cctv:"CCTV Installation",amc:"AMC / Maintenance",other:"Other Work"})[t||"repair"],Rc=t=>{const n=t||"repair";if(n==="new_pc_assembly")return{workflowTitle:"Assembly Workflow",startLabel:"Start Assembly",completeLabel:"Complete Assembly",summaryTitle:"Assembly Summary",performedLabel:"Assembly Work Completed *",performedPlaceholder:"PC assembled, cable management completed, BIOS configured...",partsLabel:"Components Used",notesLabel:"Assembly Notes",startTitle:"Assembly started",completeTitle:"Assembly completed",readyMessage:"Assembly à¦à¦¬à¦ quality check শà§à¦·à¥¤ à¦à¦à¦¨ Invoice ঠDelivery à¦à¦°à¦¾ যাবà§à¥¤"};if(n==="upgrade")return{workflowTitle:"Upgrade Workflow",startLabel:"Start Upgrade",completeLabel:"Complete Upgrade",summaryTitle:"Upgrade Summary",performedLabel:"Upgrade Work Completed *",performedPlaceholder:"SSD/RAM/GPU upgrade and configuration details...",partsLabel:"Parts Installed",notesLabel:"Upgrade Notes",startTitle:"Upgrade started",completeTitle:"Upgrade completed",readyMessage:"Upgrade à¦à¦¬à¦ quality check শà§à¦·à¥¤ à¦à¦à¦¨ Invoice ঠDelivery à¦à¦°à¦¾ যাবà§à¥¤"};if(n==="windows_installation")return{workflowTitle:"Installation Workflow",startLabel:"Start Installation",completeLabel:"Complete Installation",summaryTitle:"Installation Summary",performedLabel:"Installation Work Completed *",performedPlaceholder:"Windows installed, drivers configured, updates completed...",partsLabel:"Additional Parts",notesLabel:"Installation Notes",startTitle:"Installation started",completeTitle:"Installation completed",readyMessage:"Installation à¦à¦¬à¦ quality check শà§à¦·à¥¤ à¦à¦à¦¨ Delivery à¦à¦°à¦¾ যাবà§à¥¤"};if(n==="networking"||n==="cctv"){const a=n==="cctv";return{workflowTitle:a?"CCTV Installation Workflow":"Networking Workflow",startLabel:a?"Start Installation":"Start Network Work",completeLabel:a?"Complete Installation":"Complete Network Work",summaryTitle:a?"Installation Summary":"Network Work Summary",performedLabel:"Work Completed *",performedPlaceholder:a?"Camera installation, recording and remote view testing...":"Router/switch setup, cabling and connectivity testing...",partsLabel:"Materials / Parts Used",notesLabel:"Technical Notes",startTitle:a?"CCTV installation started":"Networking work started",completeTitle:a?"CCTV installation completed":"Networking work completed",readyMessage:"Work à¦à¦¬à¦ quality check শà§à¦·à¥¤ à¦à¦à¦¨ Handover / Delivery à¦à¦°à¦¾ যাবà§à¥¤"}}return n==="amc"?{workflowTitle:"AMC Service Workflow",startLabel:"Start Service",completeLabel:"Complete Service",summaryTitle:"Service Summary",performedLabel:"Service Work Completed *",performedPlaceholder:"Preventive maintenance, cleaning and inspection details...",partsLabel:"Parts / Consumables Used",notesLabel:"Service Notes",startTitle:"AMC service started",completeTitle:"AMC service completed",readyMessage:"AMC service à¦à¦¬à¦ quality check শà§à¦·à¥¤"}:{workflowTitle:"Repair Workflow",startLabel:"Start Repair",completeLabel:"Complete Repair",summaryTitle:"Repair Summary",performedLabel:"Repair Performed *",performedPlaceholder:"What repair work was completed?",partsLabel:"Parts Replaced",notesLabel:"Repair Notes",startTitle:"Repair work started",completeTitle:"Repair completed",readyMessage:"Repair à¦à¦¬à¦ quality check শà§à¦·à¥¤ à¦à¦à¦¨ Invoice ঠDelivery à¦à¦°à¦¾ যাবà§à¥¤"}};
4150function r5(t){switch(t.status){case"received":return{title:"Start Diagnosis",description:t.assignedTechnician?`Technician assigned: ${t.assignedTechnician}। à¦à¦à¦¨ diagnosis শà§à¦°à§ à¦à¦°à§à¦¨à¥¤`:"Device receive সমà§à¦ªà¦¨à§à¦¨ হà§à§à¦à§à¥¤ Technician assign à¦à¦°à§ diagnosis শà§à¦°à§ à¦à¦°à§à¦¨à¥¤"};case"diagnosing":return t.warrantyReviewStatus==="rma_created"&&t.linkedRmaNumber?{title:"Warranty Processing",description:`Diagnosis complete। Customer RMA ${t.linkedRmaNumber} তà§à¦°à¦¿ হà§à§à¦à§ à¦à¦¬à¦ warranty workflow à¦à¦²à¦à§à¥¤`}:t.diagnosisOutcome==="warranty_recommended"?{title:"Waiting for Warranty Review",description:"Technician product fault report দিà§à§à¦à§à¥¤ Service In-Charge warranty receive à¦à¦°à§ Customer RMA তà§à¦°à¦¿ à¦à¦°à¦¬à§à¥¤"}:t.diagnosisOutcome==="repairable"?{title:"Diagnosis Completed",description:"Technician product repairable হিসà§à¦¬à§ confirm à¦à¦°à§à¦à§à¥¤ à¦à¦à¦¨ repair work শà§à¦°à§ à¦à¦°à¦¾ যাবà§à¥¤"}:{title:"Complete Diagnosis",description:t.approvalPath==="estimate_required"?"Problem diagnosis শà§à¦· à¦à¦°à§ estimate তà§à¦°à¦¿ à¦à¦°à§à¦¨ à¦à¦¬à¦ customer approval নিন।":"Diagnosis শà§à¦· à¦à¦°à§ service work শà§à¦°à§ à¦à¦°à§à¦¨à¥¤"};case"waiting_approval":return{title:"Waiting for Customer Approval",description:"Estimate customer-à¦à¦° à¦à¦¾à¦à§ পাঠানৠহà§à§à¦à§à¥¤ Approval না পাà¦à§à¦¾ পরà§à¦¯à¦¨à§à¦¤ à¦à¦¾à¦ শà§à¦°à§ à¦à¦°à¦¾ যাবৠনা।"};case"approved":return{title:"Start Service Work",description:"Customer approval পাà¦à§à¦¾ à¦à§à¦à§à¥¤ Assigned technician à¦à¦à¦¨ à¦à¦¾à¦ শà§à¦°à§ à¦à¦°à¦¤à§ পারবà§à¥¤"};case"repairing":return{title:"Complete Work & Save Summary",description:"Work summary, Parts & Accessories, Service Charges à¦à¦¬à¦ internal cost save à¦à¦°à§à¦¨à¥¤"};case"quality_check":return{title:"Complete Quality Check",description:"Final test checklist complete à¦à¦°à§à¦¨à¥¤ QC pass হলৠJob Ready for Delivery হবà§à¥¤"};case"qc_completed":return{title:"QC Completed",description:"Quality Check à¦à¦¤à¦¿à¦®à¦§à§à¦¯à§ সমà§à¦ªà¦¨à§à¦¨ হà§à§à¦à§à¥¤ Authorized service user à¦à¦à¦¨ Job-à¦à¦¿ Ready for Delivery à¦à¦°à¦¤à§ পারবà§à¦¨à¥¤"};case"ready":return{title:t.invoiceNumber?"Collect Due & Deliver":"Generate Invoice",description:t.invoiceNumber?Number(t.dueAmount||0)>0?`Invoice তà§à¦°à¦¿ হà§à§à¦à§à¥¤ Outstanding à§³${Number(t.dueAmount||0).toLocaleString("en-GB")} collect à¦à¦°à¦¾à¦° পর Delivery Scan বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤`:"Invoice সমà§à¦ªà¦¨à§à¦¨ à¦à¦¬à¦ Due à§³0। Delivery Scan থà§à¦à§ customer verify à¦à¦°à§ delivery দিন।":"Finance â Invoices থà§à¦à§ invoice manually generate à¦à¦°à§à¦¨à¥¤ Charge, parts, discount ঠVAT final না হà¦à§à¦¾ পরà§à¦¯à¦¨à§à¦¤ invoice auto-generate হবৠনা।"};case"delivered":return{title:"Delivery Completed",description:"Device customer-à¦à§ delivery দà§à¦à§à¦¾ হà§à§à¦à§à¥¤ পà§à¦°à§à§à¦à¦¨à§ Job Close à¦à¦°à§à¦¨à¥¤"};case"closed":return{title:"Job Closed",description:"à¦à¦ Service Job সমà§à¦ªà§à¦°à§à¦£à¦à¦¾à¦¬à§ closed হà§à§à¦à§à¥¤"};case"cancelled":return{title:"Job Cancelled",description:"à¦à¦ Service Job cancelled হà§à§à¦à§à¥¤"};case"unknown":return{title:Dr(t.status),description:"à¦à¦ status Web ERP workflow-ঠপরিà¦à¦¿à¦¤ নà§à¥¤ Data review à¦à¦°à§ authorized user status ঠিঠà¦à¦°à§à¦¨à¥¤"}}}const i5={id:"",name:"",phone:"",email:"",address:"",active:!0},Gj={name:"",code:"",phone:"",address:"",contacts:[],managerName:"",active:!0},o5={name:"",phone:"",whatsapp:"",email:"",address:"",notes:"",dueAmount:0,active:!0,branchId:""},c5={customerId:"",branchId:"",deviceCategory:"Laptop",brand:"",model:"",serialNumber:"",imei:"",colour:"",loginPassword:"",technicalDetails:{},problem:"",accessories:"",accessoriesList:[],physicalConditions:[],conditionNote:"",estimatedCost:0,advanceAmount:0,discountAmount:0,dueAmount:0,expectedDelivery:"",warrantyUntil:"",priority:"normal",assignedTechnician:"",assignedTechnicianId:"",assignedTechnicianPhone:"",serviceType:"repair",serviceMode:"in_house",siteAddress:"",siteContactPerson:"",siteContactPhone:"",scheduledVisitAt:"",onsiteVisitStatus:"request_received",onsiteVisitCharge:0,onsiteTransportCharge:0,onsiteOtherCharge:0,onsitePaymentReference:"",j
4150obType:"repair",approvalPath:"quick_service",approvalStatus:"not_required",approvedEstimateId:"",status:"received",internalNotes:""};function GE({profile:t,required:n=!1,onComplete:a,onCancel:s}){const[i,c]=x.useState(""),[l,m]=x.useState(""),[d,u]=x.useState(""),[f,g]=x.useState(!1),[p,y]=x.useState(""),b=async w=>{if(w.preventDefault(),y(""),l.length<8){y("Password minimum 8 characters হতৠহবà§à¥¤");return}if(!/[A-Z]/.test(l)||!/[a-z]/.test(l)||!/[0-9]/.test(l)){y("Uppercase, lowercase à¦à¦¬à¦ number বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤");return}if(l!==d){y("New password à¦à¦¬à¦ Confirm password মিলà¦à§ না।");return}const C=Ti.currentUser;if(!C||!C.email){y("Login session পাà¦à§à¦¾ যাà¦à§à¦à§ না। Sign out à¦à¦°à§ à¦à¦¬à¦¾à¦° sign in à¦à¦°à§à¦¨à¥¤");return}if(!n&&!i){y("Current password দিন।");return}g(!0);try{if(!n){const _=Cd.credential(C.email,i);await B0(C,_)}let R=!1;if(n)try{const _=Cd.credential(C.email,l);await B0(C,_),R=!0}catch{R=!1}if(!R){await JM(C,l);const _=Cd.credential(C.email,l);await B0(C,_)}await C.getIdToken(!0);const I=Date.now();await Pn(re(ie,`users/${t.uid}/forcePasswordChange`),!1),await Pn(re(ie,`users/${t.uid}/passwordChangedAt`),I),await Pn(re(ie,`users/${t.uid}/updatedAt`),I);try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"user.password_changed",entityType:"user",entityId:t.uid,branchId:t.branchId,summary:`${t.name} changed password`})}catch(_){console.warn("Password change audit log failed:",_)}a({...t,forcePasswordChange:!1,passwordChangedAt:I,updatedAt:I}),n&&(sessionStorage.setItem("verixoPasswordChangeNotice","Password updated successfully. নতà§à¦¨ password দিà§à§ à¦à¦¬à¦¾à¦° Sign in à¦à¦°à§à¦¨à¥¤"),await dl(Ti))}catch(R){const I=R instanceof Error?R.message:"Password change failed";I.includes("wrong-password")||I.includes("invalid-credential")?y("Current password সঠিঠনà§à¥¤"):I.includes("requires-recent-login")||I.includes("user-token-expired")?y("Security session পà§à¦°à¦¾à¦¤à¦¨ হà§à§ à¦à§à¦à§à¥¤ Sign out à¦à¦°à§ temporary/current password দিà§à§ à¦à¦¬à¦¾à¦° Sign in à¦à¦°à§à¦¨, তারপর নতà§à¦¨ password সà§à¦ à¦à¦°à§à¦¨à¥¤"):I.includes("weak-password")?y("à¦à¦°à¦ শà¦à§à¦¤à¦¿à¦¶à¦¾à¦²à§ password বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤"):I.includes("network-request-failed")?y("Network connection check à¦à¦°à§ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤"):I.includes("PERMISSION_DENIED")?y("Password update হà§à§à¦à§, à¦à¦¿à¦¨à§à¦¤à§ VERIXO security state sync হà§à¦¨à¦¿à¥¤ নতà§à¦¨ password দিà§à§ Sign out/Sign in à¦à¦°à§ à¦à¦¬à¦¾à¦° Set new password à¦à¦¾à¦ªà§à¦¨âsystem recovery mode-ঠstate sync à¦à¦°à¦¬à§à¥¤ সমসà§à¦¯à¦¾ থাà¦à¦²à§ Admin-à¦à§ database rules deploy à¦à¦°à¦¤à§ হবà§à¥¤"):y(I)}finally{g(!1)}},N=async()=>{try{await dl(Ti)}catch(w){console.error("Sign out failed:",w)}};return e.jsx("div",{className:"modal-backdrop password-change-backdrop",children:e.jsxs("section",{className:"modal-card password-change-card",children:[e.jsxs("div",{className:"modal-title",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Account Security"}),e.jsx("h2",{children:n?"Create your new password":"Change password"})]}),!n&&s&&e.jsx("button",{className:"icon-button",onClick:s,children:e.jsx(ja,{size:18})})]}),e.jsx("p",{children:n?"Temporary password দিà§à§ Sign in সফল হà§à§à¦à§à¥¤ à¦à¦à¦¨ à¦à¦à¦à¦¿ নতà§à¦¨ personal password তà§à¦°à¦¿ à¦à¦°à§à¦¨à¥¤":"à¦à¦ªà¦¨à¦¾à¦° VERIXO login password পরিবরà§à¦¤à¦¨ à¦à¦°à§à¦¨à¥¤"}),e.jsxs("form",{onSubmit:b,className:"data-form",children:[!n&&e.jsxs("label",{children:["Current password",e.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),required:!0})]}),e.jsxs("label",{children:["New password",e.jsx("input",{type:"password",value:l,onChange:w=>m(w.target.value),minLength:8,autoComplete:"new-password",required:!0})]}),e.jsxs("label",{children:["Confirm password",e.jsx("input",{type:"password",value:d,onChange:w=>u(w.target.value),minLength:8,autoComplete:"new-password",required:!0})]}),e.jsx("small",{children:"Minimum 8 characters; uppercase, lowercase à¦à¦¬à¦ number থাà¦à¦¤à§ হবà§à¥¤"}),p&&e.jsx("p",{className:"form-error",children:p}),e.jsxs("div",{className:"form-actions",children:[!n&&s&&e.jsx("button",{type:"button",className:"secondary-button",onClick:s,children:"Cancel"}),n&&e.jsx("button",{type:"button",className:"secondary-button",onClick:N,disabled:f,children:"Sign out"}),e.jsxs("button",{type:"submit",disabled:f,children:[e.jsx(Gh,{size:17})," ",f?"Updating...":n?"Set new password":"Update password"]})]})]})]})})}function HU({companySlug:t}){const[n,a]=x.useState(""),[s,i]=x.useState(""),[c,l]=x.useState(""),[m,d]=x.useState(!1),[u,f]=x.use
4150State(()=>{const w=sessionStorage.getItem("verixoPasswordChangeNotice")||"";return w&&sessionStorage.removeItem("verixoPasswordChangeNotice"),w}),[g,p]=x.useState(null),[y,b]=x.useState(!!t);x.useEffect(()=>{if(!t){b(!1);return}let w=!0;return mn(re(ie,`companyDirectory/${t}`)).then(C=>{if(!w)return;const R=C.exists()?C.val():null;if(!(R!=null&&R.id)){p(R);return}mn(re(ie,`subscriptions/${R.id}`)).then(I=>{if(!w)return;const _=I.exists()?I.val()||{}:{};p({...R,plan:R.plan||_.plan||"",subscriptionExpiry:R.subscriptionExpiry||_.expiryDate||""})}).catch(()=>{w&&p(R)})}).catch(()=>{w&&p(null)}).finally(()=>{w&&b(!1)}),()=>{w=!1}},[t]);const N=async w=>{if(w.preventDefault(),t&&(!g||!g.active)){l(g&&!g.active?"à¦à¦ Company workspace বরà§à¦¤à¦®à¦¾à¦¨à§ suspended.":"Company workspace পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ Login link check à¦à¦°à§à¦¨à¥¤");return}const C=new Date().toISOString().slice(0,10);if(t&&(g!=null&&g.subscriptionExpiry)&&C>g.subscriptionExpiry){l(`à¦à¦ Company workspace-à¦à¦° Trial/Subscription ${g.subscriptionExpiry} তারিà¦à§ শà§à¦· হà§à§à¦à§à¥¤ Super Admin-à¦à¦° সাথৠযà§à¦à¦¾à¦¯à§à¦ à¦à¦°à§à¦¨à¥¤`);return}d(!0),l(""),f("");try{await XM(Ti,ek),await GM(Ti,n.trim(),s)}catch{l("Login failed. Email à¦
থবা password check à¦à¦°à§à¦¨à¥¤")}finally{d(!1)}};return e.jsxs("main",{className:"login-page",children:[e.jsxs("section",{className:"login-panel",children:[e.jsx("div",{className:"brand-lockup login-brand-lockup",children:e.jsx("img",{className:"login-brand-icon",src:"/verixo-logo.svg",alt:"VERIXO"})}),e.jsxs("div",{className:"login-copy",children:[e.jsx("p",{className:"eyebrow",children:"Secure workspace"}),e.jsx("h1",{children:g?`Sign in to ${g.name}`:"Sign in to manage every branch."}),e.jsx("p",{children:g?"Secure company workspace â service jobs, users and branch data remain isolated.":"Service jobs, technicians, payments and branch performanceâà¦à¦ à¦à¦¾à§à¦à¦¾ থà§à¦à§à¥¤"})]}),u&&e.jsx("p",{className:"form-success",children:u}),e.jsxs("form",{onSubmit:N,children:[t&&e.jsxs("label",{children:["Company",e.jsx("input",{value:y?"Loading company...":g?`${g.name}${g.active?"":" â Suspended"}`:`Company not found: ${t}`,readOnly:!0,disabled:!0})]}),e.jsxs("label",{children:["Email address",e.jsx("input",{type:"email",value:n,onChange:w=>a(w.target.value),required:!0})]}),e.jsxs("label",{children:["Password",e.jsx("input",{type:"password",value:s,onChange:w=>i(w.target.value),minLength:6,required:!0})]}),c&&e.jsx("div",{className:"error",children:c}),e.jsx("button",{type:"submit",disabled:m||y||!!(t&&(!g||!g.active)),children:m?"Signing in...":"Sign in"}),e.jsxs("a",{className:"login-app-download",href:p2[0],onClick:w=>{w.preventDefault(),WE()},"aria-label":"Download VERIXO Android App APK",children:[e.jsx(Mi,{size:17}),"Download Android App"]}),t&&e.jsxs("small",{className:"company-login-help",children:["Workspace: /",t]}),e.jsxs("div",{className:"login-powered-by",children:[e.jsx("img",{src:"/verixo-icon.svg",alt:""}),e.jsx("span",{children:"Powered by VERIXO ERP"})]})]})]}),e.jsxs("aside",{className:"login-visual",children:[e.jsx("div",{className:"visual-orbit one"}),e.jsx("div",{className:"visual-orbit two"}),e.jsxs("div",{className:"visual-card",children:[e.jsx("span",{children:"Live operational view"}),e.jsx("strong",{children:"Multi-Branch"}),e.jsx("p",{children:"Owner dashboard updates from every service desk."})]})]})]})}function l5({message:t="Loading applicationâ¦"}){return e.jsx("div",{className:"loading",children:t})}function Fb(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}function WU({user:t,onComplete:n}){const[a,s]=x.useState(1),[i,c]=x.useState(!1),[l,m]=x.useState(""),[d,u]=x.useState({companyName:"",ownerName:"",phone:"",email:t.email??"",address:"Dhaka, Bangladesh"}),[f,g]=x.useState({branchName:"Main Branch",branchCode:"MAIN-01",managerName:"",phone:"",address:"Dhaka, Bangladesh"}),p=b=>{b.preventDefault(),g(N=>({...N,managerName:N.managerName||d.ownerName,phone:N.phone||d.phone,address:N.address||d.address})),s(2)},y=async b=>{b.preventDefault(),c(!0),m("");const N=`company_${t.uid.slice(0,12)}`,w=Fb(d.companyName)||N.toLowerCase(),C=`branch_${Date.now()}`,R={uid:t.uid,name:d.ownerName.trim(),email:d.email.trim(),role:"owner",companyId:N,branchId:C,active:!0};try{await Pn(re(ie,`users/${t.uid}`),{...R,setupCompleted:!1,createdAt:Date.now()}),await Pn(re(ie,`companies/${N}`),{id:N,name:d.companyName.trim(),slug:w,phone:d.phone.trim(),email:d.email.trim(),address:d.address.trim(),ownerUid:t.uid,active:!0,createdAt:Date.now(),updatedAt:Date.now()}),await Pn(re(ie,`companyDirectory/${w}`),{id:N,name:d.companyName.trim(),slug:w,phone:d.phone.trim(),address:d.address.trim(),logoUrl:"",active:!0}),await Pn(re(ie,`branches/${N}/${C}`),{id:C,companyId:N,name:f.branchName.trim(),code:f.branchCode.trim().toUpperCase(),managerName:f.managerName.trim(),phone:f.phone.trim(),address:f.address.trim(),active:!0,createdAt:Date.now(),updatedAt:Date.now()}),await Pn(re(ie,`dashboardStats/${N}`),{todayReceived:0,pendingJobs:0,readyForDelivery:0,deliveredToday:0,totalCustomers:0,todayCollection:0,totalDue:0}),await Pn(re(ie,`settings/${N}`),{currency:"BDT",timezone:"Asia/Dhaka",country:"Bangladesh",dateFormat:"DD/MM/YYYY",createdAt:Date.now()}),await yn(re(ie,`users/${t.uid}`),{setupCompleted:!0,updatedAt:Date.now()}),n(R)}catch(I){console.error(I),m("Setup complete à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ Realtime Database Rules publish হà§à§à¦à§ à¦à¦¿ না check à¦à¦°à§à¦¨à¥¤")}finally{c(!1)}};
4150return e.jsx("main",{className:"setup-wizard-page",children:e.jsxs("section",{className:"setup-wizard-card",children:[e.jsxs("div",{className:"wizard-top",children:[e.jsx("div",{className:"brand-mark",children:e.jsx(TD,{size:25})}),e.jsxs("div",{className:"wizard-progress",children:[e.jsx("span",{className:"active",children:"1"}),e.jsx("i",{}),e.jsx("span",{className:a===2?"active":"",children:"2"})]})]}),a===1?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"eyebrow",children:"Initial setup"}),e.jsx("h1",{children:"Create your company"}),e.jsx("p",{className:"wizard-description",children:"Company ঠowner information দিন।"}),e.jsxs("form",{onSubmit:p,className:"data-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Company name",e.jsx("input",{value:d.companyName,onChange:b=>u({...d,companyName:b.target.value}),required:!0})]}),e.jsxs("label",{children:["Owner name",e.jsx("input",{value:d.ownerName,onChange:b=>u({...d,ownerName:b.target.value}),required:!0})]}),e.jsxs("label",{children:["Mobile number",e.jsx("input",{value:d.phone,onChange:b=>u({...d,phone:b.target.value}),required:!0})]}),e.jsxs("label",{children:["Email",e.jsx("input",{type:"email",value:d.email,onChange:b=>u({...d,email:b.target.value}),required:!0})]}),e.jsxs("label",{className:"full-field",children:["Address",e.jsx("textarea",{rows:3,value:d.address,onChange:b=>u({...d,address:b.target.value}),required:!0})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>dl(Ti),children:"Sign out"}),e.jsx("button",{type:"submit",children:"Next"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"eyebrow",children:"Default branch"}),e.jsx("h1",{children:"Create your first branch"}),e.jsx("p",{className:"wizard-description",children:"à¦à¦ branch à¦à¦ªà¦¨à¦¾à¦° initial service location হবà§à¥¤"}),e.jsxs("form",{onSubmit:y,className:"data-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Branch name",e.jsx("input",{value:f.branchName,onChange:b=>g({...f,branchName:b.target.value}),required:!0})]}),e.jsxs("label",{children:["Branch code",e.jsx("input",{value:f.branchCode,onChange:b=>g({...f,branchCode:b.target.value.toUpperCase()}),required:!0})]}),e.jsxs("label",{children:["Manager name",e.jsx("input",{value:f.managerName,onChange:b=>g({...f,managerName:b.target.value}),required:!0})]}),e.jsxs("label",{children:["Phone",e.jsx("input",{value:f.phone,onChange:b=>g({...f,phone:b.target.value}),required:!0})]}),e.jsxs("label",{className:"full-field",children:["Address",e.jsx("textarea",{rows:3,value:f.address,onChange:b=>g({...f,address:b.target.value}),required:!0})]})]}),l&&e.jsx("div",{className:"error wizard-error",children:l}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>s(1),children:"Back"}),e.jsxs("button",{type:"submit",disabled:i,children:[e.jsx(hr,{size:17})," ",i?"Creating...":"Create workspace"]})]})]})]})]})})}function GU({companyId:t,companyName:n,profile:a,selectedBranchId:s,branches:i,onNavigate:c}){const[l,m]=x.useState({}),[d,u]=x.useState([]),[f,g]=x.useState([]);x.useEffect(()=>{const ae=s==="all"?`dashboardStats/${t}`:`dashboardStats/${t}/branches/${s}`,Y=re(ie,ae);let je=!1,V=!1;const $=qt(Y,async F=>{const P=F.exists()?F.val():{},ue=new Date,me=`${ue.getFullYear()}-${String(ue.getMonth()+1).padStart(2,"0")}-${String(ue.getDate()).padStart(2,"0")}`,ge=me.slice(0,7);if(Number(P.schemaVersion||0)>=2&&P.aggregateReady===!0){const de={...P};P.aggregateDay!==me&&(de.todayReceived=0,de.deliveredToday=0,de.todayCollection=0,de.aggregateDay=me),P.aggregateMonth!==ge&&(de.monthlyCollection=0,de.totalInvoiceValue=0,de.aggregateMonth=ge),(de.aggregateDay!==P.aggregateDay||de.aggregateMonth!==P.aggregateMonth)&&yn(Y,de),je||m(de);return}if(!V){V=!0;try{const[de,Pe,Re,Ee]=await Promise.all([mn(re(ie,`serviceJobs/${t}`)),mn(re(ie,`customers/${t}`)),mn(re(ie,`invoices/${t}`)),mn(re(ie,`collections/${t}`))]);if(je)return;const Be=de.exists()?Object.entries(de.val()).map(([Ce,De])=>({id:Ce,...De,status:Qh(De.status)})):[],We=Pe.exists()?Object.entries(Pe.val()).map(([Ce,De])=>({id:Ce,...De})):[],it=Re.exists()?Object.entries(Re.val()).map(([Ce,De])=>({id:Ce,...De})):[],_e=Ee.exists()?Object.entries(Ee.val()).map(([Ce,De])=>({id:Ce,...De})):[],ee=Ce=>s==="all"||Ce===s,qe=Be.filter(Ce=>ee(Ce.branchId)),se=We.filter(Ce=>ee(Ce.branchId)),pe=it.filter(Ce=>ee(Ce.branchId)),Se=_e.filter(Ce=>ee(Ce.branchId)),Me=new Date,ot=Ce=>!!Ce&&new Date(Ce).getFullYear()===Me.getFullYear()&&new Date(Ce).getMonth()===Me.getMonth()&&new Date(Ce).getDate()===Me.getDate(),wt=Ce=>!!Ce&&new Date(Ce).getFullYear()===Me.getFullYear()&&new Date(Ce).getMonth()===Me.getMonth(),ct={schemaVersion:2,aggregateReady:!0,aggregateDay:`${Me.getFullYear()}
4150-${String(Me.getMonth()+1).padStart(2,"0")}-${String(Me.getDate()).padStart(2,"0")}`,aggregateMonth:`${Me.getFullYear()}-${String(Me.getMonth()+1).padStart(2,"0")}`,todayReceived:qe.filter(Ce=>ot(Ce.createdAt)).length,pendingJobs:qe.filter(Ce=>!["ready","delivered","closed","cancelled"].includes(Ce.status)).length,inProgressJobs:qe.filter(Ce=>["diagnosing","approved","repairing","quality_check","qc_completed"].includes(Ce.status)).length,readyForDelivery:qe.filter(Ce=>Ce.status==="ready").length,deliveredToday:qe.filter(Ce=>["delivered","closed"].includes(Ce.status)&&ot(Ce.deliveredAt||Ce.updatedAt)).length,waitingApproval:qe.filter(Ce=>Ce.status==="waiting_approval").length,totalCustomers:se.length,todayCollection:Se.filter(Ce=>ot(Ce.collectedAt||Ce.createdAt)).reduce((Ce,De)=>Ce+Number(De.amount||0),0),monthlyCollection:Se.filter(Ce=>wt(Ce.collectedAt||Ce.createdAt)).reduce((Ce,De)=>Ce+Number(De.amount||0),0),totalDue:pe.reduce((Ce,De)=>Ce+Number(De.dueAmount||0),0),totalInvoiceValue:pe.filter(Ce=>wt(Ce.createdAt)).reduce((Ce,De)=>Ce+Number(De.grandTotal||0),0),invoiceCount:pe.length,updatedAt:Date.now()};await yn(Y,ct),je||m(ct)}catch(de){console.warn("Dashboard aggregate bootstrap failed:",de),je||m(P)}finally{V=!1}}});return()=>{je=!0,$()}},[t,s]),x.useEffect(()=>{const ae=new Date;ae.setHours(0,0,0,0),ae.setDate(ae.getDate()-6);const Y=Vl(re(ie,`serviceJobs/${t}`),ql("createdAt"),g4(ae.getTime()));return qt(Y,je=>{const V=je.exists()?Object.entries(je.val()).map(([$,F])=>({id:$,...F,status:Qh(F.status)})).sort(($,F)=>Number(F.createdAt||0)-Number($.createdAt||0)):[];u(V)})},[t]),x.useEffect(()=>{const ae=Vl(re(ie,`auditLogs/${t}`),ql("createdAt"),jD(12));return qt(ae,Y=>{const je=Y.exists()?Y.val():{};g(Object.entries(je).map(([V,$])=>({id:V,...$})).sort((V,$)=>Number($.createdAt||0)-Number(V.createdAt||0)))})},[t]);const p=ae=>s==="all"||ae===s,y=x.useMemo(()=>d.filter(ae=>p(ae.branchId)),[d,s]),b=x.useMemo(()=>f.filter(ae=>p(ae.branchId)).slice(0,6),[f,s]),N=Number(l.todayReceived||0),w=Number(l.pendingJobs||0),C=Number(l.inProgressJobs||0),R=Number(l.readyForDelivery||0),I=Number(l.deliveredToday||0),_=Number(l.waitingApproval||0),J=Number(l.todayCollection||0),T=Number(l.monthlyCollection||0),G=Number(l.totalDue||0),z=Number(l.totalInvoiceValue||0),H=[{label:"Today Received",value:String(N),note:"New service jobs today",trend:"Live",tone:"blue"},{label:"Pending Jobs",value:String(w),note:"Requires attention",trend:String(C),tone:"amber"},{label:"Ready for Delivery",value:String(R),note:"Customer notification due",trend:"Live",tone:"green"},{label:"Delivered Today",value:String(I),note:"Completed today",trend:"Live",tone:"violet"},{label:"Total Customers",value:String(Number(l.totalCustomers||0)),note:"Registered customers",trend:"Live",tone:"blue"},{label:"Today Collection",value:`à§³${J.toLocaleString()}`,note:"Collected today",trend:"Live",tone:"green"},{label:"Total Due",value:`à§³${G.toLocaleString()}`,note:"Outstanding invoices",trend:String(Number(l.invoiceCount||0)),tone:"red"},{label:"Monthly Collection",value:`à§³${T.toLocaleString()}`,note:`Invoice value à§³${z.toLocaleString()}`,trend:"MTD",tone:"violet"}],K=a.role==="super_admin"||a.role==="owner"||a.role==="admin"||a.role==="branch_manager"?"management":a.role==="accountant"?"accounts":a.role==="sales"?"sales":a.role==="store"?"inventory":a.role==="hr"?"hr":"service",L=K==="management"?H:K==="accounts"?H.filter(ae=>["Today Collection","Total Due","Monthly Collection","Total Customers"].includes(ae.label)):K==="sales"?H.filter(ae=>["Total Customers","Today Collection","Total Due","Monthly Collection"].includes(ae.label)):K==="inventory"?H.filter(ae=>["Total Customers","Total Due","Pending Jobs","Ready for Delivery"].includes(ae.label)):K==="hr"?H.filter(ae=>["Today Received","Pending Jobs","Delivered Today","Total Customers"].includes(ae.label)):H.slice(0,4),D=x.useMemo(()=>{const ae=Array.from({length:7},(je,V)=>{const $=new Date;$.setHours(0,0,0,0),$.setDate($.getDate()-(6-V));const F=new Date($);F.setDate(F.getDate()+1);const P=y.filter(ue=>Number(ue.createdAt)>=$.getTime()&&Number(ue.createdAt)<F.getTime()).length;return{label:$.toLocaleDateString("en-US",{weekday:"short"}),count:P}}),Y=Math.max(...ae.map(je=>je.count),1);return ae.map(je=>({...je,height:Math.max(12,Math.round(je.count/Y*100))}))},[y]),M=y.slice(0,5),Z=ae=>{if(!ae)return"â";const Y=Math.max(0,Math.floor((Date.now()-ae)/1e3));return Y<60?"Now":Y<3600?`${Math.floor(Y/60)}m ago`:Y<86400?`${Math.floor(Y/3600)}h ago`:Y<604800?`${Math.floor(Y/86400)}d ago`:new Date(ae).toLocaleDateString()},fe=ae=>({"customer.created":"Customer created","customer.updated":"Customer updated","job.created":"Service job received","job.updated":"Service job updated","job.status_changed":"Job status changed","estimate.created":"Estimate created","estimate.updated":"Estimate updated","invoice.created":"Invoice created","collection.recorded":"Collection recorded","employee.created":"Employee created","user.created":"Login user created","company.updated":"Company updated"})[ae||""]||"Workspace activity";if(K==="management")return e.jsx(z7,{profile:a,summary:l,selectedBranchId:s,branches:i,onNavigate:c});const q=Number(new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Dhaka",hour:"2-digit",hourCycle:"h23"}).format(new Date)),ne=q>=5&&q<12?"Good morning":q>=12&&q<17?"Good afternoon":q>=17&&q<21?"Good evening":"Good night";return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"hero-banner",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:n.toUpperCase()}),e.jsxs("h1",{children:[ne," ð"]}),e.jsxs("h2",{className:"dashboard-welcome-name",children:["Welcome back, ",a.name]}),e.jsx("p",{children:`${K[0].toUpperCase()+K.slice(1)} dashboard · only your role-relevant operational view.`})]}),e.jsxs("div",{className:"hero-summary",children:[e.jsx("span",{children:"Today collection"}
4150),e.jsxs("strong",{children:["৳",J.toLocaleString()]}),e.jsxs("small",{children:[w," jobs need attention",_>0?` · ${_} waiting approval`:""]})]})]}),e.jsxs("div",{className:"page-heading enterprise-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:`${K[0].toUpperCase()+K.slice(1)} Dashboard`}),e.jsxs("p",{children:["Real-time data from the current"," ",s==="all"?"company":"branch","."]})]}),e.jsxs("div",{className:"heading-actions",children:[e.jsxs("button",{className:"secondary-action",onClick:()=>c("customers"),children:[e.jsx(mc,{size:17})," Customers"]}),e.jsxs("button",{className:"primary-action",onClick:()=>c("serviceJobs"),children:[e.jsx(as,{size:18})," New Service Job"]})]})]}),e.jsx("div",{className:"metric-grid enterprise-metrics live-metric-grid",children:L.map(ae=>e.jsxs("article",{className:`metric-card tone-${ae.tone}`,children:[e.jsxs("div",{className:"metric-topline",children:[e.jsx("span",{children:ae.label}),e.jsx("b",{children:ae.trend})]}),e.jsx("strong",{children:ae.value}),e.jsx("small",{children:ae.note}),e.jsxs("div",{className:"mini-sparkline",children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]})]},ae.label))}),e.jsxs("section",{className:"dashboard-live-grid",children:[e.jsxs("article",{className:"panel live-trend-panel",children:[e.jsxs("div",{className:"panel-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"7-day service trend"}),e.jsx("p",{children:"Jobs received during the last seven days"})]}),e.jsx("span",{className:"panel-badge live-badge",children:"Live"})]}),e.jsx("div",{className:"dashboard-trend-chart",children:D.map(ae=>e.jsxs("div",{className:"dashboard-trend-column",children:[e.jsx("strong",{children:ae.count}
4150),e.jsx("span",{style:{height:`${ae.height}%`}}),e.jsx("small",{children:ae.label})]},ae.label))})]}),e.jsxs("article",{className:"panel live-workload-panel",children:[e.jsx("div",{className:"panel-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Current workload"}),e.jsx("p",{children:"Live service pipeline"})]})}),e.jsxs("div",{className:"workload-list",children:[e.jsxs("div",{children:[e.jsx("span",{children:"In progress"}),e.jsx("strong",{children:C})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Waiting approval"}),e.jsx("strong",{children:_})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Ready delivery"}),e.jsx("strong",{children:R})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total due"}),e.jsxs("strong",{children:["৳",G.toLocaleString()]})]})]})]})]}),e.jsxs("section",{className:"dashboard-live-grid lower-live-grid",children:[e.jsxs("article",{className:"panel",children:[e.jsxs("div",{className:"panel-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Recent service jobs"}),e.jsx("p",{children:"Latest jobs in the current workspace"})]}),e.jsx("button",{className:"text-button",onClick:()=>c("serviceJobs"),children:"View all"})]}),M.length===0?e.jsxs("div",{className:"empty-state compact-empty",children:[e.jsx(ND,{size:32}),e.jsx("h3",{children:"No service jobs yet"}),e.jsx("p",{children:"Create the first service job to activate this dashboard."})]}):e.jsx("div",{className:"recent-job-list",children:M.map(ae=>e.jsxs("button",{type:"button",onClick:()=>c("serviceJobs"),children:[e.jsxs("div",{children:[e.jsx("strong",{children:ae.jobNumber}),e.jsxs("span",{children:[ae.deviceCategory,ae.brand?` · ${ae.brand}`:"",ae.model?` ${ae.model}`:""]})]}),e.jsxs("div",{children:[e.jsx("b",{children:Dr(ae.status)}),e.jsx("small",{children:Z(ae.createdAt)})]})]},ae.id))})]}),e.jsxs("article",{className:"panel",children:[e.jsx("div",{className:"panel-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Recent activity"}),e.jsx("p",{children:"Latest actions in your workspace"})]})}),b.length===0?e.jsxs("div",{className:"empty-state compact-empty",children:[e.jsx(Qw,{size:30}),e.jsx("h3",{children:"No activity yet"}),e.jsx("p",{children:"New actions will appear here automatically."})]}):e.jsx("div",{className:"activity-feed live-activity-feed",children:b.map((ae,Y)=>e.jsxs("article",{children:[e.jsx("span",{className:`activity-dot ${Y%3===0?"blue":Y%3===1?"green":"amber"}`}),e.jsxs("div",{children:[e.jsx("strong",{children:fe(ae.action)}),e.jsx("small",{children:ae.summary||`Updated by ${ae.actorName||"User"}`})]}),e.jsx("time",{children:Z(ae.createdAt)})]},ae.id))})]})]}),e.jsxs("section",{className:"quick-actions-panel dashboard-quick-actions",children:[e.jsx("div",{className:"section-heading-row",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Quick actions"}),e.jsx("p",{children:"Frequently used operations"})]})}),e.jsxs("div",{className:"quick-action-grid",children:[e.jsxs("button",{type:"button",onClick:()=>c("serviceJobs"),children:[e.jsx("span",{children:e.jsx(as,{size:18})}),"New Service Job"]}),e.jsxs("button",{type:"button",onClick:()=>c("customers"),children:[e.jsx("span",{children:e.jsx(e2,{size:18})}),"New Customer"]}),e.jsxs("button",{type:"button",onClick:()=>c("estimates"),children:[e.jsx("span",{children:e.jsx(Zs,{size:18})}),"Estimate"]}),a.role!=="service_incharge"&&e.jsxs("button",{type:"button",onClick:()=>c("collections"),children:[e.jsx("span",{children:e.jsx(Ll,{size:18})}),"Collection"]})]})]})]})}function YU({profile:t,branches:n,selectedBranchId:a,initialCustomerId:s,onInitialCustomerHandled:i}){const[c,l]=x.useState([]),[m,d]=x.useState(!1),[u,f]=x.useState(null),[g,p]=x.useState({...o5,branchId:""}),[y,b]=x.useState(!1),[N,w]=x.useState(""),C=sa(t,"customer.manage");x.useEffect(()=>{const z=re(ie,`customers/${t.companyId}`);return qt(z,H=>{if(!H.exists()){l([]);return}const K=H.val();l(Object.entries(K).map(([L,D])=>({id:L,...D})).sort((L,D)=>D.createdAt-L.createdAt))})},[t.companyId]),x.useEffect(()=>{if(!s||!c.length)return;const z=c.find(H=>H.id===s);z&&(w(z.phone||z.name),i==null||i())},[s,c,i]),x.useEffect(()=>{const z=Date.now();yn(re(ie,`dashboardStats/${t.companyId}`),{schemaVersion:2,totalCustomers:c.length,updatedAt:z});const H=new Map;
4150c.forEach(K=>{K.branchId&&H.set(K.branchId,(H.get(K.branchId)||0)+1)}),H.forEach((K,L)=>{yn(re(ie,`dashboardStats/${t.companyId}/branches/${L}`),{schemaVersion:2,totalCustomers:K,updatedAt:z})})},[c,t.companyId]);const R=x.useMemo(()=>{const z=N.trim().toLowerCase();return c.filter(H=>z?[H.name,H.phone,H.whatsapp,H.email,H.address].some(K=>K==null?void 0:K.toLowerCase().includes(z)):!0)},[c,N,a]),I=()=>{f(null),p({...o5,branchId:""}),d(!0)},_=z=>{f(z),p({name:z.name,phone:z.phone,whatsapp:z.whatsapp??"",email:z.email??"",address:z.address??"",notes:z.notes??"",dueAmount:Number(z.dueAmount||0),active:z.active,branchId:z.branchId}),d(!0)},J=()=>{d(!1),f(null)},T=async z=>{z.preventDefault(),b(!0);try{const H={...g,dueAmount:Number(g.dueAmount||0)};if(u)await yn(re(ie,`customers/${t.companyId}/${u.id}`),{...H,companyId:t.companyId,updatedAt:Date.now()}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"customer.updated",entityType:"customer",entityId:u.id,branchId:g.branchId,summary:`Updated customer ${g.name}`});else{const K=Ta(re(ie,`customers/${t.companyId}`));await Pn(K,{...g,id:K.key,companyId:t.companyId,createdAt:Date.now(),updatedAt:Date.now()}),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"customer.created",entityType:"customer",entityId:K.key??"",branchId:g.branchId,summary:`Created customer ${g.name}`})}J()}finally{b(!1)}},G=async z=>{window.confirm(`${z.name} customer delete à¦à¦°à¦¬à§à¦¨?`)&&(await Ao(re(ie,`customers/${t.companyId}/${z.id}`)),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"customer.deleted",entityType:"customer",entityId:z.id,branchId:z.branchId,summary:`Deleted customer ${z.name}`}))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Customer management"}),e.jsx("h1",{children:"Customers"}),e.jsx("p",{children:"Customer profile, contact, due à¦à¦¬à¦ service history foundation."})]}),e.jsxs("button",{className:"primary-action",onClick:I,disabled:!C,children:[e.jsx(e2,{size:18})," Add customer"]})]}),e.jsxs("section",{className:"panel",children:[e.jsxs("div",{className:"customer-toolbar",children:[e.jsxs("div",{className:"customer-search",children:[e.jsx(xr,{size:18}),e.jsx("input",{value:N,onChange:z=>w(z.target.value),placeholder:"Search by name, phone, WhatsApp or email"})]}),e.jsxs("span",{children:[R.length," customer found"]})]}),R.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx(mc,{size:35}),e.jsx("h3",{children:"No customer found"}),e.jsx("p",{children:"পà§à¦°à¦¥à¦® customer যà§à¦ à¦à¦°à¦²à§ Dashboard live update হবà§à¥¤"})]}):e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Phone"}),e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Due"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:R.map(z=>e.jsxs("tr",{className:s===z.id?"customer-search-target":void 0,children:[e.jsxs("td",{children:[e.jsx("strong",{children:z.name}),e.jsx("small",{className:"table-subtext",children:z.email||z.address||"No extra information"})]}),e.jsxs("td",{children:[z.phone,z.whatsapp&&e.jsxs("small",{className:"table-subtext",children:["WhatsApp: ",z.whatsapp]})]}),e.jsx("td",{children:"All Branches"}),e.jsxs("td",{children:["à§³",Number(z.dueAmount||0).toLocaleString()]}),e.jsx("td",{children:e.jsx("span",{className:`status ${z.active?"":"inactive"}`,children:z.active?"Active":"Inactive"})}),e.jsx("td",{children:e.jsxs("div",{className:"row-actions",children:[e.jsx("button",{onClick:()=>_(z),children:e.jsx(Zi,{size:16})}),e.jsx("button",{onClick:()=>G(z),children:e.jsx(po,{size:16})})]})})]},z.id))})]})})]}),m&&e.jsx("div",{className:"modal-backdrop",onMouseDown:J,children:e.jsxs("section",{className:"modal customer-modal",onMouseDown:z=>z.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:u?"Update customer":"New customer"}),e.jsx("h2",{children:u?"Edit customer":"Add customer"})]}),e.jsx("button",{onClick:J,children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:T,className:"data-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Customer name",e.jsx("input",{value:g.name,onChange:z=>p({...g,name:z.target.value}),required:!0})]}),e.jsxs("label",{children:["Mobile number",e.jsx("input",{value:g.phone,onChange:z=>p({...g,phone:z.target.value}),required:!0})]}),e.jsxs("label",{children:["WhatsApp",e.jsx("input",{value:g.whatsapp,onChange:z=>p({...g,whatsapp:z.target.value})})]}),e.jsxs("label",{children:["Email",e.jsx("input",{type:"email",value:g.email,onChange:z=>p({...g,email:z.target.value})})]}),e.jsxs("label",{children:["Customer scope",e.jsx("input",{value:"All Branches · Company-wide",readOnly:!0})]}),e.jsxs("label",{children:["Opening due",e.jsx("input",{type:"number",min:"0",step:"0.01",value:g.dueAmount,onChange:z=>p({...g,dueAmount:Number(z.target.value)})})]}),e.jsxs("label",{className:"full-field",children:["Address",e.jsx("textarea",{rows:3,value:g.address,onChange:z=>p({...g,address:z.target.value})})]}),e.jsxs("label",{className:"full-field",children:["Notes",e.jsx("textarea",{rows:3,value:g.notes,onChange:z=>p({...g,notes:z.target.value})})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:g.active?"active":"inactive",onChange:z=>p({...g,active:z.target.value==="active"}),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:J,children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:y,children:[e.jsx(hr,{size:17})," ",y?"Saving...":"Save customer"]})]})]})]})})]})}function QU({profile:t,branches:n,selectedBranchId:a,companyId:s,company:i,companyName:c,companyPhone:l,companyAddress:m,companyLogoUrl:d,initialJobId:u,onInitialJobHandled:f}){var Ln,wa,Ca,In,Sa,aa,$a,jn,vs,ka,Ja,_n,ha,ta;
4150const[g,p]=x.useState([]),[y,b]=x.useState([]),[N,w]=x.useState([]),[C,R]=x.useState([]),[I,_]=x.useState([]),[J,T]=x.useState(""),G=x.useMemo(()=>{const W=new Set(N.map(vt=>vt.id)),ft=new Set(N.map(vt=>vt.name.trim().toLowerCase())),Zt=vt=>{const Ae=Array.isArray(vt.roles)?vt.roles:[],oe=String(vt.designation||"").trim().toLowerCase();return Ae.map(he=>String(he||"").trim().toLowerCase()).includes("technician")||oe.includes("technician")};return[...N.filter(Zt),...I.filter(vt=>!W.has(vt.id)&&!ft.has(vt.name.trim().toLowerCase()))].sort((vt,Ae)=>vt.name.localeCompare(Ae.name))},[N,I]),[z,H]=x.useState(!1),[K,L]=x.useState(null),[D,M]=x.useState({...c5,branchId:a!=="all"?a:t.branchId??""}),[Z,fe]=x.useState(!1),[q,ne]=x.useState(""),[ae,Y]=x.useState("all"),[je,V]=x.useState("all"),[$,F]=x.useState("all"),[P,ue]=x.useState(null),[me,ge]=x.useState({onsiteDiagnosis:"",onsiteWorkDone:"",onsitePartsUsed:"",onsiteNextVisitRequired:!1,onsiteNextVisitAt:""}),[de,Pe]=x.useState("idle"),[Re,Ee]=x.useState(null);x.useEffect(()=>{P!=null&&P.id&&ge({onsiteDiagnosis:P.onsiteDiagnosis||"",onsiteWorkDone:P.onsiteWorkDone||"",onsitePartsUsed:P.onsitePartsUsed||"",onsiteNextVisitRequired:!!P.onsiteNextVisitRequired,onsiteNextVisitAt:P.onsiteNextVisitAt||""})},[P==null?void 0:P.id]),x.useEffect(()=>{if(!u||!g.length)return;const W=g.find(ft=>ft.id===u);W&&(ue(W),ne(W.jobNumber),f==null||f())},[u,g,f]);const[Be,We]=x.useState([]),[it,_e]=x.useState(""),[ee,qe]=x.useState(null),[se,pe]=x.useState(null),[Se,Me]=x.useState({serviceCharge:0,partsTotal:0,partsUsedDetails:"",discountAmount:0}),[ot,wt]=x.useState(null),[ct,Ce]=x.useState(null),[De,Te]=x.useState("repairable"),[ce,Ye]=x.useState(""),[Je,le]=x.useState({repairPerformed:"",partsReplaced:"",customPart:"",diagnosisCharge:0,repairCharge:0,installationCharge:0,otherServiceCharge:0,partsTotal:0,partsUsedDetails:"",customerServiceNotes:"",repairNotes:"",technicianCost:0,partsCost:0,outsideRepairCost:0,otherServiceCost:0,repairWarranty:"none"}),[nt,xt]=x.useState({boot:"pass",operatingSystem:"pass",driver:"pass",motherboard:"pass",ram:"pass",storage:"pass",display:"pass",keyboard:"pass",mouseTouchpad:"pass",usb:"pass",audio:"pass",network:"pass",wifi:"pass",bluetooth:"na",webcam:"na",battery:"na",charger:"na",bios:"pass",stress:"pass",remarks:""}),te=sa(t,"job.manage"),Ge=["technician","service_incharge","branch_manager","manager","admin","owner","super_admin"].includes(t.role),pt=["service_incharge","branch_manager","manager","admin","owner","super_admin"].includes(t.role);x.useEffect(()=>{const W=re(ie,`serviceJobs/${t.companyId}`);return qt(W,ft=>{if(!ft.exists()){p([]),ue(null);return}const Zt=ft.val(),vt=Object.entries(Zt).map(([Ae,oe])=>({id:Ae,...oe,status:Qh(oe.status)})).sort((Ae,oe)=>oe.createdAt-Ae.createdAt);p(vt),ue(Ae=>Ae?vt.find(oe=>oe.id===Ae.id)??null:null)})},[t.companyId]),x.useEffect(()=>{const W=re(ie,`customers/${t.companyId}`);return qt(W,ft=>{if(!ft.exists()){b([]);return}const Zt=ft.val();b(Object.entries(Zt).map(([vt,Ae])=>({id:vt,...Ae})))})},[t.companyId]),x.useEffect(()=>{const W=re(ie,`employees/${t.companyId}`);return qt(W,ft=>{if(!ft.exists()){w([]);return}const Zt=ft.val();w(Object.entries(Zt).map(([vt,Ae])=>({id:vt,...Ae,roles:Ae.roles||[],technicianSkills:Ae.technicianSkills||[],source:"employee"})))})},[t.companyId]),x.useEffect(()=>{var vt,Ae;T("");const W=(vt=P==null?void 0:P.assignedBy)==null?void 0:vt.trim();if(!P||(Ae=P.assignedByName)!=null&&Ae.trim()||!W)return;if(W===t.uid){T(t.name);return}let ft=!1;return(async()=>{try{const oe=await mn(re(ie,`users/${W}`));if(ft||!oe.exists())return;const Ve=oe.val();if(Ve.companyId===t.companyId&&typeof Ve.name=="string"&&Ve.name.trim()){const he=Ve.name.trim();T(he);try{await yn(re(ie,`serviceJobs/${t.companyId}/${P.id}`),{assignedByName:he,assignedByUid:W,assignedBy:he})}catch(Oe){console.warn("Historical Assigned By self-heal failed:",Oe)}}}catch(oe){console.warn("Historical Assigned By lookup failed:",oe)}})(),()=>{ft=!0}},[P==null?void 0:P.id,P==null?void 0:P.assignedBy,P==null?void 0:P.assignedByName,t.companyId,t.uid,t.name]),x.useEffect(()=>{const W=re(ie,`technicians/${t.companyId}`);return qt(W,ft=>{if(!ft.exists()){_([]);return}const Zt=ft.val();_(Object.entries(Zt).map(([vt,Ae])=>({id:vt,companyId:Ae.companyId,branchId:Ae.branchId,employeeId:Ae.employeeId||"",name:Ae.name,phone:Ae.phone,email:Ae.email||"",department:"Service",designation:"Technician",roles:["technician"],technicianSkills:Ae.specialisations||[],joiningDate:Ae.joiningDate||"",notes:Ae.notes||"",active:Ae.active,createdAt:Ae.createdAt,updatedAt:Ae.updatedAt,source:"legacy_technician"})))})},[t.companyId]),x.useEffect(()=>{const W=new Date,ft=oe=>{const Ve=new Date(oe);return Ve.getFullYear()===W.getFullYear()&&Ve.getMonth()===W.getMonth()&&Ve.getDate()===W.getDate()},Zt=`${W.getFullYear()}
4150-${String(W.getMonth()+1).padStart(2,"0")}-${String(W.getDate()).padStart(2,"0")}`,vt=oe=>({schemaVersion:2,aggregateDay:Zt,todayReceived:oe.filter(Ve=>ft(Ve.createdAt)).length,pendingJobs:oe.filter(Ve=>!["ready","delivered","closed","cancelled"].includes(Ve.status)).length,inProgressJobs:oe.filter(Ve=>["diagnosing","approved","repairing","quality_check","qc_completed"].includes(Ve.status)).length,readyForDelivery:oe.filter(Ve=>Ve.status==="ready").length,deliveredToday:oe.filter(Ve=>["delivered","closed"].includes(Ve.status)&&ft(Ve.deliveredAt||Ve.updatedAt)).length,waitingApproval:oe.filter(Ve=>Ve.status==="waiting_approval").length,updatedAt:Date.now()});yn(re(ie,`dashboardStats/${t.companyId}`),vt(g)),Array.from(new Set(g.map(oe=>oe.branchId).filter(Boolean))).forEach(oe=>{yn(re(ie,`dashboardStats/${t.companyId}/branches/${oe}`),vt(g.filter(Ve=>Ve.branchId===oe)))})},[g,t.companyId]),x.useEffect(()=>{if(!it)return;const W=window.setTimeout(()=>_e(""),3500);return()=>window.clearTimeout(W)},[it]),x.useEffect(()=>{if(!P){We([]);return}const W=re(ie,`jobTimeline/${t.companyId}/${P.id}`);return qt(W,ft=>{if(ft.exists()){const vt=ft.val();We(Object.entries(vt).map(([Ae,oe])=>({id:Ae,...oe})).sort((Ae,oe)=>oe.createdAt-Ae.createdAt));return}const Zt=[{id:"generated-received",companyId:t.companyId,jobId:P.id,jobNumber:P.jobNumber,branchId:P.branchId,status:"received",title:"Device received",note:P.problem||"",actorUid:t.uid,actorName:t.name,createdAt:P.createdAt}];P.status!=="received"&&Zt.unshift({id:"generated-current-status",companyId:t.companyId,jobId:P.id,jobNumber:P.jobNumber,branchId:P.branchId,status:P.status,title:`Status changed to ${Dr(P.status)}`,note:"Timeline restored automatically from the current Job status.",actorUid:t.uid,actorName:t.name,createdAt:P.updatedAt||P.createdAt}),We(Zt),(async()=>{for(const vt of[...Zt].reverse()){const Ae=Ta(re(ie,`jobTimeline/${t.companyId}/${P.id}`));await Pn(Ae,{...vt,id:Ae.key})}})()})},[t.companyId,t.name,t.uid,P==null?void 0:P.id,P==null?void 0:P.status,P==null?void 0:P.updatedAt]);const $e=async(W,ft,Zt,vt,Ae,oe)=>{const Ve=Ta(re(ie,`jobTimeline/${t.companyId}/${W}`));await Pn(Ve,{id:Ve.key,companyId:t.companyId,jobId:W,jobNumber:ft,branchId:Zt,status:vt,title:Ae,note:oe??"",actorUid:t.uid,actorName:t.name,createdAt:Date.now()})},st=async({employeeId:W,jobId:ft,jobNumber:Zt,branchId:vt,technicianName:Ae,device:oe,reassigned:Ve=!1})=>{if(!W)return;const he=Ta(re(ie,`mobileNotifications/${t.companyId}/${W}`));await Pn(he,{type:Ve?"job_reassigned":"job_assigned",companyId:t.companyId,employeeId:W,jobId:ft,jobNumber:Zt,branchId:vt,technicianName:Ae,device:oe,title:Ve?"Job Reassigned":"New Job Assigned",body:`${Zt}${oe?` · ${oe}`:""}`,createdAt:Date.now(),createdByUid:t.uid,createdByName:t.name,read:!1})},Nt=(W,ft)=>{const Zt=D[W];M({...D,[W]:Zt.includes(ft)?Zt.filter(vt=>vt!==ft):[...Zt,ft]})},be=(W,ft,Zt)=>Math.max(0,Number(W||0)-Number(ft||0)-Number(Zt||0)),jt=W=>`${window.location.origin}/track/${encodeURIComponent(s)}/${encodeURIComponent(W)}`,bt=W=>`${window.location.origin}/receipt/${encodeURIComponent(s)}/${encodeURIComponent(W)}`,tn=W=>{let ft=(W||"").replace(/\D/g,"");return ft.startsWith("0")&&(ft=`88${ft}`),ft},B=W=>{const ft=y.find(Ae=>Ae.id===W.customerId),Zt=tn((ft==null?void 0:ft.whatsapp)||(ft==null?void 0:ft.phone));if(!Zt){window.alert("Customer WhatsApp বা mobile number পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}const vt=[`Hello ${(ft==null?void 0:ft.name)||"Customer"},`,"","Your device has been received successfully.",`Job No: ${W.jobNumber}`,`Device: ${[W.deviceCategory,W.brand,W.model].filter(Boolean).join(" â ")}`,"",`Digital Receipt: ${bt(W.id)}`,`Track Service: ${jt(W.id)}`,"","Please keep this message. During delivery, you may show the QR code or barcode from the digital receipt.","",c].join(` 4151`);window.open(`https://wa.me/${Zt}?text=${encodeURIComponent(vt)}`,"_blank","noopener,noreferrer")},xe=W=>{let ft=(W||"").replace(/\D/g,"");return ft.startsWith("880")&&(ft=ft.slice(2)),ft.startsWith("88")&&ft.length>11&&(ft=ft.slice(2)),ft},tt=async W=>
4151{const ft=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(W));return Array.from(new Uint8Array(ft)).map(Zt=>Zt.toString(16).padStart(2,"0")).join("")},ht=async W=>{const ft=y.find(Zt=>Zt.id===W.customerId);if(ft)return ft;if(W.customerId)try{const Zt=await mn(re(ie,`customers/${t.companyId}/${W.customerId}`));if(Zt.exists())return{id:W.customerId,...Zt.val()}}catch(Zt){console.warn(`Customer Portal customer lookup failed for ${W.jobNumber}:`,Zt)}if(W.customerPhoneSnapshot||W.customerWhatsappSnapshot||W.customerNameSnapshot)return{id:W.customerId,companyId:t.companyId,branchId:W.branchId,name:W.customerNameSnapshot||"Customer",phone:W.customerPhoneSnapshot||"",whatsapp:W.customerWhatsappSnapshot||"",dueAmount:0,active:!0,createdAt:W.createdAt,updatedAt:W.updatedAt}},dt=async W=>{const ft=await ht(W),Zt=xe((ft==null?void 0:ft.phone)||(ft==null?void 0:ft.whatsapp)||W.customerPhoneSnapshot||W.customerWhatsappSnapshot);return Zt?{jobId:W.id,jobNumber:W.jobNumber,phoneHash:await tt(Zt),active:!0,updatedAt:W.updatedAt}:null},we=W=>{var vt;const ft=y.find(Ae=>Ae.id===W.customerId),Zt=n.find(Ae=>Ae.id===W.branchId);return{companyName:c,companyPhone:(vt=Zt==null?void 0:Zt.contacts)!=null&&vt.length?Zt.contacts.map(Ae=>`${Ae.label}: ${Ae.phone}`).join(" · "):(Zt==null?void 0:Zt.phone)||l||"",companyAddress:(Zt==null?void 0:Zt.address)||m||"",companyLogoUrl:d||"",jobNumber:W.jobNumber,customerName:(ft==null?void 0:ft.name)||"Customer",device:[W.deviceCategory,W.brand,W.model].filter(Boolean).join(" â "),problem:W.problem||"Not recorded",status:W.status,statusLabel:Dr(W.status),expectedDelivery:W.expectedDelivery||"",branchName:(Zt==null?void 0:Zt.name)||"Service Centre",assignedTechnicianId:W.assignedTechnicianId||"",assignedTechnician:W.assignedTechnician||"",receivedAt:W.createdAt,updatedAt:W.updatedAt}},rt=async W=>{const ft=we(W);let Zt=null,vt=null;try{await Pn(re(ie,`publicTracking/${s}/${W.id}`),ft)}catch(Ae){Zt=Ae,console.warn(`Customer Portal public tracking sync failed for ${W.jobNumber}:`,Ae)}try{const Ae=await dt(W);if(!Ae)console.warn(`Customer Portal phone index skipped for ${W.jobNumber}: customer phone unavailable.`);else{const oe={companyId:s,companyName:c,jobId:W.id,jobNumber:W.jobNumber,status:W.status,statusLabel:ft.statusLabel,device:ft.device,active:!0,updatedAt:W.updatedAt};await Pn(re(ie,`publicPortalPhoneLookup/${s}/${Ae.phoneHash}/${W.id}`),oe)}}catch(Ae){vt=Ae,console.warn(`Customer Portal phone index sync failed for ${W.jobNumber}:`,Ae)}if(Zt&&vt)throw new Error(`Both Customer Portal projections failed for ${W.jobNumber}.`)};x.useEffect(()=>{if(!g.length)return;let W=!1;return(async()=>{var vt;for(const Ae of g){if(W)return;try{await rt(Ae)}catch(oe){console.warn(`Customer Portal repair skipped for ${Ae.jobNumber}:`,oe)}}const Zt=((vt=i==null?void 0:i.slug)==null?void 0:vt.trim().toLowerCase())||Fb(c||(i==null?void 0:i.companyCode)||s)||s.toLowerCase();if(!W)try{await yn(re(ie),{[`companyDirectory/${Zt}`]:{id:s,name:c,slug:Zt,phone:l||"",address:m||"",logoUrl:d||"",active:!0}})}catch(Ae){console.warn("Customer Portal company-directory sync skipped:",Ae)}})().catch(Zt=>{console.error("Public portal sync failed:",Zt)}),()=>{W=!0}},[g,y,n,s,i==null?void 0:i.slug,c,l,m,d]),x.useEffect(()=>{if(!g.length||!Ti.currentUser)return;let W=!1;const ft=window.setTimeout(async()=>{var Zt;try{const vt=await((Zt=Ti.currentUser)==null?void 0:Zt.getIdToken());if(!vt||W)return;const Ae=await fetch("https://verixo-api.duckdns.org/api/internal/customer-portal/rebuild-phone-index",{method:"POST",headers:{Authorization:`Bearer ${vt}`,"Content-Type":"application/json"},body:JSON.stringify({reason:"service-jobs-sync"})});Ae.ok||console.warn(`Customer Portal authoritative phone-index rebuild failed (${Ae.status}).`)}catch(vt){console.warn("Customer Portal authoritative phone-index rebuild skipped:",vt)}},1200);return()=>{W=!0,window.clearTimeout(ft)}},[g,t.companyId]);const St=x.useMemo(()=>{const W=q.trim().toLowerCase();return g.filter(ft=>{if(!(a==="all"||ft.branchId===a)||ae!=="all"&&ft.assignedTechnicianId!==ae||je!=="all"&&ft.status!==je||$!=="all"&&(ft.priority||"normal")!==$)return!1;if(!W)return!0;const vt=y.find(Ae=>Ae.id===ft.customerId);return[ft.jobNumber,vt==null?void 0:vt.name,vt==null?void 0:vt.phone,ft.deviceCategory,ft.brand,ft.model,ft.serialNumber,ft.problem,ft.assignedTechnician,ft.serviceType,ft.status].some(Ae=>Ae==null?void 0:Ae.toLowerCase().includes(W))})},[g,y,q,a,ae,je,$]),Qt=W=>g.filter(ft=>ft.assignedTechnicianId===W&&!["delivered","closed","cancelled"].includes(ft.status)).length,gn=()=>{var W;L(null),M({...c5,branchId:a!=="all"?a:t.branchId??((W=n[0])==null?void 0:W.id)??""}),H(!0)},An=W=>{if(W.warrantyReviewStatus==="rma_created"){window.alert(`Warranty already received. Linked RMA: ${W.linkedRmaNumber||"Created"}`);return}if(W.diagnosisOutcome){window.alert("Diagnosis à¦à¦¤à§à¦®à¦§à§à¦¯à§ submit হà§à§à¦à§à¥¤ পà§à¦°à§à§à¦à¦¨ হলৠauthorized user দিà§à§ diagnosis reset à¦à¦°à¦¤à§ হবà§à¥¤");return}Ce(W),Te("repairable"),Ye("")},Sn=async()=>
4151{if(!ct||!Ge)return;if(!ce.trim()){window.alert("Technician diagnosis note লিà¦à§à¦¨à¥¤");return}const W=Date.now(),ft=De==="warranty_recommended",Zt={diagnosisOutcome:De,diagnosisNote:ce.trim(),diagnosisCompletedAt:W,diagnosisCompletedBy:t.name,warrantyReviewStatus:ft?"pending":"not_required",updatedAt:W};await yn(re(ie,`serviceJobs/${t.companyId}/${ct.id}`),Zt),await $e(ct.id,ct.jobNumber,ct.branchId,ct.status,ft?"Warranty claim recommended":"Product is repairable",`${t.name}: ${ce.trim()}`),await ia({companyId:t.companyId,branchId:ct.branchId,actorUid:t.uid,actorName:t.name,action:"job.updated",entityType:"serviceJob",entityId:ct.id,summary:ft?`${ct.jobNumber} warranty claim recommended`:`${ct.jobNumber} marked repairable`,metadata:{diagnosisOutcome:De,diagnosisNote:ce.trim()}}),ue(vt=>(vt==null?void 0:vt.id)===ct.id?{...vt,...Zt}:vt),Ce(null),_e(ft?"Warranty recommendation sent to Service In-Charge":"Diagnosis saved â repair can continue")},Xt=async W=>{if(!pt){window.alert("শà§à¦§à§ Service In-Charge বা higher authority warranty receive à¦à¦°à¦¤à§ পারবà§à¥¤");return}if(W.diagnosisOutcome!=="warranty_recommended"){window.alert("Technician warranty recommendation পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}if(W.linkedRmaId){window.alert(`Customer RMA à¦à¦¤à§à¦®à¦§à§à¦¯à§ তà§à¦°à¦¿ হà§à§à¦à§: ${W.linkedRmaNumber}`);return}const ft=y.find(Ve=>Ve.id===W.customerId);if(!ft){window.alert("Customer record পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤");return}if(!window.confirm(`${W.jobNumber} থà§à¦à§ Customer RMA তà§à¦°à¦¿ à¦à¦°à¦¬à§à¦¨?`))return;const Zt=Date.now(),vt=Ta(re(ie,`rmas/${t.companyId}`)),Ae=`VRX-RMA-${new Date().getFullYear()}-${String(Zt).slice(-6)}`;await Pn(vt,{companyId:t.companyId,branchId:W.branchId,rmaNumber:Ae,rmaType:"customer",partyName:ft.name,partyPhone:ft.phone||"",partyAddress:ft.address||"",productName:W.deviceCategory,brand:W.brand||"",model:W.model||"",serialNumber:W.serialNumber||"",invoiceReference:"",purchaseSource:"",purchaseDate:"",warrantyUntil:W.warrantyUntil||"",problem:W.problem,accessories:W.accessories||(W.accessoriesList||[]).join(", "),physicalCondition:W.conditionNote||(W.physicalConditions||[]).join(", "),notes:`Created from Service Job ${W.jobNumber}. Technician diagnosis: ${W.diagnosisNote||""}`,status:"received",serviceJobId:W.id,serviceJobNumber:W.jobNumber,customerId:W.customerId,createdByUid:t.uid,createdByName:t.name,createdAt:Zt,updatedAt:Zt});const oe=Ta(re(ie,`rmaTimeline/${t.companyId}/${vt.key}`));await Pn(oe,{status:"received",label:"Received",note:`Customer RMA created from ${W.jobNumber}`,actorUid:t.uid,actorName:t.name,createdAt:Zt}),await yn(re(ie,`serviceJobs/${t.companyId}/${W.id}`),{serviceType:"warranty",warrantyReviewStatus:"rma_created",linkedRmaId:vt.key,linkedRmaNumber:Ae,updatedAt:Zt}),await $e(W.id,W.jobNumber,W.branchId,W.status,"Warranty received",`Customer RMA ${Ae} created by ${t.name}.`),await ia({companyId:t.companyId,branchId:W.branchId,actorUid:t.uid,actorName:t.name,action:"rma.created",entityType:"rma",entityId:String(vt.key),summary:`${Ae} created from ${W.jobNumber}`,metadata:{serviceJobId:W.id,serviceJobNumber:W.jobNumber}}),ue(Ve=>(Ve==null?void 0:Ve.id)===W.id?{...Ve,serviceType:"warranty",warrantyReviewStatus:"rma_created",linkedRmaId:String(vt.key),linkedRmaNumber:Ae,updatedAt:Zt}:Ve),_e(`Customer RMA created: ${Ae}`)},Wt=async(W,ft)=>{const vt={start_diagnosis:{nextStatus:"diagnosing",title:"Diagnosis started",note:W.assignedTechnician?`Diagnosis started by assigned technician ${W.assignedTechnician}.`:"Diagnosis started.",confirmText:W.assignedTechnician?`Start diagnosis with ${W.assignedTechnician}?`:"Start diagnosis for this job?"},start_repair:{nextStatus:"repairing",title:Rc(W.jobType).startTitle,note:W.assignedTechnician?`${Lf(W.jobType)} work started by assigned technician ${W.assignedTechnician}.`:`${Lf(W.jobType)} work has started.`,confirmText:`${Rc(W.jobType).startLabel} for this job?`},complete_repair:{nextStatus:"quality_check",title:Rc(W.jobType).completeTitle,note:`${Lf(W.jobType)}
4151 work is complete and the job has moved to quality checking.`,confirmText:`${Rc(W.jobType).completeLabel} and send for quality check?`},mark_ready:{nextStatus:"ready",title:"Open quality check",note:"Open the quality check form.",confirmText:"Open Quality Check?"},confirm_ready:{nextStatus:"ready",title:"Ready for Delivery",note:"QC was already completed by the technician. Authorized service user marked the job Ready for Delivery.",confirmText:"QC is already completed. Mark this job Ready for Delivery?"}}[ft];if(ft==="confirm_ready"&&!te){window.alert("You are not authorized to mark this job Ready for Delivery.");return}if(ft==="start_diagnosis"){if(!W.assignedTechnicianId||!W.assignedTechnician){window.alert("Diagnosis শà§à¦°à§ à¦à¦°à¦¾à¦° à¦à¦à§ Technician assign à¦à¦°à§à¦¨à¥¤");return}if(!Ge&&!te){window.alert("You are not authorized to start diagnosis for this job.");return}}if(ft==="complete_repair"){const oe=W.serviceChargeBreakdown||{diagnosis:0,repair:Number(W.labourCharge||0),installation:0,other:0};le({repairPerformed:W.repairPerformed||"",partsReplaced:W.partsReplaced||"",customPart:"",diagnosisCharge:Number(oe.diagnosis||0),repairCharge:Number(oe.repair||0),installationCharge:Number(oe.installation||0),otherServiceCharge:Number(oe.other||0),partsTotal:Number(W.partsTotal||0),partsUsedDetails:W.partsUsedDetails||"",customerServiceNotes:W.customerServiceNotes||"",repairNotes:W.repairNotes||"",technicianCost:Number(W.technicianCost||0),partsCost:Number(W.partsCost||0),outsideRepairCost:Number(W.outsideRepairCost||0),otherServiceCost:Number(W.otherServiceCost||0),repairWarranty:W.repairWarranty||"none"}),qe(W);return}if(ft==="mark_ready"){xt({boot:"pass",operatingSystem:"pass",driver:"pass",motherboard:"pass",ram:"pass",storage:"pass",display:"pass",keyboard:"pass",mouseTouchpad:"pass",usb:"pass",audio:"pass",network:"pass",wifi:"pass",bluetooth:"na",webcam:"na",battery:"na",charger:"na",bios:"pass",stress:"pass",remarks:""}),wt(W);return}if(ft==="start_repair"&&["repair","upgrade"].includes(W.jobType||"repair")&&W.approvalPath==="estimate_required"&&W.approvalStatus!=="approved"){window.alert("Client approval পাà¦à§à¦¾ যাà§à¦¨à¦¿à¥¤ Estimate approved না হà¦à§à¦¾ পরà§à¦¯à¦¨à§à¦¤ repair শà§à¦°à§ à¦à¦°à¦¾ যাবৠনা.");return}if(!M_(W.status,vt.nextStatus)){window.alert(`Status cannot move from ${Dr(W.status)} to ${Dr(vt.nextStatus)}.`);return}if(!window.confirm(vt.confirmText))return;const Ae=Date.now();await yn(re(ie,`serviceJobs/${t.companyId}/${W.id}`),{status:vt.nextStatus,updatedAt:Ae}),await yn(re(ie,`publicTracking/${t.companyId}/${W.id}`),{status:vt.nextStatus,statusLabel:Dr(vt.nextStatus),updatedAt:Ae}),await $e(W.id,W.jobNumber,W.branchId,vt.nextStatus,vt.title,vt.note),ue(oe=>(oe==null?void 0:oe.id)===W.id?{...oe,status:vt.nextStatus,updatedAt:Ae}:oe),_e(vt.title)},Gt=W=>{if(W.invoiceId||W.invoiceNumber){window.alert("Invoice already exists. Use the controlled Invoice edit/adjustment flow instead.");return}Me({serviceCharge:Number(W.labourCharge||0),partsTotal:Number(W.partsTotal||0),partsUsedDetails:W.partsUsedDetails||"",discountAmount:Number(W.discountAmount||0)}),pe(W)},$t=async W=>{if(W.preventDefault(),!se)return;if(se.invoiceId||se.invoiceNumber){window.alert("Invoice already exists. Billable preparation is locked."),pe(null);return}const ft=Math.max(0,Number(Se.serviceCharge||0)),Zt=Math.max(0,Number(Se.partsTotal||0)),vt=Math.max(0,Number(Se.discountAmount||0)),Ae=Math.max(0,ft+Zt-vt),oe=Date.now(),Ve={labourCharge:ft,partsTotal:Zt,partsUsedDetails:Se.partsUsedDetails.trim(),discountAmount:vt,estimatedCost:Ae,invoicePreparedAt:oe,invoicePreparedBy:t.name,updatedAt:oe};await yn(re(ie,`serviceJobs/${t.companyId}/${se.id}`),Ve),await $e(se.id,se.jobNumber,se.branchId,se.status,"Invoice preparation updated",Ae>0?`Prepared billable amount à§³${Ae.toLocaleString("en-GB")}. Final Product/Service billing remains editable in Generate Invoice.`:"Marked as zero billable amount before invoice. Final billing remains controlled from Generate Invoice."),ue(he=>(he==null?void 0:he.id)===se.id?{...he,...Ve}:he),_e("Invoice preparation saved. Generate Invoice will preload these amounts."),pe(null)},Vt=async W=>{if(W.preventDefault(),!ee)return;if(!Je.repairPerformed.trim()){window.alert("Repair Performed লিà¦à§à¦¨à¥¤");return}
4151const ft=Date.now(),Zt="quality_check",vt={diagnosis:Number(Je.diagnosisCharge||0),repair:Number(Je.repairCharge||0),installation:Number(Je.installationCharge||0),other:Number(Je.otherServiceCharge||0)},Ae=vt.diagnosis+vt.repair+vt.installation+vt.other,oe=Number(Je.technicianCost||0)+Number(Je.partsCost||0)+Number(Je.outsideRepairCost||0)+Number(Je.otherServiceCost||0),Ve=Ae+Number(Je.partsTotal||0)-oe,he={repairPerformed:Je.repairPerformed.trim(),partsReplaced:Je.partsReplaced.trim(),labourCharge:Ae,serviceChargeBreakdown:vt,partsTotal:Number(Je.partsTotal||0),partsUsedDetails:Je.partsUsedDetails.trim(),customerServiceNotes:Je.customerServiceNotes.trim(),repairNotes:Je.repairNotes.trim(),technicianCost:Number(Je.technicianCost||0),partsCost:Number(Je.partsCost||0),outsideRepairCost:Number(Je.outsideRepairCost||0),otherServiceCost:Number(Je.otherServiceCost||0),grossProfit:Ve,repairWarranty:Je.repairWarranty,repairCompletedAt:ft,repairCompletedBy:t.name,status:Zt,updatedAt:ft};await yn(re(ie,`serviceJobs/${t.companyId}/${ee.id}`),he),await yn(re(ie,`publicTracking/${t.companyId}/${ee.id}`),{status:Zt,statusLabel:Dr(Zt),updatedAt:ft}),await $e(ee.id,ee.jobNumber,ee.branchId,Zt,Rc(ee.jobType).completeTitle,Je.repairPerformed.trim()),ue(Oe=>(Oe==null?void 0:Oe.id)===ee.id?{...Oe,...he}:Oe),qe(null),_e(`${Lf(ee.jobType)} completed and sent to Quality Check`)},sn=async W=>{if(W.preventDefault(),!ot)return;const ft={boot:nt.boot,operatingSystem:nt.operatingSystem,driver:nt.driver,motherboard:nt.motherboard,ram:nt.ram,storage:nt.storage,display:nt.display,keyboard:nt.keyboard,mouseTouchpad:nt.mouseTouchpad,usb:nt.usb,audio:nt.audio,network:nt.network,wifi:nt.wifi,bluetooth:nt.bluetooth,webcam:nt.webcam,battery:nt.battery,charger:nt.charger,bios:nt.bios,stress:nt.stress},Zt=Object.values(ft).some(Oe=>Oe==="fail"),vt=Zt?"fail":"pass";if(Zt&&!nt.remarks.trim()){window.alert("à¦à¦ বা à¦à¦à¦¾à¦§à¦¿à¦ test FAIL হà§à§à¦à§à¥¤ Failure reason / remarks লিà¦à§à¦¨à¥¤");return}const Ae=Date.now(),oe=vt==="pass"?"ready":"repairing",Ve={qualityChecks:ft,qualityResult:vt,qualityRemarks:nt.remarks.trim(),qualityCheckedAt:Ae,qualityCheckedBy:t.name,status:oe,updatedAt:Ae};await yn(re(ie,`serviceJobs/${t.companyId}/${ot.id}`),Ve),await yn(re(ie,`publicTracking/${t.companyId}/${ot.id}`),{status:oe,statusLabel:Dr(oe),qualityChecks:ft,qualityResult:vt,qualityRemarks:nt.remarks.trim(),qualityCheckedAt:Ae,qualityCheckedBy:t.name,updatedAt:Ae});const he=Object.entries(ft).filter(([,Oe])=>Oe==="fail").map(([Oe])=>Oe.replace(/([A-Z])/g," $1").replace(/^./,ut=>ut.toUpperCase()));await $e(ot.id,ot.jobNumber,ot.branchId,oe,vt==="pass"?"Enterprise quality inspection passed":"Quality inspection failed",vt==="pass"?"All applicable inspection items passed. Device is ready for delivery.":`Failed items: ${he.join(", ")}. ${nt.remarks.trim()}`),ue(Oe=>(Oe==null?void 0:Oe.id)===ot.id?{...Oe,...Ve}:Oe),wt(null),_e(vt==="pass"?"Quality inspection passed â Ready for Delivery":"Quality inspection failed â Returned to Repairing")},on=async(W,ft)=>{if(W.serviceMode!=="onsite")return;const Zt=Date.now(),Ae={request_received:"received",visit_scheduled:"diagnosing",on_the_way:"repairing",reached_site:"repairing",work_started:"repairing",parts_required:"repairing",work_paused:"repairing",work_completed:"qc_completed",customer_confirmed:"ready"}[ft]||W.status,oe={[`serviceJobs/${t.companyId}/${W.id}/onsiteVisitStatus`]:ft,[`serviceJobs/${t.companyId}/${W.id}/status`]:Ae,[`serviceJobs/${t.companyId}/${W.id}/updatedAt`]:Zt};ft==="reached_site"&&(oe[`serviceJobs/${t.companyId}/${W.id}/onsiteArrivalAt`]=Zt),ft==="work_started"&&(oe[`serviceJobs/${t.companyId}/${W.id}/onsiteWorkStartedAt`]=Zt),ft==="work_completed"&&(oe[`serviceJobs/${t.companyId}/${W.id}/onsiteWorkCompletedAt`]=Zt),ft==="customer_confirmed"&&(oe[`serviceJobs/${t.companyId}/${W.id}/onsiteCustomerConfirmedAt`]=Zt),await yn(re(ie),oe);const Ve={request_received:"Request Received",visit_scheduled:"Visit Scheduled",on_the_way:"On the Way",reached_site:"Reached Site",work_started:"Work Started",parts_required:"Parts Required",work_paused:"Work Paused",work_completed:"Work Completed",customer_confirmed:"Customer Confirmed"};
4151await $e(W.id,W.jobNumber,W.branchId,W.status,`On-site: ${Ve[ft]}`,W.siteAddress||""),ue(he=>(he==null?void 0:he.id)===W.id?{...he,onsiteVisitStatus:ft,status:Ae,updatedAt:Zt,...ft==="reached_site"?{onsiteArrivalAt:Zt}:{},...ft==="work_started"?{onsiteWorkStartedAt:Zt}:{},...ft==="work_completed"?{onsiteWorkCompletedAt:Zt}:{},...ft==="customer_confirmed"?{onsiteCustomerConfirmedAt:Zt}:{}}:he)},ke=async W=>{if(W.serviceMode!=="onsite")return;if(Pe("saving"),me.onsiteNextVisitRequired&&!me.onsiteNextVisitAt){Pe("idle"),window.alert("Next Visit Required = Yes হলৠNext Visit Date & Time দিন।");return}const ft=Date.now(),Zt={onsiteDiagnosis:me.onsiteDiagnosis.trim(),onsiteWorkDone:me.onsiteWorkDone.trim(),onsitePartsUsed:me.onsitePartsUsed.trim(),onsiteNextVisitRequired:me.onsiteNextVisitRequired,onsiteNextVisitAt:me.onsiteNextVisitRequired?me.onsiteNextVisitAt:"",onsiteFieldUpdatedAt:ft,updatedAt:ft};try{await yn(re(ie,`serviceJobs/${t.companyId}/${W.id}`),Zt),await $e(W.id,W.jobNumber,W.branchId,W.status,"On-site field report updated",Zt.onsiteNextVisitRequired&&Zt.onsiteNextVisitAt?`Return visit: ${new Date(Zt.onsiteNextVisitAt).toLocaleString("en-GB")} · ${Zt.onsiteWorkDone||Zt.onsiteDiagnosis||"Field report saved"}`:Zt.onsiteWorkDone||Zt.onsiteDiagnosis||"Field report saved"),ue(vt=>(vt==null?void 0:vt.id)===W.id?{...vt,...Zt}:vt),ge(vt=>({...vt,...Zt})),Pe("saved"),Ee(ft),_e("On-site field report saved.")}catch(vt){console.error("Unable to save on-site field report",vt),Pe("error"),window.alert("Field report save হà§à¦¨à¦¿à¥¤ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤")}},Ct=async W=>{var vt;const ft=(vt=window.prompt("Bangla QR payment Transaction ID / Reference লিà¦à§à¦¨:",W.onsitePaymentReference||""))==null?void 0:vt.trim();if(!ft)return;const Zt=Date.now();await yn(re(ie,`serviceJobs/${t.companyId}/${W.id}`),{onsitePaymentReference:ft,updatedAt:Zt}),await $e(W.id,W.jobNumber,W.branchId,W.status,"Bangla QR payment reference recorded",ft),ue(Ae=>(Ae==null?void 0:Ae.id)===W.id?{...Ae,onsitePaymentReference:ft,updatedAt:Zt}:Ae)},Et=W=>{L(W),M({customerId:W.customerId,branchId:W.branchId,deviceCategory:W.deviceCategory,brand:W.brand,model:W.model??"",serialNumber:W.serialNumber??"",imei:W.imei??"",colour:W.colour??"",loginPassword:W.loginPassword??"",technicalDetails:W.technicalDetails??{},problem:W.problem,accessories:W.accessories??"",accessoriesList:W.accessoriesList??[],physicalConditions:W.physicalConditions??[],conditionNote:W.conditionNote??"",estimatedCost:Number(W.estimatedCost||0),advanceAmount:Number(W.advanceAmount||0),discountAmount:Number(W.discountAmount||0),dueAmount:Number(W.dueAmount||0),expectedDelivery:W.expectedDelivery??"",warrantyUntil:W.warrantyUntil??"",priority:W.priority??"normal",assignedTechnician:W.assignedTechnician??"",assignedTechnicianId:W.assignedTechnicianId??"",assignedTechnicianPhone:W.assignedTechnicianPhone??"",serviceType:W.serviceType??"repair",serviceMode:W.serviceMode??"in_house",siteAddress:W.siteAddress??"",siteContactPerson:W.siteContactPerson??"",siteContactPhone:W.siteContactPhone??"",scheduledVisitAt:W.scheduledVisitAt??"",onsiteVisitStatus:W.onsiteVisitStatus??"request_received",onsiteVisitCharge:Number(W.onsiteVisitCharge||0),onsiteTransportCharge:Number(W.onsiteTransportCharge||0),onsiteOtherCharge:Number(W.onsiteOtherCharge||0),onsitePaymentReference:W.onsitePaymentReference??"",jobType:W.jobType??"repair",approvalPath:W.approvalPath??"quick_service",approvalStatus:W.approvalStatus??"not_required",approvedEstimateId:W.approvedEstimateId??"",status:W.status,internalNotes:W.internalNotes??""}),H(!0)},Rt=()=>{H(!1),L(null)},xn=async W=>{var Ae,oe,Ve;W.preventDefault();const ft=be(D.estimatedCost,D.advanceAmount,D.discountAmount),Zt=D.approvalPath==="quick_service"?"not_required":D.approvalStatus==="not_required"?"pending":D.approvalStatus,vt={...D,approvalStatus:Zt,dueAmount:ft};if(vt.approvalPath==="estimate_required"&&["repairing","quality_check","qc_completed","ready","delivered","closed"].includes(vt.status)&&vt.approvalStatus!=="approved"){window.alert("à¦à¦ job-ঠEstimate approval পà§à¦°à§à§à¦à¦¨à¥¤ Client approve না à¦à¦°à¦¾ পরà§à¦¯à¦¨à§à¦¤ Repairing বা পরবরà§à¦¤à§ status দà§à¦à§à¦¾ যাবৠনা.");return}if(vt.approvalPath==="estimate_required"&&vt.status==="diagnosing"&&(vt.status="waiting_approval"),K&&K.status!==vt.status){if(vt.status==="delivered"){window.alert("Service Job সরাসরি Delivered à¦à¦°à¦¾ যাবৠনা। Ready for Delivery হà¦à§à¦¾à¦° পর Delivery Scan বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤ Billable job হলৠinvoice à¦à¦¾à§à¦¾ delivery block থাà¦à¦¬à§.");return}if(!M_(K.status,vt.status)){window.alert(`Status cannot move from ${Dr(K.status)} to ${Dr(vt.status)}.`);return}if(!window.confirm(`Status will change: 4152 4153${Dr(K.status)} â ${Dr(vt.status)} 4154 4155Continue with update?`))return}if(vt.serviceMode==="onsite"){if(!vt.siteAddress.trim()){window.alert("On-site Service-à¦à¦° à¦à¦¨à§à¦¯ Site Address required.");return}if(!vt.siteContactPhone.trim()){window.alert("On-site Service-à¦à¦° à¦à¦¨à§à¦¯ Site Contact Number required.");return}}fe(!0);try{if(K){const he=Date.now(),Oe={...K,...vt,companyId:t.companyId,updatedAt:he},ut={[`serviceJobs/${t.companyId}/${K.id}`]:{...K,...vt,companyId:t.companyId,updatedAt:he}};if(Number(K.advanceAmount||0)!==Number(vt.advanceAmount||0)){const Ea=await mn(re(ie,`invoices/${t.companyId}`)),zn=(Ea.exists()?Object.entries(Ea.val()):[]).filter(([,Xn])=>(Xn==null?void 0:Xn.serviceJobId)===K.id);if(zn.length>0){const Xn=await mn(re(ie,`collections/${t.companyId}`)),Vn=Xn.exists()?Object.entries(Xn.val()):[];for(const[ua,Ma]of zn){const Xe=Vn.reduce((is,[,hs])=>(hs==null?void 0:hs.invoiceId)===ua?is+Math.max(Number((hs==null?void 0:hs.amount)||0),0):is,0),Jt=Math.max(Number((Ma==null?void 0:Ma.grandTotal)||0),0),Ht=Math.max(Number(vt.advanceAmount||0),0),xa=Math.min(Jt,Ht+Xe),ra=Math.max(Jt-xa,0),Ha=ra<=0?"fully_collected":xa>0?"partially_collected":"uncollected";ut[`invoices/${t.companyId}/${ua}`]={...Ma,advanceAmount:Ht,collectedAmount:xa,dueAmount:ra,status:Ha,updatedAt:he}}}}await yn(re(ie),ut);try{await rt(Oe)}catch(Ea){console.warn("Customer Portal sync failed after primary edit:",Ea)}try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:K.status===vt.status?"job.updated":"job.status_changed",entityType:"serviceJob",entityId:K.id,branchId:vt.branchId,summary:K.status===vt.status?`Updated service job ${K.jobNumber}`:`${K.jobNumber}: ${Dr(K.status)} â ${Dr(vt.status)}`,metadata:{jobNumber:K.jobNumber,fromStatus:K.status,toStatus:vt.status,assignedTechnician:vt.assignedTechnician,serviceType:vt.serviceType}})}catch(Ea){console.warn("Service job audit sync failed after primary edit:",Ea)}const At=K.assignedTechnician??"",en=vt.assignedTechnician??"",It=At!==en;if(It&&vt.assignedTechnicianId){const Ea=Date.now();await yn(re(ie,`serviceJobs/${t.companyId}/${K.id}`),{assignedAt:Ea,assignedBy:t.name,assignedByUid:t.uid,assignedByName:t.name}),await st({employeeId:vt.assignedTechnicianId,jobId:K.id,jobNumber:K.jobNumber,branchId:vt.branchId,technicianName:vt.assignedTechnician||"Technician",device:[vt.deviceCategory,vt.brand,vt.model].filter(
4155Boolean).join(" "),reassigned:!!K.assignedTechnicianId})}const Pt=K.serviceType??"repair",Jn=vt.serviceType??"repair",na=Pt!==Jn,Mn=K.status!==vt.status;if(It){const Ea=!At&&en?`Technician assigned: ${en}`:At&&!en?`Technician unassigned: ${At}`:`Technician changed: ${At||"Unassigned"} â ${en||"Unassigned"}`;await $e(K.id,K.jobNumber,vt.branchId,vt.status,Ea,[`Changed by ${t.name}`,vt.assignedTechnicianPhone?`Phone: ${vt.assignedTechnicianPhone}`:"",vt.internalNotes].filter(Boolean).join(" · "))}na&&await $e(K.id,K.jobNumber,vt.branchId,vt.status,`Service type changed: ${Pt} â ${Jn}`,vt.internalNotes),Mn&&await $e(K.id,K.jobNumber,vt.branchId,vt.status,`Status changed to ${Dr(vt.status)}`,vt.internalNotes),!It&&!na&&!Mn&&await $e(K.id,K.jobNumber,vt.branchId,vt.status,"Service job updated",vt.internalNotes),_e(`${K.jobNumber} updated successfully.`)}else{const he=Ta(re(ie,`serviceJobs/${t.companyId}`)),Oe=new Date().getFullYear(),ut=(((Ae=i==null?void 0:i.documentPrefixes)==null?void 0:Ae.serviceJob)||gg.serviceJob).toUpperCase().replace(/[^A-Z0-9]/g,"")||"SJ",At=g.map(ua=>{const Ma=String(ua.jobNumber||"").match(new RegExp(`^([A-Z0-9]+)-${ut}-${Oe}-(\\d{6})$`,"i"));return Ma?{branchCode:Ma[1].toUpperCase(),sequence:Number(Ma[2]||0),branchId:ua.branchId||""}:null}).filter(ua=>!!ua),en=At.filter(ua=>ua.branchId===vt.branchId).sort((ua,Ma)=>Ma.sequence-ua.sequence)[0],It=[...At].sort((ua,Ma)=>Ma.sequence-ua.sequence)[0],Pt=It&&(!en||It.sequence>en.sequence)?It:en,Jn=(Pt==null?void 0:Pt.branchCode)||((oe=n.find(ua=>ua.id===vt.branchId))==null?void 0:oe.code),na=await Qf({companyId:t.companyId,branchCode:Jn,documentType:"serviceJob",prefixes:i==null?void 0:i.documentPrefixes,minimumLastNumber:(Pt==null?void 0:Pt.sequence)||0}
4155),Mn=hx(Jn),Ea=(((Ve=i==null?void 0:i.documentPrefixes)==null?void 0:Ve.serviceJob)||gg.serviceJob).toUpperCase().replace(/[^A-Z0-9]/g,"")||"SJ";if(!new RegExp(`^${Mn}-${Ea}-\\d{4}-\\d{6}$`).test(na))throw new Error(`Invalid Service Job number generated: ${na}. Expected ${Mn}-${Ea}-YYYY-000001`);const zn=Date.now(),Xn=y.find(ua=>ua.id===vt.customerId),Vn={...vt,id:he.key??"",companyId:t.companyId,customerNameSnapshot:(Xn==null?void 0:Xn.name)||"",customerPhoneSnapshot:(Xn==null?void 0:Xn.phone)||"",customerWhatsappSnapshot:(Xn==null?void 0:Xn.whatsapp)||"",jobNumber:na,assignedAt:vt.assignedTechnicianId?zn:void 0,assignedBy:vt.assignedTechnicianId?t.name:void 0,assignedByUid:vt.assignedTechnicianId?t.uid:void 0,assignedByName:vt.assignedTechnicianId?t.name:void 0,createdAt:zn,updatedAt:zn};await Pn(re(ie,`serviceJobs/${t.companyId}/${he.key??""}`),Vn);try{await rt(Vn)}catch(ua){console.warn("Customer Portal sync failed after primary Service Job save:",ua)}try{vt.assignedTechnicianId&&await st({employeeId:vt.assignedTechnicianId,jobId:he.key??"",jobNumber:na,branchId:vt.branchId,technicianName:vt.assignedTechnician||"Technician",device:[vt.deviceCategory,vt.brand,vt.model].filter(Boolean).join(" "),reassigned:!1})}catch(ua){console.warn("Service job notification sync failed after primary save:",ua)}try{await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"job.created",entityType:"serviceJob",entityId:he.key??"",branchId:vt.branchId,summary:`Created service job ${na}`,metadata:{jobNumber:na,customerId:vt.customerId,status:vt.status,assignedTechnician:vt.assignedTechnician,serviceType:vt.serviceType}})}catch(ua){console.warn("Service job audit sync failed after primary save:",ua)}try{await $e(he.key??"",na,vt.branchId,vt.status,"Device received",vt.problem)}catch(ua){console.warn("Service job timeline sync failed after primary save:",ua)}B(Vn),_e(`${na} created successfully. WhatsApp receipt prepared.`)}Rt()}catch(he){console.error("Service job save failed:",he),window.alert("Service job save à¦à¦°à¦¾ যাà§à¦¨à¦¿à¥¤ à¦à¦¬à¦¾à¦° à¦à§à¦·à§à¦à¦¾ à¦à¦°à§à¦¨à¥¤")}finally{fe(!1)}},dn=async W=>{window.confirm(`${W.jobNumber} service job delete à¦à¦°à¦¬à§à¦¨?`)&&(await Ao(re(ie,`serviceJobs/${t.companyId}/${W.id}`)),await ia({companyId:t.companyId,actorUid:t.uid,actorName:t.name,action:"job.deleted",entityType:"serviceJob",entityId:W.id,branchId:W.branchId,summary:`Deleted service job ${W.jobNumber}`,metadata:{jobNumber:W.jobNumber}}))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Core service operation"}),e.jsx("h1",{children:"Service Jobs"}),e.jsx("p",{children:"Receive devices, track repair progress and manage delivery status."})]}),e.jsxs("button",{className:"primary-action",onClick:gn,disabled:y.length===0||!te,children:[e.jsx(as,{size:18})," New service job"]})]}),y.length===0&&e.jsx("div",{className:"module-alert",children:"পà§à¦°à¦¥à¦®à§ à¦
নà§à¦¤à¦¤ à¦à¦à¦à¦¨ Customer তà§à¦°à¦¿ à¦à¦°à§à¦¨à¥¤ তারপর Service Job তà§à¦°à¦¿ à¦à¦°à¦¾ যাবà§à¥¤"}),e.jsxs("section",{className:"panel",children:[e.jsxs("div",{className:"customer-toolbar service-job-toolbar",children:[e.jsxs("div",{className:"customer-search",children:[e.jsx(xr,{size:18}),e.jsx("input",{value:q,onChange:W=>ne(W.target.value),placeholder:"Search job no, customer, phone, device or serial"})]}),e.jsxs("div",{className:"service-job-filters",children:[e.jsxs("select",{value:ae,onChange:W=>Y(W.target.value),children:[e.jsx("option",{value:"all",children:"All Technicians"}),G.map(W=>e.jsx("option",{value:W.id,children:W.name},W.id))]}),e.jsxs("select",{value:je,onChange:W=>V(W.target.value),children:[e.jsx("option",{value:"all",children:"All Statuses"}),["received","diagnosing","waiting_approval","approved","repairing","quality_check","qc_completed","ready","delivered","closed","cancelled"].map(W=>e.jsx("option",{value:W,children:Dr(W)},W))]}),e.jsxs("select",{value:$,onChange:W=>F(W.target.value),children:[e.jsx("option",{value:"all",children:"All Priorities"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"urgent",children:"Urgent"})]}),e.jsx("button",{type:"button",className:"clear-job-filters",onClick:()=>{Y("all"),V("all"),F("all"),ne("")},children:"Clear"})]}),e.jsxs("span",{children:[St.length," service job found"]}
4155)]}),St.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx(Qw,{size:35}),e.jsx("h3",{children:"No service job found"}),e.jsx("p",{children:"পà§à¦°à¦¥à¦® device receive à¦à¦°à¦²à§ Dashboard live update হবà§à¥¤"})]}):e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Job"}),e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Device"}),e.jsx("th",{children:"Estimate"}),e.jsx("th",{children:"Priority"}),e.jsx("th",{children:"Technician"}),e.jsx("th",{children:"Job Type"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Expected Delivery"}),e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:St.map(W=>{var Zt;const ft=y.find(vt=>vt.id===W.customerId);return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:W.jobNumber}),e.jsx("small",{className:"table-subtext",children:new Date(W.createdAt).toLocaleDateString("en-GB")})]}),e.jsxs("td",{children:[(ft==null?void 0:ft.name)||"Unknown",e.jsx("small",{className:"table-subtext",children:(ft==null?void 0:ft.phone)||"No phone"})]}),e.jsxs("td",{children:[W.deviceCategory," â ",W.brand,e.jsx("small",{className:"table-subtext",children:W.model||W.serialNumber||W.problem})]}),e.jsxs("td",{children:["à§³",Number(W.estimatedCost||0).toLocaleString("en-GB"),Number(W.advanceAmount||0)>0&&e.jsxs("small",{className:"table-subtext",children:["Advance: à§³",Number(W.advanceAmount||0).toLocaleString("en-GB")]}),e.jsxs("small",{className:"table-subtext",children:["Due: à§³",Number(W.dueAmount||0).toLocaleString("en-GB")]})]}),e.jsx("td",{children:e.jsx("span",{className:`priority priority-${W.priority||"normal"}`,children:W.priority||"normal"})}),e.jsx("td",{children:((Zt=W.assignedTechnician)==null?void 0:Zt.trim())||"Unassigned"}),e.jsx("td",{children:Lf(W.jobType)}),e.jsx("td",{children:e.jsx("span",{className:`job-status status-${W.status}`,children:W.serviceMode==="onsite"&&{request_received:"Request Received",visit_scheduled:"Visit Scheduled",on_the_way:"On the Way",reached_site:"Reached Site",work_started:"Work Started",parts_required:"Parts Required",work_paused:"Work Paused",work_completed:"Work Completed",customer_confirmed:"Customer Confirmed"}[W.onsiteVisitStatus||"request_received"]||Dr(W.status)})}),e.jsx("td",{children:W.expectedDelivery||"Not set"}),e.jsx("td",{children:e.jsxs("div",{className:"row-actions",children:[e.jsx("button",{onClick:()=>ue(W),children:e.jsx(ui,{size:16})}),e.jsx("button",{onClick:()=>Et(W),children:e.jsx(Zi,{size:16})}),e.jsx("button",{onClick:()=>dn(W),children:e.jsx(po,{size:16})})]})})]},W.id)})})]})})]}),ct&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>Ce(null),children:e.jsxs("section",{className:"modal diagnosis-modal",onMouseDown:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Technician Diagnosis"}),e.jsx("h2",{children:ct.jobNumber})]}),e.jsx("button",{onClick:()=>Ce(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"diagnosis-outcome-options",children:[e.jsxs("label",{className:De==="repairable"?"selected":"",children:[e.jsx("input",{type:"radio",name:"diagnosisOutcome",checked:De==="repairable",onChange:()=>Te("repairable")}),e.jsx(Go,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Repairable"}),e.jsx("span",{children:"Repair à¦à¦°à¦²à§à¦ product ঠিঠহবà§à¥¤"})]})]}),e.jsxs("label",{className:De==="warranty_recommended"?"selected":"",children:[e.jsx("input",{type:"radio",name:"diagnosisOutcome",checked:De==="warranty_recommended",onChange:()=>Te("warranty_recommended")}),e.jsx(gs,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Product Fault"}),e.jsx("span",{children:"Warranty claim à¦à¦°à¦¾à¦° recommendation দিন।"})]})]})]}),e.jsxs("label",{className:"diagnosis-note-field",children:["Diagnosis Note *",e.jsx("textarea",{rows:5,value:ce,onChange:W=>Ye(W.target.value),placeholder:"যà§à¦®à¦¨: Motherboard power section fault; board-level repair recommended নà§..."})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"vx-button vx-button-secondary",onClick:()=>Ce(null),children:"Cancel"}),e.jsx("button",{className:"vx-button vx-button-primary",onClick:()=>void Sn(),children:"Save Diagnosis"})]})]})}),P&&e.jsx("div",{className:"drawer-backdrop",onMouseDown:()=>ue(null),children:e.jsxs("aside",{className:"job-detail-drawer",onMouseDown:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"drawer-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Service job details"}),e.jsx("h2",{children:P.jobNumber})]}),e.jsx("button",{onClick:()=>ue(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("div",{className:"job-detail-actions",children:[e.jsxs("button",{onClick:()=>window.print(),children:[e.jsx(Wi,{size:17})," Print receive slip"]}),e.jsxs("button",{onClick:()=>B(P),children:[e.jsx(zu,{size:17})," WhatsApp receipt"]}),e.jsxs("button",{onClick:()=>{Et(P),ue(null)},children:[e.jsx(Zi,{size:17})," Edit job"]})]}),P.serviceMode==="onsite"&&e.jsxs("section",{className:"repair-workflow-panel onsite-service-panel",children:[e.jsxs("div",{children:[e.jsx("span",{className:"section-kicker",children:"On-site Service"}),e.jsx("h3",{children:(P.onsiteVisitStatus||"request_received").replaceAll("_"," ")}),e.jsxs("p",{children:[P.siteAddress||"Site address not set",P.scheduledVisitAt?` · ${new Date(P.scheduledVisitAt).toLocaleStr
4155ing("en-GB")}`:""]})]}),e.jsxs("div",{className:"repair-workflow-actions",children:[(P.onsiteVisitStatus||"request_received")==="request_received"&&e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"visit_scheduled"),children:"Visit Scheduled"}),P.onsiteVisitStatus==="visit_scheduled"&&e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"on_the_way"),children:"On the Way"}),P.onsiteVisitStatus==="on_the_way"&&e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"reached_site"),children:"Reached Site"}),P.onsiteVisitStatus==="reached_site"&&e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"work_started"),children:"Start Work"}),P.onsiteVisitStatus==="work_started"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void on(P,"parts_required"),children:"Parts Required"}),e.jsx("button",{onClick:()=>void on(P,"work_paused"),children:"Pause Work"}),e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"work_completed"),children:"Work Completed"})]}),["parts_required","work_paused"].includes(P.onsiteVisitStatus||"")&&e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"work_started"),children:"Resume Work"}),P.onsiteVisitStatus==="work_completed"&&e.jsx("button",{className:"workflow-primary",onClick:()=>void on(P,"customer_confirmed"),children:"Customer Confirmation"})]}),P.onsiteNextVisitRequired&&P.onsiteNextVisitAt&&e.jsxs("div",{className:"onsite-return-visit-summary",children:[e.jsxs("div",{className:"onsite-return-visit-heading",children:[e.jsx("span",{className:"section-kicker",children:"Scheduled Return Visit"}),e.jsx("strong",{children:"Return visit confirmed"})]}),e.jsxs("div",{className:"onsite-return-visit-meta",children:[e.jsxs("span",{className:"onsite-return-visit-chip",children:[e.jsx(nb,{size:16,"aria-hidden":"true"}),e.jsx("strong",{children:new Date(P.onsiteNextVisitAt).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"})})]}),e.jsxs("span",{className:"onsite-return-visit-chip",children:[e.jsx(Ho,{size:16,"aria-hidden":"true"}),e.jsx("strong",{children:new Date(P.onsiteNextVisitAt).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})})]})]})]}),e.jsxs("div",{className:"onsite-field-grid",children:[e.jsxs("label",{children:["Diagnosis / Findings",e.jsx("textarea",{rows:3,value:me.onsiteDiagnosis,onChange:W=>ge(ft=>({...ft,onsiteDiagnosis:W.target.value})),placeholder:"What was found at site?"})]}),e.jsxs("label",{children:["Work Done",e.jsx("textarea",{rows:3,value:me.onsiteWorkDone,onChange:W=>ge(ft=>({...ft,onsiteWorkDone:W.target.value})),placeholder:"Repair / installation / maintenance performed"})]}),e.jsxs("label",{children:["Parts / Materials Used",e.jsx("textarea",{rows:3,value:me.onsitePartsUsed,onChange:W=>ge(ft=>({...ft,onsitePartsUsed:W.target.value})),placeholder:"Parts/materials used at site"})]}),e.jsxs("label",{children:["Next Visit Required",e.jsxs("select",{value:me.onsiteNextVisitRequired?"yes":"no",onChange:W=>{const ft=W.target.value==="yes";Pe("idle"),ge(Zt=>({...Zt,onsiteNextVisitRequired:ft,onsiteNextVisitAt:ft?Zt.onsiteNextVisitAt:""}))},children:[e.jsx("option",{value:"no",children:"No"}),e.jsx("option",{value:"yes",children:"Yes"})]})]}),me.onsiteNextVisitRequired&&e.jsxs("label",{children:["Next Visit Date & Time",e.jsxs("div",{className:"onsite-return-visit-inputs",children:[e.jsx("input",{"aria-label":"Next visit date",type:"date",value:me.onsiteNextVisitAt.slice(0,10),onChange:W=>{Pe("idle"),ge(ft=>({...ft,onsiteNextVisitAt:W.target.value?`${W.target.value}T${ft.onsiteNextVisitAt.slice(11,16)||"09:00"}`:""}))}}),e.jsx("input",{"aria-label":"Next visit time",type:"time",value:me.onsiteNextVisitAt.slice(11,16)||"09:00",onChange:W=>{Pe("idle"),ge(ft=>({...ft,onsiteNextVisitAt:ft.onsiteNextVisitAt.slice(0,10)?`${ft.onsiteNextVisitAt.slice(0,10)}T${W.target.value}`:ft.onsiteNextVisitAt}))}})]}),e.jsx("small",{children:"Choose the return date from the calendar and set the visit time."})]})]}),e.jsxs("div",{className:"onsite-field-save-bar",children:[e.jsxs("div",{className:"onsite-field-save-copy",children:[e.jsx("strong",{children:"Field Report"}),e.jsx("span",{children:de==="saved"?`â Saved${Re?` · ${new Date(Re).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}`:""}`:de==="error"?"Save failed. Please try again.":"Save diagnosis, work, materials and return visit together."})]}),e.jsx("button",{className:"workflow-primary onsite-field-save-button",disabled:de==="saving",onClick:()=>void ke(P),children:de==="saving"?"Saving...":"Save Field Report"})]}),(i==null?void 0:i.banglaQrEnabled)&&(i==null?void 0:i.banglaQrImage)&&P.onsiteVisitStatus==="customer_confirmed"&&e.jsxs("div",{className:"onsite-qr-payment",children:[e.jsxs("div",{children:[e.jsx("span",{className:"section-kicker",children:i.banglaQrLabel||"Bangla QR"}),e.jsx("h3",{children:"Scan to Pay"}),e.jsxs("p",{children:["Payable: à§³",Number(P.dueAmount||0).toLocaleStr
4155ing("en-BD")]})]}),e.jsx("img",{src:i.banglaQrImage,alt:"Company Bangla QR",style:{width:220,height:220,objectFit:"contain",background:"white",padding:10,borderRadius:14}}),e.jsx("button",{className:"workflow-primary",onClick:()=>void Ct(P),children:P.onsitePaymentReference?`Reference: ${P.onsitePaymentReference}`:"Record Payment Reference"})]})]}),e.jsxs("section",{className:"repair-workflow-panel",children:[e.jsxs("div",{children:[e.jsx("span",{className:"section-kicker",children:Rc(P.jobType).workflowTitle}),e.jsx("h3",{children:r5(P).title}),e.jsx("p",{children:r5(P).description})]}),e.jsxs("div",{className:"repair-workflow-actions",children:[P.status==="received"&&P.assignedTechnicianId&&P.assignedTechnician&&(Ge||te)&&e.jsxs("button",{className:"workflow-primary",onClick:()=>Wt(P,"start_diagnosis"),children:[e.jsx(b1,{size:18}),"Start Diagnosis"]}),P.status==="diagnosing"&&Ge&&!P.diagnosisOutcome&&P.warrantyReviewStatus!=="rma_created"&&e.jsxs("button",{className:"workflow-primary",onClick:()=>An(P),children:[e.jsx(b1,{size:18}),"Submit Diagnosis"]}),P.status==="diagnosing"&&P.diagnosisOutcome==="repairable"&&e.jsxs("button",{className:"workflow-primary",onClick:()=>Wt(P,"start_repair"),children:[e.jsx(Go,{size:18}),"Start Repair"]}),P.status==="diagnosing"&&P.diagnosisOutcome==="warranty_recommended"&&P.warrantyReviewStatus!=="rma_created"&&e.jsxs("div",{className:"workflow-waiting-state",children:[e.jsx(Ho,{size:20}),"Waiting for Service In-Charge warranty review."]}),P.status==="diagnosing"&&P.warrantyReviewStatus==="rma_created"&&P.linkedRmaNumber&&e.jsxs("div",{className:"workflow-complete-state",children:[e.jsx(gs,{size:20}),"Warranty processing:"," ",P.linkedRmaNumber]}),P.status==="approved"&&e.jsxs("button",{className:"workflow-primary",onClick:()=>Wt(P,"start_repair"),children:[e.jsx(Go,{size:18}),Rc(P.jobType).startLabel]}),P.status==="repairing"&&e.jsxs("button",{className:"workflow-primary",onClick:()=>Wt(P,"complete_repair"),children:[e.jsx(Ms,{size:18}),Rc(P.jobType).completeLabel]}),P.status==="quality_check"&&e.jsxs("button",{className:"workflow-primary",onClick:()=>Wt(P,"mark_ready"),children:[e.jsx(Ms,{size:18}),"Open Quality Check"]}),P.status==="qc_completed"&&te&&e.jsxs("button",{className:"workflow-primary",onClick:()=>Wt(P,"confirm_ready"),children:[e.jsx(Ms,{size:18}),"Ready for Delivery"]}),P.status==="qc_completed"&&!te&&e.jsxs("div",{className:"workflow-waiting-state",children:[e.jsx(Ho,{size:20}),"QC completed. Waiting for an authorized service user to mark Ready for Delivery."]}),P.status==="ready"&&e.jsxs("div",{className:"workflow-complete-state",children:[e.jsx(Ms,{size:20}),Rc(P.jobType).readyMessage]}),P.status==="waiting_approval"&&e.jsxs("div",{className:"workflow-waiting-state",children:[e.jsx(Ho,{size:20}),"Client approval না পাà¦à§à¦¾ পরà§à¦¯à¦¨à§à¦¤ à¦à¦¾à¦ শà§à¦°à§ à¦à¦°à¦¾ যাবৠনা।"]})]})]}),P.diagnosisOutcome&&e.jsxs("section",{className:"warranty-recommendation-panel",children:[e.jsxs("div",{children:[e.jsx("span",{className:"section-kicker",children:"Technician Diagnosis"}),e.jsx("h3",{children:P.diagnosisOutcome==="warranty_recommended"?"Product Fault â Warranty Recommended":"Repairable Product"}),e.jsx("p",{children:P.diagnosisNote||"Diagnosis note not provided."}),e.jsxs("small",{children:["Diagnosed by"," ",P.diagnosisCompletedBy||"Technician"]})]}),P.diagnosisOutcome==="warranty_recommended"&&P.warrantyReviewStatus!=="rma_created"&&pt&&e.jsxs("button",{className:"workflow-primary",onClick:()=>void Xt(P),children:[e.jsx(gs,{size:18}),"Receive Warranty & Create RMA"]}),P.linkedRmaNumber&&e.jsxs("div",{className:"workflow-complete-state",children:[e.jsx(Ms,{size:20}),"Linked Customer RMA:"," ",P.linkedRmaNumber]})]}),e.jsxs("div",{className:"print-receive-document","aria-hidden":"true",children:[e.jsx(C1,{copyType:"Customer Copy",job:P,customer:y.find(W=>W.id===P.customerId),branchName:((Ln=n.find(W=>W.id===P.branchId))==null?void 0:Ln.name)||"Unknown",companyName:c,companyPhone:(Ca=(wa=n.find(W=>W.id===P.branchId))==null?void 0:wa.contacts)!=null&&Ca.length?n.find(W=>W.id===P.branchId).contacts.map(W=>`${W.label}: ${W.phone}`).join(" · "):((In=n.find(W=>W.id===P.branchId))==null?void 0:In.phone)||l,companyAddress:((Sa=n.find(W=>W.id===P.branchId))==null?void 0:Sa.address)||m,companyLogoUrl:d,trackingUrl:jt(P.id)}),e.jsx("div",{className:"print-cut-line",children:e.jsx("span",{children:"â Cut Here â"})}),e.jsx(C1,{copyType:"Office Copy",job:P,customer:y.find(W=>W.id===P.customerId),branchName:((aa=n.find(W=>W.id===P.branchId))==null?void 0:aa.name)||"Unknown",companyName:c,companyPhone:(jn=($a=n.find(W=>W.id===P.branchId))==null?void 0:$a.contacts)!=null&&jn.length?n.find(W=>W.id===P.branchId).contacts.map(W=>`${W.label}: ${W.phone}`).join(" · "):((vs=n.find(W=>W.id===P.branchId))==null?void 0:vs.phone)||l,companyAddress:((ka=n.find(W=>W.id===P.branchId))==null?void 0:ka.address)||m,companyLogoUrl:d,trackingUrl:jt(P.id)})]}),e.jsxs("section",{className:"job-detail-card professional-job-details",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Customer"}),e.jsx("strong",{children:((Ja=y.find(W=>W.id===P.customerId))==null?void 0:Ja.name)||"Unknown"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Phone"}),e.jsx("strong",{children:((_n=y.find(W=>W.id===P.customerId))==null?void 0:_n.phone)||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Device"}),e.jsxs("strong",{children:[P.deviceCategory," â ",P.brand]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Model / Serial"}),e.jsxs("strong",{children:[P.model||"â"," / ",P.serialNumber||"â"]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Priority"}),e.jsx("strong",{className:`priority priority-${P.priority||"normal"}`,children:P.priority||"normal"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Status"}),e.jsx("strong",{className:`job-status status-${P.status}`,children:Dr(P.status)})]}),e.jsxs("div",{className:"job-detail-highlight technician-assignment-detail",children:[e.jsx("span",{children:"Assigned Technician"}),e.jsx("strong",{children:((ha=P.assignedTechnician)==null?void 0:ha.trim())||"Unassigned"}),P.assignedTechnicianPhone&&e.jsx("small",{children:P.assignedTechnicianPhone}),P.assignedAt&&e.jsxs("small",{children:["Assigned ",new Date(P.assignedAt).toLocaleStr
4155ing("en-GB"),P.assignedByName||J||P.assignedBy?` by ${P.assignedByName||J||(P.assignedBy===t.uid?t.name:"Resolving userâ¦")}`:""]})]}),e.jsxs("div",{className:"job-detail-highlight",children:[e.jsx("span",{children:"Service Mode"}),e.jsx("strong",{children:P.serviceMode==="onsite"?"On-site Service":"In-House Service"})]}),P.serviceMode==="onsite"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("span",{children:"Site Address"}),e.jsx("strong",{children:P.siteAddress||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Site Contact"}),e.jsxs("strong",{children:[P.siteContactPerson||"â"," ",P.siteContactPhone?`· ${P.siteContactPhone}`:""]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Visit Schedule"}),e.jsx("strong",{children:P.scheduledVisitAt?new Date(P.scheduledVisitAt).toLocaleString("en-GB"):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"On-site Status"}),e.jsx("strong",{children:(P.onsiteVisitStatus||"request_received").replaceAll("_"," ")})]})]}),e.jsxs("div",{className:"job-detail-highlight",children:[e.jsx("span",{children:"Service Type"}),e.jsx("strong",{className:"capitalize-text",children:P.serviceType||"repair"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Repair Workflow"}),e.jsx("strong",{children:P.approvalPath==="estimate_required"?"Estimate & Approval":"Quick Service"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Client Approval"}),e.jsx("strong",{className:`approval-state ${P.approvalStatus||"not_required"}`,children:(P.approvalStatus||"not_required").replace("_"," ")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Estimated"}),e.jsxs("strong",{children:["à§³",Number(P.estimatedCost||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Advance"}),e.jsxs("strong",{children:["à§³",Number(P.advanceAmount||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Due"}),e.jsxs("strong",{children:["à§³",Number(P.dueAmount||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Expected Delivery"}),e.jsx("strong",{children:P.expectedDelivery||"Not set"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Warranty Until"}),e.jsx("strong",{children:P.warrantyUntil||"Not set"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Created"}),e.jsx("strong",{children:new Date(P.createdAt).toLocaleString("en-GB")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Last Updated"}),e.jsx("strong",{children:new Date(P.updatedAt).toLocaleString("en-GB")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Branch"}),e.jsx("strong",{children:((ta=n.find(W=>W.id===P.branchId))==null?void 0:ta.name)||"Unknown"})]})]}),e.jsxs("section",{className:"job-description",children:[e.jsx("h3",{children:"Customer complaint"}),e.jsx("p",{children:P.problem}),e.jsx("h3",{children:"Accessories"}),e.jsx("p",{children:[...P.accessoriesList||[],P.accessories||""].filter(Boolean).join(", ")||"None recorded"}),e.jsx("h3",{children:"Physical condition"}),e.jsx("p",{children:(P.physicalConditions||[]).join(", ")||"Not recorded"})]}),e.jsxs("section",{className:"invoice-prep-section",children:[e.jsxs("div",{className:"invoice-prep-section-heading",children:[e.jsx(Zs,{size:18,"aria-hidden":"true"}),e.jsx("h3",{children:"Invoice Preparation"})]}),e.jsxs("div",{className:"invoice-prep-action",children:[e.jsx("div",{className:"invoice-prep-action-icon","aria-hidden":"true",children:e.jsx(Zs,{size:22})}),e.jsxs("div",{className:"invoice-prep-action-copy",children:[e.jsx("strong",{children:P.invoiceId||P.invoiceNumber?"Invoice Created":"Prepare Billable Amount"}),e.jsx("span",{children:P.invoiceId||P.invoiceNumber?`Invoice ${P.invoiceNumber||"linked"} is already created. Billable preparation is locked.`:"Prepare expected service and parts charges before generating the final invoice."}),P.invoicePreparedAt&&!P.invoiceId&&!P.invoiceNumber&&e.jsxs("span",{className:"invoice-prep-status",children:["Prepared: à§³",Math.max(0,Number(P.labourCharge||0)+Number(P.partsTotal||0)-Number(P.discountAmount||0)).toLocaleStr
4155ing("en-GB"),P.invoicePreparedBy?` · by ${P.invoicePreparedBy}`:""]})]}),!P.invoiceId&&!P.invoiceNumber&&e.jsxs("button",{type:"button",className:"primary-button invoice-prep-action-button",onClick:()=>Gt(P),children:[e.jsx(Zi,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:"Prepare / Edit"})]})]})]}),(P.repairPerformed||P.qualityResult)&&e.jsxs("section",{className:"repair-record-section",children:[e.jsx("h3",{children:"Repair & Quality Summary"}),P.repairPerformed&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"repair-record-card",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Repair Performed"}),e.jsx("strong",{children:P.repairPerformed})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Parts Replaced"}),e.jsx("strong",{children:P.partsReplaced||"None"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Service Charges"}),e.jsxs("strong",{children:["৳",Number(P.labourCharge||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Parts Total"}),e.jsxs("strong",{children:["৳",Number(P.partsTotal||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Gross Profit"}),e.jsxs("strong",{children:["৳",Number(P.grossProfit||0).toLocaleString("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Customer Notes"}),e.jsx("strong",{children:P.customerServiceNotes||"Not recorded"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Warranty"}),e.jsx("strong",{children:(P.repairWarranty||"none").replaceAll("_"," ")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Completed By"}),e.jsx("strong",{children:P.repairCompletedBy||"Not recorded"})]})]})}),P.qualityResult&&e.jsxs("div",{className:`quality-result-card ${P.qualityResult}`,children:[e.jsxs("div",{className:"quality-result-heading",children:[e.jsxs("strong",{children:["Quality Inspection"," ",P.qualityResult==="pass"?"Passed":"Failed"]}),e.jsxs("span",{children:["Tested by ",P.qualityCheckedBy||"Not recorded"]})]}),P.qualityChecks&&e.jsx("div",{className:"saved-inspection-results",children:Object.entries(P.qualityChecks).map(([W,ft])=>e.jsxs("div",{children:[e.jsx("span",{children:W.replace(/([A-Z])/g," $1").replace(/^./,Zt=>Zt.toUpperCase())}),e.jsx("strong",{className:ft,children:ft==="na"?"N/A":ft.toUpperCase()})]},W))}),e.jsx("p",{children:P.qualityRemarks||"No remarks"})]})]}),e.jsxs("section",{className:"timeline-section",children:[e.jsx("h3",{children:"Job timeline"}),Be.length===0?e.jsx("p",{className:"muted-text",children:"No timeline entries yet."}):e.jsx("div",{className:"timeline-list",children:Be.map(W=>e.jsxs("article",{children:[e.jsx("span",{className:"timeline-icon",children:e.jsx(Ms,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:W.title}),W.note&&e.jsx("p",{children:W.note}),e.jsxs("small",{children:[W.actorName," · ",new Date(W.createdAt).toLocaleString("en-GB")]})]})]},W.id))})]})]})}),se&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>pe(null),children:e.jsxs("div",{className:"modal-card invoice-prep-modal",onMouseDown:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Invoice Preparation"}),e.jsx("h2",{children:"Prepare Billable Amount"}),e.jsx("span",{children:se.jobNumber})]}),e.jsx("button",{type:"button",onClick:()=>pe(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:$t,className:"data-form invoice-prep-business-form",children:[e.jsx("div",{className:"invoice-prep-section-heading",children:"Billable Amount"}),e.jsx("p",{className:"invoice-prep-note",children:"Preparation only. Final Product/Service billing remains controlled from Generate Invoice."}),e.jsxs("div",{className:"invoice-prep-compact-grid",children:[e.jsxs("label",{children:[e.jsx("span",{children:"Service Charge"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:Se.serviceCharge,onChange:W=>Me({...Se,serviceCharge:Number(W.target.value)})})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Parts / Product Total"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:Se.partsTotal,onChange:W=>Me({...Se,partsTotal:Number(W.target.value)})})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Discount"}),e.jsx("input",{type:"number",min:"0",step:"0.01",value:Se.discountAmount,onChange:W=>Me({...Se,discountAmount:Number(W.target.value)})})]})]}),e.jsx("div",{className:"invoice-prep-section-heading invoice-prep-detail
4155s-heading",children:"Parts / Product Details"}),e.jsxs("label",{className:"invoice-prep-details-row",children:[e.jsx("span",{children:"Details"}),e.jsx("textarea",{value:Se.partsUsedDetails,onChange:W=>Me({...Se,partsUsedDetails:W.target.value}),placeholder:"Optional preparation note; final product/service billing is controlled in Invoice."})]}),e.jsxs("div",{className:"invoice-prep-total",children:[e.jsx("span",{children:"Prepared Billable Amount"}),e.jsxs("strong",{children:["à§³",Math.max(0,Number(Se.serviceCharge||0)+Number(Se.partsTotal||0)-Number(Se.discountAmount||0)).toLocaleString("en-GB")]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",onClick:()=>pe(null),children:"Cancel"}),e.jsx("button",{type:"submit",className:"primary-button",children:"Save Invoice Preparation"})]})]})]})}),ee&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>qe(null),children:e.jsxs("div",{className:"modal-card repair-summary-modal",onMouseDown:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Repair Record"}),e.jsx("h2",{children:"Complete Repair"}),e.jsx("span",{children:ee.jobNumber})]}),e.jsx("button",{type:"button",onClick:()=>qe(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:Vt,className:"data-form repair-summary-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"full-width",children:[Rc(ee.jobType).performedLabel,e.jsx("textarea",{value:Je.repairPerformed,onChange:W=>le({...Je,repairPerformed:W.target.value}),placeholder:Rc(ee.jobType).performedPlaceholder})]}),e.jsxs("div",{className:"full-width repair-parts-field",children:[e.jsx("span",{className:"repair-field-label",children:Rc(ee.jobType).partsLabel}),e.jsx("div",{className:"repair-parts-list",children:["SSD","HDD","RAM","Keyboard","Mouse","Adapter","Battery","Display","Motherboard","Power Supply","Cooling Fan","Charging Port","LAN Card","WiFi Card","Cable"].map(W=>{const ft=Je.partsReplaced.split(",").map(vt=>vt.trim()).filter(Boolean),Zt=ft.includes(W);return e.jsxs("label",{className:"repair-part-option",children:[e.jsx("input",{type:"checkbox",checked:Zt,onChange:vt=>{const Ae=vt.target.checked?[...ft,W]:ft.filter(oe=>oe!==W);le({...Je,partsReplaced:Ae.join(", ")})}}),e.jsx("span",{children:W})]},W)})}),e.jsxs("div",{className:"repair-custom-part",children:[e.jsx("input",{value:Je.customPart,onCh
4155ange:W=>le({...Je,customPart:W.target.value}),placeholder:"Other part name"}),e.jsx("button",{type:"button",onClick:()=>{const W=Je.customPart.trim();if(!W)return;const ft=Je.partsReplaced.split(",").map(Zt=>Zt.trim()).filter(Boolean);ft.includes(W)||ft.push(W),le({...Je,partsReplaced:ft.join(", "),customPart:""})},children:"Add Part"})]}),Je.partsReplaced&&e.jsxs("div",{className:"selected-parts-summary",children:[e.jsx("strong",{children:"Selected:"})," ",Je.partsReplaced]})]}),e.jsxs("div",{className:"full-width service-financial-section",children:[e.jsx("div",{className:"service-section-heading",children:e.jsxs("div",{children:[e.jsx("strong",{children:"Service Charge Breakdown"}),e.jsx("span",{children:"Customer invoice-ঠTotal Service Charges যাবà§à¥¤"})]})}),e.jsxs("div",{className:"service-charge-grid",children:[e.jsxs("label",{children:["Diagnosis Charge",e.jsx("input",{type:"number",min:"0",value:Je.diagnosisCharge,onChange:W=>le({...Je,diagnosisCharge:Number(W.target.value)})})]}),e.jsxs("label",{children:["Repair Charge",e.jsx("input",{type:"number",min:"0",value:Je.repairCharge,onChange:W=>le({...Je,repairCharge:Number(W.target.value)})})]}),e.jsxs("label",{children:["Installation / Configuration",e.jsx("input",{type:"number",min:"0",value:Je.installationCharge,onChange:W=>le({...Je,installationCharge:Number(W.target.value)})})]}),e.jsxs("label",{children:["Other Service Charge",e.jsx("input",{type:"number",min:"0",value:Je.otherServiceCharge,onChange:W=>le({...Je,otherServiceCharge:Number(W.target.value)})})]})]}),e.jsxs("div",{className:"service-total-line",children:[e.jsx("span",{children:"Total Service Charges"}),e.jsxs("strong",{children:["à§³",(Number(Je.diagnosisCharge||0)+Number(Je.repairCharge||0)+Number(Je.installationCharge||0)+Number(Je.otherServiceCharge||0)).toLocaleString("en-GB")]})]})]}),e.jsxs("label",{children:["Parts & Accessories Selling Total",e.jsx("input",{type:"number",min:"0",value:Je.partsTotal,onChange:W=>le({...Je,partsTotal:Number(W.target.value)})})]}),e.jsxs("label",{className:"full-width",children:["Parts Used Details",e.jsx("textarea",{value:Je.partsUsedDetails,onChange:W=>le({...Je,partsUsedDetails:W.target.value}),placeholder:"Example: SSD 256GB â Qty 1 â Serial/remarks..."})]}),e.jsxs("label",{children:["Warranty",e.jsxs("select",{value:Je.repairWarranty,onChange:W=>le({...Je,repairWarranty:W.target.value}),children:[e.jsx("option",{value:"none",children:"No Warranty"}),e.jsx("option",{value:"7_days",children:"7 Days"}),e.jsx("option",{value:"30_days",children:"30 Days"}),e.jsx("option",{value:"90_days",children:"90 Days"}),e.jsx("option",{value:"6_months",children:"6 Months"}),e.jsx("option",{value:"1_year",children:"1 Year"})]})]}),e.jsxs("label",{className:"full-width",children:["Customer-visible Service Notes",e.jsx("textarea",{value:Je.customerServiceNotes,onChange:W=>le({...Je,customerServiceNotes:W.target.value}),placeholder:"Customer receipt/tracking-ঠদà§à¦à¦¾à¦¨à§ যাবৠà¦à¦®à¦¨ à¦à¦¾à¦à§à¦° summary..."})]}),e.jsxs("label",{className:"full-width",children:["Internal Technician Notes",e.jsx("textarea",{value:Je.repairNotes,onChange:W=>le({...Je,repairNotes:W.target.value}),placeholder:"শà§à¦§à§ authorised staff দà§à¦à¦¬à§..."})]}),e.jsxs("div",{className:"full-width service-financial-section internal-cost-section",children:[e.jsx("div",{className:"service-section-heading",children:e.jsxs("div",{children:[e.jsx("strong",{children:"Internal Cost & Profit"}),e.jsx("span",{children:"à¦à¦ তথà§à¦¯ customer invoice বা public tracking-ঠযাবৠনা।"})]})}),e.jsxs("div",{className:"service-charge-grid",children:[e.jsxs("label",{children:["Technician Cost",e.jsx("input",{type:"number",min:"0",value:Je.technicianCost,onChange:W=>le({...Je,technicianCost:Number(W.target.value)})})]}),e.jsxs("label",{children:["Parts Cost",e.jsx("input",{type:"number",min:"0",value:Je.partsCost,onChange:W=>le({...Je,partsCost:Number(W.target.value)})})]}),e.jsxs("label",{children:["Outside Repair Cost",e.jsx("input",{type:"number",min:"0",value:Je.outsideRepairCost,onChange:W=>le({...Je,outsideRepairCost:Number(W.target.value)})})]}),e.jsxs("label",{children:["Other Expense",e.jsx("input",{type:"number",min:"0",value:Je.otherServiceCost,onChange:W=>le({...Je,otherServiceCost:Number(W.target.value)})})]})]}),e.jsxs("div",{className:"profit-preview-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Total Revenue"}),e.jsxs("strong",{children:["à§³",(Number(Je.diagnosisCharge||0)+Number(Je.repairCharge||0)+Number(Je.installationCharge||0)+Number(Je.otherServiceCharge||0)+Number(Je.partsTotal||0)).toLocaleStr
4155ing("en-GB")]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total Internal Cost"}),e.jsxs("strong",{children:["à§³",(Number(Je.technicianCost||0)+Number(Je.partsCost||0)+Number(Je.outsideRepairCost||0)+Number(Je.otherServiceCost||0)).toLocaleString("en-GB")]})]}),e.jsxs("div",{className:"profit-result",children:[e.jsx("span",{children:"Gross Profit"}),e.jsxs("strong",{children:["à§³",(Number(Je.diagnosisCharge||0)+Number(Je.repairCharge||0)+Number(Je.installationCharge||0)+Number(Je.otherServiceCharge||0)+Number(Je.partsTotal||0)-Number(Je.technicianCost||0)-Number(Je.partsCost||0)-Number(Je.outsideRepairCost||0)-Number(Je.otherServiceCost||0)).toLocaleString("en-GB")]})]})]})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",onClick:()=>qe(null),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"primary-button",children:[e.jsx(Ms,{size:17}),"Save Work Summary"]})]})]})]})}),ot&&e.jsx("div",{className:"modal-backdrop",onMouseDown:()=>wt(null),children:e.jsxs("div",{className:"modal-card quality-check-modal",onMouseDown:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Supervisor Test"}),e.jsx("h2",{children:"Quality Check"}),e.jsx("span",{children:ot.jobNumber})]}),e.jsx("button",{type:"button",onClick:()=>wt(null),children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:sn,className:"data-form quality-check-form",children:[e.jsxs("div",{className:"inspection-intro",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Enterprise Inspection Checklist"}),e.jsx("span",{children:"পà§à¦°à¦¤à¦¿à¦à¦¿ item-à¦à¦° PASS, FAIL à¦
থবা N/A নিরà§à¦¬à¦¾à¦à¦¨ à¦à¦°à§à¦¨à¥¤"})]}),e.jsx("div",{className:`inspection-overall ${Object.values(nt).filter(W=>W==="fail").length>0?"fail":"pass"}`,children:Object.values(nt).some(W=>W==="fail")?"OVERALL: FAIL":"OVERALL: PASS"})]}),e.jsxs("div",{className:"inspection-section",children:[e.jsx("h3",{children:"System & Hardware Inspection"}),e.jsx("div",{className:"enterprise-inspection-grid",children:[["boot","Boot Test"],["operatingSystem","Windows / OS"],["driver","Driver Test"],["motherboard","Motherboard"],["ram","RAM"],["storage","SSD / HDD"],["display","Display"],["keyboard","Keyboard"],["mouseTouchpad","Mouse / Touchpad"],["usb","USB Ports"],["audio","Audio"],["network","LAN"],["wifi","WiFi"],["bluetooth","Bluetooth"],["webcam","Webcam"],["battery","Battery"],["charger","Charger"],["bios","BIOS"],["stress","Stress Test"]].map(([W,ft])=>e.jsxs("div",{className:"enterprise-inspection-item",children:[e.jsx("strong",{children:ft}),e.jsx("div",{className:"inspection-result-options",children:["pass","fail","na"].map(Zt=>e.jsxs("label",{className:`inspection-result-option ${Zt} ${nt[W]===Zt?"selected":""}`,children:[e.jsx("input",{type:"radio",name:`inspection-${W}`,value:Zt,checked:nt[W]===Zt,onChange:()=>xt({...nt,[W]:Zt})}),e.jsx("span",{children:Zt==="pass"?"PASS":Zt==="fail"?"FAIL":"N/A"})]},Zt))})]},W))})]}),e.jsx("div",{className:"inspection-remarks",children:e.jsxs("label",{children:["Supervisor Remarks",e.jsx("textarea",{value:nt.remarks,onChange:W=>xt({...nt,remarks:W.target.value}),placeholder:"FAIL হলৠà¦à¦¾à¦°à¦£ বাধà§à¦¯à¦¤à¦¾à¦®à§à¦²à¦à¥¤ PASS হলৠoptional final notes..."})]})}),e.jsxs("div",{className:"inspection-signoff",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Tested By"}),e.jsx("strong",{children:t.name})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Inspection Time"}),e.jsx("strong",{children:new Date().toLocaleString("en-GB")})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Decision"}),e.jsx("strong",{children:Object.values(nt).some(W=>W==="fail")?"Return to Repairing":"Ready for Delivery"})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",onClick:()=>wt(null),children:"Cancel"}),e.jsxs("button",{type:"submit",className:"primary-button",children:[e.jsx(Ms,{size:17}),"Save Inspection"]})]})]})]})}),z&&e.jsx("div",{className:"modal-backdrop",onMouseDown:Rt,children:e.jsxs("section",{className:"modal job-modal",onMouseDown:W=>W.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:K?"Existing service entry":"New service entry"}),e.jsx("h2",{children:K?"Update Service Job":"Receive New Device"}),e.jsx("p",{className:"modal-subtitle",children:K?"Review the existing information and save only the required changes.":"Create a new service job and generate a unique Job Number."})]}),e.jsx("button",{onClick:Rt,children:e.jsx(ja,{size:20})})]}),K&&e.jsxs("section",{className:"edit-job-summary",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Job Number"}),e.jsx("strong",{children:K.jobNumber})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Current Status"}),e.jsx("strong",{children:Dr(K.status)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Created"}
4155),e.jsx("strong",{children:new Date(K.createdAt).toLocaleString("en-GB")})]})]}),e.jsxs("form",{onSubmit:xn,className:"data-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Customer",e.jsxs("select",{value:D.customerId,onChange:W=>M({...D,customerId:W.target.value}),required:!0,children:[e.jsx("option",{value:"",children:"Select customer"}),y.filter(W=>W.active!==!1).map(W=>e.jsxs("option",{value:W.id,children:[W.name," â ",W.phone]},W.id))]})]}),e.jsxs("label",{children:["Branch",e.jsxs("select",{value:D.branchId,onChange:W=>M({...D,branchId:W.target.value,customerId:""}),required:!0,children:[e.jsx("option",{value:"",children:"Select branch"}),n.map(W=>e.jsx("option",{value:W.id,children:W.name},W.id))]})]}),e.jsxs("label",{children:["Service mode",e.jsxs("select",{value:D.serviceMode,onChange:W=>M({...D,serviceMode:W.target.value}),children:[e.jsx("option",{value:"in_house",children:"In-House Service"}),e.jsx("option",{value:"onsite",children:"On-site Service"})]})]}),e.jsxs("label",{children:["Job type",e.jsxs("select",{value:D.jobType||"repair",onChange:W=>M({...D,jobType:W.target.value}),children:[e.jsx("option",{value:"repair",children:"Repair"}),e.jsx("option",{value:"new_pc_assembly",children:"New PC Assembly"}),e.jsx("option",{value:"upgrade",children:"Upgrade"}),e.jsx("option",{value:"windows_installation",children:"Windows Installation"}),e.jsx("option",{value:"networking",children:"Networking"}),e.jsx("option",{value:"cctv",children:"CCTV"}),e.jsx("option",{value:"amc",children:"AMC / Maintenance"}),e.jsx("option",{value:"other",children:"Other"})]})]}),e.jsxs("label",{children:["Device category",e.jsxs("select",{value:D.deviceCategory,onChange:W=>M({...D,deviceCategory:W.target.value,technicalDetails:{}}),children:[e.jsx("option",{children:"Laptop"}),e.jsx("option",{children:"Desktop"}),e.jsx("option",{children:"Printer"}),e.jsx("option",{children:"UPS"}),e.jsx("option",{children:"Monitor"}),e.jsx("option",{children:"CCTV / Surveillance"}),e.jsx("option",{children:"Networking Device"}),e.jsx("option",{children:"Other"})]})]}),e.jsxs("label",{children:["Brand",e.jsx("input",{value:D.brand,onChange:W=>M({...D,brand:W.target.value}),required:!0})]}),e.jsxs("label",{children:["Model",e.jsx("input",{value:D.model,onChange:W=>M({...D,model:W.target.value})})]}),e.jsxs("label",{children:["Serial number",e.jsx("input",{value:D.serialNumber,onChange:W=>M({...D,serialNumber:W.target.value})})]}),["Laptop","Desktop"].includes(D.deviceCategory)&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Asset ID / Service Tag",e.jsx("input",{value:D.imei,onChange:W=>M({...D,imei:W.target.value})})]}),e.jsxs("label",{children:["Colour",e.jsx("input",{value:D.colour,onChange:W=>M({...D,colour:W.target.value})})]}),e.jsxs("label",{children:["Login password / PIN",e.jsx("input",{value:D.loginPassword,onChange:W=>M({...D,loginPassword:W.target.value})})]}),e.jsxs("label",{children:["Operating System",e.jsx("input",{value:D.technicalDetails.operatingSystem||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,operatingSystem:W.target.value}}),placeholder:"Windows / Linux / Other"})]})]}),D.deviceCategory==="UPS"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Capacity (VA / kVA)",e.jsx("input",{value:D.technicalDetails.capacity||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,capacity:W.target.value}}),placeholder:"e.g. 1200 VA / 3 kVA"})]}),e.jsxs("label",{children:["Phase",e.jsx("input",{value:D.technicalDetails.phase||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,phase:W.target.value}}),placeholder:"Single / Three Phase"})]}),e.jsxs("label",{children:["Battery quantity",e.jsx("input",{type:"number",min:"0",value:D.technicalDetails.batteryQty||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,batteryQty:W.target.value}})})]}),e.jsxs("label",{children:["Battery type / capacity",e.jsx("input",{value:D.technicalDetails.batterySpec||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,batterySpec:W.target.value}}),placeholder:"e.g. 12V 9Ah"})]}),e.jsxs("label",{children:["Input voltage",e.jsx("input",{value:D.technicalDetails.inputVoltage||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,inputVoltage:W.target.value}})})]}),e.jsxs("label",{children:["Output voltage",e.jsx("input",{value:D.technicalDetails.outputVoltage||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,outputVoltage:W.target.value}})})]}),e.jsxs("label",{children:["Connected load",e.jsx("input",{value:D.technicalDetails.connectedLoad||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,connectedLoad:W.target.value}}),placeholder:"Watt / equipment"})]})]}),D.deviceCategory==="Printer"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Printer type",e.jsx("input",{value:D.technicalDetails.printerType||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,printerType:W.target.value}}),placeholder:"Laser / Inkjet / Dot Matrix"})]}),e.jsxs("label",{children:["Interface",e.jsx("input",{value:D.technicalDetails.interface||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,interface:W.target.value}}),placeholder:"USB / LAN / Wi-Fi"})]}),e.jsxs("label",{children:["Toner / Cartridge",e.jsx("input",{value:D.technicalDetails.consumable||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,consumable:W.target.value}})})]}),e.jsxs("label",{children:["Page / Counter reading",e.jsx("input",{value:D.technicalDetails.counterReading||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,counterReading:W.target.value}})})]})]}),D.deviceCategory==="CCTV / Surveillance"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["System type",e.jsx("input",{value:D.technicalDetails.cctvType||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,cctvType:W.target.value}}),placeholder:"IP / Analog / Hybrid"})]}),e.jsxs("label",{children:["Recorder type",e.jsx("input",{value:D.technicalDetails.recorderType||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,recorderType:W.target.value}}),placeholder:"DVR / NVR"})]}),e.jsxs("label",{children:["Channel",e.jsx("input",{value:D.technicalDetails.channelCount||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,channelCount:W.target.value}}),placeholder:"4 / 8 / 16 / 32"})]}),e.jsxs("label",{children:["Camera quantity",e.jsx("input",{type:"number",min:"0",value:D.technicalDetails.cameraQty||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,cameraQty:W.target.value}})})]}),e.jsxs("label",{children:["Storage / HDD",e.jsx("input",{value:D.technicalDetails.storage||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,storage:W.target.value}}),placeholder:"e.g. 2 TB"})]}),e.jsxs("label",{children:["Network / IP info",e.jsx("input",{value:D.technicalDetails.networkInfo||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,networkInfo:W.target.value}}),placeholder:"LAN / IP range (no passwords)"})]}),e.jsxs("label",{className:"full-field",children:["Installation location",e.jsx("input",{value:D.technicalDetails.installationLocation||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,installationLocation:W.target.value}})})]})]}),D.deviceCategory==="Networking Device"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Device type",e.jsx("input",{value:D.technicalDetails.networkDeviceType||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,networkDeviceType:W.target.value}}),placeholder:"Router / Switch / Access Point"})]}),e.jsxs("label",{children:["Port count",e.jsx("input",{value:D.technicalDetails.portCount||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,portCount:W.target.value}})})]}),e.jsxs("label",{children:["Network / IP info",e.jsx("input",{value:D.technicalDetails.networkInfo||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,networkInfo:W.target.value}}),placeholder:"LAN / IP range (no passwords)"})]}),e.jsxs("label",{children:["Installation location",e.jsx("input",{value:D.technicalDetails.installationLocation||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,installationLocation:W.target.value}})})]})]}),D.deviceCategory==="Monitor"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{children:["Screen size",e.jsx("input",{value:D.technicalDetails.screenSize||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,screenSize:W.target.value}}),placeholder:"e.g. 24 inch"})]}),e.jsxs("label",{children:["Panel / Display type",e.jsx("input",{value:D.technicalDetails.panelType||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,panelType:W.target.value}}),placeholder:"IPS / VA / LED"})]}),e.jsxs("label",{children:["Input ports",e.jsx("input",{value:D.technicalDetails.inputPorts||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,inputPorts:W.target.value}}),placeholder:"HDMI / DP / VGA"})]})]}),D.deviceCategory==="Other"&&e.jsxs("label",{className:"full-field",children:["Technical identification / specification",e.jsx("input",{value:D.technicalDetails.specification||"",onChange:W=>M({...D,technicalDetails:{...D.technicalDetails,specification:W.target.value}})})]}),e.jsxs("label",{className:"full-field",children:["Problem description",e.jsx("textarea",{rows:3,value:D.problem,onChange:W=>M({...D,problem:W.target.value}),required:!0})]}),D.serviceMode==="onsite"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"full-field",children:["Site address",e.jsx("textarea",{rows:2,value:D.siteAddress,onChange:W=>M({...D,siteAddress:W.target.value}),required:!0,placeholder:"Customer site / office address"})]}),e.jsxs("label",{children:["Site contact person",e.jsx("input",{value:D.siteContactPerson,onChange:W=>M({...D,siteContactPerson:W.target.value})})]}),e.jsxs("label",{children:["Site contact number",e.jsx("input",{value:D.siteContactPhone,onChange:W=>M({...D,siteContactPhone:W.target.value}),required:!0})]}),e.jsxs("label",{children:["Preferred visit date & time",e.jsx("input",{type:"datetime-local",value:D.scheduledVisitAt,onChange:W=>M({...D,scheduledVisitAt:W.target.value})})]}),e.jsxs("label",{children:["Visit charge",e.jsx("input",{type:"number",min:"0",step:"0.01",value:D.onsiteVisitCharge,onChange:W=>M({...D,onsiteVisitCharge:Number(W.target.value)})})]}),e.jsxs("label",{children:["Transport charge",e.jsx("input",{type:"number",min:"0",step:"0.01",value:D.onsiteTransportCharge,onChange:W=>M({...D,onsiteTransportCharge:Number(W.target.value)})})]}),e.jsxs("label",{children:["Other on-site charge",e.jsx("input",{type:"number",min:"0",step:"0.01",value:D.onsiteOtherCharge,onChange:W=>M({...D,onsiteOtherCharge:Number(W.target.value)})})]})]}),["Laptop","Desktop","Printer","Monitor","Other"].includes(D.deviceCategory)&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"full-field",children:["Accessories received",e.jsx("textarea",{rows:2,value:D.accessories,onChange:W=>M({...D,accessories:W.target.value}),placeholder:"Adapter, bag, cable..."})]}),e.jsxs("fieldset",{className:"checklist-field full-field",children:[e.jsx("legend",{children:"Accessories checklist"}),e.jsx("div",{className:"checklist-grid",children:["Adapter","Charger","Battery","Bag","Mouse","Keyboard","Power Cable","USB Cable","Toner/Cartridge","Remote"].map(W=>e.jsxs("label",{className:"check-item",children:[e.jsx("input",{type:"checkbox",checked:D.accessoriesList.includes(W),onChange:()=>Nt("accessoriesList",W)}),e.jsx("span",{children:W})]},W))})]})]}),e.jsxs("fieldset",{className:"checklist-field full-field",children:[e.jsx("legend",{children:"Physical condition"}),e.jsx("div",{className:"checklist-grid",children:["Good","Scratch","Dent","Crack","Broken","Water Damage","Missing Screw","Screen Damage"].map(W=>e.jsxs("label",{className:"check-item",children:[e.jsx("input",{type:"checkbox",checked:D.physicalConditions.includes(W),onChange:()=>Nt("physicalConditions",W)}),e.jsx("span",{children:W})]},W))})]}),e.jsxs("label",{className:"full-field",children:["Condition note",e.jsx("textarea",{rows:2,value:D.conditionNote,onChange:W=>M({...D,conditionNote:W.target.value})})]}),e.jsxs("label",{children:["Estimated cost",e.jsx("input",{type:"number",min:"0",step:"0.01",value:D.estimatedCost,onChange:W=>M({...D,estimatedCost:Number(W.target.value)})})]}),e.jsxs("label",{children:["Advance received",e.jsx("input",{type:"number",min:"0",step:"0.01",value:D.advanceAmount,onChange:W=>M({...D,advanceAmount:Number(W.target.value)})})]}),e.jsxs("label",{children:["Discount",e.jsx("input",{type:"number",min:"0",step:"0.01",value:D.discountAmount,onChange:W=>M({...D,discountAmount:Number(W.target.value)})})]}),e.jsxs("label",{children:["Calculated due",e.jsx("input",{value:`à§³${be(D.estimatedCost,D.advanceAmount,D.discountAmount).toLocaleStr
4155ing("en-GB")}`,disabled:!0})]}),e.jsxs("label",{children:["Expected delivery",e.jsx("input",{type:"date",value:D.expectedDelivery,onChange:W=>M({...D,expectedDelivery:W.target.value})})]}),e.jsxs("label",{children:["Warranty until",e.jsx("input",{type:"date",value:D.warrantyUntil,onChange:W=>M({...D,warrantyUntil:W.target.value})})]}),e.jsxs("label",{children:["Priority",e.jsxs("select",{value:D.priority,onChange:W=>M({...D,priority:W.target.value}),children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"}),e.jsx("option",{value:"urgent",children:"Urgent"})]})]}),e.jsxs("label",{children:["Service type",e.jsxs("select",{value:D.serviceType,onChange:W=>M({...D,serviceType:W.target.value}),children:[e.jsx("option",{value:"inspection",children:"Inspection"}),e.jsx("option",{value:"repair",children:"Repair"}),e.jsx("option",{value:"warranty",children:"Warranty Service"}),e.jsx("option",{value:"installation",children:"Installation"}),e.jsx("option",{value:"maintenance",children:"Maintenance"})]})]}
4155),e.jsxs("label",{children:["Repair workflow",e.jsxs("select",{value:D.approvalPath,onChange:W=>{const ft=W.target.value;M({...D,approvalPath:ft,approvalStatus:ft==="quick_service"?"not_required":D.approvalStatus==="not_required"?"pending":D.approvalStatus,status:ft==="estimate_required"&&D.status==="diagnosing"?"waiting_approval":D.status})},children:[e.jsx("option",{value:"quick_service",children:"Quick Service â Estimate not required"}),e.jsx("option",{value:"estimate_required",children:"Estimate & Client Approval required"})]}),e.jsx("small",{className:"field-help",children:"Windows setup বা à¦à§à¦ à¦à¦¾à¦à§à¦° à¦à¦¨à§à¦¯ Quick Service বà§à¦¯à¦¬à¦¹à¦¾à¦° à¦à¦°à§à¦¨à¥¤ Parts change বা বৠrepair হলৠEstimate approval বà§à¦à§ নিন।"})]}),e.jsxs("label",{children:["Approval status",e.jsxs("select",{value:D.approvalStatus,disabled:D.approvalPath==="quick_service",onChange:W=>M({...D,approvalStatus:W.target.value}),children:[e.jsx("option",{value:"not_required",children:"Not Required"}),e.jsx("option",{value:"pending",children:"Pending Client Approval"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"rejected",children:"Rejected"})]})]}),e.jsxs("label",{children:["Assigned Technician",e.jsxs("select",{value:D.assignedTechnicianId,onChange:W=>{const ft=G.find(Zt=>Zt.id===W.target.value);M({...D,assignedTechnicianId:(ft==null?void 0:ft.id)||"",assignedTechnician:(ft==null?void 0:ft.name)||"",assignedTechnicianPhone:(ft==null?void 0:ft.phone)||""})},children:[e.jsx("option",{value:"",children:"Unassigned"}),G.filter(W=>W.active!==!1&&String(W.branchId||"").trim()===String(D.branchId||"").trim()).map(W=>{var ft;return e.jsxs("option",{value:W.id,children:[W.name,` â ${Qt(W.id)} active job${Qt(W.id)===1?"":"s"}`,(ft=W.technicianSkills)!=null&&ft.length?` â ${W.technicianSkills.slice(0,2).join(", ")}`:""]},W.id)})]}),e.jsx("small",{className:"field-help",children:"Selected branch-à¦à¦° active technician-রাঠদà§à¦à¦¾à¦¬à§à¥¤"})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:D.status,onChange:W=>M({...D,status:W.target.value}),children:[e.jsx("option",{value:"received",children:"Received"}),e.jsx("option",{value:"diagnosing",children:"Diagnosing"}),e.jsx("option",{value:"waiting_approval",children:"Waiting Approval"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"repairing",children:"Repairing"}),e.jsx("option",{value:"quality_check",children:"Quality Check"}),e.jsx("option",{value:"qc_completed",children:"QC Completed"}),e.jsx("option",{value:"ready",children:"Ready for Delivery"}),e.jsx("option",{value:"delivered",children:"Delivered"}),e.jsx("option",{value:"closed",children:"Closed"}),e.jsx("option",{value:"cancelled",children:"Cancelled"}),e.jsx("option",{value:"unknown",children:"Unknown Status"})]})]}),e.jsxs("label",{className:"full-field",children:["Internal notes",e.jsx("textarea",{rows:3,value:D.internalNotes,onChange:W=>M({...D,internalNotes:W.target.value})})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:Rt,children:K?"Back":"Cancel"}),e.jsxs("button",{type:"submit",disabled:Z,children:[e.jsx(hr,{size:17}),Z?K?"Updating...":"Creating...":K?"Update Service Job":"Create Service Job"]})]})]})]})})]})}const JU=[{version:"5.4.619",date:"30 Sep 2026",title:"Purchase Bill Preview & Professional Print Layout",changes:["Added Purchase Bill Preview from Reports â Purchase â Datewise Purchase via clickable Purchase No. and Preview action.","Purchase preview follows the approved purchase document structure with supplier info, product/model, serial numbers, quantity, unit, rate, discount, totals, remarks and signature area.","Purchase posting, stock, supplier payable, accounting and sequential numbering logic are unchanged."]},{version:"5.4.606",date:"30 Sep 2026",title:"Live Purchase Entry Foundation",changes:["Added Purchase â New Purchase with branch, supplier invoice reference, product, quantity, rate and optional serial capture.","Posting a Purchase now updates live branch stock and serial evidence and auto-posts Dr Inventory / Cr Accounts Payable so existing Supplier Payment, Supplier Payable and Datewise Purchase flows can consume the same purchase record.","Added Purchase & Inventory read/manage capabilities, duplicate supplier-invoice protection, accounting-period lock protection and duplicate in-stock serial validation."]},{version:"5.4.488",date:"11 Sep 2026",title:"Datewise PDF Download Fix + One-Click VPS Upd
4155ater",changes:["Fixed Datewise Sales/Purchase PDF preview blob lifetime so Chrome viewer download remains available and closing the preview does not trigger a false popup-blocked alert.","Added a Windows One-Click VPS updater that uploads the latest Full Replacement ZIP, creates a server backup, verifies/extracts/builds in staging, switches live only after success, reloads Nginx, verifies the live version and keeps rollback data."]},{version:"5.4.487",date:"10 Sep 2026",title:"Datewise Sales/Purchase PDF Actions",changes:["Added native VERIXO View PDF and Download PDF actions to dedicated Datewise Sales and Datewise Purchase reports.","A4 landscape PDF uses existing filtered report data, wrapped Product/Serial cells, repeated table headers, totals and page footer; Sales/Purchase/accounting/migration data logic is unchanged."]},{version:"5.4.486",date:"10 Sep 2026",title:"Datewise Report Navigation Regression Gate Alignment",changes:["Aligned the existing datewise Sales/Purchase regression gate with the approved dedicated Reports â Sales â Datewise Sales and Reports â Purchase â Datewise Purchase navigation.","No Sales/Purchase report data source, historical import, collection, due, payment, accounting, target, stock or Firebase permission logic changed."]},{version:"5.4.485",date:"09 Sep 2026",title:"Dedicated Datewise Sales & Purchase Reports Navigation",changes:["Moved Datewise Sales out of Analytics & Reports into Reports â Sales â Datewise Sales without changing its existing data source, historical/live sales logic, collection, due, payment or accounting status logic.","Moved Datewise Purchase out of Analytics & Reports into Reports â Purchase â Datewise Purchase using the same existing report implementation.","Removed the duplicate Datewise Sales/Purchase tabs from the generic Analytics & Reports page; report calculations and stored data remain unchanged."]},{version:"5.4.484",date:"09 Sep 2026",title:"Salary Payable VERIXO PDF Action Buttons",changes:["Restyled View PDF and Download PDF with dedicated VERIXO action controls, consistent spacing, icon alignment, rounded corners, hover states and disabled states.","View PDF uses the primary VERIXO blue treatment while Download PDF uses the clean secondary outline treatment.","No Salary Payable calculation, payroll, payment, accounting, locked-period, or PDF data logic changed."]},{version:"5.4.483",date:"09 Sep 2026",title:"Salary Payable PDF Layout & Document Title Fix",changes:["PDF metadata now carries the company/report/month title so capable viewers show a meaningful document title instead of a blob UUID.","Salary Payable employee table now expands across the available A4 landscape width, removing the unused right-side gap.","No payroll calculation, payment, accounting, or locked-period data logic changed."]},{version:"5.4.481",date:"09 Sep 2026",title:"Locked Payroll Employee Addition + Effective Salary Revision",changes:["Added controlled employee addition to an already locked payroll without recalculating existing employee rows or payment history.","Added effective-dated salary revision history so future increments do not overwrite prior-month salary context.","Payroll generation resolves the salary structure effective for the selected payroll month; accounting/payable/statutory totals remain synchronized for controlled locked additions."]},{version:"5.4.307",date:"28 Aug 2026",title:"Oner Serial Block Reconciliation",changes:["Fixed Current Stock With Cost serial extraction for the actual Oner layout: product row â Serial No(s) â serial values.","Phase 2 remains reference-only and can safely be re-applied against the already-posted opening batch; qty/openingQty/openingDate are never changed.","Reports keeps Stock Report as a direct submenu separate from the Accounts & Finance report group."]},{version:"5.4.306",date:"28 Aug 2026",title:"Stock Serial Visibility + Reports Menu Split",changes:["Moved Stock Report out of Reports â Accounts & Finance and made it a direct Reports submenu while preserving the existing finance.manage access gate.","Stock Report now joins each live stock row to its Opening Stock batch evidence and shows the actual reliable serial numbers captured by Phase 2, with serial-number search and CSV export.","Serial display is evidence-only: it does not change live qty, opening qty/date, cost, or create fake serials; existing Phase 1/Phase 2 migration safeguards remain unchanged."]},{version:"5.4.301",date:"28 Aug 2026",title:"Opening Stock Dynamic Date Runtime Hardening",changes:["Removed the remaining runtime assumption that Back Dated text must survive PDF extraction; Date Wise Stock + detected snapshot date is sufficient for read-only preview.","Hardened As On date extraction for named, numeric and ISO formats plus PDF.js separator/spacing fragmentation, with a Date Wise header-date fallback.","Added an on-screen Runtime v5.4.301 marker and removed the sidebar 31-Jul wording so deployed-bundle freshness is visually verifiable; no specific opening calendar date is mandatory."]},{version:"5.4.300",date:"28 Aug 2026",title:"Dynamic Opening Date Detection + Cutover Safety",changes:["Removed the hard-coded 31-Jul-2026 opening-date requirement; any valid Takeplus/Oner Back Dated Date Wise Stock report is accepted and its As On date is detected automatically.","Opening batch key, openingDate, cutoverDate (next day), audit text and Phase 2 reconciliation now follow the detected report date, so 30-Jul/31-Jul/other valid snapshots remain isolated and traceable.","Added dynamic-date regression fixtures for named, numeric and ISO report dates while preserving preview-first, duplicate/live-stock blocking, reference-only Current Stock and no-fake-serial safeguards."]},{version:"5.4.298",date:"28 Aug 2026",title:"Opening Stock Preview Visibility + Import Gate Runtime Fix",changes:["Fixed 31-Jul Date Wise report identity validation to use both PDF raw text and reconstructed page rows, avoiding false rejection of the valid Takeplus/Oner Back Dated report.","Added an always-visible preview status panel directly under the action buttons with explicit READY/error details and automatic scroll-to-result after preview.","Moved Phase 1 branch/confirmation gating ahead of the long preview table and added a clear import-gate state so users can see exactly why Import is disabled.","Kept 31-Jul opening quantity authoritative, Current Stock reference-only, duplicate/live-stock blocks, and no-fake-serial safeguards unchanged."]},{version:"5.4.297",date:"28 Aug 2026",title:"Opening Stock Two-Phase Production Migration Fix",changes:["Split live opening migration into Phase 1 authoritative 31-Jul quantity and Phase 2 Current Stock cost/serial reference enrichment so Current Stock can never block or over
4155write opening quantity.","Fixed Date Wise Stock column reconstruction to use the actual Oner column starts instead of midpoint slicing, preserving complete product names for reliable Current Stock matching.","Hardened wrapped Current Stock product reconstruction and serial ownership so serial lines following a pending descriptor attach to that product instead of the previous row.","Fixed v5.4.295/v5.4.296 release-alignment regression gates to be forward-compatible and added exact v5.4.297 release/two-phase safety gates."]},{version:"5.4.295",date:"28 Aug 2026",title:"Opening Stock Match Diagnostics",changes:["Added read-only top-3 Current PDF candidate diagnostics per opening product with confidence, Qty, cost, serial count and match evidence/penalties.","Kept 31-Jul-2026 opening quantity authoritative and Current Stock reference-only; diagnostics do not write to Firebase.","Made the v5.4.294 release alignment gate forward-compatible while adding an exact v5.4.295 alignment gate."]},{version:"5.4.293",date:"27 Aug 2026",title:"Opening Stock Preview Gate Runtime Fix",changes:["Generate Reconciliation Preview now enables from the two actually selected PDF File objects instead of stale parsed-array state.","Generate Preview re-reads and validates both selected PDFs fresh before building the read-only reconciliation table, eliminating the selected-but-disabled workflow dead end.","Live import remains disabled until preview, branch selection and acknowledgement; 31-Jul authoritative quantity, no-fake-serial and v5.4.292 production reconciliation safeguards remain unchanged."]},{version:"5.4.292",date:"27 Aug 2026",title:"Live Opening Stock Production Reconciliation Safety",changes:["Made Current Stock reconciliation one-to-one so a single later-stock row can never supply cost/serial evidence to multiple opening products.","Added final pre-import invariants that block invalid/duplicate opening identities, any change to the authoritative 31-Jul quantity, and duplicated Current Stock reference links before the atomic Firebase write.","Capped serial evidence by opening quantity, current reference quantity and actual serial count; stored cutover/historical-import policy metadata so future pre-cutover Purchase/Sales imports reconcile without reapplying opening quantity.","Clarified that items missing from the later Current Stock report are valid reference-missing states, not automatic zero opening stock; Current Stock remains reconciliation-only."]},{version:"5.4.291",date:"27 Aug 2026",title:"Opening Stock Preview/Import Action Visibility Fix",changes:["Made Generate Reconciliation Preview permanently visible directly below the two PDF selectors so the next safe step cannot be hidden below the viewport.","Made Import Live Opening Stock visible beside Preview from the start but strictly disabled until preview, branch selection and live-stock acknowledgement are complete.","Kept all v5.4.290 live-stock safety, authoritative 31-Jul quantity, no-fake-serial and existing-stock overwrite protections unchanged."]},{version:"5.4.290",date:"27 Aug 2026",title:"Live Opening Stock Safety & Reconciliation Gate",changes:["Added an explicit Generate Reconciliation Preview step; selecting PDFs never writes stock and Import stays disabled until preview + branch + live-stock confirmation are complete.","Hardened Date Wise â Current Stock product matching with normalized weighted identity matching and an ambiguity guard; uncertain matches are deliberately left unmatched instead of attaching the wrong cost/serial reference.","Added a live-stock preflight block that refuses opening migration when the selected branch already contains any non-zero inventory stock, preventing accidental overwrite of operational stock.","31-Jul-2026 remains the sole authoritative opening quantity. Reliable current serials are preserved only as reconciliation evidence with serial-linked/pending quantities; no fake serials are generated and historical Purchase/Sales imports remain deferred for reconciliation."]},{version:"5.4.289",date:"27 Aug 2026",title:"Opening Stock Coordinate Parser Runtime Fix",changes:["Added a PDF.js coordinate-level fallback parser for Oner/Takeplus Current Stock so parsing no longer depends on text items landing in exactly the same reconstructed row.","Current Stock rows are detected from the unit token and same-baseline numeric columns, then merged with the existing row/serial parser;
4155 Current Stock remains reconciliation-only and cannot overwrite 31-Jul opening quantity.","Read failures now report row-parser count, coordinate-fallback count and confidence so runtime extraction issues are diagnosable without any database write.","Accounting Voucher, finance posting, permissions, branch safeguards and historical migration architecture remain unchanged."]},{version:"5.4.287",date:"27 Aug 2026",title:"Opening Stock Browser PDF Parser Hardening",changes:["Reworked Current Stock parsing around the actual PDF.js browser text-item layout so unit tokens are detected even when Product/PCS/Qty/Cost cells are merged or split differently.","Current reference parser now tolerates currency glyphs and spacing variations, uses the final Qty/Cost triplet as Oner report Total, preserves serialized-product descriptor/serial/PCS multi-row structure, and de-duplicates repeated visual rows.","31-Jul-2026 Date Wise Stock remains the sole authoritative opening quantity; Current Stock remains reconciliation-only and no fake serial is created.","No Accounting Voucher, finance posting, permissions, branch safeguards or historical migration architecture changed."]},{version:"5.4.286",date:"27 Aug 2026",title:"Opening Stock Oner Current PDF Parser Fix",changes:["Fixed Current Stock With Cost recognition for the actual Oner/Takeplus Current Stock â Location Wise Stock layout, without filename or literal Stock With Cost heading dependency.","Added support for serialized rows where product description, Serial No(s), serial values and PCS/Qty/Cost are emitted on separate PDF text rows; reliable serials remain references only and fake serials are never created.","Uses the final Qty/Cost triplet as report Total when location columns are present, keeps 31-Jul-2026 opening quantity authoritative, and accepts safe equivalent 31-Jul date formats.","Added v5.4.286 parser and release-alignment regression gates; Accounting Voucher and existing finance/migration safeguards remain unchanged."]},{version:"5.4.285",date:"27 Aug 2026",title:"Release Version Alignment Fix",changes:["Aligned package.json, package-lock.json, public/version.json and APP_VERSION to v5.4.285 after the v5.4.284 release pipeline gate detected stale v5.4.283 metadata.","Kept the v5.4.284 Opening Stock parser, reconciliation preview, serial safety and Data Migration UI behavior unchanged.","Made the v5.4.284 opening-stock regression gate forward-compatible so later sequential releases continue validating the same safeguards."]},{version:"5.4.284",date:"27 Aug 2026",title:"Opening Stock Parser, Reconciliation Preview & UI Fix",changes:["Recognizes Takeplus/Oner Current Stock With Cost PDFs by report structure and parsed stock/cost rows instead of brittle exact headings or filenames.","Added combined product-wise reconciliation preview with authoritative 31-Jul opening quantity, current reference quantity/cost, reliable serial matched/pending quantity, difference and warning status.","Import remains disabled until both PDFs parse successfully, branch is selected and combined preview is complete; no fake serials are created and current reference never overwrites opening quantity.","Aligned Data Migration typography/tabs/cards with VERIXO global design tokens without changing Accounting Voucher or finance posting safeguards."]},{version:"5.4.283",date:"26 Aug 2026",title:"Opening Stock PDF Recognition & Migration UI Polish",changes:["Removed brittle filename-only rejection for legacy Date Wise Stock and Current Stock With Cost PDFs; report content remains the validation source.","Aligned Data Migration typography with the main VERIXO application font and heading treatment.","No opening quantity authority, branch posting, serial safety or accounting posting rule was changed."]},{version:"5.4.282",date:"26 Aug 2026",title:"Data Migration Compile Fix",changes:["Added the missing DatabaseBackup icon import used by the standalone Data Migration sidebar entry.","Corrected Opening Stock migration audit action to accounting.opening_balances_updated.","No migration workflow, stock quantity logic, Firebase schema or permission behavior changed."]},{version:"5.4.281",date:"26 Aug 2026",title:"Standalone Data Migration Center",changes:["Moved migration tools out of Accounts & Finance into a dedicated Data Migration menu.","Opening Stock and Accounting Voucher are active; Purchase, Sales, Opening Balances and Import History are reserved.","Data Migration requires finance.manage permission.","Opening Stock safeguards from v5.4.280 are retained."]},{version:"5.4.280",date:"26 Aug 2026",title:"Opening Stock Migration Foundation",changes:["Added Stock Migration under Accounting Foundation for 31-Jul-2026 opening quantity import.","Supports previewing the Back Dated Date Wise Stock PDF and optional Current Stock With Cost reconciliation reference.","Opening quantity remains authoritative; current serial/cost reference never overwrites it automatically.","Creates no fake serials. Cost and serial history remain explicitly pending for later Purchase/Sales reconciliation.","Opening stock batch, product master and branch stock are posted atomically with duplicate-batch protection."]},{version:"5.4.279",date:"26 Aug 2026",title:"August 2026 Migration Foundation",changes:["Operational PDF migration currently starts 01 Aug 2026.","August is not irreversible; earlier history can later use Historical Backfill.","Existing source-document, date, branch, duplicate and atomic safeguards remain."]},{version:"5.4.278",date:"26 Aug 2026",title:"PDF Import Permission + Atomic Posting",changes:["Added finance-managed Realtime Database rules for the accountingPdfImports registry used by duplicate-safe PDF migration.","Voucher, ledger entries and PDF import registry continue to post in one atomic RTDB multi-location update.","Audit-log failure after a successful accounting post is now reported as a warning instead of falsely reporting the entire import as failed.","Import errors now explicitly state that Voucher, Ledger and Import Registry were not partially saved."]},{version:"5.4.277",date:"26 Aug 2026",title:"Permanent Release Pipeline Fix",changes:["Legacy release version validation is now dynamic instead of hardcoded.","package.json, version.json and APP_VERSION must match.","v5.4.276 PDF import fixes and safeguards are retained."]},{version:"5.4.276",date:"26 Aug 2026",title:"PDF Source Voucher Compile Fix",changes:["Fixed the TypeScript string-or-undefined compile error introduced by the v5.4.275 source voucher de-duplication helper.","Clean source voucher de-duplication remains unchanged.","PDF date, description, branch posting and Debit/Credit mapping behavior remain unchanged."]},{version:"5.4.275",date:"26 Aug 2026",title:"PDF Source Voucher De-duplication",changes:["Normalized Takeplus/Oner source voucher numbers so repeated PDF text fragments do not duplicate the Voucher No in preview.","Duplicate protection now receives the clean source key, e.g. DV-TPCBG-2025-26-000207.","PDF date, description, branch posting and debit/credit parsing behavior remain unchanged."]},{version:"5.4.274",date:"26 Aug 2026",title:"Release Alignment Fix",changes:["Aligned package.json, public/version.json and src/core/version.ts to v5.4.274.","Fixed the stale v5.4.273 PDF header regression checker so it validates the real source tokens reliably.","Retained all PDF Header + Branch Posting Safety behavior from v5.4.273 unchanged."]},{version:"5.4.273",date:"26 Aug 2026",title:"PDF Header + Branch Posting Safety",changes:["PDF Import now reads Voucher No, Voucher Date, Status, Approved By and multiline Description from exact coordinate labels before using text fallback.","Voucher Date no longer falls through to the PDF Print Date when the actual voucher header is available.","PDF Import clearly shows the VERIXO Branch that will receive the voucher and all ledger entries.","Source cash-account branch hints such as BGC Complex remain descriptive only; the selected VERIXO Branch is the posting dimension."]},{version:"5.4.272",date:"26 Aug 2026",title:"Takeplus PDF Coordinate Parser",changes:["Rebuilt Debit Voucher PDF table extraction around PDF text coordinates instead of depending on re
4155constructed line text.","Accounts, Project, Particular, Dr and Cr column positions are detected from the PDF header and used to read voucher rows safely.","Added a final normalized-text fallback for the supplied Takeplus Office Expenses / Cash In Hand debit voucher format.","PDF Import remains Preview First and does not post anything until Import Voucher is explicitly confirmed."]},{version:"5.4.271",date:"26 Aug 2026",title:"Takeplus PDF Parser Fix",changes:["Rebuilt browser PDF text extraction to preserve PDF row structure using text coordinates instead of flattening every page into one sentence.","Takeplus/Oner Debit Voucher parser now reads the actual Voucher No, Date, Status, multiline Description and Debit/Credit rows used by PrintIndVoucher.pdf.","Added fallback parsing for PDFs that still return merged table text.","Import remains preview-first; no accounting data is posted when parsing fails."]},{version:"5.4.270",date:"26 Aug 2026",title:"Expense PDF Accounting Import",changes:["Added PDF Accounting Import under Accounting Foundation for historical expense migration.","First supported source format is the Takeplus / Oner ERP Debit Voucher Report supplied from the existing software.","PDF import uses Preview -> Branch Mapping -> Ledger Mapping -> Validation -> Import and blocks duplicate source voucher numbers.","Approved balanced Debit Vouchers post directly to the existing double-entry voucher and ledger engine, including Office Expense to Cash mappings.","Period lock remains enforced and PDFs are never posted automatically on upload."]},{version:"5.4.268",date:"26 Aug 2026",title:"Detailed Financial Ledger View",changes:["Income Statement now opens in Ledger Accounts Wise view by default, so Service Revenue is shown as 4200 instead of only the 4000 Income control total.","Balance Sheet now opens in Ledger Accounts Wise view by default, so Cash in Hand, Bank and Accounts Receivable are shown instead of only the 1000 Assets control total.","Control Wise and Subsidiary Wise views remain available from Report Level.","Verified existing Service Accounting mapping already posts Invoice to 1200 Accounts Receivable / 4200 Service Revenue and Collection to 1110 Cash or 1120 Bank / 1200 Accounts Receivable; no historical repost or duplicate entry is required."]},{version:"5.4.267",date:"26 Aug 2026",title:"VERIXO Backfill Confirmation Modal",changes:["Replaced the browser-native historical backfill confirmation alert with a VERIXO-styled modal.","Confirmation now summarizes Invoice Candidates, Collection Candidates, duplicate-safe skips and Period Lock status.","Cancel and Run Backfill actions now match the existing VERIXO accounting UI.","Historical backfill posting, duplicate protection, branch validation and period-lock logic are unchanged."]},{version:"5.4.266",date:"26 Aug 2026",title:"Historical Backfill Branch Resolution",changes:["Historical Backfill preview now resolves stored branch IDs to actual Branch names.","Internal branchId remains unchanged for correct voucher and ledger posting.","Invoice and Collection preview tables show Branch Name with the internal ID as secondary reference.","Backfill is blocked if a historical branch ID cannot be matched to the active Branch master."]},{version:"5.4.265",date:"26 Aug 2026",title:"Service Backfill AuditAction Compile Fix",changes:["Registered the Historical Service Accounting Backfill audit event in the typed AuditAction list.","Fixes the TypeScript build failure reported by the v5.4.264 one-click update.","Historical Backfill logic and accounting behavior are unchanged."]},{version:"5.4.264",date:"26 Aug 2026",title:"Historical Service Accounting Backfill Center",changes:["Added Preview-only historical scan for Service Invoices and Collections missing source-linked accounting vouchers.","Backfill reuses idempotent Service Accounting voucher keys and skips already-posted records.","Date-range controls, candidate totals, skipped counts and locked-period warnings are included.","Run Backfill requires Finance Manage permission, writes an audit log, and never silently bypasses Accounting Perio
4155d Lock."]},{version:"5.4.263",date:"26 Aug 2026",title:"Collections Due Invoice Search",changes:["Collections now has a direct Record Collection action for previous outstanding dues.","The selector shows only invoices with Due Amount greater than zero.","Due invoices can be searched by Invoice No, full or partial Mobile No, Customer Name or Job No.","Selecting an invoice opens the existing Collection Date / Amount / Method / Reference / Notes workflow."]},{version:"5.4.262",date:"26 Aug 2026",title:"Customer Collection Date",changes:["Added Collection Date to Record Collection, defaulting to today.","Selected collection date is used for receipt and accounting posting timestamps.","Existing collection amount, payment method, reference, notes and accounting flow remain unchanged."]},{version:"5.4.261",date:"26 Aug 2026",title:"Release Pipeline Stability Fix",changes:["Aligned source, package and web metadata versions.","Android metadata preservation now finishes cleanly on Windows after successful fetch.","v5.4.260 retry and verified safe-cache fallback remain protected.","No ERP business logic changed."]},{version:"5.4.259",date:"26 Aug 2026",title:"Invoice Date Visible Placement",changes:["Moved Invoice Date to the top of Generate Invoice so it is visible without scrolling.","Invoice Date remains defaulted to today, future dates remain blocked, and backdated invoices still respect Accounting Period Lock.","No invoice accounting, Service Delivery, permission or Firebase rule was changed."]},{version:"5.4.258",date:"26 Aug 2026",title:"Invoice Date Control",changes:["Generate Invoice now includes a selectable Invoice Date, defaulting to today.","Future invoice dates are blocked.","The selected invoice date is used for invoice numbering and accounting posting, so Accounting Period Lock also applies to backdated invoices.","Invoice Date is stored with both private and public invoice records."]},{version:"5.4.257",date:"26 Aug 2026",title:"Strict Invoice Before Service Delivery",changes:["Payable service jobs cannot be delivered until an invoice exists.","Zero-amount/free jobs can still be delivered without an invoice.","Ready status, zero outstanding due and customer verification controls remain enforced.","Delivery Scan shows Invoice Control and the payable amount when delivery is blocked."]},{version:"5.4.256",date:"26 Aug 2026",title:"Safe Web Auto Update",changes:["Added lightweight web version detection using a tiny version.json file every 15 minutes and whenever the browser tab returns to focus.","When a newer VERIXO web version is detected and the user is idle, the page reloads automatically.","When the user may have unsaved form work, VERIXO shows an update prompt instead of silently discarding work.","version.json is served with no-cache headers so Firebase Hosting/CDN does not hide a newly deployed version.","No GitHub dependency, Firebase database read, accounting logic or user permission change was introduced."]},{version:"5.4.255",date:"26 Aug 2026",title:"Service Collection Accounting Type Fix",changes:["Added the missing optional accountingPosted boolean to the Collection TypeScript model.","No Service accounting logic, Firebase permission, Period Lock or ledger calculation changed."]},{version:"5.4.254",date:"26 Aug 2026",title:"Service Finance Accounting Integration",changes:["New Service Invoices now auto-post Accounts Receivable Dr / Service Revenue Cr to the accounting ledger.","Invoice advances auto-post Cash Dr / Accounts Receivable Cr when the invoice is generated.","Customer Collections auto-post Cash/Bank Dr / Accounts Receivable Cr using source-linked deterministic vouchers.","Invoice and Collection corrections create current-period adjustment journals instead of rewriting posted ledger history.","Automatic service accounting respects Accounting Period Lock and uses existing Chart of Accounts system links.","Existing historical invoices/collections are not backfilled automatically, preventing duplicate legacy postings.","No Firebase schema or permission rule was broadened."]},{version:"5.4.253",date:"26 Aug 2026",title:"Production Period Lock Enforcement",changes:["Verified and retained locked-period guards on Voucher Draft save and Voucher Post.","Accounting Perio
4155d now states that the active Vouchers & Journal engine enforces the lock immediately.","Locked Through cannot be set to a future month and cannot be reduced silently after it is saved.","Current Period must remain later than Locked Through.","Vouchers & Journal now shows the live period-lock status and explains which actions are blocked.","Reversal uses a separate current-period Journal Voucher so a closed period's original ledger date and report remain unchanged.","No Firebase schema, ledger calculation or existing finance permission was changed."]},{version:"5.4.252",date:"26 Aug 2026",title:"Accounting Posting Status Alignment",changes:["Updated the Accounting Foundation page to reflect the already-active double-entry Vouchers & Journal posting engine.","Removed stale text that incorrectly said journal posting was not enabled.","Accounting Period now clearly states that locked months are enforced by voucher posting.","Added Posting Engine status visibility without changing any posting, reversal, ledger or permission logic.","No Firebase schema, accounting calculation or security rule was changed."]},{version:"5.4.251",date:"26 Aug 2026",title:"Account Hierarchy TypeScript Compile Fix",changes:["Fixed the TS7022 TypeScript compile error in the new account hierarchy ancestor traversal helper.","Added explicit generic type annotations to parent-account variables without changing hierarchy behavior.","Control Wise, Subsidiary Wise and Accounts Wise reporting logic remains unchanged.","No Firebase schema, accounting calculation, permission or security rule was changed."]},{version:"5.4.250",date:"26 Aug 2026",title:"Account Hierarchy Reporting",changes:["Activated the existing Chart of Accounts parent/group structure as the financial reporting hierarchy without changing the Firebase account schema.","Chart of Accounts now identifies Control, Subsidiary and Ledger Account levels with visual hierarchy indentation.","Income Statement and Balance Sheet now support Control Wise, Subsidiary Wise and Accounts Wise report levels.","Control Wise aggregates each root control group, Subsidiary Wise aggregates each immediate child under a control group, and Accounts Wise shows individual posting accounts.","Totals always remain based on underlying ledger accounts so switching report level does not change the financial result.","No new Firebase node, permission or security-rule change was introduced."]},{version:"5.4.249",date:"26 Aug 2026",title:"View Report Regression Gate Fix",changes:["Aligned every legacy Income Statement and Balance Sheet regression gate with the intentional View Report launcher label.","Kept Print, Download PDF and Close actions inside the report viewer unchanged.","Added a dedicated regression gate preventing the old View PDF launcher label from returning.","No accounting calculation, Firebase rule, permission or report logic was changed."]},{version:"5.4.248",date:"26 Aug 2026",title:"Financial Report Action Label",changes:["Renamed the Income Statement and Balance Sheet opening action from View PDF to View Report.","Kept Print, Download PDF and Close actions inside the report viewer unchanged.","No accounting logic, Firebase data path or permission was changed."]},{version:"5.4.247",date:"26 Aug 2026",title:"Balance Sheet Report",changes:["Added Reports â Accounts & Finance â Balance Sheet.","Balance Sheet supports As of Date, Branch selection and Skip Zero.","Calculates Assets, Liabilities and Equity from posted ledger balances and includes current-period Profit/Loss in Equity.","Added the same clean full-screen VERIXO PDF viewer with Print, Download PDF and Close actions.","Uses existing accounting data and Finance read permission; no new Firebase node or permission was introduced."]},{version:"5.4.246",date:"26 Aug 2026",title:"Income Statement Inline Viewer Actions",changes:["Placed Print, Download PDF and Close side-by-side in a single horizontal action row.","Kept the Income Statement title and reporting period aligned on the left.","Preserved responsive wrapping only on narrow screens.","No report calculation, PDF content, Firebase rule or security baseline was changed."]},{version:"5.4.245",date:"26 Aug 2026",title:"Income Statement PDF Zoom Fix",changes:["Removed Fit-to-Width from the Income Statement PDF preview because it made A4 pages appear excessively zoomed on desktop screens.","The PDF now opens at a restrained 75% initial zoom while keeping the clean toolbar-free full-screen VERIXO viewer.","Print, Download PDF and Close controls remain unchanged.","No accounting calculation, report content, Firebase rule or security baseline was changed."]},{version:"5.4.244",date:"26 Aug 2026",title:"Clean Income Statement Viewer",changes:["Removed duplicate Income/Expense/Net Profit cards and table from the report launcher page because the PDF already contains the financial statement.","Changed View PDF to the standard VERIXO primary button style.","Removed the native Chrome PDF toolbar from the embedded preview so the blob UUID/file strip no longer appears.","Added clean VERIXO Print, Download PDF and Close controls in the full-screen viewer header.","Kept Date From, Date To, Branch and Skip Zero as the only report selection controls before opening the PDF.","No accounting calculation, Firebase permission or security baseline was changed."]},{version:"5.4.243",date:"26 Aug 2026",title:"Professional Income Statement",changes:["Renamed Profit & Loss to Income Statement in the report page, menu and PDF.","Added Branch selection directly beside Date From / Date To / Skip Zero.","Redesigned report controls into a clean professional VERIXO filter card.","Changed PDF preview to true full-screen view with a compact VERIXO header and styled Close button.","No accounting calculation, Firebase rule or security baseline was changed."]},{version:"5.4.242",date:"26 Aug 2026",title:"Profit & Loss Report Preview",changes:["Changed Profit & Loss Download PDF action to View PDF with an in-ERP PDF preview.","Profit & Loss report filters now clearly show From Date, To Date, current Branch scope and Skip Zero.","The generated PDF carries the selected branch and reporting period and can be printed/downloaded from the PDF viewer.","No accounting calculation, Firebase node or permission was changed."]},{version:"5.4.241",date:"26 Aug 2026",title:"Profit & Loss Statement",changes:["Added Reports â Accounts & Finance â Profit & Loss.","Calculates period Income, Expenses and Net Profit/Loss from posted double-entry ledger entries.","Report follows current Branch / All Branches workspace scope and From/To date period.","Added direct A4 PDF download with company branding and income/expense breakdown.","Uses existing Finance read permissions and accounting data; no new Firebase node or permission was introduced."]},{version:"5.4.240",date:"25 Aug 2026",title:"Final Security Baseline Lock",changes:["Closed the core VERIXO Web ERP/Firebase security-hardening cycle with a final whole-ERP regression baseline.","No new Firebase permission was removed in this closure release; v5.4.239 live access remains unchanged.","Locked tenant isolation, HR/Attendance/Payroll/Advance-Loan/Finance protections, public-surface inventory, portal data minimization and print security invariants.","Customer-facing public paths required by Tracking, Estimate, Invoice, Review and phone lookup remain explicitly allowed and regression-controlled.","Server-side keyed phone lookup and abuse controls remain optional future infrastru
4155cture hardening."]},{version:"5.4.239",date:"25 Aug 2026",title:"Platform Config & Tax Monitor Security",changes:["Restricted the unused legacy platformConfig node to Super Admin read/write only.","Aligned global NBR taxMonitor read access with existing Payroll read/manage audiences instead of every authenticated login.","Kept taxMonitor client writes Super Admin-only and preserved the GitHub service-account NBR publishing workflow.","Preserved company-scoped NBR review acknowledgements and all Payroll/Tax rule workflows.","Attendance Connector, Advance/Loan, Finance and other critical positive permissions were regression-protected."]},{version:"5.4.238",date:"25 Aug 2026",title:"Public Portal Data Minimization",changes:["Removed raw customer phone and WhatsApp values from public service-tracking records.","Removed accessories, accessory lists and physical-condition internals from the public tracking payload because the public page does not use them.","Preserved the full internal ServiceJob schema and all Web ERP service workflow fields.","Kept customer-name masking, service problem/status, company contact details and technician attribution required by the delivered-job review workflow.","Added Firebase validation preventing sensitive removed fields from being written back into publicTracking."]},{version:"5.4.237",date:"25 Aug 2026",title:"Public Phone Lookup Hardening",changes:["Removed the unused global publicCustomerMobileLookup phone-hash directory from web sync and closed its public read/write surface.","Kept the live Customer Portal on the company-scoped publicPortalPhoneLookup path so existing customer phone search remains compatible.","Confirmed lookup records do not contain raw customer phone or WhatsApp values.","A stronger server-side keyed lookup/rate-limit layer remains an optional infrastructure hardening step because a browser-only secret would not provide real protection.","Attendance Connector, Payroll, Advance/Loan and Finance permissions were preserved."]},{version:"5.4.236",date:"25 Aug 2026",title:"Users Tenant Isolation",changes:["Restricted Owner/Admin users-collection reads to an indexed companyId query equal to their own company, closing cross-company parent-read exposure.","Preserved Super Admin global access, self-read, direct same-company Owner/Admin child reads and existing user-management writes.","Verified Employees, User Permission and Reporting Hierarchy already use the required company-scoped users query.","No Attendance Connector, Payroll, Advance/Loan or Finance positive permission was removed."]},{version:"5.4.235",date:"25 Aug 2026",title:"Finance Print Typography & Border Polish",changes:["Increased Invoice and Money Receipt print typography by one size step.","Darkened address, phone and muted metadata for clearer printing.","Strengthened internal box, table, divider and signature lines.","Retained A4 layout, blank-window fix and print security hardening."]},{version:"5.4.234",date:"25 Aug 2026",title:"Finance Print Blank Window Fix",changes:["Fixed Invoice and Money Receipt print popups opening as blank about:blank pages in Chrome.","Removed noopener/noreferrer from the window.open feature string because Chrome may return a null WindowProxy, preventing document.write.","Retained opener isolation by setting printWindow.opener = null immediately after opening the popup.","Retained A4 standard print layout and all v5.4.232 HTML escaping protections.","No Finance calculation, accounting or Firebase permission logic was changed."]},{version:"5.4.233",date:"25 Aug 2026",title:"Finance A4 Standard Print Restore",changes:["Restored Invoice and Money Receipt printing to a standard A4 portrait layout using the full printable width.","Removed the legacy compact print mode that made short invoices appear compressed after the earlier A5-oriented adjustments.","Reduced print-page margin to 8mm while preserving natural multi-page flow for longer documents.","Retained v5.4.232 print HTML escaping and popup isolation security hardening.","No Finance calculation, collection, accounting or Firebase permission logic was changed."]},{version:"5.4.232",date:"25 Aug 2026",title:"Print XSS & Public Lookup Hardening",changes:["Escaped dynamic Invoice and Money Receipt print content before inserting it into the print document, closing stored HTML/script injection risk.","Hardened print popups with
4155noopener/noreferrer and explicit opener isolation.","Disabled the unused predictable publicPortalLookup job-number index and stopped syncing new records into it.","Kept the live phone-hash customer/mobile lookup unchanged for compatibility; secure server-side HMAC/rate-limit migration remains a separate backend phase.","Attendance Connector, Payroll, Advance/Loan and Finance role permissions were preserved."]},{version:"5.4.231",date:"25 Aug 2026",title:"Whole-ERP Security Audit â No Permission Change",changes:["Completed a whole-ERP Firebase permission inventory covering 91 top-level rule nodes and all literal public read/write surfaces.","No Firebase permission was changed in this audit release; Attendance Connector, Payroll, Advance/Loan, Finance and Mobile ESS positive access remain frozen.","Recorded tenant-isolation and public-surface findings for separate compatibility-safe remediation instead of changing live permissions immediately.","Added a permanent audit gate to detect new public read/write surfaces and accidental loss of critical positive permissions."]},{version:"5.4.230",date:"25 Aug 2026",title:"Payroll Pre-Check Attendance Mode Alignment",changes:["Payroll Pre-Check now follows the current company Attendance Mode before flagging historical Outside Movement records.","Standard First IN / Last OUT mode ignores pending/unclassified Outside Movement warnings because that workflow is inactive.","Access Control Multi-Punch mode continues to flag pending/unclassified movements exactly as before.","Historical movement data is preserved and no Firebase permission, Attendance Connector, Payroll calculation or accounting logic was changed."]},{version:"5.4.229",date:"25 Aug 2026",title:"Finance Security Closure",changes:["Closed the Accounts/Finance Security Baseline phase with an audit-only regression release.","No Firebase permission was tightened or removed in this release; current Finance, Payroll, Advance/Loan and Attendance Connector positive access is intentionally frozen.","Added closure checks for finance.read, finance.manage, voucher/ledger branch safety, voucher counters and accounting dependencies.","Critical Finance/Payroll nodes remain non-public and all prior security phases remain regression-protected."]},{version:"5.4.228",date:"25 Aug 2026",title:"Salary Structure Horizontal Scroll Fix",changes:["Fixed the Salary Structure table being clipped on the right when Tax/PF/Bank columns make the table wider than the Payroll panel.","Added a dedicated horizontal scroll container and wide intrinsic table width so all Salary Structure columns remain reachable.","Kept the Employee column sticky while scrolling horizontally for easier editing.","No Payroll calculation, Tax/PF, Advance/Loan, Firebase or accounting logic was changed."]},{version:"5.4.227",date:"25 Aug 2026",title:"Advance/Loan Disbursement Button Polish",changes:["Applied VERIXO primary/secondary button styling to the disbursement modal footer.","Cancel now uses the standard secondary action style and Confirm Disbursement uses the standard VERIXO primary action style.","No disbursement, accounting, payroll recovery or Firebase logic was changed."]},{version:"5.4.226",date:"25 Aug 2026",title:"VERIXO Styled Advance/Loan Disbursement",changes:["Replaced browser prompt dialogs for Advance/Loan payment method and disbursement date with the existing VERIXO modal design.","Disbursement now uses Cash/Bank dropdown, proper date input, transaction summary and Confirm Disbursement action.","Existing accounting voucher posting, request disbursed status and payroll recovery activation logic remain unchanged."]},{version:"5.4.225",date:"25 Aug 2026",title:"Advance/Loan Finalization Queue",changes:["Added the missing Recovery Plan Pending stage to the operational Employee Advance & Loan page.","Manager-approved requests now remain visible to HR/Admin/Owner/Super Admin with Set Recovery Plan action.","Finalization creates the existing approved employeeAdvanceLoans record and moves the request to Pending Disbursement without changing the established workflow.","Existing request page, Firebase security model, Attendance Connector, Payroll recovery and Finance posting architecture remain unchanged."]},{version:"5.4.224",date:"25 Aug 2026",title:"Unified Mobile ESS Regression Compatibility",changes:["Audited all legacy Leave and Mobile ESS regression scripts together and aligned them to one temporary Android compatibility policy.","Removed the obsolete v5.4.221 regression assumption that employeeId-query support must exist at the parent rule while the legacy Android parent-read fallback is intentionally active.","Retained My Leave and Attendance Summary compatibility for active same-company employees linked to an employee profile.","Preserved Leave identity/status write protections and all prior Payroll, Advance/Loan, Finance and Attendance Connector security gates."]},{version:"5.4.223",date:"25 Aug 2026",title:"Mobile ESS Compatibility Regression Fix",changes:["Aligned the legacy Leave Privacy Phase 2B2 regression gate with the temporary Android parent-read compatibility introduced in v5.4.222.","Retained My Leave and Attendance Summary compatibility for active same-company employees linked to an employee profile.","Preserved Leave identity/creator spoof protection and pending/withdrawn controls.","Attendance Connector, Payroll, Advance/Loan and Finance rules remain unchanged."]},{version:"5.4.222",date:"25 Aug 2026",title:"Mobile Employee Self-Service Compatibility Restore",changes:["Restored current Android My Leave and Attendance Summary compatibility for active authenticated employees while preserving company isolation.","This is a temporary compatibility fallback because the current Android client performs company-parent reads and filters locally.","Leave create/withdraw identity and approval protections remain unchanged.","Attendance write rules and Attendance Connector permissions remain unchanged.","Payroll, Advance/Loan and Finance security rules remain unchanged."]},{version:"5.4.221",date:"25 Aug 2026",title:"Leave Self-Service Permission Compatibility",changes:["Added a secure Android-friendly Leave history query using createdByUid == auth.uid while retaining the existing employeeId-scoped Web query.","Added own single-request read support without granting company-wide Leave visibility.","Preserved employee creator/employeeId spoof protection and existing Leave workflow.","Attendance Connector, Payroll, Advance/Loan and Finance rules were not changed."]},{version:"5.4.220",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2D3 - Voucher, Ledger & Counter Security",changes:["Audited transaction-critical accountingVouchers and accountingLedgerEntries and locked regression tests around their existing finance.read/finance.manage separation and assigned-branch write validation.","Narrowed accountingVoucherCounters read access from the broader finance.read audience to finance.manage users only because counters are posting infrastru
4155cture, not reporting data.","Added Firebase validation for voucher-counter sequence/schema fields to reject malformed counter records.","Preserved Draft â Post â Reverse double-entry controls, Payroll recovery journals and Advance/Loan accounting posting dependencies.","Attendance Connector and all prior security phases remain regression-protected."]},{version:"5.4.219",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2D2 - Accounting Accounts & Settings Privacy",changes:["Hardened accountingAccounts and accountingSettings reads instead of allowing every same-company authenticated user to read core accounting configuration.","Preserved the complete finance.read audience plus Payroll and Advance/Loan dependencies that consume accounting accounts/settings.","Preserved HR access required for Payroll/Advance-Loan workflows without granting unrelated employee roles broad accounting visibility.","All accountingAccounts/accountingSettings write rules remain unchanged.","Transaction-critical vouchers, ledger entries and voucher counters were deliberately deferred for the next Finance security batch."]},{version:"5.4.218",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2D1 - Accounting Opening Balance Privacy",changes:["Started Finance security with the lowest-risk accounting dataset: accountingOpeningBalances read access now matches the existing finance.read audience instead of every same-company login.","Preserved all current Finance roles and explicit finance.read overrides used by General Ledger and Trial Balance.","Opening-balance write permissions remain unchanged.","Shared accountingAccounts/accountingSettings and transaction-critical vouchers/ledger were deliberately deferred because Payroll and Advance/Loan depend on them.","Attendance Connector, Payroll, Advance/Loan, Service and existing accounting posting workflows were not changed."]},{version:"5.4.217",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2C4 - Attendance Device Data Privacy",changes:["Restricted Web reads of attendanceDevices, attendanceDeviceLogs and attendanceRawPunches to the existing Attendance Device Manager audience.","Preserved Super Admin, Owner, Admin, Branch Manager and explicit attendance.device.manage access.","Attendance Web listeners now avoid subscribing to sensitive device/log/raw-punch feeds when the user cannot manage devices.","All connector/device/raw write permissions remain unchanged to avoid interrupting the live Attendance Connector.","Connector heartbeat/command reads and pending/processed punch connector paths were deliberately deferred and remain unchanged."]},{version:"5.4.216",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2C3 - Daily Attendance Privacy",changes:["Hardened attendanceDaily full-collection reads to verified Attendance and Payroll audiences while preserving Payroll pre-check and calculation dependencies.","Preserved Appraisal's direct date/employee attendance lookups through item-level appraisal.view access without granting company-wide attendance history.","Added authenticated employee own-record read support and aligned My Leave self-service to load only the linked employee profile instead of the full employee directory.","Normal employee self-service no longer subscribes to the company-wide attendanceDaily collection.","Attendance writes, Connector, devices, raw punches, pending punches and device logs remain unchanged."]},{version:"5.4.215",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2C2 - Attendance Movement Privacy",changes:["Hardened attendanceMovements read access to verified Attendance and Payroll audiences while retaining Payroll pre-check dependency access.","Normal employee self-service no longer subscribes to the company-wide Attendance Movement feed, preventing denied-read noise and unnecessary exposure.","Movement create/approve write permissions remain unchanged.","attendanceDaily was deliberately not changed because Attendance, Payroll and Appraisal dependencies require a separate read-model migration.","Attendance Connector, device, raw-punch, pending-punch and device-log rules remain untouched."]},{version:"5.4.214",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2C1 - Attendance Policy Privacy",changes:["Hardened Attendance policy, shift, assignment, holiday, weekly-off and lunch-setting reads while preserving existing Attendance and Employee-directory dependencies.","Preserved Super Admin, Owner, Admin, HR, Branch Manager, Viewer plus explicit attendance.read, attendance.manage and employee.read capability access.","All Attendance configuration write rules remain unchanged.","Connector, device-log, raw-punch, pending-punch and punch nodes were deliberately not changed in this live-safe batch.","attendanceDaily and attendanceMovements were deferred because Payroll/Appraisal depend on them."]},{version:"5.4.213",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2B6 - Gratuity Privacy",changes:["Hardened Gratuity policy, settlement and payment reads to the existing employee.read audience instead of every same-company authenticated login.","Preserved legitimate visibility for Super Admin, Owner, Admin, HR, Branch Manager, Viewer and explicit employee.read overrides.","Preserved employee.manage Gratuity write workflow and existing employee/salary-structure dependencies.","Attendance Connector, Payroll, Advance/Loan, Employees, Leave, HR Letters, Appraisal, Recruitment, Service and Accounts permissions were not changed.","Added a Gratuity privacy positive/negative regression gate."]},{version:"5.4.212",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2B5 - Recruitment Privacy",changes:["Hardened recruitment vacancy and candidate reads to match the existing Web ERP employee.read permission instead of every same-company authenticated login.","Preserved legitimate Recruitment visibility for Super Admin, Owner, Admin, HR, Branch Manager, Viewer and explicit employee.read overrides.","Preserved employee.manage Recruitment write access and the existing candidate-to-employee / payroll salary-structure integration.","Attendance Connector, Payroll, Advance/Loan, Employees, Leave, HR Letters, Appraisal, Service and Accounts permissions were not changed.","Added a Recruitment privacy positive/negative regression gate."]},{version:"5.4.211",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2B4 - Employee Directory Privacy",changes:["Completed the employees shared-dependency audit across HR, Attendance, Payroll, Advance/Loan, Appraisal, Performance, Recruitment and User Permissions before changing the live Firebase read rule.","Removed blanket company-wide employee-directory read from roles with no verified v5.4.210 full-directory dependency, while preserving every identified live Web module capability family.","Preserved Payroll accountant, Performance sales/branch-operator, Appraisal service-incharge, HR/Branch Manager/Viewer and explicit capability-override access.","Employee write permissions were not changed; Owner/Admin/HR and employee.manage behavior remains intact.","Attendance Connector and all previously hardened HR rules remain protected by regression checks."]},{version:"5.4.210",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2B3 - Appraisal Privacy",changes:["Hardened employeeAppraisals read access to match the existing Web ERP appraisal.view capability instead of every same-company authenticated user.","Preserved appraisal visibility for Super Admin, Owner, Admin, HR, Branch Manager, Service In-Charge and explicit appraisal.view overrides.","Preserved the existing appraisal create/edit/submit/approve/finalize write workflow in this live-safe read-only hardening batch.","Employees, Leave Requests, HR Letters, Attendance Connector, Payroll, Advance/Loan, Service and Accounts permissions were not changed.","Added an appraisal privacy positive/negative regression gate."]},{version:"5.4.209",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2B2 - Leave Privacy",changes:["Normal employee Leave self-service now reads only that employee's leave history through an employeeId-scoped Firebase query instead of downloading the company-wide leave collection.","Preserved full Leave read access for the existing Web attendance.read audience: Super Admin, Owner, Admin, Branch Manager, HR, Viewer and explicit attendance.read overrides.","Preserved the existing Leave write workflow for Owner/Admin/HR/Branch Manager, attendance.manage overrides, employee pending request creation and employee pending withdrawal.","Added an employeeId index and a Leave privacy positive/negative regression gate.","Employees, Appraisals, Attendance Connector, Payroll, Advance/Loan, Service and Accounts permissions were not changed."]},{version:"5.4.208",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2B1 - HR Letters Privacy",changes:["Hardened HR Letters read access to match the existing Web ERP employee.read capability instead of allowing every same-company authenticated user.","Preserved legitimate HR Letters access for Super Admin, Owner, Admin, HR, Branch Manager, Viewer and explicit employee.read overrides.","Preserved HR Letter write access for Owner/Admin/HR and explicit employee.manage overrides.","Employees, Leave Requests and Appraisals were deliberately not changed in this batch because their self-service/reporting-manager query patterns require separate live-safe migrations.","Attendance Connector permissions and all Payroll/Service/Accounts rules remain unchanged."]},{version:"5.4.207",date:"25 Aug 2026",title:"Security Baseline v2 Phase 2A - Workspace Notifications",changes:["Hardened workspaceNotifications to the roles that actually consume and create NBR/Payroll tax alerts: Super Admin, Owner, Admin and HR.","Added the same role gate to the Web ERP workspace-notification listener so other roles do not generate denied-read errors.","Preserved mobileNotifications unchanged because the live technician Android n
4155otification queue depends on that path.","Preserved the legacy notifications node unchanged because no active v5.4.206 source owner was verified; it will not be tightened blindly.","Added a notification-specific positive/negative regression gate to future production builds."]},{version:"5.4.206",date:"24 Aug 2026",title:"Security Baseline v2 Phase 1",changes:["Completed a live-safe Web ERP/Firebase security baseline audit without changing production data-access rules.","Added positive-access regression protection for Attendance Connector, Payroll, Advance/Loan and Accounting workflows before future rule hardening.","Documented broad same-company access nodes and a phased hardening sequence to avoid live-service regressions.","No Android source, Web ERP workflow, Firebase permission behavior or accounting logic was changed."]},{version:"5.4.205",date:"24 Aug 2026",title:"Android Advance/Loan Self-Service Security Compatibility",changes:["Enabled least-privilege employee create/read access on the existing employeeAdvanceLoanRequests node for Android Employee Self-Service.","Normal employees can query only their own request history by employeeId and can create only a pending request bound to their authenticated user/employee/company.","Protected approval, rejection, recovery-plan, disbursement and accounting fields are blocked from employee request creation; employees cannot update submitted requests.","Reporting Manager stage-one approval/rejection and existing HR/Admin/Owner/payroll-management workflow remain on the same node and schema.","Web self-service request loading now uses the same secure query pattern for non-privileged users so tightened rules do not break the existing page.","Added Android Advance/Loan RTDB security regression checks to the production build gate."]},{version:"5.4.204",date:"24 Aug 2026",title:"Advance/Loan Firebase Rules Boolean Fix",changes:["Fixed Firebase Realtime Database Rules syntax for employee Advance/Loan recovery-plan authorization.","Replaced unary negation on nullable recoveryPlanFinalized with an explicit boolean comparison accepted by Firebase Rules.","Added regression protection so this invalid Firebase Rules expression cannot be reintroduced.","No Advance/Loan workflow, Payroll, Attendance Connector or Service Receive behavior was changed."]},{version:"5.4.203",date:"24 Aug 2026",title:"Advance/Loan Audit Action Build Fix",changes:["Added AuditAction support for Reporting Manager approval and recovery-plan finalization events introduced in v5.4.202.","No workflow, payroll, attendance connector or Service Receive behavior was changed.","This release is a compile/build compatibility fix for the v5.4.202 Advance/Loan authorization workflow."]},{version:"5.4.202",date:"24 Aug 2026",title:"Employee Advance/Loan Recovery Plan Authorization",changes:["Employee self-service Advance/Loan request now asks only Type, Requested Amount, Needed Date and Reason.","Recovery Method, Recover From Salary Month and installment count are no longer employee-controlled.","Reporting Manager approval is now stage one; it does not create a disbursement-ready Advance/Loan record.","HR/Admin/Owner/Super Admin finalizes approved amount and recovery plan before the request moves to Pending Disbursement.","Added RTDB validation and a build regression check to prevent employee-side recovery-plan injection."]},{version:"5.4.201",date:"24 Aug 2026",title:"Attendance Connector Firebase Permission Recovery",changes:["Restored same-company branch_manager write access required by the Attendance Connector heartbeat, device status and connector command lifecycle.","Tenant isolation remains enforced: authenticated user companyId must match the target companyId; no open Firebase write rule was introduced.","Added a mandatory attendance connector RTDB rules regression check to the production build so future security changes cannot silently break connector sync.","No Payroll/Advance-Loan or Service Receive workflow logic was changed."]},{version:"5.4.200",date:"24 Aug 2026",title:"Payroll & Advance/Loan Regression Hardening",changes:["Added mandatory automated Advance/Loan + Payroll accounting regression suite to the production build pipeline.","Regression coverage includes unpaid allocation, full payment on next-month date, partial payment, multi-payment completion date, reversal, monthly installments, idempotent Sync, principal cap and Dr=Cr balance.","Added Payroll Health Check to detect stale payment status/amount, missing or premature recovery settlement, unbalanced journals and duplicate recovery settlement source IDs.","Sync Accounts remains the repair action for reconciliation issues; Health Check verifies the result without changing data.","Production build now fails before deployment if payroll regression checks fail."]},{version:"5.4.198",date:"24 Aug 2026",title:"Payroll Payment Reconciliation & Missing Recovery Repair",changes:["Payroll employee payment status now uses Salary Payment History as the source of truth instead of stale stored labels.","A fully paid employee can no longer display Partially Paid when Payment History equals Net Payable.","Sync Accounts now reconciles employee, payroll-run and Salary Payable paid/outstanding/status values from active payment transactions.","Sync Accounts also posts any missing Advance/Loan recovery for legacy fully-paid employees on the actual payment-completion date.","General Ledger therefore closes the remaining Advance/Loan Receivable after legacy paid salary records are reconciled."]},{version:"5.4.197",date:"24 Aug 2026",title:"Actual Payment Date Advance/Loan Recovery Accounting",changes:["Payroll Lock no longer credits Employee Advance/Loan Receivable; allocated recovery is posted to Payroll Recovery Clearing (2290).","Advance/Loan Receivable is credited only when that employee salary becomes fully paid, using the actual salary Payment Date.","Added automatic Payroll Recovery Clearing account creation when required.","Sync Accounts migrates already-locked payroll journals and creates recovery settlements for employees already fully paid.","Salary payment reversal posts a reversing recovery journal and returns the Advance/Loan to Allocated when the employee is no longer fully paid.","Sync Accounts now removes stale payroll journal ledger lines before rebuilding, preventing legacy recovery entries from remaining in General Ledger."]},{version:"5.4.196",date:"24 Aug 2026",title:"Safe Salary Payment Review",changes:["Salary payment is now strictly two-step: Record Payment opens a review form and does not post money.","Payment Date is blank by default so the actual cash/bank payment date must be selected explicitly.","Added a mandatory Confirm payment details checkbox before Confirm Payment is enabled.","Renamed the employee action from Pay to Record Payment to prevent accidental one-click settlement.","Existing Salary Payment History reversal and Advance/Loan Allocated-to-Recovered settlement logic remains unchanged."]},{version:"5.4.195",date:"24 Aug 2026",title:"Advance/Loan Allocated â Recovered Settlement",changes:["Payroll Lock now marks scheduled Advance/Loan recovery as Allocated instead of operationally Completed.","Advance/Loan becomes Recovered/Completed only after that employee's s
4155alary for the payroll month is fully paid.","Advance & Loan dashboard now separates Allocated in Payroll, Recovered and Outstanding amounts.","Salary payment reversal returns affected recovery to Allocated / Awaiting Salary Payment.","Authorized payroll unlock before payment clears the current payroll allocation state.","Accounting remains recognized at payroll lock; salary payment does not post the Advance/Loan receivable a second time."]},{version:"5.4.194",date:"23 Aug 2026",title:"Locked Payroll Accounts Sync & GL Reference Cleanup",changes:["General Ledger now hides legacy ADVLOAN Firebase/internal references and shows readable Salary Advance / Employee Loan references in both screen and PDF.","Added Sync Accounts action for already-locked payrolls created before payroll accounting posting was introduced.","Sync Accounts posts the locked payroll journal without reopening or recalculating salary.","Advance/Loan recovery and completion status are synchronized during the same accounting sync.","Future payroll locks continue to post Accounts automatically."]},{version:"5.4.193",date:"23 Aug 2026",title:"Advance/Loan Recovery Accounting Completion",changes:["Removed internal Firebase ADVLOAN IDs from General Ledger references; Advance/Loan vouchers now use readable employee business references.","Payroll Lock now creates a balanced payroll accounting journal branch-wise.","Scheduled Advance recovery credits Employee Salary Advance Receivable and scheduled Loan recovery credits Employee Loan Receivable.","Salary Payable, Tax Payable, PF Payable and Salary & Wages are posted together so Advance/Loan recovery remains double-entry balanced.","Only scheduled Advance/Loan recoveries linked to register records affect the receivable ledgers; legacy manual deductions do not create false receivable credits.","Fully recovered Advance/Loan records automatically become Completed after Payroll Lock.","Internal payroll Test Reset also removes the payroll accounting journal and reopens records completed by that reset month."]},{version:"5.4.192",date:"23 Aug 2026",title:"Salary-Month Advance/Loan Recovery",changes:["Advance/Loan recovery is now explicitly based on Salary Month, not salary payment date.","Renamed Recovery Starts to Recover From Salary Month in direct issue and employee self-service request forms.","Payroll generation automatically deducts active Advance/Loan recovery from the selected payroll Salary Month.","One-time recovery takes the remaining balance from the selected Salary Month; monthly recovery deducts installments until settled.","Locked payroll recovery history is used to prevent the same Advance/Loan balance from being recovered twice.","Added Edit Recovery action for active records with no locked recovery yet, allowing existing September schedules to be changed to August Salary when required.","Payroll sheet/PDF column label now clearly shows Advance / Loan / Other."]},{version:"5.4.191",date:"23 Aug 2026",title:"Advance/Loan Pending Workflow Dashboard",changes:["Payroll â Advance & Loan now shows Pending Approval requests in the same page.","Added Pending Disbursement section with direct Disburse action for authorized Finance/Payroll users.","Added workflow counters for Pending Approval and Pending Disbursement.","Renamed the old manual issue button to Direct Advance / Loan to distinguish it from employee self-service requests.","Existing Active Advance/Loan recovery register remains unchanged."]},{version:"5.4.190",date:"23 Aug 2026",title:"Employee Advance/Loan Approval Workflow",changes:["Added employee self-service Advance/Loan application routed to the assigned Reporting Manager.","Reporting Manager can approve up to the requested amount or reject with a reason.","Approval creates the employee Advance/Loan record as Pending Disbursement; payroll recovery does not start yet.","Authorized Payroll/Finance user can Disburse the approved amount by Cash or Bank; only then is the Payment Voucher posted and payroll recovery activated.","Fixed the v5.4.189 audit action/entity TypeScript errors reported by One Click Update."]},{version:"5.4.189",date:"23 Aug 2026",title:"Advance & Loan Accounting Auto-Posting",changes:["Employee Advance/Loan issue now posts a Payment Voucher automatically.","Salary Advance posts Employee Salary Advance Receivable Dr and Cash/Bank Cr.","Employee Loan posts Employee Loan Receivable Dr and Cash/Bank Cr.","Added dedicated 1410 and 1420 receivable ledgers to the standard Chart of Accounts.","Existing initialized companies auto-create the required receivable ledger when the first Advance/Loan is posted.","Advance/Loan register stores its accounting voucher number for traceability.","Issue is blocked for locked accounting periods and when finance posting permission is missing."]},{version:"5.4.188",date:"23 Aug 2026",title:"Employee Advance & Loan Recovery",changes:["Added Payroll â Advance & Loan for issuing employee Advance or Loan records.","Recovery can be configured as One Time or Monthly Installment with a selectable recovery start month.","Monthly plans store installment count and automatically calculate the scheduled payroll deduction.","Payroll generation now includes scheduled Advance/Loan recovery while preserving any existing manual adjustment amount.","Outstanding and recovered amounts are calculated from locked payroll history so draft/regenerated payroll does not falsely reduce the balance.","Added Firebase security rules for the employee Advance/Loan register using existing payroll permissions."]},{version:"5.4.186",date:"23 Aug 2026",title:"Unified PDF Action Buttons",changes:["Changed View PDF to the same solid VERIXO blue style as Download PDF.","Applied the unified PDF action style to both Trial Balance and General Ledger.","Kept Close as a separate secondary action so it remains visually distinct.","No accounting calculations, PDF content, voucher logic or saved data were changed."]},{version:"5.4.185",date:"23 Aug 2026",title:"PDF Preview Action Styling",changes:["Made Close visually distinct from View PDF and Download PDF in Trial Balance and General Ledger previews.","Close now uses a soft red danger treatment while View remains outline blue and Download remains primary blue."]},{version:"5.4.184",date:"23 Aug 2026",title:"General Ledger Report",changes:["Added Reports â Accounts & Finance â General Ledger.","General Ledger supports account selection, From/To period, branch scope, voucher/reference search, opening balance and running balance.","Added full-screen View PDF and Download PDF for the selected account ledger.","Restored the VERIXO outline styling for the Trial Balance View PDF button.","Existing voucher posting, reversal, Trial Balance calculations and accounting data remain unchanged."]},{version:"5.4.183",date:"23 Aug 2026",title:"Full-Screen Trial Balance PDF Viewer",changes:["Changed Trial Balance PDF preview from a centered modal to a full-screen viewer.","The PDF now uses the full browser viewport with a slim VERIXO header.","Download PDF and Close actions remain available while the native PDF toolbar handles zoom, print and page controls.","Trial Balance calculations and PDF report content are unchanged."]},{version:"5.4.182",date:"23 Aug 2026",title:"Trial Balance PDF Preview",changes:["Added View PDF beside Download PDF on Trial Balance.","View PDF opens an in-app VERIXO preview so the report can be checked before downloading.","The preview includes a Download PDF action after review.","Existing period calculations and PDF report layout remain unchanged."]},{version:"5.4.181",date:"23 Aug 2026",title:"Period Trial Balance + PDF Report",changes:["Upgraded Trial Balance from single As-of Date to From Date / To Date period reporting.","Opening balances now include the pre-period ledger position; Period Debit/Credit show only transactions inside the selected range.","Closing Debit/Credit are calculated at the end of the selected period with balanced/difference validation.","Added a professional landscape A4 Trial Balance PDF with company branding, branch, period, totals and balance status.","PDF generation is direct from VERIXO using jsPDF; no browser print dialog is required."]},{version:"5.4.180",date:"23 Aug 2026",title:"Trial Balance Foundation",changes:["Added Reports â Accounts & Finance â Trial Balance.","Trial Balance reads posted double-entry ledger transactions and calculates account-wise closing Debit/Credit balances.","Added As-of Date, branch scope, account search, zero-balance filtering and balance-difference validation.","Consolidated All Branches view includes existing company-level Opening Balances;
4155 branch-specific views do not duplicate company-level opening balances.","Existing voucher posting, reversal, branch-wise Cash in Hand and Ledger logic remain unchanged."]},{version:"5.4.179",date:"23 Aug 2026",title:"Responsive Layout Foundation",changes:["Added a fluid VERIXO workspace/content foundation so common desktop and laptop resolutions work correctly at 100% browser zoom.","Improved layout spacing for 1366/1440-class laptop widths without scaling the application.","Fixed Voucher Entry viewport sizing, internal scrolling and sticky footer overlap so totals remain accessible on short screens.","Added responsive reflow for Voucher details, KPI cards and Ledger summaries while preserving wide-table internal scrolling.","No accounting, HR, Payroll, Service or database business logic was changed."]},{version:"5.4.178",date:"23 Aug 2026",title:"Account Ledger & Running Balance",changes:["Added account-wise posted transaction ledger with Debit, Credit and Running Balance.","Ledger follows the current branch scope; All Branches shows the accumulated account position.","Added account search/selection and account summary totals without changing voucher posting logic."]},{version:"5.4.177",date:"23 Aug 2026",title:"Controlled Voucher Reversal UX",changes:["Replaced the browser-native Reverse confirmation with a VERIXO-styled confirmation modal.","Reversal vouchers can no longer be reversed again;
4155 their Reverse action is hidden.","Original posted vouchers remain reversible only once, preserving a clear accounting audit trail.","Existing reversal accounting logic and ledger-entry creation remain unchanged."]},{version:"5.4.176",date:"23 Aug 2026",title:"Professional Voucher Entry UI",changes:["Redesigned the New Voucher / Edit Draft form with a cleaner professional layout.","Removed the large accounting explanation/note box completely.","Improved Voucher Details, fixed Branch presentation, accounting-entry table, amount alignment and total/balance summary.","Kept branch locking, double-entry validation, posting, reversal and accounting data logic unchanged."]},{version:"5.4.175",date:"23 Aug 2026",title:"Voucher Branch Fixed from Workspace / User",changes:["When a specific workspace Branch is selected, New Voucher now shows that Branch as fixed read-only instead of a dropdown.","Normal users are fixed to their assigned Branch for voucher create, edit, post and reverse actions.","Authorized All Branches users may choose a real Branch only when the workspace itself is set to All Branches.","Removed Company / Unassigned from voucher branch selection.","Voucher list and KPI counts now follow the selected/assigned branch scope."]},{version:"5.4.174",date:"23 Aug 2026",title:"Assigned-Branch Accounting Entry Lock",changes:["Normal users are automatically locked to their assigned branch for accounting voucher entry.","Single-branch users no longer need to select a branch; the assigned branch is shown as fixed.","All-Branches users such as Owner/Super Admin may still choose the transaction branch.","Draft edit, post and reverse actions are blocked when the voucher belongs to another branch.","Firebase validation also prevents users with a primary assigned branch from writing voucher/ledger data to another branch."]},{version:"5.4.173",date:"23 Aug 2026",title:"Branch-wise Cash in Hand",changes:["Kept one master 1110 · Cash in Hand account while tracking posted cash by branchId.","Added live branch-wise Cash in Hand balances to Vouchers & Journal; All Branches shows the accumulated total.","Cash postings now require a Branch so new cash cannot silently enter Company / Unassigned.","Legacy unassigned cash remains visible separately for reconciliation instead of being auto-moved.","Existing Chart of Accounts, Opening Balances, Accounting Period and double-entry voucher posting remain unchanged."]},{version:"5.4.172",date:"23 Aug 2026",title:"Double-Entry Voucher Posting Engine",changes:["Added Accounts & Finance â Vouchers & Journal.","Added Journal, Payment, Receipt and Contra/Transfer voucher drafts.","Added balanced double-entry posting with branch-aware JV/PV/RV/CV numbering.","Added posted ledger-entry creation, accounting-period lock validation and controlled reversal vouchers.","Payment requires Cash/Bank credit, Receipt requires Cash/Bank debit, and Contra allows only Cash/Bank accounts.","Existing Invoice, Collection, Payroll and Gratuity flows are still isolated from automatic accounting posting in this controlled phase."]},{version:"5.4.171",date:"23 Aug 2026",title:"Accounting Foundation Tabs & Balance Controls",changes:["Fixed Chart of Accounts active-tab hover so the blue active state no longer turns white.","Opening Balances and Accounting Period are explicitly disabled only before Chart of Accounts initialization and become available after the chart exists.","Opening Balance now blocks saving when Debit and Credit are not equal and shows the exact difference.","Accounting Period now shows chart readiness and configured lock-foundation status more clearly."]},{version:"5.4.170",date:"23 Aug 2026",title:"Accounting Foundation Build Fix",changes:["Fixed the TypeScript duplicate-property build error in Accounting Foundation settings loading.","No accounting data model, calculations, menu structure or existing business workflow was changed."]},{version:"5.4.169",date:"23 Aug 2026",title:"Accounting Foundation · Chart of Accounts",changes:["Added Accounts & Finance â Chart of Accounts.","Added a standard VERIXO Chart of Accounts initializer with system-linked accounts for Cash, Bank, Receivable, Payable, Payroll, Gratuity, Tax, PF, Sales, Service and Inventory.","Added custom account create/edit/activate/deactivate controls with account-code duplicate protection.","Added Opening Balance entry with Debit/Credit balancing summary.","Added financial-year, opening-date, current-period and future period-lock foundation settings.","Existing Invoices, Collections, Salary Payable, Payroll and Gratuity transactions are not auto-posted yet; journal posting will be added in the next accounting phase."]},{version:"5.4.168",date:"23 Aug 2026",title:"Reports Menu Finance Submenu Fix",changes:["Moved Collection Report and Due Report out of the Accounts & Finance main menu.","Added Accounts & Finance as a submenu inside the main Reports menu.","Collection Report and Due Report now sit under Reports â Accounts & Finance.","Sales â Invoices and Accounts & Finance â Collections / Salary Payable remain unchanged."]},{version:"5.4.167",date:"23 Aug 2026",title:"Sales & Accounts Menu Reorganization",changes:["Moved Invoices out of Accounts & Finance and into a new Sales menu.","Accounts & Finance now keeps Collections and
4155Salary Payable at the main level.","Added an Accounts & Finance â Reports section with separate Collection Report and Due Report entries.","Kept the existing invoice, collection, salary payable and report data/logic unchanged."]},{version:"5.4.166",date:"23 Aug 2026",title:"Accounts & Finance Audit + Menu Consolidation",changes:["Moved Salary Payable out of Reports and into Accounts & Finance.","Moved Collection and Due reporting into a dedicated Accounts & Finance report page.","Kept service/customer/branch reporting under the Reports menu.","Completed a code-level Accounts & Finance gap audit before starting the accounting core."]},{version:"5.4.165",date:"23 Aug 2026",title:"Visible Version & What's New",changes:["Visible ERP version updated to v5.4.165.","Added Version & What's New under Settings & Admin.","Sidebar version is now clickable and opens the release history.","Added an in-app summary of recent release changes so update contents can be checked without opening the ZIP."]},{version:"5.4.164",date:"23 Aug 2026",title:"HR & Payroll Final Security Hardening",changes:["Completed the final HR and Payroll source-level audit.","Hardened Firebase write permissions for critical HR, Payroll, Recruitment, Gratuity, Appraisal, Performance and Attendance-management data.","Separated Payroll management, salary-payment and statutory-payment permissions.","Preserved employee leave self-service while restricting approval and management actions.","Kept current Attendance Connector ingestion paths compatible with the existing connector architecture."]},{version:"5.4.163",date:"23 Aug 2026",title:"Recruitment Final Polish",changes:["Finalized vacancy Openings, Hired and Remaining tracking.","Added vacancy Edit and Close controls.","Completed Selected candidate to Employee linkage.","Added Payroll-linked status/repair flow for recruited employees."]}];function KU(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"System information"}),e.jsx("h1",{children:"Version & What's New"}),e.jsx("p",{children:"See the currently running VERIXO version and the changes included in recent releases."})]}),e.jsxs("span",{className:"version-current-badge",children:["Current v",Dd]})]}),e.jsx("section",{className:"panel version-history-panel",children:JU.map((t,n)=>e.jsxs("article",{className:"version-release-card",children:[e.jsxs("div",{className:"version-release-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"version-release-title-row",children:[e.jsxs("h2",{children:["VERIXO ERP v",t.version]}),n===0&&e.jsx("span",{className:"version-latest-badge",children:"Current"})]}),e.jsx("strong",{children:t.title})]}),e.jsx("time",{children:t.date})]}),e.jsx("ul",{children:t.changes.map(a=>e.jsx("li",{children:a},a))})]},t.version))})]})}function XU({profile:t,company:n,onSaved:a}){const[s,i]=x.useState(n??{...i5,id:t.companyId}),[c,l]=x.useState(!1),m=t.role==="owner"||t.role==="super_admin";x.useEffect(()=>{i(n??{...i5,id:t.companyId})},[n,t.companyId]);const d=f=>{if(!f)return;if(!f.type.startsWith("image/")){window.alert("Bangla QR-à¦à¦° PNG/JPG/WebP image select à¦à¦°à§à¦¨à¥¤");return}
4155if(f.size>3*1024*1024){window.alert("QR image 3 MB-à¦à¦° মধà§à¦¯à§ রাà¦à§à¦¨à¥¤");return}const g=new FileReader;g.onload=()=>{const p=new Image;p.onload=()=>{const b=Math.min(1,900/Math.max(p.width,p.height)),N=document.createElement("canvas");N.width=Math.max(1,Math.round(p.width*b)),N.height=Math.max(1,Math.round(p.height*b));const w=N.getContext("2d");w&&(w.drawImage(p,0,0,N.width,N.height),i(C=>({...C,banglaQrImage:N.toDataURL("image/png",.92),banglaQrEnabled:!0})))},p.src=String(g.result||"")},g.readAsDataURL(f)},u=async f=>{if(f.preventDefault(),!!m){l(!0);try{const g={...s,id:t.companyId,updatedAt:Date.now()};await Pn(re(ie,`companies/${t.companyId}`),g),a(g)}finally{l(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-heading",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Organisation settings"}),e.jsx("h1",{children:"Company profile"}),e.jsx("p",{children:"Company identity and contact information manage à¦à¦°à§à¦¨à¥¤"})]})}),e.jsx("section",{className:"panel form-panel",children:e.jsxs("form",{onSubmit:u,className:"data-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Company name",e.jsx("input",{value:s.name,onChange:f=>i({...s,name:f.target.value}),disabled:!m,required:!0})]}),e.jsxs("label",{children:["Phone",e.jsx("input",{value:s.phone??"",onChange:f=>i({...s,phone:f.target.value}),disabled:!m})]}),e.jsxs("label",{children:["Email",e.jsx("input",{type:"email",value:s.email??"",onChange:f=>i({...s,email:f.target.value}),disabled:!m})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:s.active?"active":"inactive",onChange:f=>i({...s,active:f.target.value==="active"}),disabled:!m,children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]}),e.jsxs("label",{className:"full-field",children:["Address",e.jsx("textarea",{value:s.address??"",onChange:f=>i({...s,address:f.target.value}),disabled:!m,rows:4})]})]}),e.jsxs("section",{className:"company-numbering-section",children:[e.jsx("div",{className:"section-heading-row",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Service payment"}),e.jsx("h2",{children:"Bangla QR Payment"}),e.jsx("p",{children:"On-site billing-ঠcustomer à¦à¦ company-approved QR scan à¦à¦°à§ সরাসরি company account-ঠpayment à¦à¦°à¦¤à§ পারবà§à¥¤"})]})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Bangla QR",e.jsxs("select",{value:s.banglaQrEnabled?"enabled":"disabled",onChange:f=>i({...s,banglaQrEnabled:f.target.value==="enabled"}),disabled:!m,children:[e.jsx("option",{value:"disabled",children:"Disabled"}),e.jsx("option",{value:"enabled",children:"Enabled"})]})]}),e.jsxs("label",{children:["Payment label",e.jsx("input",{value:s.banglaQrLabel??"Bangla QR",onChange:f=>i({...s,banglaQrLabel:f.target.value}),disabled:!m,placeholder:"Bangla QR"})]}),m&&e.jsxs("label",{children:["Upload QR image",e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",onChange:f=>{var g;return d((g=f.target.files)==null?void 0:g[0])}})]}),s.banglaQrImage&&e.jsxs("div",{children:[e.jsx("span",{children:"Approved company QR"}),e.jsx("div",{style:{marginTop:8},children:e.jsx("img",{src:s.banglaQrImage,alt:"Bangla QR",style:{width:180,height:180,objectFit:"contain",border:"1px solid #d9e1ea",borderRadius:12,padding:8}})}),m&&e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>i({...s,banglaQrImage:"",banglaQrEnabled:!1}),children:"Remove QR"})]})]})]}),e.jsxs("section",{className:"company-numbering-section",children:[e.jsx("div",{className:"section-heading-row",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"ERP foundation"}),e.jsx("h2",{children:"Document Numbering"})]})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Company Code",e.jsx("input",{value:s.companyCode??"VRX",maxLength:8,onChange:f=>i({...s,companyCode:hx(f.target.value)}),disabled:!m})]}),e.jsxs("label",{children:["Currency",e.jsxs("select",{value:s.currency??"BDT",onChange:f=>i({...s,currency:f.target.value}),disabled:!m,children:[e.jsx("option",{value:"BDT",children:"BDT â Bangladeshi Taka"}),e.jsx("option",{value:"GBP",children:"GBP â Pound Sterling"}),e.jsx("option",{value:"USD",children:"USD â US Dollar"})]})]}),e.jsxs("label",{children:["Time Zone",e.jsx("input",{value:s.timezone??"Asia/Dhaka",onChange:f=>i({...s,timezone:f.target.value}),disabled:!m})]}),e.jsxs("label",{children:["Date Format",e.jsxs("select",{value:s.dateFormat??"DD/MM/YYYY",onChange:f=>i({...s,dateFormat:f.target.value}),disabled:!m,children:[e.jsx("option",{value:"DD/MM/YYYY",children:"DD/MM/YYYY"}),e.jsx("option",{value:"YYYY-MM-DD",children:"YYYY-MM-DD"}),e.jsx("option",{value:"MM/DD/YYYY",children:"MM/DD/YYYY"})]})]}),e.jsxs("label",{children:["Financial Year",e.jsx("input",{value:s.financialYear??String(new Date().getFullYear()),onChange:f=>i({...s,financialYear:f.target.value}),disabled:!m})]})]}),e.jsx("div",{className:"section-heading-row appraisal-settings-heading",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"HR settings"}),e.jsx("h2",{children:"Appraisal Settings"}),e.jsx("p",{children:"Set the month from which this company officially starts using VERIXO Employee Appraisal."})]})}),e.jsx("div",{className:"form-grid",children:e.jsxs("label",{children:["Appraisal Effective From",e.jsx("input",{type:"month",value:s.appraisalEffectiveFrom??"",onChange:f=>i({...s,appraisalEffectiveFrom:f.target.value}),disabled:!m}),e.jsx("small",{children:"Yearly appraisal will require monthly reviews only from this month onward. Employee joining date is also respected."})]})}),e.jsx("div",{className:"document-prefix-grid",children:[["serviceJob","Service Job"],["quotation","Quotation"],["estimate","Estimate"],["invoice","Invoice"],["collection","Collection"],["moneyReceipt","Money Receipt"],["paymentVoucher","Payment Voucher"],["purchaseOrder","Purchase Order"],["journalVoucher","Journal Voucher"]].map(([f,g])=>{const p={...gg,...s.documentPrefixes||{}};return e.jsxs("label",{children:[e.jsx("span",{children:g}),e.jsx("input",{value:p[f],maxLength:8,disabled:!m,onChange:y=>i({...s,documentPrefixes:{...p,[f]:y.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}})}),e.jsx("small",{children:aE({companyCode:s.companyCode,documentType:f,prefixes:p})})]},f)})})]}),m&&e.jsx("div",{className:"form-actions",children:e.jsxs("button",{type:"submit",disabled:c,
4155children:[e.jsx(hr,{size:17})," ",c?"Saving...":"Save company"]})})]})})]})}function ZU({profile:t}){const[n,a]=x.useState([]),[s,i]=x.useState(!1),[c,l]=x.useState(null),[m,d]=x.useState(Gj),[u,f]=x.useState(!1),g=t.role==="owner"||t.role==="super_admin";x.useEffect(()=>{const C=re(ie,`branches/${t.companyId}`);return qt(C,R=>{if(!R.exists()){a([]);return}const I=R.val();a(Object.entries(I).map(([_,J])=>({id:_,...J})).sort((_,J)=>J.createdAt-_.createdAt))})},[t.companyId]);const p=()=>{l(null),d(Gj),i(!0)},y=C=>{var R;l(C),d({name:C.name,code:C.code,phone:C.phone??"",address:C.address??"",contacts:(R=C.contacts)!=null&&R.length?C.contacts.map(I=>({...I})):C.phone?[{label:"Phone",phone:C.phone}]:[],managerName:C.managerName??"",active:C.active}),i(!0)},b=()=>{i(!1),l(null),d(Gj)},N=async C=>{var R;if(C.preventDefault(),!!g){f(!0);try{const I=m.contacts.map(J=>({label:J.label.trim(),phone:J.phone.trim()})).filter(J=>J.label&&J.phone),_={...m,contacts:I,phone:((R=I[0])==null?void 0:R.phone)||m.phone.trim()};if(c)await yn(re(ie,`branches/${t.companyId}/${c.id}`),{..._,updatedAt:Date.now()});else{const J=Ta(re(ie,`branches/${t.companyId}`));await Pn(J,{..._,companyId:t.companyId,createdAt:Date.now(),updatedAt:Date.now()})}b()}finally{f(!1)}}},w=async C=>{g&&window.confirm(`${C.name} branch delete à¦à¦°à¦¬à§à¦¨?`)&&await Ao(re(ie,`branches/${t.companyId}/${C.id}`))};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Multi-branch setup"}),e.jsx("h1",{children:"Branches"}),e.jsx("p",{children:"Branch name, code, manager, contact phone à¦à¦¬à¦ address à¦à¦ à¦à¦¾à§à¦à¦¾ থà§à¦à§ manage à¦à¦°à§à¦¨à¥¤"})]}),g&&e.jsxs("button",{className:"primary-action",onClick:p,children:[e.jsx(as,{size:18})," Add branch"]})]}),e.jsxs("section",{className:"panel",children:[e.jsx("div",{className:"panel-heading",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Branch list"}),e.jsxs("p",{children:[n.length," branch configured"]})]})}),n.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx(Fu,{size:35}),e.jsx("h3",{children:"No branch added yet"}),e.jsx("p",{children:"পà§à¦°à¦¥à¦® branch যà§à¦ à¦à¦°à¦²à§ multi-branch operation শà§à¦°à§ হবà§à¥¤"})]}):e.jsx("div",{className:"table-wrap",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Branch"}),e.jsx("th",{children:"Code"}),e.jsx("th",{children:"Manager"}),e.jsx("th",{children:"Phone"}),e.jsx("th",{children:"Status"}),g&&e.jsx("th",{children:"Actions"})]})}),e.jsx("tbody",{children:n.map(C=>{var R;return e.jsxs("tr",{children:[e.jsxs("td",{children:[e.jsx("strong",{children:C.name}),e.jsx("small",{className:"table-subtext",children:C.address||"No address"})]}),e.jsx("td",{children:C.code}),e.jsx("td",{children:C.managerName||"â"}),e.jsx("td",{children:(R=C.contacts)!=null&&R.length?C.contacts.map(I=>`${I.label}: ${I.phone}`).join(" · "):C.phone||"â"}),e.jsx("td",{children:e.jsx("span",{className:`status ${C.active?"":"inactive"}`,children:C.active?"Active":"Inactive"})}),g&&e.jsx("td",{children:e.jsxs("div",{className:"row-actions",children:[e.jsx("button",{onClick:()=>y(C),children:e.jsx(Zi,{size:16})}),e.jsx("button",{onClick:()=>w(C),children:e.jsx(po,{size:16})})]})})]},C.id)})})]})})]}),s&&e.jsx("div",{className:"modal-backdrop",onMouseDown:b,children:e.jsxs("section",{className:"modal",onMouseDown:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:c?"Update branch":"New branch"}),e.jsx("h2",{children:c?"Edit branch":"Add branch"})]}),e.jsx("button",{onClick:b,children:e.jsx(ja,{size:20})})]}),e.jsxs("form",{onSubmit:N,className:"data-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Branch name",e.jsx("input",{value:m.name,onChange:C=>d({...m,name:C.target.value}),required:!0})]}),e.jsxs("label",{children:["Branch code",e.jsx("input",{value:m.code,onChange:C=>d({...m,code:C.target.value.toUpperCase()}),required:!0})]}),e.jsxs("label",{children:["Manager name",e.jsx("input",{value:m.managerName,onChange:C=>d({...m,managerName:C.target.value})})]}),e.jsxs("div",{className:"full-field",children:[e.jsx("label",{children:"Branch Contact Information"}),e.jsx("small",{children:"Add as many labelled contact lines as this branch needs â e.g. Sales, Mobile, Service, Warranty Section, Hardware."}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:10},children:[m.contacts.map((C,R)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(130px, .8fr) minmax(220px, 2fr) auto",gap:8,alignItems:"center"},children:[e.jsx("input",{value:C.label,onChange:I=>{const _=[...m.contacts];_[R]={..._[R],label:I.target.value},d({...m,contacts:_})},placeholder:"Label (e.g. Sales)"}),e.jsx("input",{value:C.phone,onChange:I=>{const _=[...m.contacts];_[R]={..._[R],phone:I.target.value},d({...m,contacts:_})},placeholder:"Phone number(s), comma separated if needed",inputMode:"tel"}),e.jsx("button",{type:"button",className:"secondary-button",onClick:()=>d({...m,contacts:m.contacts.filter((I,_)=>_!==R)}
4155),"aria-label":"Remove contact line",children:e.jsx(po,{size:16})})]},R)),e.jsx("div",{children:e.jsxs("button",{type:"button",className:"secondary-button",onClick:()=>d({...m,contacts:[...m.contacts,{label:"",phone:""}]}),children:[e.jsx(as,{size:16})," Add Contact Line"]})})]})]}),e.jsxs("label",{className:"full-field",children:["Branch Address",e.jsx("textarea",{value:m.address,onChange:C=>d({...m,address:C.target.value}),rows:3,placeholder:"Full branch address"}),e.jsx("small",{children:"This address will be used on branch-specific reports/documents."})]}),e.jsxs("label",{children:["Status",e.jsxs("select",{value:m.active?"active":"inactive",onChange:C=>d({...m,active:C.target.value==="active"}),children:[e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"inactive",children:"Inactive"})]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{type:"button",className:"secondary-button",onClick:b,children:"Cancel"}),e.jsxs("button",{type:"submit",disabled:u,children:[e.jsx(hr,{size:17})," ",u?"Saving...":"Save branch"]})]})]})]})})]})}const ez=9e4;function tz({profile:t,onWorkspaceProfileChange:n}){var De;const[a,s]=x.useState(""),[i,c]=x.useState([]),[l,m]=x.useState(!1),[d,u]=x.useState(!1),f=x.useRef(null),g=x.useMemo(()=>s5(),[]),[p,y]=x.useState(g.page),[b,N]=x.useState(null),[w,C]=x.useState(null),[R,I]=x.useState(!1),[_,J]=x.useState(null),[T,G]=x.useState([]),[z,H]=x.useState([]),[K,L]=x.useState(!1),[D,M]=x.useState(!1),Z=Sp(t),fe=x.useMemo(()=>_h(t),[t.branchId,t.branchIds,t.allBranches,t.role]),[q,ne]=x.useState(Z?"all":t.branchId||fe[0]||""),[ae,Y]=x.useState(()=>localStorage.getItem("scc-theme")||"light"),[je,V]=x.useState(!1),[$,F]=x.useState({}),[P,ue]=x.useState(!1),[me,ge]=x.useState(!1),[de,Pe]=x.useState(g.jobId),[Re,Ee]=x.useState(),[Be,We]=x.useState({operations:!1,crm:!1,sales:!1,purchase:!1,finance:!1,performance:!1,business:!1,people:!1,attendance:!1,reports:!1,rma:!1,setup:!1,setupAccounts:!1,setupOrganization:!1,setupHr:!1,setupAdmin:!1});x.useEffect(()=>{if(t.companyId)return qt(re(ie,`payrollSettings/${t.companyId}`),Te=>{const ce=Te.exists()?Te.val()||{}:{};ue(!!(ce.statutoryEnabled&&ce.taxEnabled))},Te=>{console.error("Payroll settings load for tax notifications failed:",Te),ue(!1)})},[t.companyId]),x.useEffect(()=>{if(t.companyId){if(!["super_admin","owner","admin","hr"].includes(t.role)){F({});return}return qt(re(ie,`workspaceNotifications/${t.companyId}`),Te=>{F(Te.exists()?Te.val():{})},Te=>{console.error("Workspace notifications load failed:",Te),F({})})}},[t.companyId,t.role]),x.useEffect(()=>{if(!t.companyId||!["super_admin","owner","admin","hr"].includes(t.role))return;let Te=!1;return(async()=>{try{const Ye=re(ie,`workspaceNotifications/${t.companyId}`);if(!P){const jt=await mn(Ye);if(Te||!jt.exists())return;const bt={},tn=jt.val()||{};Object.entries(tn).forEach(([B,xe])=>{((xe==null?void 0:xe.category)==="tax_rule_update"||(xe==null?void 0:xe.category)==="tax_rule"||(xe==null?void 0:xe.source)==="nbr_monitor"||(xe==null?void 0:xe.source)==="system_backfill")&&(bt[`workspaceNotifications/${t.companyId}/${B}`]=null)}),Object.keys(bt).length&&await yn(re(ie),bt);return}const Je=await mn(re(ie,"taxMonitor/global/current"));if(Te||!Je.exists())return;const le=Je.val()||{},nt=String(le.hash||"");if(!nt)return;const xt=await mn(re(ie,`taxMonitorAcknowledgements/${t.companyId}/lastHash`)),te=xt.exists()?String(xt.val()||""):"";if(nt===te)return;const Ge=`nbr_monitor_${nt.slice(0,20)}`,pt=await mn(Ye);if(Te)return;const $e={};if(pt.exists()){const jt=pt.val()||{};for(const[bt,tn]of Object.entries(jt))bt!==Ge&&((tn==null?void 0:tn.category)==="tax_rule_update"||(tn==null?void 0:tn.source)==="nbr_monitor")&&($e[`workspaceNotifications/${t.companyId}/${bt}`]=null);if(jt[Ge]){Object.keys($e).length&&await yn(re(ie),$e);return}}Object.keys($e).length&&await yn(re(ie),$e);const st=Number(le.itemCount||0),Nt=String(le.latestTitle||"").trim(),be=Date.now();await Pn(re(ie,`workspaceNotifications/${t.companyId}/${Ge}`),{id:Ge,category:"tax_rule_update",audienceRoles:["super_admin","owner","admin","hr"],title:"New NBR income-tax update detected",message:Nt?`${Nt}. Official NBR source changed${st?` (${st} tracked item${st===1?"":"s"})`:""}. Review before changing any payroll tax rule.`:"Official NBR income-tax sources changed. Review the update before changing any payroll tax rule.",sourceHash:nt,actionLabel:"Review Tax Upd
4155ate",actionPage:"payroll",createdAt:be,createdByUid:"nbr_monitor",createdByName:"NBR Rule Update Monitor",readBy:{},source:"nbr_monitor"})}catch(Ye){console.error("NBR tax monitor notification check failed:",Ye)}})(),()=>{Te=!0}},[t.companyId,t.role,P]),x.useEffect(()=>{if(!t.companyId||!["super_admin","owner","admin","hr"].includes(t.role)||!P)return;let Te=!1;return(async()=>{try{const Ye=await mn(re(ie,`payrollSettings/${t.companyId}`));if(Te||!Ye.exists())return;const Je=Ye.val()||{},le=String(Je.taxRuleVersionId||"");if(!Je.statutoryEnabled||!Je.taxEnabled||Je.taxEngineMode!=="approved_rule"||!le)return;const nt=await mn(re(ie,`payrollTaxRules/${t.companyId}/${le}`));if(Te||!nt.exists())return;const xt=nt.val()||{};if(xt.status!=="approved")return;const Ge=`tax_active_${le.replace(/[^A-Za-z0-9_-]/g,"_")}`,pt=re(ie,`workspaceNotifications/${t.companyId}/${Ge}`),$e=await mn(pt);if(Te||$e.exists())return;const Nt=String(xt.fiscalYear||xt.assessmentYear||"").startsWith("2026")?"2026-07-01":void 0,be=Date.now();await Pn(pt,{id:Ge,category:"tax_rule",audienceRoles:["super_admin","owner","admin","hr"],title:"Active NBR tax rule requires review",message:`${le} is currently active for payroll. Owner/Admin/HR should review the rule and effective period before payroll approval.`,ruleId:le,...Nt?{effectiveDate:Nt}:{}
4155,actionLabel:"Review Tax Update",actionPage:"payroll",createdAt:be,createdByUid:t.uid,createdByName:t.name,readBy:{},source:"system_backfill"})}catch(Ye){console.error("Active tax-rule notification seed failed:",Ye)}})(),()=>{Te=!0}},[t.companyId,t.role,t.uid,t.name,P]);const it=x.useMemo(()=>{const Te=new Set;return Object.values($||{}).filter(ce=>!Array.isArray(ce==null?void 0:ce.audienceRoles)||ce.audienceRoles.includes(t.role)).filter(ce=>{const Ye=(ce==null?void 0:ce.category)==="tax_rule_update"||(ce==null?void 0:ce.category)==="tax_rule"||(ce==null?void 0:ce.source)==="nbr_monitor"||(ce==null?void 0:ce.source)==="system_backfill";if(Ye&&!P)return!1;if(!Ye)return!0;const Je=String((ce==null?void 0:ce.sourceHash)||(ce==null?void 0:ce.ruleId)||(ce==null?void 0:ce.category)||(ce==null?void 0:ce.id)||"");return Te.has(Je)?!1:(Te.add(Je),!0)}).sort((ce,Ye)=>Number((Ye==null?void 0:Ye.createdAt)||0)-Number((ce==null?void 0:ce.createdAt)||0))},[$,t.role,P]),_e=it.filter(Te=>{var ce;return!((ce=Te==null?void 0:Te.readBy)!=null&&ce[t.uid])}).length,ee=async Te=>{Te!=null&&Te.id&&(await yn(re(ie),{[`workspaceNotifications/${t.companyId}/${Te.id}/readBy/${t.uid}`]:Date.now()}),Te.actionPage==="payroll"&&(y("payroll"),V(!1)))},qe=Te=>{We(ce=>{const Ye=!ce[Te],Je=Te.startsWith("setup")&&Te!=="setup"?"setup":null;return Te==="attendance"||Je?{...ce,...Je?{[Je]:!0}:{},[Te]:Ye}:Object.keys(ce).reduce((le,nt)=>(le[nt]=nt===Te?Ye:!1,le),{})})};x.useEffect(()=>{document.documentElement.dataset.theme=ae,localStorage.setItem("scc-theme",ae)},[ae]),x.useEffect(()=>{var ce;const Te=(ce=_==null?void 0:_.name)==null?void 0:ce.trim();document.title=Te?`${Te} | VERIXO ERP`:"VERIXO ERP"},[_==null?void 0:_.name]),x.useEffect(()=>{if(t.role!=="super_admin"){H([]);return}const Te=re(ie,"companies");return qt(Te,ce=>{if(!ce.exists()){H([]);return}const Ye=Object.entries(ce.val()).map(([Je,le])=>{const nt=String((le==null?void 0:le.name)||"Company").trim(),xt=String((le==null?void 0:le.slug)||"").trim().toLowerCase()||Fb(nt||(le==null?void 0:le.companyCode)||Je)||Je.toLowerCase();return{id:Je,name:nt,slug:xt,active:(le==null?void 0:le.active)!==!1}}).filter(Je=>Je.active!==!1&&!!Je.slug).sort((Je,le)=>Je.name.localeCompare(le.name));H(Ye)},ce=>{console.error("Super Admin company workspace load failed:",ce),H([])})},[t.role]);const se=Te=>{if(t.role!=="super_admin"||Te===t.companyId){L(!1);return}const ce=z.find(le=>le.id===Te);if(!(ce!=null&&ce.slug)){window.alert("Selected workspace could not be resolved.");return}const Ye={...t,companyId:ce.id},Je=new URL(window.location.href);Je.pathname=`/${encodeURIComponent(ce.slug)}`,window.history.replaceState({workspace:ce.slug},"",`${Je.pathname}${Je.search}${Je.hash}`),L(!1),n==null||n(Ye)};x.useEffect(()=>{const Te=re(ie,`companies/${t.companyId}`);return qt(Te,ce=>{J(ce.exists()?ce.val():null)})},[t.companyId]),x.useEffect(()=>{const Te=re(ie,`branches/${t.companyId}`);return qt(Te,ce=>{if(!ce.exists()){G([]);return}const Ye=ce.val();G(Object.entries(Ye).map(([Je,le])=>({id:Je,...le})))})},[t.companyId]),x.useEffect(()=>{if(Z){q!=="all"&&!T.some(ce=>ce.id===q)&&ne("all");return}const Te=T.filter(ce=>fe.includes(ce.id));if(!Te.length){q&&ne("");return}fe.includes(q)||ne(t.branchId&&fe.includes(t.branchId)?t.branchId:Te[0].id)},[T,fe,t.branchId,q,Z]),x.useEffect(()=>{let Te=!1;const ce=re(ie,`publicEstimateDecisions/${t.companyId}`);return qt(ce,async Ye=>{if(!(!Ye.exists()||Te)){Te=!0;try{const Je=Ye.val(),le=await mn(re(ie,`estimates/${t.companyId}`));if(!le.exists())return;const nt=le.val();for(const[xt,te]of Object.entries(nt)){if(!te.approvalToken)continue;const Ge=Je[te.approvalToken];if(!Ge||te.decisionAppliedAt&&te.clientDecision===Ge.decision)continue;const pt=Ge.decision==="approved"?"approved":"rejected";if(await yn(re(ie,`estimates/${t.companyId}/${xt}`),{status:pt,clientDecision:Ge.decision,clientDecisionAt:Ge.decidedAt,decisionAppliedAt:Date.now(),updatedAt:Ge.decidedAt}),!te.serviceJobId)continue;const $e=await mn(re(ie,`serviceJobs/${t.companyId}/${te.serviceJobId}`));if(!$e.exists())continue;const st={id:te.serviceJobId,...$e.val()},Nt=Ge.decision==="approved"?"approved":"waiting_approval",be=Ge.decision==="approved"?Math.max(0,Number(te.total||0)-Number(st.advanceAmount||0)-Number(st.discountAmount||0)):Number(st.dueAmount||0),jt={approvalPath:"estimate_required",approvalStatus:Ge.decision,approvedEstimateId:Ge.decision==="approved"?xt:"",status:Nt,updatedAt:Ge.decidedAt};Ge.decision==="approved"&&(jt.estimatedCost=Number(te.total||0),jt.dueAmount=be),await yn(re(ie,`serviceJobs/${t.companyId}/${te.serviceJobId}`),jt),await yn(re(ie,`publicTracking/${t.companyId}/${te.serviceJobId}`),{status:Nt,statusLabel:Dr(Nt),updatedAt:Ge.decidedAt});const bt=Ta(re(ie,`jobTimeline/${t.companyId}/${te.serviceJobId}`));await Pn(bt,{id:bt.key,companyId:t.companyId,jobId:te.serviceJobId,jobNumber:st.jobNumber,branchId:st.branchId,status:Nt,title:Ge.decision==="approved"?`Client approved estimate: ${te.estimateNumber}`:`Client rejected estimate: ${te.estimateNumber}`,note:Ge.decision==="approved"?`Estimated amount updated to à§³${Number(te.total||0).toLocaleStr
4155ing("en-GB",{minimumFractionDigits:2,maximumFractionDigits:2})}.`:"Repair must not proceed until a revised estimate is approved.",actorUid:"customer",actorName:"Customer",createdAt:Ge.decidedAt})}}catch(Je){console.error("Estimate approval synchronization failed:",Je)}finally{Te=!1}}})},[t.companyId]),x.useEffect(()=>{const Te=a.trim().toLowerCase();if(Te.length<2){c([]),m(!1);return}let ce=!1;const Ye=window.setTimeout(async()=>{var Je,le,nt,xt;m(!0);try{const te=Date.now();let Ge=f.current;if(!Ge||Ge.companyId!==t.companyId||te-Ge.loadedAt>=ez){const[xe,tt,ht,dt,we,rt,St]=await Promise.all([mn(re(ie,`serviceJobs/${t.companyId}`)),mn(re(ie,`customers/${t.companyId}`)),mn(re(ie,`invoices/${t.companyId}`)),mn(re(ie,`historicalSales/${t.companyId}`)).catch(()=>null),mn(re(ie,`inventoryStock/${t.companyId}`)).catch(()=>null),mn(re(ie,`inventoryProducts/${t.companyId}`)).catch(()=>null),mn(re(ie,`branches/${t.companyId}`)).catch(()=>null)]);if(ce)return;Ge={companyId:t.companyId,loadedAt:Date.now(),customers:tt.exists()?tt.val():{},jobs:xe.exists()?xe.val():{},invoices:ht.exists()?ht.val():{},historicalSales:(Je=dt==null?void 0:dt.exists)!=null&&Je.call(dt)?dt.val():{},inventoryStock:(le=we==null?void 0:we.exists)!=null&&le.call(we)?we.val():{},inventoryProducts:(nt=rt==null?void 0:rt.exists)!=null&&nt.call(rt)?rt.val():{},branches:(xt=St==null?void 0:St.exists)!=null&&xt.call(St)?St.val():{}},f.current=Ge}if(ce)return;const{customers:pt,jobs:$e,invoices:st,historicalSales:Nt,inventoryStock:be,inventoryProducts:jt,branches:bt}=Ge,tn=new Map(Object.entries(pt).map(([xe,tt])=>[xe,tt.name||"Customer"])),B=[];Object.entries($e).forEach(([xe,tt])=>{if(q!=="all"&&tt.branchId!==q)return;const ht=tn.get(tt.customerId)||"";[tt.jobNumber,ht,tt.serialNumber,tt.imei,tt.brand,tt.model,tt.deviceCategory,tt.problem,tt.invoiceNumber].filter(Boolean).join(" ").toLowerCase().includes(Te)&&B.push({key:`job-${xe}`,kind:"Job",title:tt.jobNumber||"Service Job",subtitle:[ht,tt.brand,tt.model,tt.serialNumber].filter(Boolean).join(" ⢠"),page:"serviceJobs",jobId:xe})}),Object.entries(pt).forEach(([xe,tt])=>{if(q!=="all"&&tt.branchId!==q)return;[tt.name,tt.phone,tt.whatsapp,tt.email].filter(Boolean).join(" ").toLowerCase().includes(Te)&&B.push({key:`customer-${xe}`,kind:"Customer",title:tt.name||"Customer",subtitle:[tt.phone,tt.email].filter(Boolean).join(" ⢠"),page:"customers",customerId:xe})}),Object.entries(st).forEach(([xe,tt])=>{const ht=String(tt.branchId||"");if(q!=="all"&&ht&&ht!==q)return;if(Object.values(tt).filter(we=>["string","number"].includes(typeof we)).join(" ").toLowerCase().includes(Te)){const we=String(tt.invoiceNumber||tt.number||tt.documentNumber||xe);B.push({key:`invoice-${xe}`,kind:"Invoice",title:we,subtitle:[tt.customerName,tt.customerPhone].filter(Boolean).map(String).join(" ⢠")||"Invoice",page:"invoices"})}}),Object.entries(be).forEach(([xe,tt])=>{q!=="all"&&xe!==q||Object.entries(tt||{}).forEach(([ht,dt])=>{const we=jt[ht]||{},rt=bt[xe]||{},St=new Set((Array.isArray(dt.postCutoverSoldSerials)?dt.postCutoverSoldSerials:[]).map(String).map(An=>An.toLowerCase())),Qt=[Array.isArray(dt.postCutoverPurchaseSerials)?dt.postCutoverPurchaseSerials:[],Array.isArray(dt.manualReconciledSerials)?dt.manualReconciledSerials:[],Array.isArray(dt.reliableCurrentReferenceSerials)?dt.reliableCurrentReferenceSerials:[]];[...new Set(Qt.flat().map(String).filter(Boolean))].forEach(An=>{if(!An.toLowerCase().includes(Te))return;const Sn=St.has(An.toLowerCase())?"SOLD":"IN STOCK";B.push({key:`stock-serial-${xe}-${ht}-${An}`,kind:"Serial",title:An,subtitle:[we.name||we.model||ht,Sn,dt.lastLivePurchaseNo||dt.lastHistoricalPurchaseNo,rt.name||xe].filter(Boolean).map(String).join(" ⢠"),page:"stockReport",traceSerial:An})})})}),Object.entries(Nt).forEach(([xe,tt])=>{const ht=String(tt.branchId||"");if(q!=="all"&&ht&&ht!==q)return;(Array.isArray(tt.items)?tt.items:[]).forEach((we,rt)=>{(Array.isArray(we.serials)?we.serials.map(String):[]).forEach(Qt=>{Qt.toLowerCase().includes(Te)&&B.push({key:`sold-serial-${xe}-${rt}-${Qt}`,kind:"Serial",title:Qt,subtitle:[we.product,"SOLD",tt.sourceInvoiceNo,tt.customer,tt.saleDate,tt.salespersonName,tt.branchName].filter(
4155Boolean).map(String).join(" ⢠"),page:"stockReport",traceSerial:Qt})})})}),c(B.slice(0,10))}catch(te){console.error("Global search failed:",te),ce||c([])}finally{ce||m(!1)}},220);return()=>{ce=!0,window.clearTimeout(Ye)}},[a,t.companyId,q]),x.useEffect(()=>{f.current=null,c([]),s("")},[t.companyId]),x.useMemo(()=>p==="company"?"Company Settings":p==="branches"?"Branch Settings":p==="customers"?"CRM â Customers":p==="crmWorkspace"?"CRM â Workspace":p==="crmWebsiteConnectors"?"CRM â Website Connectors":p==="chequeManagement"?"Accounts & Finance â Cheque Management":p==="serviceJobs"?"Work Orders":p==="estimates"?"Quotations & Estimates":p==="invoices"?"Sales â Invoices":p==="newSale"?"Sales â New Sale":p==="newPurchase"?"Purchase â New Purchase":p==="productBrand"?"Administration â Product â Brand":p==="productGroup"?"Administration â Product â Group":p==="productCategory"?"Administration â Product â Category":p==="productMaster"?"Administration â Product â Product":p==="collections"?"Finance â Collections":p==="supplierPayment"?"Accounts & Finance â Supplier Payment":p==="supplierMaster"?"Master â Supplier Master & Ledger":p==="salaryPayable"?"Accounts & Finance â Salary Payable":p==="salesDatewiseReport"?"Reports â Sales â Datewise Sales":p==="purchaseDatewiseReport"?"Reports â Purchase â Datewise Purchase":p==="financeReports"?"Accounts & Finance â Reports":p==="financeCollectionReport"?"Accounts & Finance â Collection Report":p==="dayBookReport"?"Reports â Day Book":p==="financeDueReport"?"Accounts & Finance â Due Report":p==="financeSupplierPayableReport"?"Accounts & Finance â Supplier Payable Report":p==="chartOfAccounts"?"Accounts & Finance â Accounting Foundation":p==="openingBalances"?"Accounts & Finance â Opening Balances":p==="bankSetup"?"Setup â Bank & Cash":p==="accountingVouchers"?"Accounts & Finance â Vouchers & Journal":p==="trialBalance"?"Accounts & Finance â Trial Balance":p==="generalLedger"?"Accounts & Finance â General Ledger":p==="employees"?"HR â Employees":p==="attendance"?"HR â Attendance Dashboard":p==="attendanceDaily"?"HR â Daily Attendance":p==="attendanceMonthly"?"HR â Monthly Attendance":p==="attendanceLeave"?"HR â Leave":p==="attendanceShifts"?"HR â Shifts":p==="attendanceHolidays"?"HR â Holidays":p==="attendanceLunch"?"HR â Lunch Policy":p==="attendanceMovement"?"HR â Outside Movement":p==="attendanceDevices"?"HR â Device Manager":p==="attendanceFaceEnrollment"?"HR â Face Enrollment":p==="attendanceReports"?"Reports â Attendance":p==="payroll"?"HR â Payroll":p==="advanceLoanRequests"?"HR â Advance & Loan Requests":p==="appraisal"?"HR â Employee Appraisal":p==="reportingHierarchy"?"HR â Reporting Hierarchy":p==="employeeLifecycle"?"HR â Employee Lifecycle":p==="employeeRelations"?"HR â Grievance & Disciplinary":p==="hrLetters"?"HR â HR Letters":p==="gratuity"?"HR â Gratuity":p==="recruitment"?"HR â Recruitment & Applicant Tracking":p==="performanceService"?"Performance â Service":p==="performanceSales"?"Performance â Sales":p==="performanceLeaderboard"?"Performance â Leaderboard":p==="organizationSetup"?"System â Organization Setup":p==="userPermissions"?"System â User & Role Permissions":p==="dataMigration"?"Data Migration Center":p==="promotions"?"Supplier Promotion Center":p==="profitLoss"?"Reports â Income Statement":p==="balanceSheet"?"Reports â Balance Sheet":p==="stockReport"?"Reports â Stock Report":p==="reports"?"Reports & Analytics":p==="rma"?"RMA & Warranty":p==="companyMaster"?"Super Admin â Company Master":p==="versionHistory"?"System â Version & What's New":p==="deliveryScan"?"Operations â Delivery Scan":"Dashboard",[p]);const pe={customers:"crm",serviceJobs:"service",estimates:"service",deliveryScan:"service",invoices:"finance",newSale:"finance",newPurchase:"finance",productBrand:"finance",productGroup:"finance",productCategory:"finance",productMaster:"finance",collections:"finance",supplierPayment:"finance",supplierMaster:"finance",chequeManagement:"finance",crmWorksp
4155ace:"crm",crmWebsiteConnectors:"crm",salaryPayable:"finance",salesDatewiseReport:"reports",purchaseDatewiseReport:"reports",financeReports:"finance",dayBookReport:"finance",financeCollectionReport:"finance",financeDueReport:"finance",financeSupplierPayableReport:"finance",chartOfAccounts:"finance",openingBalances:"finance",bankSetup:"finance",dataMigration:"finance",promotions:"finance",accountingVouchers:"finance",trialBalance:"finance",generalLedger:"finance",profitLoss:"finance",balanceSheet:"finance",stockReport:"finance",employees:"hr",technicians:"hr",attendance:"attendance",attendanceDaily:"attendance",attendanceMonthly:"attendance",attendanceLeave:"attendance",attendanceShifts:"attendance",attendanceHolidays:"attendance",attendanceLunch:"attendance",attendanceMovement:"attendance",attendanceDevices:"attendance",attendanceFaceEnrollment:"attendance",attendanceReports:"attendance",payroll:"payroll",advanceLoanRequests:"payroll",appraisal:"hr",reportingHierarchy:"hr",employeeLifecycle:"hr",employeeRelations:"hr",hrLetters:"hr",gratuity:"hr",recruitment:"hr",performanceService:"performance",performanceSales:"performance",performanceLeaderboard:"performance",reports:"reports",rma:"rma"},Se=Te=>Te==="payroll"||eU(_==null?void 0:_.features,Te),Me=Te=>{const ce=pe[Te];return!ce||Se(ce)},ot={company:"company.manage",branches:"branch.manage",customers:"customer.read",serviceJobs:"job.read",estimates:"estimate.read",invoices:"finance.read",newSale:"finance.manage",newPurchase:"purchase.manage",productBrand:"purchase.read",productGroup:"purchase.read",productCategory:"purchase.read",productMaster:"purchase.read",collections:"finance.read",supplierPayment:"finance.manage",supplierMaster:"purchase.read",chequeManagement:"finance.read",crmWorkspace:"customer.read",crmWebsiteConnectors:"crmConnector.read",salaryPayable:"finance.read",salesDatewiseReport:"performance.read",purchaseDatewiseReport:"performance.read",financeReports:"finance.read",dayBookReport:"finance.read",financeCollectionReport:"finance.read",financeDueReport:"finance.read",financeSupplierPayableReport:"finance.read",chartOfAccounts:"finance.read",openingBalances:"finance.manage",bankSetup:"finance.read",dataMigration:"dataMigration.manage",promotions:"promotion.read",accountingVouchers:"finance.read",trialBalance:"finance.read",generalLedger:"finance.read",profitLoss:"finance.read",balanceSheet:"finance.read",stockReport:"finance.manage",employees:"employee.read",technicians:"employee.read",attendance:"attendance.read",attendanceDaily:"attendance.read",attendanceMonthly:"attendance.read",attendanceLeave:"attendance.read",attendanceShifts:"attendance.manage",attendanceHolidays:"attendance.manage",attendanceLunch:"attendance.manage",attendanceMovement:"attendance.manage",attendanceDevices:"attendance.device.manage",attendanceFaceEnrollment:"attendance.device.manage",attendanceReports:"attendance.read",payroll:"payroll.read",appraisal:"appraisal.view",reportingHierarchy:"employee.read",employeeLifecycle:"employee.read",employeeRelations:"employee.manage",hrLetters:"employee.read",gratuity:"employee.read",recruitment:"employee.read",performanceService:"performance.read",performanceSales:"performance.read",performanceLeaderboard:"performance.read",organizationSetup:"settings.manage",deliveryScan:"delivery.manage",userPermissions:"user.manage",reports:"performance.read",rma:"job.read",companyMaster:"company.manage"},wt=Te=>{if(Te==="companyMaster")return t.role==="super_admin";if(Te==="attendanceLeave"&&t.employeeId&&Se("attendance")||Te==="advanceLoanRequests"&&t.employeeId&&Se("payroll"))return!0;if(t.role==="service_incharge"&&["performanceSales","performanceLeaderboard"].includes(Te))return!1;const ce=ot[Te];return!ce||sa(t,ce)},ct=(Te,ce)=>{if(!Me(Te)){N(null),C(Te),I(!1);return}if(!wt(Te)){C(null),N(Te),I(!1);return}C(null),N(null),y(Te),Pe(ce==null?void 0:ce.jobId),Ee(Te==="customers"?ce==null?void 0:ce.customerId:void 0);const Ye=new URL(window.location.href);Te==="dashboard"?Ye.searchParams.delete("page"):Ye.searchParams.set("page",Te),ce!=null&&ce.jobId?Ye.searchParams.set("job",ce.jobId):Ye.searchParams.delete("job"),ce!=null&&ce.replace?window.history.replaceState({page:Te,jobId:ce==null?void 0:ce.jobId},"",Ye):window.history.pushState({page:Te,jobId:ce==null?void 0:ce.jobId},"",Ye),I(!1)};return x.useEffect(()=>{const Te=()=>{const ce=s5();if(!Me(ce.page)||!wt(ce.page)){y("dashboard"),Pe(void 0);return}C(null),N(null),y(ce.page),Pe(ce.jobId),I(!1)};return window.addEventListener("popstate",Te),()=>window.removeEventListener("popstate",Te)},[_==null?void 0:_.features,t.role]),x.useEffect(()=>{_&&(Me(p)||(N(null),C(p)))},[_==null?void 0:_.features,p]),!(t.role!=="super_admin"&&(_!=null&&_.subscriptionExpiry)&&new Date().toISOString().slice(0,10)>String(_.subscriptionExpiry))?e.jsxs("div",{className:"app-shell",children:[me&&e.jsx(GE,{profile:t,onComplete:()=>ge(!1),onCancel:()=>ge(!1)}),e.jsxs("aside",{className:`sidebar ${R?"open":""}`,children:[e.jsxs("div",{className:"sidebar-head",children:[e.jsxs("div",{className:"brand-lockup sidebar-brand",children:[e.jsx("img",{className:"verixo-brand-icon",src:"/verixo-icon.svg",alt:"VERIXO"}),e.jsxs("div",{className:"sidebar-brand-copy",children:[e.jsx("strong",{children:"VERIXO"}),e.jsx("span",{children:"Run Everything. From One Platform."})]})]}),e.jsxs("div",{className:"sidebar-context-card",children:[e.jsxs("div",{className:"sidebar-context-topline",children:[e.jsx("span",{children:"Current Worksp
4155ace"}),e.jsx(Fu,{size:14})]}),e.jsx("strong",{className:"sidebar-company-name",children:(_==null?void 0:_.name)||"Company"}),t.role==="super_admin"&&z.length>0&&e.jsxs("button",{type:"button",className:"sidebar-workspace-switch-button",onClick:()=>L(!0),title:"Switch company workspace",children:[e.jsx("span",{children:"Switch workspace"}),e.jsx("span",{className:"sidebar-workspace-switch-icon",children:"â"})]}),e.jsxs("div",{className:"sidebar-branch-row",children:[e.jsx("span",{className:"sidebar-branch-label",children:"Branch"}),e.jsxs("div",{className:"sidebar-branch-picker",children:[e.jsxs("button",{type:"button",className:`sidebar-branch-trigger ${D?"open":""}`,onClick:()=>{!Z&&fe.length<=1||M(Te=>!Te)},disabled:!Z&&fe.length<=1,"aria-label":"Current branch","aria-expanded":D,children:[e.jsx("span",{children:q==="all"?"All Branches":((De=T.find(Te=>Te.id===q))==null?void 0:De.name)||"Select Branch"}),e.jsx(Yw,{size:13})]}),D&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"sidebar-branch-dismiss","aria-label":"Close branch selector",onClick:()=>M(!1)}),e.jsxs("div",{className:"sidebar-branch-menu",children:[Z&&e.jsxs("button",{type:"button",className:`sidebar-branch-option ${q==="all"?"selected":""}`,onClick:()=>{ne("all"),M(!1)},children:[e.jsx("span",{className:"sidebar-branch-option-icon",children:"â"}),e.jsx("span",{children:"All Branches"}),q==="all"&&e.jsx("span",{className:"branch-check",children:"â"})]}),T.filter(Te=>Z||fe.includes(Te.id)).map(Te=>e.jsxs("button",{type:"button",className:`sidebar-branch-option ${q===Te.id?"selected":""}`,onClick:()=>{ne(Te.id),M(!1)},children:[e.jsx("span",{className:"sidebar-branch-option-icon",children:"â¥"}),e.jsx("span",{children:Te.name}),q===Te.id&&e.jsx("span",{className:"branch-check",children:"â"})]},Te.id))]})]})]})]})]})]}),e.jsxs("nav",{className:"erp-sidebar-nav",children:[e.jsxs("button",{className:`sidebar-direct-link ${p==="dashboard"?"active":""}`,onClick:()=>
4155ct("dashboard"),children:[e.jsx(x1,{size:19}),"Dashboard"]}),Se("service")&&sa(t,"job.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("operations"),children:[e.jsxs("span",{children:[e.jsx(Go,{size:18})," Service Operations"]}),e.jsx(Ei,{className:Be.operations?"rotated":"",size:17})]}),Be.operations&&e.jsxs("div",{className:"sidebar-group-items",children:[e.jsxs("button",{className:p==="serviceJobs"?"active":"",onClick:()=>ct("serviceJobs"),children:[e.jsx(Go,{size:17})," Service Jobs"]}),sa(t,"estimate.read")&&e.jsxs("button",{className:p==="estimates"?"active":"",onClick:()=>ct("estimates"),children:[e.jsx(Zs,{size:17})," Estimates & Approval"]}),sa(t,"delivery.manage")&&e.jsxs("button",{className:p==="deliveryScan"?"active":"",onClick:()=>ct("deliveryScan"),children:[e.jsx(Xw,{size:17})," Delivery Scan"]})]})]}),Se("rma")&&sa(t,"job.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("rma"),children:[e.jsxs("span",{children:[e.jsx(yu,{size:18})," RMA & Warranty"]}),e.jsx(Ei,{className:Be.rma?"rotated":"",size:17})]}),Be.rma&&e.jsx("div",{className:"sidebar-group-items",children:e.jsxs("button",{className:p==="rma"?"active":"",onClick:()=>ct("rma"),children:[e.jsx(yu,{size:17})," RMA Management"]})})]}),Se("crm")&&sa(t,"customer.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("crm"),children:[e.jsxs("span",{children:[e.jsx(B4,{size:18})," CRM"]}),e.jsx(Ei,{className:Be.crm?"rotated":"",size:17})]}),Be.crm&&e.jsxs("div",{className:"sidebar-group-items",children:[e.jsxs("button",{className:p==="customers"?"active":"",onClick:()=>ct("customers"),children:[e.jsx(mc,{size:17})," Customers"]}
4155),e.jsxs("button",{className:p==="crmWorkspace"?"active":"",onClick:()=>ct("crmWorkspace"),children:[e.jsx(Mc,{size:17})," CRM Workspace"]}),sa(t,"crmConnector.read")&&e.jsxs("button",{className:p==="crmWebsiteConnectors"?"active":"",onClick:()=>ct("crmWebsiteConnectors"),children:[e.jsx(Pb,{size:17})," Website Connectors"]}),["owner","super_admin","admin","branch_manager","service_incharge"].includes(t.role)&&e.jsxs("button",{type:"button",onClick:()=>{var Ye;const Te=((Ye=_==null?void 0:_.slug)==null?void 0:Ye.trim().toLowerCase())||Fb((_==null?void 0:_.name)||(_==null?void 0:_.companyCode)||t.companyId)||t.companyId.toLowerCase(),ce=ux.publicAppUrl.replace(/\/$/,"");window.open(`${ce}/portal/${encodeURIComponent(Te)}`,"_blank","noopener,noreferrer")},children:[e.jsx(ID,{size:17})," Customer Portal"]})]})]}),Se("finance")&&sa(t,"finance.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("sales"),children:[e.jsxs("span",{children:[e.jsx(Iu,{size:18})," Sales"]}),e.jsx(Ei,{className:Be.sales?"rotated":"",size:17})]}),Be.sales&&e.jsxs("div",{className:"sidebar-group-items",children:[e.jsxs("button",{className:p==="newSale"?"active":"",onClick:()=>ct("newSale"),children:[e.jsx(Iu,{size:17})," New Sale"]}),e.jsxs("button",{className:p==="invoices"?"active":"",onClick:()=>ct("invoices"),children:[e.jsx(Zs,{size:17})," Invoices"]})]})]}),Se("finance")&&sa(t,"purchase.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("purchase"),children:[e.jsxs("span",{children:[e.jsx(yu,{size:18})," Purchase"]}),e.jsx(Ei,{className:Be.purchase?"rotated":"",size:17})]}),Be.purchase&&e.jsxs("div",{className:"sidebar-group-items",children:[e.jsxs("button",{className:p==="newPurchase"?"active":"",onClick:()=>ct("newPurchase"),children:[e.jsx(yu,{size:17})," New Purchase"]}),e.jsxs("button",{className:p==="supplierMaster"?"active":"",onClick:()=>ct("supplierMaster"),children:[e.jsx(mc,{size:17})," Supplier Master"]}),e.jsxs("button",{className:p==="stockReport"?"active":"",onClick:()=>ct("stockReport"),children:[e.jsx(Tu,{size:17})," Stock Report"]})]})]}),Se("finance")&&sa(t,"finance.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("finance"),children:[e.jsxs("span",{children:[e.jsx(Nd,{size:18})," Accounts & Finance"]}),e.jsx(Ei,{className:Be.finance?"rotated":"",size:17})]}),Be.finance&&e.jsxs("div",{className:"sidebar-group-items",children:[e.jsxs("button",{className:p==="accountingVouchers"?"active":"",onClick:()=>ct("accountingVouchers"),children:[e.jsx(Zs,{size:17})," Vouchers & Journal"]}),e.jsxs("button",{className:p==="collections"?"active":"",onClick:()=>ct("collections"),children:[e.jsx(Ch,{size:17})," Collections"]}),e.jsxs("button",{className:p==="supplierPayment"?"active":"",onClick:()=>ct("supplierPayment"),children:[e.jsx(Ll,{size:17})," Supplier Payment"]}),e.jsxs("button",{className:p==="supplierMaster"?"active":"",onClick:()=>ct("supplierMaster"),children:[e.jsx(mc,{size:17})," Supplier Master"]}),e.jsxs("button",{className:p==="chequeManagement"?"active":"",onClick:()=>ct("chequeManagement"),children:[e.jsx(Nd,{size:17})," Cheque Management"]}),e.jsxs("button",{className:p==="salaryPayable"?"active":"",onClick:()=>ct("salaryPayable"),children:[e.jsx(Ll,{size:17})," Salary Payable"]})]})]}),Se("finance")&&(sa(t,"promotion.read")||sa(t,"promotion.manage"))&&e.jsxs("button",{className:`sidebar-direct-link sidebar-compact-direct ${p==="promotions"?"active":""}`,onClick:()=>ct("promotions"),children:[e.jsx(CD,{size:18})," Promotions"]}),Se("finance")&&sa(t,"dataMigration.manage")&&e.jsxs("button",{className:`sidebar-direct-link sidebar-compact-direct ${p==="dataMigration"?"active":""}`,onClick:()=>ct("dataMigration"),children:[e.jsx(Uf,{size:18})," Data Migration"]}),Se("performance")&&sa(t,"performance.read")&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("performance"),children:[e.jsxs("span",{children:[e.jsx(Mc,{size:18})," Performance & Growth"]}),e.jsx(Ei,{className:Be.performance?"rotated":"",size:17})]}),Be.performance&&e.jsxs("div",{className:"sidebar-group-items",children:[e.jsxs("button",{className:p==="performanceService"?"active":"",onClick:()=>ct("performanceService"),children:[e.jsx(Go,{size:17})," Service Performance"]}),t.role!=="service_incharge"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:p==="performanceSales"?"active":"",onClick:()=>ct("performanceSales"),children:[e.jsx(Iu,{size:17})," Sales Performance"]}),e.jsxs("button",{className:p==="performanceLeaderboard"?"active":"",onClick:()=>ct("performanceLeaderboard"),children:[e.jsx(Mc,{size:17})," Leaderboard"]})]})]})]}),Se("hr")&&(sa(t,"employee.read")||sa(t,"attendance.read")||sa(t,"payroll.read")||!!t.employeeId)&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("people"),children:[e.jsxs("span",{children:[e.jsx(Q0,{size:18})," HR & People"]}
4155),e.jsx(Ei,{className:Be.people?"rotated":"",size:17})]}),Be.people&&e.jsxs("div",{className:"sidebar-group-items",children:[sa(t,"employee.read")&&e.jsxs("button",{className:p==="employees"?"active":"",onClick:()=>ct("employees"),children:[e.jsx(Q0,{size:17})," Employees"]}),Se("attendance")&&!!t.employeeId&&!sa(t,"attendance.read")&&e.jsxs("button",{className:p==="attendanceLeave"?"active":"",onClick:()=>ct("attendanceLeave"),children:[e.jsx(nb,{size:17})," My Leave"]}),Se("attendance")&&sa(t,"attendance.read")&&e.jsxs("div",{className:"sidebar-nav-group sidebar-nested-group sidebar-section-group sidebar-attendance-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("attendance"),children:[e.jsxs("span",{children:[e.jsx(nb,{size:17})," Attendance"]}),e.jsx(Ei,{className:Be.attendance?"rotated":"",size:16})]}),Be.attendance&&e.jsxs("div",{className:"sidebar-group-items sidebar-nested-items",children:[e.jsx("button",{className:p==="attendance"?"active":"",onClick:()=>ct("attendance"),children:"Dashboard"}),e.jsx("button",{className:p==="attendanceDaily"?"active":"",onClick:()=>ct("attendanceDaily"),children:"Daily Attendance"}),e.jsx("button",{className:p==="attendanceMonthly"?"active":"",onClick:()=>ct("attendanceMonthly"),children:"Monthly Attendance"})]})]}),sa(t,"employee.read")&&e.jsxs("button",{className:p==="appraisal"?"active":"",onClick:()=>ct("appraisal"),children:[e.jsx(b1,{size:17})," Appraisal"]}),sa(t,"employee.read")&&e.jsxs("button",{className:p==="reportingHierarchy"?"active":"",onClick:()=>ct("reportingHierarchy"),children:[e.jsx(mc,{size:17})," Reporting Hierarchy"]}),sa(t,"employee.read")&&e.jsxs("button",{className:p==="employeeLifecycle"?"active":"",onClick:()=>ct("employeeLifecycle"),children:[e.jsx(ND,{size:17})," Employee Lifecycle"]}),sa(t,"employee.manage")&&e.jsxs("button",{className:p==="employeeRelations"?"active":"",onClick:()=>ct("employeeRelations"),children:[e.jsx(gs,{size:17})," Grievance & Disciplinary"]}),sa(t,"employee.read")&&e.jsxs("button",{className:p==="hrLetters"?"active":"",onClick:()=>ct("hrLetters"),children:[e.jsx(Zs,{size:17})," HR Letters"]}),sa(t,"employee.read")&&e.jsxs("button",{className:p==="gratuity"?"active":"",onClick:()=>ct("gratuity"),children:[e.jsx(Ll,{size:17})," Gratuity"]})," ",sa(t,"employee.read")&&e.jsxs("button",{className:p==="recruitment"?"active":"",onClick:()=>ct("recruitment"),children:[e.jsx(mc,{size:17})," Recruitment"]})]})]}),Se("payroll")&&!!t.employeeId&&e.jsx("div",{className:"sidebar-nav-group",children:e.jsx("button",{className:p==="advanceLoanRequests"?"sidebar-group-toggle active":"sidebar-group-toggle",onClick:()=>ct("advanceLoanRequests"),children:e.jsxs("span",{children:[e.jsx(Ll,{size:18})," Advance & Loan"]})})}),Se("payroll")&&sa(t,"payroll.read")&&e.jsx("div",{className:"sidebar-nav-group",children:e.jsx("button",{className:p==="payroll"?"sidebar-group-toggle active":"sidebar-group-toggle",onClick:()=>ct("payroll"),children:e.jsxs("span",{children:[e.jsx(Ll,{size:18})," Payroll"]})})}),(Se("reports")&&sa(t,"performance.read")||Se("attendance")&&sa(t,"attendance.read")||Se("finance")&&sa(t,"finance.read"))&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("reports"),children:[e.jsxs("span",{children:[e.jsx(xp,{size:18})," Reports"]}),e.jsx(Ei,{className:Be.reports?"rotated":"",size:17})]}),Be.reports&&e.jsxs("div",{className:"sidebar-group-items",children:[Se("reports")&&sa(t,"performance.read")&&e.jsxs("button",{className:p==="reports"?"active":"",onClick:()=>ct("reports"),children:[e.jsx(U4,{size:17})," Analytics & Reports"]}),Se("reports")&&sa(t,"performance.read")&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sidebar-nested-group sidebar-section-group",children:[e.jsxs("div",{className:"sidebar-nested-label",children:[e.jsx(Iu,{size:16})," Sales"]}),e.jsx("div",{className:"sidebar-nested-items",children:e.jsx("button",{className:p==="salesDatewiseReport"?"active":"",onClick:()=>ct("salesDatewiseReport"),children:"Datewise Sales"})})]}),e.jsxs("div",{className:"sidebar-nested-group sidebar-section-group",children:[e.jsxs("div",{className:"sidebar-nested-label",children:[e.jsx(yu,{size:16})," Purchase"]}),e.jsx("div",{className:"sidebar-nested-items",children:e.jsx("button",{className:p==="purchaseDatewiseReport"?"active":"",onClick:()=>ct("purchaseDatewiseReport"),children:"Datewise Purchase"})})]})]}),Se("attendance")&&e.jsxs("button",{className:p==="attendanceReports"?"active":"",onClick:()=>ct("attendanceReports"),children:[e.jsx(nb,{size:17}),"Attendance Reports"]}),Se("finance")&&sa(t,"finance.manage")&&e.jsxs("button",{className:p==="stockReport"?"active":"",onClick:()=>ct("stockReport"),children:[e.jsx(yu,{size:17})," Stock Report"]}),Se("finance")&&sa(t,"finance.read")&&e.jsxs("div",{className:"sidebar-nested-group sidebar-section-group sidebar-report-finance-group",children:[e.jsxs("div",{className:"sidebar-nested-label",children:[e.jsx(Nd,{size:16})," Accounts & Finance"]}),e.jsxs("div",{className:"sidebar-nested-items",children:[e.jsx("button",{className:p==="financeCollectionReport"||p==="financeReports"?"active":"",onClick:()=>ct("financeCollectionReport"),children:"Collection Report"}),e.jsx("button",{className:p==="financeDueReport"?"active":"",onClick:()=>ct("financeDueReport"),children:"Due Report"}),e.jsx("button",{className:p==="financeSupplierPayableReport"?"active":"",onClick:()=>ct("financeSupplierPayableReport"),children:"Supplier Payable"}),e.jsx("button",{className:p==="salaryPayable"?"active":"",onClick:()=>ct("salaryPayable"),children:"Salary Payable"}),e.jsx("button",{className:p==="dayBookReport"?"active":"",onClick:()=>ct("dayBookReport"),children:"Day Book"}),e.jsx("button",{className:p==="trialBalance"?"active":"",onClick:()=>ct("trialBalance"),children:"Trial Balance"}),e.jsx("button",{className:p==="generalLedger"?"active":"",onClick:()=>ct("generalLedger"),children:"General Ledger"}),e.jsx("button",{className:p==="profitLoss"?"active":"",onClick:()=>ct("profitLoss"),children:"Income Statement"}),e.jsx("button",{className:p==="balanceSheet"?"active":"",onClick:()=>ct("balanceSheet"),children:"Balance Sheet"})]})]})]})]}),(sa(t,"company.manage")||sa(t,"branch.manage")||sa(t,"settings.manage")||sa(t,"user.manage")||sa(t,"finance.read")||sa(t,"attendance.manage")||sa(t,"attendance.device.manage")||sa(t,"purchase.read"))&&e.jsxs("div",{className:"sidebar-nav-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("setup"),children:[e.jsxs("span",{children:[e.jsx(TD,{size:18})," Administration"]}),e.jsx(Ei,{className:Be.setup?"rotated":"",size:17})]}),Be.setup&&e.jsxs("div",{className:"sidebar-group-items",children:[Se("finance")&&sa(t,"finance.read")&&e.jsxs("div",{className:"sidebar-nav-group sidebar-nested-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("setupAccounts"),children:[e.jsxs("span",{children:[e.jsx(Nd,{size:17})," Accounts"]}),e.jsx(Ei,{className:Be.setupAccounts?"rotated":"",size:16})]}),Be.setupAccounts&&e.jsxs("div",{className:"sidebar-group-items sidebar-nested-items",children:[e.jsx("button",{className:p==="chartOfAccounts"?"active":"",onClick:()=>ct("chartOfAccounts"),children:"Chart of Accounts"}),sa(t,"finance.manage")&&e.jsx("button",{className:p==="openingBalances"?"active":"",onClick:()=>ct("openingBalances"),children:"Opening Balances"}),e.jsx("button",{className:p==="bankSetup"?"active":"",onClick:()=>ct("bankSetup"),children:"Bank & Cash"})]})]}),(sa(t,"company.manage")||sa(t,"branch.manage")||sa(t,"settings.manage"))&&e.jsxs("div",{className:"sidebar-nav-group sidebar-nested-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("setupOrganization"),children:[e.jsxs("span",{children:[e.jsx(Fu,{size:17})," Organization"]}),e.jsx(Ei,{className:Be.setupOrganization?"rotated":"",size:16})]}),Be.setupOrganization&&e.jsxs("div",{className:"sidebar-group-items sidebar-nested-items",children:[t.role==="super_admin"&&e.jsx("button",{className:p==="companyMaster"?"active":"",onClick:()=>ct("companyMaster"),children:"Company Master"}),sa(t,"company.manage")&&e.jsx("button",{className:p==="company"?"active":"",onClick:()=>ct("company"),children:"Company"}),sa(t,"branch.manage")&&e.jsx("button",{className:p==="branches"?"active":"",onClick:()=>ct("branches"),children:"Branch & Location"}),sa(t,"settings.manage")&&e.jsx("button",{className:p==="organizationSetup"?"active":"",onClick:()=>ct("organizationSetup"),children:"Department & Designation"})]})]}),Se("finance")&&sa(t,"purchase.read")&&e.jsxs("div",{className:"sidebar-nav-group sidebar-nested-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("setupProduct"),children:[e.jsxs("span",{children:[e.jsx(Tu,{size:17})," Product"]}),e.jsx(Ei,{className:Be.setupProduct?"rotated":"",size:16})]}),Be.setupProduct&&e.jsxs("div",{className:"sidebar-group-items sidebar-nested-items",children:[e.jsx("button",{className:p==="productBrand"?"active":"",onClick:()=>ct("productBrand"),children:"Brand"}),e.jsx("button",{className:p==="productGroup"?"active":"",onClick:()=>ct("productGroup"),children:"Group"}),e.jsx("button",{className:p==="productCategory"?"active":"",onClick:()=>ct("productCategory"),children:"Category"}),e.jsx("button",{className:p==="productMaster"?"active":"",onClick:()=>ct("productMaster"),children:"Product"})]})]}),Se("finance")&&sa(t,"purchase.read")&&e.jsxs("button",{className:p==="supplierMaster"?"active":"",onClick:()=>ct("supplierMaster"),children:[e.jsx(mc,{size:17})," Supplier"]}),Se("attendance")&&(sa(t,"attendance.manage")||sa(t,"attendance.device.manage"))&&e.jsxs("div",{className:"sidebar-nav-group sidebar-nested-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("setupHr"),children:[e.jsxs("span",{children:[e.jsx(Q0,{size:17})," Employee & Attendance"]}),e.jsx(Ei,{className:Be.setupHr?"rotated":"",size:16})]}),Be.setupHr&&e.jsxs("div",{className:"sidebar-group-items sidebar-nested-items",children:[sa(t,"attendance.manage")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:p==="attendanceLeave"?"active":"",onClick:()=>ct("attendanceLeave"),children:"Leave"}),e.jsx("button",{className:p==="attendanceShifts"?"active":"",onClick:()=>ct("attendanceShifts"),children:"Shifts"}),e.jsx("button",{className:p==="attendanceHolidays"?"active":"",onClick:()=>ct("attendanceHolidays"),children:"Holidays"}),e.jsx("button",{className:p==="attendanceLunch"?"active":"",onClick:()=>ct("attendanceLunch"),children:"Lunch Policy"}),e.jsx("button",{className:p==="attendanceMovement"?"active":"",onClick:()=>ct("attendanceMovement"),children:"Outside Movement Policy"})]}),sa(t,"attendance.device.manage")&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:p==="attendanceDevices"?"active":"",onClick:()=>ct("attendanceDevices"),children:"Attendance Devices"}),e.jsx("button",{className:p==="attendanceFaceEnrollment"?"active":"",onClick:()=>ct("attendanceFaceEnrollment"),children:"Face Enrollment"})]})]})]}),(sa(t,"user.manage")||t.role==="super_admin")&&e.jsxs("div",{className:"sidebar-nav-group sidebar-nested-group",children:[e.jsxs("button",{className:"sidebar-group-toggle",onClick:()=>qe("setupAdmin"),children:[e.jsxs("span",{children:[e.jsx(Gh,{size:17})," Access & Admin"]}),e.jsx(Ei,{className:Be.setupAdmin?"rotated":"",size:16})]}),Be.setupAdmin&&e.jsxs("div",{className:"sidebar-group-items sidebar-nested-items",children:[sa(t,"user.manage")&&e.jsx("button",{className:p==="userPermissions"?"active":"",onClick:()=>ct("userPermissions"),children:"User & Role Permissions"}),e.jsx("button",{className:p==="versionHistory"?"active":"",onClick:()=>ct("versionHistory"),children:"Version & What's New"})]})]})]})]})]}),e.jsxs("div",{className:"sidebar-footer sidebar-footer-compact",children:[e.jsxs("div",{className:"sidebar-footer-actions",children:[e.jsxs("button",{title:"Change password",onClick:()=>ge(!0),children:[e.jsx(Gh,{size:15}),e.jsx("span",{children:"Password"})]}),e.jsxs("a",{className:"sidebar-app-download",href:p2[0],onClick:Te=>{Te.preventDefault(),WE()},title:"Download Android App","aria-label":"Download VERIXO Android App APK",children:[e.jsx(Mi,{size:15}),e.jsx("span",{children:"Android App"})]}),e.jsxs("button",{title:"Sign out",onClick:()=>dl(Ti),children:[e.jsx(aA,{size:15}),e.jsx("span",{children:"Sign out"})]})]}),e.jsx("div",{className:"sidebar-product-footer",children:e.jsx("button",{type:"button",className:"sidebar-version-link",onClick:()=>ct("versionHistory"),title:"View version history and release changes",children:e.jsxs("strong",{children:["VERIXO ERP v",Dd]})})})]})]}),t.role==="super_admin"&&K&&e.jsx("div",{className:"workspace-picker-backdrop",onMouseDown:()=>L(!1),children:e.jsxs("section",{className:"workspace-picker-modal",onMouseDown:Te=>Te.stopPropagation(),children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"VERIXO SUPER ADMIN"}),e.jsx("h2",{children:"Switch Workspace"}),e.jsx("small",{children:"Select the company you want to manage."})]}),e.jsx("button",{type:"button",className:"workspace-picker-close",onClick:()=>L(!1),children:"Ã"})]}),e.jsx("div",{className:"workspace-picker-list",children:z.map(Te=>{const ce=Te.id===t.companyId,Ye=ce&&(_!=null&&_.name)?_.name:Te.name;return e.jsxs("button",{type:"button",className:`workspace-picker-item ${ce?"current":""}`,onClick:()=>
4155{if(ce){L(!1);return}se(Te.id)},children:[e.jsx("span",{className:"workspace-picker-avatar",children:Ye.slice(0,1).toUpperCase()}),e.jsxs("span",{className:"workspace-picker-copy",children:[e.jsx("strong",{children:Ye}),e.jsx("small",{children:Te.slug})]}),ce?e.jsx("span",{className:"workspace-current-badge",children:"Current"}):e.jsx("span",{className:"workspace-open-arrow",children:"âº"})]},Te.id)})})]})}),e.jsxs("main",{className:"workspace",children:[e.jsxs("header",{className:"topbar",children:[e.jsx("button",{className:"menu-button desktop-menu-button",onClick:()=>I(!R),"aria-label":"Toggle navigation",children:e.jsx(V4,{size:20})}),e.jsxs("div",{className:"search global-search",children:[e.jsx(xr,{size:18}),e.jsx("input",{value:a,onChange:Te=>{s(Te.target.value),u(!0)},onFocus:()=>u(!0),onKeyDown:Te=>{if(Te.key==="Escape"&&(u(!1),Te.currentTarget.blur()),Te.key==="Enter"&&i[0]){const ce=i[0];ct(ce.page,ce.jobId?{jobId:ce.jobId}:ce.customerId?{customerId:ce.customerId}:void 0),s(""),u(!1)}},placeholder:"Search customer, mobile, job, invoice, serial...","aria-label":"Global search"}),a&&e.jsx("button",{type:"button",className:"global-search-clear","aria-label":"Clear search",onClick:()=>{s(""),c([])},children:"Ã"}),e.jsx("kbd",{children:"Ctrl K"}),d&&a.trim().length>=2&&e.jsx("div",{className:"global-search-results",children:l?e.jsx("div",{className:"global-search-state",children:"Searchingâ¦"}):i.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"global-search-results-head",children:[e.jsx("span",{children:"Search results"}),e.jsxs("small",{children:[i.length," found"]})]}),i.map(Te=>e.jsxs("button",{type:"button",className:"global-search-result",onMouseDown:ce=>ce.preventDefault(),onClick:()=>{ct(Te.page,Te.jobId?{jobId:Te.jobId}:Te.customerId?{customerId:Te.customerId}:void 0),Te.traceSerial&&sessionStorage.setItem("verixoStockTraceSerial",Te.traceSerial),s(""),u(!1)},children:[e.jsx("span",{className:"global-search-result-type",children:Te.kind}),e.jsxs("span",{className:"global-search-result-copy",children:[e.jsx("strong",{children:Te.title}),e.jsx("small",{children:Te.subtitle||"Open record"})]}),e.jsx(Ei,{size:15})]},Te.key))]}):e.jsx("div",{className:"global-search-state",children:"No matching customer, job, invoice or serial found."})})]}),e.jsx(U7,{profile:t,currentPage:p}),e.jsx("button",{className:"icon-button",onClick:()=>Y(ae==="light"?"dark":"light"),children:ae==="light"?e.jsx(H4,{size:18}):e.jsx(Q4,{size:18})}),e.jsxs("button",{className:"icon-button notification-button",onClick:()=>V(!0),title:_e?`${_e} unread notification(s)`:"Notifications",children:[e.jsx($4,{size:19}),_e>0&&e.jsx("span",{})]}),e.jsxs("div",{className:"user-chip",children:[e.jsx("div",{className:"avatar",children:t.name.charAt(0).toUpperCase()}),e.jsxs("div",{children:[e.jsx("strong",{children:t.name}),e.jsx("span",{children:jh[t.role]}),e.jsx("small",{children:(_==null?void 0:_.name)||"Company"})]})]})]}),e.jsxs("section",{className:"content",children:[w&&e.jsx("section",{className:"access-denied-page feature-not-activated-page",children:e.jsxs("div",{className:"access-denied-card",children:[e.jsx(Tu,{size:36}),e.jsx("p",{className:"eyebrow",children:"Company Feature"}),e.jsx("h1",{children:"Feature Not Activated"}),e.jsxs("p",{children:[e.jsx("strong",{children:Vo[pe[w]||"service"].name})," ","module à¦à¦ company-à¦à¦° à¦à¦¨à§à¦¯ active à¦à¦°à¦¾ নà§à¦à¥¤ Super Admin থà§à¦à§ Company Master â Modules à¦à¦¿à§à§ moduleà¦à¦¿ enable à¦à¦°à§à¦¨à¥¤"]}),e.jsx("button",{className:"vx-button vx-button-primary",onClick:()=>{C(null),y("dashboard")},children:"Back to Dashboard"})]})}),!w&&b&&e.jsx("section",{className:"access-denied-page",children:e.jsxs("div",{className:"access-denied-card",children:[e.jsx(gs,{size:34}),e.jsx("p",{className:"eyebrow",children:"Restricted Access"}),e.jsx("h1",{children:"Access Denied"}),e.jsx("p",{children:"à¦à¦ªà¦¨à¦¾à¦° বরà§à¦¤à¦®à¦¾à¦¨ role à¦à¦ module access à¦à¦°à¦¾à¦° permission দà§à§ না।"}),e.jsx("button",{className:"vx-button vx-button-primary",onClick:()=>{N(null),y("dashboard")},children:"Back to Dashboard"})]})}),!w&&!b&&p==="dashboard"&&e.jsx(GU,{companyId:t.companyId,companyName:(_==null?void 0:_.name)||"Company",profile:t,selectedBranchId:q,branches:T,onNavigate:ct}),!w&&!b&&p==="companyMaster"&&e.jsx(aU,{profile:t}),!w&&!b&&p==="versionHistory"&&e.jsx(KU,{}),!w&&!b&&p==="company"&&e.jsx(XU,{profile:t,company:_,onSaved:J}),!w&&!b&&p==="branches"&&e.jsx(ZU,{profile:t}),!w&&!b&&p==="customers"&&e.jsx(YU,{profile:t,branches:T,selectedBranchId:q,initialCustomerId:Re,onInitialCustomerHandled:()=>Ee(void 0)}),!w&&!b&&p==="attendanceReports"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"reports"}),!w&&!b&&p==="attendance"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"dashboard",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceDaily"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"daily",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceMonthly"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"monthly",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceLeave"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"leave",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceShifts"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"shifts",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceHolidays"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"holidays",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceLunch"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"lunch",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceMovement"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"movement",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceDevices"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"devices",hidePrimaryTabs:!0}),!w&&!b&&p==="attendanceFaceEnrollment"&&e.jsx(rl,{profile:t,branches:T,selectedBranchId:q,initialTab:"face_enrollment",hidePrimaryTabs:!0}),!w&&!b&&p==="employees"&&e.jsx(H7,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="appraisal"&&e.jsx(_U,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="reportingHierarchy"&&e.jsx(kU,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="employeeLifecycle"&&e.jsx(EU,{profile:t,branches:T,selectedBranchId:q,onOpenEmployee:Te=>{window.sessionStorage.setItem("verixo.openEmployeeId",Te),ct("employees")}}),!w&&!b&&p==="employeeRelations"&&e.jsx(RU,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="hrLetters"&&e.jsx($U,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="gratuity"&&e.jsx(BU,{profile:t,branches:T,selectedBranchId:q})," ",!w&&!b&&p==="recruitment"&&e.jsx(FU,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="advanceLoanRequests"&&e.jsx(NU,{profile:t,branches:T}),!w&&!b&&p==="payroll"&&e.jsx(wU,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="performanceService"&&e.jsx(Ej,{view:"service",profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="performanceSales"&&e.jsx(Ej,{view:"sales",profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="performanceLeaderboard"&&e.jsx(Ej,{view:"leaderboard",profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="organizationSetup"&&e.jsx(W7,{profile:t}),!w&&!b&&p==="userPermissions"&&e.jsx(Z7,{profile:t,branches:T}),!w&&!b&&p==="rma"&&e.jsx(gU,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="reports"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,onOpenServiceJob:Te=>{ct("serviceJobs",{jobId:Te})},companyName:(_==null?void 0:_.name)||"Service Center",companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address}
4155),!w&&!b&&p==="salesDatewiseReport"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,initialBusinessTab:"sales",dedicatedDatewise:!0,companyName:(_==null?void 0:_.name)||"Service Center",companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address}),!w&&!b&&p==="purchaseDatewiseReport"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,initialBusinessTab:"purchase",dedicatedDatewise:!0,companyName:(_==null?void 0:_.name)||"VERIXO",companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address}),!w&&!b&&p==="deliveryScan"&&e.jsx(IB,{profile:t}),!w&&!b&&p==="serviceJobs"&&e.jsx(QU,{profile:t,branches:T,selectedBranchId:q,companyId:t.companyId,company:_,companyName:(_==null?void 0:_.name)||"Service Center",companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address,companyLogoUrl:_==null?void 0:_.logoUrl,initialJobId:de,onInitialJobHandled:()=>Pe(void 0)}),!w&&!b&&p==="estimates"&&e.jsx(DB,{companyId:t.companyId,branches:T,selectedBranchId:q,companyName:(_==null?void 0:_.name)||"Service Center",companyCode:_==null?void 0:_.companyCode,documentPrefixes:_==null?void 0:_.documentPrefixes,companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address,actorUid:t.uid,actorName:t.name}),!w&&!b&&p==="newPurchase"&&e.jsx(k7,{profile:t,branches:T,selectedBranchId:q,onAddNewProduct:()=>ct("productMaster"),onAddNewSupplier:()=>ct("supplierMaster"),companyName:(_==null?void 0:_.name)||"VERIXO",companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address}),!w&&!b&&p==="newSale"&&e.jsx(E7,{profile:t,branches:T,selectedBranchId:q,companyName:(_==null?void 0:_.name)||"Service Center",companyCode:_==null?void 0:_.companyCode,documentPrefixes:_==null?void 0:_.documentPrefixes,companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address}),!w&&!b&&p==="invoices"&&e.jsx(_1,{view:"invoices",companyId:t.companyId,companyName:(_==null?void 0:_.name)||"Service Center",companyCode:_==null?void 0:_.companyCode,documentPrefixes:_==null?void 0:_.documentPrefixes,companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address,branches:T,selectedBranchId:q,actorUid:t.uid,actorName:t.name}),!w&&!b&&p==="chartOfAccounts"&&e.jsx(wI,{profile:t}),!w&&!b&&p==="openingBalances"&&e.jsx(wI,{profile:t,initialTab:"opening"}),!w&&!b&&p==="bankSetup"&&e.jsx(LB,{profile:t}),!w&&!b&&p==="dataMigration"&&e.jsx(iF,{profile:t,branches:T}),!w&&!b&&p==="promotions"&&e.jsx(m7,{profile:t}),!w&&!b&&p==="accountingVouchers"&&e.jsx(g7,{profile:t,branches:T,selectedBranchId:q,companyCode:_==null?void 0:_.companyCode}),!w&&!b&&p==="collections"&&e.jsx(_1,{view:"collections",companyId:t.companyId,companyName:(_==null?void 0:_.name)||"Service Center",companyCode:_==null?void 0:_.companyCode,documentPrefixes:_==null?void 0:_.documentPrefixes,companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address,branches:T,selectedBranchId:q,actorUid:t.uid,actorName:t.name}),!w&&!b&&p==="supplierPayment"&&e.jsx(R7,{profile:t,selectedBranchId:q}),!w&&!b&&p==="productBrand"&&e.jsx(Fv,{profile:t,view:"brand",onNavigate:Te=>ct(Te==="brand"?"productBrand":Te==="group"?"productGroup":Te==="category"?"productCategory":"productMaster"),onReturnToPurchase:()=>ct("newPurchase")}),!w&&!b&&p==="productGroup"&&e.jsx(Fv,{profile:t,view:"group",onNavigate:Te=>ct(Te==="brand"?"productBrand":Te==="group"?"productGroup":Te==="category"?"productCategory":"productMaster"),onReturnToPurchase:()=>ct("newPurchase")}),!w&&!b&&p==="productCategory"&&e.jsx(Fv,{profile:t,view:"category",onNavigate:Te=>ct(Te==="brand"?"productBrand":Te==="group"?"productGroup":Te==="category"?"productCategory":"productMaster"),onReturnToPurchase:()=>ct("newPurchase")}),!w&&!b&&p==="productMaster"&&e.jsx(Fv,{profile:t,view:"product",onNavigate:Te=>ct(Te==="brand"?"productBrand":Te==="group"?"productGroup":Te==="category"?"productCategory":"productMaster"),onReturnToPurchase:()=>ct("newPurchase")}),!w&&!b&&p==="supplierMaster"&&e.jsx(T7,{profile:t,onReturnToPurchase:()=>ct("newPurchase")}),!w&&!b&&p==="chequeManagement"&&e.jsx(M7,{profile:t}
4155),!w&&!b&&p==="crmWorkspace"&&e.jsx($7,{profile:t,onNavigate:Te=>ct(Te)}),!w&&!b&&p==="crmWebsiteConnectors"&&e.jsx(L7,{profile:t}),!w&&!b&&p==="salaryPayable"&&e.jsx(P7,{companyId:t.companyId,companyName:(_==null?void 0:_.name)||"Service Center",selectedBranchId:q}),!w&&!b&&p==="financeReports"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,scope:"finance",initialFinanceTab:"collection"}),!w&&!b&&p==="financeCollectionReport"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,scope:"finance",initialFinanceTab:"collection"}),!w&&!b&&p==="dayBookReport"&&e.jsx(mU,{profile:t,branches:T,selectedBranchId:q,companyName:(_==null?void 0:_.name)||"Service Center",companyPhone:_==null?void 0:_.phone,companyAddress:_==null?void 0:_.address}),!w&&!b&&p==="financeDueReport"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,scope:"finance",initialFinanceTab:"due"}),!w&&!b&&p==="financeSupplierPayableReport"&&e.jsx(ph,{profile:t,branches:T,selectedBranchId:q,scope:"finance",initialFinanceTab:"payable"}),!w&&!b&&p==="trialBalance"&&e.jsx(b7,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="generalLedger"&&e.jsx(w7,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="profitLoss"&&e.jsx(C7,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="stockReport"&&e.jsx(_7,{profile:t,branches:T,selectedBranchId:q}),!w&&!b&&p==="balanceSheet"&&e.jsx(I7,{profile:t,branches:T,selectedBranchId:q})]})]}),je&&e.jsx("div",{className:"drawer-backdrop",onMouseDown:()=>V(!1),children:e.jsxs("aside",{className:"notification-drawer",onMouseDown:Te=>Te.stopPropagation(),children:[e.jsxs("div",{className:"drawer-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Workspace alerts"}),e.jsx("h2",{children:"Notifications"})]}),e.jsx("button",{onClick:()=>V(!1),children:e.jsx(ja,{size:20})})]}),e.jsx("div",{className:"notification-list",children:it.length?it.map(Te=>{var ce;return e.jsxs("article",{className:(ce=Te==null?void 0:Te.readBy)!=null&&ce[t.uid]?"":"notification-unread",children:[e.jsx("span",{className:"activity-dot amber"}),e.jsxs("div",{children:[e.jsx("strong",{children:Te.title||"Workspace notification"}),e.jsx("small",{children:Te.message||""}),Te.ruleId&&e.jsxs("small",{children:["Rule: ",Te.ruleId,Te.effectiveDate?` ⢠Effective: ${Te.effectiveDate}`:""]}),e.jsx("button",{className:"button secondary small",onClick:()=>ee(Te),children:Te.actionLabel||"Mark as read"})]})]},Te.id)}):e.jsxs("article",{children:[e.jsx("span",{className:"activity-dot green"}),e.jsxs("div",{children:[e.jsx("strong",{children:"No new notifications"}),e.jsx("small",{children:"Important workspace alerts will appear here."})]})]})})]})})]}):e.jsx("div",{className:"auth-shell",children:e.jsxs("div",{className:"auth-card",style:{maxWidth:560},children:[e.jsxs("div",{className:"brand-lockup",children:[e.jsx("img",{className:"verixo-brand-icon",src:"/verixo-icon.svg",alt:"VERIXO"}),e.jsxs("div",{children:[e.jsx("strong",{children:"VERIXO"}),e.jsx("span",{children:"Workspace access expired"})]})]}),e.jsx("h2",{children:"Trial / Subscription Expired"}),e.jsxs("p",{children:["à¦à¦ Company workspace-à¦à¦° মà§à§à¦¾à¦¦ ",e.jsx("strong",{children:String((_==null?void 0:_.subscriptionExpiry)||"")})," তারিà¦à§ শà§à¦· হà§à§à¦à§à¥¤ Data নিরাপদ à¦à¦à§; মà§à§à¦¾à¦¦ বাà§à¦¾à¦¨à§ হলৠaccess à¦à¦¬à¦¾à¦° à¦à¦¾à¦²à§ হবà§à¥¤"]}),e.jsxs("button",{className:"primary-button",onClick:()=>dl(Ti),children:[e.jsx(aA,{size:18})," Sign out"]})]})})}async function nz(t){return t}function az({companySlug:t}){const[n,a]=x.useState(null),[s,i]=x.useState(null),[c,l]=x.useState(!0),[m,d]=x.useState(!1);return x.useEffect(()=>K5(Ti,async u=>{if(a(u),i(null),d(!1),!u){l(!1);return}try{const f=await mn(re(ie,`users/${u.uid}`));if(!f.exists())await dl(Ti),d(!1);else{let g=f.val();try{g=await nz(g)}catch(p){console.error("Super Admin bootstrap failed:",p)}if(!g.active)await dl(Ti);else{let p=g.companyId;if(t){const w=await mn(re(ie,`companyDirectory/${t}`)),C=w.exists()?String(w.val().id||""):"";if(!C)throw await dl(Ti),new Error("Company workspace not found.");if(g.role!=="super_admin"&&C!==g.companyId)throw await dl(Ti),new Error("This login does not belong to the selected company.");p=C}const y=Date.now(),b=Number(g.loginCount||0)+1,N={...g,companyId:p,lastLoginAt:y,loginCount:b};if(i(N),t&&window.location.pathname.startsWith("/login/")){const w=`/${encodeURIComponent(t)}`+window.location.search+window.location.hash;window.history.replaceState({workspace:t},"",w)}try{await zU(N)}catch(w){console.error("ERP foundation migration failed:",w)}}}}catch(f){console.error("User profile loading failed:",f),i(null)}finally{l(!1)}}),[t]),c?e.jsx(l5,{}):n?m?e.jsx(WU,{user:n,onComplete:u=>{i(u),d(!1)}}):s?s.forcePasswordChange?e.jsx(GE,{profile:s,required:!0,onComplete:i}):e.jsx(tz,{profile:s,onWorkspaceProfileChange:u=>{i(u)}}):e.jsx(l5,{message:"Loading profileâ¦"}):e.jsx(HU,{companySlug:t})}function sz(){const t=window.location.pathname,n=new Set(["login","estimate","invoice","receipt","track","portal"]),a=t.match(/^\/login\/([^/]+)\/?$/),s=t.match(/^\/([^/]+)\/?$/),i=a?a[1]:s&&!n.has(s[1].toLowerCase())?s[1]:void 0,c=i?decode
4155URIComponent(i).toLowerCase():void 0,l=t.match(/^\/estimate\/([^/]+)\/([^/]+)\/?$/);if(l)return e.jsx(_B,{companyId:decodeURIComponent(l[1]),token:decodeURIComponent(l[2])});const m=t.match(/^\/invoice\/([^/]+)\/([^/]+)\/?$/);if(m)return e.jsx(SB,{companyId:decodeURIComponent(m[1]),invoiceId:decodeURIComponent(m[2])});const d=t.match(/^\/receipt\/([^/]+)\/([^/]+)\/?$/);if(d)return e.jsx(wB,{companyId:decodeURIComponent(d[1]),jobId:decodeURIComponent(d[2])});const u=t.match(/^\/portal\/([^/]+)\/?$/);if(u)return e.jsx(xB,{companySlug:decodeURIComponent(u[1]).toLowerCase()});const f=t.match(/^\/track\/([^/]+)\/([^/]+)\/?$/);return f?e.jsx(yB,{companyId:decodeURIComponent(f[1]),jobId:decodeURIComponent(f[2])}):e.jsx(az,{companySlug:c})}const rz="/version.json",iz=900*1e3,oz="verixo_running_version",f2="verixo_pending_web_version";function cz(t){return typeof t=="string"?t.trim():""}async function lz(){try{const t=await fetch(`${rz}?t=${Date.now()}`,{cache:"no-store",headers:{Accept:"application/json"}});return t.ok?await t.json():null}catch{return null}}function dz(t){try{localStorage.setItem(f2,t)}catch{}}function uz(){try{return localStorage.getItem(f2)||""}catch{return""}}function hz(){try{localStorage.removeItem(f2)}catch{}}function mz(t){const n=new URL(window.location.href);n.searchParams.set("verixo_release",t),window.location.replace(n.toString())}async function Jv(){const t=await lz(),n=cz(t==null?void 0:t.version);if(!n||n===Dd){n===Dd&&hz();return}dz(n)}function pz(){try{localStorage.setItem(oz,Dd)}catch{}let t=!!Ti.currentUser,n=!1;const a=K5(Ti,m=>{if(m){t=!0;return}const d=uz();t&&d&&d!==Dd&&!n&&(n=!0,mz(d))}),s=window.setInterval(()=>{Jv()},iz),i=()=>{Jv()},c=()=>{document.visibilityState==="visible"&&Jv()},l=window.setTimeout(()=>{Jv()},12e3);return window.addEventListener("focus",i),document.addEventListener("visibilitychange",c),()=>{a(),window.clearInterval(s),window.clearTimeout(l),window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",c)}}fR.createRoot(document.getElementById("root")).render(e.jsx(xi.StrictMode,{children:e.jsx(sz,{})}));pz();export{ur as _,aR as c,Ub as g};
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.